Thursday, January 19, 2012

DHCP discovery using scapy

Taken from here

Putting it plain and simple:

The following script sends a network packet containing the following layers:

a. DHCP: Application layer packet, message-type=discover
b. BOOTP: chaddr is used both as a hardware address for transmission of BOOTP reply messages and as a client identifier == MAC address of the nic
c. UDP: destination port is 67
d. IP: destination IP is broadcast IP address 255.255.255.255
e. ETHERNET: destination MAC is broadcast MAC ff:ff:ff:ff:ff:ff

from scapy.all import *
import sys

conf.checkIPaddr = False

#
# Get the hardware address of nic card
#
fam,hw = get_if_raw_hwaddr(conf.iface)

def dhcp_discover(resp):
    print "Source: " +resp[Ether].src
    print "Dest: " +resp[Ether].dst

#
# What if there is no DHCP component 
# in the incoming packet (so try and except)
#
    try: 
        for opt in resp[DHCP].options:
            if opt == 'end':
                break
            elif opt == 'pad':
                break
            print "Response:" + opt
    except:
        return 0
#
# send the raw packet to network
#
    sendp(Ether(dst="ff:ff:ff:ff:ff:ff") \
    /IP(src="0.0.0.0",dst="255.255.255.255") \
    /UDP(sport=68,dport=67)/BOOTP(chaddr=hw) \
    /DHCP(options=[("message-type","discover")]),count=3)

#
# sniff on udp port 67 and 68 
# and run the function dhcp_discover on all packets sniffed
# 
sniff(filter="udp and (port 67 or 68)", \
        prn=dhcp_discover, store=1)


The following is the response from DHCP server
, when the above script is executed

# python dhcp,py
Source: 00:1c:f9:93:04:00
Dest: 00:50:56:7c:c3:4f
('message-type', 5)
('server_id', '10.112.11.12')
('lease_time', 1800)
('subnet_mask', '255.255.252.0')
('router', '10.112.75.253')
('domain', 'dhcpserver.com')
('name_server', '10.112.11.12')

0 comments:

Post a Comment