Hacking With Python

About Me

  • Sr. Security Automation Engineer
  • Utah Cyber Protection Team
  • 15+ years Python
  • 15+ years Linux administration

Twitter: @GarrettHyde

Basic Networking

Sockets


# Echo client program
import socket

HOST = 'example.com'  # The remote host
PORT = 50007          # The same port as used by the server

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))     # Connect to server
    s.sendall(b'Hello, world')  # Send text
    data = s.recv(1024)         # Get server reply
print('Received', repr(data))   # Print data
						

Reference: https://docs.python.org/3/library/socket.html#example

Open URLs


from urllib.request import urlopen

with urlopen('https://python.org/') as response:
    html = response.read()
						

Reference: https://docs.python.org/3/howto/urllib2.html#fetching-urls

Work With HTTP


import requests
r = requests.get('https://example.com/user',
                 auth=('user', 'pass'))
r.status_code  # 200
r.headers['content-type']  # 'application/json; charset=utf8'
r.encoding  # 'utf-8'
r.text      # '{"type":"User"...'
r.json()    # {'type': 'User', ...}
						

Reference: http://docs.python-requests.org/en/master/

Beautiful Soup

https://www.crummy.com/software/BeautifulSoup/

What Is Beautiful Soup?

Beautiful Soup is a Python library designed for quick turnaround projects like screen-scraping.

ASCII Captcha

ASCII Captcha

ASCII Captcha HTML

ASCII Captcha HTML

Parse HTML


from bs4 import BeautifulSoup
import requests

def get_captcha(url):
    r = requests.get(url)
    data = r.text
    soup = BeautifulSoup(data, 'html.parser')
    captcha = soup.find_all('p')[0]

    # Replace "br" tags with "\n"
    for br in captcha.find_all('br'):
        br.replace_with("\n")

    # Filter out empty lines
    captcha = [l for l in captcha.getText().split("\n")
               if l.strip() != ""]
    return captcha, r.cookies
						

Scapy

https://scapy.net/

What is Scapy?

Scapy is a powerful interactive packet manipulation program. It is able to forge or decode packets of a wide number of protocols, send them on the wire, capture them, match requests and replies, and much more.

ARP Request


from scapy.all import *

src_nic = "eth0"
src_mac = "ab:cd:ef:01:02:03"
src_ip = "10.1.0.50"
dest_ip = "10.1.0.100"

e = Ether(src=src_mac, dst="ff:ff:ff:ff:ff:ff", type=0x0806)
a = ARP(op=0x01, hwsrc=src_mac, psrc=src_ip, pdst=dest_ip)

sendp(e/a, iface=src_nic)
						

IPv6 Address Request


from scapy.all import *

src_nic = "eth0"
src_mac = "ab:cd:ef:01:02:03"

a = IPv6(dst="ff02::1")  # Send to IPv6 Multicast Address
b = ICMPv6ND_RA()        # IPv6 Router Adversitement
c = ICMPv6NDOptSrcLLAddr(lladdr=src_mac)  # Source Link-Layer Address
d = ICMPv6NDOptMTU()     # Maximum Transfer Unit
e = ICMPv6NDOptPrefixInfo(prefix="cc5f::", prefixlen=64)  # Advertised Prefix

send(a/b/c/d/e, iface=src_nic)
						

Reference: https://samsclass.info/ipv6/proj/projL3-scapy-ra.html

Cryptography

Crypt

Standard Library


import crypt
import getpass

# Prompt for user's password
plain_text = getpass.getpass()

# Hash password
pw_hash = crypt.crypt(plain_text, crypt.METHOD_SHA512)
print(pw_hash)

# Output (on Linux)
# $6$cPJEwX8kfKRW8UR5$GSDzRNOaTCczs3g/axuZkLaRRKvSxaP7v
# Cj.xBbE6xo1X0g3JQ6B4AuNDmRo7oW4ZukoeEiOHBmipLjHibz3t0
						

Documentation: https://docs.python.org/3/library/crypt.html

Cryptography (Module)

https://cryptography.io/en/latest/


from cryptography.fernet import Fernet

key = Fernet.generate_key()
cipher_suite = Fernet(key)
data = b"A really secret message"

# Encryption
cipher_text = cipher_suite.encrypt(data)

# Decryption
plain_text = cipher_suite.decrypt(cipher_text)
						

Reference: http://docs.python-guide.org/en/latest/scenarios/crypto/#example

PyCryptodome

https://www.pycryptodome.org/en/latest/

from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes

data = b"A really secret message."
key = get_random_bytes(16)

# Encryption
encryption_suite = AES.new(key, AES.MODE_EAX)
nonce = encryption_suite.nonce  # a number used only once
cipher_text = encryption_suite.encrypt(data)

# Decryption
decryption_suite = AES.new(key, AES.MODE_EAX, nonce)
plain_text = decryption_suite.decrypt(cipher_text)
						

Reference: https://www.pycryptodome.org/en/latest/src/examples.html#encrypt-data-with-aes

Other Uses

Buffer Overflow


$ python3 -c 'print("a" * 5)'
aaaaa

$ python3 -c \
    'import sys; sys.stdout.buffer.write(b"0"*128 + b"\x8b\x87\x04\x08")' \
    | pwned.exe
						

Generate Random Strings


import random
import string

chars = string.ascii_letters + string.digits
str_len = 16

random_str = "".join(random.sample(chars, str_len))
print(random_str)
						

Anything you need to automate

Resources

Books

Black Hat Python

Python Packages

Questions?