]> git.proxmox.com Git - pve-firewall.git/blame - src/pvefw-logger.c
logger: basic ipv6 support
[pve-firewall.git] / src / pvefw-logger.c
CommitLineData
ba0b3a0a
DM
1/*
2
3 Copyright (C) 2014 Proxmox Server Solutions GmbH
4
5 This software is written by Proxmox Server Solutions GmbH <support@proxmox.com>
6
7 This program is free software: you can redistribute it and/or modify
8 it under the terms of the GNU Affero General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU Affero General Public License for more details.
16
17 You should have received a copy of the GNU Affero General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20 Author: Dietmar Maurer <dietmar@proxmox.com>
21
22*/
23
24#define _GNU_SOURCE
25
26#include <stdlib.h>
27#include <stdio.h>
28#include <errno.h>
29#include <stdarg.h>
30#include <string.h>
31#include <signal.h>
985fd74e 32#include <sys/signalfd.h>
7bb6e8dd 33#include <sys/types.h>
ba0b3a0a
DM
34#include <sys/stat.h>
35#include <fcntl.h>
36#include <unistd.h>
37#include <arpa/inet.h>
38#include <sys/socket.h>
39#include <sys/file.h>
40#include <linux/netlink.h>
41#include <libnfnetlink/libnfnetlink.h>
42#include <libnetfilter_log/libnetfilter_log.h>
43#include <netinet/ip.h>
44#include <netinet/ip_icmp.h>
d1b290fc
WB
45#include <netinet/ip6.h>
46#include <netinet/icmp6.h>
ba0b3a0a
DM
47#include <netinet/udp.h>
48#include <netinet/tcp.h>
49#include <netinet/if_ether.h>
9da3465c 50#include <syslog.h>
ba0b3a0a
DM
51
52#include <glib.h>
ba0b3a0a
DM
53
54static struct nflog_handle *logh = NULL;
55static struct nlif_handle *nlifh = NULL;
7bb6e8dd 56GMainLoop *main_loop;
ba0b3a0a 57
84786ec0
DM
58gboolean foreground = FALSE;
59gboolean debug = FALSE;
60
782c4cde 61/*
7bb6e8dd 62
782c4cde
DM
63LOG FORMAT:
64
65Special care was taken to allow fast parsing (and filer messages for a singl VM).
66
7bb6e8dd 67<VMID> <LOGLEVEL> <CHAIN> <TIME> <TIMEZONE> <MSG>
782c4cde
DM
68
69Example:
70
71117 6 tap117i0-IN 14/Mar/2014:12:47:07 +0100 policy REJECT: IN=vmbr1 ...
7bb6e8dd 72
782c4cde
DM
73*/
74
ba0b3a0a
DM
75#define LOGFILE "/var/log/pve-firewall.log"
76
77#define LOCKFILE "/var/lock/pvefw-logger.lck"
78#define PIDFILE "/var/run/pvefw-logger.pid"
79
80#define LQ_LEN 512
5b06fd6c 81#define LE_MAX (512 - 4) // try to fit into 512 bytes
ba0b3a0a 82
782c4cde
DM
83#define MAX_CHAIN_LEN 28
84
7bb6e8dd 85struct log_entry {
ba0b3a0a
DM
86 guint32 len; // max LE_MAX chars
87 char buf[LE_MAX];
88};
89
5b06fd6c
DM
90#define STATIC_ASSERT(cond) \
91 extern void pve_static_assert(int test[(cond) ? 1 : -1])
92
93STATIC_ASSERT(sizeof(struct log_entry) == 512);
94
ba0b3a0a
DM
95int outfd = -1;
96
97gboolean terminate_threads = FALSE;
98
99static gboolean write_pidfile(pid_t pid)
100{
101 gboolean res;
102
103 char *strpid = g_strdup_printf("%d\n", pid);
104 res = g_file_set_contents(PIDFILE, strpid, strlen(strpid), NULL);
105 g_free(strpid);
106
107 return res;
108}
109
110static GAsyncQueue *queue;
111
7bb6e8dd 112ssize_t
ba0b3a0a
DM
113safe_write(int fd, char *buf, size_t count)
114{
115 ssize_t n;
116
117 do {
118 n = write(fd, buf, count);
119 } while (n < 0 && errno == EINTR);
120
121 return n;
122}
123
124static gpointer
7bb6e8dd 125log_writer_thread(gpointer data)
ba0b3a0a
DM
126{
127 while (1) {
128 struct log_entry *le = (struct log_entry *)g_async_queue_timeout_pop(queue, 250000);
129 if (le == NULL) {
130 if (terminate_threads) {
131 return NULL;
132 }
133 continue;
134 }
7bb6e8dd 135
84786ec0
DM
136 if (debug) fputs(le->buf, stdout);
137
ba0b3a0a 138 int res = safe_write(outfd, le->buf, le->len);
7bb6e8dd 139
ba0b3a0a
DM
140 g_free(le);
141
142 if (res < 0) {
9da3465c 143 syslog(3, "writing log failed, stopping daemon - %s", strerror (errno));
7bb6e8dd 144 g_main_loop_quit(main_loop);
9da3465c 145 return NULL;
ba0b3a0a
DM
146 }
147 }
148
149 return NULL;
150}
151
152static int skipped_logs = 0;
153
782c4cde 154static void log_status_message(guint loglevel, const char *fmt, ...);
7bb6e8dd 155
ba0b3a0a
DM
156static void
157queue_log_entry(struct log_entry *le)
158{
159 gint len = g_async_queue_length(queue);
160
161 if (skipped_logs > 0) {
162 if (len >= (LQ_LEN - 1)) {
163 skipped_logs++;
164 } else {
7bb6e8dd 165 int skip_tmp = skipped_logs;
ba0b3a0a 166 skipped_logs = 0; // clear before calling log_status_message()
782c4cde 167 log_status_message(3, "skipped %d log entries (queue full)", skip_tmp);
ba0b3a0a
DM
168 g_async_queue_push(queue, le);
169 }
170 } else {
171 if (len >= LQ_LEN) {
172 skipped_logs++;
173 } else {
174 g_async_queue_push(queue, le);
175 }
176 }
177}
178
179
6c293b5d
WB
180#define LEPRINTF(format, ...) \
181 do { \
182 if (le->len < LE_MAX) \
183 le->len += snprintf(le->buf + le->len, LE_MAX - le->len, format, ##__VA_ARGS__); \
184 } while (0)
185#define LEPRINTTIME(sec) \
186 do { \
187 time_t tmp_sec = sec; \
188 if (le->len < (LE_MAX - 30)) \
189 le->len += strftime(le->buf + le->len, LE_MAX - le->len, "%d/%b/%Y:%H:%M:%S %z ", localtime(&tmp_sec)); \
190 } while (0)
ba0b3a0a 191
7bb6e8dd
DM
192static void
193log_status_message(guint loglevel, const char *fmt, ...)
ba0b3a0a
DM
194{
195 va_list ap;
196 va_start(ap, fmt);
7bb6e8dd 197
782c4cde
DM
198 if (loglevel > 7 ) loglevel = 7; // syslog defines level 0-7
199
ba0b3a0a
DM
200 struct log_entry *le = g_new0(struct log_entry, 1);
201
782c4cde
DM
202 LEPRINTF("0 %d - ", loglevel);
203
ba0b3a0a
DM
204 LEPRINTTIME(time(NULL));
205
206 le->len += vsnprintf(le->buf + le->len, LE_MAX - le->len, fmt, ap);
207
208 LEPRINTF("\n");
209
210 queue_log_entry(le);
9da3465c
DM
211
212 // also log to syslog
213
214 vsyslog(loglevel, fmt, ap);
ba0b3a0a
DM
215}
216
7bb6e8dd 217static int
ba0b3a0a
DM
218print_tcp(struct log_entry *le, struct tcphdr *h, int payload_len)
219{
220 LEPRINTF("PROTO=TCP ");
221
222 if (payload_len < sizeof(struct tcphdr)) {
223 LEPRINTF("LEN=%d ", payload_len);
224 LEPRINTF("INVALID=LEN ");
225 return -1;
226 }
227
228 LEPRINTF("SPT=%u DPT=%u ", ntohs(h->source), ntohs(h->dest));
229 LEPRINTF("SEQ=%u ACK=%u ", ntohl(h->seq), ntohl(h->ack_seq));
230 LEPRINTF("WINDOW=%u ", ntohs(h->window));
231
232 if (h->urg) LEPRINTF("URG ");
233 if (h->ack) LEPRINTF("ACK ");
234 if (h->psh) LEPRINTF("PSH ");
235 if (h->rst) LEPRINTF("RST ");
236 if (h->syn) LEPRINTF("SYN ");
237 if (h->fin) LEPRINTF("FIN ");
238
239 if (h->urg) LEPRINTF("URGP=%u ",ntohs(h->urg_ptr));
240
241 return 0;
242}
243
7bb6e8dd 244static int
ba0b3a0a
DM
245print_udp(struct log_entry *le, struct udphdr *h, int payload_len)
246{
247 LEPRINTF("PROTO=UDP ");
248
249 if (payload_len < sizeof(struct udphdr)) {
250 LEPRINTF("LEN=%d ", payload_len);
251 LEPRINTF("INVALID=LEN ");
252 return -1;
253 }
254
255 LEPRINTF("SPT=%u DPT=%u LEN=%u", ntohs(h->source), ntohs(h->dest), ntohs(h->len));
256
257 return 0;
258}
259
7bb6e8dd 260static int
ba0b3a0a
DM
261print_icmp(struct log_entry *le, struct icmphdr *h, int payload_len)
262{
263 char tmp[INET_ADDRSTRLEN];
264 u_int32_t gateway;
265
266 LEPRINTF("PROTO=ICMP ");
267
268 if (payload_len < sizeof(struct icmphdr)) {
269 LEPRINTF("LEN=%d ", payload_len);
270 LEPRINTF("INVALID=LEN ");
271 return -1;
272 }
273
274 LEPRINTF("TYPE=%u CODE=%u ", h->type, h->code);
275
276 switch (h->type) {
277 case ICMP_ECHO:
278 case ICMP_ECHOREPLY:
279 LEPRINTF("ID=%u SEQ=%u ", ntohs(h->un.echo.id), ntohs(h->un.echo.sequence));
280 break;
281 case ICMP_PARAMETERPROB:
282 LEPRINTF("PARAMETER=%u ", ntohl(h->un.gateway) >> 24);
283 break;
284 case ICMP_REDIRECT:
285 gateway = ntohl(h->un.gateway);
7bb6e8dd 286 inet_ntop(AF_INET, &gateway, tmp, sizeof(tmp));
ba0b3a0a
DM
287 LEPRINTF("GATEWAY=%s ", tmp);
288 break;
289 case ICMP_DEST_UNREACH:
290 if (h->code == ICMP_FRAG_NEEDED) {
291 LEPRINTF("MTU=%u ", ntohs(h->un.frag.mtu));
292 }
293 break;
294 }
295
296 return 0;
297}
298
299/* Section 3.1. SCTP Common Header Format */
300typedef struct sctphdr {
301 __be16 source;
302 __be16 dest;
303 __be32 vtag;
304 __be32 checksum;
305} __attribute__((packed)) sctp_sctphdr_t;
306
7bb6e8dd 307static int
ba0b3a0a
DM
308print_sctp(struct log_entry *le, struct sctphdr *h, int payload_len)
309{
310 LEPRINTF("PROTO=SCTP ");
311
312 if (payload_len < sizeof(struct sctphdr)) {
313 LEPRINTF("LEN=%d ", payload_len);
314 LEPRINTF("INVALID=LEN ");
315 return -1;
316 }
317
318 LEPRINTF("SPT=%u DPT=%u ", ntohs(h->source), ntohs(h->dest));
319
320 return 0;
321}
322
f5b3bf34
WB
323static int
324print_ipproto(struct log_entry *le, char * nexthdr, int payload_len, u_int8_t proto)
325{
326 switch (proto) {
327 case IPPROTO_TCP:
328 print_tcp(le, (struct tcphdr *)nexthdr, payload_len);
329 break;
330 case IPPROTO_UDP:
331 print_udp(le, (struct udphdr *)nexthdr, payload_len);
332 break;
333 case IPPROTO_ICMP:
334 print_icmp(le, (struct icmphdr *)nexthdr, payload_len);
335 break;
336 case IPPROTO_SCTP:
337 print_sctp(le, (struct sctphdr *)nexthdr, payload_len);
338 break;
339 case IPPROTO_AH:
340 LEPRINTF("PROTO=AH ");
341 break;
342 case IPPROTO_ESP:
343 LEPRINTF("PROTO=ESP ");
344 break;
345 case IPPROTO_IGMP:
346 LEPRINTF("PROTO=IGMP ");
347 break;
348 default:
349 return -1;
350 }
351 return 0;
352}
353
7bb6e8dd 354static int
ba0b3a0a
DM
355print_iphdr(struct log_entry *le, char * payload, int payload_len)
356{
357 if (payload_len < sizeof(struct iphdr)) {
358 LEPRINTF("LEN=%d ", payload_len);
359 LEPRINTF("INVALID=LEN ");
360 return -1;
361 }
362
363 struct iphdr *h = (struct iphdr *)payload;
7bb6e8dd 364
ba0b3a0a
DM
365 if (payload_len <= (u_int32_t)(h->ihl * 4)) {
366 LEPRINTF("INVALID=IHL ");
367 return -1;
368 }
369
370 char tmp[INET_ADDRSTRLEN];
7bb6e8dd
DM
371
372 inet_ntop(AF_INET, &h->saddr, tmp, sizeof(tmp));
ba0b3a0a 373 LEPRINTF("SRC=%s ", tmp);
7bb6e8dd 374 inet_ntop(AF_INET, &h->daddr, tmp, sizeof(tmp));
ba0b3a0a
DM
375 LEPRINTF("DST=%s ", tmp);
376
377 LEPRINTF("LEN=%u TOS=0x%02X PREC=0x%02X TTL=%u ID=%u ",
378 ntohs(h->tot_len), h->tos & IPTOS_TOS_MASK,
379 h->tos & IPTOS_PREC_MASK, h->ttl, ntohs(h->id));
7bb6e8dd 380
ba0b3a0a 381 short ip_off = ntohs(h->frag_off);
7bb6e8dd 382 if (ip_off & IP_OFFMASK)
ba0b3a0a
DM
383 LEPRINTF("FRAG=%u ", ip_off & IP_OFFMASK);
384
385 if (ip_off & IP_DF) LEPRINTF("DF ");
386 if (ip_off & IP_MF) LEPRINTF("MF ");
387
388 void *nexthdr = (u_int32_t *)h + h->ihl;
389 payload_len -= h->ihl * 4;
390
f5b3bf34 391 if (print_ipproto(le, nexthdr, payload_len, h->protocol) < 0) {
ba0b3a0a
DM
392 LEPRINTF("PROTO=%u ", h->protocol);
393 }
394
395 return 0;
396}
397
7bb6e8dd 398static int
d1b290fc 399print_routing(struct log_entry *le, struct ip6_rthdr *rthdr, int payload_len)
ba0b3a0a 400{
d1b290fc
WB
401 char tmp[INET6_ADDRSTRLEN];
402 LEPRINTF("TYPE=%u SEGMENTS=%u", rthdr->ip6r_type, rthdr->ip6r_segleft);
403
404 if (payload_len < sizeof(*rthdr) || payload_len < rthdr->ip6r_len*8) {
405 LEPRINTF("LEN=%d ", payload_len);
406 LEPRINTF("INVALID=LEN ");
407 return -1;
408 }
409
410 if (rthdr->ip6r_type == 0) {
411 /* Route via waypoints (deprecated), this contains a list of waypoints
412 * to visit. (RFC2460 (4.4))
413 */
414 unsigned i;
415 struct ip6_rthdr0 *h = (struct ip6_rthdr0*)rthdr;
416 if (rthdr->ip6r_len*8 < sizeof(*h) + rthdr->ip6r_segleft * sizeof(struct in6_addr)) {
417 LEPRINTF("INVALID=SEGMENTS ");
418 return 0;
419 }
420 return 0;
421 } else if (rthdr->ip6r_type == 1) {
422 /* nimrod routing (RFC1992) */
423 return 0;
424 } else if (rthdr->ip6r_type == 2) {
425 /* RFC3375 (6.4), the layout is like type-0 but with exactly 1 address */
426 struct ip6_rthdr0 *h = (struct ip6_rthdr0*)rthdr;
427 if (rthdr->ip6r_len*8 < sizeof(*h) + sizeof(struct in6_addr)) {
428 LEPRINTF("LEN=%d ", payload_len);
429 LEPRINTF("INVALID=LEN ");
430 return -1;
431 }
432 inet_ntop(AF_INET6, &h->ip6r0_addr[0], tmp, sizeof(tmp));
433 LEPRINTF("HOME=%s ", tmp);
434 return 0;
435 }
ba0b3a0a
DM
436
437 return 0;
438}
439
d1b290fc
WB
440static int
441print_fragment(struct log_entry *le, struct ip6_frag *frag, int payload_len)
442{
443 u_int16_t offlg;
444
445 if (payload_len < sizeof(*frag)) {
446 LEPRINTF("LEN=%d ", payload_len);
447 LEPRINTF("INVALID=LEN ");
448 return -1;
449 }
450
451 offlg = ntohs(frag->ip6f_offlg);
452 LEPRINTF("FRAG=%d ID=%d ", (offlg&0x2FFF), ntohl(frag->ip6f_ident));
453 if (offlg>>15) {
454 LEPRINTF("MF ");
455 }
456 return 0;
457}
458
459static int
460print_icmp6(struct log_entry *le, struct icmp6_hdr *h, int payload_len)
461{
462 struct nd_router_advert *ra;
463 struct nd_neighbor_advert *na;
464 struct nd_redirect *re;
465 char tmp[INET6_ADDRSTRLEN];
466
467 if (payload_len < sizeof(struct icmp6_hdr)) {
468 LEPRINTF("LEN=%d ", payload_len);
469 LEPRINTF("INVALID=LEN ");
470 return -1;
471 }
472
473 LEPRINTF("TYPE=%u CODE=%u ", h->icmp6_type, h->icmp6_code);
474
475 switch (h->icmp6_type) {
476 case ICMP6_ECHO_REQUEST:
477 case ICMP6_ECHO_REPLY:
478 LEPRINTF("ID=%u SEQ=%u ", ntohs(h->icmp6_id), ntohs(h->icmp6_seq));
479 break;
480
481 case ND_ROUTER_SOLICIT:
482 /* can be followed by options, otherwise nothing to print */
483 break;
484
485 case ND_ROUTER_ADVERT:
486 ra = (struct nd_router_advert*)h;
487 LEPRINTF("HOPLIMIT=%d ", ra->nd_ra_curhoplimit);
488 /* nd_ra_flags_reserved is only 8 bit, so no swapping here as
489 * opposed to the neighbor advertisement flags (see below).
490 */
491 LEPRINTF("RA=%02x LIFETIME=%d REACHABLE=%d RETRANSMIT=%d ",
492 ra->nd_ra_flags_reserved,
493 ntohs(ra->nd_ra_router_lifetime),
494 ntohl(ra->nd_ra_reachable),
495 ntohl(ra->nd_ra_retransmit));
496 /* can be followed by options */
497 break;
498
499 case ND_NEIGHBOR_SOLICIT:
500 /* can be followed by options */
501 break;
502
503 case ND_NEIGHBOR_ADVERT:
504 na = (struct nd_neighbor_advert*)h;
505 LEPRINTF("NA=%08x ", ntohl(na->nd_na_flags_reserved));
506 /* can be followed by options */
507 break;
508
509 case ND_REDIRECT:
510 re = (struct nd_redirect*)h;
511 inet_ntop(AF_INET6, &re->nd_rd_target, tmp, sizeof(tmp));
512 LEPRINTF("TARGET=%s ", tmp);
513 inet_ntop(AF_INET6, &re->nd_rd_dst, tmp, sizeof(tmp));
514 LEPRINTF("GATEWAY=%s ", tmp);
515 /* can be followed by options */
516 break;
517
518 case ICMP6_DST_UNREACH:
519 /* CODE shows the type, no extra parameters available in ipv6 */
520 break;
521
522 case ICMP6_PACKET_TOO_BIG:
523 LEPRINTF("MTU=%u ", ntohl(h->icmp6_mtu));
524 break;
525
526 case ICMP6_TIME_EXCEEDED:
527 /* CODE shows the type (0 = hop limit, 1 = reassembly timed out) */
528 break;
529
530 case ICMP6_PARAM_PROB:
531 switch (ntohl(h->icmp6_pptr)) {
532 case ICMP6_PARAMPROB_HEADER:
533 LEPRINTF("PARAMETER=HEADER "); /* erroneous header */
534 break;
535 case ICMP6_PARAMPROB_NEXTHEADER:
536 LEPRINTF("PARAMETER=NEXTHEADER "); /* bad next-header field */
537 break;
538 case ICMP6_PARAMPROB_OPTION:
539 LEPRINTF("PARAMETER=OPTION "); /* bad ipv6 option (hop/dst header?) */
540 break;
541 default:
542 LEPRINTF("PARAMETER=%u ", ntohl(h->icmp6_pptr)); /* unknown */
543 break;
544 }
545 break;
546 }
547
548 return 0;
549}
550
551static int
552check_ip6ext(struct log_entry *le, struct ip6_ext *exthdr, int payload_len)
553{
554 if (payload_len < sizeof(*exthdr) ||
555 payload_len < exthdr->ip6e_len)
556 {
557 LEPRINTF("LEN=%d ", payload_len);
558 LEPRINTF("INVALID=LEN ");
559 return -1;
560 }
561 return 0;
562}
563
564static int
565print_nexthdr(struct log_entry *le, char *hdr, int payload_len, u_int8_t proto)
566{
567 while (1) {
568 if (print_ipproto(le, hdr, payload_len, proto) == 0)
569 return 0;
570
571 struct ip6_ext *exthdr = (struct ip6_ext*)hdr;
572
573 switch (proto) {
574 /* protocols (these return) */
575 case IPPROTO_ICMPV6:
576 LEPRINTF("PROTO=ICMPV6 ");
577 if (check_ip6ext(le, exthdr, payload_len) < 0)
578 return -1;
579 if (print_icmp6(le, (struct icmp6_hdr*)(hdr + exthdr->ip6e_len),
580 payload_len - exthdr->ip6e_len) < 0)
581 {
582 return -1;
583 }
584 return 0;
585
586 /* extension headers (these break to keep iterating) */
587 case IPPROTO_ROUTING:
588 if (check_ip6ext(le, exthdr, payload_len) < 0)
589 return -1;
590 if (print_routing(le, (struct ip6_rthdr*)hdr, payload_len) < 0)
591 return -1;
592 break;
593 case IPPROTO_FRAGMENT:
594 if (check_ip6ext(le, exthdr, payload_len) < 0)
595 return -1;
596 if (print_fragment(le, (struct ip6_frag*)hdr, payload_len) < 0)
597 return -1;
598 break;
599 case IPPROTO_HOPOPTS:
600 LEPRINTF("NEXTHDR=HOPOPTS ");
601 if (check_ip6ext(le, exthdr, payload_len) < 0)
602 return -1;
603 /* do we want to print these? */
604 break;
605 case IPPROTO_DSTOPTS:
606 LEPRINTF("NEXTHDR=DSTOPTS ");
607 if (check_ip6ext(le, exthdr, payload_len) < 0)
608 return -1;
609 /* do we want to print these? */
610 break;
611 case IPPROTO_MH:
612 LEPRINTF("NEXTHDR=MH ");
613 if (check_ip6ext(le, exthdr, payload_len) < 0)
614 return -1;
615 break;
616
617 /* unknown protocol */
618 default:
619 LEPRINTF("PROTO=%u ", proto);
620 return 0; /* bail */
621 }
622 /* next header: */
623 if (check_ip6ext(le, exthdr, payload_len) < 0)
624 return -1;
625 hdr += exthdr->ip6e_len;
626 payload_len -= exthdr->ip6e_len;
627 }
628}
629
630static int
631print_ip6hdr(struct log_entry *le, char * payload, int payload_len)
632{
633 if (payload_len < sizeof(struct ip6_hdr)) {
634 LEPRINTF("LEN=%d ", payload_len);
635 LEPRINTF("INVALID=LEN ");
636 return -1;
637 }
638
639 struct ip6_hdr *h = (struct ip6_hdr*)payload;
640
641 char tmp[INET6_ADDRSTRLEN];
642 inet_ntop(AF_INET6, &h->ip6_src, tmp, sizeof(tmp));
643 LEPRINTF("SRC=%s ", tmp);
644 inet_ntop(AF_INET6, &h->ip6_dst, tmp, sizeof(tmp));
645 LEPRINTF("DST=%s ", tmp);
646
647 LEPRINTF("LEN=%u ", ntohs(h->ip6_plen));
648
649 u_int32_t flow = ntohl(h->ip6_flow);
650 LEPRINTF("TC=%d FLOWLBL=%d ", (flow>>20)&0xFF, flow&0xFFFFF);
651
652 LEPRINTF("HOPLIMIT=%d ", h->ip6_hlim);
653
654 return print_nexthdr(le, (char *)(h+1), payload_len - sizeof(*h), h->ip6_nxt);
655}
656
ba0b3a0a 657// ebtables -I FORWARD --nflog --nflog-group 0
7bb6e8dd 658static int
ba0b3a0a
DM
659print_arp(struct log_entry *le, struct ether_arp *h, int payload_len)
660{
661 if (payload_len < sizeof(struct ether_arp)) {
662 LEPRINTF("LEN=%d ", payload_len);
663 LEPRINTF("INVALID=LEN ");
664 return -1;
665 }
666
667 LEPRINTF("SRC=%u.%u.%u.%u ", h->arp_spa[0], h->arp_spa[1],
668 h->arp_spa[2], h->arp_spa[3]);
669
670 LEPRINTF("DST=%u.%u.%u.%u ", h->arp_tpa[0], h->arp_tpa[1],
671 h->arp_tpa[2], h->arp_tpa[3]);
672
673 LEPRINTF("PROTO=ARP ");
674
675 unsigned short code = ntohs(h->arp_op);
676 switch (code) {
677 case ARPOP_REQUEST:
678 LEPRINTF("REQUEST ");
679 break;
680 case ARPOP_REPLY:
7bb6e8dd
DM
681 LEPRINTF("REPLY MAC=%02x:%02x:%02x:%02x:%02x:%02x ",
682 h->arp_sha[0], h->arp_sha[1], h->arp_sha[2],
ba0b3a0a
DM
683 h->arp_sha[3], h->arp_sha[4], h->arp_sha[5]);
684 break;
685 case ARPOP_NAK:
686 LEPRINTF("NAK ");
687 break;
688 default:
689 LEPRINTF("CODE=%u ", code);
690 }
691
692
693 // LEPRINTF("HTYPE=%u ", ntohs(h->arp_hrd));
694
695 // LEPRINTF("PTYPE=%u ", ntohs(h->arp_pro));
696
697 return 0;
698}
699
700
701static int print_pkt(struct log_entry *le, struct nflog_data *ldata, u_int8_t family)
702{
703 u_int32_t mark = nflog_get_nfmark(ldata);
704 u_int32_t indev = nflog_get_indev(ldata);
705 u_int32_t outdev = nflog_get_outdev(ldata);
706 u_int32_t physindev = nflog_get_physindev(ldata);
707 u_int32_t physoutdev = nflog_get_physoutdev(ldata);
708
709 char *prefix = nflog_get_prefix(ldata);
710 char *payload;
711 char devname[256];
7bb6e8dd 712
782c4cde
DM
713 guint32 vmid = 0;
714
715 guint8 log_level = 6; // info
716
717 char *chain_name = "-";
718
719 if (prefix != NULL) {
720 // Note: parse ":$vmid:$loglevel:$chain: $msg"
721 if (prefix[0] == ':') {
722 char *p = prefix + 1;
723 guint32 tmpid = 0;
724 while(*p >= '0' && *p <= '9') { tmpid *= 10; tmpid += *p - '0'; p++; }
725
726 if ((*p == ':') &&
727 (p[1] >= '0' && p[1] <= '7') &&
728 (p[2] == ':')) {
729
730 guint8 tmp_level = p[1] - '0'; // store for later use
731 char *chain_start = p + 3; // store for later use
732 p = chain_start;
733 while (*p && *p != ':' && *p != ' ') p++;
734 int len = p - chain_start;
735
736 if (*p == ':' && p[1] == ' ' && len && (len <= MAX_CHAIN_LEN)) {
737 // parsing successful
738
739 *p = 0; // terminate string
740
741 vmid = tmpid;
742 log_level = tmp_level;
743 chain_name = chain_start;
744 prefix = p + 2; // the rest
7bb6e8dd 745 }
782c4cde
DM
746 }
747 }
748 }
749
750 LEPRINTF("%d ", vmid);
751
752 LEPRINTF("%d ", log_level);
753
754 LEPRINTF("%s ", chain_name);
755
ba0b3a0a
DM
756 struct timeval ts;
757 nflog_get_timestamp(ldata, &ts);
758
759 LEPRINTTIME(ts.tv_sec);
760
ba0b3a0a
DM
761 if (prefix != NULL) {
762 LEPRINTF("%s", prefix);
763 }
7bb6e8dd
DM
764
765 if (indev > 0) {
e7ceb650 766 if (nlif_index2name(nlifh, indev, devname) != -1) {
7bb6e8dd 767 LEPRINTF("IN=%s ", devname);
e7ceb650 768 } else {
7bb6e8dd 769 LEPRINTF("IN=%u ", indev);
e7ceb650 770 }
ba0b3a0a
DM
771 }
772
e7ceb650
DM
773 if (outdev > 0) {
774 if (nlif_index2name(nlifh, outdev, devname) != -1) {
775 LEPRINTF("OUT=%s ", devname);
776 } else {
777 LEPRINTF("OUT=%u ", outdev);
778 }
ba0b3a0a
DM
779 }
780
7bb6e8dd 781 if (physindev > 0) {
e7ceb650
DM
782 if (nlif_index2name(nlifh, physindev, devname) != -1) {
783 LEPRINTF("PHYSIN=%s ", devname);
784 } else {
785 LEPRINTF("PHYSIN=%u ", physindev);
786 }
ba0b3a0a 787 }
7bb6e8dd 788
e7ceb650
DM
789 if (physoutdev > 0) {
790 if (nlif_index2name(nlifh, physoutdev, devname) != -1) {
791 LEPRINTF("PHYSOUT=%s ", devname);
792 } else {
793 LEPRINTF("PHYSOUT=%u ", physoutdev);
794 }
ba0b3a0a
DM
795 }
796
797 int payload_len = nflog_get_payload(ldata, &payload);
798
799 int hwhdrlen = nflog_get_msg_packet_hwhdrlen(ldata);
800 if (hwhdrlen > 0) {
801 unsigned char *hwhdr = (unsigned char *)nflog_get_msg_packet_hwhdr(ldata);
802 if (hwhdr != NULL) {
803 int i;
804 LEPRINTF("MAC=");
805 for (i = 0; i < hwhdrlen; i++) {
806 LEPRINTF("%02x", hwhdr[i]);
807 if (i < (hwhdrlen -1 )) LEPRINTF(":");
808 }
809 LEPRINTF(" ");
810 }
811 }
812
813 u_int16_t hw_protocol = 0;
814 struct nfulnl_msg_packet_hdr *ph = NULL;
815
816 switch (family) {
7bb6e8dd 817 case AF_INET:
ba0b3a0a
DM
818 print_iphdr(le, payload, payload_len);
819 break;
820 case AF_INET6:
821 print_ip6hdr(le, payload, payload_len);
822 break;
823 case AF_BRIDGE:
824 ph = nflog_get_msg_packet_hdr(ldata);
825 if (ph) hw_protocol = ntohs(ph->hw_protocol);
826
827 switch (hw_protocol) {
828 case ETH_P_IP:
829 print_iphdr(le, payload, payload_len);
830 break;
831 case ETH_P_IPV6:
832 print_ip6hdr(le, payload, payload_len);
833 break;
834 case ETH_P_ARP:
835 print_arp(le, (struct ether_arp *)payload, payload_len);
836 break;
837 }
838 break;
839 }
840
841 if (mark) LEPRINTF("mark=%u ", mark);
842
843
844 return 0;
845
846}
847
7bb6e8dd 848static int
ba0b3a0a
DM
849nflog_cb(struct nflog_g_handle *gh, struct nfgenmsg *nfmsg,
850 struct nflog_data *nfa, void *data)
851{
852 struct log_entry *le = g_new0(struct log_entry, 1);
7bb6e8dd 853
ba0b3a0a
DM
854 print_pkt(le, nfa, nfmsg->nfgen_family);
855
856 LEPRINTF("\n"); // add newline
857
858 queue_log_entry(le);
859
860 return 0;
861}
862
863static gboolean
864nflog_read_cb(GIOChannel *source,
865 GIOCondition condition,
866 gpointer data)
867{
868 int rv = 0;
869 gchar buf[8192];
870
871 int fd = g_io_channel_unix_get_fd(source);
7bb6e8dd 872
ba0b3a0a
DM
873 if ((rv = recv(fd, buf, sizeof(buf), 0)) && rv >= 0) {
874 nflog_handle_packet(logh, buf, rv);
875 }
876
877 return TRUE;
878}
879
880static gboolean
881nlif_read_cb(GIOChannel *source,
882 GIOCondition condition,
883 gpointer data)
884{
9da3465c
DM
885 static int last_res = 0;
886 int res;
887
888 if ((res = nlif_catch(nlifh)) < 0) {
889 if (last_res == 0) { // only report once
890 log_status_message(3, "nlif_catch failed (res = %d)", res);
891 }
892 last_res = res;
893 } else {
894 last_res = 0;
895 }
896
7bb6e8dd 897 return TRUE;
ba0b3a0a
DM
898}
899
ba0b3a0a 900static gboolean
985fd74e
DM
901signal_read_cb(GIOChannel *source,
902 GIOCondition condition,
903 gpointer data)
ba0b3a0a 904{
985fd74e
DM
905 int rv = 0;
906 struct signalfd_siginfo si;
ba0b3a0a 907
985fd74e 908 int fd = g_io_channel_unix_get_fd(source);
ba0b3a0a 909
985fd74e
DM
910 if ((rv = read(fd, &si, sizeof(si))) && rv >= 0) {
911 terminate_threads = TRUE;
912 log_status_message(5, "received terminate request (signal)");
913 g_main_loop_quit(main_loop);
914 }
7bb6e8dd 915
ba0b3a0a
DM
916 return TRUE;
917}
7bb6e8dd 918
ba0b3a0a
DM
919int
920main(int argc, char *argv[])
921{
922 int lockfd = -1;
985fd74e
DM
923 int sigfd = -1;
924
ba0b3a0a
DM
925 gboolean wrote_pidfile = FALSE;
926
9da3465c
DM
927 openlog("pvepw-logger", LOG_CONS|LOG_PID, LOG_DAEMON);
928
84786ec0
DM
929 GOptionContext *context;
930
931 GOptionEntry entries[] = {
932 { "debug", 'd', 0, G_OPTION_ARG_NONE, &debug, "Turn on debug messages", NULL },
933 { "foreground", 'f', 0, G_OPTION_ARG_NONE, &foreground, "Do not daemonize server", NULL },
934 { NULL },
935 };
936
937 context = g_option_context_new("");
938 g_option_context_add_main_entries (context, entries, NULL);
939
940 GError *err = NULL;
941 if (!g_option_context_parse (context, &argc, &argv, &err)) {
942 fprintf(stderr, "error: %s\n", err->message);
943 fprintf(stderr, "%s", g_option_context_get_help(context, FALSE, NULL));
944 g_error_free (err);
945 exit(-1);
946 }
947
948 if (optind < argc) {
949 fprintf(stderr, "error: too many arguments\n");
950 fprintf(stderr, "%s", g_option_context_get_help(context, FALSE, NULL));
951 exit(-1);
952 }
953
954 g_option_context_free(context);
955
956 if (debug) foreground = TRUE;
957
ba0b3a0a 958 if ((lockfd = open(LOCKFILE, O_RDWR|O_CREAT|O_APPEND, 0644)) == -1) {
84786ec0 959 fprintf(stderr, "unable to create lock '%s': %s\n", LOCKFILE, strerror (errno) );
ba0b3a0a
DM
960 exit(-1);
961 }
962
963 for (int i = 10; i >= 0; i--) {
964 if (flock(lockfd, LOCK_EX|LOCK_NB) != 0) {
965 if (!i) {
84786ec0 966 fprintf(stderr, "unable to aquire lock '%s': %s\n", LOCKFILE, strerror (errno));
ba0b3a0a
DM
967 exit(-1);
968 }
969 if (i == 10)
970 fprintf(stderr, "unable to aquire lock '%s' - trying again.\n", LOCKFILE);
7bb6e8dd 971
ba0b3a0a
DM
972 sleep(1);
973 }
974 }
975
976 if ((outfd = open(LOGFILE, O_WRONLY|O_CREAT|O_APPEND, 0644)) == -1) {
84786ec0 977 fprintf(stderr, "unable to open file '%s': %s\n", LOGFILE, strerror (errno));
ba0b3a0a
DM
978 exit(-1);
979 }
980
981 if ((logh = nflog_open()) == NULL) {
982 fprintf(stderr, "unable to open nflog\n");
983 exit(-1);
984 }
985
986 if (!nflog_bind_pf(logh, AF_INET) <= 0) {
987 fprintf(stderr, "nflog_bind_pf AF_INET failed\n");
988 exit(-1);
989 }
990
991#if 0
992 if (!nflog_bind_pf(logh, AF_INET6) <= 0) {
993 fprintf(stderr, "nflog_bind_pf AF_INET6 failed\n");
994 exit(-1);
995 }
996#endif
7bb6e8dd 997
ba0b3a0a
DM
998 if (!nflog_bind_pf(logh, AF_BRIDGE) <= 0) {
999 fprintf(stderr, "nflog_bind_pf AF_BRIDGE failed\n");
1000 exit(-1);
1001 }
1002
1003 struct nflog_g_handle *qh = nflog_bind_group(logh, 0);
1004 if (!qh) {
84786ec0 1005 fprintf(stderr, "no nflog handle for group 0\n");
ba0b3a0a
DM
1006 exit(-1);
1007 }
7bb6e8dd 1008
ba0b3a0a
DM
1009 if (nflog_set_mode(qh, NFULNL_COPY_PACKET, 0xffff) < 0) {
1010 fprintf(stderr, "can't set packet copy mode\n");
1011 exit(-1);
1012 }
1013
1014 if ((nlifh = nlif_open()) == NULL) {
1015 fprintf(stderr, "unable to open netlink interface handle\n");
1016 exit(-1);
1017 }
1018
985fd74e
DM
1019 sigset_t mask;
1020 sigemptyset(&mask);
1021 sigaddset(&mask, SIGINT);
1022 sigaddset(&mask, SIGTERM);
1023
1024 sigprocmask(SIG_BLOCK, &mask, NULL);
1025
1026 if ((sigfd = signalfd(-1, &mask, SFD_NONBLOCK)) < 0) {
1027 fprintf(stderr, "unable to open signalfd: %s\n", strerror (errno));
1028 exit(-1);
1029 }
1030
ba0b3a0a
DM
1031 if (!foreground) {
1032 pid_t cpid = fork();
1033
1034 if (cpid == -1) {
1035 fprintf(stderr, "failed to daemonize program - %s\n", strerror (errno));
1036 exit(-1);
1037 } else if (cpid) {
1038 write_pidfile(cpid);
1039 _exit(0);
1040 } else {
1041 int nullfd;
1042
1043 if (chroot("/") != 0) fprintf(stderr, "chroot '/' failed - %s\n", strerror (errno));
1044
1045 if ((nullfd = open("/dev/null", O_RDWR, 0)) != -1) {
1046 dup2(nullfd, 0);
1047 dup2(nullfd, 1);
1048 dup2(nullfd, 2);
1049 if (nullfd > 2)
1050 close (nullfd);
1051 }
1052
1053 setsid();
1054 }
1055 } else {
1056 write_pidfile(getpid());
1057 }
1058
1059 wrote_pidfile = TRUE;
1060
1061 nflog_callback_register(qh, &nflog_cb, logh);
1062
1063 queue = g_async_queue_new_full(g_free);
1064
782c4cde 1065 log_status_message(5, "starting pvefw logger");
ba0b3a0a
DM
1066
1067 nlif_query(nlifh);
1068
1069 GIOChannel *nlif_ch = g_io_channel_unix_new(nlif_fd(nlifh));
1070
1071 g_io_add_watch(nlif_ch, G_IO_IN, nlif_read_cb, NULL);
1072
1073 int logfd = nflog_fd(logh);
1074 GIOChannel *nflog_ch = g_io_channel_unix_new(logfd);
1075
1076 g_io_add_watch(nflog_ch, G_IO_IN, nflog_read_cb, NULL);
1077
985fd74e 1078 GIOChannel *sig_ch = g_io_channel_unix_new(sigfd);
985fd74e 1079 if (!g_io_add_watch(sig_ch, G_IO_IN, signal_read_cb, NULL)) {
e2beb7aa 1080 exit(-1);
985fd74e
DM
1081 }
1082
ba0b3a0a 1083 GThread *wthread = g_thread_new("log_writer_thread", log_writer_thread, NULL);
7bb6e8dd 1084
ba0b3a0a 1085 main_loop = g_main_loop_new(NULL, TRUE);
7bb6e8dd 1086
ba0b3a0a
DM
1087 g_main_loop_run(main_loop);
1088
782c4cde 1089 log_status_message(5, "stopping pvefw logger");
ba0b3a0a
DM
1090
1091 g_thread_join(wthread);
1092
1093 close(outfd);
1094
1095 nflog_close(logh);
1096
1097 if (wrote_pidfile)
1098 unlink(PIDFILE);
1099
1100 exit(0);
1101}