SlideShare une entreprise Scribd logo
1  sur  44
Offensive Python
for
Pentesting
Mike Felch, Joff Thyer
Who are we?
• Mike Felch
• Vuln Research/Exploit Dev/Reverse Engineering
• Black Hills Information Security
• Established circa ‘99 in the lost underground
• Joff Thyer
• Security Researcher, Pen Tester, Developer
• Black Hills Information Security
• Certified SANS Instructor of SEC573 - Automating Infosec with Python
What are we covering?
• Attacking Cloud
• AWS
• Google
• Microsoft Azure
• Writing Malware
• Evasion
• Injection
• Execution
• Ways to weaponize
• Libraries
• Tooling/Frameworks
Attacking Cloud
Attacking Cloud: Overview
• Infrastructure AND Services
• SaaS Platforms: O365 vs G Suite
• IaaS Platforms: AWS vs Azure vs Google
• Overlooked rich attack surfaces
• Customer: “We don’t use Azure, just O365”
• Pentesters: “.. but we need DA!”
• Developers: “Oops.. I checked in my .aws folder.”
• Major providers released an SDK/API
Attacking Cloud: Auth Flow
Standard Auth Flow
• Creating a client
• Need authorization to authorize
• Need access token to resources
• Auth on behalf of victim
• ….
• Profit!
Attacking Cloud: AWS
Boto 3: The AWS SDK for Python
• Client:
• Low-level AWS access
• Maps 1:1 to AWS services
• Most (all?) operations supported
• Resource/Sessions
• CRUD-like Operations
• Enumerate all the things..
• 219 services supported!
Resource: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html
Attacking Cloud: AWS
• SDK: pip install boto3
• Auth is easier w/ awscli installed
• Requires access key & secret access key
• Leak via SSRF
• Source-code repos
• Hard-coded credentials
• Commonly misconfigured
• S3, EBS, EC2, SQS, Lambda, IAM, etc
Attacking Cloud: AWS
Searching S3
• public?
• ro vs rw?
• data!
Attacking Cloud: AWS
Dump Secrets
• creds
• API keys
• SSH keys
• binaries
Attacking Cloud: Google
• API Client: pip install oauth2client
• Requires registering your app
• Save the token.json
• Auth is easier w/ logged in web session
• Cache to credentials.json
• Search files, pilfer email, and add backdoors
• GMail, GDrive, Calendar, etc
• Compute SDK(s):
• https://cloud.google.com/python/setup
Resource: https://oauth2client.readthedocs.io/en/latest/
Attacking Cloud: Google
Backdoor
• Persistence
• Full access
Attacking Cloud: Azure
• SDK: pip install azure (or individuals)
• Auth is easier w/ az cli installed
• Prompts web session for authorization
• Just a bunch of API’s wrapped
• Enumerate resources
• Breaks services into smaller libraries
• AzureAD, Storage, KeyVault, VMs, etc
• Dump Users, Groups, Memberships
Resource: https://docs.microsoft.com/en-us/azure/python/
Attacking Cloud: Azure
Attacking Cloud: Azure
AzureAD
• Users
• Groups
• Devices
• Memberships
• SPN’s
Attacking Cloud: Azure
Freebie!
• Portal access
• Enabled by default
• More attack
surfaces
• Just auth.. :)
Writing Malware
Writing Python Malware
● Evasion
○ Evading AMSI: Stripping PowerShell
● Injection
○ Injecting shellcode wi/ custom Python
● Execution
○ Creating an EXE from a Python script
1)Evading AMSI: PowerStrip.py
● PowerShell detection by Anti-Malware Scan Interface (AMSI)
● Can be suboptimal and annoying on a test
● Evasion?
○ Invoke-Obfuscation by Daniel Bohannon is amazing
○ But… you really don’t have to go that far.
PowerStrip.py
● What if we just stripped comments, and changed a few applet
names? No really… not kidding.
● https://github.com/yoda66/PowerStrip
No obfuscation = :(
● BUMMER!!!! AMSI busted me...
After PowerStripping...
● https://github.com/yoda66/PowerStrip
Hack on and profit..
● And we only stripped the comments out.
Once again with stutter!
Applet Name Stuttering
2) Python Malware
● Python has access to Windows kernel32 DLL calls through the
“ctypes” module
○ Setting up the correct kernel32 DLL calls is a painstaking process.
● You can leverage this to run a shellcode of choice.
○ msfvenom, or cobalt strike generated shellcode for example.
● There are a huge number of different process injection techniques.
● There is a lot of BAD code floating around the Internet.
Steps for shellcode injection
● Three fundamental steps no matter whether you are creating a
thread locally, or in remote process
○ Allocate Memory
○ Copy Shellcode to allocated memory
○ Create a running thread of code
● Notes:
○ We will not be using reflexive DLL injection which typically involves using
LoadLibraryA() from DLL on disk.
○ Remote process injection requires opening a remote process handle
○ We will not address “Process Hollowing” either.
Injection: Memory Allocation
● Limited number of choices of kernel32 API call
○ VirtualAlloc()
■ allocate memory within same process
○ VirtualAllocEx()
■ allocate memory in a remote process
○ HeapCreate() then HeapAlloc()
■ allocate memory from heap within same process
Injection: Copy shellcode
● Two basic choices
○ RtlMoveMemory()
■ for local in-process activity
○ WriteProcessMemory()
■ for remote process activity
● Note: “ctypes” under Python3 will not allow you to copy a payload
with NULL “x00” characters within it.
○ This nearly drove me nuts. As much as I hate to say it, use Python2 for now.
○ Alternative: Encode your shellcode but this has ramifications
Injection: Starting Thread
● Three possibilities
○ CreateThread()
■ in local process only
○ CreateRemoteThread()
■ in remote process
○ QueueUserAPC()
■ in remote process.
■ interesting variant...
Matching API Arg Types
● if you don’t do this, then the API calls will all assume a Windows
MFC INT type, and you will fail.
○ Make sure to use “from ctypes.wintypes import DWORD, HANDLE … “
○ This example as part of a Python Class. (yes I learned the hard way)
Same Process Example
Remote Process Injection
● You first need to find a process!
● Python “psutil” module is helpful and well… “svchost.exe”
Remote Process Injection Steps
● OpenProcess() - open the remote process handle
● VirtualAllocEx() - allocate memory within process
● WriteProcessMemory() - write shellcode to memory
● VirtualProtectEx() - change to READ_EXECUTE only
● CreateRemoteThread() - spin up remote process thread
● VirtualFreeEx() - free Virtual Memory
● CloseHandle() - close remote process handle
3) Create EXE from Script
● A number of different methods
○ PyInstaller
○ Py2EXE
○ Possibly IronPython but its maintenance is lagging
● Pyinstaller install with “pip2” for Python2
C:> pip2 --install pyinstaller
C:> pyinstaller.exe --onefile scriptname.py
● Resulting EXE will be within “dist” directory.
PyInjector Demo
● https://github.com/yoda66/PyInjector
● DEMO TIME!
Ways to Weaponize:
Libraries
Libraries: Networks
● C2/DNS: socket
● Port scan (nmap wrapper): python-libnmap
● Packet Manipulation: scapy
● Packet Crafting/Parsing: dpkt
● PCAP interaction: pcapy
● Live host discovery: ping3
● Network Protocols: impacket
● Exploit Development: pwntools
Libraries: Windows
● Win32 API: pywin32
● DLL/Shared Libraries: ctypes
● Windows Management Instrumentation: wmi
● Windows Remote Management: pywinrm
● PowerShell Remoting: pypsrp
Libraries: Web & Cloud
● Internet recon: shodan
● Web requests/Password attacks: requests
● Attacking hipster web: requestium
● Parsing/Querying HTML (BeautifulSoup4): bs4
● Cracking JSON Web Tokens: jwt
● Parsing SQLite: sqlite3
● Processing XML/HTML: lxml
● AWS: boto3
● Google Cloud: google-api-python-client
● Azure: azure
Ways to Weaponize:
Tooling/Frameworks
Tooling/Frameworks
● ScoutSuite: https://github.com/nccgroup/ScoutSuite
● SilentTrinity: https://github.com/byt3bl33d3r/SILENTTRINITY
● FireProx: https://github.com/ustayready/fireprox
● CredSniper: https://github.com/ustayready/CredSniper
● Recon-ng: https://github.com/lanmaster53/recon-ng
● Veil: https://github.com/Veil-Framework/Veil
Go Get Started!
● pymeta.py
● powerstrip.py
● pyinjector.py
● pivot_winrm.py
● cloud_aws_s3.py
● cloud_aws_secrets.py
● cloud_azure_ad.py
● cloud_gsuite_backdoor.py
● cloud_gsuite_email.py
● crack_jwt.py
● live_host_discovery.py
● live_port_discovery.py
● passwords_attack.py
● pivot_psremoting.py
● pivot_wmi.py
● shodan_search.py
● socket_c2_client.py
● socket_c2_server.py
● web_brute.py
● web_robots.py
● web_sniff.py
● web_spa.py
https://github.com/ustayready/python-pentesting
Here’s some motivation...
End Slide
• Mike Felch @ustayready
• Joff Thyer @joff_thyer
• Black Hills Information Security
• http://www.blackhillsinfosec.com/
• Python Goodies!
• https://github.com/ustayready/python-pentesting
• Questions?

