1. 程式人生 > >用winpacp監聽並分析 FTP 協議並記錄 IP、使用者名稱、密碼和登陸是否成功

用winpacp監聽並分析 FTP 協議並記錄 IP、使用者名稱、密碼和登陸是否成功

為了完成計算機網路的實驗,翻了一些部落格,有的沒原始碼,有的記錄不全。就很煩。所以自己寫一篇吧。

首先我們通過wireshark看看FTP的登陸是怎麼完成的。

(1)選一個當前在用的網路,我是WLAN

(2)選擇TCP過濾器方便找到FTP的包(沒有過濾FTP的,最多隻能過濾出TCP)

(3)開始捕捉後我們就可以找到需要的包了。右鍵一個FTP包,點跟蹤流,可以看到所有相關的包。

OK,現在我們已經知道FTP登陸的過程了。一個頭部是USER的包,一個頭部是PASS的包,以及頭部是530表示登入失敗(230代表成功)的包。三個包就足夠讓我們開一個暴力的beta程式了。

開始程式設計吧。我們首先要設定在程式中設定TCP過濾器。如下:

       char packet_filter[] = "tcp";
       //編譯過濾器  
	if (pcap_compile(adhandle, &fcode, packet_filter, 1, netmask) <0)
	{
		fprintf(stderr, "\nUnable to compile the packet filter. Check the syntax.\n");
		/* 釋放裝置列表 */
		pcap_freealldevs(alldevs);
		return -1;
	}

	//設定過濾器  
	if (pcap_setfilter(adhandle, &fcode)<0)
	{
		fprintf(stderr, "\nError setting the filter.\n");
		/* 釋放裝置列表 */
		pcap_freealldevs(alldevs);
		return -1;
	}

然後在回撥函式中,我們讀取每個包資訊部分(注意要跳過頭部)的前四個字元,進行判斷如下:

        string com;//讀取
	for (int i = 0; i < 4; i++)
		com += (char)pkt_data[head + i];
	if (com == "USER")
	{
		string m_ip_message = get_request_m_ip_message(pkt_data);
		string user;
		ostringstream sout;
		for (int i = head+5; pkt_data[i]!=13; i++)
		{
			sout << pkt_data[i];
		}
		user = sout.str();
		ftp[m_ip_message][0] = user;
	}
	if (com == "PASS")
	{
		string m_ip_message = get_request_m_ip_message(pkt_data);
		string pass;
		ostringstream sout;
		for (int i = head + 5; pkt_data[i] != 13; i++)
		{
			sout << pkt_data[i];
		}
		pass = sout.str();
		ftp[m_ip_message][1] = pass;
	}
	if (com == "230 ")
	{
		string m_ip_message = get_response_m_ip_message(pkt_data);
		ftp[m_ip_message][2] = "SUCCEED";
		print(header, m_ip_message);
	}
	if (com == "530 ")
	{
		string m_ip_message = get_response_m_ip_message(pkt_data);
		ftp[m_ip_message][2] = "FAILD";
		print(header, m_ip_message);
	}

FTP是一個map<string,string[3]> 記錄了以某兩臺電腦之間通訊的USER PASS以及訪問狀態。這樣可以避免多個FTP同時訪問造成錯誤。完成程式碼如下:

#include<iostream>
#include<sstream>
#include<string>
#include<map>
#include<fstream>
#include <pcap.h>
#pragma warning(disable:4996)
using namespace std;
map<string,string[3]> ftp;
bool flag;
ofstream out("mark.txt");
typedef struct mac_header
{
	u_char dest_addr[6];
	u_char src_addr[6];
	u_char type[2];
} mac_header;

/* IPv4 首部 ,20位元組*/
typedef struct ip_header {
	u_char  ver_ihl;        // 版本 (4 bits) + 首部長度 (4 bits)  
	u_char  tos;            // 服務型別(Type of service)  
	u_short tlen;           // 總長(Total length)  
	u_short identification; // 標識(Identification)  
	u_short flags_fo;       // 標誌位(Flags) (3 bits) + 段偏移量(Fragment offset) (13 bits)  
	u_char  ttl;            // 存活時間(Time to live)  
	u_char  proto;          // 協議(Protocol)  
	u_short crc;            // 首部校驗和(Header checksum)  
	u_char  saddr[4];      // 源地址(Source address)  
	u_char  daddr[4];      // 目的地址(Destination address)  
	u_int   op_pad;         // 選項與填充(Option + Padding)  
}ip_header;
//TCP頭部,總長度20位元組  
typedef struct tcp_header
{
	u_short sport;            //源埠號  
	u_short dport;             //目的埠號  
	u_int th_seq;                //序列號  
	u_int th_ack;               //確認號  
	u_int th1 : 4;              //tcp頭部長度  
	u_int th_res : 4;             //6位中的4位首部長度  
	u_int th_res2 : 2;            //6位中的2位首部長度  
	u_char th_flags;            //6位標誌位  
	u_short th_win;             //16位視窗大小  
	u_short th_sum;             //16位tcp檢驗和  
	u_short th_urp;             //16位緊急指標  
}tcp_header;

