SANS Pen Test Cheat Sheet: Scapy

One of my favorite tools for fine-grained interactions with target systems during penetration testing is the mighty Scapy.   While other tools are indispensable for scanning large numbers of machines, Scapy is like a fine-grained scalpel for manipulating a single target in a myriad of cool ways.  With all kinds of features, Scapy just rocks.

In fact, a few years ago, I tweeted thusly:

niBXBKgXTTo that end, just a couple weeks ago, we released a Scapy cheat sheet, covering the items we use Scapy for in the SANS Security 560 course on Network Pen Testing and Ethical Hacking, plus some additional tips and tricks.  Enjoy!

scapy

If you like this kinda thing, plus a whole bunch of other practical, hands-on pen testing techniques (including recon, scanning, exploitation, post exploitation, and more), please do check out the SANS Security 560 course.  I’ve recently added great new stuff on recon-ng, Anti-Virus evasion, PowerShell for post-exploitation, and much more!

Hope to see you there!

–Ed Skoudis.
SANS Instructor & Pen Test Curriculum Lead
Founder, Counter Hack

Pen Test Cheat Sheets:

Upcoming SANS Special Event – 2018 Holiday Hack Challenge

KringleCon

SANS Holiday Hack Challenge – KringleCon 2018

  • Free SANS Online Capture-the-Flag Challenge
  • Our annual gift to the entire Information Security Industry
  • Designed for novice to advanced InfoSec professionals
  • Fun for the whole family!!
  • Build and hone your skills in a fun and festive roleplaying like video game, by the makers of SANS NetWars
  • Learn more: www.kringlecon.com
  • Play previous versions from free 24/7/365: www.holidayhackchallenge.com

Player Feedback!

  • “On to level 4 of the #holidayhackchallenge. Thanks again @edskoudis / @SANSPenTest team.” – @mikehodges
  • “#SANSHolidayHack Confession – I have never used python or scapy before. I got started with both today because of this game! Yay!” – @tww2b
  • “Happiness is watching my 12 yo meet @edskoudis at the end of #SANSHolidayHack quest. Now the gnomes #ProudHackerPapa” – @dnlongen
kringle_02

Mission Impossible? Thwarting Cheating in an Advanced Pen Test Class CtF: The SANS SEC660 Experience

[Editor’s Note: SANS course on advanced pen testing (SEC660) teaches a lot of great, in-depth topics, including exploit development, network manipulation (NAC bypass, Scapy packet crafting, man-in-the-middle attacks, and more), and Python for pen testers with tons of hands-on exercises.  The whole class culminates in a full-day, intense capture the flag event, where the winners earn a 660 challenge coin  (which includes a cool cipher, natch).

But, when you teach a bunch of skills like that and hold a CtF on the last day, sometimes, a few students get a little too  rambunctious in applying their new-found skills.  At the risk of being indelicate, I’ll come out and say it — they try to cheat.  By using their Python skills along with their MiTM capabilities, they try to snarf flags from other teams attempting to send them to the score server.  What’s an enterprising course author to do?  Well, Steve Sims has some clever things up his sleeve, turning the tables on such shenanigans using the concepts taught in the course with a little Python magic of his own.  

I recommend you read through Steve Sims’ script to see how he uses Python with Scapy to call Nmap, call the underlying OS, formulate HTTP requests, and more.  Check it out! –Ed.]

By Stephen Sims

Here is a short blog article about an attack that students were attempting to pull off in some of the Capture the Flag (CtF) events as part of SANS SEC660: Advanced Penetration Testing, Exploits, and Ethical Hacking.  To thwart their attempts,  I wrote a python script.  In this article, I’d like to review the skills and techniques students use to try to undermine the CtF, and tell you my technical approach to address it in class.

The Source

During Day 1 of class, which is focused mostly on network attacks, we spend a lot of time looking at various ways to pull off a Man-in-the-Middle (MitM) attack, and then what you can accomplish by having that position. We cover techniques such as attacking SSL, routers, switches, and Network Access Control (NAC) solutions. During Day 3 of class, we spend a lot of time on Python, and various Python-based tools such as Scapy (by Philippe Biondi) and the Sulley Fuzzing Framework (by Pedram Amini / Aaron Portnoy  / Ryan Sears).