Contenu connexe

Tendances

Dom based xss
Dom based xssDom based xss
Dom based xss
Lê Giáp
 

Tendances (20)

ColdFusion for Penetration Testers
ColdFusion for Penetration TestersColdFusion for Penetration Testers
ColdFusion for Penetration Testers
 
Pentesting ReST API
Pentesting ReST APIPentesting ReST API
Pentesting ReST API
 
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.
 
HTTP Security Headers
HTTP Security HeadersHTTP Security Headers
HTTP Security Headers
 
Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)
 
Cross Site Scripting ( XSS)
Cross Site Scripting ( XSS)Cross Site Scripting ( XSS)
Cross Site Scripting ( XSS)
 
OWASP Top 10 2021 Presentation (Jul 2022)
OWASP Top 10 2021 Presentation (Jul 2022)OWASP Top 10 2021 Presentation (Jul 2022)
OWASP Top 10 2021 Presentation (Jul 2022)
 
Getting Started with Spring Authorization Server
Getting Started with Spring Authorization ServerGetting Started with Spring Authorization Server
Getting Started with Spring Authorization Server
 
Pentesting Rest API's by :- Gaurang Bhatnagar
Pentesting Rest API's by :- Gaurang BhatnagarPentesting Rest API's by :- Gaurang Bhatnagar
Pentesting Rest API's by :- Gaurang Bhatnagar
 