/* 回撥函式原型 */
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data);
string get_request_m_ip_message(const u_char* pkt_data);
string get_response_m_ip_message(const u_char* pkt_data);
void print(const struct pcap_pkthdr *header, string m_ip_message);

int main()
{
	flag = false;
	pcap_if_t *alldevs;
	pcap_if_t *d;
	int inum;
	int i = 0;
	pcap_t *adhandle;
	char errbuf[PCAP_ERRBUF_SIZE];
	u_int netmask;
	char packet_filter[] = "tcp";
	struct bpf_program fcode;

	/* 獲得裝置列表 */
	if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1)
	{
		fprintf(stderr, "Error in pcap_findalldevs: %s\n", errbuf);
		exit(1);
	}

	/* 列印列表 */
	for (d = alldevs; d; d = d->next)
	{
		printf("%d. %s", ++i, d->name);
		if (d->description)
			printf(" (%s)\n", d->description);
		else
			printf(" (No description available)\n");
	}

	if (i == 0)
	{
		printf("\nNo interfaces found! Make sure WinPcap is installed.\n");
		return -1;
	}

	printf("Enter the interface number (1-%d):", i);
	scanf("%d", &inum);

	if (inum < 1 || inum > i)
	{
		printf("\nInterface number out of range.\n");
		/* 釋放裝置列表 */
		pcap_freealldevs(alldevs);
		return -1;
	}

	/* 跳轉到已選裝置 */
	for (d = alldevs, i = 0; i< inum - 1; d = d->next, i++);

	/* 開啟介面卡 */
	if ((adhandle = pcap_open(d->name,  // 裝置名  
		65536,     // 要捕捉的資料包的部分  
				   // 65535保證能捕獲到不同資料鏈路層上的每個資料包的全部內容  
		PCAP_OPENFLAG_PROMISCUOUS,         // 混雜模式  
		1000,      // 讀取超時時間  
		NULL,      // 遠端機器驗證  
		errbuf     // 錯誤緩衝池  
		)) == NULL)
	{
		fprintf(stderr, "\nUnable to open the adapter. %s is not supported by WinPcap\n", d->name);
		/* 釋放裝置列表 */
		pcap_freealldevs(alldevs);
		return -1;
	}

	/* 檢查資料鏈路層,為了簡單,我們只考慮乙太網 */
	if (pcap_datalink(adhandle) != DLT_EN10MB)
	{
		fprintf(stderr, "\nThis program works only on Ethernet networks.\n");
		/* 釋放裝置列表 */
		pcap_freealldevs(alldevs);
		return -1;
	}

	if (d->addresses != NULL)
		/* 獲得介面第一個地址的掩碼 */
		netmask = ((struct sockaddr_in *)(d->addresses->netmask))->sin_addr.S_un.S_addr;
	else
		/* 如果介面沒有地址,那麼我們假設一個C類的掩碼 */
		netmask = 0xffffff;


	//編譯過濾器  
	if (pcap_compile(adhandle, &fcode, packet_filter, 1, netmask) <0)
	{
		fprintf(stderr, "\nUnable to compile the packet filter. Check the syntax.\n");
		/* 釋放裝置列表 */
		pcap_freealldevs(alldevs);
		return -1;
	}

	//設定過濾器  
	if (pcap_setfilter(adhandle, &fcode)<0)
	{
		fprintf(stderr, "\nError setting the filter.\n");
		/* 釋放裝置列表 */
		pcap_freealldevs(alldevs);
		return -1;
	}

	printf("\nlistening on %s...\n", d->description);

	/* 釋放裝置列表 */
	pcap_freealldevs(alldevs);

	/* 開始捕捉 */
	pcap_loop(adhandle, 0, packet_handler, NULL);
	out.close();
	return 0;
}