The Attack

Armed with this information taught in class, every so often a CtF team attempts to steal key submissions from other teams. Now, one could certainly argue that there is technically no cheating in a CtF; however, this does not mean it should be really easy to pull the attack off. To score in the SEC660 CtF, SHA-1 hashes, which act as keys, are submitted into the scoring system by each team. If a hash/key matches a challenge, points are awarded to the team. Regardless of whether SSL or simple HTTP is being used as the transport protocol to the scoring server, the aforementioned teams were attempting to, and sometimes successfully, performing ARP cache poisoning and SSL stripping. This would allow the teams performing the attack to potentially read valid key submissions from other teams and get the points without completing the challenge.  Ouch.

The Solution

The script you are about to read was written in about 90 minutes during a live CtF, so please forgive the stylistic issues and cut corners, such as not putting in the full paths to binaries when using the system() function. One of the solutions I designed to thwart this type of attack, and note that I am only sharing just one of them, was to create a script that would make a lot of noise on the wire. The script is not well-commented (again with the quick turnaround during the game), but it’s easy to read as it’s in Python. I decided to use Scapy together with Python to do the following:

  • Scan the student subnets to look for inactive IP addresses within the valid range assigned during class, using Nmap. This way it doesn’t stand out as an IP address that is obviously part of the script.
  • Use one of these addresses very briefly and also use a random MAC address in the VMware OUI range.
  • Automatically configure my interface with these addresses and perform a valid TCP_HTTP session to the scoring server.
  • Submit a pseudo-random SHA-1 hash as a key submission and use a pseudo-random PHP session ID.
  • Loop through this script until terminated.

The bottom line here is that my script injects false flags into the network, so anyone looking to steal a flag will likely get a non-valid flag delivered by my script.  Instead of stealing a valid flag from a legitimate student, they will have stolen a false flag from my script, netting them  NOTHING, except some wasted time.

Getting an automated script like this working with Scapy, that shows no errors when sniffing with a tool like Wireshark, can sometimes be challenging.  There are multiple ways to get it working. Feel free to read through the script and use it to improve your Scapy skills, or even better, improve it and send it to me at stephen@deadlisting.com. I will totally buy you a beer! Don’t forget to change the interface listed in the script if necessary.

–Stephen Sims

p.s. Josh Wright, Jake Williams, and I will be teaching SEC 660 using SANS on-line training system, vLive, from March 4 through April 17.  No travel is required, as you can take the class from the comfort of your home or office.  We meet twice a week, and we’ll be sharing our best tips and tricks for advanced pen testing.  Details are here: http://www.sans.org/vlive/details/sec660-04mar2014-joshua-wright.

from scapy.all import *
from time import sleep
from hashlib import sha1
from random import random, sample, randint
import string
from os import system
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
conf.verb=0
os.system("clear")
print "\nPlease stand by while NMAP results are collected... This could take a minute...\n"
f = os.popen("nmap -n -PA -p0 10.10.75,76,77,78.1-254 | grep 'scan report for'") #Grab IP Addr from student range
z = []

for lines in f:
    y = lines.split("\n") #Split \n from extra possible host addr's shorter than 3 digits.
    x = [] # Empty list
    x.append(y[0]) #Append the IP addr from y, and ignore the possible \n's
    r = y[0] #Assign the list element (IP ADDR) from y to r
    z.append(r[21:33]) #Grab only the IP ADDR from the NMAP scan results

