aboutsummaryrefslogtreecommitdiffstats
path: root/gg_sniff/pcap.c
blob: e66a6d55daa360ee71876eed8d9d1b03fb7371c1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/param.h>
#include <sys/time.h>

#if !defined(__OpenBSD__)
#define __FAVOR_BSD
#endif
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <netinet/in_systm.h>
#include <netinet/if_ether.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
#include <netinet/ip_icmp.h>

#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <errno.h>
#include <time.h>

#include <pcap.h>
#include <event.h>

#include <libglouglou.h>
#include <libggnet.h>

#define PCAP_SNAPLEN 100
#define PCAP_FILTER "not port 4430 and not port 4431 and not port 53"
#define PCAP_COUNT 20
#define PCAP_TO 300

#define NULL_HDRLEN 4 // XXX portable ?
#define NODE_MAX_WITHOUT_TIMEOUT 1000
#define NODE_TIMEOUT 300 // XXX conf ?
#define CONN_TIMEOUT 300 // XXX conf ?
#define CONN_TIMEOUT_UDP 20 // XXX conf ?
#define CONN_TIMEOUT_ICMP 10 // XXX conf ?
#define CONNTIMER 5 // XXX conf ?

struct phandler {
	pcap_handler f;
	int type;
};

struct _cap_t {
  pcap_t           *pcap;
  pcap_handler      handler;
  struct event     *ev;
  struct event     *conntimer_ev;
  struct timeval    conntimer_tv;
  struct gg_client *ggcli;
  struct ggnet     *net;
  int               pinvalid;
  int               ptruncated;
};

static pcap_t *my_pcap_open_live(const char *, int, int, int,
                                 char *, u_int, u_int);
static void	 ip_handle(struct ip *, const u_char *, u_int);
static pcap_handler	lookup_phandler(int);
static void		phandler_ether(u_char *,
                             const struct pcap_pkthdr *, const u_char *);
static void		phandler_loop(u_char *,
                            const struct pcap_pkthdr *, const u_char *);
static void		cb_pcap(int, short, void *);
static void		cb_conntimer(int, short, void *);

static struct phandler phandlers[] = {
  { phandler_ether, DLT_EN10MB },
  { phandler_ether, DLT_IEEE802 },
  { phandler_loop,  DLT_LOOP },
  { NULL,           0 },
};

static struct _cap_t _cap;

int
ggsniff_pcap_init(struct event_base *ev_base, struct gg_client *ggcli,
                  struct ggnet *net, char *iface)
{
	char errbuf[PCAP_ERRBUF_SIZE];
	struct bpf_program bprog;
  pcap_t *pcap;

	pcap = my_pcap_open_live(iface, PCAP_SNAPLEN, 1, PCAP_TO,
	                         errbuf, -1, 0);
	if (pcap == NULL)
		gg_log_fatal("capture: pcap_open_live failed on interface %s\n"
                 "with snaplen %d : %s",
                 iface, PCAP_SNAPLEN, errbuf);
	if (pcap_compile(pcap, &bprog, PCAP_FILTER, 0, 0) < 0)
		gg_log_fatal("capture: pcap_compile failed with filter %s : %s",
                 PCAP_FILTER, pcap_geterr(pcap));
	if (pcap_setfilter(pcap, &bprog) < 0)
		gg_log_fatal("capture: pcap_setfilter failed : %s",
                 pcap_geterr(pcap));

	_cap.pcap = pcap;
	_cap.handler = lookup_phandler(pcap_datalink(pcap));
	//_cap.tv.tv_sec = 0;
	//_cap.tv.tv_usec = PCAP_TO;
	fd_nonblock(pcap_fileno(pcap));
  _cap.ev = event_new(ev_base, pcap_fileno(pcap), EV_READ|EV_PERSIST,
                       cb_pcap, NULL);
  //event_add(_cap.ev, &_cap->tv);
  event_add(_cap.ev, NULL);

	_cap.conntimer_tv.tv_sec = CONNTIMER;
	_cap.conntimer_tv.tv_usec = 0;
	_cap.conntimer_ev = evtimer_new(ev_base, cb_conntimer, NULL);
	if (evtimer_add(_cap.conntimer_ev, &_cap.conntimer_tv) == -1)
		gg_log_fatal("user: event_add conntimer failed: %s", strerror(errno));

  _cap.ggcli = ggcli;
  _cap.net = net;

	return 1;
}

void
ggsniff_pcap_shutdown(void)
{
  event_del(_cap.ev);
  pcap_close(_cap.pcap);
}

/*
 * reimplement pcap_open_live with more restrictions on the bpf fd :
 * - open device read only
 * - lock the fd
 * based on OpenBSD tcpdump, privsep_pcap.c v1.16
 */

