Python's scanner writing

Source: Internet
Author: User
Tags ack dns spoofing

Well! The late stage of procrastination, has been incurable, survived the night of two nights, the basic computer network curriculum design of the Web scanner function realized.

In fact, write a scanner is also very fun, involving the raw socket programming, can indulge in DIY packets (of course, do not conform to the rules of the packet, such as checksum errors can not be the way), harvest quite deep. Among them, I think writing in C is more advantageous in the process of writing to deepen the understanding of the computer network, especially the details of the packet. But because of the efficiency problem, there is also Python is very useful (since the use of Python, the daily no longer want to touch C + +, although Python is also very bad writing). Talk not much, but to the truth.

Learn the nature of information security heard Nmap This network scanning artifact, which has many functional options, both young and old, not only to meet the daily life of network administrators, but also to meet the network security engineer penetration testing, the curriculum design level of the scanner naturally will not have so many functions, The main implementation of TCP and UDP to take advantage of some of the characteristics of IP segment host survival and port scanning.

The basic functions are as follows:

1. Send the UDP packet, detect a very small port to use, analyze the ICMP packet of the backhaul to determine if the host is alive.

2. Using the TCP three-time handshake, determine whether the port is open by the successful connection, which uses multithreading to speed up the scanning speed.

3. Through the raw socket's native programming, the TCP flag bit is manually set, the signature of the reply packet is analyzed, so no TCP three handshake can be used to determine whether the port is open. Some of the ways are

I: Detects if the flag bit of the callback packet is syn/ack by SYN 1

II: Check if the packet is returned via ACK 1, and the packet's flag bit is rst

III: Check whether the packet is returned by placing all the flag bits 0, and whether the packet's flag bit is rst

IV: Check whether the packet is returned via FIN+URG+PSH 1, and whether the packet's flag bit is rst

Before writing the function, it is necessary to write the IP,ICMP,TCP header to parse, directly look at the code:

IP Packet Header:

_fields_ = [        ("IHL", C_ubyte, 4),        ("version", C_ubyte, 4),        ("TOS", C_ubyte), ("Len", C_ushort), ("ID", C_ushort), ("Offset", C_ushort), ("TTL", C_ubyte), ("Protocol_num", C_ubyte), ("sum", C_ushort), ("src", C_ulong), ("DST", C_ulong)]

