aboutsummaryrefslogtreecommitdiffstats
path: root/fap/dhcpd
diff options
context:
space:
mode:
Diffstat (limited to 'fap/dhcpd')
-rw-r--r--fap/dhcpd/DHCP_protocol_breakdown.txt18
-rw-r--r--fap/dhcpd/module_craft_option.py79
-rw-r--r--fap/dhcpd/module_lease.py174
-rw-r--r--fap/dhcpd/server_dhcp.py323
-rw-r--r--fap/dhcpd/terminal.log146
5 files changed, 740 insertions, 0 deletions
diff --git a/fap/dhcpd/DHCP_protocol_breakdown.txt b/fap/dhcpd/DHCP_protocol_breakdown.txt
new file mode 100644
index 0000000..5af2bf2
--- /dev/null
+++ b/fap/dhcpd/DHCP_protocol_breakdown.txt
@@ -0,0 +1,18 @@
+Length of DHCP fields in octets, and their placement in packet.
+Ref: http://4.bp.blogspot.com/-IyYoFjAC4l8/UXuo16a3sII/AAAAAAAAAXQ/b6BojbYXoXg/s1600/DHCPTitle.JPG
+0 OP - 1
+1 HTYPE - 1
+2 HLEN - 1
+3 HOPS - 1
+4 XID - 4
+5 SECS - 2
+6 FLAGS - 2
+7 CIADDR - 4
+8 YIADDR - 4
+9 SIADDR - 4
+10 GIADDR - 4
+11 CHADDR - 6
+12 MAGIC COOKIE - 10
+13 PADDING - 192 octets of 0's
+14 MAGIC COOKIE - 4
+15 OPTIONS - variable length
diff --git a/fap/dhcpd/module_craft_option.py b/fap/dhcpd/module_craft_option.py
new file mode 100644
index 0000000..35e7328
--- /dev/null
+++ b/fap/dhcpd/module_craft_option.py
@@ -0,0 +1,79 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+
+'''
+ Created by Jonas 'j' Lindstad for The Gathering 2015
+ License: GPLv3
+
+ Class used to craft byte hex encoded DHCP options
+
+ NB: No direct support for suboptions. Should be possible to craft suboptions as
+ options, and inject them with craft_option(<option>).raw_hes(<conconcatenated options>)
+
+ Usage examples:
+ craft_option.debug = True
+ print(craft_option(1).string('vg.no'))
+ print(craft_option(2).bytes(b'abcd'))
+ print(craft_option(3).bytes(socket.inet_aton('192.168.0.55')))
+ print(craft_option(4).bytes(b'\xde\xad\xbe\xef\xfe\xed'))
+ print(craft_option(5).raw_hex(b'\x72\x78'))
+ print(craft_option(6).ip('255.255.128.0'))
+'''
+
+from binascii import hexlify, unhexlify
+
+class craft_option(object):
+ # content = b'' # content will be stored as hex values like hex(10) + hex(255) = 0aff
+ debug = False
+ def __init__(self, code):
+ self.code = self.__int_to_pad_byte(code)
+
+ # Works as intended
+ # internal function. Converts int(3) to str('03'), int('11') to str('0b'), int(255) to str('ff')
+ def __int_to_pad_byte(self, integer):
+ return hex(integer).split('x')[1].rjust(2, '0').encode()
+
+ # Works as intended
+ def string(self, string):
+ self.method = 'string'
+ self.content = hexlify(string.encode())
+ return self.process()
+
+ # Works as intended
+ def bytes(self, bytes):
+ self.method = 'bytes'
+ self.content = hexlify(bytes)
+ return self.process()
+
+ # Works as intended
+ # str('10.20.30.40') to b'\x10\x20\x30\x40'
+ def ip(self, ip):
+ self.method = 'ip'
+ self.content = ''.join([hex(int(i))[2:].rjust(2, '0') for i in ip.split('.')]).encode()
+ return self.process()
+
+ # Works as intended
+ # string like '\x72\x78' for 'rx'
+ def raw_hex(self, raw_hex):
+ self.method = 'raw_hex'
+ self.content = hexlify(raw_hex)
+ return self.process()
+
+
+
+ # TODO Does not work as intended
+ # int(666) to b'\x02\x9A'
+ def integer(self, integer):
+ self.method = 'integer'
+ self.content = ''.join([hex(int(i))[2:].rjust(2, '0') for i in ip.split('.')])
+ return self.process()
+
+ def process(self):
+ length = self.__int_to_pad_byte(len(unhexlify(self.content)))
+ if self.debug is True:
+ print('----------')
+ print(self.method + '():')
+ print(self.code + length)
+ print(b'content: ' + self.content)
+ print(unhexlify(self.content))
+ return unhexlify(self.code + length + self.content)
diff --git a/fap/dhcpd/module_lease.py b/fap/dhcpd/module_lease.py
new file mode 100644
index 0000000..306f13a
--- /dev/null
+++ b/fap/dhcpd/module_lease.py
@@ -0,0 +1,174 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+
+'''
+ Created by Jonas 'j' Lindstad for The Gathering 2015
+ License: GPLv3
+
+ Class used to fetch data from the Postgres DB
+
+ Usage examples:
+ lease.debug = True
+ x = lease({'distro_name': 'distro-test', 'distro_phy_port': 'ge-0/0/6'}).get_dict()
+ print('key lookup - hostname: %s' % x['hostname'])
+'''
+
+import psycopg2
+import psycopg2.extras
+
+# settings
+settings = dict(
+ db = dict(
+ user = 'bootstrap',
+ password = 'asdf',
+ dbname = 'bootstrap',
+ host = 'localhost'
+ )
+)
+
+# connect to Postgres DB
+connect_params = ("dbname='%s' user='%s' host='%s' password='%s'" % (settings['db']['dbname'], settings['db']['user'], settings['db']['host'], settings['db']['password']))
+conn = psycopg2.connect(connect_params)
+cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
+
+class lease(object):
+ debug = False
+
+ def __init__(self, identifiers):
+ if len(identifiers) > 0: # 1 or more identifiers - we're good to go
+
+ # build query string
+ where_pieces = []
+ for x in identifiers.items():
+ where_pieces.append(str(x[0]) + " = '" + str(x[1]) + "'")
+ where = ' AND '.join(where_pieces)
+ select = "SELECT * FROM switches WHERE " + where + " LIMIT 1"
+
+ if self.debug is True:
+ print('Executing query: ' + select)
+
+ cur.execute(select)
+
+ rows = cur.fetchall()
+ if len(rows) is 1:
+ if self.debug is True:
+ print('returned from DB:')
+ for key, value in rows[0].items():
+ print('%s: %s' % (key, value))
+
+ self.row = rows[0]
+ else:
+ self.row = False
+ else:
+ print('Missing identifier parameter')
+ exit()
+
+ def get_ip(self):
+ if self.row is not False:
+ return self.row['ip']
+ else:
+ print('identifiers (%s) not found' % self.row)
+ return False
+
+ def get_config(self):
+ if self.row is not False:
+ return self.row['config']
+ else:
+ print('identifiers (%s) not found' % self.row)
+ return False
+
+ def get_dict(self):
+ if self.row is not False:
+ return self.row
+ else:
+ print('identifiers (%s) not found' % self.row)
+ return False
+
+
+#
+# TESTING - Bruker ID fra DB-en som identifier, og kjører en query per lease.get_x()
+#
+class lease2(object):
+ debug = False
+ hostname = False
+ identifiers = False
+
+ # identifiers = dict of field/values
+ def __init__(self, identifiers):
+ cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
+
+ if len(identifiers) > 0: # 1 or more identifiers - we're good to go
+ self.identifiers = identifiers # Used to debug if no match for the identifiers is given
+
+ # build query string
+ where_pieces = []
+ for identifier in identifiers.items():
+ where_pieces.append(str(identifier[0]) + " = '" + str(identifier[1]) + "'")
+ where = ' AND '.join(where_pieces)
+ select = "SELECT hostname FROM switches WHERE " + where + " LIMIT 1"
+
+ if self.debug is True:
+ print('Executing query: ' + select)
+
+ cur.execute(select)
+ rows = cur.fetchall()
+ cur.close()
+ if len(rows) is 1:
+ if self.debug is True:
+ print('returned from DB:')
+ print(rows[0][0])
+ self.hostname = rows[0][0]
+ else:
+ self.hostname = False
+ else:
+ print('Missing identifier parameter')
+ exit()
+
+ # Used to fetch fields from DB
+ def get(self, field):
+ if self.hostname is not False:
+ cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
+
+ query = "SELECT %s FROM switches WHERE hostname = '%s' LIMIT 1" % (field, self.hostname)
+ if self.debug is True:
+ print('Query: %s' % query)
+
+ try:
+ cur.execute(query)
+ rows = cur.fetchall()
+
+ if len(rows) is 1:
+ if self.debug is True:
+ print('returned from DB:')
+ print(rows[0][0])
+ return rows[0][0]
+ else:
+ if self.debug is True:
+ print('No data found - field: %s' % field)
+ return False
+ except psycopg2.ProgrammingError:
+ print('Field (%s) not found' % field)
+ conn.rollback() # Prevents DB from locking up the next queries - http://initd.org/psycopg/docs/connection.html#connection.rollback
+ return False
+ else:
+ print('identifiers (%s) not found' % self.identifiers)
+ return False
+
+ # Used to set fields in DB
+ def set(self, field, value):
+ if self.hostname is not False:
+ cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
+ query = "UPDATE switches SET %s = '%s' WHERE hostname = '%s'" % (field, value, self.hostname)
+ if self.debug is True:
+ print('Query: %s' % query)
+ try:
+ cur.execute(query)
+ conn.commit()
+ return True
+ except psycopg2.ProgrammingError:
+ print('Field (%s) not found' % field)
+ conn.rollback()
+ return False
+ else:
+ print('identifiers (%s) not found' % self.identifiers)
+ return False
diff --git a/fap/dhcpd/server_dhcp.py b/fap/dhcpd/server_dhcp.py
new file mode 100644
index 0000000..0c05505
--- /dev/null
+++ b/fap/dhcpd/server_dhcp.py
@@ -0,0 +1,323 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+
+'''
+server_dhcp.py by Jonas "j" Lindstad for The Gathering tech:server
+
+Used to configure the Juniper EX2200 edge switches with Zero Touch Protocol
+License: GPLv2
+
+Based on the work of psychomario - https://github.com/psychomario
+'''
+
+
+'''
+
+TODO
+
+ * try/catch around each incomming packet - prevents DHCP-server from crashing if it receives a malformed packet
+
+'''
+
+import socket, binascii, IN
+from module_craft_option import craft_option # Module that crafts DHCP options
+# from module_lease import lease # Module that fetches data from DB and provides data for the lease
+from module_lease import lease2 as lease # Module that fetches data from DB and provides data for the lease
+
+
+# Global options - not a pretty hack
+options_raw = {} # TODO - not a nice way to do things
+option_82_1 = ''
+client = ''
+
+
+#############
+# FUNCTIONS #
+#############
+
+# Generator for each of the dhcp fields
+def split_packet(msg,slices):
+ for x in slices:
+ yield msg[:x]
+ msg = msg[x:]
+
+# Splits a chunk of hex into a list of hex. (0123456789abcdef => ['01', '23', '45', '67', '89', 'ab', 'cd', 'ef'])
+def chunk_hex(hex):
+ return [hex[i:i+2] for i in range(0, len(hex), 2)]
+
+# Convert hex IP to string with formated decimal IP. (0a0000ff => 10.0.0.255)
+def hex_ip_to_str(hex_ip):
+ return '.'.join(str(y) for y in map(lambda x: int(x, 16), chunk_hex(hex_ip))) # cast int to str for join
+
+# formats a MAC address in the format "b827eb9a520f" to "b8:27:eb:9a:52:0f"
+def format_hex_mac(hex_mac):
+ return ':'.join(str(x) for x in chunk_hex(hex_mac))
+
+# Formats a 6 byte MAC to a readable string (b'5e\x21\x00r3' => '35:65:21:00:72:33')
+def six_byte_mac_to_str(mac):
+ return ':'.join('%02x' % byte for byte in mac)
+
+# b'b827eb9a520f' => 'b8:27:eb:9a:52:0f'
+def prettyprint_hex_as_str(hex):
+ return ':'.join('%02x' % byte for byte in binascii.unhexlify(hex))
+
+# CIDR notation to subnet string ('25' => '255.255.255.128')
+def cidr_to_subnet(cidr):
+ mask = [0, 0, 0, 0]
+ for i in range(int(cidr)):
+ mask[i//8] = mask[i//8] + (1 << (7 - i % 8))
+ return '.'.join(str(x) for x in mask)
+
+# Parses DHCP options - raw = hex options
+def parse_options(raw):
+ print('[%s] --> processing DHCP options' % client)
+ chunked = chunk_hex(raw)
+ chunked_length = len(chunked)
+ pointer = 0 # counter - next option start
+ options = {} # options dataset
+
+ global options_raw
+ options_raw = {} # incomming request's options
+ special_options = [53, 82]
+
+ while True: # Loop over the DHCP options
+ option = int(chunked[pointer], 16) # option ID (0 => 255)
+ code = int(chunked[pointer], 16) # option code (0 => 255) # New int for options' ID with correct name. Replaces $option
+
+ length = int(chunked[pointer+1], 16) # option length
+ option_payload = raw[((pointer+2)*2):((pointer+length+2)*2)] # Contains the payload of the option - without option ID and length
+ options_raw[code] = option_payload # copying incomming request's options, directly usable in outgoing replies
+
+ asciivalue = binascii.unhexlify(option_payload) # should not contain unreadable characters
+
+ if option in special_options:
+ if option is 82:
+ option82_raw = option_payload
+ options[option] = parse_suboptions(option, option_payload)
+ elif option is 53:
+ options[option] = option_payload
+ # options[option] = 1 # Not adding DHCP DISCOVER to the options list, becouse it will not be used further on
+ if int(chunked[pointer+2], 16) is 1:
+ print('[%s] --> option: %s: %s' % (client, option, 'DHCP Discover (will not be used in reply)'))
+ else:
+ print('[%s] --> option: %s: %s' % (client, option, asciivalue))
+
+ else:
+ options[option] = asciivalue
+ # TODO: Formating.... Also crap code
+ try:
+ if len(asciivalue) > 30:
+ print('[%s] --> option: %s: %s' % (client, option, asciivalue[:26] + ' [...]'))
+ else:
+ print('[%s] --> option: %s: %s' % (client, option, asciivalue))
+ except Exception:
+ if len(asciivalue) > 30:
+ print('[%s] --> option: %s: %s' % (client, option, prettyprint_hex_as_str(option_payload)[:26] + ' [...]'))
+ else:
+ print('[%s] --> option: %s: %s' % (client, option, prettyprint_hex_as_str(option_payload)))
+ pass
+
+ pointer = pointer + length + 2 # place pointer at the next options' option ID/code field
+
+ if int(chunked[pointer], 16) is 255: # end of DHCP options - should allways last field
+ print('[%s] --> Finished processing options' % client)
+ break
+ return options
+
+# Parses suboptions
+def parse_suboptions(option, raw):
+ print('[%s] --> processing suboption hook for option %s' % (client, option))
+ chunked = chunk_hex(raw)
+ chunked_length = len(chunked)
+ pointer = 0 # counter - next option start
+ dataset = {}
+
+ if option is 82: # Option 82 - custom shit: Setting global variable to list
+ global option_82_1
+
+ while True:
+ length = int(chunked[pointer+1], 16) # option length in bytes
+ value = raw[4:(length*2)+(4)]
+
+ if option is 82 and int(chunked[0], 16) is 1: # Option 82 - custom shit: Putting data in list
+ option_82_1 = binascii.unhexlify(value).decode()
+
+ print('[%s] --> suboption %s found - value: "%s"' % (client, int(chunked[0], 16), binascii.unhexlify(value).decode())) # will fail on non-ascii characters
+
+ dataset[int(chunked[0], 16)] = value
+ pointer = pointer + length + 2 # place pointer at the next options' option ID/code field
+ if pointer not in chunked: # end of DHCP options - allways last field
+ print('[%s] --> Finished processing suboption %s' % (client, option))
+ break
+ return dataset
+
+# Parses and handles DHCP DISCOVER or DHCP REQUEST
+def reqparse(message):
+ data=None
+ dhcpfields=[1,1,1,1,4,2,2,4,4,4,4,6,10,192,4,message.rfind(b'\xff'),1]
+ hexmessage=binascii.hexlify(message)
+ messagesplit=[binascii.hexlify(x) for x in split_packet(message,dhcpfields)]
+
+ global client
+ client = prettyprint_hex_as_str(messagesplit[11])
+
+ print('[%s] Parsing DHCP packet from client' % client)
+
+ #
+ # Logical checks to decide to whether respond or reject
+ #
+ if int(hex_ip_to_str(messagesplit[10]).replace('.', '')) is 0: # DHCP request has been forwarded by DHCP relay - A bit haxxy..
+ print('[%s] Rejecting to process DHCP packet - not forwarded by DHCP relay' % client)
+ return False
+
+ # Process DHCP options
+ options = parse_options(messagesplit[15])
+
+ # Option 82 is set in the packet
+ if 82 not in options:
+ print('[%s] Rejecting to process DHCP packet - DHCP option 82 not set' % client)
+ return False
+
+ # Check DHCP request type
+ if options[53] == b'01':
+ mode = 'dhcp_discover'
+ print('[%s] --> DHCP packet type: DHCP DISCOVER' % client)
+ elif options[53] == b'03':
+ mode = 'dhcp_request'
+ print('[%s] --> DHCP packet type: DHCP REQUEST' % client)
+ else:
+ print('[%s] Rejecting to continue process DHCP packet - option 53 missing' % client) # Small sanity check
+ return False
+
+ #
+ # Packet passes our requirements
+ #
+ print('[%s] --> DHCP packet contains option 82 - continues to process' % client)
+ print('[%s] --> DHCP packet forwarded by relay %s' % (client, hex_ip_to_str(messagesplit[10])))
+ print('[%s] --> DHCP XID/Transaction ID: %s' % (client, prettyprint_hex_as_str(messagesplit[4])))
+
+ # Handle DB request - do DB lookup based on option 82
+ print('[%s] --> Looking up in the DB' % (client))
+ if len(option_82_1) > 0:
+ (distro, phy, vlan) = option_82_1.split(':')
+ print('[%s] --> Query details: distro_name:%s, distro_phy_port:%s' % (client, distro, phy.split('.')[0]))
+
+ lease_identifiers = {'distro_name': distro, 'distro_phy_port': phy.split('.')[0]}
+ if lease(lease_identifiers).get('hostname') is not False:
+ l={
+ 'hostname': lease(lease_identifiers).get('hostname'),
+ 'mgmt_addr': lease(lease_identifiers).get('mgmt_addr'),
+ 'mgmt_gw': lease(lease_identifiers).get('mgmt_gw'),
+ 'mgmt_cidr': lease(lease_identifiers).get('mgmt_cidr')
+ }
+
+ # lease_details = lease({'distro_name': distro, 'distro_phy_port': phy[:-2]}).get_dict()
+ print('[%s] --> Data found, switch exists in DB - ready to craft response' % client)
+ else:
+ print('[%s] --> Data not found, switch does not exists in DB' % client)
+ return False
+ else:
+ print('[%s] Rejecting to continue to process DHCP packet - option 82.1 is empty' % client)
+
+ if mode == 'dhcp_discover':
+ print('[%s] --> Crafting DHCP OFFER response' % client)
+
+ if mode == 'dhcp_request':
+ print('[%s] --> Crafting DHCP ACK response' % client)
+
+ print('[%s] --> XID/Transaction ID: %s' % (client, prettyprint_hex_as_str(messagesplit[4])))
+ print('[%s] --> Client IP: %s' % (client, l['mgmt_addr']))
+ print('[%s] --> DHCP forwarder IP: %s' % (client, l['mgmt_gw']))
+ print('[%s] --> Client MAC: %s' % (client, client))
+
+ data = b'\x02' # Message type - boot reply
+ data += b'\x01' # Hardware type - ethernet
+ data += b'\x06' # Hardware address length - 6 octets for MAC
+ data += b'\x01' # Hops
+ data += binascii.unhexlify(messagesplit[4]) # XID / Transaction ID
+ data += b'\x00\x00' # seconds elapsed - 1 second
+ data += b'\x80\x00' # BOOTP flags - broadcast (unicast: 0x0000)
+ data += b'\x00'*4 # Client IP address
+ data += socket.inet_aton(l['mgmt_addr']) # New IP to client
+ data += socket.inet_aton(dhcp_server_address) # Next server IP address
+ data += socket.inet_aton(l['mgmt_gw']) # Relay agent IP - DHCP forwarder
+ data += binascii.unhexlify(messagesplit[11]) # Client MAC
+ data += b'\x00'*202 # Client hardware address padding (10) + Server hostname (64) + Boot file name (128)
+ data += b'\x63\x82\x53\x63' # Magic cookie
+
+ #
+ # Craft DHCP options
+ #
+ print('[%s] --> Completed DHCP header structure, building DHCP options' % client)
+
+ if mode == 'dhcp_discover':
+ print('[%s] --> Option 53 (DHCP OFFER): 2' % client)
+ data += craft_option(53).raw_hex(b'\x02') # Option 53 - DHCP OFFER
+
+ if mode == 'dhcp_request':
+ print('[%s] --> Option 53 (DHCP ACK): 5' % client)
+ data += craft_option(53).raw_hex(b'\x05') # Option 53 - DHCP ACK
+
+ data += craft_option(54).bytes(socket.inet_aton(dhcp_server_address)) # Option 54 - DHCP server identifier
+ print('[%s] --> Option 54 (DHCP server identifier): %s' % (client, dhcp_server_address))
+
+ data += craft_option(51).raw_hex(b'\x00\x00\xa8\xc0') # Option 51 - Lease time left padded with "0"
+ print('[%s] --> Option 51 (Lease time): %s' % (client, '43200 (12 hours)'))
+
+ data += craft_option(1).ip(cidr_to_subnet(l['mgmt_cidr'])) # Option 1 - Subnet mask
+ print('[%s] --> Option 1 (subnet mask): %s' % (client, cidr_to_subnet(l['mgmt_cidr'])))
+
+ data += craft_option(3).ip(l['mgmt_gw']) # Option 3 - Default gateway (set to DHCP forwarders IP)
+ print('[%s] --> Option 3 (default gateway): %s' % (client, l['mgmt_gw']))
+
+ data += craft_option(150).bytes(socket.inet_aton(dhcp_server_address)) # Option 150 - TFTP Server. Used as target for the Zero Touch Protocol. Not necessarily TFTP protocol used.
+ print('[%s] --> Option 150 (Cisco proprietary TFTP server(s)): %s' % (client, dhcp_server_address))
+
+ # http://www.juniper.net/documentation/en_US/junos13.2/topics/concept/software-image-and-configuration-automatic-provisioning-understanding.html
+ data += craft_option(43).bytes(craft_option(0).string(target_junos_file) + craft_option(1).string('/tg-edge/' + l['hostname']) + craft_option(3).string('http')) # Option 43 - ZTP
+ print('[%s] --> Option 43 (Vendor-specific option):' % client)
+ print('[%s] --> Suboption 0: %s' % (client, target_junos_file))
+ print('[%s] --> Suboption 1: %s' % (client, '/tg-edge/' + l['hostname']))
+ print('[%s] --> Suboption 3: %s' % (client, 'http'))
+
+ data += b'\xff'
+
+ lease(lease_identifiers).set('current_mac', client) # updates MAC in DB
+
+ return data
+
+if __name__ == "__main__":
+ interface = b'eth0'
+ dhcp_server_address = '10.0.100.2'
+ # target_junos_file = '/files/jinstall-ex-2200-14.1X53-D15.2-domestic-signed.tgz'
+ target_junos_file = '/files/jinstall-ex-2200-14.1X53-D15.2-domestic-signed.tgz'
+
+ # Setting up the server, and how it will communicate
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # IPv4 UDP socket
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
+ s.setsockopt(socket.SOL_SOCKET, 25, interface)
+ s.bind(('', 67))
+
+ # Starting the whole loop
+ print('Starting main loop')
+ while True: #main loop
+ try:
+ message, addressf = s.recvfrom(8192)
+ # print(message)
+ if message.startswith(b'\x01'): # UDP payload is DHCP request (discover, request, release)
+ if addressf[0] == '0.0.0.0':
+ print('[%s] DHCP broadcast - unsupported' % client)
+ reply_to = '<broadcast>'
+ else:
+ print('[%s] DHCP unicast - DHCP forwarding' % client)
+ reply_to = addressf[0] # senders (DHCP forwarders) IP
+ # print(addressf[0])
+ # reply_to = '10.0.0.1'
+ data=reqparse(message) # Parse the DHCP request
+ if data:
+ print('[%s] --> replying to %s' % (client, reply_to))
+ s.sendto(data, (reply_to, 67)) # Sends reply
+ print('')
+ except KeyboardInterrupt:
+ exit()
diff --git a/fap/dhcpd/terminal.log b/fap/dhcpd/terminal.log
new file mode 100644
index 0000000..e865bd4
--- /dev/null
+++ b/fap/dhcpd/terminal.log
@@ -0,0 +1,146 @@
+j@lappie:~/git/tgmanage$ sudo python3 fap/dhcpd/server_dhcp.py
+Starting main loop
+[] DHCP unicast - DHCP forwarding
+[40:b4:f0:cc:76:01] Parsing DHCP packet from client
+[40:b4:f0:cc:76:01] --> processing DHCP options
+[40:b4:f0:cc:76:01] --> option: 53: DHCP Discover (will not be used in reply)
+[40:b4:f0:cc:76:01] --> option: 12: b'GP0212466317'
+[40:b4:f0:cc:76:01] --> option: 60: 4a:75:6e:69:70:65:72:2d:65 [...]
+[40:b4:f0:cc:76:01] --> processing suboption hook for option 82
+[40:b4:f0:cc:76:01] --> suboption 1 found - value: "distro0gw:ge-0/0/0.0:mgmt"
+[40:b4:f0:cc:76:01] --> Finished processing suboption 82
+[40:b4:f0:cc:76:01] --> Finished processing options
+[40:b4:f0:cc:76:01] --> DHCP packet type: DHCP DISCOVER
+[40:b4:f0:cc:76:01] --> DHCP packet contains option 82 - continues to process
+[40:b4:f0:cc:76:01] --> DHCP packet forwarded by relay 10.0.200.1
+[40:b4:f0:cc:76:01] --> DHCP XID/Transaction ID: 75:45:e1:46
+[40:b4:f0:cc:76:01] --> Looking up in the DB
+[40:b4:f0:cc:76:01] --> Query details: distro_name:distro0gw, distro_phy_port:ge-0/0/0
+[40:b4:f0:cc:76:01] --> Data found, switch exists in DB - ready to craft response
+[40:b4:f0:cc:76:01] --> Crafting DHCP OFFER response
+[40:b4:f0:cc:76:01] --> XID/Transaction ID: 75:45:e1:46
+[40:b4:f0:cc:76:01] --> Client IP: 10.0.200.101
+[40:b4:f0:cc:76:01] --> DHCP forwarder IP: 10.0.200.1
+[40:b4:f0:cc:76:01] --> Client MAC: 40:b4:f0:cc:76:01
+[40:b4:f0:cc:76:01] --> Completed DHCP header structure, building DHCP options
+[40:b4:f0:cc:76:01] --> Option 53 (DHCP OFFER): 2
+[40:b4:f0:cc:76:01] --> Option 54 (DHCP server identifier): 10.0.100.2
+[40:b4:f0:cc:76:01] --> Option 51 (Lease time): 43200 (12 hours)
+[40:b4:f0:cc:76:01] --> Option 1 (subnet mask): 255.255.255.0
+[40:b4:f0:cc:76:01] --> Option 3 (default gateway): 10.0.200.1
+[40:b4:f0:cc:76:01] --> Option 150 (Cisco proprietary TFTP server(s)): 10.0.100.2
+[40:b4:f0:cc:76:01] --> Option 43 (Vendor-specific option):
+[40:b4:f0:cc:76:01] --> Suboption 0: /files/jinstall-ex-2200-12.3R6.6-domestic-signed.tgz
+[40:b4:f0:cc:76:01] --> Suboption 1: /tg-edge/e-00-1
+[40:b4:f0:cc:76:01] --> Suboption 3: http
+[40:b4:f0:cc:76:01] --> replying to 10.0.100.1
+
+[40:b4:f0:cc:76:01] DHCP unicast - DHCP forwarding
+[40:b4:f0:cc:76:01] Parsing DHCP packet from client
+[40:b4:f0:cc:76:01] --> processing DHCP options
+[40:b4:f0:cc:76:01] --> option: 54: b'\n\x00d\x02'
+[40:b4:f0:cc:76:01] --> option: 55: b'\x033\x01\x0f\x06BC+\x96\x0c\x07*'
+[40:b4:f0:cc:76:01] --> option: 50: b'\n\x00\xc8e'
+[40:b4:f0:cc:76:01] --> option: 53: b'\x03'
+[40:b4:f0:cc:76:01] --> option: 12: b'GP0212466317'
+[40:b4:f0:cc:76:01] --> option: 60: 4a:75:6e:69:70:65:72:2d:65 [...]
+[40:b4:f0:cc:76:01] --> processing suboption hook for option 82
+[40:b4:f0:cc:76:01] --> suboption 1 found - value: "distro0gw:ge-0/0/0.0:mgmt"
+[40:b4:f0:cc:76:01] --> Finished processing suboption 82
+[40:b4:f0:cc:76:01] --> Finished processing options
+[40:b4:f0:cc:76:01] --> DHCP packet type: DHCP REQUEST
+[40:b4:f0:cc:76:01] --> DHCP packet contains option 82 - continues to process
+[40:b4:f0:cc:76:01] --> DHCP packet forwarded by relay 10.0.200.1
+[40:b4:f0:cc:76:01] --> DHCP XID/Transaction ID: 51:5f:00:7c
+[40:b4:f0:cc:76:01] --> Looking up in the DB
+[40:b4:f0:cc:76:01] --> Query details: distro_name:distro0gw, distro_phy_port:ge-0/0/0
+[40:b4:f0:cc:76:01] --> Data found, switch exists in DB - ready to craft response
+[40:b4:f0:cc:76:01] --> Crafting DHCP ACK response
+[40:b4:f0:cc:76:01] --> XID/Transaction ID: 51:5f:00:7c
+[40:b4:f0:cc:76:01] --> Client IP: 10.0.200.101
+[40:b4:f0:cc:76:01] --> DHCP forwarder IP: 10.0.200.1
+[40:b4:f0:cc:76:01] --> Client MAC: 40:b4:f0:cc:76:01
+[40:b4:f0:cc:76:01] --> Completed DHCP header structure, building DHCP options
+[40:b4:f0:cc:76:01] --> Option 53 (DHCP ACK): 5
+[40:b4:f0:cc:76:01] --> Option 54 (DHCP server identifier): 10.0.100.2
+[40:b4:f0:cc:76:01] --> Option 51 (Lease time): 43200 (12 hours)
+[40:b4:f0:cc:76:01] --> Option 1 (subnet mask): 255.255.255.0
+[40:b4:f0:cc:76:01] --> Option 3 (default gateway): 10.0.200.1
+[40:b4:f0:cc:76:01] --> Option 150 (Cisco proprietary TFTP server(s)): 10.0.100.2
+[40:b4:f0:cc:76:01] --> Option 43 (Vendor-specific option):
+[40:b4:f0:cc:76:01] --> Suboption 0: /files/jinstall-ex-2200-12.3R6.6-domestic-signed.tgz
+[40:b4:f0:cc:76:01] --> Suboption 1: /tg-edge/e-00-1
+[40:b4:f0:cc:76:01] --> Suboption 3: http
+[40:b4:f0:cc:76:01] --> replying to 10.0.100.1
+
+[40:b4:f0:cc:76:01] DHCP unicast - DHCP forwarding
+[40:b4:f0:cc:76:01] Parsing DHCP packet from client
+[40:b4:f0:cc:76:01] --> processing DHCP options
+[40:b4:f0:cc:76:01] --> option: 53: DHCP Discover (will not be used in reply)
+[40:b4:f0:cc:76:01] --> option: 60: 4a:75:6e:69:70:65:72:2d:65 [...]
+[40:b4:f0:cc:76:01] --> processing suboption hook for option 82
+[40:b4:f0:cc:76:01] --> suboption 1 found - value: "distro0gw:ge-0/0/0.0:mgmt"
+[40:b4:f0:cc:76:01] --> Finished processing suboption 82
+[40:b4:f0:cc:76:01] --> Finished processing options
+[40:b4:f0:cc:76:01] --> DHCP packet type: DHCP DISCOVER
+[40:b4:f0:cc:76:01] --> DHCP packet contains option 82 - continues to process
+[40:b4:f0:cc:76:01] --> DHCP packet forwarded by relay 10.0.200.1
+[40:b4:f0:cc:76:01] --> DHCP XID/Transaction ID: 64:3c:98:69
+[40:b4:f0:cc:76:01] --> Looking up in the DB
+[40:b4:f0:cc:76:01] --> Query details: distro_name:distro0gw, distro_phy_port:ge-0/0/0
+[40:b4:f0:cc:76:01] --> Data found, switch exists in DB - ready to craft response
+[40:b4:f0:cc:76:01] --> Crafting DHCP OFFER response
+[40:b4:f0:cc:76:01] --> XID/Transaction ID: 64:3c:98:69
+[40:b4:f0:cc:76:01] --> Client IP: 10.0.200.101
+[40:b4:f0:cc:76:01] --> DHCP forwarder IP: 10.0.200.1
+[40:b4:f0:cc:76:01] --> Client MAC: 40:b4:f0:cc:76:01
+[40:b4:f0:cc:76:01] --> Completed DHCP header structure, building DHCP options
+[40:b4:f0:cc:76:01] --> Option 53 (DHCP OFFER): 2
+[40:b4:f0:cc:76:01] --> Option 54 (DHCP server identifier): 10.0.100.2
+[40:b4:f0:cc:76:01] --> Option 51 (Lease time): 43200 (12 hours)
+[40:b4:f0:cc:76:01] --> Option 1 (subnet mask): 255.255.255.0
+[40:b4:f0:cc:76:01] --> Option 3 (default gateway): 10.0.200.1
+[40:b4:f0:cc:76:01] --> Option 150 (Cisco proprietary TFTP server(s)): 10.0.100.2
+[40:b4:f0:cc:76:01] --> Option 43 (Vendor-specific option):
+[40:b4:f0:cc:76:01] --> Suboption 0: /files/jinstall-ex-2200-12.3R6.6-domestic-signed.tgz
+[40:b4:f0:cc:76:01] --> Suboption 1: /tg-edge/e-00-1
+[40:b4:f0:cc:76:01] --> Suboption 3: http
+[40:b4:f0:cc:76:01] --> replying to 10.0.100.1
+
+[40:b4:f0:cc:76:01] DHCP unicast - DHCP forwarding
+[40:b4:f0:cc:76:01] Parsing DHCP packet from client
+[40:b4:f0:cc:76:01] --> processing DHCP options
+[40:b4:f0:cc:76:01] --> option: 54: b'\n\x00d\x02'
+[40:b4:f0:cc:76:01] --> option: 55: b'\x033\x01\x0f\x06BC+\x96\x0c\x07*'
+[40:b4:f0:cc:76:01] --> option: 50: b'\n\x00\xc8e'
+[40:b4:f0:cc:76:01] --> option: 53: b'\x03'
+[40:b4:f0:cc:76:01] --> option: 60: 4a:75:6e:69:70:65:72:2d:65 [...]
+[40:b4:f0:cc:76:01] --> processing suboption hook for option 82
+[40:b4:f0:cc:76:01] --> suboption 1 found - value: "distro0gw:ge-0/0/0.0:mgmt"
+[40:b4:f0:cc:76:01] --> Finished processing suboption 82
+[40:b4:f0:cc:76:01] --> Finished processing options
+[40:b4:f0:cc:76:01] --> DHCP packet type: DHCP REQUEST
+[40:b4:f0:cc:76:01] --> DHCP packet contains option 82 - continues to process
+[40:b4:f0:cc:76:01] --> DHCP packet forwarded by relay 10.0.200.1
+[40:b4:f0:cc:76:01] --> DHCP XID/Transaction ID: 66:33:48:73
+[40:b4:f0:cc:76:01] --> Looking up in the DB
+[40:b4:f0:cc:76:01] --> Query details: distro_name:distro0gw, distro_phy_port:ge-0/0/0
+[40:b4:f0:cc:76:01] --> Data found, switch exists in DB - ready to craft response
+[40:b4:f0:cc:76:01] --> Crafting DHCP ACK response
+[40:b4:f0:cc:76:01] --> XID/Transaction ID: 66:33:48:73
+[40:b4:f0:cc:76:01] --> Client IP: 10.0.200.101
+[40:b4:f0:cc:76:01] --> DHCP forwarder IP: 10.0.200.1
+[40:b4:f0:cc:76:01] --> Client MAC: 40:b4:f0:cc:76:01
+[40:b4:f0:cc:76:01] --> Completed DHCP header structure, building DHCP options
+[40:b4:f0:cc:76:01] --> Option 53 (DHCP ACK): 5
+[40:b4:f0:cc:76:01] --> Option 54 (DHCP server identifier): 10.0.100.2
+[40:b4:f0:cc:76:01] --> Option 51 (Lease time): 43200 (12 hours)
+[40:b4:f0:cc:76:01] --> Option 1 (subnet mask): 255.255.255.0
+[40:b4:f0:cc:76:01] --> Option 3 (default gateway): 10.0.200.1
+[40:b4:f0:cc:76:01] --> Option 150 (Cisco proprietary TFTP server(s)): 10.0.100.2
+[40:b4:f0:cc:76:01] --> Option 43 (Vendor-specific option):
+[40:b4:f0:cc:76:01] --> Suboption 0: /files/jinstall-ex-2200-12.3R6.6-domestic-signed.tgz
+[40:b4:f0:cc:76:01] --> Suboption 1: /tg-edge/e-00-1
+[40:b4:f0:cc:76:01] --> Suboption 3: http
+[40:b4:f0:cc:76:01] --> replying to 10.0.100.1
+