Hacking With Python

About Me

  • Red Hat Architect
  • Utah Cyber Protection Team
  • 10+ years Python
  • 10+ years Linux administration

Twitter: @GarrettHyde

Basic Networking

Sockets


import socket

HOST = "example.com"
PORT = 23

s = socket.socket()
try:
    s.connect((HOST, PORT))  # Connect to server
    reply = s.recv(1024)     # Get server prompt
    s.send("Hello, World!")  # Send text
    reply = s.recv(2048)     # Get server reply
    print(reply)
finally:
    s.close()
						
https://docs.python.org/2/library/socket.html

Open URLs


import urllib2

response = urllib2.urlopen('http://example.com/')
html = response.read()
						
https://docs.python.org/2/howto/urllib2.html

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      # u'{"type":"User"...'
r.json()    # {u'some_info': u'foo', u'more_info': u'bar'}
						
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() != u""]
  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)

# Encryption
cipher_text = cipher_suite.encrypt(
  b"A really secret message. Not for prying eyes.")

# Decryption
plain_text = cipher_suite.decrypt(cipher_text)
						

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

PyCrypto

https://www.dlitz.net/software/pycrypto/

from Crypto.Cipher import AES

# Encryption
encryption_suite = AES.new('This is a key123',
  AES.MODE_CBC, 'This is an IV456')
cipher_text = encryption_suite.encrypt(
  "A really secret message. Not for prying eyes.")

# Decryption
decryption_suite = AES.new('This is a key123',
  AES.MODE_CBC, 'This is an IV456')
plain_text = decryption_suite.decrypt(cipher_text)
						

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

Other Uses

Buffer Overflow


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

$ python -c 'print("0"*128 + b"\x8b\x87\x04\x08")' | pwned.exe
						

Generate Random Strings


import random

chars = "abcdefghijklmnopqrstuvwxyz1234567890"
str_len = 16

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

Anything you need to automate

Resources

Books

Violent Python Black Hat Python

Python Packages

Questions?