forked from majek/p0f
-
Notifications
You must be signed in to change notification settings - Fork 0
/
p0f.c
1235 lines (744 loc) · 27.8 KB
/
p0f.c
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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
p0f - main entry point and all the pcap / unix socket innards
-------------------------------------------------------------
Copyright (C) 2012 by Michal Zalewski <[email protected]>
Distributed under the terms and conditions of GNU LGPL.
*/
#define _GNU_SOURCE
#define _FROM_P0F
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <getopt.h>
#include <errno.h>
#include <dirent.h>
#include <pwd.h>
#include <grp.h>
#include <poll.h>
#include <time.h>
#include <locale.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/un.h>
#include <sys/fcntl.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <pcap.h>
#ifdef NET_BPF
# include <net/bpf.h>
#else
# include <pcap-bpf.h>
#endif /* !NET_BPF */
#include "types.h"
#include "debug.h"
#include "alloc-inl.h"
#include "process.h"
#include "readfp.h"
#include "api.h"
#include "tcp.h"
#include "fp_http.h"
#include "p0f.h"
#ifndef PF_INET6
# define PF_INET6 10
#endif /* !PF_INET6 */
#ifndef O_NOFOLLOW
# define O_NOFOLLOW 0
#endif /* !O_NOFOLLOW */
#ifndef O_LARGEFILE
# define O_LARGEFILE 0
#endif /* !O_LARGEFILE */
static u8 *use_iface, /* Interface to listen on */
*orig_rule, /* Original filter rule */
*switch_user, /* Target username */
*log_file, /* Binary log file name */
*api_sock, /* API socket file name */
*fp_file, /* Location of p0f.fp */
*read_file; /* File to read pcap data from */
static u32
api_max_conn = API_MAX_CONN; /* Maximum number of API connections */
u32
max_conn = MAX_CONN, /* Connection entry count limit */
max_hosts = MAX_HOSTS, /* Host cache entry count limit */
conn_max_age = CONN_MAX_AGE, /* Maximum age of a connection entry */
host_idle_limit = HOST_IDLE_LIMIT; /* Host cache idle timeout */
static struct api_client *api_cl; /* Array with API client state */
static s32 null_fd = -1, /* File descriptor of /dev/null */
api_fd = -1; /* API socket descriptor */
static FILE* lf; /* Log file stream */
static u8 stop_soon; /* Ctrl-C or so pressed? */
u8 daemon_mode; /* Running in daemon mode? */
static u8 set_promisc; /* Use promiscuous mode? */
static pcap_t *pt; /* PCAP capture thingy */
s32 link_type; /* PCAP link type */
u32 hash_seed; /* Hash seed */
static u8 obs_fields; /* No of pending observation fields */
/* Memory allocator data: */
#ifdef DEBUG_BUILD
struct TRK_obj* TRK[ALLOC_BUCKETS];
u32 TRK_cnt[ALLOC_BUCKETS];
#endif /* DEBUG_BUILD */
#define LOGF(_x...) fprintf(lf, _x)
/* Display usage information */
static void usage(void) {
ERRORF(
"Usage: p0f [ ...options... ] [ 'filter rule' ]\n"
"\n"
"Network interface options:\n"
"\n"
" -i iface - listen on the specified network interface\n"
" -r file - read offline pcap data from a given file\n"
" -p - put the listening interface in promiscuous mode\n"
" -L - list all available interfaces\n"
"\n"
"Operating mode and output settings:\n"
"\n"
" -f file - read fingerprint database from 'file' (%s)\n"
" -o file - write information to the specified log file\n"
#ifndef __CYGWIN__
" -s name - answer to API queries at a named unix socket\n"
#endif /* !__CYGWIN__ */
" -u user - switch to the specified unprivileged account and chroot\n"
" -d - fork into background (requires -o or -s)\n"
"\n"
"Performance-related options:\n"
"\n"
#ifndef __CYGWIN__
" -S limit - limit number of parallel API connections (%u)\n"
#endif /* !__CYGWIN__ */
" -t c,h - set connection / host cache age limits (%us,%um)\n"
" -m c,h - cap the number of active connections / hosts (%u,%u)\n"
"\n"
"Optional filter expressions (man tcpdump) can be specified in the command\n"
"line to prevent p0f from looking at incidental network traffic.\n"
"\n"
"Problems? You can reach the author at <[email protected]>.\n",
FP_FILE,
#ifndef __CYGWIN__
API_MAX_CONN,
#endif /* !__CYGWIN__ */
CONN_MAX_AGE, HOST_IDLE_LIMIT, MAX_CONN, MAX_HOSTS);
exit(1);
}
/* Obtain hash seed: */
static void get_hash_seed(void) {
s32 f = open("/dev/urandom", O_RDONLY);
if (f < 0) PFATAL("Cannot open /dev/urandom for reading.");
#ifndef DEBUG_BUILD
/* In debug versions, use a constant seed. */
if (read(f, &hash_seed, sizeof(hash_seed)) != sizeof(hash_seed))
FATAL("Cannot read data from /dev/urandom.");
#endif /* !DEBUG_BUILD */
close(f);
}
/* Get rid of unnecessary file descriptors */
static void close_spare_fds(void) {
s32 i, closed = 0;
DIR* d;
struct dirent* de;
d = opendir("/proc/self/fd");
if (!d) {
/* Best we could do... */
for (i = 3; i < 256; i++)
if (!close(i)) closed++;
return;
}
while ((de = readdir(d))) {
i = atol(de->d_name);
if (i > 2 && !close(i)) closed++;
}
closedir(d);
if (closed)
SAYF("[+] Closed %u file descriptor%s.\n", closed, closed == 1 ? "" : "s" );
}
/* Create or open log file */
static void open_log(void) {
struct stat st;
s32 log_fd;
log_fd = open((char*)log_file, O_WRONLY | O_APPEND | O_NOFOLLOW | O_LARGEFILE);
if (log_fd >= 0) {
if (fstat(log_fd, &st)) PFATAL("fstat() on '%s' failed.", log_file);
if (!S_ISREG(st.st_mode)) FATAL("'%s' is not a regular file.", log_file);
} else {
if (errno != ENOENT) PFATAL("Cannot open '%s'.", log_file);
log_fd = open((char*)log_file, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW,
LOG_MODE);
if (log_fd < 0) PFATAL("Cannot open '%s'.", log_file);
}
if (flock(log_fd, LOCK_EX | LOCK_NB))
FATAL("'%s' is being used by another process.", log_file);
lf = fdopen(log_fd, "a");
if (!lf) FATAL("fdopen() on '%s' failed.", log_file);
SAYF("[+] Log file '%s' opened for writing.\n", log_file);
}
/* Create and start listening on API socket */
static void open_api(void) {
s32 old_umask;
u32 i;
struct sockaddr_un u;
struct stat st;
api_fd = socket(PF_UNIX, SOCK_STREAM, 0);
if (api_fd < 0) PFATAL("socket(PF_UNIX) failed.");
memset(&u, 0, sizeof(u));
u.sun_family = AF_UNIX;
if (strlen((char*)api_sock) >= sizeof(u.sun_path))
FATAL("API socket filename is too long for sockaddr_un (blame Unix).");
strcpy(u.sun_path, (char*)api_sock);
/* This is bad, but you can't do any better with standard unix socket
semantics today :-( */
if (!stat((char*)api_sock, &st) && !S_ISSOCK(st.st_mode))
FATAL("'%s' exists but is not a socket.", api_sock);
if (unlink((char*)api_sock) && errno != ENOENT)
PFATAL("unlink('%s') failed.", api_sock);
old_umask = umask(0777 ^ API_MODE);
if (bind(api_fd, (struct sockaddr*)&u, sizeof(u)))
PFATAL("bind() on '%s' failed.", api_sock);
umask(old_umask);
if (listen(api_fd, api_max_conn))
PFATAL("listen() on '%s' failed.", api_sock);
if (fcntl(api_fd, F_SETFL, O_NONBLOCK))
PFATAL("fcntl() to set O_NONBLOCK on API listen socket fails.");
api_cl = DFL_ck_alloc(api_max_conn * sizeof(struct api_client));
for (i = 0; i < api_max_conn; i++) api_cl[i].fd = -1;
SAYF("[+] Listening on API socket '%s' (max %u clients).\n",
api_sock, api_max_conn);
}
/* Open log entry. */
void start_observation(char* keyword, u8 field_cnt, u8 to_srv,
struct packet_flow* f) {
if (obs_fields) FATAL("Premature end of observation.");
if (!daemon_mode) {
SAYF(".-[ %s/%u -> ", addr_to_str(f->client->addr, f->client->ip_ver),
f->cli_port);
SAYF("%s/%u (%s) ]-\n|\n", addr_to_str(f->server->addr, f->client->ip_ver),
f->srv_port, keyword);
SAYF("| %-8s = %s/%u\n", to_srv ? "client" : "server",
addr_to_str(to_srv ? f->client->addr :
f->server->addr, f->client->ip_ver),
to_srv ? f->cli_port : f->srv_port);
}
if (log_file) {
u8 tmp[64];
time_t ut = get_unix_time();
struct tm* lt = localtime(&ut);
strftime((char*)tmp, 64, "%Y/%m/%d %H:%M:%S", lt);
LOGF("[%s] mod=%s|cli=%s/%u|",tmp, keyword, addr_to_str(f->client->addr,
f->client->ip_ver), f->cli_port);
LOGF("srv=%s/%u|subj=%s", addr_to_str(f->server->addr, f->server->ip_ver),
f->srv_port, to_srv ? "cli" : "srv");
}
obs_fields = field_cnt;
}
/* Add log item. */
void add_observation_field(char* key, u8* value) {
if (!obs_fields) FATAL("Unexpected observation field ('%s').", key);
if (!daemon_mode)
SAYF("| %-8s = %s\n", key, value ? value : (u8*)"???");
if (log_file) LOGF("|%s=%s", key, value ? value : (u8*)"???");
obs_fields--;
if (!obs_fields) {
if (!daemon_mode) SAYF("|\n`----\n\n");
if (log_file) LOGF("\n");
}
}
/* Show PCAP interface list */
static void list_interfaces(void) {
char pcap_err[PCAP_ERRBUF_SIZE];
pcap_if_t *dev;
u8 i = 0;
/* There is a bug in several years' worth of libpcap releases that causes it
to SEGV here if /sys/class/net is not readable. See http://goo.gl/nEnGx */
if (access("/sys/class/net", R_OK | X_OK) && errno != ENOENT)
FATAL("This operation requires access to /sys/class/net/, sorry.");
if (pcap_findalldevs(&dev, pcap_err) == -1)
FATAL("pcap_findalldevs: %s\n", pcap_err);
if (!dev) FATAL("Can't find any interfaces. Maybe you need to be root?");
SAYF("\n-- Available interfaces --\n");
do {
pcap_addr_t *a = dev->addresses;
SAYF("\n%3d: Name : %s\n", i++, dev->name);
SAYF(" Description : %s\n", dev->description ? dev->description : "-");
/* Let's try to find something we can actually display. */
while (a && a->addr->sa_family != PF_INET && a->addr->sa_family != PF_INET6)
a = a->next;
if (a) {
if (a->addr->sa_family == PF_INET)
SAYF(" IP address : %s\n", addr_to_str(((u8*)a->addr) + 4, IP_VER4));
else
SAYF(" IP address : %s\n", addr_to_str(((u8*)a->addr) + 8, IP_VER6));
} else SAYF(" IP address : (none)\n");
} while ((dev = dev->next));
SAYF("\n");
pcap_freealldevs(dev);
}
#ifdef __CYGWIN__
/* List PCAP-recognized interfaces */
static u8* find_interface(int num) {
char pcap_err[PCAP_ERRBUF_SIZE];
pcap_if_t *dev;
if (pcap_findalldevs(&dev, pcap_err) == -1)
FATAL("pcap_findalldevs: %s\n", pcap_err);
do {
if (!num--) {
u8* ret = DFL_ck_strdup((char*)dev->name);
pcap_freealldevs(dev);
return ret;
}
} while ((dev = dev->next));
FATAL("Interface not found (use -L to list all).");
}
#endif /* __CYGWIN__ */
/* Initialize PCAP capture */
static void prepare_pcap(void) {
char pcap_err[PCAP_ERRBUF_SIZE];
u8* orig_iface = use_iface;
if (read_file) {
if (set_promisc)
FATAL("Dude, how am I supposed to make a file promiscuous?");
if (use_iface)
FATAL("Options -i and -r are mutually exclusive.");
if (access((char*)read_file, R_OK))
PFATAL("Can't access file '%s'.", read_file);
pt = pcap_open_offline((char*)read_file, pcap_err);
if (!pt) FATAL("pcap_open_offline: %s", pcap_err);
SAYF("[+] Will read pcap data from file '%s'.\n", read_file);
} else {
if (!use_iface) {
/* See the earlier note on libpcap SEGV - same problem here.
Also, this retusns something stupid on Windows, but hey... */
if (!access("/sys/class/net", R_OK | X_OK) || errno == ENOENT)
use_iface = (u8*)pcap_lookupdev(pcap_err);
if (!use_iface)
FATAL("libpcap is out of ideas; use -i to specify interface.");
}
#ifdef __CYGWIN__
/* On Windows, interface names are unwieldy, and people prefer to use
numerical IDs. */
else {
int iface_id;
if (sscanf((char*)use_iface, "%u", &iface_id) == 1) {
use_iface = find_interface(iface_id);
}
}
pt = pcap_open_live((char*)use_iface, SNAPLEN, set_promisc, 250, pcap_err);
#else
/* PCAP timeouts tend to be broken, so we'll use a minimum value
and rely on select() instead. */
pt = pcap_open_live((char*)use_iface, SNAPLEN, set_promisc, 1, pcap_err);
#endif /* ^__CYGWIN__ */
if (!orig_iface)
SAYF("[+] Intercepting traffic on default interface '%s'.\n", use_iface);
else
SAYF("[+] Intercepting traffic on interface '%s'.\n", use_iface);
if (!pt) FATAL("pcap_open_live: %s", pcap_err);
}
link_type = pcap_datalink(pt);
}
/* Initialize BPF filtering */
static void prepare_bpf(void) {
struct bpf_program flt;
u8* final_rule;
u8 vlan_support;
/* VLAN matching is somewhat brain-dead: you need to request it explicitly,
and it alters the semantics of the remainder of the expression. */
vlan_support = (pcap_datalink(pt) == DLT_EN10MB);
retry_no_vlan:
if (!orig_rule) {
if (vlan_support) {
final_rule = (u8*)"tcp or (vlan and tcp)";
} else {
final_rule = (u8*)"tcp";
}
} else {
if (vlan_support) {
final_rule = ck_alloc(strlen((char*)orig_rule) * 2 + 64);
sprintf((char*)final_rule, "(tcp and (%s)) or (vlan and tcp and (%s))",
orig_rule, orig_rule);
} else {
final_rule = ck_alloc(strlen((char*)orig_rule) + 16);
sprintf((char*)final_rule, "tcp and (%s)", orig_rule);
}
}
DEBUG("[#] Computed rule: %s\n", final_rule);
if (pcap_compile(pt, &flt, (char*)final_rule, 1, 0)) {
if (vlan_support) {
if (orig_rule) ck_free(final_rule);
vlan_support = 0;
goto retry_no_vlan;
}
pcap_perror(pt, "[-] pcap_compile");
if (!orig_rule)
FATAL("pcap_compile() didn't work, strange");
else
FATAL("Syntax error! See 'man tcpdump' for help on filters.");
}
if (pcap_setfilter(pt, &flt))
FATAL("pcap_setfilter() didn't work, strange.");
pcap_freecode(&flt);
if (!orig_rule) {
SAYF("[+] Default packet filtering configured%s.\n",
vlan_support ? " [+VLAN]" : "");
} else {
SAYF("[+] Custom filtering rule enabled: %s%s\n",
orig_rule ? orig_rule : (u8*)"tcp",
vlan_support ? " [+VLAN]" : "");
ck_free(final_rule);
}
}
/* Drop privileges and chroot(), with some sanity checks */
static void drop_privs(void) {
struct passwd* pw;
pw = getpwnam((char*)switch_user);
if (!pw) FATAL("User '%s' not found.", switch_user);
if (!strcmp(pw->pw_dir, "/"))
FATAL("User '%s' must have a dedicated home directory.", switch_user);
if (!pw->pw_uid || !pw->pw_gid)
FATAL("User '%s' must be non-root.", switch_user);
if (initgroups(pw->pw_name, pw->pw_gid))
PFATAL("initgroups() for '%s' failed.", switch_user);
if (chdir(pw->pw_dir))
PFATAL("chdir('%s') failed.", pw->pw_dir);
if (chroot(pw->pw_dir))
PFATAL("chroot('%s') failed.", pw->pw_dir);
if (chdir("/"))
PFATAL("chdir('/') after chroot('%s') failed.", pw->pw_dir);
if (!access("/proc/", F_OK) || !access("/sys/", F_OK))
FATAL("User '%s' must have a dedicated home directory.", switch_user);
if (setgid(pw->pw_gid))
PFATAL("setgid(%u) failed.", pw->pw_gid);
if (setuid(pw->pw_uid))
PFATAL("setuid(%u) failed.", pw->pw_uid);
if (getegid() != pw->pw_gid || geteuid() != pw->pw_uid)
FATAL("Inconsistent euid / egid after dropping privs.");
SAYF("[+] Privileges dropped: uid %u, gid %u, root '%s'.\n",
pw->pw_uid, pw->pw_gid, pw->pw_dir);
}
/* Enter daemon mode. */
static void fork_off(void) {
s32 npid;
fflush(0);
npid = fork();
if (npid < 0) PFATAL("fork() failed.");
if (!npid) {
/* Let's assume all this is fairly unlikely to fail, so we can live
with the parent possibly proclaiming success prematurely. */
if (dup2(null_fd, 0) < 0) PFATAL("dup2() failed.");
/* If stderr is redirected to a file, keep that fd and use it for
normal output. */
if (isatty(2)) {
if (dup2(null_fd, 1) < 0 || dup2(null_fd, 2) < 0)
PFATAL("dup2() failed.");
} else {
if (dup2(2, 1) < 0) PFATAL("dup2() failed.");
}
close(null_fd);
null_fd = -1;
if (chdir("/")) PFATAL("chdir('/') failed.");
setsid();
} else {
SAYF("[+] Daemon process created, PID %u (stderr %s).\n", npid,
isatty(2) ? "not kept" : "kept as-is");
SAYF("\nGood luck, you're on your own now!\n");
exit(0);
}
}
/* Handler for Ctrl-C and related signals */
static void abort_handler(int sig) {
if (stop_soon) exit(1);
stop_soon = 1;
}
#ifndef __CYGWIN__
/* Regenerate pollfd data for poll() */
static u32 regen_pfds(struct pollfd* pfds, struct api_client** ctable) {
u32 i, count = 2;
pfds[0].fd = pcap_fileno(pt);
pfds[0].events = (POLLIN | POLLERR | POLLHUP);
DEBUG("[#] Recomputing pollfd data, pcap_fd = %d.\n", pfds[0].fd);
if (!api_sock) return 1;
pfds[1].fd = api_fd;
pfds[1].events = (POLLIN | POLLERR | POLLHUP);
for (i = 0; i < api_max_conn; i++) {
if (api_cl[i].fd == -1) continue;
ctable[count] = api_cl + i;
/* If we haven't received a complete query yet, wait for POLLIN.
Otherwise, we want to write stuff. */
if (api_cl[i].in_off < sizeof(struct p0f_api_query))
pfds[count].events = (POLLIN | POLLERR | POLLHUP);
else
pfds[count].events = (POLLOUT | POLLERR | POLLHUP);
pfds[count++].fd = api_cl[i].fd;
}
return count;
}
#endif /* !__CYGWIN__ */
/* Event loop! Accepts and dispatches pcap data, API queries, etc. */
static void live_event_loop(void) {
#ifndef __CYGWIN__
/* The huge problem with winpcap on cygwin is that you can't get a file
descriptor suitable for poll() / select() out of it:
http://www.winpcap.org/pipermail/winpcap-users/2009-April/003179.html
The only alternatives seem to be additional processes / threads, a
nasty busy loop, or a ton of Windows-specific code. If you need APi
queries on Windows, you are welcome to fix this :-) */
struct pollfd *pfds;
struct api_client** ctable;
u32 pfd_count;
/* We need room for pcap, and possibly api_fd + api_clients. */
pfds = ck_alloc((1 + (api_sock ? (1 + api_max_conn) : 0)) *
sizeof(struct pollfd));
ctable = ck_alloc((1 + (api_sock ? (1 + api_max_conn) : 0)) *
sizeof(struct api_client*));
pfd_count = regen_pfds(pfds, ctable);
if (!daemon_mode)
SAYF("[+] Entered main event loop.\n\n");
while (!stop_soon) {
s32 pret, i;
u32 cur;
/* We use a 250 ms timeout to keep Ctrl-C responsive without resortng to
silly sigaction hackery or unsafe signal handler code. */
poll_again:
pret = poll(pfds, pfd_count, 250);
if (pret < 0) {
if (errno == EINTR) break;
PFATAL("poll() failed.");
}
if (!pret) { if (log_file) fflush(lf); continue; }
/* Examine pfds... */
for (cur = 0; cur < pfd_count; cur++) {
if (pfds[cur].revents & POLLOUT) switch (cur) {
case 0: case 1:
FATAL("Unexpected POLLOUT on fd %d.\n", cur);
default:
/* Write API response, restart state when complete. */
if (ctable[cur]->in_off < sizeof(struct p0f_api_query))
FATAL("Inconsistent p0f_api_response state.\n");
i = write(pfds[cur].fd,
((char*)&ctable[cur]->out_data) + ctable[cur]->out_off,
sizeof(struct p0f_api_response) - ctable[cur]->out_off);
if (i <= 0) PFATAL("write() on API socket fails despite POLLOUT.");
ctable[cur]->out_off += i;
/* All done? Back to square zero then! */
if (ctable[cur]->out_off == sizeof(struct p0f_api_response)) {
ctable[cur]->in_off = ctable[cur]->out_off = 0;
pfds[cur].events = (POLLIN | POLLERR | POLLHUP);
}
}
if (pfds[cur].revents & POLLIN) switch (cur) {
case 0:
/* Process traffic on the capture interface. */
if (pcap_dispatch(pt, -1, (pcap_handler)parse_packet, 0) < 0)
FATAL("Packet capture interface is down.");
break;
case 1:
/* Accept new API connection, limits permitting. */
if (!api_sock) FATAL("Unexpected API connection.");
if (pfd_count - 2 < api_max_conn) {
for (i = 0; i < api_max_conn && api_cl[i].fd >= 0; i++);
if (i == api_max_conn) FATAL("Inconsistent API connection data.");
api_cl[i].fd = accept(api_fd, NULL, NULL);
if (api_cl[i].fd < 0) {
WARN("Unable to handle API connection: accept() fails.");
} else {
if (fcntl(api_cl[i].fd, F_SETFL, O_NONBLOCK))
PFATAL("fcntl() to set O_NONBLOCK on API connection fails.");
api_cl[i].in_off = api_cl[i].out_off = 0;
pfd_count = regen_pfds(pfds, ctable);
DEBUG("[#] Accepted new API connection, fd %d.\n", api_cl[i].fd);
goto poll_again;
}
} else WARN("Too many API connections (use -S to adjust).\n");
break;
default:
/* Receive API query, dispatch when complete. */
if (ctable[cur]->in_off >= sizeof(struct p0f_api_query))
FATAL("Inconsistent p0f_api_query state.\n");
i = read(pfds[cur].fd,
((char*)&ctable[cur]->in_data) + ctable[cur]->in_off,
sizeof(struct p0f_api_query) - ctable[cur]->in_off);
if (i < 0) PFATAL("read() on API socket fails despite POLLIN.");
ctable[cur]->in_off += i;
/* Query in place? Compute response and prepare to send it back. */
if (ctable[cur]->in_off == sizeof(struct p0f_api_query)) {
handle_query(&ctable[cur]->in_data, &ctable[cur]->out_data);
pfds[cur].events = (POLLOUT | POLLERR | POLLHUP);
}
}
if (pfds[cur].revents & (POLLERR | POLLHUP)) switch (cur) {
case 0:
FATAL("Packet capture interface is down.");
case 1:
FATAL("API socket is down.");
default:
/* Shut down API connection and free its state. */
DEBUG("[#] API connection on fd %d closed.\n", pfds[cur].fd);
close(pfds[cur].fd);
ctable[cur]->fd = -1;
pfd_count = regen_pfds(pfds, ctable);
goto poll_again;
}
/* Processed all reported updates already? If so, bail out early. */
if (pfds[cur].revents && !--pret) break;
}
}
ck_free(ctable);
ck_free(pfds);
#else
if (!daemon_mode)
SAYF("[+] Entered main event loop.\n\n");
/* Ugh. The only way to keep SIGINT and other signals working is to have this
funny loop with dummy I/O every 250 ms. Signal handlers don't get called
in pcap_dispatch() or pcap_loop() unless there's I/O. */
while (!stop_soon) {
s32 ret = pcap_dispatch(pt, -1, (pcap_handler)parse_packet, 0);
if (ret < 0) return;
if (log_file && !ret) fflush(lf);
write(2, NULL, 0);
}
#endif /* ^!__CYGWIN__ */
WARN("User-initiated shutdown.");
}
/* Simple event loop for processing offline captures. */
static void offline_event_loop(void) {
if (!daemon_mode)
SAYF("[+] Processing capture data.\n\n");