print "Collected %d IP Addresses... Standby..." % len(z)
while True:
    print "Spoofing process started..."
    sp = RandNum(1025,65535) #Random number for ephemeral port assignment.
    char_set = string.ascii_lowercase + string.digits #Random string for PHPSESSID
    w = ''.join("10.10."+str(randint(75,78))+"."+str(randint(1,254)))

    for x in z:
        if w == x:
                w = ''.join("10.10."+str(randint(75,78))+"."+str(randint(1,254)))

    system("ifconfig eth1 down") #You may have to change interface number...
    sleep(.5)
    system("ifconfig eth1 hw ether " + str(RandMAC("00:0c:29:*:*:*")))
    sleep(.5)
    system("ifconfig eth1 " + w + " " + "netmask 255.255.0.0")
    sleep(.5)
    system("ifconfig eth1 up")
    sleep(.1)
    system("iptables -A OUTPUT -p tcp --destination-port 80 --tcp-flags RST RST -s " + str(w) + " -d 10.10.10.100 -j DROP")
    sleep(1)
    ah = os.popen("ifconfig eth1 | grep 00:0c:29") #Grab IP Addr
    for lines in ah:
            x = lines.split("\n")
            y = []
            y.append(x[0])
            ah = x[0]
            ah = ah[-19:]
            print "Using MAC Address: " + ah

    p = IP(src=w,dst="10.10.10.100") #Random IP from student subnets.
    saveip = p[IP].src
    print "Saved IP IS: " + str(saveip)
    key = sha1(str(random())).hexdigest()
    print "Using key: " + key
    myseq = 1000
    q= TCP(sport=sp, dport=80, flags="S", seq=myseq)
    SYNACK = sr1(p/q)
    sleep(.1)

    SPORT2=SYNACK.dport
    my_seq = myseq+1
    my_ack = SYNACK.seq+1
    ACK = TCP(sport=SPORT2, dport = 80, flags="A", seq=my_seq, ack=my_ack)
    derp = send(p/ACK)

    ACK = TCP(sport=SPORT2, dport = 80, flags="PA", seq=my_seq, ack=my_ack)
    b = ''.join(sample(char_set,26)) #Joining 26 random chars from char_set for SESSID.
    spoof = "HTTP/1.1 Host: 10.10.10.100"+\
    "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.15) "+\
    "Gecko/2009102814 Ubuntu/8.10 (intrepid) Firefox/3.0.15"+\
    "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"+\
    "Accept-Language: en-us,en;q=0.5"+\
    "Accept-Encoding: gzip,deflate"+\
    "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7"+\
    "Keep-Alive: 300"+\
    "Connection: keep-alive"+\
    "Referer: http://10.10.10.100/board.php"+\
    "Cookie: PHPSESSID="

    r = "GET /checkscore.php?key=" + key + spoof + b

    getReq = sr1(p/ACK/r)

    my_seq = myseq+507
    ACK = TCP(sport=SPORT2, dport = 80, flags="FA", seq=my_seq, ack=my_ack)
    derp = sr1(p/ACK)
    ACK = TCP(sport=SPORT2, dport = 80, flags="A", seq=my_seq+1, ack=my_ack+1)

    derp = send(p/ACK)
    print "Successfully spoofed packet, no errors..."
    sleep(3)
    os.system("clear")

Special Request: Wireless Client Sniffing with Scapy

[Editor comment: Dude! A Scapy article by Josh Wright that can help us stay in scope and follow rules of engagement in a pen test? What’s not to like?  :)  –Ed.]

By Joshua Wright

I participate on the Scapy mailing list, helping out with questions where I am able. Recently, I saw a question that piqued my interest:
“What I’m looking to do is identify the MAC addresses of client devices without actually sniffing any packets containing actual data relating to website content, email content etc. […] Are there any packets I could look at that would contain the MAC of client devices but not contain any online usage data as outlined?”

If we want to investigate the presence of wireless client devices but want to avoid capturing any data frames, we can focus on management frames. WiFi networks use management frames to establish a connection to the network, disconnect from the network, and more. Three management frames are easily distinguishable as being sent by client devices only:

– Probe Request Frames
– Association Request Frames
– Reassociation Request Frames

Using Scapy, it is easy to write a little Python that checks for the IEEE 802.11 type field to determine if a frame is a management frame, then examine the subtype field to determine if it is one of the three only sent by client devices.

First, we need to put a wireless card interface into monitor mode, as shown:

root@bt:~# airmon-ng start wlan0
Interface      Chipset        Driver
wlan0          Ralink RT2870/3070 rt2800usb - [phy0]
                           (monitor mode enabled on mon0)

With the mon0 interface receiving packets in monitor mode, we can run the following Scapy script. I’ve added a lot of comments in the script to help explain what is happening.

