简体   繁体   中英

Intercepting/Rerouting TCP SYN packets to C++ program in linux

I am trying to find the easiest way to intercept TCP SYN packets sent by my computer in a c++ program. There are couple of options that I know. One would be monitor all traffic and just selectively work with the SYN packets doing nothing with the rest. Another option I came across was to use a packet filtering utility which will forward the SYN packets to my program. Someone suggested me to use netfilter for the same.

I was wondering if there are other options or should I delve into netfilter. Also, any pointers on how to do it this with netfilter would be helpful.

EDIT: I want to intercept the SYN packet and may need to modify it (reroute to different destination, change destination port etc) before reinjecting it back to the network

Edit: I was able to do this using a combination of iptables and libnetfilter_queue. I used ipfilter to redirect all TCP SYN packets to a particular queue (this was using a simple command)
Then in a C program I was able to use libnetfilter_queue API to access the packets in the queue analyze them and reinject them back to the network.

If you merely want to see the packets, use libpcap and packet filtering - that'll work on most any UNIX variant.

If you want to somehow intercept and rewrite the packets, please supply more information about what you're trying to do, and what's supposed to happen to the packets afterwards.

As you suggest, that might be an application for netfilter and its queue module, although that requires a 2.6.14 or later kernel:

Main Features

  • receiving queued packets from the kernel nfnetlink_queue subsystem
  • issuing verdicts and/or reinjecting altered packets to the kernel nfnetlink_queue subsystem

You can use the raw sockets or for example the pcap library. With pcap you set up the filter and capture the interesting traffic:

#include <pcap.h>
...
pcap_t* reader_handle;
char errbuf[PCAP_ERRBUF_SIZE];
if ( (reader_handle = pcap_open_live(device_string, capture_size, 0, timeout, errbuf) ) == NULL)
{
    //ooops
}
struct bpf_program fp;
if (pcap_compile(reader_handle, &fp, filter_string, 1, 0) == -1)
{
    //ooops, cleanup
}
if (pcap_setfilter(reader_handle, &fp) == -1)
{
    //ooops, cleanup
}
pcap_freecode(&fp);

And afterwards you just capture, there are few different ways, for example:

pcap_pkthdr* header; 
u_char* pkt_data;
const int status = pcap_next_ex(reader_handle, &header, &pkt_data);
// Check the status

After ending the capture:

pcap_close(reader_handle);

You need privileges to play with raw sockets. The above example can be nicely wrapped in C++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM