summaryrefslogtreecommitdiff
path: root/module/bsnmp-pcap.c
blob: f88ab164e6208eee12db8f095f12e291c8bd7bec (plain)
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
/*
 * Copyright (c) 2008, Stefan Walter
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *     * Redistributions of source code must retain the above
 *       copyright notice, this list of conditions and the
 *       following disclaimer.
 *     * Redistributions in binary form must reproduce the
 *       above copyright notice, this list of conditions and
 *       the following disclaimer in the documentation and/or
 *       other materials provided with the distribution.
 *     * The names of contributors to this software may not be
 *       used to endorse or promote products derived from this
 *       software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 *
 *
 * CONTRIBUTORS
 *  Stefan Walter <stef@memberwebs.com>
 */

#include "usuals.h"

#include <sys/param.h>
#include <sys/types.h>

#include <sys/limits.h>
#include <sys/queue.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <sys/sockio.h>
#include <sys/sysctl.h>

#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <arpa/inet.h>

#include <syslog.h>
#include <unistd.h>
#include <stdarg.h>
#include <ctype.h>
#include <fcntl.h>

#include <bsnmp/snmpmod.h>
#include <pcap.h>

#include "pcap_tree.h"
#include "pcap_oid.h"

#define SNAP_LEN 48
#define DEFAULT_FILTER "ip or ip6"

/* our module handle */
static struct lmodule *module;

/* OIDs */
static const struct asn_oid oid_pcap = OIDX_pcap;

/* the Object Resource registration index */
static u_int reg_index = 0;

struct monitor {
	uint32_t		index;
	TAILQ_ENTRY(monitor)	link;

	char			*descr;
	char                    *device;
	pcap_t                  *handle;
	void                    *watch;
	char			*filter;
	struct bpf_program      filter_bpf;
	int                     filter_valid;

	/* Stats gathered */
	uint64_t		seen_octets;
	uint64_t		seen_packets;
};

TAILQ_HEAD(monitor_list, monitor);

/* list of monitor structures */
static struct monitor_list monitors = TAILQ_HEAD_INITIALIZER (monitors);

/* Number of monitors */
static int monitor_count = 0;

/* -----------------------------------------------------------------------------
 * HELPERS
 */

static void
emsg(const char *format, ...)
{
	va_list va;
	va_start (va, format);
	vsyslog (LOG_ERR, format, va);
	va_end (va);
}

/* -----------------------------------------------------------------------------
 * MONITORING
 */

#pragma pack(1)

/* Ethernet header */
struct ethhdr {
	#define ETHER_ADDR_LEN	6
	u_char dhost[ETHER_ADDR_LEN]; /* Destination host address */
	u_char shost[ETHER_ADDR_LEN]; /* Source host address */
	u_short type; /* IP? ARP? RARP? etc */
};

/* IP4 header */
struct ip4hdr {
	uint8_t vhl;		/* version << 4 | header length >> 2 */
	uint8_t tos;		/* type of service */
	uint16_t len;		/* total length */
	uint16_t id;		/* identification */
	uint16_t off;		/* fragment offset field */
	#define IP_RF 0x8000		/* reserved fragment flag */
	#define IP_DF 0x4000		/* dont fragment flag */
	#define IP_MF 0x2000		/* more fragments flag */
	#define IP_OFFMASK 0x1fff	/* mask for fragmenting bits */
	uint8_t ttl;		/* time to live */
	uint8_t proto;		/* protocol */
	uint16_t sum;		/* checksum */
	struct in_addr src, dst; /* source and dest address */
};

/* IP6 header */
struct ip6hdr {
	int32_t flow;
	int16_t payload;
	int8_t next;
	int8_t hops;
	struct in6_addr src, dst;
};

#pragma pack()

static void
monitor_packet (u_char *data, const struct pcap_pkthdr *hdr, const u_char *bytes)
{
	struct monitor *mon = (struct monitor*)data;
	int octets;

	/* Short packet, don't care */
	if (hdr->len < sizeof (struct ethhdr))
		return;

	octets = hdr->len - sizeof (struct ethhdr);
	mon->seen_octets += octets;
	mon->seen_packets += 1;
}

static void
monitor_io (int fd, void *data)
{
	struct monitor* mon = (struct monitor*)data;
	const char *error;
	int n_packets;

	n_packets = pcap_dispatch (mon->handle, -1, monitor_packet, (u_char*)mon);
	if (n_packets < 0) {
		error = pcap_geterr (mon->handle);
		emsg ("couldn't capture packets in monitor: %s", error ? error : "");
	}
}

static void
monitor_free (struct monitor *mon)
{
	ASSERT (mon);

	if (mon->descr)
		free (mon->descr);
	if (mon->device)
		free (mon->device);
	if (mon->watch)
		fd_deselect (mon->watch);
	if (mon->handle)
		pcap_close (mon->handle);
	if (mon->filter_valid)
		pcap_freecode (&mon->filter_bpf);
	if (mon->filter)
		free (mon->filter);

	TAILQ_REMOVE (&monitors, mon, link);
	monitor_count--;
	free (mon);
}