ICMP packet header:

 _fields_ = [(  " type   , C_ubyte), (  " code  "    checksum  
      
        "
         " unused   , C_ushort), (  " next_hop_mtu  "  , C_ushort)]  

TCP Packet Header:

_fields_ = [        ("Src_port", C_ushort), ("Dst_port", C_ushort), ("seq", C_ulong), ("Ack_seq", C_ulong), ("Offset", C_ubyte), ("Flag", C_ubyte), ("Windows", C_ushort), ("Checksum", C_ushort), (" Point", C_ushort),]

TCP packet Header Offset,flag is not a real packet structure, but because the single-byte detail is not good processing, directly written as above, all the structure is not a word two words can be said, details can refer to the "ip/tcp detailed".

1. Start with the simplest tcpconnect multi-line threaded port scanning, based on the policy of the partial firewall, we should make a random allocation algorithm to the port intervals that need to be scanned to interfere with the firewall's judgment. Of course, because it was too lazy, I went straight all the way down. The specific code is as follows:

defporttest (ip,port,num): s=Socket.socket (socket.af_inet, socket. SOCK_STREAM) I=0 whileI <Num:Try: MyPort= i +Port S.connect (("%s"%IP, MyPort)) S.close ()Print "%s:%d is open"%(Ip,myport)exceptbaseexception,e:PassI= I+1defTcpconnect (subnet,port,num=1): Port=Int (port)ifnum > 8:         forIpinchipnetwork (subnet): forIinchRange (0,threadnum): t= Threading. Thread (Target=porttest, args= (ip,port+i*num/threadnum,num/threadnum)) #开了8个线程, T.start ()Else:         forIpinchipnetwork (subnet): #方便对区段进行扫描 porttest (ip,port,num)

A total of eight threads were opened, and the port segment was divided into 8 parts for scanning. Using exceptions to exit the connection to a bit open port, but in practice, easy to be discovered by the network, this method can only be said to be the simplest, but not recommended.

2. Use UDP for scanning.

This involves the programming of raw sockets, and the code for UDP scanning in Python black hat is very good (the other code is good, and there are a lot of python tricks in it too). The basic principle is to set the promiscuous mode of the NIC via the Setsocketopt function. To sniff, paste directly inside the code:

defUdp_sender (subnet,magic_message): Time.sleep (5) Sender=Socket.socket (socket.af_inet, socket. SOCK_DGRAM) forIpinchipnetwork (subnet):Try: Sender.sendto (Magic_message, ("%s"% IP, 65211)) #对每个ip地址进行发包except:              PassdefIcmpecho (subnet):ifOs.name = ="NT": Socket_protocol=socket. Ipproto_ipElse: Socket_protocol=socket. IPPROTO_ICMP Sniffer=Socket.socket (socket.af_inet, socket. Sock_raw, Socket_protocol) Sniffer.bind ((host, 0)) sniffer.setsockopt (socket. IPPROTO_IP, Socket. IP_HDRINCL,1)      ifOs.name = ="NT": #跨平台必备 sniffer.ioctl (socket. Sio_rcvall, Socket. rcvall_on) T= Threading. Thread (Target=udp_sender, args=(subnet,magic_message)) #线程用于发送数据包 T.start ()Try:           whileTrue:raw_buffer= Sniffer.recvfrom (65565) [0] #对收到的数据包进行检测 Ip_header= IP (raw_buffer[0:20])              ifIp_header.protocol = ="ICMP": Offset= IP_HEADER.IHL * 4buf= raw_buffer[offset:offset+sizeof (ICMP)] Icmp_header=ICMP (BUF)ifIcmp_header.type = = 3 andIcmp_header.code = = 3:                      ifIPAddress (ip_header.src_address)inchipnetwork (subnet):ifRaw_buffer[len (Raw_buffer)-Len (magic_message):] = =Magic_message:Print "Host up:%s"%ip_header.src_addressexceptKeyboardinterrupt:ifOs.name = ="NT": Sniffer.ioctl (socket. Sio_rcvall, Socket. Rcvall_off)

3: The best thing to play is to construct the data package, you can do a lot of very geek things, such as DNS spoofing, ARP spoofing, SYN flooding and so on. First look at how to construct the sign.

def Createtcpflag (fin=0,syn=0,rst=0,psh=0,ack=0,urg=0):    = fin + (syn<<1) + (rst<<2 ) + (psh<<3) + (ack<<4) + (urg<<5)    return tcp_flags

The simple shift operation enables the operation of the symbol bit.

Let's look at how to create a TCP packet header.

defCreate_tcp_header (source_ip, Dest_ip, Dest_port,tcp_flag): Source= Random.randrange (32000,62000,1) Seq=0 Ack_seq=0 Doff= 5window= Socket.htons (8192) Check=0 #先将数据包的校验位置0 urg_ptr=0 Offset_res= (Doff << 4) +0 Tcp_flags=Tcp_flag Tcp_header= Struct.pack ('! Hhllbbhhh', source, Dest_port, seq, Ack_seq, offset_res, tcp_flags, window, check, urg_ptr)
#TCP头在进行校验和时, there needs to be a pseudo IP header, the basic details are as follows Source_address=Socket.inet_aton (source_ip) dest_address=Socket.inet_aton (dest_ip) placeholder=0 Protocol=socket. Ipproto_tcp Tcp_length=Len (tcp_header) PSH= Struct.pack ('!4S4SBBH', source_address, dest_address, placeholder, protocol, tcp_length); PSH= PSH +Tcp_header; Tcp_checksum=Checksum (PSH) Tcp_header= Struct.pack ('! Hhllbbhhh', source, Dest_port, seq, Ack_seq, offset_res, tcp_flags, window, Tcp_checksum, urg_ptr)returnTcp_header

The IP packet head is basically as above, please see the GitHub address at the end of the article. Can combine

Create_tcp_header () and Createtcpflag () manipulate the packet sign bits to achieve the functionality under Basic function 3.
  

Python's scanner writing

Related Article

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.