static pcap_t *
my_pcap_open_live(const char *dev, int slen, int promisc, int to_ms,
	char *ebuf, u_int dlt, u_int dirfilt)
{
#if defined(__OpenBSD__)
	struct bpf_version bv;
	u_int v;
	pcap_t *p;
	char		bpf[sizeof "/dev/bpf0000000000"];
	int		fd, n = 0;
	struct ifreq	ifr;

	p = xmalloc(sizeof(*p));
	bzero(p, sizeof(*p));

	/* priv part */

	do {
		snprintf(bpf, sizeof(bpf), "/dev/bpf%d", n++);
		fd = open(bpf, O_RDONLY);
	} while (fd < 0 && errno == EBUSY);
	if (fd < 0)
		return NULL;

	v = 32768;	/* XXX this should be a user-accessible hook */
	ioctl(fd, BIOCSBLEN, &v);

	strlcpy(ifr.ifr_name, dev, sizeof(ifr.ifr_name));
	if (ioctl(fd, BIOCSETIF, &ifr) < 0)
		return NULL;

	if (dlt != (u_int) -1 && ioctl(fd, BIOCSDLT, &dlt))
		return NULL;

	if (promisc)
		/* this is allowed to fail */
		ioctl(fd, BIOCPROMISC, NULL);
	if (ioctl(fd, BIOCSDIRFILT, &dirfilt) < 0)
		return NULL;

	/* lock the descriptor */
	if (ioctl(fd, BIOCLOCK, NULL) < 0)
		return NULL;

	/* end of priv part */

	/* fd is locked, can only use 'safe' ioctls */
	if (ioctl(fd, BIOCVERSION, &bv) < 0) {
		snprintf(ebuf, PCAP_ERRBUF_SIZE, "BIOCVERSION: %s",
		    pcap_strerror(errno));
		return NULL;
	}

	if (bv.bv_major != BPF_MAJOR_VERSION ||
	    bv.bv_minor < BPF_MINOR_VERSION) {
		snprintf(ebuf, PCAP_ERRBUF_SIZE,
		    "kernel bpf filter out of date");
		return NULL;
	}

	p->fd = fd;
	p->snapshot = slen;

	/* Get the data link layer type. */
	if (ioctl(fd, BIOCGDLT, &v) < 0) {
		snprintf(ebuf, PCAP_ERRBUF_SIZE, "BIOCGDLT: %s",
		    pcap_strerror(errno));
		return NULL;
	}
#if _BSDI_VERSION - 0 >= 199510
	/* The SLIP and PPP link layer header changed in BSD/OS 2.1 */
	switch (v) {

	case DLT_SLIP:
		v = DLT_SLIP_BSDOS;
		break;

	case DLT_PPP:
		v = DLT_PPP_BSDOS;
		break;
	}
#endif
	p->linktype = v;

	/* XXX hack from tcpdump */
	if (p->linktype == DLT_PFLOG && p->snapshot < 160)
		p->snapshot = 160;

	/* set timeout */
	if (to_ms != 0) {
		struct timeval to;
		to.tv_sec = to_ms / 1000;
		to.tv_usec = (to_ms * 1000) % 1000000;
		if (ioctl(p->fd, BIOCSRTIMEOUT, &to) < 0) {
			snprintf(ebuf, PCAP_ERRBUF_SIZE, "BIOCSRTIMEOUT: %s",
			    pcap_strerror(errno));
			return NULL;
		}
	}

	if (ioctl(fd, BIOCGBLEN, &v) < 0) {
		snprintf(ebuf, PCAP_ERRBUF_SIZE, "BIOCGBLEN: %s",
		    pcap_strerror(errno));
		return NULL;
	}
	p->bufsize = v;
	p->buffer = (u_char *)malloc(p->bufsize);
	if (p->buffer == NULL) {
		snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
		    pcap_strerror(errno));
		return NULL;
	}
	return p;
#else /* defined(__OpenBSD__) */
  return pcap_open_live(dev, slen, promisc, to_ms, ebuf);
#endif
}

static void
cb_pcap(int fd, short why, void *data)
{
  gg_log_tmp("cb_pcap");
  pcap_dispatch(_cap.pcap, PCAP_COUNT, _cap.handler, NULL);

  /* reschedule */
  //if (event_add(&_cap->ev, &_cap->tv) == -1)
  //	gg_log_fatal("user: event_add pcap failed : %s", strerror(errno));
}