static struct monitor*
monitor_alloc (int index)
{
	char errbuf[PCAP_ERRBUF_SIZE];
	struct monitor* mon;

	mon = calloc (1, sizeof (struct monitor));
	if (!mon) {
		emsg ("couldn't allocate monitor: out of memory");
		return NULL;
	}

	mon->index = index;
	INSERT_OBJECT_INT (mon, &monitors);
	monitor_count++;

	mon->device = pcap_lookupdev (errbuf);
	if (!mon->device) {
		mon->device = strdup ("any");
		if (!mon->device) {
			monitor_free (mon);
			return NULL;
		}
	}

	mon->filter = strdup (DEFAULT_FILTER);
	if (!mon->filter) {
		monitor_free (mon);
		return NULL;
	}

	mon->descr = strdup ("");
	if (!mon->descr) {
		monitor_free (mon);
		return NULL;
	}

	return mon;
}

static void
monitor_start (struct monitor *mon)
{
	char errbuf[PCAP_ERRBUF_SIZE];
	const char *error;
	int fd;

	ASSERT (mon->device);
	ASSERT (mon->filter);

	mon->handle = pcap_open_live (mon->device, SNAP_LEN, 1, 100, errbuf);
	if (!mon->handle) {
		emsg ("couldn't open monitor on %s: %s", mon->device, errbuf);
		return;
	}

	if (pcap_compile (mon->handle, &mon->filter_bpf, mon->filter, 1, 0) < 0) {
		error = pcap_geterr (mon->handle);
		emsg ("couldn't compile monitor expression: %s", error ? error : "");
		return;
	}

	mon->filter_valid = 1;
	if (pcap_setfilter (mon->handle, &mon->filter_bpf) < 0) {
		error = pcap_geterr (mon->handle);
		emsg ("couldn't setup monitor expression: %s", error ? error : "");
		return;
	}

	if (pcap_setnonblock (mon->handle, 1, errbuf) < 0) {
		emsg ("couldn't set monitor in non-block mode: %s", errbuf);
		return;
	}

	fd = pcap_get_selectable_fd (mon->handle);
	if (fd < 0) {
		error = pcap_geterr (mon->handle);
		emsg ("couldn't get selectable monitor: %s", error ? error : "");
		return;
	}

	mon->watch = fd_select (fd, monitor_io, mon, module);
	if (!mon->watch) {
		emsg ("couldn't listen to monitor: %s", strerror (errno));
		return;
	}
}

/* -----------------------------------------------------------------------------
 * CALLBACKS/CONFIG
 */

static int
op_config (struct monitor *mon, struct snmp_context *ctx,
           struct snmp_value *value,  u_int sub, u_int iidx, enum snmp_op op)
{
	asn_subid_t which = value->var.subs[sub - 1];
	int index, r;

	/* Just return values, no creation */
	if (op == SNMP_OP_GET || op == SNMP_OP_GETNEXT) {

		if (!mon)
			return SNMP_ERR_NOSUCHNAME;

		switch (which) {
		case LEAF_pcapIndex:
			value->v.integer = mon->index;
			return SNMP_ERR_NOERROR;
		case LEAF_pcapDescr:
			return string_get (value, (const u_char*)(mon->descr), -1);
		case LEAF_pcapDevice:
			return string_get (value, (const u_char*)(mon->device), -1);
		case LEAF_pcapFilter:
			return string_get (value, (const u_char*)(mon->filter), -1);
		default:
			ASSERT (0);
			return SNMP_ERR_NOSUCHNAME;
		}
	}

	/* Remainder only at initialization */
	if (community != COMM_INITIALIZE)
		return mon ? SNMP_ERR_NOT_WRITEABLE : SNMP_ERR_NO_CREATION;

	/* No writing to pcapIndex */
	if (which == LEAF_pcapIndex)
		return SNMP_ERR_NOT_WRITEABLE;

	if (index_decode (&value->var, sub, iidx, &index))
		return SNMP_ERR_NO_CREATION;

	/* Create it if necessary */
	if (!mon) {
		mon = monitor_alloc (index);
		if (!mon) {
			emsg ("out of memory");
			return SNMP_ERR_GENERR;
		}
	}

