summaryrefslogtreecommitdiffstats
path: root/qemu/roms/ipxe/src/util/hijack.c
blob: ed89592b1d64da1b63e0f534183234dc0a2ccdfa (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
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdarg.h>
#include <errno.h>
#include <fcntl.h>
#include <libgen.h>
#include <signal.h>
#include <net/if.h>
#include <net/ethernet.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <syslog.h>
#include <getopt.h>
#include <pcap.h>

#define SNAPLEN 1600

/*
 * FIXME: is there a way to detect the version of the libpcap library?
 * Version 0.9 has pcap_inject; version 0.8 doesn't, but both report
 * their version number as 2.4.
 */
#define HAVE_PCAP_INJECT 0

struct hijack {
	pcap_t *pcap;
	int fd;
	int datalink;
	int filtered;
	unsigned long rx_count;
	unsigned long tx_count;
};

struct hijack_listener {
	struct sockaddr_un sun;
	int fd;
};

struct hijack_options {
	char interface[IF_NAMESIZE];
	int daemonise;
};

static int daemonised = 0;

static int signalled = 0;

static void flag_signalled ( int signal __attribute__ (( unused )) ) {
	signalled = 1;
}

#if ! HAVE_PCAP_INJECT
/**
 * Substitute for pcap_inject(), if this version of libpcap doesn't
 * have it.  Will almost certainly only work under Linux.
 *
 */
int pcap_inject ( pcap_t *pcap, const void *data, size_t len ) {
	int fd;
	char *errbuf = pcap_geterr ( pcap );

	fd = pcap_get_selectable_fd ( pcap );
	if ( fd < 0 ) {
		snprintf ( errbuf, PCAP_ERRBUF_SIZE,
			   "could not get file descriptor" );
		return -1;
	}
	if ( write ( fd, data, len ) != len ) {
		snprintf ( errbuf, PCAP_ERRBUF_SIZE,
			   "could not write data: %s", strerror ( errno ) );
		return -1;
	}
	return len;
}
#endif /* ! HAVE_PCAP_INJECT */

/**
 * Log error message
 *
 */
static __attribute__ (( format ( printf, 2, 3 ) )) void
logmsg ( int level, const char *format, ... ) {
	va_list ap;

	va_start ( ap, format );
	if ( daemonised ) {
		vsyslog ( ( LOG_DAEMON | level ), format, ap );
	} else {
		vfprintf ( stderr, format, ap );
	}
	va_end ( ap );
}

/**
 * Open pcap device
 *
 */
static int hijack_open ( const char *interface, struct hijack *hijack ) {
	char errbuf[PCAP_ERRBUF_SIZE];

	/* Open interface via pcap */
	errbuf[0] = '\0';
	hijack->pcap = pcap_open_live ( interface, SNAPLEN, 1, 0, errbuf );
	if ( ! hijack->pcap ) {
		logmsg ( LOG_ERR, "Failed to open %s: %s\n",
			 interface, errbuf );
		goto err;
	}
	if ( errbuf[0] )
		logmsg ( LOG_WARNING, "Warning: %s\n", errbuf );

	/* Set capture interface to non-blocking mode */
	if ( pcap_setnonblock ( hijack->pcap, 1, errbuf ) < 0 ) {
		logmsg ( LOG_ERR, "Could not make %s non-blocking: %s\n",
			 interface, errbuf );
		goto err;
	}

	/* Get file descriptor for select() */
	hijack->fd = pcap_get_selectable_fd ( hijack->pcap );
	if ( hijack->fd < 0 ) {
		logmsg ( LOG_ERR, "Cannot get selectable file descriptor "
			 "for %s\n", interface );
		goto err;
	}

	/* Get link layer type */
	hijack->datalink = pcap_datalink ( hijack->pcap );

	return 0;

 err:
	if ( hijack->pcap )
		pcap_close ( hijack->pcap );
	return -1;
}

/**
 * Close pcap device
 *
 */
static void hijack_close ( struct hijack *hijack ) {
	pcap_close ( hijack->pcap );
}

/**
 * Install filter for hijacked connection
 *
 */
static int hijack_install_filter ( struct hijack *hijack,
				   char *filter ) {
	struct bpf_program program;

	/* Compile filter */
	if ( pcap_compile ( hijack->pcap, &program, filter, 1, 0 ) < 0 ) {
		logmsg ( LOG_ERR, "could not compile filter \"%s\": %s\n",
			 filter, pcap_geterr ( hijack->pcap ) );
		goto err_nofree;
	}

	/* Install filter */
	if ( pcap_setfilter ( hijack->pcap, &program ) < 0 ) {
		logmsg ( LOG_ERR, "could not install filter \"%s\": %s\n",
			 filter, pcap_geterr ( hijack->pcap ) );
		goto err;
	}
	
	logmsg ( LOG_INFO, "using filter \"%s\"\n", filter );

	pcap_freecode ( &program );
	return 0;

 err:	
	pcap_freecode ( &program );
 err_nofree:
	return -1;
}

/**
 * Set up filter for hijacked ethernet connection
 *
 */
static int hijack_filter_ethernet ( struct hijack *hijack, const char *buf,
				    size_t len ) {
	char filter[55]; /* see format string */
	struct ether_header *ether_header = ( struct ether_header * ) buf;
	unsigned char *hwaddr = ether_header->ether_shost;

	if ( len < sizeof ( *ether_header ) )
		return -1;

	snprintf ( filter, sizeof ( filter ), "broadcast or multicast or "
		   "ether host %02x:%02x:%02x:%02x:%02x:%02x", hwaddr[0],
		   hwaddr[1], hwaddr[2], hwaddr[3], hwaddr[4], hwaddr[5] );

	return hijack_install_filter ( hijack, filter );
}

/**
 * Set up filter for hijacked connection
 *
 */
static int hijack_filter ( struct hijack *hijack, const char *buf,
			   size_t len ) {
	switch ( hijack->datalink ) {
	case DLT_EN10MB:
		return hijack_filter_ethernet ( hijack, buf, len );
	default:
		logmsg ( LOG_ERR, "unsupported protocol %s: cannot filter\n",
			 ( pcap_datalink_val_to_name ( hijack->datalink ) ?
			   pcap_datalink_val_to_name ( hijack->datalink ) :
			   "UNKNOWN" ) );
		/* Return success so we don't get called again */
		return 0;
	}
}

/**
 * Forward data from hijacker
 *
 */
static ssize_t forward_from_hijacker ( struct hijack *hijack, int fd ) {
	char buf[SNAPLEN];
	ssize_t len;

	/* Read packet from hijacker */
	len = read ( fd, buf, sizeof ( buf ) );
	if ( len < 0 ) {
		logmsg ( LOG_ERR, "read from hijacker failed: %s\n",
			 strerror ( errno ) );
		return -1;
	}
	if ( len == 0 )
		return 0;

	/* Set up filter if not already in place */
	if ( ! hijack->filtered ) {
		if ( hijack_filter ( hijack, buf, len ) == 0 )
			hijack->filtered = 1;
	}

	/* Transmit packet to network */
	if ( pcap_inject ( hijack->pcap, buf, len ) != len ) {
		logmsg ( LOG_ERR, "write to hijacked port failed: %s\n",
			 pcap_geterr ( hijack->pcap ) );
		return -1;
	}

	hijack->tx_count++;
	return len;
};

/**
 * Forward data to hijacker
 *
 */
static ssize_t forward_to_hijacker ( int fd, struct hijack *hijack ) {
	struct pcap_pkthdr *pkt_header;
	const unsigned char *pkt_data;
	ssize_t len;

	/* Receive packet from network */
	if ( pcap_next_ex ( hijack->pcap, &pkt_header, &pkt_data ) < 0 ) {
		logmsg ( LOG_ERR, "read from hijacked port failed: %s\n",
			 pcap_geterr ( hijack->pcap ) );
		return -1;
	}
	if ( pkt_header->caplen != pkt_header->len ) {
		logmsg ( LOG_ERR, "read partial packet (%d of %d bytes)\n",
			 pkt_header->caplen, pkt_header->len );
		return -1;
	}
	if ( pkt_header->caplen == 0 )
		return 0;
	len = pkt_header->caplen;

	/* Write packet to hijacker */
	if ( write ( fd, pkt_data, len ) != len ) {
		logmsg ( LOG_ERR, "write to hijacker failed: %s\n",
			 strerror ( errno ) );
		return -1;
	}

	hijack->rx_count++;
	return len;
};


/**
 * Run hijacker
 *
 */
static int run_hijacker ( const char *interface, int fd ) {
	struct hijack hijack;
	fd_set fdset;
	int max_fd;
	ssize_t len;

	logmsg ( LOG_INFO, "new connection for %s\n", interface );

	/* Open connection to network */
	memset ( &hijack, 0, sizeof ( hijack ) );
	if ( hijack_open ( interface, &hijack ) < 0 )
		goto err;
	
	/* Do the forwarding */
	max_fd = ( ( fd > hijack.fd ) ? fd : hijack.fd );
	while ( 1 ) {
		/* Wait for available data */
		FD_ZERO ( &fdset );
		FD_SET ( fd, &fdset );
		FD_SET ( hijack.fd, &fdset );
		if ( select ( ( max_fd + 1 ), &fdset, NULL, NULL, 0 ) < 0 ) {
			logmsg ( LOG_ERR, "select failed: %s\n",
				 strerror ( errno ) );
			goto err;
		}
		if ( FD_ISSET ( fd, &fdset ) ) {
			len = forward_from_hijacker ( &hijack, fd );
			if ( len < 0 )
				goto err;
			if ( len == 0 )
				break;
		}
		if ( FD_ISSET ( hijack.fd, &fdset ) ) {
			len = forward_to_hijacker ( fd, &hijack );
			if ( len < 0 )
				goto err;
			if ( len == 0 )
				break;
		}
	}

	hijack_close ( &hijack );
	logmsg ( LOG_INFO, "closed connection for %s\n", interface );
	logmsg ( LOG_INFO, "received %ld packets, sent %ld packets\n",
		 hijack.rx_count, hijack.tx_count );

	return 0;

 err:
	if ( hijack.pcap )
		hijack_close ( &hijack );
	return -1;
}

/**
 * Open listener socket
 *
 */
static int open_listener ( const char *interface,
			   struct hijack_listener *listener ) {
	
	/* Create socket */
	listener->fd = socket ( PF_UNIX, SOCK_SEQPACKET, 0 );
	if ( listener->fd < 0 ) {
		logmsg ( LOG_ERR, "Could not create socket: %s\n",
			 strerror ( errno ) );
		goto err;
	}

	/* Bind to local filename */
	listener->sun.sun_family = AF_UNIX,
	snprintf ( listener->sun.sun_path, sizeof ( listener->sun.sun_path ),
		   "/var/run/hijack-%s", interface );
	if ( bind ( listener->fd, ( struct sockaddr * ) &listener->sun,
		    sizeof ( listener->sun ) ) < 0 ) {
		logmsg ( LOG_ERR, "Could not bind socket to %s: %s\n",
			 listener->sun.sun_path, strerror ( errno ) );
		goto err;
	}

	/* Set as a listening socket */
	if ( listen ( listener->fd, 0 ) < 0 ) {
		logmsg ( LOG_ERR, "Could not listen to %s: %s\n",
			 listener->sun.sun_path, strerror ( errno ) );
		goto err;
	}

	return 0;
	
 err:
	if ( listener->fd >= 0 )
		close ( listener->fd );
	return -1;
}

/**
 * Listen on listener socket
 *
 */
static int listen_for_hijackers ( struct hijack_listener *listener,
				  const char *interface ) {
	int fd;
	pid_t child;
	int rc;

	logmsg ( LOG_INFO, "Listening on %s\n", listener->sun.sun_path );

	while ( ! signalled ) {
		/* Accept new connection, interruptibly */
		siginterrupt ( SIGINT, 1 );
		siginterrupt ( SIGHUP, 1 );
		fd = accept ( listener->fd, NULL, 0 );
		siginterrupt ( SIGINT, 0 );
		siginterrupt ( SIGHUP, 0 );
		if ( fd < 0 ) {
			if ( errno == EINTR ) {
				continue;
			} else {
				logmsg ( LOG_ERR, "accept failed: %s\n",
					 strerror ( errno ) );
				goto err;
			}
		}

		/* Fork child process */
		child = fork();
		if ( child < 0 ) {
			logmsg ( LOG_ERR, "fork failed: %s\n",
				 strerror ( errno ) );
			goto err;
		}
		if ( child == 0 ) {
			/* I am the child; run the hijacker */
			rc = run_hijacker ( interface, fd );
			close ( fd );
			exit ( rc );
		}
		
		close ( fd );
	}

	logmsg ( LOG_INFO, "Stopped listening on %s\n",
		 listener->sun.sun_path );
	return 0;

 err:
	if ( fd >= 0 )
		close ( fd );
	return -1;
}

/**
 * Close listener socket
 *
 */
static void close_listener ( struct hijack_listener *listener ) {
	close ( listener->fd );
	unlink ( listener->sun.sun_path );
}

/**
 * Print usage
 *
 */
static void usage ( char **argv ) {
	logmsg ( LOG_ERR,
		 "Usage: %s [options]\n"
		 "\n"
		 "Options:\n"
		 "  -h|--help               Print this help message\n"
		 "  -i|--interface intf     Use specified network interface\n"
		 "  -n|--nodaemon           Run in foreground\n",
		 argv[0] );
}

/**
 * Parse command-line options
 *
 */
static int parse_options ( int argc, char **argv,
			   struct hijack_options *options ) {
	static struct option long_options[] = {
		{ "interface", 1, NULL, 'i' },
		{ "nodaemon", 0, NULL, 'n' },
		{ "help", 0, NULL, 'h' },
		{ },
	};
	int c;

	/* Set default options */
	memset ( options, 0, sizeof ( *options ) );
	strncpy ( options->interface, "eth0", sizeof ( options->interface ) );
	options->daemonise = 1;

	/* Parse command-line options */
	while ( 1 ) {
		int option_index = 0;
		
		c = getopt_long ( argc, argv, "i:hn", long_options,
				  &option_index );
		if ( c < 0 )
			break;

		switch ( c ) {
		case 'i':
			strncpy ( options->interface, optarg,
				  sizeof ( options->interface ) );
			break;
		case 'n':
			options->daemonise = 0;
			break;
		case 'h':
			usage( argv );
			return -1;
		case '?':
			/* Unrecognised option */
			return -1;
		default:
			logmsg ( LOG_ERR, "Unrecognised option '-%c'\n", c );
			return -1;
		}
	}

	/* Check there's nothing left over on the command line */
	if ( optind != argc ) {
		usage ( argv );
		return -1;
	}

	return 0;
}

/**
 * Daemonise
 *
 */
static int daemonise ( const char *interface ) {
	char pidfile[16 + IF_NAMESIZE + 4]; /* "/var/run/hijack-<intf>.pid" */
	char pid[16];
	int pidlen;
	int fd = -1;

	/* Daemonise */
	if ( daemon ( 0, 0 ) < 0 ) {
		logmsg ( LOG_ERR, "Could not daemonise: %s\n",
			 strerror ( errno ) );
		goto err;
	}
	daemonised = 1; /* Direct messages to syslog now */

	/* Open pid file */
	snprintf ( pidfile, sizeof ( pidfile ), "/var/run/hijack-%s.pid",
		   interface );
	fd = open ( pidfile, ( O_WRONLY | O_CREAT | O_TRUNC ),
		    ( S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH ) );
	if ( fd < 0 ) {
		logmsg ( LOG_ERR, "Could not open %s for writing: %s\n",
			 pidfile, strerror ( errno ) );
		goto err;
	}

	/* Write pid to file */
	pidlen = snprintf ( pid, sizeof ( pid ), "%d\n", getpid() );
	if ( write ( fd, pid, pidlen ) != pidlen ) {
		logmsg ( LOG_ERR, "Could not write %s: %s\n",
			 pidfile, strerror ( errno ) );
		goto err;
	}

	close ( fd );
	return 0;

 err:
	if ( fd >= 0 )
		close ( fd );
	return -1;
}

int main ( int argc, char **argv ) {
	struct hijack_options options;
	struct hijack_listener listener;
	struct sigaction sa;

	/* Parse command-line options */
	if ( parse_options ( argc, argv, &options ) < 0 )
		exit ( 1 );

	/* Set up syslog connection */
	openlog ( basename ( argv[0] ), LOG_PID, LOG_DAEMON );

	/* Set up listening socket */
	if ( open_listener ( options.interface, &listener ) < 0 )
		exit ( 1 );

	/* Daemonise on demand */
	if ( options.daemonise ) {
		if ( daemonise ( options.interface ) < 0 )
			exit ( 1 );
	}

	/* Avoid creating zombies */
	memset ( &sa, 0, sizeof ( sa ) );
	sa.sa_handler = SIG_IGN;
	sa.sa_flags = SA_RESTART | SA_NOCLDWAIT;
	if ( sigaction ( SIGCHLD, &sa, NULL ) < 0 ) {
		logmsg ( LOG_ERR, "Could not set SIGCHLD handler: %s",
			 strerror ( errno ) );
		exit ( 1 );
	}

	/* Set 'signalled' flag on SIGINT or SIGHUP */
	sa.sa_handler = flag_signalled;
	sa.sa_flags = SA_RESTART | SA_RESETHAND;
	if ( sigaction ( SIGINT, &sa, NULL ) < 0 ) {
		logmsg ( LOG_ERR, "Could not set SIGINT handler: %s",
			 strerror ( errno ) );
		exit ( 1 );
	}
	if ( sigaction ( SIGHUP, &sa, NULL ) < 0 ) {
		logmsg ( LOG_ERR, "Could not set SIGHUP handler: %s",
			 strerror ( errno ) );
		exit ( 1 );
	}

	/* Listen for hijackers */
	if ( listen_for_hijackers ( &listener, options.interface ) < 0 )
		exit ( 1 );

	close_listener ( &listener );
	
	return 0;
}