#!/usr/bin/env python
# The previous line ensures that this script is run under the context
# of the Python interpreter. Next, import the Scapy functions:
from scapy.all import *
# Define the interface name that we will be sniffing from, you can
# change this if needed.
interface = "mon0"
# Next, declare a Python list to keep track of client MAC addresses
# that we have already seen so we only print the address once per client.
observedclients = []
# The sniffmgmt() function is called each time Scapy receives a packet
# (we'll tell Scapy to use this function below with the sniff() function).
# The packet that was sniffed is passed as the function argument, "p".
def sniffmgmt(p):
    # Define our tuple (an immutable list) of the 3 management frame
    # subtypes sent exclusively by clients. I got this list from Wireshark.
    stamgmtstypes = (0, 2, 4)
    # Make sure the packet has the Scapy Dot11 layer present
    if p.haslayer(Dot11):
        # Check to make sure this is a management frame (type=0) and that
        # the subtype is one of our management frame subtypes indicating a
        # a wireless client
        if p.type == 0 and p.subtype in stamgmtstypes:
            # We only want to print the MAC address of the client if it
            # hasn't already been observed. Check our list and if the
            # client address isn't present, print the address and then add
            # it to our list.
            if p.addr2 not in observedclients:
                print p.addr2
                observedclients.append(p.addr2)
# With the sniffmgmt() function complete, we can invoke the Scapy sniff()
# function, pointing to the monitor mode interface, and telling Scapy to call
# the sniffmgmt() function for each packet received. Easy!
sniff(iface=interface, prn=sniffmgmt)

Next, we simply run the script:

# python client-nodata-enum.py
WARNING: No route found for IPv6 destination :: (no default route?)
88:c6:63:fa:de:d9
00:26:b0:75:ef:f5
00:1f:3a:4f:a2:be
58:1f:aa:ba:77:fe
0c:74:c2:5e:25:11
60:33:4b:f0:43:34
f4:0b:93:04:b5:d9
90:4c:e5:60:61:2e
8c:58:77:90:a0:da
00:21:5c:7e:70:c3
From here, lots of opportunities become available. For example, we could disconnect each client from the network by adding the following line after the print statement:
sendp(RadioTap()/Dot11(type=0,subtype=12,addr1=p.addr2,addr2=p.addr3,addr3=p.addr3)/Dot11Deauth())

We might do this in a penetration test to gently disconnect each user from the network once while capturing the activity to observe the EAP types in use (since clients reconnect automatically, this will typically have little impact to the network, but it’s a good idea to ensure your customer is prepared for a potential outage if clients do not reconnect gracefully).

I’m not sure why the original request wanted to obtain a list of client MAC addresses without looking at data frames, but it’s a simple task with Scapy. In SANS SEC617: Wireless Ethical Hacking, Penetration Testing, and Defenses, we spend a good amount of time on Scapy with an emphasis on wireless fuzzing, while the Advanced Penetration Testing SEC660 course leverages Scapy for a number of wired-side attack techniques.
You can grab the script in this module, without comments, from my website at http://www.willhackforsushi.com/code/client-nodata-enum.py.
-Josh

 

Upcoming SANS Special Event – 2018 Holiday Hack Challenge

KringleCon

SANS Holiday Hack Challenge – KringleCon 2018

  • Free SANS Online Capture-the-Flag Challenge
  • Our annual gift to the entire Information Security Industry
  • Designed for novice to advanced InfoSec professionals
  • Fun for the whole family!!
  • Build and hone your skills in a fun and festive roleplaying like video game, by the makers of SANS NetWars
  • Learn more: www.kringlecon.com
  • Play previous versions from free 24/7/365: www.holidayhackchallenge.com

Player Feedback!

  • “On to level 4 of the #holidayhackchallenge. Thanks again @edskoudis / @SANSPenTest team.” – @mikehodges
  • “#SANSHolidayHack Confession – I have never used python or scapy before. I got started with both today because of this game! Yay!” – @tww2b
  • “Happiness is watching my 12 yo meet @edskoudis at the end of #SANSHolidayHack quest. Now the gnomes #ProudHackerPapa” – @dnlongen
kringle_02