	switch (which) {

	/* pcapDescr */
	case LEAF_pcapDescr:
		switch (op) {
		case SNMP_OP_SET:
			return string_save (value, ctx, -1, (u_char**)(&mon->descr));
		case SNMP_OP_ROLLBACK:
			return SNMP_ERR_NOERROR;
		case SNMP_OP_COMMIT:
			return SNMP_ERR_NOERROR;
		default:
			ASSERT (0);
			return SNMP_ERR_GENERR;
		}
		break;

	/* pcapDevice */
	case LEAF_pcapDevice:
		switch (op) {
		case SNMP_OP_SET:
			return string_save (value, ctx, -1, (u_char**)(&mon->device));
		case SNMP_OP_ROLLBACK:
			return SNMP_ERR_NOERROR;
		case SNMP_OP_COMMIT:
			return SNMP_ERR_NOERROR;
		default:
			ASSERT (0);
			return SNMP_ERR_GENERR;
		}
		break;

	/* pcapFilter */
	case LEAF_pcapFilter:
		switch (op) {
		case SNMP_OP_SET:
			r = string_save (value, ctx, -1, (u_char**)(&mon->filter));
			return r;
		case SNMP_OP_ROLLBACK:
			return SNMP_ERR_NOERROR;
		case SNMP_OP_COMMIT:
			return SNMP_ERR_NOERROR;
		default:
			ASSERT (0);
			return SNMP_ERR_GENERR;
		}
		break;

	/* Unknown OID */
	default:
		ASSERT (0);
		return SNMP_ERR_NOSUCHNAME;
	}
}

int
op_pcapentry (struct snmp_context *ctx, struct snmp_value *value,
              u_int sub, u_int iidx, enum snmp_op op)
{
	asn_subid_t which = value->var.subs[sub - 1];
	struct monitor *mon = NULL;

	switch (op) {
	case SNMP_OP_GETNEXT:
		mon = NEXT_OBJECT_INT (&monitors, &value->var, sub);
		if (mon == NULL)
			return SNMP_ERR_NOSUCHNAME;
		value->var.len = sub + 1;
		value->var.subs[sub] = mon->index;
		break;

	case SNMP_OP_GET:
		mon = FIND_OBJECT_INT (&monitors, &value->var, sub);
		if (mon == NULL)
			return SNMP_ERR_NOSUCHNAME;
		break;

	default:
		mon = FIND_OBJECT_INT (&monitors, &value->var, sub);
		break;
	};

	/* Send configuration stuff off elsewhere */
	switch (which) {
	case LEAF_pcapIndex:
	case LEAF_pcapDescr:
	case LEAF_pcapDevice:
	case LEAF_pcapFilter:
		return op_config (mon, ctx, value, sub, iidx, op);
	}

	if (op != SNMP_OP_GET && op != SNMP_OP_GETNEXT)
		return SNMP_ERR_NOT_WRITEABLE;

	switch (which) {
	case LEAF_pcapOctets:
		value->v.counter64 = mon->seen_octets;
		return SNMP_ERR_NOERROR;
	case LEAF_pcapPackets:
		value->v.counter64 = mon->seen_packets;
		return SNMP_ERR_NOERROR;
	default:
		ASSERT (0);
		return SNMP_ERR_NOSUCHNAME;
	};
}

int
op_pcap (struct snmp_context *ctx, struct snmp_value *value,
         u_int sub, u_int iidx, enum snmp_op op)
{
	asn_subid_t which = value->var.subs[sub - 1];

	switch (op) {
	case SNMP_OP_GET:
		break;

	case SNMP_OP_SET:
		return SNMP_ERR_NOT_WRITEABLE;

	case SNMP_OP_ROLLBACK:
	case SNMP_OP_COMMIT:
		return SNMP_ERR_NOERROR;

	default:
		ASSERT(0);
		break;
    	};

	switch (which) {
	case LEAF_pcapCount:
		value->v.integer = monitor_count;
		break;

	default:
		ASSERT(0);
		break;
	};

	return SNMP_ERR_NOERROR;
}


/* -----------------------------------------------------------------------------
 * MODULE
 */

/* Called, when the module is to be unloaded after it was successfully loaded */
static int
module_fini (void)
{
	struct monitor *mon;

	if (reg_index)
		or_unregister (reg_index);

	while ((mon = TAILQ_FIRST(&monitors)) != NULL)
		monitor_free (mon);

	return 0;
}

/* the initialisation function */
static int
module_init (struct lmodule *mod, int argc, char *argv[])
{
	module = mod;

	if (argc != 0) {
		syslog (LOG_ERR, "bad number of arguments for %s", __func__);
		return EINVAL;
	}

	return 0;
}

/* Module is started */
static void
module_start (void)
{
	struct monitor *mon;

	reg_index = or_register (&oid_pcap, "The MIB for pcap data.", module);

	/* Start each monitor */
	TAILQ_FOREACH (mon, &monitors, link) {
		monitor_start (mon);
	}
}

const struct snmp_module config = {
	.comment =      "This module implements SNMP pcap monitoring of traffic",
	.init =         module_init,
	.start =        module_start,
	.fini =         module_fini,
	.tree =         pcap_ctree,
	.tree_size =    pcap_CTREE_SIZE,
};