REST API Pentester's perspective
REST API Pentester's perspectiveREST API Pentester's perspective
REST API Pentester's perspective
 
File upload vulnerabilities & mitigation
File upload vulnerabilities & mitigationFile upload vulnerabilities & mitigation
File upload vulnerabilities & mitigation
 
Insecure direct object reference (null delhi meet)
Insecure direct object reference (null delhi meet)Insecure direct object reference (null delhi meet)
Insecure direct object reference (null delhi meet)
 
I hunt sys admins 2.0
I hunt sys admins 2.0I hunt sys admins 2.0
I hunt sys admins 2.0
 
Dom based xss
Dom based xssDom based xss
Dom based xss
 
Xss attack
Xss attackXss attack
Xss attack
 
System hacking
System hackingSystem hacking
System hacking
 
Frans Rosén Keynote at BSides Ahmedabad
Frans Rosén Keynote at BSides AhmedabadFrans Rosén Keynote at BSides Ahmedabad
Frans Rosén Keynote at BSides Ahmedabad
 
HTTP Request Smuggling via higher HTTP versions
HTTP Request Smuggling via higher HTTP versionsHTTP Request Smuggling via higher HTTP versions
HTTP Request Smuggling via higher HTTP versions
 
Sqlmap
SqlmapSqlmap
Sqlmap
 
OWASP Top 10 2021 What's New
OWASP Top 10 2021 What's NewOWASP Top 10 2021 What's New
OWASP Top 10 2021 What's New
 

Similaire à Offensive Python for Pentesting

Similaire à Offensive Python for Pentesting (20)

Security research over Windows #defcon china
Security research over Windows #defcon chinaSecurity research over Windows #defcon china
Security research over Windows #defcon china
 
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
 
The Future of Security and Productivity in Our Newly Remote World
The Future of Security and Productivity in Our Newly Remote WorldThe Future of Security and Productivity in Our Newly Remote World
The Future of Security and Productivity in Our Newly Remote World
 
Us 17-krug-hacking-severless-runtimes
Us 17-krug-hacking-severless-runtimesUs 17-krug-hacking-severless-runtimes
Us 17-krug-hacking-severless-runtimes
 
