forked from freebsd/freebsd-src
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathipfw2.c
5618 lines (5012 loc) · 130 KB
/
ipfw2.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
/*-
* Copyright (c) 2002-2003 Luigi Rizzo
* Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp
* Copyright (c) 1994 Ugen J.S.Antsilevich
*
* Idea and grammar partially left from:
* Copyright (c) 1993 Daniel Boulet
*
* Redistribution and use in source forms, with and without modification,
* are permitted provided that this entire comment appears intact.
*
* Redistribution in binary form may occur without any restrictions.
* Obviously, it would be nice if you gave credit where credit is due
* but requiring it would be too onerous.
*
* This software is provided ``AS IS'' without any warranties of any kind.
*
* NEW command line interface for IP firewall facility
*
* $FreeBSD$
*/
#include <sys/types.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/sysctl.h>
#include "ipfw2.h"
#include <ctype.h>
#include <err.h>
#include <errno.h>
#include <grp.h>
#include <jail.h>
#include <netdb.h>
#include <pwd.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
#include <time.h> /* ctime */
#include <timeconv.h> /* _long_to_time */
#include <unistd.h>
#include <fcntl.h>
#include <stddef.h> /* offsetof */
#include <net/ethernet.h>
#include <net/if.h> /* only IFNAMSIZ */
#include <netinet/in.h>
#include <netinet/in_systm.h> /* only n_short, n_long */
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netinet/ip_fw.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
struct cmdline_opts co; /* global options */
struct format_opts {
int bcwidth;
int pcwidth;
int show_counters;
int show_time; /* show timestamp */
uint32_t set_mask; /* enabled sets mask */
uint32_t flags; /* request flags */
uint32_t first; /* first rule to request */
uint32_t last; /* last rule to request */
uint32_t dcnt; /* number of dynamic states */
ipfw_obj_ctlv *tstate; /* table state data */
};
int resvd_set_number = RESVD_SET;
int ipfw_socket = -1;
#define CHECK_LENGTH(v, len) do { \
if ((v) < (len)) \
errx(EX_DATAERR, "Rule too long"); \
} while (0)
/*
* Check if we have enough space in cmd buffer. Note that since
* first 8? u32 words are reserved by reserved header, full cmd
* buffer can't be used, so we need to protect from buffer overrun
* only. At the beginning, cblen is less than actual buffer size by
* size of ipfw_insn_u32 instruction + 1 u32 work. This eliminates need
* for checking small instructions fitting in given range.
* We also (ab)use the fact that ipfw_insn is always the first field
* for any custom instruction.
*/
#define CHECK_CMDLEN CHECK_LENGTH(cblen, F_LEN((ipfw_insn *)cmd))
#define GET_UINT_ARG(arg, min, max, tok, s_x) do { \
if (!av[0]) \
errx(EX_USAGE, "%s: missing argument", match_value(s_x, tok)); \
if (_substrcmp(*av, "tablearg") == 0) { \
arg = IP_FW_TARG; \
break; \
} \
\
{ \
long _xval; \
char *end; \
\
_xval = strtol(*av, &end, 10); \
\
if (!isdigit(**av) || *end != '\0' || (_xval == 0 && errno == EINVAL)) \
errx(EX_DATAERR, "%s: invalid argument: %s", \
match_value(s_x, tok), *av); \
\
if (errno == ERANGE || _xval < min || _xval > max) \
errx(EX_DATAERR, "%s: argument is out of range (%u..%u): %s", \
match_value(s_x, tok), min, max, *av); \
\
if (_xval == IP_FW_TARG) \
errx(EX_DATAERR, "%s: illegal argument value: %s", \
match_value(s_x, tok), *av); \
arg = _xval; \
} \
} while (0)
static struct _s_x f_tcpflags[] = {
{ "syn", TH_SYN },
{ "fin", TH_FIN },
{ "ack", TH_ACK },
{ "psh", TH_PUSH },
{ "rst", TH_RST },
{ "urg", TH_URG },
{ "tcp flag", 0 },
{ NULL, 0 }
};
static struct _s_x f_tcpopts[] = {
{ "mss", IP_FW_TCPOPT_MSS },
{ "maxseg", IP_FW_TCPOPT_MSS },
{ "window", IP_FW_TCPOPT_WINDOW },
{ "sack", IP_FW_TCPOPT_SACK },
{ "ts", IP_FW_TCPOPT_TS },
{ "timestamp", IP_FW_TCPOPT_TS },
{ "cc", IP_FW_TCPOPT_CC },
{ "tcp option", 0 },
{ NULL, 0 }
};
/*
* IP options span the range 0 to 255 so we need to remap them
* (though in fact only the low 5 bits are significant).
*/
static struct _s_x f_ipopts[] = {
{ "ssrr", IP_FW_IPOPT_SSRR},
{ "lsrr", IP_FW_IPOPT_LSRR},
{ "rr", IP_FW_IPOPT_RR},
{ "ts", IP_FW_IPOPT_TS},
{ "ip option", 0 },
{ NULL, 0 }
};
static struct _s_x f_iptos[] = {
{ "lowdelay", IPTOS_LOWDELAY},
{ "throughput", IPTOS_THROUGHPUT},
{ "reliability", IPTOS_RELIABILITY},
{ "mincost", IPTOS_MINCOST},
{ "congestion", IPTOS_ECN_CE},
{ "ecntransport", IPTOS_ECN_ECT0},
{ "ip tos option", 0},
{ NULL, 0 }
};
struct _s_x f_ipdscp[] = {
{ "af11", IPTOS_DSCP_AF11 >> 2 }, /* 001010 */
{ "af12", IPTOS_DSCP_AF12 >> 2 }, /* 001100 */
{ "af13", IPTOS_DSCP_AF13 >> 2 }, /* 001110 */
{ "af21", IPTOS_DSCP_AF21 >> 2 }, /* 010010 */
{ "af22", IPTOS_DSCP_AF22 >> 2 }, /* 010100 */
{ "af23", IPTOS_DSCP_AF23 >> 2 }, /* 010110 */
{ "af31", IPTOS_DSCP_AF31 >> 2 }, /* 011010 */
{ "af32", IPTOS_DSCP_AF32 >> 2 }, /* 011100 */
{ "af33", IPTOS_DSCP_AF33 >> 2 }, /* 011110 */
{ "af41", IPTOS_DSCP_AF41 >> 2 }, /* 100010 */
{ "af42", IPTOS_DSCP_AF42 >> 2 }, /* 100100 */
{ "af43", IPTOS_DSCP_AF43 >> 2 }, /* 100110 */
{ "be", IPTOS_DSCP_CS0 >> 2 }, /* 000000 */
{ "ef", IPTOS_DSCP_EF >> 2 }, /* 101110 */
{ "cs0", IPTOS_DSCP_CS0 >> 2 }, /* 000000 */
{ "cs1", IPTOS_DSCP_CS1 >> 2 }, /* 001000 */
{ "cs2", IPTOS_DSCP_CS2 >> 2 }, /* 010000 */
{ "cs3", IPTOS_DSCP_CS3 >> 2 }, /* 011000 */
{ "cs4", IPTOS_DSCP_CS4 >> 2 }, /* 100000 */
{ "cs5", IPTOS_DSCP_CS5 >> 2 }, /* 101000 */
{ "cs6", IPTOS_DSCP_CS6 >> 2 }, /* 110000 */
{ "cs7", IPTOS_DSCP_CS7 >> 2 }, /* 100000 */
{ NULL, 0 }
};
static struct _s_x limit_masks[] = {
{"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
{"src-addr", DYN_SRC_ADDR},
{"src-port", DYN_SRC_PORT},
{"dst-addr", DYN_DST_ADDR},
{"dst-port", DYN_DST_PORT},
{NULL, 0}
};
/*
* we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
* This is only used in this code.
*/
#define IPPROTO_ETHERTYPE 0x1000
static struct _s_x ether_types[] = {
/*
* Note, we cannot use "-:&/" in the names because they are field
* separators in the type specifications. Also, we use s = NULL as
* end-delimiter, because a type of 0 can be legal.
*/
{ "ip", 0x0800 },
{ "ipv4", 0x0800 },
{ "ipv6", 0x86dd },
{ "arp", 0x0806 },
{ "rarp", 0x8035 },
{ "vlan", 0x8100 },
{ "loop", 0x9000 },
{ "trail", 0x1000 },
{ "at", 0x809b },
{ "atalk", 0x809b },
{ "aarp", 0x80f3 },
{ "pppoe_disc", 0x8863 },
{ "pppoe_sess", 0x8864 },
{ "ipx_8022", 0x00E0 },
{ "ipx_8023", 0x0000 },
{ "ipx_ii", 0x8137 },
{ "ipx_snap", 0x8137 },
{ "ipx", 0x8137 },
{ "ns", 0x0600 },
{ NULL, 0 }
};
static struct _s_x rule_eactions[] = {
{ "nat64clat", TOK_NAT64CLAT },
{ "nat64lsn", TOK_NAT64LSN },
{ "nat64stl", TOK_NAT64STL },
{ "nptv6", TOK_NPTV6 },
{ "tcp-setmss", TOK_TCPSETMSS },
{ NULL, 0 } /* terminator */
};
static struct _s_x rule_actions[] = {
{ "abort6", TOK_ABORT6 },
{ "abort", TOK_ABORT },
{ "accept", TOK_ACCEPT },
{ "pass", TOK_ACCEPT },
{ "allow", TOK_ACCEPT },
{ "permit", TOK_ACCEPT },
{ "count", TOK_COUNT },
{ "pipe", TOK_PIPE },
{ "queue", TOK_QUEUE },
{ "divert", TOK_DIVERT },
{ "tee", TOK_TEE },
{ "netgraph", TOK_NETGRAPH },
{ "ngtee", TOK_NGTEE },
{ "fwd", TOK_FORWARD },
{ "forward", TOK_FORWARD },
{ "skipto", TOK_SKIPTO },
{ "deny", TOK_DENY },
{ "drop", TOK_DENY },
{ "reject", TOK_REJECT },
{ "reset6", TOK_RESET6 },
{ "reset", TOK_RESET },
{ "unreach6", TOK_UNREACH6 },
{ "unreach", TOK_UNREACH },
{ "check-state", TOK_CHECKSTATE },
{ "//", TOK_COMMENT },
{ "nat", TOK_NAT },
{ "reass", TOK_REASS },
{ "setfib", TOK_SETFIB },
{ "setdscp", TOK_SETDSCP },
{ "call", TOK_CALL },
{ "return", TOK_RETURN },
{ "eaction", TOK_EACTION },
{ "tcp-setmss", TOK_TCPSETMSS },
{ NULL, 0 } /* terminator */
};
static struct _s_x rule_action_params[] = {
{ "altq", TOK_ALTQ },
{ "log", TOK_LOG },
{ "tag", TOK_TAG },
{ "untag", TOK_UNTAG },
{ NULL, 0 } /* terminator */
};
/*
* The 'lookup' instruction accepts one of the following arguments.
* -1 is a terminator for the list.
* Arguments are passed as v[1] in O_DST_LOOKUP options.
*/
static int lookup_key[] = {
TOK_DSTIP, TOK_SRCIP, TOK_DSTPORT, TOK_SRCPORT,
TOK_UID, TOK_JAIL, TOK_DSCP, -1 };
static struct _s_x rule_options[] = {
{ "tagged", TOK_TAGGED },
{ "uid", TOK_UID },
{ "gid", TOK_GID },
{ "jail", TOK_JAIL },
{ "in", TOK_IN },
{ "limit", TOK_LIMIT },
{ "set-limit", TOK_SETLIMIT },
{ "keep-state", TOK_KEEPSTATE },
{ "record-state", TOK_RECORDSTATE },
{ "bridged", TOK_LAYER2 },
{ "layer2", TOK_LAYER2 },
{ "out", TOK_OUT },
{ "diverted", TOK_DIVERTED },
{ "diverted-loopback", TOK_DIVERTEDLOOPBACK },
{ "diverted-output", TOK_DIVERTEDOUTPUT },
{ "xmit", TOK_XMIT },
{ "recv", TOK_RECV },
{ "via", TOK_VIA },
{ "fragment", TOK_FRAG },
{ "frag", TOK_FRAG },
{ "fib", TOK_FIB },
{ "ipoptions", TOK_IPOPTS },
{ "ipopts", TOK_IPOPTS },
{ "iplen", TOK_IPLEN },
{ "ipid", TOK_IPID },
{ "ipprecedence", TOK_IPPRECEDENCE },
{ "dscp", TOK_DSCP },
{ "iptos", TOK_IPTOS },
{ "ipttl", TOK_IPTTL },
{ "ipversion", TOK_IPVER },
{ "ipver", TOK_IPVER },
{ "estab", TOK_ESTAB },
{ "established", TOK_ESTAB },
{ "setup", TOK_SETUP },
{ "sockarg", TOK_SOCKARG },
{ "tcpdatalen", TOK_TCPDATALEN },
{ "tcpflags", TOK_TCPFLAGS },
{ "tcpflgs", TOK_TCPFLAGS },
{ "tcpmss", TOK_TCPMSS },
{ "tcpoptions", TOK_TCPOPTS },
{ "tcpopts", TOK_TCPOPTS },
{ "tcpseq", TOK_TCPSEQ },
{ "tcpack", TOK_TCPACK },
{ "tcpwin", TOK_TCPWIN },
{ "icmptype", TOK_ICMPTYPES },
{ "icmptypes", TOK_ICMPTYPES },
{ "dst-ip", TOK_DSTIP },
{ "src-ip", TOK_SRCIP },
{ "dst-port", TOK_DSTPORT },
{ "src-port", TOK_SRCPORT },
{ "proto", TOK_PROTO },
{ "MAC", TOK_MAC },
{ "mac", TOK_MAC },
{ "mac-type", TOK_MACTYPE },
{ "verrevpath", TOK_VERREVPATH },
{ "versrcreach", TOK_VERSRCREACH },
{ "antispoof", TOK_ANTISPOOF },
{ "ipsec", TOK_IPSEC },
{ "icmp6type", TOK_ICMP6TYPES },
{ "icmp6types", TOK_ICMP6TYPES },
{ "ext6hdr", TOK_EXT6HDR},
{ "flow-id", TOK_FLOWID},
{ "ipv6", TOK_IPV6},
{ "ip6", TOK_IPV6},
{ "ipv4", TOK_IPV4},
{ "ip4", TOK_IPV4},
{ "dst-ipv6", TOK_DSTIP6},
{ "dst-ip6", TOK_DSTIP6},
{ "src-ipv6", TOK_SRCIP6},
{ "src-ip6", TOK_SRCIP6},
{ "lookup", TOK_LOOKUP},
{ "flow", TOK_FLOW},
{ "defer-action", TOK_SKIPACTION },
{ "defer-immediate-action", TOK_SKIPACTION },
{ "//", TOK_COMMENT },
{ "not", TOK_NOT }, /* pseudo option */
{ "!", /* escape ? */ TOK_NOT }, /* pseudo option */
{ "or", TOK_OR }, /* pseudo option */
{ "|", /* escape */ TOK_OR }, /* pseudo option */
{ "{", TOK_STARTBRACE }, /* pseudo option */
{ "(", TOK_STARTBRACE }, /* pseudo option */
{ "}", TOK_ENDBRACE }, /* pseudo option */
{ ")", TOK_ENDBRACE }, /* pseudo option */
{ NULL, 0 } /* terminator */
};
void bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg);
static int ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
ipfw_cfg_lheader **pcfg, size_t *psize);
static int ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
ipfw_cfg_lheader *cfg, size_t sz, int ac, char **av);
static void ipfw_list_tifaces(void);
struct tidx;
static uint16_t pack_object(struct tidx *tstate, char *name, int otype);
static uint16_t pack_table(struct tidx *tstate, char *name);
static char *table_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx);
static void object_sort_ctlv(ipfw_obj_ctlv *ctlv);
static char *object_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx,
uint16_t type);
/*
* Simple string buffer API.
* Used to simplify buffer passing between function and for
* transparent overrun handling.
*/
/*
* Allocates new buffer of given size @sz.
*
* Returns 0 on success.
*/
int
bp_alloc(struct buf_pr *b, size_t size)
{
memset(b, 0, sizeof(struct buf_pr));
if ((b->buf = calloc(1, size)) == NULL)
return (ENOMEM);
b->ptr = b->buf;
b->size = size;
b->avail = b->size;
return (0);
}
void
bp_free(struct buf_pr *b)
{
free(b->buf);
}
/*
* Flushes buffer so new writer start from beginning.
*/
void
bp_flush(struct buf_pr *b)
{
b->ptr = b->buf;
b->avail = b->size;
b->buf[0] = '\0';
}
/*
* Print message specified by @format and args.
* Automatically manage buffer space and transparently handle
* buffer overruns.
*
* Returns number of bytes that should have been printed.
*/
int
bprintf(struct buf_pr *b, char *format, ...)
{
va_list args;
int i;
va_start(args, format);
i = vsnprintf(b->ptr, b->avail, format, args);
va_end(args);
if (i > b->avail || i < 0) {
/* Overflow or print error */
b->avail = 0;
} else {
b->ptr += i;
b->avail -= i;
}
b->needed += i;
return (i);
}
/*
* Special values printer for tablearg-aware opcodes.
*/
void
bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg)
{
if (str != NULL)
bprintf(bp, "%s", str);
if (arg == IP_FW_TARG)
bprintf(bp, "tablearg");
else
bprintf(bp, "%u", arg);
}
/*
* Helper routine to print a possibly unaligned uint64_t on
* various platform. If width > 0, print the value with
* the desired width, followed by a space;
* otherwise, return the required width.
*/
int
pr_u64(struct buf_pr *b, uint64_t *pd, int width)
{
#ifdef TCC
#define U64_FMT "I64"
#else
#define U64_FMT "llu"
#endif
uint64_t u;
unsigned long long d;
bcopy (pd, &u, sizeof(u));
d = u;
return (width > 0) ?
bprintf(b, "%*" U64_FMT " ", width, d) :
snprintf(NULL, 0, "%" U64_FMT, d) ;
#undef U64_FMT
}
void *
safe_calloc(size_t number, size_t size)
{
void *ret = calloc(number, size);
if (ret == NULL)
err(EX_OSERR, "calloc");
return ret;
}
void *
safe_realloc(void *ptr, size_t size)
{
void *ret = realloc(ptr, size);
if (ret == NULL)
err(EX_OSERR, "realloc");
return ret;
}
/*
* Compare things like interface or table names.
*/
int
stringnum_cmp(const char *a, const char *b)
{
int la, lb;
la = strlen(a);
lb = strlen(b);
if (la > lb)
return (1);
else if (la < lb)
return (-01);
return (strcmp(a, b));
}
/*
* conditionally runs the command.
* Selected options or negative -> getsockopt
*/
int
do_cmd(int optname, void *optval, uintptr_t optlen)
{
int i;
if (co.test_only)
return 0;
if (ipfw_socket == -1)
ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
if (ipfw_socket < 0)
err(EX_UNAVAILABLE, "socket");
if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
optname == IP_FW_ADD || optname == IP_FW3 ||
optname == IP_FW_NAT_GET_CONFIG ||
optname < 0 ||
optname == IP_FW_NAT_GET_LOG) {
if (optname < 0)
optname = -optname;
i = getsockopt(ipfw_socket, IPPROTO_IP, optname, optval,
(socklen_t *)optlen);
} else {
i = setsockopt(ipfw_socket, IPPROTO_IP, optname, optval, optlen);
}
return i;
}
/*
* do_set3 - pass ipfw control cmd to kernel
* @optname: option name
* @optval: pointer to option data
* @optlen: option length
*
* Assumes op3 header is already embedded.
* Calls setsockopt() with IP_FW3 as kernel-visible opcode.
* Returns 0 on success or errno otherwise.
*/
int
do_set3(int optname, ip_fw3_opheader *op3, size_t optlen)
{
if (co.test_only)
return (0);
if (ipfw_socket == -1)
ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
if (ipfw_socket < 0)
err(EX_UNAVAILABLE, "socket");
op3->opcode = optname;
return (setsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, optlen));
}
/*
* do_get3 - pass ipfw control cmd to kernel
* @optname: option name
* @optval: pointer to option data
* @optlen: pointer to option length
*
* Assumes op3 header is already embedded.
* Calls getsockopt() with IP_FW3 as kernel-visible opcode.
* Returns 0 on success or errno otherwise.
*/
int
do_get3(int optname, ip_fw3_opheader *op3, size_t *optlen)
{
int error;
socklen_t len;
if (co.test_only)
return (0);
if (ipfw_socket == -1)
ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
if (ipfw_socket < 0)
err(EX_UNAVAILABLE, "socket");
op3->opcode = optname;
len = *optlen;
error = getsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, &len);
*optlen = len;
return (error);
}
/**
* match_token takes a table and a string, returns the value associated
* with the string (-1 in case of failure).
*/
int
match_token(struct _s_x *table, const char *string)
{
struct _s_x *pt;
uint i = strlen(string);
for (pt = table ; i && pt->s != NULL ; pt++)
if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
return pt->x;
return (-1);
}
/**
* match_token_relaxed takes a table and a string, returns the value associated
* with the string for the best match.
*
* Returns:
* value from @table for matched records
* -1 for non-matched records
* -2 if more than one records match @string.
*/
int
match_token_relaxed(struct _s_x *table, const char *string)
{
struct _s_x *pt, *m;
int i, c;
i = strlen(string);
c = 0;
for (pt = table ; i != 0 && pt->s != NULL ; pt++) {
if (strncmp(pt->s, string, i) != 0)
continue;
m = pt;
c++;
}
if (c == 1)
return (m->x);
return (c > 0 ? -2: -1);
}
int
get_token(struct _s_x *table, const char *string, const char *errbase)
{
int tcmd;
if ((tcmd = match_token_relaxed(table, string)) < 0)
errx(EX_USAGE, "%s %s %s",
(tcmd == 0) ? "invalid" : "ambiguous", errbase, string);
return (tcmd);
}
/**
* match_value takes a table and a value, returns the string associated
* with the value (NULL in case of failure).
*/
char const *
match_value(struct _s_x *p, int value)
{
for (; p->s != NULL; p++)
if (p->x == value)
return p->s;
return NULL;
}
size_t
concat_tokens(char *buf, size_t bufsize, struct _s_x *table, char *delimiter)
{
struct _s_x *pt;
int l;
size_t sz;
for (sz = 0, pt = table ; pt->s != NULL; pt++) {
l = snprintf(buf + sz, bufsize - sz, "%s%s",
(sz == 0) ? "" : delimiter, pt->s);
sz += l;
bufsize += l;
if (sz > bufsize)
return (bufsize);
}
return (sz);
}
/*
* helper function to process a set of flags and set bits in the
* appropriate masks.
*/
int
fill_flags(struct _s_x *flags, char *p, char **e, uint32_t *set,
uint32_t *clear)
{
char *q; /* points to the separator */
int val;
uint32_t *which; /* mask we are working on */
while (p && *p) {
if (*p == '!') {
p++;
which = clear;
} else
which = set;
q = strchr(p, ',');
if (q)
*q++ = '\0';
val = match_token(flags, p);
if (val <= 0) {
if (e != NULL)
*e = p;
return (-1);
}
*which |= (uint32_t)val;
p = q;
}
return (0);
}
void
print_flags_buffer(char *buf, size_t sz, struct _s_x *list, uint32_t set)
{
char const *comma = "";
int i, l;
for (i = 0; list[i].x != 0; i++) {
if ((set & list[i].x) == 0)
continue;
set &= ~list[i].x;
l = snprintf(buf, sz, "%s%s", comma, list[i].s);
if (l >= sz)
return;
comma = ",";
buf += l;
sz -=l;
}
}
/*
* _substrcmp takes two strings and returns 1 if they do not match,
* and 0 if they match exactly or the first string is a sub-string
* of the second. A warning is printed to stderr in the case that the
* first string is a sub-string of the second.
*
* This function will be removed in the future through the usual
* deprecation process.
*/
int
_substrcmp(const char *str1, const char* str2)
{
if (strncmp(str1, str2, strlen(str1)) != 0)
return 1;
if (strlen(str1) != strlen(str2))
warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
str1, str2);
return 0;
}
/*
* _substrcmp2 takes three strings and returns 1 if the first two do not match,
* and 0 if they match exactly or the second string is a sub-string
* of the first. A warning is printed to stderr in the case that the
* first string does not match the third.
*
* This function exists to warn about the bizarre construction
* strncmp(str, "by", 2) which is used to allow people to use a shortcut
* for "bytes". The problem is that in addition to accepting "by",
* "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
* other string beginning with "by".
*
* This function will be removed in the future through the usual
* deprecation process.
*/
int
_substrcmp2(const char *str1, const char* str2, const char* str3)
{
if (strncmp(str1, str2, strlen(str2)) != 0)
return 1;
if (strcmp(str1, str3) != 0)
warnx("DEPRECATED: '%s' matched '%s'",
str1, str3);
return 0;
}
/*
* prints one port, symbolic or numeric
*/
static void
print_port(struct buf_pr *bp, int proto, uint16_t port)
{
if (proto == IPPROTO_ETHERTYPE) {
char const *s;
if (co.do_resolv && (s = match_value(ether_types, port)) )
bprintf(bp, "%s", s);
else
bprintf(bp, "0x%04x", port);
} else {
struct servent *se = NULL;
if (co.do_resolv) {
struct protoent *pe = getprotobynumber(proto);
se = getservbyport(htons(port), pe ? pe->p_name : NULL);
}
if (se)
bprintf(bp, "%s", se->s_name);
else
bprintf(bp, "%d", port);
}
}
static struct _s_x _port_name[] = {
{"dst-port", O_IP_DSTPORT},
{"src-port", O_IP_SRCPORT},
{"ipid", O_IPID},
{"iplen", O_IPLEN},
{"ipttl", O_IPTTL},
{"mac-type", O_MAC_TYPE},
{"tcpdatalen", O_TCPDATALEN},
{"tcpmss", O_TCPMSS},
{"tcpwin", O_TCPWIN},
{"tagged", O_TAGGED},
{NULL, 0}
};
/*
* Print the values in a list 16-bit items of the types above.
* XXX todo: add support for mask.
*/
static void
print_newports(struct buf_pr *bp, ipfw_insn_u16 *cmd, int proto, int opcode)
{
uint16_t *p = cmd->ports;
int i;
char const *sep;
if (opcode != 0) {
sep = match_value(_port_name, opcode);
if (sep == NULL)
sep = "???";
bprintf(bp, " %s", sep);
}
sep = " ";
for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
bprintf(bp, "%s", sep);
print_port(bp, proto, p[0]);
if (p[0] != p[1]) {
bprintf(bp, "-");
print_port(bp, proto, p[1]);
}
sep = ",";
}
}
/*
* Like strtol, but also translates service names into port numbers
* for some protocols.
* In particular:
* proto == -1 disables the protocol check;
* proto == IPPROTO_ETHERTYPE looks up an internal table
* proto == <some value in /etc/protocols> matches the values there.
* Returns *end == s in case the parameter is not found.
*/
static int
strtoport(char *s, char **end, int base, int proto)
{
char *p, *buf;
char *s1;
int i;
*end = s; /* default - not found */
if (*s == '\0')
return 0; /* not found */
if (isdigit(*s))
return strtol(s, end, base);
/*
* find separator. '\\' escapes the next char.
*/
for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\' ||
*s1 == '_' || *s1 == '.') ; s1++)
if (*s1 == '\\' && s1[1] != '\0')
s1++;
buf = safe_calloc(s1 - s + 1, 1);
/*
* copy into a buffer skipping backslashes
*/
for (p = s, i = 0; p != s1 ; p++)
if (*p != '\\')
buf[i++] = *p;
buf[i++] = '\0';
if (proto == IPPROTO_ETHERTYPE) {
i = match_token(ether_types, buf);
free(buf);
if (i != -1) { /* found */
*end = s1;
return i;
}
} else {
struct protoent *pe = NULL;
struct servent *se;
if (proto != 0)
pe = getprotobynumber(proto);
setservent(1);
se = getservbyname(buf, pe ? pe->p_name : NULL);
free(buf);
if (se != NULL) {
*end = s1;
return ntohs(se->s_port);
}
}
return 0; /* not found */
}
/*
* Fill the body of the command with the list of port ranges.
*/
static int
fill_newports(ipfw_insn_u16 *cmd, char *av, int proto, int cblen)
{
uint16_t a, b, *p = cmd->ports;
int i = 0;
char *s = av;
while (*s) {
a = strtoport(av, &s, 0, proto);
if (s == av) /* empty or invalid argument */
return (0);
CHECK_LENGTH(cblen, i + 2);