Python uses raw sockets for TCP SYN scan

Source: Internet
Author: User
Tags ack ord

1. TCP SYN Scan

Port scanning is commonly used to detect server or host open ports, used by computer administrators to confirm security policies, and is used by attackers to identify operational network services on targeted hosts. A port scan confirms the ports that can be used by sending a corresponding request to a range of server ports. Although it is not a malicious network activity in itself, it is also an important means for network attackers to probe the target host service to exploit known vulnerabilities in the service.
TCP SYN Scan is one of the many ways of port scanning, including TCP scanning, UDP scanning, ACK scanning, window scanning and fin scanning.
A TCP SYN scan is another TCP scan. The port Scan tool does not use the operating system native network functionality, but instead generates, sends, and monitors the IP packet itself. This scan mode is called a "semi-open scan" because it never establishes a full TCP connection. The port Scan tool generates a SYN packet and returns the Syn-ack package if the destination port is open. The scan side responds to an RST packet and then closes the connection before the handshake is complete. If the port is closed but no filtering is used, the destination port should continue to return the RST package.
Advantages of TCP SYN Scan:
  

    • Gives the scanning tool full control over the power of the packet to send and wait for the response time, allowing more detailed response analysis.

    • The SYN scan never establishes a full connection.
2. Python Code

Use raw sockets for SYN flooding, encapsulating multiple functions to make them modular and easy to understand. Structs can be used to encode data packets conveniently using formatted strings and variable lists.
  

#!/usr/bin/env python#-*-Coding:utf-8-*-# must run with root privilegesImportSocketImportSysImportTime fromstructImport*# Calculate Checksum def checksum(msg):s =0    # fetch 2 bytes at a time     forIinchRange0, Len (msg),2): W = (ord (msg[i]) <<8) + (ORD (msg[i+1])) s = s+w s = (s>> -) + (S &0xFFFF) s = ~s &0xFFFF    returnS def createsocket(source_ip,dest_ip):    Try: s = socket.socket (socket.af_inet, socket. SOCK_RAW, Socket. IPPROTO_TCP)exceptSocket.error, msg:Print ' Socket Create error: ', str (msg[0]),' message: ', msg[1] Sys.exit ()# Set the IP header to be supplied manuallyS.setsockopt (socket. IPPROTO_TCP, Socket. IP_HDRINCL,1)returnS# Create IP header def createipheader(source_ip, dest_ip):Packet ="'    # IP Header OptionsHeaderlen =5Version =4TOS =0Tot_len = -+ -id = random.randrange (18000,65535,1) Frag_off =0TTL =255protocol = socket. IPPROTO_TCP check =TenSADDR = Socket.inet_aton (source_ip) daddr = Socket.inet_aton (dest_ip) hl_version = (version <<4) + Headerlen Ip_header = Pack ('! Bbhhhbbh4s4s ', Hl_version, TOS, Tot_len, ID, Frag_off, TTL, protocol, check, SADDR, daddr)returnIp_header# Create a TCP header def create_tcp_syn_header(source_ip, Dest_ip, Dest_port):    # TCP Header OptionsSource = Random.randrange (32000,62000,1)# randomization of one source portSeq =0Ack_seq =0Doff =5    # TCP FlagsFin =0SYN =1TS2 =0PSH =0ACK =0Urg =0window = Socket.htons (8192)# Maximum Window sizeCheck =0Urg_ptr =0Offset_res = (Doff <<4) +0Tcp_flags = fin + (syn<<1) + (rst<<2) + (psh<<3) + (ack<<4) + (urg<<5) Tcp_header = Pack ('! Hhllbbhhh ', source, Dest_port, seq, Ack_seq, offset_res, tcp_flags, window, check, urg_ptr)# Pseudo-Header optionssource_address = Socket.inet_aton (source_ip) dest_address = Socket.inet_aton (dest_ip) placeholder =0protocol = socket. Ipproto_tcp tcp_length = Len (tcp_header) PSH = Pack ('!4S4SBBH ', source_address, dest_address, placeholder, protocol, tcp_length);    PSH = PSH + Tcp_header; Tcp_checksum = Checksum (PSH)# Repackage the TCP header and populate the correct checksumTcp_header = Pack ('! Hhllbbhhh ', source, Dest_port, seq, Ack_seq, offset_res, tcp_flags, window, Tcp_checksum, urg_ptr)returnTcp_header def range_scan(source_ip, Dest_ip, Start_port, End_port) :syn_ack_received = []# Open Port Storage list     forJinchRange (Start_port, end_port): s = Createsocket (Source_ip, dest_ip) Ip_header = Createipheader (Source_ip, DE ST_IP) Tcp_header = Create_tcp_syn_header (source_ip, dest_ip,j) packet = Ip_header + Tcp_header S.sen DTOs (Packet, DEST_IP,0)) data = S.recvfrom (1024x768) [0][0:] Ip_header_len = (Ord (data[0]) &0x0f) *4Ip_header_ret = data[0: Ip_header_len-1] Tcp_header_len = (Ord (data[ +]) &0xf0) >>2Tcp_header_ret = Data[ip_header_len:ip_header_len+tcp_header_len-1]ifOrd (tcp_header_ret[ -]) ==0x12:# Syn/ack FlagsSyn_ack_received.append (j)returnSyn_ack_received# The program starts here:Open_port_list = []ipsource =' 192.168.1.95 'Ipdest =' 192.168.1.31 'Start = -Stop = theStep = (Stop-start)/TenScan_ports = Range (start, stop, step)ifScan_ports[len (Scan_ports)-1] < Stop:scan_ports.append (stop) forIinchRange (len (scan_ports)-1): OPL = Range_scan (Ipsource, Ipdest, Scan_ports[i], scan_ports[i+1]) Open_port_list.append (OPL) forIinchRange (len (open_port_list)):Print ' Process #: 'I' Open ports: ', Open_port_list[i]Print ' A List of all open ports found: ' forIinchRange (len (open_port_list)): forJinchRange (len (open_port_list[i)):PrintOPEN_PORT_LIST[I][J],', '

Python uses raw sockets for TCP SYN scan

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.