static void
cb_conntimer(int fd, short why, void *data)
{
	struct ggnet_conn *c, *ctmp;
	struct ggnet_node *n, *ntmp;
	int i, to;

	gg_log_debug("ev_timer");
	ggnet_time_update(_cap.net, time(NULL));

	i = 0;
	LIST_FOREACH_SAFE(c, &_cap.net->conn_list, entry, ctmp) {
		switch (c->proto) {
		case IPPROTO_UDP:
			to = CONN_TIMEOUT_UDP;
			break;
		case IPPROTO_ICMP:
			to = CONN_TIMEOUT_ICMP;
			break;
		default:
			to = CONN_TIMEOUT;
			break;
		}
		if (_cap.net->time > c->lastseen + to)
			ggnet_conn_del(_cap.net, c);
		else
			i++;
	}

	if (_cap.net->node_count > NODE_MAX_WITHOUT_TIMEOUT) {
		LIST_FOREACH_SAFE(n, &_cap.net->node_list, entry, ntmp) {
			if (n->used == 0 &&
				_cap.net->time > n->lastseen + NODE_TIMEOUT)
				ggnet_node_del(_cap.net, n);
		}
	}

	gg_log_debug("user: ev_timer leaving with %d active connections and %d active nodes", i, _cap.net->node_count);
	if (event_add(_cap.conntimer_ev, &_cap.conntimer_tv) == -1)
		gg_log_fatal("user: event_add conntimer failed : %s", strerror(errno));
}

/*
 * Parse an IP packet and descide what to do with it.
 * 'ip' is a pointer the the captured IP packet
 * 'pend' is a pointer to the end of the captured IP packet
 * 'wirelen' is the size of the IP packet off the wire
 */
