使用raw socket 编写简易的syn扫描器,发送请求包后无法收到响应包(使用wireshark),查阅资料,可能出现的情况是checksum不使用网络字节序,但是修改后发送依然收不到响应包,通过tcp connect扫描已排除不是wireshark的问题。以下是我构造头文件的代码:
IPheader
def creat_ip_header(ip_source, ip_dest):
ip_ver = 4 #ipv4
ip_hlh = 5 #Header_lenth
ip_dscp = 0 #服务类型
ip_total_lenth = 0 #自行填充
ip_id = 22222
ip_frag_offset = 0
ip_ttl = 255
ip_protocol = socket.IPPROTO_TCP
ip_checksum = 0
ip_saddr = socket.inet_pton(socket.AF_INET, ip_source)
ip_daddr = socket.inet_pton(socket.AF_INET, ip_dest)
ip_ver_hlh = (ip_ver<<4) + ip_hlh
ip_header = pack("!BBHHHBBH4s4s", ip_ver_hlh, ip_dscp, ip_total_lenth, ip_id, ip_frag_offset, ip_ttl, ip_protocol, ip_checksum, ip_saddr, ip_daddr)
ip_checksum = check_sum(ip_header)
ip_header = pack("!BBHHHBBH4s4s", ip_ver_hlh, ip_dscp, ip_total_lenth, ip_id, ip_frag_offset, ip_ttl, ip_protocol, socket.htons(ip_checksum), ip_saddr, ip_daddr)
return ip_header
#TCP header
def creat_tcp_header(ip_source, ip_dest, tcp_dport):
tcp_sport = 41876
tcp_seq = 10
tcp_ack_seq = 0
tcp_data_offset = 5 # same as ip_hlh 32bit为单位
tcp_flag_urg = 0
tcp_flag_ack = 0
tcp_flag_psh = 0
tcp_flag_rst = 0
tcp_flag_syn = 1
tcp_flag_fin = 0
tcp_window_size = socket.htons(5840)
tcp_checksum = 0
tcp_urgent_ptr = 0
tcp_offset_reserv = (tcp_data_offset <<4)#合并
tcp_flag = tcp_flag_fin + (tcp_flag_syn<<1) + (tcp_flag_rst<<2) + (tcp_flag_psh<<3) + (tcp_flag_ack<<4) + (tcp_flag_urg<<5)
tcp_header = pack("!HHLLBBHHH", tcp_sport, tcp_dport, tcp_seq, tcp_ack_seq, tcp_offset_reserv, tcp_flag, tcp_window_size, tcp_checksum, tcp_urgent_ptr) #构建TCP头
psh_saddr = ip_source #构造伪头部
psh_daddr = ip_dest
psh_zero = 0
psh_protocol = socket.IPPROTO_TCP
psh_TCP_len = len(tcp_header)
psh = pack("!4s4sBBH", psh_saddr, psh_daddr, psh_zero, psh_protocol, psh_TCP_len)
psh = psh + tcp_header
if len(psh)%2 !=0: #必要追加1字节
psh += '\0'
tcp_checksum = check_sum(psh)
tcp_header = pack("!HHLLBBH", tcp_sport, tcp_dport, tcp_seq, tcp_ack_seq, tcp_offset_reserv, tcp_flag, tcp_window_size) + pack("<H", tcp_checksum) + pack("!H", tcp_urgent_ptr) #重新打包tcp_header
return tcp_header
创建套接字并设置
def creatSocket(ip_source, ip_dest):
try:
#z = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
z = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)
# z.settimeout(20)
except socket.error, msg:
print 'Socket creat erro:' , str(msg[0]), 'message', msg[1]