Npcap 是一款高性能的网络捕获和数据包分析库,作为 Nmap 项目的一部分,Npcap 可用于捕获、发送和分析网络数据包。本章将介绍如何使用 Npcap 库来实现半开放扫描功能。TCP SYN 半开放扫描是一种常见且广泛使用的端口扫描技术,用于探测目标主机端口的开放状态。由于这种方法并不完成完整的 TCP 三次握手过程,因此具有更高的隐蔽性和扫描效率。
笔者原本想为大家整理并分享如何使用Nmap
工具进行端口扫描的,但觉得仅仅讲解Nmap
的命令使用方法并不能让大家更好地理解其工作原理。实际上,Nmap 的底层使用的是Npcap
库,因此笔者决定演示如何使用Npcap
库开发一个简单的扫描功能,从而帮助大家更好地理解Nmap
的原理。
首先,若使用Nmap
对目标主机进行SYN
扫描,只需要执行nmap -sS 39.97.203.57
命令即可,等待一段时间则可获取到目标主机常规开放端口状态,若要扫描特定端口开放状态仅需要指定-p
参数并携带扫描区间即可,如下命令所示;
Npcap库的配置非常简单,读者仅需要去到 官网下载,初次使用还需安装 Npcap 1.79 installer驱动程序,并下载 Npcap SDK 1.13对应的开发工具包,如下图所示;
接着,读者需要自行解压SDK
开发工具包,并配置VC++
目录包含目录与库目录,如下图所示;
在进行开发之前,我们需要先定义三个结构体变量,首先定义eth_header
数据包头,以太网包头(Ethernet Frame Header)用于传输控制信息和数据,它是数据链路层的一部分,负责在局域网中实现数据的可靠传输。
接着定义ip_header
数据包头,IP头(IP Header)用于传输控制信息和数据,IP头是网络层的一部分,负责实现跨越不同网络的数据传输。
最后定义tcp_header
数据包头,TCP头(TCP Header)用于传输控制信息和数据,TCP头是传输层的一部分,负责在主机之间提供可靠的、面向连接的通信。
若要发送TCP数据包,必须要构造一个完整的通信协议头,将以太网数据包头、IP数据包头、TCP数据包头封装起来即可,其定义部分如下所示,其中每一个变量均对应于协议的每一个参数。
接着需要实现两个通用函数,其中EnumAdapters
用于枚举当前系统中所有的网卡信息,并输出其下标号与网卡描述信息,BindAdapters
函数则用于根据用户传入的下标号对网卡进行动态绑定,函数中通过循环的方式查找网卡下标若匹配则将下标所对应的句柄存储到temp_adapter
变量内,最后通过pcap_open_live
实现对网卡的打开。
抓包回调函数packet_handler
由pcap_loop
调用,当启用抓包后若句柄返回数据则会通过回调函数通知用户,用户获取到数据包header
后,通过逐层解析即可得到所需要的字段,若要实现SYN
快速探测则需要判断tcph
标志,若标志被返回则可通过RST
断开会话,并以此节约扫描时间。
如下代码,定义了一个网络数据包回调函数 packet_handler
,用于处理通过 pcap
库捕获的网络数据包。函数首先打印数据包的长度,然后解析以太网头部以检查其类型是否为 IP(0x0800)
。如果是 IP
数据包,进一步解析 IP
头部并打印相关信息,包括 IP
版本、头长度、源 IP
地址和目标 IP
地址。随后检查 IP
数据包的协议字段是否为 TCP(6)
,若是,则解析 TCP
头部并打印源端口、目标端口、序列号、确认号、头部长度、标志、窗口大小、校验和及紧急指针等信息。
最后来看下主函数是如何实现的,首先通过调用EnumAdapters
函数获取到网卡编号,并调用BindAdapters(4)
函数绑定到指定的网卡之上,套接字的创建依然采用原生API
接口来实现,只不过在调用sendto
发送数据包时我们需要自行构建一个符合SYN
扫描条件的数据包,在构建数据包时,以太网数据包用于指定网卡MAC地址等信息,IP数据包头则用于指定IP地址等信息,TCP数据包头则用于指定端口号信息,并仅需将tcph->syn = 1;
设置为1,通过checksum
计算校验和,并将校验好的packet
包通过sendto
函数发送到对端主机,如下所示;
读者可自行编译并运行上述代码,当执行成功后则可看到数据包的方向及标志类型,如下图所示。