#define NOTCAPTURED(v) ((u_char *)v > (u_char *)pend - sizeof(*v))
#define NOTRECEIVED(v) (wirelen < sizeof(v))
#define log_pinvalid(fmt, ...) \
  gg_log_info("ggsniff pinvalid: " fmt, ##__VA_ARGS__)
static void
ip_handle(struct ip *ip, const u_char *pend, u_int wirelen)
{
	u_int		len, ip_hlen, off;
	const u_char	*cp;
	struct tcphdr	*tcph;
	struct udphdr	*udph;
	struct icmp	*icmp;
	struct in_addr	src, dst;
	u_int		src_port, dst_port;
	u_int		size, proto, close;
	int response;
	struct ggnet_conn	*conn;
	struct gg_packet pkt;

	if (NOTCAPTURED(ip)) {
		log_pinvalid("user: ip truncated (ip %x pend %x sizeof(ip) %d",
        ip, pend, sizeof(ip));
		_cap.ptruncated++;
		return;
	}

	if (ip->ip_v != IPVERSION) {
		log_pinvalid("user: invalid ip version");
		_cap.pinvalid++;
		return;
	}

	len = ntohs(ip->ip_len);
	if (wirelen < len) {
		log_pinvalid("user: ip too small");
		_cap.pinvalid++;
		len = wirelen;
	}

	ip_hlen = ip->ip_hl * 4;
	if (ip_hlen < sizeof(struct ip) || ip_hlen > len) {
		log_pinvalid("user: ip_hlen invalid, %d", ip_hlen);
		_cap.pinvalid++;
		return;
	}
	len -= ip_hlen;

	src.s_addr = ntohl(ip->ip_src.s_addr);
	dst.s_addr = ntohl(ip->ip_dst.s_addr);
	src_port = 0;
	dst_port = 0;
	proto = IPPROTO_IP;
	size = len;
	close = 0;

	off = ntohs(ip->ip_off);
	if ((off & IP_OFFMASK) == 0) {
		cp = (const u_char *)ip + ip_hlen;
		switch (ip->ip_p) {

		case IPPROTO_TCP:
			tcph = (struct tcphdr *)cp;
			if (NOTCAPTURED(&tcph->th_flags)) {
				log_pinvalid("user: tcp truncated");
				_cap.ptruncated++;
				return;
			}
			if (NOTRECEIVED(*tcph)) {
				log_pinvalid("user: tcp too small");
				_cap.pinvalid++;
				return;
			}
			src_port = ntohs(tcph->th_sport);
			dst_port = ntohs(tcph->th_dport);
			proto = IPPROTO_TCP;
			size = len - sizeof(*tcph);
			if ((tcph->th_flags & TH_FIN) &&
				(tcph->th_flags & TH_ACK))
				close = 1;
			break;

		case IPPROTO_UDP:
			udph = (struct udphdr *)cp;
			if (NOTCAPTURED(&udph->uh_dport)) {
				log_pinvalid("user: udp truncated, "
					"ip %x, udph %x, uh_port %x, pend %x, ip_hlen %d",
					ip, udph, &udph->uh_dport, pend, ip_hlen);
				_cap.ptruncated++;
				return;
			}
			if (NOTRECEIVED(*udph)) {
				log_pinvalid("user: udp too small");
				_cap.pinvalid++;
				return;
			}
			src_port = ntohs(udph->uh_sport);
			dst_port = ntohs(udph->uh_dport);
			proto = IPPROTO_UDP;
			size = len - sizeof(*udph);
			break;

		case IPPROTO_ICMP:
			icmp = (struct icmp *)cp;
			if (NOTRECEIVED(*icmp)) {
				log_pinvalid("user: icmp too small");
				_cap.pinvalid++;
				return;
			}
			proto = IPPROTO_ICMP;
			size = len - sizeof(*icmp);
			break;

		default:
			gg_log_warn("user: unknown ip protocol !");
			break;
		}
	} else {
		/*
		 * if this isn't the first frag, we're missing the
		 * next level protocol header.
		 */
		gg_log_tmp("user: got a fragmented ip packet !");
	}

  pkt.ver = PACKET_VERSION;
  conn = ggnet_conn_find(_cap.net, &src, src_port, &dst, dst_port,
                         proto, &response);
	if (conn) {
		if (!close) {
		  pkt.type = PACKET_DATA;
		  pkt.data_connid = conn->id;
		  pkt.data_size = size << 8 | response;
      gg_client_send(_cap.ggcli, &pkt);
			ggnet_conn_data(_cap.net, conn, size, response);
		} else {
		  pkt.type = PACKET_DELCONN;
		  pkt.delconn_id = conn->id;
      gg_client_send(_cap.ggcli, &pkt);
			ggnet_conn_del(_cap.net, conn);
		}
	} else {
		if (!close) {
			conn = ggnet_conn_add(_cap.net, &src, src_port, &dst, dst_port, proto, size);
		  pkt.type = PACKET_NEWCONN;
		  pkt.newconn_id = conn->id;
		  pkt.newconn_src = src.s_addr;
		  pkt.newconn_dst = dst.s_addr;
		  pkt.newconn_proto = proto;
		  pkt.newconn_size = size << 8;
      gg_client_send(_cap.ggcli, &pkt);
		} else {
			gg_log_warn("user: captured connection close w/o open !");
		}
	}
}

static pcap_handler
lookup_phandler(int type)
{
        struct phandler *p;

        for (p = phandlers; p->f; ++p) {
                if (type == p->type)
                        return p->f;
        }
        gg_log_fatal("user: unknown data link type 0x%x", type);
        /* NOTREACHED */
	return NULL;
}

static void
phandler_ether(u_char *user, const struct pcap_pkthdr *h, const u_char *p)
{
	struct ether_header *ep;
	struct ip *ip;
	u_short ether_type;
	const u_char *pend;
	u_int	len;

	gg_log_debug("user: pcap handler ethernet !");

	/* XXX here i assume that packets are alligned, which might not
	 * be the case when using dump files, says tcpdump sources */

	ep = (struct ether_header *)p;
	pend = p + h->caplen;
	len = h->len - sizeof(struct ether_header);


	ether_type = ntohs(ep->ether_type);
	if (ether_type <= ETHERMTU)
		gg_log_tmp("llc packet !");
	else {
		switch (ether_type) {
		case ETHERTYPE_IP:
			gg_log_tmp("ether IP");
			ip = (struct ip *)((u_char *)ep + sizeof(struct ether_header));
			ip_handle(ip, pend, len);
			break;
		default:
			gg_log_tmp("non ip packet !");
			break;
		}
	}
}

static void
phandler_loop(u_char *user, const struct pcap_pkthdr *h, const u_char *p)
{
	struct ip *ip;
	struct ether_header *ep;
	u_short ether_type;
	u_int family;
	const u_char *pend;
	u_int	len;

	gg_log_debug("user: pcap handler loop !");

	/* XXX here i assume that packets are alligned, which might not
	 * be the case when using dump files, says tcpdump sources */

	pend = p + h->caplen;
	len = h->len;

	memcpy((char *)&family, (char *)p, sizeof(family));
	family = ntohl(family);
	switch (family) {
	case AF_INET:
		gg_log_tmp("loop family AF_INET");
		ip = (struct ip *)(p + NULL_HDRLEN);
		len -= NULL_HDRLEN;
		ip_handle(ip, pend, len);
		break;
#if defined(__OpenBSD__)
	case AF_LINK:
#else
	case AF_LOCAL:
#endif
		ep = (struct ether_header *)(p + NULL_HDRLEN);
		ether_type = ntohs(ep->ether_type);
		if (ether_type <= ETHERMTU)
			gg_log_tmp("llc packet !");
		else {
			switch (ether_type) {
			case ETHERTYPE_IP:
				gg_log_tmp("loop family AF_LINK IP");
				ip = (struct ip *)((u_char *)ep + sizeof(*ep));
				len -= NULL_HDRLEN + sizeof(*ep);
				ip_handle(ip, pend, len);
				break;
			default:
				gg_log_tmp("loop non ip packet !");
				break;
			}
		}
	default:
		gg_log_tmp("unknown family %x !", family);
		break;
	}
}