Injection on Steroids: Codeless code injection and 0-day techniques
Injection on Steroids: Codeless code injection and 0-day techniquesInjection on Steroids: Codeless code injection and 0-day techniques
Injection on Steroids: Codeless code injection and 0-day techniques
 
Road to Opscon (Pisa '15) - DevOoops
Road to Opscon (Pisa '15) - DevOoopsRoad to Opscon (Pisa '15) - DevOoops
Road to Opscon (Pisa '15) - DevOoops
 
Codetainer: a Docker-based browser code 'sandbox'
Codetainer: a Docker-based browser code 'sandbox'Codetainer: a Docker-based browser code 'sandbox'
Codetainer: a Docker-based browser code 'sandbox'
 
Lions, Tigers and Deers: What building zoos can teach us about securing micro...
Lions, Tigers and Deers: What building zoos can teach us about securing micro...Lions, Tigers and Deers: What building zoos can teach us about securing micro...
Lions, Tigers and Deers: What building zoos can teach us about securing micro...
 
On the Edge Systems Administration with Golang
On the Edge Systems Administration with GolangOn the Edge Systems Administration with Golang
On the Edge Systems Administration with Golang
 
Gianluca Varisco - DevOoops (Increase awareness around DevOps infra security)
Gianluca Varisco - DevOoops (Increase awareness around DevOps infra security)Gianluca Varisco - DevOoops (Increase awareness around DevOps infra security)
Gianluca Varisco - DevOoops (Increase awareness around DevOps infra security)
 
Socially Acceptable Methods to Walk in the Front Door
Socially Acceptable Methods to Walk in the Front DoorSocially Acceptable Methods to Walk in the Front Door
Socially Acceptable Methods to Walk in the Front Door
 
Bsides tampa
Bsides tampaBsides tampa
Bsides tampa
 
Bsidesnova- Pentesting Methodology - Making bits less complicated
Bsidesnova- Pentesting Methodology - Making bits less complicatedBsidesnova- Pentesting Methodology - Making bits less complicated
Bsidesnova- Pentesting Methodology - Making bits less complicated
 
Reactive summit 2020 microsoft orleans the easy way
Reactive summit 2020   microsoft orleans the easy wayReactive summit 2020   microsoft orleans the easy way
Reactive summit 2020 microsoft orleans the easy way
 
BSIDES-PR Keynote Hunting for Bad Guys
BSIDES-PR Keynote Hunting for Bad GuysBSIDES-PR Keynote Hunting for Bad Guys
BSIDES-PR Keynote Hunting for Bad Guys
 
The Hacking Games - A Road to Post Exploitation Meetup - 20240222.pptx
The Hacking Games - A Road to Post Exploitation Meetup - 20240222.pptxThe Hacking Games - A Road to Post Exploitation Meetup - 20240222.pptx
The Hacking Games - A Road to Post Exploitation Meetup - 20240222.pptx
 
Owning computers without shell access 2
Owning computers without shell access 2Owning computers without shell access 2
Owning computers without shell access 2
 
DEF CON 27 - WENXIANG QIAN and YUXIANG LI HUIYU - breaking google home exploi...
DEF CON 27 - WENXIANG QIAN and YUXIANG LI HUIYU - breaking google home exploi...DEF CON 27 - WENXIANG QIAN and YUXIANG LI HUIYU - breaking google home exploi...
DEF CON 27 - WENXIANG QIAN and YUXIANG LI HUIYU - breaking google home exploi...
 
The Supporting Role of Antivirus Evasion while Persisting
The Supporting Role of Antivirus Evasion while PersistingThe Supporting Role of Antivirus Evasion while Persisting
The Supporting Role of Antivirus Evasion while Persisting
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 

Dernier

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Dernier (20)

What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 

Offensive Python for Pentesting

  • 2. Who are we? • Mike Felch • Vuln Research/Exploit Dev/Reverse Engineering • Black Hills Information Security • Established circa ‘99 in the lost underground • Joff Thyer • Security Researcher, Pen Tester, Developer • Black Hills Information Security • Certified SANS Instructor of SEC573 - Automating Infosec with Python
  • 3. What are we covering? • Attacking Cloud • AWS • Google • Microsoft Azure • Writing Malware • Evasion • Injection • Execution • Ways to weaponize • Libraries • Tooling/Frameworks
  • 5. Attacking Cloud: Overview • Infrastructure AND Services • SaaS Platforms: O365 vs G Suite • IaaS Platforms: AWS vs Azure vs Google • Overlooked rich attack surfaces • Customer: “We don’t use Azure, just O365” • Pentesters: “.. but we need DA!” • Developers: “Oops.. I checked in my .aws folder.” • Major providers released an SDK/API
  • 6. Attacking Cloud: Auth Flow Standard Auth Flow • Creating a client • Need authorization to authorize • Need access token to resources • Auth on behalf of victim • …. • Profit!
  • 7. Attacking Cloud: AWS Boto 3: The AWS SDK for Python • Client: • Low-level AWS access • Maps 1:1 to AWS services • Most (all?) operations supported • Resource/Sessions • CRUD-like Operations • Enumerate all the things.. • 219 services supported! Resource: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html
  • 8. Attacking Cloud: AWS • SDK: pip install boto3 • Auth is easier w/ awscli installed • Requires access key & secret access key • Leak via SSRF • Source-code repos • Hard-coded credentials • Commonly misconfigured • S3, EBS, EC2, SQS, Lambda, IAM, etc
  • 9. Attacking Cloud: AWS Searching S3 • public? • ro vs rw? • data!
  • 10. Attacking Cloud: AWS Dump Secrets • creds • API keys • SSH keys • binaries
  • 11. Attacking Cloud: Google • API Client: pip install oauth2client • Requires registering your app • Save the token.json • Auth is easier w/ logged in web session • Cache to credentials.json • Search files, pilfer email, and add backdoors • GMail, GDrive, Calendar, etc • Compute SDK(s): • https://cloud.google.com/python/setup Resource: https://oauth2client.readthedocs.io/en/latest/
  • 12. Attacking Cloud: Google Backdoor • Persistence • Full access
  • 13. Attacking Cloud: Azure • SDK: pip install azure (or individuals) • Auth is easier w/ az cli installed • Prompts web session for authorization • Just a bunch of API’s wrapped • Enumerate resources • Breaks services into smaller libraries • AzureAD, Storage, KeyVault, VMs, etc • Dump Users, Groups, Memberships Resource: https://docs.microsoft.com/en-us/azure/python/
  • 15. Attacking Cloud: Azure AzureAD • Users • Groups • Devices • Memberships • SPN’s
  • 16. Attacking Cloud: Azure Freebie! • Portal access • Enabled by default • More attack surfaces • Just auth.. :)
  • 18. Writing Python Malware ● Evasion ○ Evading AMSI: Stripping PowerShell ● Injection ○ Injecting shellcode wi/ custom Python ● Execution ○ Creating an EXE from a Python script
  • 19. 1)Evading AMSI: PowerStrip.py ● PowerShell detection by Anti-Malware Scan Interface (AMSI) ● Can be suboptimal and annoying on a test ● Evasion? ○ Invoke-Obfuscation by Daniel Bohannon is amazing ○ But… you really don’t have to go that far.
  • 20. PowerStrip.py ● What if we just stripped comments, and changed a few applet names? No really… not kidding. ● https://github.com/yoda66/PowerStrip
  • 21. No obfuscation = :( ● BUMMER!!!! AMSI busted me...
  • 23. Hack on and profit.. ● And we only stripped the comments out.
  • 24. Once again with stutter!
  • 26. 2) Python Malware ● Python has access to Windows kernel32 DLL calls through the “ctypes” module ○ Setting up the correct kernel32 DLL calls is a painstaking process. ● You can leverage this to run a shellcode of choice. ○ msfvenom, or cobalt strike generated shellcode for example. ● There are a huge number of different process injection techniques. ● There is a lot of BAD code floating around the Internet.
  • 27. Steps for shellcode injection ● Three fundamental steps no matter whether you are creating a thread locally, or in remote process ○ Allocate Memory ○ Copy Shellcode to allocated memory ○ Create a running thread of code ● Notes: ○ We will not be using reflexive DLL injection which typically involves using LoadLibraryA() from DLL on disk. ○ Remote process injection requires opening a remote process handle ○ We will not address “Process Hollowing” either.
  • 28. Injection: Memory Allocation ● Limited number of choices of kernel32 API call ○ VirtualAlloc() ■ allocate memory within same process ○ VirtualAllocEx() ■ allocate memory in a remote process ○ HeapCreate() then HeapAlloc() ■ allocate memory from heap within same process
  • 29. Injection: Copy shellcode ● Two basic choices ○ RtlMoveMemory() ■ for local in-process activity ○ WriteProcessMemory() ■ for remote process activity ● Note: “ctypes” under Python3 will not allow you to copy a payload with NULL “x00” characters within it. ○ This nearly drove me nuts. As much as I hate to say it, use Python2 for now. ○ Alternative: Encode your shellcode but this has ramifications
  • 30. Injection: Starting Thread ● Three possibilities ○ CreateThread() ■ in local process only ○ CreateRemoteThread() ■ in remote process ○ QueueUserAPC() ■ in remote process. ■ interesting variant...
  • 31. Matching API Arg Types ● if you don’t do this, then the API calls will all assume a Windows MFC INT type, and you will fail. ○ Make sure to use “from ctypes.wintypes import DWORD, HANDLE … “ ○ This example as part of a Python Class. (yes I learned the hard way)
  • 33. Remote Process Injection ● You first need to find a process! ● Python “psutil” module is helpful and well… “svchost.exe”
  • 34. Remote Process Injection Steps ● OpenProcess() - open the remote process handle ● VirtualAllocEx() - allocate memory within process ● WriteProcessMemory() - write shellcode to memory ● VirtualProtectEx() - change to READ_EXECUTE only ● CreateRemoteThread() - spin up remote process thread ● VirtualFreeEx() - free Virtual Memory ● CloseHandle() - close remote process handle
  • 35. 3) Create EXE from Script ● A number of different methods ○ PyInstaller ○ Py2EXE ○ Possibly IronPython but its maintenance is lagging ● Pyinstaller install with “pip2” for Python2 C:> pip2 --install pyinstaller C:> pyinstaller.exe --onefile scriptname.py ● Resulting EXE will be within “dist” directory.
  • 38. Libraries: Networks ● C2/DNS: socket ● Port scan (nmap wrapper): python-libnmap ● Packet Manipulation: scapy ● Packet Crafting/Parsing: dpkt ● PCAP interaction: pcapy ● Live host discovery: ping3 ● Network Protocols: impacket ● Exploit Development: pwntools
  • 39. Libraries: Windows ● Win32 API: pywin32 ● DLL/Shared Libraries: ctypes ● Windows Management Instrumentation: wmi ● Windows Remote Management: pywinrm ● PowerShell Remoting: pypsrp
  • 40. Libraries: Web & Cloud ● Internet recon: shodan ● Web requests/Password attacks: requests ● Attacking hipster web: requestium ● Parsing/Querying HTML (BeautifulSoup4): bs4 ● Cracking JSON Web Tokens: jwt ● Parsing SQLite: sqlite3 ● Processing XML/HTML: lxml ● AWS: boto3 ● Google Cloud: google-api-python-client ● Azure: azure
  • 42. Tooling/Frameworks ● ScoutSuite: https://github.com/nccgroup/ScoutSuite ● SilentTrinity: https://github.com/byt3bl33d3r/SILENTTRINITY ● FireProx: https://github.com/ustayready/fireprox ● CredSniper: https://github.com/ustayready/CredSniper ● Recon-ng: https://github.com/lanmaster53/recon-ng ● Veil: https://github.com/Veil-Framework/Veil
  • 43. Go Get Started! ● pymeta.py ● powerstrip.py ● pyinjector.py ● pivot_winrm.py ● cloud_aws_s3.py ● cloud_aws_secrets.py ● cloud_azure_ad.py ● cloud_gsuite_backdoor.py ● cloud_gsuite_email.py ● crack_jwt.py ● live_host_discovery.py ● live_port_discovery.py ● passwords_attack.py ● pivot_psremoting.py ● pivot_wmi.py ● shodan_search.py ● socket_c2_client.py ● socket_c2_server.py ● web_brute.py ● web_robots.py ● web_sniff.py ● web_spa.py https://github.com/ustayready/python-pentesting Here’s some motivation...
  • 44. End Slide • Mike Felch @ustayready • Joff Thyer @joff_thyer • Black Hills Information Security • http://www.blackhillsinfosec.com/ • Python Goodies! • https://github.com/ustayready/python-pentesting • Questions?