/* 回撥函式,當收到每一個數據包時會被libpcap所呼叫 */
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data)
{
	struct tm *ltime;
	char timestr[16];
	ip_header *ih;
	tcp_header *uh;
	u_int ip_len;
	u_short sport, dport;
	time_t local_tv_sec;

	/* 將時間戳轉換成可識別的格式 */
	local_tv_sec = header->ts.tv_sec;
	ltime = localtime(&local_tv_sec);
	strftime(timestr, sizeof timestr, "%H:%M:%S", ltime);

	int head = 54;//14位乙太網頭,20位ip頭,20位tcp頭  
				  //選擇出command為USER和PASS的包,當然這裡就簡單的以首字母來代表了,反正其他的  
				  //command 沒有以U和P開頭的  
	string com;
	for (int i = 0; i < 4; i++)
		com += (char)pkt_data[head + i];
	if (com == "USER")
	{
		string m_ip_message = get_request_m_ip_message(pkt_data);
		string user;
		ostringstream sout;
		for (int i = head+5; pkt_data[i]!=13; i++)
		{
			sout << pkt_data[i];
		}
		user = sout.str();
		ftp[m_ip_message][0] = user;
	}
	if (com == "PASS")
	{
		string m_ip_message = get_request_m_ip_message(pkt_data);
		string pass;
		ostringstream sout;
		for (int i = head + 5; pkt_data[i] != 13; i++)
		{
			sout << pkt_data[i];
		}
		pass = sout.str();
		ftp[m_ip_message][1] = pass;
	}
	if (com == "230 ")
	{
		string m_ip_message = get_response_m_ip_message(pkt_data);
		ftp[m_ip_message][2] = "SUCCEED";
		print(header, m_ip_message);
	}
	if (com == "530 ")
	{
		string m_ip_message = get_response_m_ip_message(pkt_data);
		ftp[m_ip_message][2] = "FAILD";
		print(header, m_ip_message);
	}
	/*if (flag == true)
	{
		cout << com;
		for (int i = 0; i < 4; i++)
		{
			int a = com.c_str()[i];
			cout << " " << a;
		}
		cout << endl;
	}*/
}
string get_request_m_ip_message(const u_char* pkt_data)
{
	mac_header *mh;
	ip_header *ih;
	string m_ip_message;
	string str;//empty string
	ostringstream sout;
	int length = sizeof(mac_header) + sizeof(ip_header);
	mh = (mac_header*)pkt_data;
	ih = (ip_header*)(pkt_data + sizeof(mac_header));
	for (int i = 0; i<5; i++)
		sout << hex << (int)(mh->src_addr[i]) << "-";
	sout << (int)(mh->src_addr[5]) << ",";
	for (int i = 0; i<3; i++)
		sout << dec << (int)(ih->saddr[i]) << ".";
	sout << (int)(ih->saddr[3]) << ",";
	for (int i = 0; i<5; i++)
		sout << hex << (int)(mh->dest_addr[i]) << "-";
	sout << (int)(mh->dest_addr[5]) << ",";
	for (int i = 0; i < 3; i++)
		sout << dec << (int)(ih->daddr[i]) << ".";
	sout << (int)(ih->daddr[3]);
	m_ip_message = sout.str();
	return m_ip_message;
}
string get_response_m_ip_message(const u_char* pkt_data)
{
	mac_header *mh;
	ip_header *ih;
	string m_ip_message;
	string str;//empty string
	ostringstream sout;
	int length = sizeof(mac_header) + sizeof(ip_header);
	mh = (mac_header*)pkt_data;
	ih = (ip_header*)(pkt_data + sizeof(mac_header));
	for (int i = 0; i<5; i++)
		sout << hex << (int)(mh->dest_addr[i]) << "-";
	sout << (int)(mh->dest_addr[5]) << ",";
	for (int i = 0; i < 3; i++)
		sout << dec << (int)(ih->daddr[i]) << ".";
	sout << (int)(ih->daddr[3]) << ",";
	for (int i = 0; i<5; i++)
		sout << hex << (int)(mh->src_addr[i]) << "-";
	sout << (int)(mh->src_addr[5]) << ",";
	for (int i = 0; i<3; i++)
		sout << dec << (int)(ih->saddr[i]) << ".";
	sout << (int)(ih->saddr[3]);
	m_ip_message = sout.str();
	return m_ip_message;
}
void print(const struct pcap_pkthdr *header, string m_ip_message)
{
	struct tm *ltime;
	char timestr[16];
	time_t local_tv_sec;
	/* 將時間戳轉化為可識別的格式 */
	local_tv_sec = header->ts.tv_sec;
	ltime = localtime(&local_tv_sec);
	strftime(timestr, sizeof timestr, "%H:%M:%S", ltime);
	/* 列印時間戳*/
	cout << timestr << ",";
	cout << m_ip_message << ",";
	for (int i = 0; i < 2; i++)
		cout << ftp[m_ip_message][i] << ",";
	cout << ftp[m_ip_message][2] <<endl;
	out << timestr << ",";
	out << m_ip_message << ",";
	for (int i = 0; i < 2; i++)
		out << ftp[m_ip_message][i] << ",";
	out << ftp[m_ip_message][2] << endl;
	ftp.erase(m_ip_message);
}