Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
freebsd
GitHub Repository: freebsd/freebsd-src
Path: blob/main/sbin/ipfw/ipfw2.c
104102 views
1
/*-
2
* Copyright (c) 2002-2003 Luigi Rizzo
3
* Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp
4
* Copyright (c) 1994 Ugen J.S.Antsilevich
5
*
6
* Idea and grammar partially left from:
7
* Copyright (c) 1993 Daniel Boulet
8
*
9
* Redistribution and use in source forms, with and without modification,
10
* are permitted provided that this entire comment appears intact.
11
*
12
* Redistribution in binary form may occur without any restrictions.
13
* Obviously, it would be nice if you gave credit where credit is due
14
* but requiring it would be too onerous.
15
*
16
* This software is provided ``AS IS'' without any warranties of any kind.
17
*
18
* NEW command line interface for IP firewall facility
19
*/
20
21
#include <sys/types.h>
22
#include <sys/param.h>
23
#include <sys/socket.h>
24
#include <sys/sockio.h>
25
#include <sys/sysctl.h>
26
27
#include "ipfw2.h"
28
29
#include <ctype.h>
30
#include <err.h>
31
#include <errno.h>
32
#include <grp.h>
33
#include <jail.h>
34
#include <netdb.h>
35
#include <pwd.h>
36
#include <stdio.h>
37
#include <stdarg.h>
38
#include <stdint.h>
39
#include <stdlib.h>
40
#include <string.h>
41
#include <sysexits.h>
42
#include <time.h> /* ctime */
43
#include <timeconv.h> /* _long_to_time */
44
#include <unistd.h>
45
#include <fcntl.h>
46
#include <stddef.h> /* offsetof */
47
48
#include <net/ethernet.h>
49
#include <net/if.h> /* only IFNAMSIZ */
50
#include <net/if_dl.h>
51
#include <net/route.h>
52
#include <netinet/in.h>
53
#include <netinet/in_systm.h> /* only n_short, n_long */
54
#include <netinet/ip.h>
55
#include <netinet/ip_icmp.h>
56
#include <netinet/ip_fw.h>
57
#include <netinet/tcp.h>
58
#include <arpa/inet.h>
59
60
struct cmdline_opts g_co; /* global options */
61
62
struct format_opts {
63
int bcwidth;
64
int pcwidth;
65
int show_counters;
66
int show_time; /* show timestamp */
67
uint32_t set_mask; /* enabled sets mask */
68
uint32_t flags; /* request flags */
69
uint32_t first; /* first rule to request */
70
uint32_t last; /* last rule to request */
71
uint32_t dcnt; /* number of dynamic states */
72
ipfw_obj_ctlv *tstate; /* table state data */
73
};
74
75
int resvd_set_number = RESVD_SET;
76
77
static int ipfw_socket = -1;
78
79
#define CHECK_LENGTH(v, len) do { \
80
if ((v) < (len)) \
81
errx(EX_DATAERR, "Rule too long"); \
82
} while (0)
83
/*
84
* Check if we have enough space in cmd buffer. Note that since
85
* first 8? u32 words are reserved by reserved header, full cmd
86
* buffer can't be used, so we need to protect from buffer overrun
87
* only. At the beginning, cblen is less than actual buffer size by
88
* size of ipfw_insn_u32 instruction + 1 u32 work. This eliminates need
89
* for checking small instructions fitting in given range.
90
* We also (ab)use the fact that ipfw_insn is always the first field
91
* for any custom instruction.
92
*/
93
#define CHECK_CMDLEN CHECK_LENGTH(cblen, F_LEN((ipfw_insn *)cmd))
94
95
#define GET_UINT_ARG(arg, min, max, tok, s_x) do { \
96
if (!av[0]) \
97
errx(EX_USAGE, "%s: missing argument", match_value(s_x, tok)); \
98
if (_substrcmp(*av, "tablearg") == 0) { \
99
arg = IP_FW_TARG; \
100
break; \
101
} \
102
\
103
{ \
104
long _xval; \
105
char *end; \
106
\
107
_xval = strtol(*av, &end, 10); \
108
\
109
if (!isdigit(**av) || *end != '\0' || (_xval == 0 && errno == EINVAL)) \
110
errx(EX_DATAERR, "%s: invalid argument: %s", \
111
match_value(s_x, tok), *av); \
112
\
113
if (errno == ERANGE || _xval < min || _xval > max) \
114
errx(EX_DATAERR, "%s: argument is out of range (%u..%u): %s", \
115
match_value(s_x, tok), min, max, *av); \
116
\
117
if (_xval == IP_FW_TARG) \
118
errx(EX_DATAERR, "%s: illegal argument value: %s", \
119
match_value(s_x, tok), *av); \
120
arg = _xval; \
121
} \
122
} while (0)
123
124
static struct _s_x f_tcpflags[] = {
125
{ "syn", TH_SYN },
126
{ "fin", TH_FIN },
127
{ "ack", TH_ACK },
128
{ "psh", TH_PUSH },
129
{ "rst", TH_RST },
130
{ "urg", TH_URG },
131
{ "tcp flag", 0 },
132
{ NULL, 0 }
133
};
134
135
static struct _s_x f_tcpopts[] = {
136
{ "mss", IP_FW_TCPOPT_MSS },
137
{ "maxseg", IP_FW_TCPOPT_MSS },
138
{ "window", IP_FW_TCPOPT_WINDOW },
139
{ "sack", IP_FW_TCPOPT_SACK },
140
{ "ts", IP_FW_TCPOPT_TS },
141
{ "timestamp", IP_FW_TCPOPT_TS },
142
{ "cc", IP_FW_TCPOPT_CC },
143
{ "tcp option", 0 },
144
{ NULL, 0 }
145
};
146
147
/*
148
* IP options span the range 0 to 255 so we need to remap them
149
* (though in fact only the low 5 bits are significant).
150
*/
151
static struct _s_x f_ipopts[] = {
152
{ "ssrr", IP_FW_IPOPT_SSRR},
153
{ "lsrr", IP_FW_IPOPT_LSRR},
154
{ "rr", IP_FW_IPOPT_RR},
155
{ "ts", IP_FW_IPOPT_TS},
156
{ "ip option", 0 },
157
{ NULL, 0 }
158
};
159
160
static struct _s_x f_iptos[] = {
161
{ "lowdelay", IPTOS_LOWDELAY},
162
{ "throughput", IPTOS_THROUGHPUT},
163
{ "reliability", IPTOS_RELIABILITY},
164
{ "mincost", IPTOS_MINCOST},
165
{ "congestion", IPTOS_ECN_CE},
166
{ "ecntransport", IPTOS_ECN_ECT0},
167
{ "ip tos option", 0},
168
{ NULL, 0 }
169
};
170
171
static struct _s_x f_ipoff[] = {
172
{ "rf", IP_RF >> 8 },
173
{ "df", IP_DF >> 8 },
174
{ "mf", IP_MF >> 8 },
175
{ "offset", 0x1 },
176
{ NULL, 0}
177
};
178
179
struct _s_x f_ipdscp[] = {
180
{ "af11", IPTOS_DSCP_AF11 >> 2 }, /* 001010 */
181
{ "af12", IPTOS_DSCP_AF12 >> 2 }, /* 001100 */
182
{ "af13", IPTOS_DSCP_AF13 >> 2 }, /* 001110 */
183
{ "af21", IPTOS_DSCP_AF21 >> 2 }, /* 010010 */
184
{ "af22", IPTOS_DSCP_AF22 >> 2 }, /* 010100 */
185
{ "af23", IPTOS_DSCP_AF23 >> 2 }, /* 010110 */
186
{ "af31", IPTOS_DSCP_AF31 >> 2 }, /* 011010 */
187
{ "af32", IPTOS_DSCP_AF32 >> 2 }, /* 011100 */
188
{ "af33", IPTOS_DSCP_AF33 >> 2 }, /* 011110 */
189
{ "af41", IPTOS_DSCP_AF41 >> 2 }, /* 100010 */
190
{ "af42", IPTOS_DSCP_AF42 >> 2 }, /* 100100 */
191
{ "af43", IPTOS_DSCP_AF43 >> 2 }, /* 100110 */
192
{ "be", IPTOS_DSCP_CS0 >> 2 }, /* 000000 */
193
{ "va", IPTOS_DSCP_VA >> 2 }, /* 101100 */
194
{ "ef", IPTOS_DSCP_EF >> 2 }, /* 101110 */
195
{ "cs0", IPTOS_DSCP_CS0 >> 2 }, /* 000000 */
196
{ "cs1", IPTOS_DSCP_CS1 >> 2 }, /* 001000 */
197
{ "cs2", IPTOS_DSCP_CS2 >> 2 }, /* 010000 */
198
{ "cs3", IPTOS_DSCP_CS3 >> 2 }, /* 011000 */
199
{ "cs4", IPTOS_DSCP_CS4 >> 2 }, /* 100000 */
200
{ "cs5", IPTOS_DSCP_CS5 >> 2 }, /* 101000 */
201
{ "cs6", IPTOS_DSCP_CS6 >> 2 }, /* 110000 */
202
{ "cs7", IPTOS_DSCP_CS7 >> 2 }, /* 100000 */
203
{ NULL, 0 }
204
};
205
206
static struct _s_x limit_masks[] = {
207
{"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
208
{"src-addr", DYN_SRC_ADDR},
209
{"src-port", DYN_SRC_PORT},
210
{"dst-addr", DYN_DST_ADDR},
211
{"dst-port", DYN_DST_PORT},
212
{NULL, 0}
213
};
214
215
/*
216
* we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
217
* This is only used in this code.
218
*/
219
#define IPPROTO_ETHERTYPE 0x1000
220
static struct _s_x ether_types[] = {
221
/*
222
* Note, we cannot use "-:&/" in the names because they are field
223
* separators in the type specifications. Also, we use s = NULL as
224
* end-delimiter, because a type of 0 can be legal.
225
*/
226
{ "ip", 0x0800 },
227
{ "ipv4", 0x0800 },
228
{ "ipv6", 0x86dd },
229
{ "arp", 0x0806 },
230
{ "rarp", 0x8035 },
231
{ "vlan", 0x8100 },
232
{ "loop", 0x9000 },
233
{ "trail", 0x1000 },
234
{ "at", 0x809b },
235
{ "atalk", 0x809b },
236
{ "aarp", 0x80f3 },
237
{ "pppoe_disc", 0x8863 },
238
{ "pppoe_sess", 0x8864 },
239
{ "ipx_8022", 0x00E0 },
240
{ "ipx_8023", 0x0000 },
241
{ "ipx_ii", 0x8137 },
242
{ "ipx_snap", 0x8137 },
243
{ "ipx", 0x8137 },
244
{ "ns", 0x0600 },
245
{ NULL, 0 }
246
};
247
248
static struct _s_x rule_eactions[] = {
249
{ "nat64clat", TOK_NAT64CLAT },
250
{ "nat64lsn", TOK_NAT64LSN },
251
{ "nat64stl", TOK_NAT64STL },
252
{ "nptv6", TOK_NPTV6 },
253
{ "tcp-setmss", TOK_TCPSETMSS },
254
{ NULL, 0 } /* terminator */
255
};
256
257
static struct _s_x rule_actions[] = {
258
{ "abort6", TOK_ABORT6 },
259
{ "abort", TOK_ABORT },
260
{ "accept", TOK_ACCEPT },
261
{ "pass", TOK_ACCEPT },
262
{ "allow", TOK_ACCEPT },
263
{ "permit", TOK_ACCEPT },
264
{ "count", TOK_COUNT },
265
{ "pipe", TOK_PIPE },
266
{ "queue", TOK_QUEUE },
267
{ "divert", TOK_DIVERT },
268
{ "tee", TOK_TEE },
269
{ "netgraph", TOK_NETGRAPH },
270
{ "ngtee", TOK_NGTEE },
271
{ "fwd", TOK_FORWARD },
272
{ "forward", TOK_FORWARD },
273
{ "skipto", TOK_SKIPTO },
274
{ "deny", TOK_DENY },
275
{ "drop", TOK_DENY },
276
{ "reject", TOK_REJECT },
277
{ "reset6", TOK_RESET6 },
278
{ "reset", TOK_RESET },
279
{ "unreach6", TOK_UNREACH6 },
280
{ "unreach", TOK_UNREACH },
281
{ "check-state", TOK_CHECKSTATE },
282
{ "//", TOK_COMMENT },
283
{ "nat", TOK_NAT },
284
{ "reass", TOK_REASS },
285
{ "setfib", TOK_SETFIB },
286
{ "setdscp", TOK_SETDSCP },
287
{ "call", TOK_CALL },
288
{ "return", TOK_RETURN },
289
{ "eaction", TOK_EACTION },
290
{ "tcp-setmss", TOK_TCPSETMSS },
291
{ "setmark", TOK_SETMARK },
292
{ NULL, 0 } /* terminator */
293
};
294
295
static struct _s_x return_types[] = {
296
{ "next-rulenum", RETURN_NEXT_RULENUM },
297
{ "next-rule", RETURN_NEXT_RULE },
298
{ NULL, 0 } /* terminator */
299
};
300
301
static struct _s_x rule_action_params[] = {
302
{ "altq", TOK_ALTQ },
303
{ "log", TOK_LOG },
304
{ "tag", TOK_TAG },
305
{ "untag", TOK_UNTAG },
306
{ NULL, 0 } /* terminator */
307
};
308
309
/*
310
* The 'lookup' instruction accepts one of the following arguments.
311
* Arguments are passed as o.arg1 and o->value in O_DST_LOOKUP option.
312
*/
313
static struct _s_x lookup_keys[] = {
314
{ "dst-ip", LOOKUP_DST_IP },
315
{ "src-ip", LOOKUP_SRC_IP },
316
{ "dst-port", LOOKUP_DST_PORT },
317
{ "src-port", LOOKUP_SRC_PORT },
318
{ "dst-mac", LOOKUP_DST_MAC },
319
{ "src-mac", LOOKUP_SRC_MAC },
320
{ "uid", LOOKUP_UID },
321
{ "jail", LOOKUP_JAIL },
322
{ "dscp", LOOKUP_DSCP },
323
{ "mark", LOOKUP_MARK },
324
{ "rulenum", LOOKUP_RULENUM },
325
{ NULL, 0 },
326
};
327
328
/*
329
* table(name,valuename=value) instruction accepts one of the
330
* following arguments as valuename.
331
*/
332
static struct _s_x tvalue_names[] = {
333
{ "tag", TVALUE_TAG },
334
{ "pipe", TVALUE_PIPE },
335
{ "divert", TVALUE_DIVERT },
336
{ "skipto", TVALUE_SKIPTO },
337
{ "netgraph", TVALUE_NETGRAPH },
338
{ "fib", TVALUE_FIB },
339
{ "nat", TVALUE_NAT },
340
{ "nh4", TVALUE_NH4 },
341
{ "dscp", TVALUE_DSCP },
342
{ "limit", TVALUE_LIMIT },
343
{ "mark", TVALUE_MARK },
344
{ NULL, 0 }
345
};
346
347
static struct _s_x rule_options[] = {
348
{ "tagged", TOK_TAGGED },
349
{ "uid", TOK_UID },
350
{ "gid", TOK_GID },
351
{ "jail", TOK_JAIL },
352
{ "in", TOK_IN },
353
{ "limit", TOK_LIMIT },
354
{ "set-limit", TOK_SETLIMIT },
355
{ "keep-state", TOK_KEEPSTATE },
356
{ "record-state", TOK_RECORDSTATE },
357
{ "bridged", TOK_LAYER2 },
358
{ "layer2", TOK_LAYER2 },
359
{ "out", TOK_OUT },
360
{ "diverted", TOK_DIVERTED },
361
{ "diverted-loopback", TOK_DIVERTEDLOOPBACK },
362
{ "diverted-output", TOK_DIVERTEDOUTPUT },
363
{ "xmit", TOK_XMIT },
364
{ "recv", TOK_RECV },
365
{ "via", TOK_VIA },
366
{ "fragment", TOK_FRAG },
367
{ "frag", TOK_FRAG },
368
{ "fib", TOK_FIB },
369
{ "ipoptions", TOK_IPOPTS },
370
{ "ipopts", TOK_IPOPTS },
371
{ "iplen", TOK_IPLEN },
372
{ "ipid", TOK_IPID },
373
{ "ipprecedence", TOK_IPPRECEDENCE },
374
{ "dscp", TOK_DSCP },
375
{ "iptos", TOK_IPTOS },
376
{ "ipttl", TOK_IPTTL },
377
{ "ipversion", TOK_IPVER },
378
{ "ipver", TOK_IPVER },
379
{ "estab", TOK_ESTAB },
380
{ "established", TOK_ESTAB },
381
{ "setup", TOK_SETUP },
382
{ "sockarg", TOK_SOCKARG },
383
{ "tcpdatalen", TOK_TCPDATALEN },
384
{ "tcpflags", TOK_TCPFLAGS },
385
{ "tcpflgs", TOK_TCPFLAGS },
386
{ "tcpmss", TOK_TCPMSS },
387
{ "tcpoptions", TOK_TCPOPTS },
388
{ "tcpopts", TOK_TCPOPTS },
389
{ "tcpseq", TOK_TCPSEQ },
390
{ "tcpack", TOK_TCPACK },
391
{ "tcpwin", TOK_TCPWIN },
392
{ "icmptype", TOK_ICMPTYPES },
393
{ "icmptypes", TOK_ICMPTYPES },
394
{ "dst-ip", TOK_DSTIP },
395
{ "src-ip", TOK_SRCIP },
396
{ "dst-port", TOK_DSTPORT },
397
{ "src-port", TOK_SRCPORT },
398
{ "dst-mac", TOK_DSTMAC },
399
{ "src-mac", TOK_SRCMAC },
400
{ "proto", TOK_PROTO },
401
{ "MAC", TOK_MAC },
402
{ "mac", TOK_MAC },
403
{ "mac-type", TOK_MACTYPE },
404
{ "verrevpath", TOK_VERREVPATH },
405
{ "versrcreach", TOK_VERSRCREACH },
406
{ "antispoof", TOK_ANTISPOOF },
407
{ "ipsec", TOK_IPSEC },
408
{ "icmp6type", TOK_ICMP6TYPES },
409
{ "icmp6types", TOK_ICMP6TYPES },
410
{ "ext6hdr", TOK_EXT6HDR },
411
{ "flow-id", TOK_FLOWID },
412
{ "ipv6", TOK_IPV6 },
413
{ "ip6", TOK_IPV6 },
414
{ "ipv4", TOK_IPV4 },
415
{ "ip4", TOK_IPV4 },
416
{ "dst-ipv6", TOK_DSTIP6 },
417
{ "dst-ip6", TOK_DSTIP6 },
418
{ "src-ipv6", TOK_SRCIP6 },
419
{ "src-ip6", TOK_SRCIP6 },
420
{ "lookup", TOK_LOOKUP },
421
{ "flow", TOK_FLOW },
422
{ "mark", TOK_MARK },
423
{ "defer-action", TOK_SKIPACTION },
424
{ "defer-immediate-action", TOK_SKIPACTION },
425
{ "//", TOK_COMMENT },
426
427
{ "not", TOK_NOT }, /* pseudo option */
428
{ "!", /* escape ? */ TOK_NOT }, /* pseudo option */
429
{ "or", TOK_OR }, /* pseudo option */
430
{ "|", /* escape */ TOK_OR }, /* pseudo option */
431
{ "{", TOK_STARTBRACE }, /* pseudo option */
432
{ "(", TOK_STARTBRACE }, /* pseudo option */
433
{ "}", TOK_ENDBRACE }, /* pseudo option */
434
{ ")", TOK_ENDBRACE }, /* pseudo option */
435
{ NULL, 0 } /* terminator */
436
};
437
438
void bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg);
439
static int ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
440
ipfw_cfg_lheader **pcfg, size_t *psize);
441
static int ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
442
ipfw_cfg_lheader *cfg, size_t sz, int ac, char **av);
443
static void ipfw_list_tifaces(void);
444
445
struct tidx;
446
static uint32_t pack_object(struct tidx *tstate, const char *name, int otype);
447
static uint32_t pack_table(struct tidx *tstate, const char *name);
448
449
static char *table_search_ctlv(ipfw_obj_ctlv *ctlv, uint32_t idx);
450
static void object_sort_ctlv(ipfw_obj_ctlv *ctlv);
451
static char *object_search_ctlv(ipfw_obj_ctlv *ctlv, uint32_t idx,
452
uint16_t type);
453
454
int
455
is_ipfw(void)
456
{
457
return (g_co.prog == cmdline_prog_ipfw);
458
}
459
460
/*
461
* Simple string buffer API.
462
* Used to simplify buffer passing between function and for
463
* transparent overrun handling.
464
*/
465
466
/*
467
* Allocates new buffer of given size @sz.
468
*
469
* Returns 0 on success.
470
*/
471
int
472
bp_alloc(struct buf_pr *b, size_t size)
473
{
474
memset(b, 0, sizeof(struct buf_pr));
475
476
if ((b->buf = calloc(1, size)) == NULL)
477
return (ENOMEM);
478
479
b->ptr = b->buf;
480
b->size = size;
481
b->avail = b->size;
482
483
return (0);
484
}
485
486
void
487
bp_free(struct buf_pr *b)
488
{
489
490
free(b->buf);
491
}
492
493
/*
494
* Flushes buffer so new writer start from beginning.
495
*/
496
void
497
bp_flush(struct buf_pr *b)
498
{
499
500
b->ptr = b->buf;
501
b->avail = b->size;
502
b->buf[0] = '\0';
503
}
504
505
/*
506
* Print message specified by @format and args.
507
* Automatically manage buffer space and transparently handle
508
* buffer overruns.
509
*
510
* Returns number of bytes that should have been printed.
511
*/
512
int
513
bprintf(struct buf_pr *b, const char *format, ...)
514
{
515
va_list args;
516
int i;
517
518
va_start(args, format);
519
520
i = vsnprintf(b->ptr, b->avail, format, args);
521
va_end(args);
522
523
if (i < 0 || (size_t)i > b->avail) {
524
/* Overflow or print error */
525
b->avail = 0;
526
} else {
527
b->ptr += i;
528
b->avail -= i;
529
}
530
531
b->needed += i;
532
533
return (i);
534
}
535
536
/*
537
* Special values printer for tablearg-aware opcodes.
538
*/
539
void
540
bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg)
541
{
542
543
if (str != NULL)
544
bprintf(bp, "%s", str);
545
if (arg == IP_FW_TARG)
546
bprintf(bp, "tablearg");
547
else
548
bprintf(bp, "%u", arg);
549
}
550
551
/*
552
* Helper routine to print a possibly unaligned uint64_t on
553
* various platform. If width > 0, print the value with
554
* the desired width, followed by a space;
555
* otherwise, return the required width.
556
*/
557
int
558
pr_u64(struct buf_pr *b, void *pd, int width)
559
{
560
#ifdef TCC
561
#define U64_FMT "I64"
562
#else
563
#define U64_FMT "llu"
564
#endif
565
uint64_t u;
566
unsigned long long d;
567
568
bcopy (pd, &u, sizeof(u));
569
d = u;
570
return (width > 0) ?
571
bprintf(b, "%*" U64_FMT " ", width, d) :
572
snprintf(NULL, 0, "%" U64_FMT, d) ;
573
#undef U64_FMT
574
}
575
576
577
void *
578
safe_calloc(size_t number, size_t size)
579
{
580
void *ret = calloc(number, size);
581
582
if (ret == NULL)
583
err(EX_OSERR, "calloc");
584
return ret;
585
}
586
587
void *
588
safe_realloc(void *ptr, size_t size)
589
{
590
void *ret = realloc(ptr, size);
591
592
if (ret == NULL)
593
err(EX_OSERR, "realloc");
594
return ret;
595
}
596
597
/*
598
* Compare things like interface or table names.
599
*/
600
int
601
stringnum_cmp(const char *a, const char *b)
602
{
603
int la, lb;
604
605
la = strlen(a);
606
lb = strlen(b);
607
608
if (la > lb)
609
return (1);
610
else if (la < lb)
611
return (-01);
612
613
return (strcmp(a, b));
614
}
615
616
struct debug_header {
617
uint16_t cmd_type;
618
uint16_t spare1;
619
uint32_t opt_name;
620
uint32_t total_len;
621
uint32_t spare2;
622
};
623
624
/*
625
* conditionally runs the command.
626
* Selected options or negative -> getsockopt
627
*/
628
int
629
do_cmd(int optname, void *optval, uintptr_t optlen)
630
{
631
int i;
632
633
if (g_co.debug_only) {
634
struct debug_header dbg = {
635
.cmd_type = 1,
636
.opt_name = optname,
637
.total_len = optlen + sizeof(struct debug_header),
638
};
639
write(1, &dbg, sizeof(dbg));
640
write(1, optval, optlen);
641
}
642
643
if (g_co.test_only)
644
return (0);
645
646
if (ipfw_socket == -1)
647
ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
648
if (ipfw_socket < 0)
649
err(EX_UNAVAILABLE, "socket");
650
651
if (optname == IP_FW3 || optname < 0) {
652
if (optname < 0)
653
optname = -optname;
654
i = getsockopt(ipfw_socket, IPPROTO_IP, optname, optval,
655
(socklen_t *)optlen);
656
} else {
657
i = setsockopt(ipfw_socket, IPPROTO_IP, optname, optval, optlen);
658
}
659
return (i);
660
}
661
662
/*
663
* do_set3 - pass ipfw control cmd to kernel
664
* @optname: option name
665
* @optval: pointer to option data
666
* @optlen: option length
667
*
668
* Assumes op3 header is already embedded.
669
* Calls setsockopt() with IP_FW3 as kernel-visible opcode.
670
* Returns 0 on success or errno otherwise.
671
*/
672
int
673
do_set3(int optname, ip_fw3_opheader *op3, size_t optlen)
674
{
675
676
op3->opcode = optname;
677
op3->version = IP_FW3_OPVER; /* use last version */
678
679
if (g_co.debug_only) {
680
struct debug_header dbg = {
681
.cmd_type = 2,
682
.opt_name = optname,
683
.total_len = optlen, sizeof(struct debug_header),
684
};
685
write(1, &dbg, sizeof(dbg));
686
write(1, op3, optlen);
687
}
688
689
if (g_co.test_only)
690
return (0);
691
692
if (ipfw_socket == -1)
693
ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
694
if (ipfw_socket < 0)
695
err(EX_UNAVAILABLE, "socket");
696
697
698
return (setsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, optlen));
699
}
700
701
/*
702
* do_get3 - pass ipfw control cmd to kernel
703
* @optname: option name
704
* @optval: pointer to option data
705
* @optlen: pointer to option length
706
*
707
* Assumes op3 header is already embedded.
708
* Calls getsockopt() with IP_FW3 as kernel-visible opcode.
709
* Returns 0 on success or errno otherwise.
710
*/
711
int
712
do_get3(int optname, ip_fw3_opheader *op3, size_t *optlen)
713
{
714
int error;
715
socklen_t len;
716
717
op3->opcode = optname;
718
op3->version = IP_FW3_OPVER; /* use last version */
719
720
if (g_co.debug_only) {
721
struct debug_header dbg = {
722
.cmd_type = 3,
723
.opt_name = optname,
724
.total_len = *optlen + sizeof(struct debug_header),
725
};
726
write(1, &dbg, sizeof(dbg));
727
write(1, op3, *optlen);
728
}
729
730
if (g_co.test_only)
731
return (0);
732
733
if (ipfw_socket == -1)
734
ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
735
if (ipfw_socket < 0)
736
err(EX_UNAVAILABLE, "socket");
737
738
739
len = *optlen;
740
error = getsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, &len);
741
*optlen = len;
742
743
return (error);
744
}
745
746
/**
747
* match_token takes a table and a string, returns the value associated
748
* with the string (-1 in case of failure).
749
*/
750
int
751
match_token(struct _s_x *table, const char *string)
752
{
753
struct _s_x *pt;
754
uint i = strlen(string);
755
756
for (pt = table ; i && pt->s != NULL ; pt++)
757
if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
758
return pt->x;
759
return (-1);
760
}
761
762
/**
763
* match_token_relaxed takes a table and a string, returns the value associated
764
* with the string for the best match.
765
*
766
* Returns:
767
* value from @table for matched records
768
* -1 for non-matched records
769
* -2 if more than one records match @string.
770
*/
771
int
772
match_token_relaxed(struct _s_x *table, const char *string)
773
{
774
struct _s_x *pt, *m;
775
int i, c;
776
777
i = strlen(string);
778
c = 0;
779
780
for (pt = table ; i != 0 && pt->s != NULL ; pt++) {
781
if (strncmp(pt->s, string, i) != 0)
782
continue;
783
m = pt;
784
c++;
785
}
786
787
if (c == 1)
788
return (m->x);
789
790
return (c > 0 ? -2: -1);
791
}
792
793
int
794
get_token(struct _s_x *table, const char *string, const char *errbase)
795
{
796
int tcmd;
797
798
if ((tcmd = match_token_relaxed(table, string)) < 0)
799
errx(EX_USAGE, "%s %s %s",
800
(tcmd == 0) ? "invalid" : "ambiguous", errbase, string);
801
802
return (tcmd);
803
}
804
805
/**
806
* match_value takes a table and a value, returns the string associated
807
* with the value (NULL in case of failure).
808
*/
809
char const *
810
match_value(struct _s_x *p, int value)
811
{
812
for (; p->s != NULL; p++)
813
if (p->x == value)
814
return p->s;
815
return NULL;
816
}
817
818
size_t
819
concat_tokens(char *buf, size_t bufsize, struct _s_x *table,
820
const char *delimiter)
821
{
822
struct _s_x *pt;
823
int l;
824
size_t sz;
825
826
for (sz = 0, pt = table ; pt->s != NULL; pt++) {
827
l = snprintf(buf + sz, bufsize - sz, "%s%s",
828
(sz == 0) ? "" : delimiter, pt->s);
829
sz += l;
830
bufsize += l;
831
if (sz > bufsize)
832
return (bufsize);
833
}
834
835
return (sz);
836
}
837
838
/*
839
* helper function to process a set of flags and set bits in the
840
* appropriate masks.
841
*/
842
int
843
fill_flags(struct _s_x *flags, char *p, char **e, uint32_t *set,
844
uint32_t *clear)
845
{
846
char *q; /* points to the separator */
847
int val;
848
uint32_t *which; /* mask we are working on */
849
850
while (p && *p) {
851
if (*p == '!') {
852
p++;
853
which = clear;
854
} else
855
which = set;
856
q = strchr(p, ',');
857
if (q)
858
*q++ = '\0';
859
val = match_token(flags, p);
860
if (val <= 0) {
861
if (e != NULL)
862
*e = p;
863
return (-1);
864
}
865
*which |= (uint32_t)val;
866
p = q;
867
}
868
return (0);
869
}
870
871
void
872
print_flags_buffer(char *buf, size_t sz, struct _s_x *list, uint32_t set)
873
{
874
char const *comma = "";
875
int i, l;
876
877
for (i = 0; list[i].x != 0; i++) {
878
if ((set & list[i].x) == 0)
879
continue;
880
881
set &= ~list[i].x;
882
l = snprintf(buf, sz, "%s%s", comma, list[i].s);
883
if (l < 0 || (size_t)l >= sz)
884
return;
885
comma = ",";
886
buf += l;
887
sz -=l;
888
}
889
}
890
891
/*
892
* _substrcmp takes two strings and returns 1 if they do not match,
893
* and 0 if they match exactly or the first string is a sub-string
894
* of the second. A warning is printed to stderr in the case that the
895
* first string is a sub-string of the second.
896
*
897
* This function will be removed in the future through the usual
898
* deprecation process.
899
*/
900
int
901
_substrcmp(const char *str1, const char* str2)
902
{
903
904
if (strncmp(str1, str2, strlen(str1)) != 0)
905
return 1;
906
907
if (strlen(str1) != strlen(str2))
908
warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
909
str1, str2);
910
return 0;
911
}
912
913
/*
914
* _substrcmp2 takes three strings and returns 1 if the first two do not match,
915
* and 0 if they match exactly or the second string is a sub-string
916
* of the first. A warning is printed to stderr in the case that the
917
* first string does not match the third.
918
*
919
* This function exists to warn about the bizarre construction
920
* strncmp(str, "by", 2) which is used to allow people to use a shortcut
921
* for "bytes". The problem is that in addition to accepting "by",
922
* "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
923
* other string beginning with "by".
924
*
925
* This function will be removed in the future through the usual
926
* deprecation process.
927
*/
928
int
929
_substrcmp2(const char *str1, const char* str2, const char* str3)
930
{
931
932
if (strncmp(str1, str2, strlen(str2)) != 0)
933
return 1;
934
935
if (strcmp(str1, str3) != 0)
936
warnx("DEPRECATED: '%s' matched '%s'",
937
str1, str3);
938
return 0;
939
}
940
941
/*
942
* prints one port, symbolic or numeric
943
*/
944
static void
945
print_port(struct buf_pr *bp, int proto, uint16_t port)
946
{
947
948
if (proto == IPPROTO_ETHERTYPE) {
949
char const *s;
950
951
if (g_co.do_resolv && (s = match_value(ether_types, port)) )
952
bprintf(bp, "%s", s);
953
else
954
bprintf(bp, "0x%04x", port);
955
} else {
956
struct servent *se = NULL;
957
if (g_co.do_resolv) {
958
struct protoent *pe = getprotobynumber(proto);
959
960
se = getservbyport(htons(port), pe ? pe->p_name : NULL);
961
}
962
if (se)
963
bprintf(bp, "%s", se->s_name);
964
else
965
bprintf(bp, "%d", port);
966
}
967
}
968
969
static struct _s_x _port_name[] = {
970
{"dst-port", O_IP_DSTPORT},
971
{"src-port", O_IP_SRCPORT},
972
{"ipid", O_IPID},
973
{"iplen", O_IPLEN},
974
{"ipttl", O_IPTTL},
975
{"mac-type", O_MAC_TYPE},
976
{"tcpdatalen", O_TCPDATALEN},
977
{"tcpmss", O_TCPMSS},
978
{"tcpwin", O_TCPWIN},
979
{"tagged", O_TAGGED},
980
{NULL, 0}
981
};
982
983
/*
984
* Print the values in a list 16-bit items of the types above.
985
* XXX todo: add support for mask.
986
*/
987
static void
988
print_newports(struct buf_pr *bp, const ipfw_insn_u16 *cmd, int proto, int opcode)
989
{
990
const uint16_t *p = cmd->ports;
991
int i;
992
char const *sep;
993
994
if (opcode != 0) {
995
sep = match_value(_port_name, opcode);
996
if (sep == NULL)
997
sep = "???";
998
bprintf(bp, " %s", sep);
999
}
1000
sep = " ";
1001
for (i = F_LEN((const ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
1002
bprintf(bp, "%s", sep);
1003
print_port(bp, proto, p[0]);
1004
if (p[0] != p[1]) {
1005
bprintf(bp, "-");
1006
print_port(bp, proto, p[1]);
1007
}
1008
sep = ",";
1009
}
1010
}
1011
1012
/*
1013
* Like strtol, but also translates service names into port numbers
1014
* for some protocols.
1015
* In particular:
1016
* proto == -1 disables the protocol check;
1017
* proto == IPPROTO_ETHERTYPE looks up an internal table
1018
* proto == <some value in /etc/protocols> matches the values there.
1019
* Returns *end == s in case the parameter is not found.
1020
*/
1021
static int
1022
strtoport(char *s, char **end, int base, int proto)
1023
{
1024
char *p, *buf;
1025
char *s1;
1026
int i;
1027
1028
*end = s; /* default - not found */
1029
if (*s == '\0')
1030
return 0; /* not found */
1031
1032
if (isdigit(*s))
1033
return strtol(s, end, base);
1034
1035
/*
1036
* find separator. '\\' escapes the next char.
1037
*/
1038
for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\' ||
1039
*s1 == '_' || *s1 == '.') ; s1++)
1040
if (*s1 == '\\' && s1[1] != '\0')
1041
s1++;
1042
1043
buf = safe_calloc(s1 - s + 1, 1);
1044
1045
/*
1046
* copy into a buffer skipping backslashes
1047
*/
1048
for (p = s, i = 0; p != s1 ; p++)
1049
if (*p != '\\')
1050
buf[i++] = *p;
1051
buf[i++] = '\0';
1052
1053
if (proto == IPPROTO_ETHERTYPE) {
1054
i = match_token(ether_types, buf);
1055
free(buf);
1056
if (i != -1) { /* found */
1057
*end = s1;
1058
return i;
1059
}
1060
} else {
1061
struct protoent *pe = NULL;
1062
struct servent *se;
1063
1064
if (proto != 0)
1065
pe = getprotobynumber(proto);
1066
setservent(1);
1067
se = getservbyname(buf, pe ? pe->p_name : NULL);
1068
free(buf);
1069
if (se != NULL) {
1070
*end = s1;
1071
return ntohs(se->s_port);
1072
}
1073
}
1074
return 0; /* not found */
1075
}
1076
1077
/*
1078
* Fill the body of the command with the list of port ranges.
1079
*/
1080
static int
1081
fill_newports(ipfw_insn_u16 *cmd, char *av, int proto, int cblen)
1082
{
1083
uint16_t a, b, *p = cmd->ports;
1084
int i = 0;
1085
char *s = av;
1086
1087
while (*s) {
1088
a = strtoport(av, &s, 0, proto);
1089
if (s == av) /* empty or invalid argument */
1090
return (0);
1091
1092
CHECK_LENGTH(cblen, i + 2);
1093
1094
switch (*s) {
1095
case '-': /* a range */
1096
av = s + 1;
1097
b = strtoport(av, &s, 0, proto);
1098
/* Reject expressions like '1-abc' or '1-2-3'. */
1099
if (s == av || (*s != ',' && *s != '\0'))
1100
return (0);
1101
p[0] = a;
1102
p[1] = b;
1103
break;
1104
case ',': /* comma separated list */
1105
case '\0':
1106
p[0] = p[1] = a;
1107
break;
1108
default:
1109
warnx("port list: invalid separator <%c> in <%s>",
1110
*s, av);
1111
return (0);
1112
}
1113
1114
i++;
1115
p += 2;
1116
av = s + 1;
1117
}
1118
if (i > 0) {
1119
if (i + 1 > F_LEN_MASK)
1120
errx(EX_DATAERR, "too many ports/ranges\n");
1121
cmd->o.len |= i + 1; /* leave F_NOT and F_OR untouched */
1122
}
1123
return (i);
1124
}
1125
1126
/*
1127
* Fill the body of the command with the list of DiffServ codepoints.
1128
*/
1129
static void
1130
fill_dscp(ipfw_insn *cmd, char *av, int cblen)
1131
{
1132
uint32_t *low, *high;
1133
char *s = av, *a;
1134
int code;
1135
1136
cmd->opcode = O_DSCP;
1137
cmd->len |= F_INSN_SIZE(ipfw_insn_u32) + 1;
1138
1139
CHECK_CMDLEN;
1140
1141
low = (uint32_t *)(cmd + 1);
1142
high = low + 1;
1143
1144
*low = 0;
1145
*high = 0;
1146
1147
while (s != NULL) {
1148
a = strchr(s, ',');
1149
1150
if (a != NULL)
1151
*a++ = '\0';
1152
1153
if (isalpha(*s)) {
1154
if ((code = match_token(f_ipdscp, s)) == -1)
1155
errx(EX_DATAERR, "Unknown DSCP code");
1156
} else {
1157
code = strtoul(s, NULL, 10);
1158
if (code < 0 || code > 63)
1159
errx(EX_DATAERR, "Invalid DSCP value");
1160
}
1161
1162
if (code >= 32)
1163
*high |= 1 << (code - 32);
1164
else
1165
*low |= 1 << code;
1166
1167
s = a;
1168
}
1169
}
1170
1171
/*
1172
* Fill the body of the command with mark value and mask.
1173
*/
1174
static void
1175
fill_mark(ipfw_insn *cmd, char *av, int cblen)
1176
{
1177
uint32_t *value, *mask;
1178
char *value_str;
1179
1180
cmd->opcode = O_MARK;
1181
cmd->len |= F_INSN_SIZE(ipfw_insn_u32) + 1;
1182
1183
CHECK_CMDLEN;
1184
1185
value = (uint32_t *)(cmd + 1);
1186
mask = value + 1;
1187
1188
value_str = strsep(&av, ":");
1189
1190
if (strcmp(value_str, "tablearg") == 0) {
1191
cmd->arg1 = IP_FW_TARG;
1192
*value = 0;
1193
} else {
1194
/* This is not a tablearg */
1195
cmd->arg1 |= 0x8000;
1196
*value = strtoul(value_str, NULL, 0);
1197
}
1198
if (av)
1199
*mask = strtoul(av, NULL, 0);
1200
else
1201
*mask = 0xFFFFFFFF;
1202
1203
if ((*value & *mask) != *value)
1204
errx(EX_DATAERR, "Static mark value: some bits in value are"
1205
" set that will be masked out by mask "
1206
"(%#x & %#x) = %#x != %#x",
1207
*value, *mask, (*value & *mask), *value);
1208
}
1209
1210
static struct _s_x icmpcodes[] = {
1211
{ "net", ICMP_UNREACH_NET },
1212
{ "host", ICMP_UNREACH_HOST },
1213
{ "protocol", ICMP_UNREACH_PROTOCOL },
1214
{ "port", ICMP_UNREACH_PORT },
1215
{ "needfrag", ICMP_UNREACH_NEEDFRAG },
1216
{ "srcfail", ICMP_UNREACH_SRCFAIL },
1217
{ "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
1218
{ "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
1219
{ "isolated", ICMP_UNREACH_ISOLATED },
1220
{ "net-prohib", ICMP_UNREACH_NET_PROHIB },
1221
{ "host-prohib", ICMP_UNREACH_HOST_PROHIB },
1222
{ "tosnet", ICMP_UNREACH_TOSNET },
1223
{ "toshost", ICMP_UNREACH_TOSHOST },
1224
{ "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
1225
{ "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
1226
{ "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
1227
{ NULL, 0 }
1228
};
1229
1230
static uint16_t
1231
get_reject_code(const char *str)
1232
{
1233
int val;
1234
char *s;
1235
1236
val = strtoul(str, &s, 0);
1237
if (s == str || *s != '\0' || val >= 0x100)
1238
val = match_token(icmpcodes, str);
1239
if (val < 0)
1240
errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
1241
return (val);
1242
}
1243
1244
static void
1245
print_reject_code(struct buf_pr *bp, uint16_t code)
1246
{
1247
char const *s;
1248
1249
if ((s = match_value(icmpcodes, code)) != NULL)
1250
bprintf(bp, "unreach %s", s);
1251
else
1252
bprintf(bp, "unreach %u", code);
1253
}
1254
1255
/*
1256
* Returns the number of bits set (from left) in a contiguous bitmask,
1257
* or -1 if the mask is not contiguous.
1258
* XXX this needs a proper fix.
1259
* This effectively works on masks in big-endian (network) format.
1260
* when compiled on little endian architectures.
1261
*
1262
* First bit is bit 7 of the first byte -- note, for MAC addresses,
1263
* the first bit on the wire is bit 0 of the first byte.
1264
* len is the max length in bits.
1265
*/
1266
int
1267
contigmask(const uint8_t *p, int len)
1268
{
1269
int i, n;
1270
1271
for (i=0; i<len ; i++)
1272
if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
1273
break;
1274
for (n=i+1; n < len; n++)
1275
if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
1276
return -1; /* mask not contiguous */
1277
return i;
1278
}
1279
1280
/*
1281
* print flags set/clear in the two bitmasks passed as parameters.
1282
* There is a specialized check for f_tcpflags.
1283
*/
1284
static void
1285
print_flags(struct buf_pr *bp, char const *name, const ipfw_insn *cmd,
1286
struct _s_x *list)
1287
{
1288
char const *comma = "";
1289
int i;
1290
uint8_t set = cmd->arg1 & 0xff;
1291
uint8_t clear = (cmd->arg1 >> 8) & 0xff;
1292
1293
if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
1294
bprintf(bp, " setup");
1295
return;
1296
}
1297
1298
bprintf(bp, " %s ", name);
1299
for (i=0; list[i].x != 0; i++) {
1300
if (set & list[i].x) {
1301
set &= ~list[i].x;
1302
bprintf(bp, "%s%s", comma, list[i].s);
1303
comma = ",";
1304
}
1305
if (clear & list[i].x) {
1306
clear &= ~list[i].x;
1307
bprintf(bp, "%s!%s", comma, list[i].s);
1308
comma = ",";
1309
}
1310
}
1311
}
1312
1313
static void
1314
print_tvalue(struct buf_pr *bp, const ipfw_insn_table *cmd)
1315
{
1316
const char *name;
1317
1318
name = match_value(tvalue_names, IPFW_TVALUE_TYPE(&cmd->o));
1319
bprintf(bp, ",%s=%u", name != NULL ? name: "<invalid>", cmd->value);
1320
}
1321
1322
1323
/*
1324
* Print the ip address contained in a command.
1325
*/
1326
static void
1327
print_ip(struct buf_pr *bp, const struct format_opts *fo,
1328
const ipfw_insn_ip *cmd)
1329
{
1330
struct hostent *he = NULL;
1331
const struct in_addr *ia;
1332
const uint32_t *a = ((const ipfw_insn_u32 *)cmd)->d;
1333
uint32_t len = F_LEN(&cmd->o);
1334
char *t;
1335
1336
bprintf(bp, " ");
1337
switch (cmd->o.opcode) {
1338
case O_IP_SRC_ME:
1339
case O_IP_DST_ME:
1340
bprintf(bp, "me");
1341
return;
1342
1343
case O_IP_DST_LOOKUP:
1344
if ((len == F_INSN_SIZE(ipfw_insn_kidx) ||
1345
len == F_INSN_SIZE(ipfw_insn_table)) &&
1346
IPFW_LOOKUP_TYPE(&cmd->o) != LOOKUP_NONE) {
1347
const char *key;
1348
1349
key = match_value(lookup_keys,
1350
IPFW_LOOKUP_TYPE(&cmd->o));
1351
t = table_search_ctlv(fo->tstate,
1352
insntoc(&cmd->o, kidx)->kidx);
1353
if (len == F_INSN_SIZE(ipfw_insn_table)) {
1354
bprintf(bp, "lookup %s:%#x %s",
1355
(key != NULL ? key : "<invalid>"),
1356
insntoc(&cmd->o, table)->value, t);
1357
} else
1358
bprintf(bp, "lookup %s %s", key != NULL ? key:
1359
"<invalid>", t);
1360
return;
1361
}
1362
/* FALLTHROUGH */
1363
case O_IP_SRC_LOOKUP:
1364
t = table_search_ctlv(fo->tstate,
1365
insntoc(&cmd->o, kidx)->kidx);
1366
bprintf(bp, "table(%s", t);
1367
if (len == F_INSN_SIZE(ipfw_insn_table))
1368
print_tvalue(bp, insntoc(&cmd->o, table));
1369
bprintf(bp, ")");
1370
return;
1371
}
1372
1373
if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
1374
const uint32_t *map = (const uint32_t *)&cmd->mask;
1375
struct in_addr addr;
1376
uint32_t x;
1377
int i, j;
1378
char comma = '{';
1379
1380
x = cmd->o.arg1 - 1;
1381
x = htonl(~x);
1382
addr.s_addr = htonl(cmd->addr.s_addr);
1383
bprintf(bp, "%s/%d", inet_ntoa(addr),
1384
contigmask((uint8_t *)&x, 32));
1385
x = cmd->addr.s_addr;
1386
x &= 0xff; /* base */
1387
/*
1388
* Print bits and ranges.
1389
* Locate first bit set (i), then locate first bit unset (j).
1390
* If we have 3+ consecutive bits set, then print them as a
1391
* range, otherwise only print the initial bit and rescan.
1392
*/
1393
for (i=0; i < cmd->o.arg1; i++)
1394
if (map[i/32] & (1<<(i & 31))) {
1395
for (j=i+1; j < cmd->o.arg1; j++)
1396
if (!(map[ j/32] & (1<<(j & 31))))
1397
break;
1398
bprintf(bp, "%c%d", comma, i+x);
1399
if (j>i+2) { /* range has at least 3 elements */
1400
bprintf(bp, "-%d", j-1+x);
1401
i = j-1;
1402
}
1403
comma = ',';
1404
}
1405
bprintf(bp, "}");
1406
return;
1407
}
1408
/*
1409
* len == 2 indicates a single IP, whereas lists of 1 or more
1410
* addr/mask pairs have len = (2n+1). We convert len to n so we
1411
* use that to count the number of entries.
1412
*/
1413
for (len = len / 2; len > 0; len--, a += 2) {
1414
int mb = /* mask length */
1415
(cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
1416
32 : contigmask((const uint8_t *)&(a[1]), 32);
1417
if (mb == 32 && g_co.do_resolv)
1418
he = gethostbyaddr((const char *)&(a[0]), sizeof(in_addr_t),
1419
AF_INET);
1420
if (he != NULL) /* resolved to name */
1421
bprintf(bp, "%s", he->h_name);
1422
else if (mb == 0) /* any */
1423
bprintf(bp, "any");
1424
else { /* numeric IP followed by some kind of mask */
1425
ia = (const struct in_addr *)&a[0];
1426
bprintf(bp, "%s", inet_ntoa(*ia));
1427
if (mb < 0) {
1428
ia = (const struct in_addr *)&a[1];
1429
bprintf(bp, ":%s", inet_ntoa(*ia));
1430
} else if (mb < 32)
1431
bprintf(bp, "/%d", mb);
1432
}
1433
if (len > 1)
1434
bprintf(bp, ",");
1435
}
1436
}
1437
1438
/*
1439
* prints a MAC address/mask pair
1440
*/
1441
static void
1442
format_mac(struct buf_pr *bp, const uint8_t *addr, const uint8_t *mask)
1443
{
1444
int l = contigmask(mask, 48);
1445
1446
if (l == 0)
1447
bprintf(bp, " any");
1448
else {
1449
bprintf(bp, " %02x:%02x:%02x:%02x:%02x:%02x",
1450
addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
1451
if (l == -1)
1452
bprintf(bp, "&%02x:%02x:%02x:%02x:%02x:%02x",
1453
mask[0], mask[1], mask[2],
1454
mask[3], mask[4], mask[5]);
1455
else if (l < 48)
1456
bprintf(bp, "/%d", l);
1457
}
1458
}
1459
1460
static void
1461
print_mac(struct buf_pr *bp, const ipfw_insn_mac *mac)
1462
{
1463
1464
bprintf(bp, " MAC");
1465
format_mac(bp, mac->addr, mac->mask);
1466
format_mac(bp, mac->addr + 6, mac->mask + 6);
1467
}
1468
1469
static void
1470
print_mac_lookup(struct buf_pr *bp, const struct format_opts *fo,
1471
const ipfw_insn *cmd)
1472
{
1473
uint32_t len = F_LEN(cmd);
1474
char *t;
1475
1476
bprintf(bp, " ");
1477
1478
t = table_search_ctlv(fo->tstate, insntoc(cmd, kidx)->kidx);
1479
bprintf(bp, "table(%s", t);
1480
if (len == F_INSN_SIZE(ipfw_insn_table))
1481
print_tvalue(bp, insntoc(cmd, table));
1482
bprintf(bp, ")");
1483
}
1484
1485
static void
1486
fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
1487
{
1488
uint8_t type;
1489
1490
cmd->d[0] = 0;
1491
while (*av) {
1492
if (*av == ',')
1493
av++;
1494
1495
type = strtoul(av, &av, 0);
1496
1497
if (*av != ',' && *av != '\0')
1498
errx(EX_DATAERR, "invalid ICMP type");
1499
1500
if (type > 31)
1501
errx(EX_DATAERR, "ICMP type out of range");
1502
1503
cmd->d[0] |= 1 << type;
1504
}
1505
cmd->o.opcode = O_ICMPTYPE;
1506
cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1507
}
1508
1509
static void
1510
print_icmptypes(struct buf_pr *bp, const ipfw_insn_u32 *cmd)
1511
{
1512
int i;
1513
char sep= ' ';
1514
1515
bprintf(bp, " icmptypes");
1516
for (i = 0; i < 32; i++) {
1517
if ( (cmd->d[0] & (1 << (i))) == 0)
1518
continue;
1519
bprintf(bp, "%c%d", sep, i);
1520
sep = ',';
1521
}
1522
}
1523
1524
static void
1525
print_dscp(struct buf_pr *bp, const ipfw_insn_u32 *cmd)
1526
{
1527
const uint32_t *v;
1528
const char *code;
1529
int i = 0;
1530
char sep= ' ';
1531
1532
bprintf(bp, " dscp");
1533
v = cmd->d;
1534
while (i < 64) {
1535
if (*v & (1 << i)) {
1536
if ((code = match_value(f_ipdscp, i)) != NULL)
1537
bprintf(bp, "%c%s", sep, code);
1538
else
1539
bprintf(bp, "%c%d", sep, i);
1540
sep = ',';
1541
}
1542
1543
if ((++i % 32) == 0)
1544
v++;
1545
}
1546
}
1547
1548
struct show_state {
1549
struct ip_fw_rule *rule;
1550
const ipfw_insn_kidx *eaction;
1551
uint8_t *printed;
1552
int flags;
1553
#define HAVE_PROTO 0x0001
1554
#define HAVE_SRCIP 0x0002
1555
#define HAVE_DSTIP 0x0004
1556
#define HAVE_PROBE_STATE 0x0008
1557
int proto;
1558
int or_block;
1559
};
1560
1561
static int
1562
init_show_state(struct show_state *state, struct ip_fw_rule *rule)
1563
{
1564
1565
state->printed = calloc(rule->cmd_len, sizeof(uint8_t));
1566
if (state->printed == NULL)
1567
return (ENOMEM);
1568
state->rule = rule;
1569
state->eaction = NULL;
1570
state->flags = 0;
1571
state->proto = 0;
1572
state->or_block = 0;
1573
return (0);
1574
}
1575
1576
static void
1577
free_show_state(struct show_state *state)
1578
{
1579
1580
free(state->printed);
1581
}
1582
1583
static uint8_t
1584
is_printed_opcode(struct show_state *state, const ipfw_insn *cmd)
1585
{
1586
1587
return (state->printed[cmd - state->rule->cmd]);
1588
}
1589
1590
static void
1591
mark_printed(struct show_state *state, const ipfw_insn *cmd)
1592
{
1593
1594
state->printed[cmd - state->rule->cmd] = 1;
1595
}
1596
1597
static void
1598
print_limit_mask(struct buf_pr *bp, const ipfw_insn_limit *limit)
1599
{
1600
struct _s_x *p = limit_masks;
1601
char const *comma = " ";
1602
uint8_t x;
1603
1604
for (x = limit->limit_mask; p->x != 0; p++) {
1605
if ((x & p->x) == p->x) {
1606
x &= ~p->x;
1607
bprintf(bp, "%s%s", comma, p->s);
1608
comma = ",";
1609
}
1610
}
1611
bprint_uint_arg(bp, " ", limit->conn_limit);
1612
}
1613
1614
static int
1615
print_instruction(struct buf_pr *bp, const struct format_opts *fo,
1616
struct show_state *state, const ipfw_insn *cmd)
1617
{
1618
struct protoent *pe;
1619
struct passwd *pwd;
1620
struct group *grp;
1621
const char *s;
1622
double d;
1623
1624
if (is_printed_opcode(state, cmd))
1625
return (0);
1626
if ((cmd->len & F_OR) != 0 && state->or_block == 0)
1627
bprintf(bp, " {");
1628
if (cmd->opcode != O_IN && (cmd->len & F_NOT) != 0)
1629
bprintf(bp, " not");
1630
1631
switch (cmd->opcode) {
1632
case O_PROB:
1633
d = 1.0 * insntoc(cmd, u32)->d[0] / 0x7fffffff;
1634
bprintf(bp, "prob %f ", d);
1635
break;
1636
case O_PROBE_STATE: /* no need to print anything here */
1637
state->flags |= HAVE_PROBE_STATE;
1638
break;
1639
case O_IP_SRC:
1640
case O_IP_SRC_LOOKUP:
1641
case O_IP_SRC_MASK:
1642
case O_IP_SRC_ME:
1643
case O_IP_SRC_SET:
1644
if (state->flags & HAVE_SRCIP)
1645
bprintf(bp, " src-ip");
1646
print_ip(bp, fo, insntoc(cmd, ip));
1647
break;
1648
case O_IP_DST:
1649
case O_IP_DST_MASK:
1650
case O_IP_DST_ME:
1651
case O_IP_DST_SET:
1652
case O_IP_DST_LOOKUP:
1653
/*
1654
* Special handling for O_IP_DST_LOOKUP when
1655
* lookup type is not LOOKUP_NONE.
1656
*/
1657
if ((state->flags & HAVE_DSTIP) != 0 && (
1658
cmd->opcode != O_IP_DST_LOOKUP ||
1659
IPFW_LOOKUP_TYPE(cmd) == LOOKUP_NONE))
1660
bprintf(bp, " dst-ip");
1661
print_ip(bp, fo, insntoc(cmd, ip));
1662
break;
1663
case O_IP6_SRC:
1664
case O_IP6_SRC_MASK:
1665
case O_IP6_SRC_ME:
1666
if (state->flags & HAVE_SRCIP)
1667
bprintf(bp, " src-ip6");
1668
print_ip6(bp, insntoc(cmd, ip6));
1669
break;
1670
case O_IP6_DST:
1671
case O_IP6_DST_MASK:
1672
case O_IP6_DST_ME:
1673
if (state->flags & HAVE_DSTIP)
1674
bprintf(bp, " dst-ip6");
1675
print_ip6(bp, insntoc(cmd, ip6));
1676
break;
1677
case O_MAC_SRC_LOOKUP:
1678
bprintf(bp, " src-mac");
1679
print_mac_lookup(bp, fo, cmd);
1680
break;
1681
case O_MAC_DST_LOOKUP:
1682
bprintf(bp, " dst-mac");
1683
print_mac_lookup(bp, fo, cmd);
1684
break;
1685
case O_FLOW6ID:
1686
print_flow6id(bp, insntoc(cmd, u32));
1687
break;
1688
case O_IP_DSTPORT:
1689
case O_IP_SRCPORT:
1690
print_newports(bp, insntoc(cmd, u16), state->proto,
1691
(state->flags & (HAVE_SRCIP | HAVE_DSTIP)) ==
1692
(HAVE_SRCIP | HAVE_DSTIP) ? cmd->opcode: 0);
1693
break;
1694
case O_PROTO:
1695
pe = getprotobynumber(cmd->arg1);
1696
if (state->flags & HAVE_PROTO)
1697
bprintf(bp, " proto");
1698
if (pe != NULL)
1699
bprintf(bp, " %s", pe->p_name);
1700
else
1701
bprintf(bp, " %u", cmd->arg1);
1702
state->proto = cmd->arg1;
1703
break;
1704
case O_MACADDR2:
1705
print_mac(bp, insntoc(cmd, mac));
1706
break;
1707
case O_MAC_TYPE:
1708
print_newports(bp, insntoc(cmd, u16),
1709
IPPROTO_ETHERTYPE, cmd->opcode);
1710
break;
1711
case O_FRAG:
1712
print_flags(bp, "frag", cmd, f_ipoff);
1713
break;
1714
case O_FIB:
1715
bprintf(bp, " fib %u", cmd->arg1);
1716
break;
1717
case O_SOCKARG:
1718
bprintf(bp, " sockarg");
1719
break;
1720
case O_IN:
1721
bprintf(bp, cmd->len & F_NOT ? " out" : " in");
1722
break;
1723
case O_DIVERTED:
1724
switch (cmd->arg1) {
1725
case 3:
1726
bprintf(bp, " diverted");
1727
break;
1728
case 2:
1729
bprintf(bp, " diverted-output");
1730
break;
1731
case 1:
1732
bprintf(bp, " diverted-loopback");
1733
break;
1734
default:
1735
bprintf(bp, " diverted-?<%u>", cmd->arg1);
1736
break;
1737
}
1738
break;
1739
case O_LAYER2:
1740
bprintf(bp, " layer2");
1741
break;
1742
case O_XMIT:
1743
case O_RECV:
1744
case O_VIA:
1745
if (cmd->opcode == O_XMIT)
1746
s = "xmit";
1747
else if (cmd->opcode == O_RECV)
1748
s = "recv";
1749
else /* if (cmd->opcode == O_VIA) */
1750
s = "via";
1751
switch (insntoc(cmd, if)->name[0]) {
1752
case '\0':
1753
bprintf(bp, " %s %s", s,
1754
inet_ntoa(insntoc(cmd, if)->p.ip));
1755
break;
1756
case '\1':
1757
bprintf(bp, " %s table(%s)", s,
1758
table_search_ctlv(fo->tstate,
1759
insntoc(cmd, if)->p.kidx));
1760
break;
1761
default:
1762
bprintf(bp, " %s %s", s,
1763
insntoc(cmd, if)->name);
1764
}
1765
break;
1766
case O_IP_FLOW_LOOKUP:
1767
s = table_search_ctlv(fo->tstate,
1768
insntoc(cmd, kidx)->kidx);
1769
bprintf(bp, " flow table(%s", s);
1770
if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_table))
1771
print_tvalue(bp, insntoc(cmd, table));
1772
bprintf(bp, ")");
1773
break;
1774
case O_IPID:
1775
case O_IPTTL:
1776
case O_IPLEN:
1777
case O_TCPDATALEN:
1778
case O_TCPMSS:
1779
case O_TCPWIN:
1780
if (F_LEN(cmd) == 1) {
1781
switch (cmd->opcode) {
1782
case O_IPID:
1783
s = "ipid";
1784
break;
1785
case O_IPTTL:
1786
s = "ipttl";
1787
break;
1788
case O_IPLEN:
1789
s = "iplen";
1790
break;
1791
case O_TCPDATALEN:
1792
s = "tcpdatalen";
1793
break;
1794
case O_TCPMSS:
1795
s = "tcpmss";
1796
break;
1797
case O_TCPWIN:
1798
s = "tcpwin";
1799
break;
1800
default:
1801
s = "<unknown>";
1802
break;
1803
}
1804
bprintf(bp, " %s %u", s, cmd->arg1);
1805
} else
1806
print_newports(bp, insntoc(cmd, u16), 0,
1807
cmd->opcode);
1808
break;
1809
case O_IPVER:
1810
bprintf(bp, " ipver %u", cmd->arg1);
1811
break;
1812
case O_IPPRECEDENCE:
1813
bprintf(bp, " ipprecedence %u", cmd->arg1 >> 5);
1814
break;
1815
case O_DSCP:
1816
print_dscp(bp, insntoc(cmd, u32));
1817
break;
1818
case O_IPOPT:
1819
print_flags(bp, "ipoptions", cmd, f_ipopts);
1820
break;
1821
case O_IPTOS:
1822
print_flags(bp, "iptos", cmd, f_iptos);
1823
break;
1824
case O_ICMPTYPE:
1825
print_icmptypes(bp, insntoc(cmd, u32));
1826
break;
1827
case O_ESTAB:
1828
bprintf(bp, " established");
1829
break;
1830
case O_TCPFLAGS:
1831
print_flags(bp, "tcpflags", cmd, f_tcpflags);
1832
break;
1833
case O_TCPOPTS:
1834
print_flags(bp, "tcpoptions", cmd, f_tcpopts);
1835
break;
1836
case O_TCPACK:
1837
bprintf(bp, " tcpack %d",
1838
ntohl(insntoc(cmd, u32)->d[0]));
1839
break;
1840
case O_TCPSEQ:
1841
bprintf(bp, " tcpseq %d",
1842
ntohl(insntoc(cmd, u32)->d[0]));
1843
break;
1844
case O_UID:
1845
pwd = getpwuid(insntoc(cmd, u32)->d[0]);
1846
if (pwd != NULL)
1847
bprintf(bp, " uid %s", pwd->pw_name);
1848
else
1849
bprintf(bp, " uid %u",
1850
insntoc(cmd, u32)->d[0]);
1851
break;
1852
case O_GID:
1853
grp = getgrgid(insntoc(cmd, u32)->d[0]);
1854
if (grp != NULL)
1855
bprintf(bp, " gid %s", grp->gr_name);
1856
else
1857
bprintf(bp, " gid %u",
1858
insntoc(cmd, u32)->d[0]);
1859
break;
1860
case O_JAIL:
1861
bprintf(bp, " jail %d", insntoc(cmd, u32)->d[0]);
1862
break;
1863
case O_VERREVPATH:
1864
bprintf(bp, " verrevpath");
1865
break;
1866
case O_VERSRCREACH:
1867
bprintf(bp, " versrcreach");
1868
break;
1869
case O_ANTISPOOF:
1870
bprintf(bp, " antispoof");
1871
break;
1872
case O_IPSEC:
1873
bprintf(bp, " ipsec");
1874
break;
1875
case O_NOP:
1876
bprintf(bp, " // %s", (const char *)(cmd + 1));
1877
break;
1878
case O_KEEP_STATE:
1879
if (state->flags & HAVE_PROBE_STATE)
1880
bprintf(bp, " keep-state");
1881
else
1882
bprintf(bp, " record-state");
1883
bprintf(bp, " :%s",
1884
object_search_ctlv(fo->tstate,
1885
insntoc(cmd, kidx)->kidx,
1886
IPFW_TLV_STATE_NAME));
1887
break;
1888
case O_LIMIT:
1889
if (state->flags & HAVE_PROBE_STATE)
1890
bprintf(bp, " limit");
1891
else
1892
bprintf(bp, " set-limit");
1893
print_limit_mask(bp, insntoc(cmd, limit));
1894
bprintf(bp, " :%s",
1895
object_search_ctlv(fo->tstate,
1896
insntoc(cmd, kidx)->kidx,
1897
IPFW_TLV_STATE_NAME));
1898
break;
1899
case O_IP6:
1900
if (state->flags & HAVE_PROTO)
1901
bprintf(bp, " proto");
1902
bprintf(bp, " ip6");
1903
break;
1904
case O_IP4:
1905
if (state->flags & HAVE_PROTO)
1906
bprintf(bp, " proto");
1907
bprintf(bp, " ip4");
1908
break;
1909
case O_ICMP6TYPE:
1910
print_icmp6types(bp, insntoc(cmd, u32));
1911
break;
1912
case O_EXT_HDR:
1913
print_ext6hdr(bp, cmd);
1914
break;
1915
case O_TAGGED:
1916
if (F_LEN(cmd) == 1)
1917
bprint_uint_arg(bp, " tagged ", cmd->arg1);
1918
else
1919
print_newports(bp, insntoc(cmd, u16),
1920
0, O_TAGGED);
1921
break;
1922
case O_SKIP_ACTION:
1923
bprintf(bp, " defer-immediate-action");
1924
break;
1925
case O_MARK:
1926
bprintf(bp, " mark");
1927
if (cmd->arg1 == IP_FW_TARG)
1928
bprintf(bp, " tablearg");
1929
else
1930
bprintf(bp, " %#x", insntoc(cmd, u32)->d[0]);
1931
1932
if (insntoc(cmd, u32)->d[1] != 0xFFFFFFFF)
1933
bprintf(bp, ":%#x", insntoc(cmd, u32)->d[1]);
1934
break;
1935
1936
default:
1937
bprintf(bp, " [opcode %d len %d]", cmd->opcode,
1938
cmd->len);
1939
}
1940
if (cmd->len & F_OR) {
1941
bprintf(bp, " or");
1942
state->or_block = 1;
1943
} else if (state->or_block != 0) {
1944
bprintf(bp, " }");
1945
state->or_block = 0;
1946
}
1947
mark_printed(state, cmd);
1948
1949
return (1);
1950
}
1951
1952
static ipfw_insn *
1953
print_opcode(struct buf_pr *bp, struct format_opts *fo,
1954
struct show_state *state, int opcode)
1955
{
1956
ipfw_insn *cmd;
1957
int l;
1958
1959
for (l = state->rule->act_ofs, cmd = state->rule->cmd;
1960
l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1961
/* We use zero opcode to print the rest of options */
1962
if (opcode >= 0 && cmd->opcode != opcode)
1963
continue;
1964
/*
1965
* Skip O_NOP, when we printing the rest
1966
* of options, it will be handled separately.
1967
*/
1968
if (cmd->opcode == O_NOP && opcode != O_NOP)
1969
continue;
1970
if (!print_instruction(bp, fo, state, cmd))
1971
continue;
1972
return (cmd);
1973
}
1974
return (NULL);
1975
}
1976
1977
static void
1978
print_fwd(struct buf_pr *bp, const ipfw_insn *cmd)
1979
{
1980
char buf[INET6_ADDRSTRLEN + IF_NAMESIZE + 2];
1981
const ipfw_insn_sa6 *sa6;
1982
const ipfw_insn_sa *sa;
1983
uint16_t port;
1984
1985
if (cmd->opcode == O_FORWARD_IP) {
1986
sa = insntoc(cmd, sa);
1987
port = sa->sa.sin_port;
1988
if (sa->sa.sin_addr.s_addr == INADDR_ANY)
1989
bprintf(bp, "fwd tablearg");
1990
else
1991
bprintf(bp, "fwd %s", inet_ntoa(sa->sa.sin_addr));
1992
} else {
1993
sa6 = insntoc(cmd, sa6);
1994
port = sa6->sa.sin6_port;
1995
bprintf(bp, "fwd ");
1996
if (getnameinfo((const struct sockaddr *)&sa6->sa,
1997
sizeof(struct sockaddr_in6), buf, sizeof(buf), NULL, 0,
1998
NI_NUMERICHOST) == 0)
1999
bprintf(bp, "%s", buf);
2000
}
2001
if (port != 0)
2002
bprintf(bp, ",%u", port);
2003
}
2004
2005
static void
2006
print_logdst(struct buf_pr *bp, uint16_t arg1)
2007
{
2008
char const *comma = "";
2009
2010
bprintf(bp, " logdst ");
2011
if (arg1 & IPFW_LOG_SYSLOG) {
2012
bprintf(bp, "%ssyslog", comma);
2013
comma = ",";
2014
}
2015
if (arg1 & IPFW_LOG_IPFW0) {
2016
bprintf(bp, "%sbpf", comma);
2017
comma = ",";
2018
}
2019
if (arg1 & IPFW_LOG_RTSOCK) {
2020
bprintf(bp, "%srtsock", comma);
2021
comma = ",";
2022
}
2023
}
2024
2025
static int
2026
print_action_instruction(struct buf_pr *bp, const struct format_opts *fo,
2027
struct show_state *state, const ipfw_insn *cmd)
2028
{
2029
const char *s;
2030
2031
if (is_printed_opcode(state, cmd))
2032
return (0);
2033
switch (cmd->opcode) {
2034
case O_CHECK_STATE:
2035
bprintf(bp, "check-state");
2036
if (insntoc(cmd, kidx)->kidx != 0)
2037
s = object_search_ctlv(fo->tstate,
2038
insntoc(cmd, kidx)->kidx,
2039
IPFW_TLV_STATE_NAME);
2040
else
2041
s = NULL;
2042
bprintf(bp, " :%s", s ? s: "any");
2043
break;
2044
case O_ACCEPT:
2045
bprintf(bp, "allow");
2046
break;
2047
case O_COUNT:
2048
bprintf(bp, "count");
2049
break;
2050
case O_DENY:
2051
bprintf(bp, "deny");
2052
break;
2053
case O_REJECT:
2054
if (cmd->arg1 == ICMP_REJECT_RST)
2055
bprintf(bp, "reset");
2056
else if (cmd->arg1 == ICMP_REJECT_ABORT)
2057
bprintf(bp, "abort");
2058
else if (cmd->arg1 == ICMP_UNREACH_HOST)
2059
bprintf(bp, "reject");
2060
else if (cmd->arg1 == ICMP_UNREACH_NEEDFRAG &&
2061
cmd->len == F_INSN_SIZE(ipfw_insn_u16))
2062
bprintf(bp, "needfrag %u",
2063
insntoc(cmd, u16)->ports[0]);
2064
else
2065
print_reject_code(bp, cmd->arg1);
2066
break;
2067
case O_UNREACH6:
2068
if (cmd->arg1 == ICMP6_UNREACH_RST)
2069
bprintf(bp, "reset6");
2070
else if (cmd->arg1 == ICMP6_UNREACH_ABORT)
2071
bprintf(bp, "abort6");
2072
else
2073
print_unreach6_code(bp, cmd->arg1);
2074
break;
2075
case O_SKIPTO:
2076
bprint_uint_arg(bp, "skipto ", insntoc(cmd, u32)->d[0]);
2077
break;
2078
case O_PIPE:
2079
bprint_uint_arg(bp, "pipe ", cmd->arg1);
2080
break;
2081
case O_QUEUE:
2082
bprint_uint_arg(bp, "queue ", cmd->arg1);
2083
break;
2084
case O_DIVERT:
2085
bprint_uint_arg(bp, "divert ", cmd->arg1);
2086
break;
2087
case O_TEE:
2088
bprint_uint_arg(bp, "tee ", cmd->arg1);
2089
break;
2090
case O_NETGRAPH:
2091
bprint_uint_arg(bp, "netgraph ", cmd->arg1);
2092
break;
2093
case O_NGTEE:
2094
bprint_uint_arg(bp, "ngtee ", cmd->arg1);
2095
break;
2096
case O_FORWARD_IP:
2097
case O_FORWARD_IP6:
2098
print_fwd(bp, cmd);
2099
break;
2100
case O_LOG:
2101
bprintf(bp, " log");
2102
if (insntoc(cmd, log)->max_log > 0)
2103
bprintf(bp, " logamount %d",
2104
insntoc(cmd, log)->max_log);
2105
if (cmd->arg1 != IPFW_LOG_DEFAULT)
2106
print_logdst(bp, cmd->arg1);
2107
break;
2108
case O_ALTQ:
2109
#ifndef NO_ALTQ
2110
print_altq_cmd(bp, insntoc(cmd, altq));
2111
#endif
2112
break;
2113
case O_TAG:
2114
bprint_uint_arg(bp, cmd->len & F_NOT ? " untag ":
2115
" tag ", cmd->arg1);
2116
break;
2117
case O_NAT:
2118
if (cmd->arg1 != IP_FW_NAT44_GLOBAL)
2119
bprint_uint_arg(bp, "nat ", cmd->arg1);
2120
else
2121
bprintf(bp, "nat global");
2122
break;
2123
case O_SETFIB:
2124
if (cmd->arg1 == IP_FW_TARG)
2125
bprint_uint_arg(bp, "setfib ", cmd->arg1);
2126
else
2127
bprintf(bp, "setfib %u", cmd->arg1 & 0x7FFF);
2128
break;
2129
case O_EXTERNAL_ACTION:
2130
/*
2131
* The external action can consists of two following
2132
* each other opcodes - O_EXTERNAL_ACTION and
2133
* O_EXTERNAL_INSTANCE. The first contains the ID of
2134
* name of external action. The second contains the ID
2135
* of name of external action instance.
2136
* NOTE: in case when external action has no named
2137
* instances support, the second opcode isn't needed.
2138
*/
2139
state->eaction = insntoc(cmd, kidx);
2140
s = object_search_ctlv(fo->tstate,
2141
state->eaction->kidx,
2142
IPFW_TLV_EACTION);
2143
if (match_token(rule_eactions, s) != -1)
2144
bprintf(bp, "%s", s);
2145
else
2146
bprintf(bp, "eaction %s", s);
2147
break;
2148
case O_EXTERNAL_INSTANCE:
2149
if (state->eaction == NULL)
2150
break;
2151
/*
2152
* XXX: we need to teach ipfw(9) to rewrite opcodes
2153
* in the user buffer on rule addition. When we add
2154
* the rule, we specify zero TLV type for
2155
* O_EXTERNAL_INSTANCE object. To show correct
2156
* rule after `ipfw add` we need to search instance
2157
* name with zero type. But when we do `ipfw show`
2158
* we calculate TLV type using IPFW_TLV_EACTION_NAME()
2159
* macro.
2160
*/
2161
s = object_search_ctlv(fo->tstate,
2162
insntoc(cmd, kidx)->kidx, 0);
2163
if (s == NULL)
2164
s = object_search_ctlv(fo->tstate,
2165
insntoc(cmd, kidx)->kidx, IPFW_TLV_EACTION_NAME(
2166
state->eaction->kidx));
2167
bprintf(bp, " %s", s);
2168
break;
2169
case O_EXTERNAL_DATA:
2170
if (state->eaction == NULL)
2171
break;
2172
/*
2173
* Currently we support data formatting only for
2174
* external data with datalen u16. For unknown data
2175
* print its size in bytes.
2176
*/
2177
if (cmd->len == F_INSN_SIZE(ipfw_insn))
2178
bprintf(bp, " %u", cmd->arg1);
2179
else
2180
bprintf(bp, " %ubytes",
2181
(unsigned)(cmd->len * sizeof(uint32_t)));
2182
break;
2183
case O_SETDSCP:
2184
if (cmd->arg1 == IP_FW_TARG) {
2185
bprintf(bp, "setdscp tablearg");
2186
break;
2187
}
2188
s = match_value(f_ipdscp, cmd->arg1 & 0x3F);
2189
if (s != NULL)
2190
bprintf(bp, "setdscp %s", s);
2191
else
2192
bprintf(bp, "setdscp %u", cmd->arg1 & 0x3F);
2193
break;
2194
case O_REASS:
2195
bprintf(bp, "reass");
2196
break;
2197
case O_CALLRETURN:
2198
if (cmd->len & F_NOT) {
2199
s = match_value(return_types, cmd->arg1);
2200
bprintf(bp, "return %s", s ? s: "<invalid>");
2201
} else
2202
bprint_uint_arg(bp, "call ", insntoc(cmd, u32)->d[0]);
2203
break;
2204
case O_SETMARK:
2205
if (cmd->arg1 == IP_FW_TARG) {
2206
bprintf(bp, "setmark tablearg");
2207
break;
2208
}
2209
bprintf(bp, "setmark %#x", insntoc(cmd, u32)->d[0]);
2210
break;
2211
default:
2212
bprintf(bp, "** unrecognized action %d len %d ",
2213
cmd->opcode, cmd->len);
2214
}
2215
mark_printed(state, cmd);
2216
2217
return (1);
2218
}
2219
2220
2221
static ipfw_insn *
2222
print_action(struct buf_pr *bp, struct format_opts *fo,
2223
struct show_state *state, uint8_t opcode)
2224
{
2225
ipfw_insn *cmd;
2226
int l;
2227
2228
for (l = state->rule->cmd_len - state->rule->act_ofs,
2229
cmd = ACTION_PTR(state->rule); l > 0;
2230
l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2231
if (cmd->opcode != opcode)
2232
continue;
2233
if (!print_action_instruction(bp, fo, state, cmd))
2234
continue;
2235
return (cmd);
2236
}
2237
return (NULL);
2238
}
2239
2240
static void
2241
print_proto(struct buf_pr *bp, struct format_opts *fo,
2242
struct show_state *state)
2243
{
2244
ipfw_insn *cmd;
2245
int l, proto, ip4, ip6;
2246
2247
/* Count all O_PROTO, O_IP4, O_IP6 instructions. */
2248
proto = ip4 = ip6 = 0;
2249
for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2250
l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2251
switch (cmd->opcode) {
2252
case O_PROTO:
2253
proto++;
2254
break;
2255
case O_IP4:
2256
ip4 = 1;
2257
if (cmd->len & F_OR)
2258
ip4++;
2259
break;
2260
case O_IP6:
2261
ip6 = 1;
2262
if (cmd->len & F_OR)
2263
ip6++;
2264
break;
2265
default:
2266
continue;
2267
}
2268
}
2269
if (proto == 0 && ip4 == 0 && ip6 == 0) {
2270
state->proto = IPPROTO_IP;
2271
state->flags |= HAVE_PROTO;
2272
bprintf(bp, " ip");
2273
return;
2274
}
2275
/* To handle the case { ip4 or ip6 }, print opcode with F_OR first */
2276
cmd = NULL;
2277
if (ip4 || ip6)
2278
cmd = print_opcode(bp, fo, state, ip4 > ip6 ? O_IP4: O_IP6);
2279
if (cmd != NULL && (cmd->len & F_OR))
2280
cmd = print_opcode(bp, fo, state, ip4 > ip6 ? O_IP6: O_IP4);
2281
if (cmd == NULL || (cmd->len & F_OR))
2282
for (l = proto; l > 0; l--) {
2283
cmd = print_opcode(bp, fo, state, O_PROTO);
2284
if (cmd == NULL || (cmd->len & F_OR) == 0)
2285
break;
2286
}
2287
/* Initialize proto, it is used by print_newports() */
2288
state->flags |= HAVE_PROTO;
2289
if (state->proto == 0 && ip6 != 0)
2290
state->proto = IPPROTO_IPV6;
2291
}
2292
2293
static int
2294
match_opcode(int opcode, const int opcodes[], size_t nops)
2295
{
2296
size_t i;
2297
2298
for (i = 0; i < nops; i++)
2299
if (opcode == opcodes[i])
2300
return (1);
2301
return (0);
2302
}
2303
2304
static void
2305
print_address(struct buf_pr *bp, struct format_opts *fo,
2306
struct show_state *state, const int opcodes[], size_t nops, int portop,
2307
int flag)
2308
{
2309
ipfw_insn *cmd;
2310
int count, l, portcnt, pf;
2311
2312
count = portcnt = 0;
2313
for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2314
l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2315
if (match_opcode(cmd->opcode, opcodes, nops)) {
2316
/*
2317
* Special handling for O_IP_DST_LOOKUP when
2318
* lookup type is not LOOKUP_NONE.
2319
*/
2320
if (cmd->opcode == O_IP_DST_LOOKUP &&
2321
IPFW_LOOKUP_TYPE(cmd) != LOOKUP_NONE)
2322
continue;
2323
count++;
2324
} else if (cmd->opcode == portop)
2325
portcnt++;
2326
}
2327
if (count == 0)
2328
bprintf(bp, " any");
2329
for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2330
l > 0 && count > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2331
if (!match_opcode(cmd->opcode, opcodes, nops))
2332
continue;
2333
print_instruction(bp, fo, state, cmd);
2334
if ((cmd->len & F_OR) == 0)
2335
break;
2336
count--;
2337
}
2338
/*
2339
* If several O_IP_?PORT opcodes specified, leave them to the
2340
* options section.
2341
*/
2342
if (portcnt == 1) {
2343
for (l = state->rule->act_ofs, cmd = state->rule->cmd, pf = 0;
2344
l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2345
if (cmd->opcode != portop) {
2346
pf = (cmd->len & F_OR);
2347
continue;
2348
}
2349
/* Print opcode iff it is not in OR block. */
2350
if (pf == 0 && (cmd->len & F_OR) == 0)
2351
print_instruction(bp, fo, state, cmd);
2352
break;
2353
}
2354
}
2355
state->flags |= flag;
2356
}
2357
2358
static const int action_opcodes[] = {
2359
O_CHECK_STATE, O_ACCEPT, O_COUNT, O_DENY, O_REJECT,
2360
O_UNREACH6, O_SKIPTO, O_PIPE, O_QUEUE, O_DIVERT, O_TEE,
2361
O_NETGRAPH, O_NGTEE, O_FORWARD_IP, O_FORWARD_IP6, O_NAT,
2362
O_SETFIB, O_SETDSCP, O_REASS, O_CALLRETURN, O_SETMARK,
2363
/* keep the following opcodes at the end of the list */
2364
O_EXTERNAL_ACTION, O_EXTERNAL_INSTANCE, O_EXTERNAL_DATA
2365
};
2366
2367
static const int modifier_opcodes[] = {
2368
O_LOG, O_ALTQ, O_TAG
2369
};
2370
2371
static const int src_opcodes[] = {
2372
O_IP_SRC, O_IP_SRC_LOOKUP, O_IP_SRC_MASK, O_IP_SRC_ME,
2373
O_IP_SRC_SET, O_IP6_SRC, O_IP6_SRC_MASK, O_IP6_SRC_ME
2374
};
2375
2376
static const int dst_opcodes[] = {
2377
O_IP_DST, O_IP_DST_LOOKUP, O_IP_DST_MASK, O_IP_DST_ME,
2378
O_IP_DST_SET, O_IP6_DST, O_IP6_DST_MASK, O_IP6_DST_ME
2379
};
2380
2381
#if IPFW_DEFAULT_RULE > 65535
2382
#define RULENUM_FORMAT "%06d"
2383
#else
2384
#define RULENUM_FORMAT "%05d"
2385
#endif
2386
2387
static void
2388
show_static_rule(struct cmdline_opts *co, struct format_opts *fo,
2389
struct buf_pr *bp, struct ip_fw_rule *rule, struct ip_fw_bcounter *cntr)
2390
{
2391
static int twidth = 0;
2392
struct show_state state;
2393
ipfw_insn *cmd;
2394
size_t i;
2395
2396
/* Print # DISABLED or skip the rule */
2397
if ((fo->set_mask & (1 << rule->set)) == 0) {
2398
/* disabled mask */
2399
if (!co->show_sets)
2400
return;
2401
else
2402
bprintf(bp, "# DISABLED ");
2403
}
2404
if (init_show_state(&state, rule) != 0) {
2405
warn("init_show_state() failed");
2406
return;
2407
}
2408
2409
bprintf(bp, RULENUM_FORMAT " ", rule->rulenum);
2410
2411
/* only if counters are available */
2412
if (cntr != NULL) {
2413
/* Print counters if enabled */
2414
if (fo->pcwidth > 0 || fo->bcwidth > 0) {
2415
pr_u64(bp, &cntr->pcnt, fo->pcwidth);
2416
pr_u64(bp, &cntr->bcnt, fo->bcwidth);
2417
}
2418
2419
/* Print timestamp */
2420
if (co->do_time == TIMESTAMP_NUMERIC)
2421
bprintf(bp, "%10u ", cntr->timestamp);
2422
else if (co->do_time == TIMESTAMP_STRING) {
2423
char timestr[30];
2424
time_t t = (time_t)0;
2425
2426
if (twidth == 0) {
2427
strcpy(timestr, ctime(&t));
2428
*strchr(timestr, '\n') = '\0';
2429
twidth = strlen(timestr);
2430
}
2431
if (cntr->timestamp > 0) {
2432
t = _long_to_time(cntr->timestamp);
2433
2434
strcpy(timestr, ctime(&t));
2435
*strchr(timestr, '\n') = '\0';
2436
bprintf(bp, "%s ", timestr);
2437
} else {
2438
bprintf(bp, "%*s ", twidth, "");
2439
}
2440
}
2441
}
2442
2443
/* Print set number */
2444
if (co->show_sets)
2445
bprintf(bp, "set %d ", rule->set);
2446
2447
/* Print the optional "match probability" */
2448
cmd = print_opcode(bp, fo, &state, O_PROB);
2449
/* Print rule action */
2450
for (i = 0; i < nitems(action_opcodes); i++) {
2451
cmd = print_action(bp, fo, &state, action_opcodes[i]);
2452
if (cmd == NULL)
2453
continue;
2454
/* Handle special cases */
2455
switch (cmd->opcode) {
2456
case O_CHECK_STATE:
2457
goto end;
2458
case O_EXTERNAL_ACTION:
2459
case O_EXTERNAL_INSTANCE:
2460
/* External action can have several instructions */
2461
continue;
2462
}
2463
break;
2464
}
2465
/* Print rule modifiers */
2466
for (i = 0; i < nitems(modifier_opcodes); i++)
2467
print_action(bp, fo, &state, modifier_opcodes[i]);
2468
/*
2469
* Print rule body
2470
*/
2471
if (co->comment_only != 0)
2472
goto end;
2473
2474
if (rule->flags & IPFW_RULE_JUSTOPTS) {
2475
state.flags |= HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP;
2476
/*
2477
* Print `proto ip` if all opcodes has been already printed.
2478
*/
2479
if (memchr(state.printed, 0, rule->act_ofs) == NULL) {
2480
bprintf(bp, " proto ip");
2481
goto end;
2482
}
2483
goto justopts;
2484
}
2485
2486
print_proto(bp, fo, &state);
2487
if (co->do_compact != 0 && (rule->flags & IPFW_RULE_NOOPT))
2488
goto justopts;
2489
2490
/* Print source */
2491
bprintf(bp, " from");
2492
print_address(bp, fo, &state, src_opcodes, nitems(src_opcodes),
2493
O_IP_SRCPORT, HAVE_SRCIP);
2494
2495
/* Print destination */
2496
bprintf(bp, " to");
2497
print_address(bp, fo, &state, dst_opcodes, nitems(dst_opcodes),
2498
O_IP_DSTPORT, HAVE_DSTIP);
2499
2500
justopts:
2501
/* Print the rest of options */
2502
while (print_opcode(bp, fo, &state, -1))
2503
;
2504
end:
2505
/* Print comment at the end */
2506
cmd = print_opcode(bp, fo, &state, O_NOP);
2507
if (co->comment_only != 0 && cmd == NULL)
2508
bprintf(bp, " // ...");
2509
bprintf(bp, "\n");
2510
free_show_state(&state);
2511
}
2512
2513
static void
2514
show_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2515
struct buf_pr *bp, ipfw_dyn_rule *d)
2516
{
2517
struct protoent *pe;
2518
struct in_addr a;
2519
char buf[INET6_ADDRSTRLEN];
2520
2521
if (!d->expire && !(d->type == O_LIMIT_PARENT))
2522
return;
2523
2524
bprintf(bp, RULENUM_FORMAT, d->rulenum);
2525
if (fo->pcwidth > 0 || fo->bcwidth > 0) {
2526
bprintf(bp, " ");
2527
pr_u64(bp, &d->pcnt, fo->pcwidth);
2528
pr_u64(bp, &d->bcnt, fo->bcwidth);
2529
bprintf(bp, "(%ds)", d->expire);
2530
}
2531
switch (d->type) {
2532
case O_LIMIT_PARENT:
2533
bprintf(bp, " PARENT %u", d->count);
2534
break;
2535
case O_LIMIT:
2536
bprintf(bp, " LIMIT");
2537
break;
2538
case O_KEEP_STATE: /* bidir, no mask */
2539
bprintf(bp, " STATE");
2540
break;
2541
}
2542
2543
if ((pe = getprotobynumber(d->id.proto)) != NULL)
2544
bprintf(bp, " %s", pe->p_name);
2545
else
2546
bprintf(bp, " proto %u", d->id.proto);
2547
2548
if (d->id.addr_type == 4) {
2549
a.s_addr = htonl(d->id.src_ip);
2550
bprintf(bp, " %s %d", inet_ntoa(a), d->id.src_port);
2551
2552
a.s_addr = htonl(d->id.dst_ip);
2553
bprintf(bp, " <-> %s %d", inet_ntoa(a), d->id.dst_port);
2554
} else if (d->id.addr_type == 6) {
2555
bprintf(bp, " %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
2556
sizeof(buf)), d->id.src_port);
2557
bprintf(bp, " <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6,
2558
buf, sizeof(buf)), d->id.dst_port);
2559
} else
2560
bprintf(bp, " UNKNOWN <-> UNKNOWN");
2561
if (d->kidx != 0)
2562
bprintf(bp, " :%s", object_search_ctlv(fo->tstate,
2563
d->kidx, IPFW_TLV_STATE_NAME));
2564
2565
#define BOTH_SYN (TH_SYN | (TH_SYN << 8))
2566
#define BOTH_FIN (TH_FIN | (TH_FIN << 8))
2567
if (co->verbose) {
2568
bprintf(bp, " state 0x%08x%s", d->state,
2569
d->state ? " ": ",");
2570
if (d->state & IPFW_DYN_ORPHANED)
2571
bprintf(bp, "ORPHANED,");
2572
if ((d->state & BOTH_SYN) == BOTH_SYN)
2573
bprintf(bp, "BOTH_SYN,");
2574
else {
2575
if (d->state & TH_SYN)
2576
bprintf(bp, "F_SYN,");
2577
if (d->state & (TH_SYN << 8))
2578
bprintf(bp, "R_SYN,");
2579
}
2580
if ((d->state & BOTH_FIN) == BOTH_FIN)
2581
bprintf(bp, "BOTH_FIN,");
2582
else {
2583
if (d->state & TH_FIN)
2584
bprintf(bp, "F_FIN,");
2585
if (d->state & (TH_FIN << 8))
2586
bprintf(bp, "R_FIN,");
2587
}
2588
bprintf(bp, " f_ack 0x%x, r_ack 0x%x", d->ack_fwd,
2589
d->ack_rev);
2590
}
2591
}
2592
2593
static int
2594
do_range_cmd(int cmd, ipfw_range_tlv *rt)
2595
{
2596
ipfw_range_header rh;
2597
size_t sz;
2598
2599
memset(&rh, 0, sizeof(rh));
2600
memcpy(&rh.range, rt, sizeof(*rt));
2601
rh.range.head.length = sizeof(*rt);
2602
rh.range.head.type = IPFW_TLV_RANGE;
2603
sz = sizeof(rh);
2604
2605
if (do_get3(cmd, &rh.opheader, &sz) != 0)
2606
return (-1);
2607
/* Save number of matched objects */
2608
rt->new_set = rh.range.new_set;
2609
return (0);
2610
}
2611
2612
/*
2613
* This one handles all set-related commands
2614
* ipfw set { show | enable | disable }
2615
* ipfw set swap X Y
2616
* ipfw set move X to Y
2617
* ipfw set move rule X to Y
2618
*/
2619
void
2620
ipfw_sets_handler(char *av[])
2621
{
2622
ipfw_range_tlv rt;
2623
const char *msg;
2624
size_t size;
2625
uint32_t masks[2], rulenum;
2626
int i;
2627
uint8_t cmd;
2628
2629
av++;
2630
memset(&rt, 0, sizeof(rt));
2631
2632
if (av[0] == NULL)
2633
errx(EX_USAGE, "set needs command");
2634
if (_substrcmp(*av, "show") == 0) {
2635
struct format_opts fo;
2636
ipfw_cfg_lheader *cfg;
2637
2638
memset(&fo, 0, sizeof(fo));
2639
if (ipfw_get_config(&g_co, &fo, &cfg, &size) != 0)
2640
err(EX_OSERR, "requesting config failed");
2641
2642
for (i = 0, msg = "disable"; i < RESVD_SET; i++)
2643
if ((cfg->set_mask & (1<<i)) == 0) {
2644
printf("%s %d", msg, i);
2645
msg = "";
2646
}
2647
msg = (cfg->set_mask != (uint32_t)-1) ? " enable" : "enable";
2648
for (i = 0; i < RESVD_SET; i++)
2649
if ((cfg->set_mask & (1<<i)) != 0) {
2650
printf("%s %d", msg, i);
2651
msg = "";
2652
}
2653
printf("\n");
2654
free(cfg);
2655
} else if (_substrcmp(*av, "swap") == 0) {
2656
av++;
2657
if ( av[0] == NULL || av[1] == NULL )
2658
errx(EX_USAGE, "set swap needs 2 set numbers\n");
2659
rt.set = atoi(av[0]);
2660
rt.new_set = atoi(av[1]);
2661
if (!isdigit(*(av[0])) || rt.set > RESVD_SET)
2662
errx(EX_DATAERR, "invalid set number %s\n", av[0]);
2663
if (!isdigit(*(av[1])) || rt.new_set > RESVD_SET)
2664
errx(EX_DATAERR, "invalid set number %s\n", av[1]);
2665
i = do_range_cmd(IP_FW_SET_SWAP, &rt);
2666
} else if (_substrcmp(*av, "move") == 0) {
2667
av++;
2668
if (av[0] && _substrcmp(*av, "rule") == 0) {
2669
rt.flags = IPFW_RCFLAG_RANGE; /* move rules to new set */
2670
cmd = IP_FW_XMOVE;
2671
av++;
2672
} else
2673
cmd = IP_FW_SET_MOVE; /* Move set to new one */
2674
if (av[0] == NULL || av[1] == NULL || av[2] == NULL ||
2675
av[3] != NULL || _substrcmp(av[1], "to") != 0)
2676
errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
2677
rulenum = (uint32_t)strtoul(av[0], NULL, 10);
2678
rt.new_set = atoi(av[2]);
2679
if (cmd == IP_FW_XMOVE) {
2680
rt.start_rule = rulenum;
2681
rt.end_rule = rulenum;
2682
} else
2683
rt.set = rulenum;
2684
rt.new_set = atoi(av[2]);
2685
if (!isdigit(*(av[0])) || (cmd == 3 && rt.set > RESVD_SET) ||
2686
(cmd == 2 && rt.start_rule == IPFW_DEFAULT_RULE) )
2687
errx(EX_DATAERR, "invalid source number %s\n", av[0]);
2688
if (!isdigit(*(av[2])) || rt.new_set > RESVD_SET)
2689
errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
2690
i = do_range_cmd(cmd, &rt);
2691
if (i < 0)
2692
err(EX_OSERR, "failed to move %s",
2693
cmd == IP_FW_SET_MOVE ? "set": "rule");
2694
} else if (_substrcmp(*av, "disable") == 0 ||
2695
_substrcmp(*av, "enable") == 0 ) {
2696
int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
2697
2698
av++;
2699
masks[0] = masks[1] = 0;
2700
2701
while (av[0]) {
2702
if (isdigit(**av)) {
2703
i = atoi(*av);
2704
if (i < 0 || i > RESVD_SET)
2705
errx(EX_DATAERR,
2706
"invalid set number %d\n", i);
2707
masks[which] |= (1<<i);
2708
} else if (_substrcmp(*av, "disable") == 0)
2709
which = 0;
2710
else if (_substrcmp(*av, "enable") == 0)
2711
which = 1;
2712
else
2713
errx(EX_DATAERR,
2714
"invalid set command %s\n", *av);
2715
av++;
2716
}
2717
if ( (masks[0] & masks[1]) != 0 )
2718
errx(EX_DATAERR,
2719
"cannot enable and disable the same set\n");
2720
2721
rt.set = masks[0];
2722
rt.new_set = masks[1];
2723
i = do_range_cmd(IP_FW_SET_ENABLE, &rt);
2724
if (i)
2725
warn("set enable/disable: setsockopt(IP_FW_SET_ENABLE)");
2726
} else
2727
errx(EX_USAGE, "invalid set command %s\n", *av);
2728
}
2729
2730
static void
2731
manage_skipto_cache(int op)
2732
{
2733
ipfw_cmd_header req;
2734
2735
memset(&req, 0, sizeof(req));
2736
req.size = sizeof(req);
2737
req.cmd = op ? SKIPTO_CACHE_ENABLE : SKIPTO_CACHE_DISABLE;
2738
2739
do_set3(IP_FW_SKIPTO_CACHE, &req.opheader, sizeof(req));
2740
}
2741
2742
void
2743
ipfw_sysctl_handler(char *av[], int which)
2744
{
2745
av++;
2746
2747
if (av[0] == NULL) {
2748
warnx("missing keyword to enable/disable\n");
2749
} else if (_substrcmp(*av, "firewall") == 0) {
2750
sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
2751
&which, sizeof(which));
2752
sysctlbyname("net.inet6.ip6.fw.enable", NULL, 0,
2753
&which, sizeof(which));
2754
} else if (_substrcmp(*av, "one_pass") == 0) {
2755
sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
2756
&which, sizeof(which));
2757
} else if (_substrcmp(*av, "debug") == 0) {
2758
sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
2759
&which, sizeof(which));
2760
} else if (_substrcmp(*av, "verbose") == 0) {
2761
sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
2762
&which, sizeof(which));
2763
} else if (_substrcmp(*av, "dyn_keepalive") == 0) {
2764
sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
2765
&which, sizeof(which));
2766
} else if (_substrcmp(*av, "skipto_cache") == 0) {
2767
manage_skipto_cache(which);
2768
#ifndef NO_ALTQ
2769
} else if (_substrcmp(*av, "altq") == 0) {
2770
altq_set_enabled(which);
2771
#endif
2772
} else {
2773
warnx("unrecognize enable/disable keyword: %s\n", *av);
2774
}
2775
}
2776
2777
typedef void state_cb(struct cmdline_opts *co, struct format_opts *fo,
2778
void *arg, void *state);
2779
2780
static void
2781
prepare_format_dyn(struct cmdline_opts *co, struct format_opts *fo,
2782
void *arg __unused, void *_state)
2783
{
2784
ipfw_dyn_rule *d;
2785
int width;
2786
2787
d = (ipfw_dyn_rule *)_state;
2788
/* Count _ALL_ states */
2789
fo->dcnt++;
2790
2791
if (fo->show_counters == 0)
2792
return;
2793
2794
/* skip states from another set */
2795
if (co->use_set != 0 && d->set != co->use_set - 1)
2796
return;
2797
2798
width = pr_u64(NULL, &d->pcnt, 0);
2799
if (width > fo->pcwidth)
2800
fo->pcwidth = width;
2801
2802
width = pr_u64(NULL, &d->bcnt, 0);
2803
if (width > fo->bcwidth)
2804
fo->bcwidth = width;
2805
}
2806
2807
static int
2808
foreach_state(struct cmdline_opts *co, struct format_opts *fo,
2809
caddr_t base, size_t sz, state_cb dyn_bc, void *dyn_arg)
2810
{
2811
int ttype;
2812
state_cb *fptr;
2813
void *farg;
2814
ipfw_obj_tlv *tlv;
2815
ipfw_obj_ctlv *ctlv;
2816
2817
fptr = NULL;
2818
ttype = 0;
2819
2820
while (sz > 0) {
2821
ctlv = (ipfw_obj_ctlv *)base;
2822
switch (ctlv->head.type) {
2823
case IPFW_TLV_DYNSTATE_LIST:
2824
base += sizeof(*ctlv);
2825
sz -= sizeof(*ctlv);
2826
ttype = IPFW_TLV_DYN_ENT;
2827
fptr = dyn_bc;
2828
farg = dyn_arg;
2829
break;
2830
default:
2831
return (sz);
2832
}
2833
2834
while (sz > 0) {
2835
tlv = (ipfw_obj_tlv *)base;
2836
if (tlv->type != ttype)
2837
break;
2838
2839
fptr(co, fo, farg, tlv + 1);
2840
sz -= tlv->length;
2841
base += tlv->length;
2842
}
2843
}
2844
2845
return (sz);
2846
}
2847
2848
static void
2849
prepare_format_opts(struct cmdline_opts *co, struct format_opts *fo,
2850
ipfw_obj_tlv *rtlv, int rcnt, caddr_t dynbase, size_t dynsz)
2851
{
2852
int bcwidth, pcwidth, width;
2853
int n;
2854
struct ip_fw_bcounter *cntr;
2855
struct ip_fw_rule *r;
2856
2857
bcwidth = 0;
2858
pcwidth = 0;
2859
if (fo->show_counters != 0) {
2860
for (n = 0; n < rcnt; n++,
2861
rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2862
cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2863
r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2864
/* skip rules from another set */
2865
if (co->use_set && r->set != co->use_set - 1)
2866
continue;
2867
2868
/* packet counter */
2869
width = pr_u64(NULL, &cntr->pcnt, 0);
2870
if (width > pcwidth)
2871
pcwidth = width;
2872
2873
/* byte counter */
2874
width = pr_u64(NULL, &cntr->bcnt, 0);
2875
if (width > bcwidth)
2876
bcwidth = width;
2877
}
2878
}
2879
fo->bcwidth = bcwidth;
2880
fo->pcwidth = pcwidth;
2881
2882
fo->dcnt = 0;
2883
if (co->do_dynamic && dynsz > 0)
2884
foreach_state(co, fo, dynbase, dynsz, prepare_format_dyn, NULL);
2885
}
2886
2887
static int
2888
list_static_range(struct cmdline_opts *co, struct format_opts *fo,
2889
struct buf_pr *bp, ipfw_obj_tlv *rtlv, int rcnt)
2890
{
2891
int n, seen;
2892
struct ip_fw_rule *r;
2893
struct ip_fw_bcounter *cntr;
2894
2895
for (n = seen = 0; n < rcnt; n++,
2896
rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2897
2898
if ((fo->show_counters | fo->show_time) != 0) {
2899
cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2900
r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2901
} else {
2902
cntr = NULL;
2903
r = (struct ip_fw_rule *)(rtlv + 1);
2904
}
2905
if (r->rulenum > fo->last)
2906
break;
2907
if (co->use_set && r->set != co->use_set - 1)
2908
continue;
2909
if (r->rulenum >= fo->first && r->rulenum <= fo->last) {
2910
show_static_rule(co, fo, bp, r, cntr);
2911
printf("%s", bp->buf);
2912
bp_flush(bp);
2913
seen++;
2914
}
2915
}
2916
2917
return (seen);
2918
}
2919
2920
static void
2921
list_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2922
void *_arg, void *_state)
2923
{
2924
ipfw_dyn_rule *d;
2925
struct buf_pr *bp;
2926
2927
d = (ipfw_dyn_rule *)_state;
2928
bp = (struct buf_pr *)_arg;
2929
2930
if (d->rulenum > fo->last)
2931
return;
2932
if (co->use_set != 0 && d->set != co->use_set - 1)
2933
return;
2934
if (d->rulenum >= fo->first) {
2935
show_dyn_state(co, fo, bp, d);
2936
printf("%s\n", bp->buf);
2937
bp_flush(bp);
2938
}
2939
}
2940
2941
static int
2942
list_dyn_range(struct cmdline_opts *co, struct format_opts *fo,
2943
struct buf_pr *bp, caddr_t base, size_t sz)
2944
{
2945
2946
sz = foreach_state(co, fo, base, sz, list_dyn_state, bp);
2947
return (sz);
2948
}
2949
2950
void
2951
ipfw_list(int ac, char *av[], int show_counters)
2952
{
2953
ipfw_cfg_lheader *cfg;
2954
struct format_opts sfo;
2955
size_t sz;
2956
int error;
2957
int lac;
2958
char **lav;
2959
uint32_t rnum;
2960
char *endptr;
2961
2962
if (g_co.test_only) {
2963
fprintf(stderr, "Testing only, list disabled\n");
2964
return;
2965
}
2966
if (g_co.do_pipe) {
2967
dummynet_list(ac, av, show_counters);
2968
return;
2969
}
2970
2971
ac--;
2972
av++;
2973
memset(&sfo, 0, sizeof(sfo));
2974
2975
/* Determine rule range to request */
2976
if (ac > 0) {
2977
for (lac = ac, lav = av; lac != 0; lac--) {
2978
rnum = strtoul(*lav++, &endptr, 10);
2979
if (sfo.first == 0 || rnum < sfo.first)
2980
sfo.first = rnum;
2981
2982
if (*endptr == '-')
2983
rnum = strtoul(endptr + 1, &endptr, 10);
2984
if (sfo.last == 0 || rnum > sfo.last)
2985
sfo.last = rnum;
2986
}
2987
}
2988
2989
/* get configuration from kernel */
2990
cfg = NULL;
2991
sfo.show_counters = show_counters;
2992
sfo.show_time = g_co.do_time;
2993
if (g_co.do_dynamic != 2)
2994
sfo.flags |= IPFW_CFG_GET_STATIC;
2995
if (g_co.do_dynamic != 0)
2996
sfo.flags |= IPFW_CFG_GET_STATES;
2997
if ((sfo.show_counters | sfo.show_time) != 0)
2998
sfo.flags |= IPFW_CFG_GET_COUNTERS;
2999
if (ipfw_get_config(&g_co, &sfo, &cfg, &sz) != 0)
3000
err(EX_OSERR, "retrieving config failed");
3001
3002
error = ipfw_show_config(&g_co, &sfo, cfg, sz, ac, av);
3003
3004
free(cfg);
3005
3006
if (error != EX_OK)
3007
exit(error);
3008
}
3009
3010
static int
3011
ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
3012
ipfw_cfg_lheader *cfg, size_t sz, int ac, char *av[])
3013
{
3014
caddr_t dynbase;
3015
size_t dynsz;
3016
int rcnt;
3017
int exitval = EX_OK;
3018
int lac;
3019
char **lav;
3020
char *endptr;
3021
size_t readsz;
3022
struct buf_pr bp;
3023
ipfw_obj_ctlv *ctlv;
3024
ipfw_obj_tlv *rbase;
3025
3026
/*
3027
* Handle tablenames TLV first, if any
3028
*/
3029
rbase = NULL;
3030
dynbase = NULL;
3031
dynsz = 0;
3032
readsz = sizeof(*cfg);
3033
rcnt = 0;
3034
3035
fo->set_mask = cfg->set_mask;
3036
3037
ctlv = (ipfw_obj_ctlv *)(cfg + 1);
3038
if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
3039
object_sort_ctlv(ctlv);
3040
fo->tstate = ctlv;
3041
readsz += ctlv->head.length;
3042
ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
3043
}
3044
3045
if (cfg->flags & IPFW_CFG_GET_STATIC) {
3046
/* We've requested static rules */
3047
if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
3048
rbase = (ipfw_obj_tlv *)(ctlv + 1);
3049
rcnt = ctlv->count;
3050
readsz += ctlv->head.length;
3051
ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv +
3052
ctlv->head.length);
3053
}
3054
}
3055
3056
if ((cfg->flags & IPFW_CFG_GET_STATES) && (readsz != sz)) {
3057
/* We may have some dynamic states */
3058
dynsz = sz - readsz;
3059
/* Skip empty header */
3060
if (dynsz != sizeof(ipfw_obj_ctlv))
3061
dynbase = (caddr_t)ctlv;
3062
else
3063
dynsz = 0;
3064
}
3065
3066
prepare_format_opts(co, fo, rbase, rcnt, dynbase, dynsz);
3067
bp_alloc(&bp, 4096);
3068
3069
/* if no rule numbers were specified, list all rules */
3070
if (ac == 0) {
3071
fo->first = 0;
3072
fo->last = IPFW_DEFAULT_RULE;
3073
if (cfg->flags & IPFW_CFG_GET_STATIC)
3074
list_static_range(co, fo, &bp, rbase, rcnt);
3075
3076
if (co->do_dynamic && dynsz > 0) {
3077
printf("## Dynamic rules (%d %zu):\n", fo->dcnt,
3078
dynsz);
3079
list_dyn_range(co, fo, &bp, dynbase, dynsz);
3080
}
3081
3082
bp_free(&bp);
3083
return (EX_OK);
3084
}
3085
3086
/* display specific rules requested on command line */
3087
for (lac = ac, lav = av; lac != 0; lac--) {
3088
/* convert command line rule # */
3089
fo->last = fo->first = strtoul(*lav++, &endptr, 10);
3090
if (*endptr == '-')
3091
fo->last = strtoul(endptr + 1, &endptr, 10);
3092
if (*endptr) {
3093
exitval = EX_USAGE;
3094
warnx("invalid rule number: %s", *(lav - 1));
3095
continue;
3096
}
3097
3098
if ((cfg->flags & IPFW_CFG_GET_STATIC) == 0)
3099
continue;
3100
3101
if (list_static_range(co, fo, &bp, rbase, rcnt) == 0) {
3102
/* give precedence to other error(s) */
3103
if (exitval == EX_OK)
3104
exitval = EX_UNAVAILABLE;
3105
if (fo->first == fo->last)
3106
warnx("rule %u does not exist", fo->first);
3107
else
3108
warnx("no rules in range %u-%u",
3109
fo->first, fo->last);
3110
}
3111
}
3112
3113
if (co->do_dynamic && dynsz > 0) {
3114
printf("## Dynamic rules:\n");
3115
for (lac = ac, lav = av; lac != 0; lac--) {
3116
fo->last = fo->first = strtoul(*lav++, &endptr, 10);
3117
if (*endptr == '-')
3118
fo->last = strtoul(endptr+1, &endptr, 10);
3119
if (*endptr)
3120
/* already warned */
3121
continue;
3122
list_dyn_range(co, fo, &bp, dynbase, dynsz);
3123
}
3124
}
3125
3126
bp_free(&bp);
3127
return (exitval);
3128
}
3129
3130
3131
/*
3132
* Retrieves current ipfw configuration of given type
3133
* and stores its pointer to @pcfg.
3134
*
3135
* Caller is responsible for freeing @pcfg.
3136
*
3137
* Returns 0 on success.
3138
*/
3139
3140
static int
3141
ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
3142
ipfw_cfg_lheader **pcfg, size_t *psize)
3143
{
3144
ipfw_cfg_lheader *cfg;
3145
size_t sz;
3146
int i;
3147
3148
3149
if (co->test_only != 0) {
3150
fprintf(stderr, "Testing only, list disabled\n");
3151
return (0);
3152
}
3153
3154
/* Start with some data size */
3155
sz = 4096;
3156
cfg = NULL;
3157
3158
for (i = 0; i < 16; i++) {
3159
if (cfg != NULL)
3160
free(cfg);
3161
if ((cfg = calloc(1, sz)) == NULL)
3162
return (ENOMEM);
3163
3164
cfg->flags = fo->flags;
3165
cfg->start_rule = fo->first;
3166
cfg->end_rule = fo->last;
3167
3168
if (do_get3(IP_FW_XGET, &cfg->opheader, &sz) != 0) {
3169
if (errno != ENOMEM) {
3170
free(cfg);
3171
return (errno);
3172
}
3173
3174
/* Buffer size is not enough. Try to increase */
3175
sz = sz * 2;
3176
if (sz < cfg->size)
3177
sz = cfg->size;
3178
continue;
3179
}
3180
3181
*pcfg = cfg;
3182
*psize = sz;
3183
return (0);
3184
}
3185
3186
free(cfg);
3187
return (ENOMEM);
3188
}
3189
3190
static int
3191
lookup_host (char *host, struct in_addr *ipaddr)
3192
{
3193
struct hostent *he;
3194
3195
if (!inet_aton(host, ipaddr)) {
3196
if ((he = gethostbyname(host)) == NULL)
3197
return(-1);
3198
*ipaddr = *(struct in_addr *)he->h_addr_list[0];
3199
}
3200
return(0);
3201
}
3202
3203
struct tidx {
3204
ipfw_obj_ntlv *idx;
3205
uint32_t count;
3206
uint32_t size;
3207
uint16_t counter;
3208
uint8_t set;
3209
};
3210
3211
int
3212
ipfw_check_object_name(const char *name)
3213
{
3214
int c, i, l;
3215
3216
/*
3217
* Check that name is null-terminated and contains
3218
* valid symbols only. Valid mask is:
3219
* [a-zA-Z0-9\-_\.]{1,63}
3220
*/
3221
l = strlen(name);
3222
if (l == 0 || l >= 64)
3223
return (EINVAL);
3224
for (i = 0; i < l; i++) {
3225
c = name[i];
3226
if (isalpha(c) || isdigit(c) || c == '_' ||
3227
c == '-' || c == '.')
3228
continue;
3229
return (EINVAL);
3230
}
3231
return (0);
3232
}
3233
3234
static const char *default_state_name = "default";
3235
3236
static int
3237
state_check_name(const char *name)
3238
{
3239
3240
if (ipfw_check_object_name(name) != 0)
3241
return (EINVAL);
3242
if (strcmp(name, "any") == 0)
3243
return (EINVAL);
3244
return (0);
3245
}
3246
3247
static int
3248
eaction_check_name(const char *name)
3249
{
3250
3251
if (ipfw_check_object_name(name) != 0)
3252
return (EINVAL);
3253
/* Restrict some 'special' names */
3254
if (match_token(rule_actions, name) != -1 &&
3255
match_token(rule_action_params, name) != -1)
3256
return (EINVAL);
3257
return (0);
3258
}
3259
3260
static uint32_t
3261
pack_object(struct tidx *tstate, const char *name, int otype)
3262
{
3263
ipfw_obj_ntlv *ntlv;
3264
uint32_t i;
3265
3266
for (i = 0; i < tstate->count; i++) {
3267
if (strcmp(tstate->idx[i].name, name) != 0)
3268
continue;
3269
if (tstate->idx[i].set != tstate->set)
3270
continue;
3271
if (tstate->idx[i].head.type != otype)
3272
continue;
3273
3274
return (tstate->idx[i].idx);
3275
}
3276
3277
if (tstate->count + 1 > tstate->size) {
3278
tstate->size += 4;
3279
tstate->idx = realloc(tstate->idx, tstate->size *
3280
sizeof(ipfw_obj_ntlv));
3281
if (tstate->idx == NULL)
3282
return (0);
3283
}
3284
3285
ntlv = &tstate->idx[i];
3286
memset(ntlv, 0, sizeof(ipfw_obj_ntlv));
3287
strlcpy(ntlv->name, name, sizeof(ntlv->name));
3288
ntlv->head.type = otype;
3289
ntlv->head.length = sizeof(ipfw_obj_ntlv);
3290
ntlv->set = tstate->set;
3291
ntlv->idx = ++tstate->counter;
3292
tstate->count++;
3293
3294
return (ntlv->idx);
3295
}
3296
3297
static uint32_t
3298
pack_table(struct tidx *tstate, const char *name)
3299
{
3300
3301
if (table_check_name(name) != 0)
3302
return (0);
3303
3304
return (pack_object(tstate, name, IPFW_TLV_TBL_NAME));
3305
}
3306
3307
static void
3308
fill_table_value(ipfw_insn *cmd, char *s)
3309
{
3310
char *p;
3311
int i;
3312
3313
p = strchr(s, '=');
3314
if (p != NULL) {
3315
*p++ = '\0';
3316
i = match_token(tvalue_names, s);
3317
if (i == -1)
3318
errx(EX_USAGE,
3319
"format: unknown table value name %s", s);
3320
} else {
3321
i = TVALUE_TAG;
3322
p = s;
3323
}
3324
3325
IPFW_SET_TVALUE_TYPE(cmd, i);
3326
insntod(cmd, table)->value = strtoul(p, NULL, 0);
3327
}
3328
3329
void
3330
fill_table(ipfw_insn *cmd, char *av, uint8_t opcode, struct tidx *tstate)
3331
{
3332
ipfw_insn_kidx *c = insntod(cmd, kidx);
3333
char *p;
3334
3335
if ((p = strchr(av + 6, ')')) == NULL)
3336
errx(EX_DATAERR, "forgotten parenthesis: '%s'", av);
3337
*p = '\0';
3338
p = strchr(av + 6, ',');
3339
if (p)
3340
*p++ = '\0';
3341
3342
if ((c->kidx = pack_table(tstate, av + 6)) == 0)
3343
errx(EX_DATAERR, "Invalid table name: %s", av + 6);
3344
3345
cmd->opcode = opcode;
3346
if (p) {
3347
cmd->len |= F_INSN_SIZE(ipfw_insn_table);
3348
fill_table_value(cmd, p);
3349
} else {
3350
IPFW_SET_LOOKUP_TYPE(cmd, LOOKUP_NONE);
3351
cmd->len |= F_INSN_SIZE(ipfw_insn_kidx);
3352
}
3353
}
3354
3355
/*
3356
* fills the addr and mask fields in the instruction as appropriate from av.
3357
* Update length as appropriate.
3358
* The following formats are allowed:
3359
* me returns O_IP_*_ME
3360
* 1.2.3.4 single IP address
3361
* 1.2.3.4:5.6.7.8 address:mask
3362
* 1.2.3.4/24 address/mask
3363
* 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
3364
* We can have multiple comma-separated address/mask entries.
3365
*/
3366
static void
3367
fill_ip(ipfw_insn_ip *cmd, char *av, int cblen, struct tidx *tstate)
3368
{
3369
int len = 0;
3370
uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
3371
3372
cmd->o.len &= ~F_LEN_MASK; /* zero len */
3373
3374
if (_substrcmp(av, "any") == 0)
3375
return;
3376
3377
if (_substrcmp(av, "me") == 0) {
3378
cmd->o.len |= F_INSN_SIZE(ipfw_insn);
3379
return;
3380
}
3381
3382
if (strncmp(av, "table(", 6) == 0) {
3383
fill_table(&cmd->o, av, O_IP_DST_LOOKUP, tstate);
3384
return;
3385
}
3386
3387
while (av) {
3388
/*
3389
* After the address we can have '/' or ':' indicating a mask,
3390
* ',' indicating another address follows, '{' indicating a
3391
* set of addresses of unspecified size.
3392
*/
3393
char *t = NULL, *p = strpbrk(av, "/:,{");
3394
int masklen;
3395
char md, nd = '\0';
3396
3397
CHECK_LENGTH(cblen, (int)F_INSN_SIZE(ipfw_insn) + 2 + len);
3398
3399
if (p) {
3400
md = *p;
3401
*p++ = '\0';
3402
if ((t = strpbrk(p, ",{")) != NULL) {
3403
nd = *t;
3404
*t = '\0';
3405
}
3406
} else
3407
md = '\0';
3408
3409
if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
3410
errx(EX_NOHOST, "hostname ``%s'' unknown", av);
3411
switch (md) {
3412
case ':':
3413
if (!inet_aton(p, (struct in_addr *)&d[1]))
3414
errx(EX_DATAERR, "bad netmask ``%s''", p);
3415
break;
3416
case '/':
3417
masklen = atoi(p);
3418
if (masklen == 0)
3419
d[1] = htonl(0U); /* mask */
3420
else if (masklen > 32)
3421
errx(EX_DATAERR, "bad width ``%s''", p);
3422
else
3423
d[1] = htonl(~0U << (32 - masklen));
3424
break;
3425
case '{': /* no mask, assume /24 and put back the '{' */
3426
d[1] = htonl(~0U << (32 - 24));
3427
*(--p) = md;
3428
break;
3429
3430
case ',': /* single address plus continuation */
3431
*(--p) = md;
3432
/* FALLTHROUGH */
3433
case 0: /* initialization value */
3434
default:
3435
d[1] = htonl(~0U); /* force /32 */
3436
break;
3437
}
3438
d[0] &= d[1]; /* mask base address with mask */
3439
if (t)
3440
*t = nd;
3441
/* find next separator */
3442
if (p)
3443
p = strpbrk(p, ",{");
3444
if (p && *p == '{') {
3445
/*
3446
* We have a set of addresses. They are stored as follows:
3447
* arg1 is the set size (powers of 2, 2..256)
3448
* addr is the base address IN HOST FORMAT
3449
* mask.. is an array of arg1 bits (rounded up to
3450
* the next multiple of 32) with bits set
3451
* for each host in the map.
3452
*/
3453
uint32_t *map = (uint32_t *)&cmd->mask;
3454
int low, high;
3455
int i = contigmask((uint8_t *)&(d[1]), 32);
3456
3457
if (len > 0)
3458
errx(EX_DATAERR, "address set cannot be in a list");
3459
if (i < 24 || i > 31)
3460
errx(EX_DATAERR, "invalid set with mask %d\n", i);
3461
cmd->o.arg1 = 1<<(32-i); /* map length */
3462
d[0] = ntohl(d[0]); /* base addr in host format */
3463
cmd->o.opcode = O_IP_DST_SET; /* default */
3464
cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
3465
for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
3466
map[i] = 0; /* clear map */
3467
3468
av = p + 1;
3469
low = d[0] & 0xff;
3470
high = low + cmd->o.arg1 - 1;
3471
/*
3472
* Here, i stores the previous value when we specify a range
3473
* of addresses within a mask, e.g. 45-63. i = -1 means we
3474
* have no previous value.
3475
*/
3476
i = -1; /* previous value in a range */
3477
while (isdigit(*av)) {
3478
char *s;
3479
int a = strtol(av, &s, 0);
3480
3481
if (s == av) { /* no parameter */
3482
if (*av != '}')
3483
errx(EX_DATAERR, "set not closed\n");
3484
if (i != -1)
3485
errx(EX_DATAERR, "incomplete range %d-", i);
3486
break;
3487
}
3488
if (a < low || a > high)
3489
errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
3490
a, low, high);
3491
a -= low;
3492
if (i == -1) /* no previous in range */
3493
i = a;
3494
else { /* check that range is valid */
3495
if (i > a)
3496
errx(EX_DATAERR, "invalid range %d-%d",
3497
i+low, a+low);
3498
if (*s == '-')
3499
errx(EX_DATAERR, "double '-' in range");
3500
}
3501
for (; i <= a; i++)
3502
map[i/32] |= 1<<(i & 31);
3503
i = -1;
3504
if (*s == '-')
3505
i = a;
3506
else if (*s == '}')
3507
break;
3508
av = s+1;
3509
}
3510
return;
3511
}
3512
av = p;
3513
if (av) /* then *av must be a ',' */
3514
av++;
3515
3516
/* Check this entry */
3517
if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
3518
/*
3519
* 'any' turns the entire list into a NOP.
3520
* 'not any' never matches, so it is removed from the
3521
* list unless it is the only item, in which case we
3522
* report an error.
3523
*/
3524
if (cmd->o.len & F_NOT) { /* "not any" never matches */
3525
if (av == NULL && len == 0) /* only this entry */
3526
errx(EX_DATAERR, "not any never matches");
3527
}
3528
/* else do nothing and skip this entry */
3529
return;
3530
}
3531
/* A single IP can be stored in an optimized format */
3532
if (d[1] == (uint32_t)~0 && av == NULL && len == 0) {
3533
cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
3534
return;
3535
}
3536
len += 2; /* two words... */
3537
d += 2;
3538
} /* end while */
3539
if (len + 1 > F_LEN_MASK)
3540
errx(EX_DATAERR, "address list too long");
3541
cmd->o.len |= len+1;
3542
}
3543
3544
3545
/* n2mask sets n bits of the mask */
3546
void
3547
n2mask(struct in6_addr *mask, int n)
3548
{
3549
static int minimask[9] =
3550
{ 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
3551
u_char *p;
3552
3553
memset(mask, 0, sizeof(struct in6_addr));
3554
p = (u_char *) mask;
3555
for (; n > 0; p++, n -= 8) {
3556
if (n >= 8)
3557
*p = 0xff;
3558
else
3559
*p = minimask[n];
3560
}
3561
return;
3562
}
3563
3564
static void
3565
fill_flags_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode,
3566
struct _s_x *flags, char *p)
3567
{
3568
char *e;
3569
uint32_t set = 0, clear = 0;
3570
3571
if (fill_flags(flags, p, &e, &set, &clear) != 0)
3572
errx(EX_DATAERR, "invalid flag %s", e);
3573
3574
cmd->opcode = opcode;
3575
cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
3576
cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
3577
}
3578
3579
3580
void
3581
ipfw_delete(char *av[])
3582
{
3583
ipfw_range_tlv rt;
3584
char *sep;
3585
uint32_t i, j;
3586
int exitval = EX_OK;
3587
int do_set = 0;
3588
3589
av++;
3590
NEED1("missing rule specification");
3591
if ( *av && _substrcmp(*av, "set") == 0) {
3592
/* Do not allow using the following syntax:
3593
* ipfw set N delete set M
3594
*/
3595
if (g_co.use_set)
3596
errx(EX_DATAERR, "invalid syntax");
3597
do_set = 1; /* delete set */
3598
av++;
3599
}
3600
3601
/* Rule number */
3602
while (*av && isdigit(**av)) {
3603
i = strtol(*av, &sep, 10);
3604
j = i;
3605
if (*sep== '-')
3606
j = strtol(sep + 1, NULL, 10);
3607
av++;
3608
if (g_co.do_nat) {
3609
exitval = ipfw_delete_nat(i);
3610
} else if (g_co.do_pipe) {
3611
exitval = ipfw_delete_pipe(g_co.do_pipe, i);
3612
} else {
3613
memset(&rt, 0, sizeof(rt));
3614
if (do_set != 0) {
3615
rt.set = i & 31;
3616
rt.flags = IPFW_RCFLAG_SET;
3617
} else {
3618
rt.start_rule = i;
3619
rt.end_rule = j;
3620
if (rt.start_rule == 0 && rt.end_rule == 0)
3621
rt.flags |= IPFW_RCFLAG_ALL;
3622
else
3623
rt.flags |= IPFW_RCFLAG_RANGE;
3624
if (g_co.use_set != 0) {
3625
rt.set = g_co.use_set - 1;
3626
rt.flags |= IPFW_RCFLAG_SET;
3627
}
3628
}
3629
if (g_co.do_dynamic == 2)
3630
rt.flags |= IPFW_RCFLAG_DYNAMIC;
3631
i = do_range_cmd(IP_FW_XDEL, &rt);
3632
if (i != 0) {
3633
exitval = EX_UNAVAILABLE;
3634
if (g_co.do_quiet)
3635
continue;
3636
warn("rule %u: setsockopt(IP_FW_XDEL)",
3637
rt.start_rule);
3638
} else if (rt.new_set == 0 && do_set == 0 &&
3639
g_co.do_dynamic != 2) {
3640
exitval = EX_UNAVAILABLE;
3641
if (g_co.do_quiet)
3642
continue;
3643
if (rt.start_rule != rt.end_rule)
3644
warnx("no rules in %u-%u range",
3645
rt.start_rule, rt.end_rule);
3646
else
3647
warnx("rule %u not found",
3648
rt.start_rule);
3649
}
3650
}
3651
}
3652
if (exitval != EX_OK && g_co.do_force == 0)
3653
exit(exitval);
3654
}
3655
3656
/*
3657
* fill the interface structure. We do not check the name as we can
3658
* create interfaces dynamically, so checking them at insert time
3659
* makes relatively little sense.
3660
* Interface names containing '*', '?', or '[' are assumed to be shell
3661
* patterns which match interfaces.
3662
*/
3663
static void
3664
fill_iface(ipfw_insn_if *cmd, char *arg, int cblen, struct tidx *tstate)
3665
{
3666
char *p;
3667
uint32_t uidx;
3668
3669
cmd->name[0] = '\0';
3670
cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
3671
3672
CHECK_CMDLEN;
3673
3674
/* Parse the interface or address */
3675
if (strcmp(arg, "any") == 0)
3676
cmd->o.len = 0; /* effectively ignore this command */
3677
else if (strncmp(arg, "table(", 6) == 0) {
3678
if ((p = strchr(arg + 6, ')')) == NULL)
3679
errx(EX_DATAERR, "forgotten parenthesis: '%s'", arg);
3680
*p = '\0';
3681
p = strchr(arg + 6, ',');
3682
if (p)
3683
*p++ = '\0';
3684
if ((uidx = pack_table(tstate, arg + 6)) == 0)
3685
errx(EX_DATAERR, "Invalid table name: %s", arg + 6);
3686
3687
cmd->name[0] = '\1'; /* Special value indicating table */
3688
cmd->p.kidx = uidx;
3689
} else if (!isdigit(*arg)) {
3690
strlcpy(cmd->name, arg, sizeof(cmd->name));
3691
cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
3692
} else if (!inet_aton(arg, &cmd->p.ip))
3693
errx(EX_DATAERR, "bad ip address ``%s''", arg);
3694
}
3695
3696
static void
3697
get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
3698
{
3699
int i;
3700
size_t l;
3701
char *ap, *ptr, *optr;
3702
struct ether_addr *mac;
3703
const char *macset = "0123456789abcdefABCDEF:";
3704
3705
if (strcmp(p, "any") == 0) {
3706
for (i = 0; i < ETHER_ADDR_LEN; i++)
3707
addr[i] = mask[i] = 0;
3708
return;
3709
}
3710
3711
optr = ptr = strdup(p);
3712
if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
3713
l = strlen(ap);
3714
if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
3715
errx(EX_DATAERR, "Incorrect MAC address");
3716
bcopy(mac, addr, ETHER_ADDR_LEN);
3717
} else
3718
errx(EX_DATAERR, "Incorrect MAC address");
3719
3720
if (ptr != NULL) { /* we have mask? */
3721
if (p[ptr - optr - 1] == '/') { /* mask len */
3722
long ml = strtol(ptr, &ap, 10);
3723
if (*ap != 0 || ml > ETHER_ADDR_LEN * 8 || ml < 0)
3724
errx(EX_DATAERR, "Incorrect mask length");
3725
for (i = 0; ml > 0 && i < ETHER_ADDR_LEN; ml -= 8, i++)
3726
mask[i] = (ml >= 8) ? 0xff: (~0) << (8 - ml);
3727
} else { /* mask */
3728
l = strlen(ptr);
3729
if (strspn(ptr, macset) != l ||
3730
(mac = ether_aton(ptr)) == NULL)
3731
errx(EX_DATAERR, "Incorrect mask");
3732
bcopy(mac, mask, ETHER_ADDR_LEN);
3733
}
3734
} else { /* default mask: ff:ff:ff:ff:ff:ff */
3735
for (i = 0; i < ETHER_ADDR_LEN; i++)
3736
mask[i] = 0xff;
3737
}
3738
for (i = 0; i < ETHER_ADDR_LEN; i++)
3739
addr[i] &= mask[i];
3740
3741
free(optr);
3742
}
3743
3744
/*
3745
* helper function, updates the pointer to cmd with the length
3746
* of the current command, and also cleans up the first word of
3747
* the new command in case it has been clobbered before.
3748
*/
3749
static ipfw_insn *
3750
next_cmd(ipfw_insn *cmd, int *len)
3751
{
3752
*len -= F_LEN(cmd);
3753
CHECK_LENGTH(*len, 0);
3754
cmd += F_LEN(cmd);
3755
bzero(cmd, sizeof(*cmd));
3756
return cmd;
3757
}
3758
3759
/*
3760
* Takes arguments and copies them into a comment
3761
*/
3762
static void
3763
fill_comment(ipfw_insn *cmd, char **av, int cblen)
3764
{
3765
int i, l;
3766
char *p = (char *)(cmd + 1);
3767
3768
cmd->opcode = O_NOP;
3769
cmd->len = (cmd->len & (F_NOT | F_OR));
3770
3771
/* Compute length of comment string. */
3772
for (i = 0, l = 0; av[i] != NULL; i++)
3773
l += strlen(av[i]) + 1;
3774
if (l == 0)
3775
return;
3776
if (l > 84)
3777
errx(EX_DATAERR,
3778
"comment too long (max 80 chars)");
3779
l = 1 + (l+3)/4;
3780
cmd->len = (cmd->len & (F_NOT | F_OR)) | l;
3781
CHECK_CMDLEN;
3782
3783
for (i = 0; av[i] != NULL; i++) {
3784
strcpy(p, av[i]);
3785
p += strlen(av[i]);
3786
*p++ = ' ';
3787
}
3788
*(--p) = '\0';
3789
}
3790
3791
/*
3792
* A function to fill simple commands of size 1.
3793
* Existing flags are preserved.
3794
*/
3795
static void
3796
fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
3797
{
3798
cmd->opcode = opcode;
3799
cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
3800
cmd->arg1 = arg;
3801
}
3802
3803
/*
3804
* Fetch and add the MAC address and type, with masks. This generates one or
3805
* two microinstructions, and returns the pointer to the last one.
3806
*/
3807
static ipfw_insn *
3808
add_mac(ipfw_insn *cmd, char *av[], int cblen)
3809
{
3810
ipfw_insn_mac *mac;
3811
3812
if ( ( av[0] == NULL ) || ( av[1] == NULL ) )
3813
errx(EX_DATAERR, "MAC dst src");
3814
3815
cmd->opcode = O_MACADDR2;
3816
cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
3817
CHECK_CMDLEN;
3818
3819
mac = (ipfw_insn_mac *)cmd;
3820
get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
3821
get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
3822
&(mac->mask[ETHER_ADDR_LEN])); /* src */
3823
return cmd;
3824
}
3825
3826
static ipfw_insn *
3827
add_mactype(ipfw_insn *cmd, char *av, int cblen)
3828
{
3829
if (!av)
3830
errx(EX_DATAERR, "missing MAC type");
3831
if (strcmp(av, "any") != 0) { /* we have a non-null type */
3832
fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE,
3833
cblen);
3834
cmd->opcode = O_MAC_TYPE;
3835
return cmd;
3836
} else
3837
return NULL;
3838
}
3839
3840
static ipfw_insn *
3841
add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
3842
{
3843
struct protoent *pe;
3844
char *ep;
3845
int proto;
3846
3847
proto = strtol(av, &ep, 10);
3848
if (*ep != '\0' || proto <= 0) {
3849
if ((pe = getprotobyname(av)) == NULL)
3850
return NULL;
3851
proto = pe->p_proto;
3852
}
3853
3854
fill_cmd(cmd, O_PROTO, 0, proto);
3855
*protop = proto;
3856
return cmd;
3857
}
3858
3859
static ipfw_insn *
3860
add_proto(ipfw_insn *cmd, char *av, u_char *protop)
3861
{
3862
u_char proto = IPPROTO_IP;
3863
3864
if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3865
; /* do not set O_IP4 nor O_IP6 */
3866
else if (strcmp(av, "ip4") == 0)
3867
/* explicit "just IPv4" rule */
3868
fill_cmd(cmd, O_IP4, 0, 0);
3869
else if (strcmp(av, "ip6") == 0) {
3870
/* explicit "just IPv6" rule */
3871
proto = IPPROTO_IPV6;
3872
fill_cmd(cmd, O_IP6, 0, 0);
3873
} else
3874
return add_proto0(cmd, av, protop);
3875
3876
*protop = proto;
3877
return cmd;
3878
}
3879
3880
static ipfw_insn *
3881
add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
3882
{
3883
u_char proto = IPPROTO_IP;
3884
3885
if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3886
; /* do not set O_IP4 nor O_IP6 */
3887
else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
3888
/* explicit "just IPv4" rule */
3889
fill_cmd(cmd, O_IP4, 0, 0);
3890
else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
3891
/* explicit "just IPv6" rule */
3892
proto = IPPROTO_IPV6;
3893
fill_cmd(cmd, O_IP6, 0, 0);
3894
} else
3895
return add_proto0(cmd, av, protop);
3896
3897
*protop = proto;
3898
return cmd;
3899
}
3900
3901
static ipfw_insn *
3902
add_srcip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3903
{
3904
fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3905
if (cmd->opcode == O_IP_DST_SET) /* set */
3906
cmd->opcode = O_IP_SRC_SET;
3907
else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3908
cmd->opcode = O_IP_SRC_LOOKUP;
3909
else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3910
cmd->opcode = O_IP_SRC_ME;
3911
else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3912
cmd->opcode = O_IP_SRC;
3913
else /* addr/mask */
3914
cmd->opcode = O_IP_SRC_MASK;
3915
return cmd;
3916
}
3917
3918
static ipfw_insn *
3919
add_dstip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3920
{
3921
fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3922
if (cmd->opcode == O_IP_DST_SET) /* set */
3923
;
3924
else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3925
;
3926
else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3927
cmd->opcode = O_IP_DST_ME;
3928
else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3929
cmd->opcode = O_IP_DST;
3930
else /* addr/mask */
3931
cmd->opcode = O_IP_DST_MASK;
3932
return cmd;
3933
}
3934
3935
static ipfw_insn *
3936
add_srcmac(ipfw_insn *cmd, char *av, struct tidx *tstate)
3937
{
3938
3939
if (strncmp(av, "table(", 6) == 0)
3940
fill_table(cmd, av, O_MAC_SRC_LOOKUP, tstate);
3941
else
3942
errx(EX_DATAERR, "only mac table lookup is supported %s", av);
3943
return cmd;
3944
}
3945
3946
static ipfw_insn *
3947
add_dstmac(ipfw_insn *cmd, char *av, struct tidx *tstate)
3948
{
3949
3950
if (strncmp(av, "table(", 6) == 0)
3951
fill_table(cmd, av, O_MAC_DST_LOOKUP, tstate);
3952
else
3953
errx(EX_DATAERR, "only mac table lookup is supported %s", av);
3954
return cmd;
3955
}
3956
3957
3958
static struct _s_x f_reserved_keywords[] = {
3959
{ "altq", TOK_OR },
3960
{ "//", TOK_OR },
3961
{ "diverted", TOK_OR },
3962
{ "dst-port", TOK_OR },
3963
{ "src-port", TOK_OR },
3964
{ "established", TOK_OR },
3965
{ "keep-state", TOK_OR },
3966
{ "frag", TOK_OR },
3967
{ "icmptypes", TOK_OR },
3968
{ "in", TOK_OR },
3969
{ "out", TOK_OR },
3970
{ "ip6", TOK_OR },
3971
{ "any", TOK_OR },
3972
{ "to", TOK_OR },
3973
{ "via", TOK_OR },
3974
{ "{", TOK_OR },
3975
{ "lookup", TOK_OR },
3976
{ "tagged", TOK_OR },
3977
{ NULL, 0 } /* terminator */
3978
};
3979
3980
static ipfw_insn *
3981
add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode, int cblen)
3982
{
3983
3984
if (match_token(f_reserved_keywords, av) != -1)
3985
return (NULL);
3986
3987
if (fill_newports((ipfw_insn_u16 *)cmd, av, proto, cblen)) {
3988
/* XXX todo: check that we have a protocol with ports */
3989
cmd->opcode = opcode;
3990
return cmd;
3991
}
3992
return NULL;
3993
}
3994
3995
static ipfw_insn *
3996
add_src(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3997
{
3998
struct in6_addr a;
3999
char *host, *ch, buf[INET6_ADDRSTRLEN];
4000
ipfw_insn *ret = NULL;
4001
size_t len;
4002
4003
/* Copy first address in set if needed */
4004
if ((ch = strpbrk(av, "/,")) != NULL) {
4005
len = ch - av;
4006
strlcpy(buf, av, sizeof(buf));
4007
if (len < sizeof(buf))
4008
buf[len] = '\0';
4009
host = buf;
4010
} else
4011
host = av;
4012
4013
if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
4014
inet_pton(AF_INET6, host, &a) == 1)
4015
ret = add_srcip6(cmd, av, cblen, tstate);
4016
/* XXX: should check for IPv4, not !IPv6 */
4017
if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
4018
inet_pton(AF_INET6, host, &a) != 1))
4019
ret = add_srcip(cmd, av, cblen, tstate);
4020
if (ret == NULL && strcmp(av, "any") != 0)
4021
ret = cmd;
4022
4023
return ret;
4024
}
4025
4026
static ipfw_insn *
4027
add_dst(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
4028
{
4029
struct in6_addr a;
4030
char *host, *ch, buf[INET6_ADDRSTRLEN];
4031
ipfw_insn *ret = NULL;
4032
size_t len;
4033
4034
/* Copy first address in set if needed */
4035
if ((ch = strpbrk(av, "/,")) != NULL) {
4036
len = ch - av;
4037
strlcpy(buf, av, sizeof(buf));
4038
if (len < sizeof(buf))
4039
buf[len] = '\0';
4040
host = buf;
4041
} else
4042
host = av;
4043
4044
if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
4045
inet_pton(AF_INET6, host, &a) == 1)
4046
ret = add_dstip6(cmd, av, cblen, tstate);
4047
/* XXX: should check for IPv4, not !IPv6 */
4048
if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
4049
inet_pton(AF_INET6, host, &a) != 1))
4050
ret = add_dstip(cmd, av, cblen, tstate);
4051
if (ret == NULL && strcmp(av, "any") != 0)
4052
ret = cmd;
4053
4054
return ret;
4055
}
4056
4057
static uint16_t
4058
parse_logdst(char *logdst_iter)
4059
{
4060
char *token;
4061
uint16_t ret;
4062
4063
ret = IPFW_LOG_DEFAULT;
4064
while ((token = strsep(&logdst_iter, ",")) != NULL) {
4065
if (_substrcmp(token, "syslog") == 0) {
4066
ret |= IPFW_LOG_SYSLOG;
4067
continue;
4068
}
4069
/* ipfw0 is compatibility keyword. */
4070
if (_substrcmp(token, "bpf") == 0 ||
4071
_substrcmp(token, "ipfw0") == 0) {
4072
ret |= IPFW_LOG_IPFW0;
4073
continue;
4074
}
4075
if (_substrcmp(token, "rtsock") == 0) {
4076
ret |= IPFW_LOG_RTSOCK;
4077
continue;
4078
}
4079
errx(EX_DATAERR,
4080
"unsupported logdst token");
4081
}
4082
return (ret);
4083
}
4084
4085
static inline uint32_t
4086
arg_or_targ_relaxed(const char *arg, const char *action, uint32_t maxarg)
4087
{
4088
uint32_t arg1 = (uint32_t)(-1);
4089
4090
if (arg == NULL)
4091
errx(EX_USAGE, "missing argument for %s", action);
4092
if (isdigit(arg[0])) {
4093
arg1 = strtoul(arg, NULL, 10);
4094
if (arg1 < IPFW_ARG_MIN || arg1 > maxarg)
4095
errx(EX_DATAERR, "illegal argument %s(%u) for %s",
4096
arg, arg1, action);
4097
} else if (_substrcmp(arg, "tablearg") == 0)
4098
arg1 = IP_FW_TARG;
4099
return (arg1);
4100
}
4101
4102
static inline uint32_t
4103
arg_or_targ(const char *arg, const char *action)
4104
{
4105
uint32_t arg1 = arg_or_targ_relaxed(arg, action, IPFW_ARG_MAX);
4106
4107
if (arg1 == (uint32_t)(-1))
4108
errx(EX_DATAERR, "illegal argument %s(%u) for %s",
4109
arg, arg1, action);
4110
return (arg1);
4111
}
4112
4113
static uint16_t
4114
get_divert_port(const char *arg, const char *action)
4115
{
4116
uint32_t arg1 = arg_or_targ_relaxed(arg, action, IPFW_ARG_MAX);
4117
4118
if (arg1 != (uint32_t)(-1))
4119
return (arg1);
4120
4121
struct servent *s;
4122
setservent(1);
4123
s = getservbyname(arg, "divert");
4124
if (s == NULL)
4125
errx(EX_DATAERR, "illegal divert/tee port");
4126
return (ntohs(s->s_port));
4127
}
4128
4129
/*
4130
* Parse arguments and assemble the microinstructions which make up a rule.
4131
* Rules are added into the 'rulebuf' and then copied in the correct order
4132
* into the actual rule.
4133
*
4134
* The syntax for a rule starts with the action, followed by
4135
* optional action parameters, and the various match patterns.
4136
* In the assembled microcode, the first opcode must be an O_PROBE_STATE
4137
* (generated if the rule includes a keep-state option), then the
4138
* various match patterns, log/altq actions, and the actual action.
4139
*
4140
*/
4141
static void
4142
compile_rule(char *av[], uint32_t *rbuf, int *rbufsize, struct tidx *tstate)
4143
{
4144
/*
4145
* rules are added into the 'rulebuf' and then copied in
4146
* the correct order into the actual rule.
4147
* Some things that need to go out of order (prob, action etc.)
4148
* go into actbuf[].
4149
*/
4150
static uint32_t actbuf[255], cmdbuf[255];
4151
int rblen, ablen, cblen;
4152
4153
ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
4154
ipfw_insn *first_cmd; /* first match pattern */
4155
4156
struct ip_fw_rule *rule;
4157
4158
/*
4159
* various flags used to record that we entered some fields.
4160
*/
4161
ipfw_insn *have_state = NULL; /* any state-related option */
4162
int have_rstate = 0;
4163
ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
4164
ipfw_insn *have_skipcmd = NULL;
4165
size_t len;
4166
4167
int i;
4168
4169
int open_par = 0; /* open parenthesis ( */
4170
4171
/* proto is here because it is used to fetch ports */
4172
u_char proto = IPPROTO_IP; /* default protocol */
4173
4174
double match_prob = 1; /* match probability, default is always match */
4175
4176
bzero(actbuf, sizeof(actbuf)); /* actions go here */
4177
bzero(cmdbuf, sizeof(cmdbuf));
4178
bzero(rbuf, *rbufsize);
4179
4180
rule = (struct ip_fw_rule *)rbuf;
4181
cmd = (ipfw_insn *)cmdbuf;
4182
action = (ipfw_insn *)actbuf;
4183
4184
rblen = *rbufsize / sizeof(uint32_t);
4185
rblen -= sizeof(struct ip_fw_rule) / sizeof(uint32_t);
4186
ablen = nitems(actbuf);
4187
cblen = nitems(cmdbuf);
4188
cblen -= F_INSN_SIZE(ipfw_insn_u32) + 1;
4189
4190
#define CHECK_RBUFLEN(len) { CHECK_LENGTH(rblen, len); rblen -= len; }
4191
#define CHECK_ACTLEN CHECK_LENGTH(ablen, action->len)
4192
4193
av++;
4194
4195
/* [rule N] -- Rule number optional */
4196
if (av[0] && isdigit(**av)) {
4197
rule->rulenum = atoi(*av);
4198
av++;
4199
}
4200
4201
/* [set N] -- set number (0..RESVD_SET), optional */
4202
if (av[0] && av[1] && _substrcmp(*av, "set") == 0) {
4203
int set = strtoul(av[1], NULL, 10);
4204
if (set < 0 || set > RESVD_SET)
4205
errx(EX_DATAERR, "illegal set %s", av[1]);
4206
rule->set = set;
4207
tstate->set = set;
4208
av += 2;
4209
}
4210
4211
/* [prob D] -- match probability, optional */
4212
if (av[0] && av[1] && _substrcmp(*av, "prob") == 0) {
4213
match_prob = strtod(av[1], NULL);
4214
4215
if (match_prob <= 0 || match_prob > 1)
4216
errx(EX_DATAERR, "illegal match prob. %s", av[1]);
4217
av += 2;
4218
}
4219
4220
/* action -- mandatory */
4221
NEED1("missing action");
4222
i = match_token(rule_actions, *av);
4223
av++;
4224
action->len = 1; /* default */
4225
CHECK_ACTLEN;
4226
switch(i) {
4227
case TOK_CHECKSTATE:
4228
have_state = action;
4229
action->opcode = O_CHECK_STATE;
4230
action->len = F_INSN_SIZE(ipfw_insn_kidx);
4231
CHECK_ACTLEN;
4232
if (*av == NULL ||
4233
match_token(rule_options, *av) == TOK_COMMENT) {
4234
insntod(have_state, kidx)->kidx = pack_object(tstate,
4235
default_state_name, IPFW_TLV_STATE_NAME);
4236
break;
4237
}
4238
if (*av[0] == ':') {
4239
if (strcmp(*av + 1, "any") == 0)
4240
insntod(have_state, kidx)->kidx = 0;
4241
else if (state_check_name(*av + 1) == 0)
4242
insntod(have_state, kidx)->kidx = pack_object(
4243
tstate, *av + 1, IPFW_TLV_STATE_NAME);
4244
else
4245
errx(EX_DATAERR, "Invalid state name %s",
4246
*av);
4247
av++;
4248
break;
4249
}
4250
errx(EX_DATAERR, "Invalid state name %s", *av);
4251
break;
4252
4253
case TOK_ABORT:
4254
action->opcode = O_REJECT;
4255
action->arg1 = ICMP_REJECT_ABORT;
4256
break;
4257
4258
case TOK_ABORT6:
4259
action->opcode = O_UNREACH6;
4260
action->arg1 = ICMP6_UNREACH_ABORT;
4261
break;
4262
4263
case TOK_ACCEPT:
4264
action->opcode = O_ACCEPT;
4265
break;
4266
4267
case TOK_DENY:
4268
action->opcode = O_DENY;
4269
action->arg1 = 0;
4270
break;
4271
4272
case TOK_REJECT:
4273
action->opcode = O_REJECT;
4274
action->arg1 = ICMP_UNREACH_HOST;
4275
break;
4276
4277
case TOK_RESET:
4278
action->opcode = O_REJECT;
4279
action->arg1 = ICMP_REJECT_RST;
4280
break;
4281
4282
case TOK_RESET6:
4283
action->opcode = O_UNREACH6;
4284
action->arg1 = ICMP6_UNREACH_RST;
4285
break;
4286
4287
case TOK_UNREACH:
4288
action->opcode = O_REJECT;
4289
NEED1("missing reject code");
4290
action->arg1 = get_reject_code(*av);
4291
av++;
4292
if (action->arg1 == ICMP_UNREACH_NEEDFRAG && isdigit(**av)) {
4293
uint16_t mtu;
4294
4295
mtu = strtoul(*av, NULL, 10);
4296
if (mtu < 68 || mtu >= IP_MAXPACKET)
4297
errx(EX_DATAERR, "illegal argument for %s",
4298
*(av - 1));
4299
action->len = F_INSN_SIZE(ipfw_insn_u16);
4300
insntod(action, u16)->ports[0] = mtu;
4301
av++;
4302
}
4303
break;
4304
4305
case TOK_UNREACH6:
4306
action->opcode = O_UNREACH6;
4307
NEED1("missing unreach code");
4308
action->arg1 = get_unreach6_code(*av);
4309
av++;
4310
break;
4311
4312
case TOK_COUNT:
4313
action->opcode = O_COUNT;
4314
break;
4315
4316
case TOK_NAT:
4317
action->opcode = O_NAT;
4318
action->len = F_INSN_SIZE(ipfw_insn_nat);
4319
CHECK_ACTLEN;
4320
if (*av != NULL && _substrcmp(*av, "global") == 0)
4321
action->arg1 = IP_FW_NAT44_GLOBAL;
4322
else
4323
action->arg1 = arg_or_targ(av[0], *(av - 1));
4324
av++;
4325
break;
4326
case TOK_QUEUE:
4327
action->opcode = O_QUEUE;
4328
action->arg1 = arg_or_targ(av[0], *(av - 1));
4329
av++;
4330
break;
4331
case TOK_PIPE:
4332
action->opcode = O_PIPE;
4333
action->arg1 = arg_or_targ(av[0], *(av - 1));
4334
av++;
4335
break;
4336
case TOK_SKIPTO:
4337
action->opcode = O_SKIPTO;
4338
action->len = F_INSN_SIZE(ipfw_insn_u32);
4339
CHECK_ACTLEN;
4340
insntod(action, u32)->d[0] =
4341
arg_or_targ_relaxed(av[0], *(av - 1), IPFW_DEFAULT_RULE);
4342
av++;
4343
break;
4344
case TOK_NETGRAPH:
4345
action->opcode = O_NETGRAPH;
4346
action->arg1 = arg_or_targ(av[0], *(av - 1));
4347
av++;
4348
break;
4349
case TOK_NGTEE:
4350
action->opcode = O_NGTEE;
4351
action->arg1 = arg_or_targ(av[0], *(av - 1));
4352
av++;
4353
break;
4354
case TOK_DIVERT:
4355
action->opcode = O_DIVERT;
4356
action->arg1 = get_divert_port(av[0], *(av - 1));
4357
av++;
4358
break;
4359
case TOK_TEE:
4360
action->opcode = O_TEE;
4361
action->arg1 = get_divert_port(av[0], *(av - 1));
4362
av++;
4363
break;
4364
case TOK_CALL:
4365
action->opcode = O_CALLRETURN;
4366
action->len = F_INSN_SIZE(ipfw_insn_u32);
4367
CHECK_ACTLEN;
4368
insntod(action, u32)->d[0] =
4369
arg_or_targ_relaxed(av[0], *(av - 1), IPFW_DEFAULT_RULE);
4370
av++;
4371
break;
4372
4373
case TOK_FORWARD: {
4374
/*
4375
* Locate the address-port separator (':' or ',').
4376
* Could be one of the following:
4377
* hostname:port
4378
* IPv4 a.b.c.d,port
4379
* IPv4 a.b.c.d:port
4380
* IPv6 w:x:y::z,port
4381
* IPv6 [w:x:y::z]:port
4382
*/
4383
struct sockaddr_storage result;
4384
struct addrinfo *res;
4385
char *s, *end;
4386
int family;
4387
u_short port_number = 0;
4388
4389
NEED1("missing forward address[:port]");
4390
4391
if (strncmp(*av, "tablearg", 8) == 0 &&
4392
((*av)[8] == '\0' || (*av)[8] == ',' || (*av)[8] == ':'))
4393
memcpy(++(*av), "0.0.0.0", 7);
4394
4395
/*
4396
* Are we an bracket-enclosed IPv6 address?
4397
*/
4398
if (strchr(*av, '['))
4399
(*av)++;
4400
4401
/*
4402
* locate the address-port separator (':' or ',')
4403
*/
4404
s = strchr(*av, ',');
4405
if (s == NULL) {
4406
s = strchr(*av, ']');
4407
/* Prevent erroneous parsing on brackets. */
4408
if (s != NULL)
4409
*(s++) = '\0';
4410
else
4411
s = *av;
4412
4413
/* Distinguish between IPv4:port and IPv6 cases. */
4414
s = strchr(s, ':');
4415
if (s && strchr(s+1, ':'))
4416
s = NULL; /* no port */
4417
}
4418
4419
if (s != NULL) {
4420
/* Terminate host portion and set s to start of port. */
4421
*(s++) = '\0';
4422
i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
4423
if (s == end)
4424
errx(EX_DATAERR,
4425
"illegal forwarding port ``%s''", s);
4426
port_number = (u_short)i;
4427
}
4428
4429
/*
4430
* Resolve the host name or address to a family and a
4431
* network representation of the address.
4432
*/
4433
if (getaddrinfo(*av, NULL, NULL, &res))
4434
errx(EX_DATAERR, NULL);
4435
/* Just use the first host in the answer. */
4436
family = res->ai_family;
4437
memcpy(&result, res->ai_addr, res->ai_addrlen);
4438
freeaddrinfo(res);
4439
4440
if (family == PF_INET) {
4441
ipfw_insn_sa *p = (ipfw_insn_sa *)action;
4442
4443
action->opcode = O_FORWARD_IP;
4444
action->len = F_INSN_SIZE(ipfw_insn_sa);
4445
CHECK_ACTLEN;
4446
4447
/*
4448
* In the kernel we assume AF_INET and use only
4449
* sin_port and sin_addr. Remember to set sin_len as
4450
* the routing code seems to use it too.
4451
*/
4452
p->sa.sin_len = sizeof(struct sockaddr_in);
4453
p->sa.sin_family = AF_INET;
4454
p->sa.sin_port = port_number;
4455
p->sa.sin_addr.s_addr =
4456
((struct sockaddr_in *)&result)->sin_addr.s_addr;
4457
} else if (family == PF_INET6) {
4458
ipfw_insn_sa6 *p = (ipfw_insn_sa6 *)action;
4459
4460
action->opcode = O_FORWARD_IP6;
4461
action->len = F_INSN_SIZE(ipfw_insn_sa6);
4462
CHECK_ACTLEN;
4463
4464
p->sa.sin6_len = sizeof(struct sockaddr_in6);
4465
p->sa.sin6_family = AF_INET6;
4466
p->sa.sin6_port = port_number;
4467
p->sa.sin6_flowinfo = 0;
4468
p->sa.sin6_scope_id =
4469
((struct sockaddr_in6 *)&result)->sin6_scope_id;
4470
bcopy(&((struct sockaddr_in6*)&result)->sin6_addr,
4471
&p->sa.sin6_addr, sizeof(p->sa.sin6_addr));
4472
} else {
4473
errx(EX_DATAERR, "Invalid address family in forward action");
4474
}
4475
av++;
4476
break;
4477
}
4478
case TOK_COMMENT:
4479
/* pretend it is a 'count' rule followed by the comment */
4480
action->opcode = O_COUNT;
4481
av--; /* go back... */
4482
break;
4483
4484
case TOK_SETFIB:
4485
{
4486
int numfibs;
4487
size_t intsize = sizeof(int);
4488
4489
action->opcode = O_SETFIB;
4490
NEED1("missing fib number");
4491
if (_substrcmp(*av, "tablearg") == 0) {
4492
action->arg1 = IP_FW_TARG;
4493
} else {
4494
action->arg1 = strtoul(*av, NULL, 10);
4495
if (sysctlbyname("net.fibs", &numfibs, &intsize,
4496
NULL, 0) == -1)
4497
errx(EX_DATAERR, "fibs not supported.\n");
4498
if (action->arg1 >= numfibs) /* Temporary */
4499
errx(EX_DATAERR, "fib too large.\n");
4500
/* Add high-order bit to fib to make room for tablearg*/
4501
action->arg1 |= 0x8000;
4502
}
4503
av++;
4504
break;
4505
}
4506
4507
case TOK_SETDSCP:
4508
{
4509
int code;
4510
4511
action->opcode = O_SETDSCP;
4512
NEED1("missing DSCP code");
4513
if (_substrcmp(*av, "tablearg") == 0) {
4514
action->arg1 = IP_FW_TARG;
4515
} else {
4516
if (isalpha(*av[0])) {
4517
if ((code = match_token(f_ipdscp, *av)) == -1)
4518
errx(EX_DATAERR, "Unknown DSCP code");
4519
action->arg1 = code;
4520
} else
4521
action->arg1 = strtoul(*av, NULL, 10);
4522
/*
4523
* Add high-order bit to DSCP to make room
4524
* for tablearg
4525
*/
4526
action->arg1 |= 0x8000;
4527
}
4528
av++;
4529
break;
4530
}
4531
4532
case TOK_REASS:
4533
action->opcode = O_REASS;
4534
break;
4535
4536
case TOK_RETURN:
4537
action->opcode = O_CALLRETURN;
4538
action->len = F_INSN_SIZE(ipfw_insn_u32) | F_NOT;
4539
CHECK_ACTLEN;
4540
if (*av != NULL) {
4541
/*
4542
* Return type is optional.
4543
* By default we use RETURN_NEXT_RULENUM.
4544
*/
4545
i = match_token(return_types, *av);
4546
if (i >= 0) {
4547
action->arg1 = i;
4548
av++;
4549
} else
4550
action->arg1 = RETURN_NEXT_RULENUM;
4551
}
4552
break;
4553
4554
case TOK_SETMARK: {
4555
action->opcode = O_SETMARK;
4556
action->len = F_INSN_SIZE(ipfw_insn_u32);
4557
NEED1("missing mark");
4558
if (strcmp(*av, "tablearg") == 0) {
4559
action->arg1 = IP_FW_TARG;
4560
} else {
4561
insntod(action, u32)->d[0] = strtoul(*av, NULL, 0);
4562
/* This is not a tablearg */
4563
action->arg1 |= 0x8000;
4564
}
4565
av++;
4566
CHECK_CMDLEN;
4567
break;
4568
}
4569
4570
case TOK_TCPSETMSS: {
4571
u_long mss;
4572
uint32_t idx;
4573
4574
idx = pack_object(tstate, "tcp-setmss", IPFW_TLV_EACTION);
4575
if (idx == 0)
4576
errx(EX_DATAERR, "pack_object failed");
4577
action->opcode = O_EXTERNAL_ACTION;
4578
action->len = F_INSN_SIZE(ipfw_insn_kidx);
4579
CHECK_ACTLEN;
4580
insntod(action, kidx)->kidx = idx;
4581
4582
NEED1("Missing MSS value");
4583
action = next_cmd(action, &ablen);
4584
action->len = 1;
4585
CHECK_ACTLEN;
4586
mss = strtoul(*av, NULL, 10);
4587
if (mss == 0 || mss > UINT16_MAX)
4588
errx(EX_USAGE, "invalid MSS value %s", *av);
4589
fill_cmd(action, O_EXTERNAL_DATA, 0, (uint16_t)mss);
4590
av++;
4591
break;
4592
}
4593
4594
default:
4595
av--;
4596
if (match_token(rule_eactions, *av) == -1)
4597
errx(EX_DATAERR, "invalid action %s\n", *av);
4598
/*
4599
* External actions support.
4600
* XXX: we support only syntax with instance name.
4601
* For known external actions (from rule_eactions list)
4602
* we can handle syntax directly. But with `eaction'
4603
* keyword we can use only `eaction <name> <instance>'
4604
* syntax.
4605
*/
4606
case TOK_EACTION: {
4607
uint32_t idx;
4608
4609
NEED1("Missing eaction name");
4610
if (eaction_check_name(*av) != 0)
4611
errx(EX_DATAERR, "Invalid eaction name %s", *av);
4612
idx = pack_object(tstate, *av, IPFW_TLV_EACTION);
4613
if (idx == 0)
4614
errx(EX_DATAERR, "pack_object failed");
4615
action->opcode = O_EXTERNAL_ACTION;
4616
action->len = F_INSN_SIZE(ipfw_insn_kidx);
4617
CHECK_ACTLEN;
4618
insntod(action, kidx)->kidx = idx;
4619
4620
av++;
4621
NEED1("Missing eaction instance name");
4622
if (eaction_check_name(*av) != 0)
4623
errx(EX_DATAERR, "Invalid eaction instance name %s",
4624
*av);
4625
/*
4626
* External action instance object has TLV type depended
4627
* from the external action name object index. Since we
4628
* currently don't know this index, use zero as TLV type.
4629
*/
4630
idx = pack_object(tstate, *av, 0);
4631
if (idx == 0)
4632
errx(EX_DATAERR, "pack_object failed");
4633
action = next_cmd(action, &ablen);
4634
action->opcode = O_EXTERNAL_INSTANCE;
4635
action->len = F_INSN_SIZE(ipfw_insn_kidx);
4636
CHECK_ACTLEN;
4637
insntod(action, kidx)->kidx = idx;
4638
av++;
4639
}
4640
}
4641
action = next_cmd(action, &ablen);
4642
4643
/*
4644
* [altq queuename] -- altq tag, optional
4645
* [log [logamount N]] -- log, optional
4646
*
4647
* If they exist, it go first in the cmdbuf, but then it is
4648
* skipped in the copy section to the end of the buffer.
4649
*/
4650
while (av[0] != NULL && (i = match_token(rule_action_params, *av)) != -1) {
4651
av++;
4652
switch (i) {
4653
case TOK_LOG:
4654
{
4655
ipfw_insn_log *c = (ipfw_insn_log *)cmd;
4656
int l;
4657
4658
if (have_log)
4659
errx(EX_DATAERR,
4660
"log cannot be specified more than once");
4661
have_log = (ipfw_insn *)c;
4662
cmd->len = F_INSN_SIZE(ipfw_insn_log);
4663
CHECK_CMDLEN;
4664
cmd->opcode = O_LOG;
4665
cmd->arg1 = IPFW_LOG_DEFAULT;
4666
/* logdst before logamount */
4667
if (av[0] && _substrcmp(*av, "logdst") == 0) {
4668
av++;
4669
NEED1("logdst requires argument");
4670
cmd->arg1 = parse_logdst(*av);
4671
av++;
4672
}
4673
4674
if (av[0] && _substrcmp(*av, "logamount") == 0) {
4675
av++;
4676
NEED1("logamount requires argument");
4677
l = atoi(*av);
4678
if (l < 0)
4679
errx(EX_DATAERR,
4680
"logamount must be positive");
4681
c->max_log = l;
4682
av++;
4683
} else {
4684
len = sizeof(c->max_log);
4685
if (sysctlbyname("net.inet.ip.fw.verbose_limit",
4686
&c->max_log, &len, NULL, 0) == -1) {
4687
if (g_co.test_only) {
4688
c->max_log = 0;
4689
break;
4690
}
4691
errx(1, "sysctlbyname(\"%s\")",
4692
"net.inet.ip.fw.verbose_limit");
4693
}
4694
}
4695
4696
/* logdst after logamount */
4697
if (av[0] && _substrcmp(*av, "logdst") == 0) {
4698
av++;
4699
NEED1("logdst requires argument");
4700
cmd->arg1 = parse_logdst(*av);
4701
av++;
4702
}
4703
}
4704
break;
4705
4706
#ifndef NO_ALTQ
4707
case TOK_ALTQ:
4708
{
4709
ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
4710
4711
NEED1("missing altq queue name");
4712
if (have_altq)
4713
errx(EX_DATAERR,
4714
"altq cannot be specified more than once");
4715
have_altq = (ipfw_insn *)a;
4716
cmd->len = F_INSN_SIZE(ipfw_insn_altq);
4717
CHECK_CMDLEN;
4718
cmd->opcode = O_ALTQ;
4719
a->qid = altq_name_to_qid(*av);
4720
av++;
4721
}
4722
break;
4723
#endif
4724
4725
case TOK_TAG:
4726
case TOK_UNTAG: {
4727
uint16_t tag;
4728
4729
if (have_tag)
4730
errx(EX_USAGE, "tag and untag cannot be "
4731
"specified more than once");
4732
GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX, i,
4733
rule_action_params);
4734
have_tag = cmd;
4735
fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
4736
av++;
4737
break;
4738
}
4739
4740
default:
4741
abort();
4742
}
4743
cmd = next_cmd(cmd, &cblen);
4744
}
4745
4746
if (have_state) { /* must be a check-state, we are done */
4747
if (*av != NULL &&
4748
match_token(rule_options, *av) == TOK_COMMENT) {
4749
/* check-state has a comment */
4750
av++;
4751
fill_comment(cmd, av, cblen);
4752
cmd = next_cmd(cmd, &cblen);
4753
av[0] = NULL;
4754
}
4755
goto done;
4756
}
4757
4758
#define OR_START(target) \
4759
if (av[0] && (*av[0] == '(' || *av[0] == '{')) { \
4760
if (open_par) \
4761
errx(EX_USAGE, "nested \"(\" not allowed\n"); \
4762
prev = NULL; \
4763
open_par = 1; \
4764
if ( (av[0])[1] == '\0') { \
4765
av++; \
4766
} else \
4767
(*av)++; \
4768
} \
4769
target: \
4770
4771
4772
#define CLOSE_PAR \
4773
if (open_par) { \
4774
if (av[0] && ( \
4775
strcmp(*av, ")") == 0 || \
4776
strcmp(*av, "}") == 0)) { \
4777
prev = NULL; \
4778
open_par = 0; \
4779
av++; \
4780
} else \
4781
errx(EX_USAGE, "missing \")\"\n"); \
4782
}
4783
4784
#define NOT_BLOCK \
4785
if (av[0] && _substrcmp(*av, "not") == 0) { \
4786
if (cmd->len & F_NOT) \
4787
errx(EX_USAGE, "double \"not\" not allowed\n"); \
4788
cmd->len |= F_NOT; \
4789
av++; \
4790
}
4791
4792
#define OR_BLOCK(target) \
4793
if (av[0] && _substrcmp(*av, "or") == 0) { \
4794
if (prev == NULL || open_par == 0) \
4795
errx(EX_DATAERR, "invalid OR block"); \
4796
prev->len |= F_OR; \
4797
av++; \
4798
goto target; \
4799
} \
4800
CLOSE_PAR;
4801
4802
first_cmd = cmd;
4803
4804
#if 0
4805
/*
4806
* MAC addresses, optional.
4807
* If we have this, we skip the part "proto from src to dst"
4808
* and jump straight to the option parsing.
4809
*/
4810
NOT_BLOCK;
4811
NEED1("missing protocol");
4812
if (_substrcmp(*av, "MAC") == 0 ||
4813
_substrcmp(*av, "mac") == 0) {
4814
av++; /* the "MAC" keyword */
4815
add_mac(cmd, av); /* exits in case of errors */
4816
cmd = next_cmd(cmd);
4817
av += 2; /* dst-mac and src-mac */
4818
NOT_BLOCK;
4819
NEED1("missing mac type");
4820
if (add_mactype(cmd, av[0]))
4821
cmd = next_cmd(cmd);
4822
av++; /* any or mac-type */
4823
goto read_options;
4824
}
4825
#endif
4826
4827
/*
4828
* protocol, mandatory
4829
*/
4830
OR_START(get_proto);
4831
NOT_BLOCK;
4832
NEED1("missing protocol");
4833
if (add_proto_compat(cmd, *av, &proto)) {
4834
av++;
4835
if (F_LEN(cmd) != 0) {
4836
prev = cmd;
4837
cmd = next_cmd(cmd, &cblen);
4838
}
4839
} else if (first_cmd != cmd) {
4840
errx(EX_DATAERR, "invalid protocol ``%s''", *av);
4841
} else {
4842
rule->flags |= IPFW_RULE_JUSTOPTS;
4843
goto read_options;
4844
}
4845
OR_BLOCK(get_proto);
4846
4847
first_cmd = cmd; /* update pointer to use in compact form */
4848
4849
/*
4850
* "from", mandatory
4851
*/
4852
if ((av[0] == NULL) || _substrcmp(*av, "from") != 0)
4853
errx(EX_USAGE, "missing ``from''");
4854
av++;
4855
4856
/*
4857
* source IP, mandatory
4858
*/
4859
OR_START(source_ip);
4860
NOT_BLOCK; /* optional "not" */
4861
NEED1("missing source address");
4862
if (add_src(cmd, *av, proto, cblen, tstate)) {
4863
av++;
4864
if (F_LEN(cmd) != 0) { /* ! any */
4865
prev = cmd;
4866
cmd = next_cmd(cmd, &cblen);
4867
}
4868
} else
4869
errx(EX_USAGE, "bad source address %s", *av);
4870
OR_BLOCK(source_ip);
4871
4872
/*
4873
* source ports, optional
4874
*/
4875
NOT_BLOCK; /* optional "not" */
4876
if ( av[0] != NULL ) {
4877
if (_substrcmp(*av, "any") == 0 ||
4878
add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4879
av++;
4880
if (F_LEN(cmd) != 0)
4881
cmd = next_cmd(cmd, &cblen);
4882
}
4883
}
4884
4885
/*
4886
* "to", mandatory
4887
*/
4888
if ( (av[0] == NULL) || _substrcmp(*av, "to") != 0 )
4889
errx(EX_USAGE, "missing ``to''");
4890
av++;
4891
4892
/*
4893
* destination, mandatory
4894
*/
4895
OR_START(dest_ip);
4896
NOT_BLOCK; /* optional "not" */
4897
NEED1("missing dst address");
4898
if (add_dst(cmd, *av, proto, cblen, tstate)) {
4899
av++;
4900
if (F_LEN(cmd) != 0) { /* ! any */
4901
prev = cmd;
4902
cmd = next_cmd(cmd, &cblen);
4903
}
4904
} else
4905
errx( EX_USAGE, "bad destination address %s", *av);
4906
OR_BLOCK(dest_ip);
4907
4908
/*
4909
* dest. ports, optional
4910
*/
4911
NOT_BLOCK; /* optional "not" */
4912
if (av[0]) {
4913
if (_substrcmp(*av, "any") == 0 ||
4914
add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
4915
av++;
4916
if (F_LEN(cmd) != 0)
4917
cmd = next_cmd(cmd, &cblen);
4918
}
4919
}
4920
if (first_cmd == cmd)
4921
rule->flags |= IPFW_RULE_NOOPT;
4922
4923
read_options:
4924
prev = NULL;
4925
while ( av[0] != NULL ) {
4926
char *s;
4927
ipfw_insn_u32 *cmd32; /* alias for cmd */
4928
4929
s = *av;
4930
cmd32 = (ipfw_insn_u32 *)cmd;
4931
4932
if (*s == '!') { /* alternate syntax for NOT */
4933
if (cmd->len & F_NOT)
4934
errx(EX_USAGE, "double \"not\" not allowed\n");
4935
cmd->len = F_NOT;
4936
s++;
4937
}
4938
i = match_token(rule_options, s);
4939
av++;
4940
switch(i) {
4941
case TOK_NOT:
4942
if (cmd->len & F_NOT)
4943
errx(EX_USAGE, "double \"not\" not allowed\n");
4944
cmd->len = F_NOT;
4945
break;
4946
4947
case TOK_OR:
4948
if (open_par == 0 || prev == NULL)
4949
errx(EX_USAGE, "invalid \"or\" block\n");
4950
prev->len |= F_OR;
4951
break;
4952
4953
case TOK_STARTBRACE:
4954
if (open_par)
4955
errx(EX_USAGE, "+nested \"(\" not allowed\n");
4956
open_par = 1;
4957
break;
4958
4959
case TOK_ENDBRACE:
4960
if (!open_par)
4961
errx(EX_USAGE, "+missing \")\"\n");
4962
open_par = 0;
4963
prev = NULL;
4964
break;
4965
4966
case TOK_IN:
4967
fill_cmd(cmd, O_IN, 0, 0);
4968
break;
4969
4970
case TOK_OUT:
4971
cmd->len ^= F_NOT; /* toggle F_NOT */
4972
fill_cmd(cmd, O_IN, 0, 0);
4973
break;
4974
4975
case TOK_DIVERTED:
4976
fill_cmd(cmd, O_DIVERTED, 0, 3);
4977
break;
4978
4979
case TOK_DIVERTEDLOOPBACK:
4980
fill_cmd(cmd, O_DIVERTED, 0, 1);
4981
break;
4982
4983
case TOK_DIVERTEDOUTPUT:
4984
fill_cmd(cmd, O_DIVERTED, 0, 2);
4985
break;
4986
4987
case TOK_FRAG: {
4988
uint32_t set = 0, clear = 0;
4989
4990
if (*av != NULL && fill_flags(f_ipoff, *av, NULL,
4991
&set, &clear) == 0)
4992
av++;
4993
else {
4994
/*
4995
* Compatibility: no argument after "frag"
4996
* keyword equals to "frag offset".
4997
*/
4998
set = 0x01;
4999
clear = 0;
5000
}
5001
fill_cmd(cmd, O_FRAG, 0,
5002
(set & 0xff) | ( (clear & 0xff) << 8));
5003
break;
5004
}
5005
5006
case TOK_LAYER2:
5007
fill_cmd(cmd, O_LAYER2, 0, 0);
5008
break;
5009
5010
case TOK_XMIT:
5011
case TOK_RECV:
5012
case TOK_VIA:
5013
NEED1("recv, xmit, via require interface name"
5014
" or address");
5015
fill_iface(insntod(cmd, if), av[0], cblen, tstate);
5016
av++;
5017
if (F_LEN(cmd) == 0) /* not a valid address */
5018
break;
5019
if (i == TOK_XMIT)
5020
cmd->opcode = O_XMIT;
5021
else if (i == TOK_RECV)
5022
cmd->opcode = O_RECV;
5023
else if (i == TOK_VIA)
5024
cmd->opcode = O_VIA;
5025
break;
5026
5027
case TOK_ICMPTYPES:
5028
NEED1("icmptypes requires list of types");
5029
fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
5030
av++;
5031
break;
5032
5033
case TOK_ICMP6TYPES:
5034
NEED1("icmptypes requires list of types");
5035
fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av, cblen);
5036
av++;
5037
break;
5038
5039
case TOK_IPTTL:
5040
NEED1("ipttl requires TTL");
5041
if (strpbrk(*av, "-,")) {
5042
if (!add_ports(cmd, *av, 0, O_IPTTL, cblen))
5043
errx(EX_DATAERR, "invalid ipttl %s", *av);
5044
} else
5045
fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
5046
av++;
5047
break;
5048
5049
case TOK_IPID:
5050
NEED1("ipid requires id");
5051
if (strpbrk(*av, "-,")) {
5052
if (!add_ports(cmd, *av, 0, O_IPID, cblen))
5053
errx(EX_DATAERR, "invalid ipid %s", *av);
5054
} else
5055
fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
5056
av++;
5057
break;
5058
5059
case TOK_IPLEN:
5060
NEED1("iplen requires length");
5061
if (strpbrk(*av, "-,")) {
5062
if (!add_ports(cmd, *av, 0, O_IPLEN, cblen))
5063
errx(EX_DATAERR, "invalid ip len %s", *av);
5064
} else
5065
fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
5066
av++;
5067
break;
5068
5069
case TOK_IPVER:
5070
NEED1("ipver requires version");
5071
fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
5072
av++;
5073
break;
5074
5075
case TOK_IPPRECEDENCE:
5076
NEED1("ipprecedence requires value");
5077
fill_cmd(cmd, O_IPPRECEDENCE, 0,
5078
(strtoul(*av, NULL, 0) & 7) << 5);
5079
av++;
5080
break;
5081
5082
case TOK_DSCP:
5083
NEED1("missing DSCP code");
5084
fill_dscp(cmd, *av, cblen);
5085
av++;
5086
break;
5087
5088
case TOK_IPOPTS:
5089
NEED1("missing argument for ipoptions");
5090
fill_flags_cmd(cmd, O_IPOPT, f_ipopts, *av);
5091
av++;
5092
break;
5093
5094
case TOK_IPTOS:
5095
NEED1("missing argument for iptos");
5096
fill_flags_cmd(cmd, O_IPTOS, f_iptos, *av);
5097
av++;
5098
break;
5099
5100
case TOK_UID:
5101
NEED1("uid requires argument");
5102
{
5103
char *end;
5104
uid_t uid;
5105
struct passwd *pwd;
5106
5107
cmd->opcode = O_UID;
5108
uid = strtoul(*av, &end, 0);
5109
pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
5110
if (pwd == NULL)
5111
errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
5112
cmd32->d[0] = pwd->pw_uid;
5113
cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
5114
av++;
5115
}
5116
break;
5117
5118
case TOK_GID:
5119
NEED1("gid requires argument");
5120
{
5121
char *end;
5122
gid_t gid;
5123
struct group *grp;
5124
5125
cmd->opcode = O_GID;
5126
gid = strtoul(*av, &end, 0);
5127
grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
5128
if (grp == NULL)
5129
errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
5130
cmd32->d[0] = grp->gr_gid;
5131
cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
5132
av++;
5133
}
5134
break;
5135
5136
case TOK_JAIL:
5137
NEED1("jail requires argument");
5138
{
5139
char *end;
5140
int jid;
5141
5142
cmd->opcode = O_JAIL;
5143
/*
5144
* If av is a number, then we'll just pass it as-is. If
5145
* it's a name, try to resolve that to a jid.
5146
*
5147
* We save the jail_getid(3) call for a fallback because
5148
* it entails an unconditional trip to the kernel to
5149
* either validate a jid or resolve a name to a jid.
5150
* This specific token doesn't currently require a
5151
* jid to be an active jail, so we save a transition
5152
* by simply using a number that we're given.
5153
*/
5154
jid = strtoul(*av, &end, 10);
5155
if (*end != '\0') {
5156
jid = jail_getid(*av);
5157
if (jid < 0)
5158
errx(EX_DATAERR, "%s", jail_errmsg);
5159
}
5160
cmd32->d[0] = (uint32_t)jid;
5161
cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
5162
av++;
5163
}
5164
break;
5165
5166
case TOK_ESTAB:
5167
fill_cmd(cmd, O_ESTAB, 0, 0);
5168
break;
5169
5170
case TOK_SETUP:
5171
fill_cmd(cmd, O_TCPFLAGS, 0,
5172
(TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
5173
break;
5174
5175
case TOK_TCPDATALEN:
5176
NEED1("tcpdatalen requires length");
5177
if (strpbrk(*av, "-,")) {
5178
if (!add_ports(cmd, *av, 0, O_TCPDATALEN, cblen))
5179
errx(EX_DATAERR, "invalid tcpdata len %s", *av);
5180
} else
5181
fill_cmd(cmd, O_TCPDATALEN, 0,
5182
strtoul(*av, NULL, 0));
5183
av++;
5184
break;
5185
5186
case TOK_TCPOPTS:
5187
NEED1("missing argument for tcpoptions");
5188
fill_flags_cmd(cmd, O_TCPOPTS, f_tcpopts, *av);
5189
av++;
5190
break;
5191
5192
case TOK_TCPSEQ:
5193
case TOK_TCPACK:
5194
NEED1("tcpseq/tcpack requires argument");
5195
cmd->len = F_INSN_SIZE(ipfw_insn_u32);
5196
cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
5197
cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
5198
av++;
5199
break;
5200
5201
case TOK_TCPMSS:
5202
case TOK_TCPWIN:
5203
NEED1("tcpmss/tcpwin requires size");
5204
if (strpbrk(*av, "-,")) {
5205
if (add_ports(cmd, *av, 0,
5206
i == TOK_TCPWIN ? O_TCPWIN : O_TCPMSS,
5207
cblen) == NULL)
5208
errx(EX_DATAERR, "invalid %s size %s",
5209
s, *av);
5210
} else
5211
fill_cmd(cmd, i == TOK_TCPWIN ? O_TCPWIN :
5212
O_TCPMSS, 0, strtoul(*av, NULL, 0));
5213
av++;
5214
break;
5215
5216
case TOK_TCPFLAGS:
5217
NEED1("missing argument for tcpflags");
5218
cmd->opcode = O_TCPFLAGS;
5219
fill_flags_cmd(cmd, O_TCPFLAGS, f_tcpflags, *av);
5220
av++;
5221
break;
5222
5223
case TOK_KEEPSTATE:
5224
case TOK_RECORDSTATE: {
5225
uint32_t uidx;
5226
5227
if (open_par)
5228
errx(EX_USAGE, "keep-state or record-state cannot be part "
5229
"of an or block");
5230
if (have_state)
5231
errx(EX_USAGE, "only one of keep-state, record-state, "
5232
" limit and set-limit is allowed");
5233
if (*av != NULL && *av[0] == ':') {
5234
if (state_check_name(*av + 1) != 0)
5235
errx(EX_DATAERR,
5236
"Invalid state name %s", *av);
5237
uidx = pack_object(tstate, *av + 1,
5238
IPFW_TLV_STATE_NAME);
5239
av++;
5240
} else
5241
uidx = pack_object(tstate, default_state_name,
5242
IPFW_TLV_STATE_NAME);
5243
have_state = cmd;
5244
have_rstate = i == TOK_RECORDSTATE;
5245
cmd->opcode = O_KEEP_STATE;
5246
cmd->len = F_INSN_SIZE(ipfw_insn_kidx);
5247
CHECK_CMDLEN;
5248
insntod(have_state, kidx)->kidx = uidx;
5249
break;
5250
}
5251
5252
case TOK_LIMIT:
5253
case TOK_SETLIMIT: {
5254
ipfw_insn_limit *c = insntod(cmd, limit);
5255
int val;
5256
5257
if (open_par)
5258
errx(EX_USAGE,
5259
"limit or set-limit cannot be part of an or block");
5260
if (have_state)
5261
errx(EX_USAGE, "only one of keep-state, record-state, "
5262
" limit and set-limit is allowed");
5263
have_state = cmd;
5264
have_rstate = i == TOK_SETLIMIT;
5265
5266
cmd->opcode = O_LIMIT;
5267
cmd->len = F_INSN_SIZE(ipfw_insn_limit);
5268
CHECK_CMDLEN;
5269
c->limit_mask = c->conn_limit = c->kidx = 0;
5270
5271
while ( av[0] != NULL ) {
5272
if ((val = match_token(limit_masks, *av)) <= 0)
5273
break;
5274
c->limit_mask |= val;
5275
av++;
5276
}
5277
5278
if (c->limit_mask == 0)
5279
errx(EX_USAGE, "limit: missing limit mask");
5280
5281
GET_UINT_ARG(c->conn_limit, IPFW_ARG_MIN, IPFW_ARG_MAX,
5282
TOK_LIMIT, rule_options);
5283
av++;
5284
5285
if (*av != NULL && *av[0] == ':') {
5286
if (state_check_name(*av + 1) != 0)
5287
errx(EX_DATAERR,
5288
"Invalid state name %s", *av);
5289
c->kidx = pack_object(tstate, *av + 1,
5290
IPFW_TLV_STATE_NAME);
5291
av++;
5292
} else
5293
c->kidx = pack_object(tstate,
5294
default_state_name, IPFW_TLV_STATE_NAME);
5295
break;
5296
}
5297
5298
case TOK_PROTO:
5299
NEED1("missing protocol");
5300
if (add_proto(cmd, *av, &proto)) {
5301
av++;
5302
} else
5303
errx(EX_DATAERR, "invalid protocol ``%s''",
5304
*av);
5305
break;
5306
5307
case TOK_SRCIP:
5308
NEED1("missing source IP");
5309
if (add_srcip(cmd, *av, cblen, tstate)) {
5310
av++;
5311
}
5312
break;
5313
5314
case TOK_DSTIP:
5315
NEED1("missing destination IP");
5316
if (add_dstip(cmd, *av, cblen, tstate)) {
5317
av++;
5318
}
5319
break;
5320
5321
case TOK_SRCIP6:
5322
NEED1("missing source IP6");
5323
if (add_srcip6(cmd, *av, cblen, tstate)) {
5324
av++;
5325
}
5326
break;
5327
5328
case TOK_DSTIP6:
5329
NEED1("missing destination IP6");
5330
if (add_dstip6(cmd, *av, cblen, tstate)) {
5331
av++;
5332
}
5333
break;
5334
5335
5336
case TOK_SRCMAC:
5337
NEED1("missing source MAC");
5338
if (add_srcmac(cmd, *av, tstate)) {
5339
av++;
5340
}
5341
break;
5342
5343
case TOK_DSTMAC:
5344
NEED1("missing destination MAC");
5345
if (add_dstmac(cmd, *av, tstate)) {
5346
av++;
5347
}
5348
break;
5349
5350
case TOK_SRCPORT:
5351
NEED1("missing source port");
5352
if (_substrcmp(*av, "any") == 0 ||
5353
add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
5354
av++;
5355
} else
5356
errx(EX_DATAERR, "invalid source port %s", *av);
5357
break;
5358
5359
case TOK_DSTPORT:
5360
NEED1("missing destination port");
5361
if (_substrcmp(*av, "any") == 0 ||
5362
add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
5363
av++;
5364
} else
5365
errx(EX_DATAERR, "invalid destination port %s",
5366
*av);
5367
break;
5368
5369
case TOK_MAC:
5370
if (add_mac(cmd, av, cblen))
5371
av += 2;
5372
break;
5373
5374
case TOK_MACTYPE:
5375
NEED1("missing mac type");
5376
if (!add_mactype(cmd, *av, cblen))
5377
errx(EX_DATAERR, "invalid mac type %s", *av);
5378
av++;
5379
break;
5380
5381
case TOK_VERREVPATH:
5382
fill_cmd(cmd, O_VERREVPATH, 0, 0);
5383
break;
5384
5385
case TOK_VERSRCREACH:
5386
fill_cmd(cmd, O_VERSRCREACH, 0, 0);
5387
break;
5388
5389
case TOK_ANTISPOOF:
5390
fill_cmd(cmd, O_ANTISPOOF, 0, 0);
5391
break;
5392
5393
case TOK_IPSEC:
5394
fill_cmd(cmd, O_IPSEC, 0, 0);
5395
break;
5396
5397
case TOK_IPV6:
5398
fill_cmd(cmd, O_IP6, 0, 0);
5399
break;
5400
5401
case TOK_IPV4:
5402
fill_cmd(cmd, O_IP4, 0, 0);
5403
break;
5404
5405
case TOK_EXT6HDR:
5406
NEED1("missing extension header");
5407
fill_ext6hdr( cmd, *av );
5408
av++;
5409
break;
5410
5411
case TOK_FLOWID:
5412
if (proto != IPPROTO_IPV6 )
5413
errx( EX_USAGE, "flow-id filter is active "
5414
"only for ipv6 protocol\n");
5415
fill_flow6( (ipfw_insn_u32 *) cmd, *av, cblen);
5416
av++;
5417
break;
5418
5419
case TOK_COMMENT:
5420
fill_comment(cmd, av, cblen);
5421
av[0]=NULL;
5422
break;
5423
5424
case TOK_TAGGED:
5425
if (av[0] && strpbrk(*av, "-,")) {
5426
if (!add_ports(cmd, *av, 0, O_TAGGED, cblen))
5427
errx(EX_DATAERR, "tagged: invalid tag"
5428
" list: %s", *av);
5429
}
5430
else {
5431
uint16_t tag;
5432
5433
GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX,
5434
TOK_TAGGED, rule_options);
5435
fill_cmd(cmd, O_TAGGED, 0, tag);
5436
}
5437
av++;
5438
break;
5439
5440
case TOK_FIB:
5441
NEED1("fib requires fib number");
5442
fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
5443
av++;
5444
break;
5445
case TOK_SOCKARG:
5446
fill_cmd(cmd, O_SOCKARG, 0, 0);
5447
break;
5448
5449
case TOK_LOOKUP: {
5450
/* optional mask for some LOOKUP types */
5451
ipfw_insn_table *c = insntod(cmd, table);
5452
char *lkey;
5453
5454
if (!av[0] || !av[1])
5455
errx(EX_USAGE,
5456
"format: lookup argument tablenum");
5457
cmd->opcode = O_IP_DST_LOOKUP;
5458
5459
lkey = strsep(av, ":");
5460
i = match_token(lookup_keys, lkey);
5461
if (i == -1)
5462
errx(EX_USAGE,
5463
"format: cannot lookup on %s", lkey);
5464
/* masked lookup key */
5465
if (*av != NULL) {
5466
switch (i) {
5467
case LOOKUP_DST_PORT:
5468
case LOOKUP_SRC_PORT:
5469
case LOOKUP_UID:
5470
case LOOKUP_JAIL:
5471
case LOOKUP_DSCP:
5472
case LOOKUP_MARK:
5473
case LOOKUP_RULENUM:
5474
break;
5475
default:
5476
errx(EX_USAGE,
5477
"masked lookup is not supported "
5478
"for %s", lkey);
5479
}
5480
cmd->len |= F_INSN_SIZE(ipfw_insn_table);
5481
c->value = strtoul(*av, NULL, 0);
5482
if (c->value == 0)
5483
errx(EX_USAGE,
5484
"all-zeroes bitmask for lookup "
5485
"is meaningless");
5486
} else {
5487
cmd->len |= F_INSN_SIZE(ipfw_insn_kidx);
5488
}
5489
CHECK_CMDLEN;
5490
5491
IPFW_SET_LOOKUP_TYPE(cmd, i);
5492
av++;
5493
c->kidx = pack_table(tstate, *av);
5494
if (c->kidx == 0)
5495
errx(EX_DATAERR,
5496
"Invalid table name: %s", *av);
5497
av++;
5498
}
5499
break;
5500
case TOK_FLOW:
5501
NEED1("missing table name");
5502
if (strncmp(*av, "table(", 6) != 0)
5503
errx(EX_DATAERR,
5504
"enclose table name into \"table()\"");
5505
fill_table(cmd, *av, O_IP_FLOW_LOOKUP, tstate);
5506
av++;
5507
break;
5508
5509
case TOK_SKIPACTION:
5510
if (have_skipcmd)
5511
errx(EX_USAGE, "only one defer-action "
5512
"is allowed");
5513
have_skipcmd = cmd;
5514
fill_cmd(cmd, O_SKIP_ACTION, 0, 0);
5515
break;
5516
5517
case TOK_MARK:
5518
NEED1("missing mark value:mask");
5519
fill_mark(cmd, *av, cblen);
5520
av++;
5521
break;
5522
5523
default:
5524
errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
5525
}
5526
if (F_LEN(cmd) > 0) { /* prepare to advance */
5527
prev = cmd;
5528
cmd = next_cmd(cmd, &cblen);
5529
}
5530
}
5531
5532
done:
5533
5534
if (!have_state && have_skipcmd)
5535
warnx("Rule contains \"defer-immediate-action\" "
5536
"and doesn't contain any state-related options.");
5537
5538
/*
5539
* Now copy stuff into the rule.
5540
* If we have a keep-state option, the first instruction
5541
* must be a PROBE_STATE (which is generated here).
5542
* If we have a LOG option, it was stored as the first command,
5543
* and now must be moved to the top of the action part.
5544
*/
5545
dst = (ipfw_insn *)rule->cmd;
5546
5547
/*
5548
* First thing to write into the command stream is the match probability.
5549
*/
5550
if (match_prob != 1) { /* 1 means always match */
5551
dst->opcode = O_PROB;
5552
dst->len = 2;
5553
*((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
5554
dst += dst->len;
5555
}
5556
5557
/*
5558
* generate O_PROBE_STATE if necessary
5559
*/
5560
if (have_state && have_state->opcode != O_CHECK_STATE && !have_rstate) {
5561
dst->opcode = O_PROBE_STATE;
5562
dst->len = F_INSN_SIZE(ipfw_insn_kidx);
5563
insntod(dst, kidx)->kidx = insntod(have_state, kidx)->kidx;
5564
dst = next_cmd(dst, &rblen);
5565
}
5566
5567
/*
5568
* copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG,
5569
* O_SKIP_ACTION
5570
*/
5571
for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
5572
i = F_LEN(src);
5573
CHECK_RBUFLEN(i);
5574
5575
switch (src->opcode) {
5576
case O_LOG:
5577
case O_KEEP_STATE:
5578
case O_LIMIT:
5579
case O_ALTQ:
5580
case O_TAG:
5581
case O_SKIP_ACTION:
5582
break;
5583
default:
5584
bcopy(src, dst, i * sizeof(uint32_t));
5585
dst += i;
5586
}
5587
}
5588
5589
/*
5590
* put back the have_state command as last opcode
5591
*/
5592
if (have_state && have_state->opcode != O_CHECK_STATE) {
5593
i = F_LEN(have_state);
5594
CHECK_RBUFLEN(i);
5595
bcopy(have_state, dst, i * sizeof(uint32_t));
5596
dst += i;
5597
}
5598
5599
/*
5600
* put back the have_skipcmd command as very last opcode
5601
*/
5602
if (have_skipcmd) {
5603
i = F_LEN(have_skipcmd);
5604
CHECK_RBUFLEN(i);
5605
bcopy(have_skipcmd, dst, i * sizeof(uint32_t));
5606
dst += i;
5607
}
5608
5609
/*
5610
* start action section
5611
*/
5612
rule->act_ofs = dst - rule->cmd;
5613
5614
/* put back O_LOG, O_ALTQ, O_TAG if necessary */
5615
if (have_log) {
5616
i = F_LEN(have_log);
5617
CHECK_RBUFLEN(i);
5618
bcopy(have_log, dst, i * sizeof(uint32_t));
5619
dst += i;
5620
}
5621
if (have_altq) {
5622
i = F_LEN(have_altq);
5623
CHECK_RBUFLEN(i);
5624
bcopy(have_altq, dst, i * sizeof(uint32_t));
5625
dst += i;
5626
}
5627
if (have_tag) {
5628
i = F_LEN(have_tag);
5629
CHECK_RBUFLEN(i);
5630
bcopy(have_tag, dst, i * sizeof(uint32_t));
5631
dst += i;
5632
}
5633
5634
/*
5635
* copy all other actions
5636
*/
5637
for (src = (ipfw_insn *)actbuf; src != action; src += i) {
5638
i = F_LEN(src);
5639
CHECK_RBUFLEN(i);
5640
bcopy(src, dst, i * sizeof(uint32_t));
5641
dst += i;
5642
}
5643
5644
rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
5645
*rbufsize = (char *)dst - (char *)rule;
5646
}
5647
5648
static int
5649
compare_ntlv(const void *_a, const void *_b)
5650
{
5651
const ipfw_obj_ntlv *a, *b;
5652
5653
a = (const ipfw_obj_ntlv *)_a;
5654
b = (const ipfw_obj_ntlv *)_b;
5655
5656
if (a->set < b->set)
5657
return (-1);
5658
else if (a->set > b->set)
5659
return (1);
5660
5661
if (a->idx < b->idx)
5662
return (-1);
5663
else if (a->idx > b->idx)
5664
return (1);
5665
5666
if (a->head.type < b->head.type)
5667
return (-1);
5668
else if (a->head.type > b->head.type)
5669
return (1);
5670
5671
return (0);
5672
}
5673
5674
/*
5675
* Provide kernel with sorted list of referenced objects
5676
*/
5677
static void
5678
object_sort_ctlv(ipfw_obj_ctlv *ctlv)
5679
{
5680
5681
qsort(ctlv + 1, ctlv->count, ctlv->objsize, compare_ntlv);
5682
}
5683
5684
struct object_kt {
5685
uint32_t uidx;
5686
uint16_t type;
5687
};
5688
static int
5689
compare_object_kntlv(const void *k, const void *v)
5690
{
5691
const ipfw_obj_ntlv *ntlv;
5692
struct object_kt key;
5693
5694
key = *((const struct object_kt *)k);
5695
ntlv = (const ipfw_obj_ntlv *)v;
5696
5697
if (key.uidx < ntlv->idx)
5698
return (-1);
5699
else if (key.uidx > ntlv->idx)
5700
return (1);
5701
5702
if (key.type < ntlv->head.type)
5703
return (-1);
5704
else if (key.type > ntlv->head.type)
5705
return (1);
5706
5707
return (0);
5708
}
5709
5710
/*
5711
* Finds object name in @ctlv by @idx and @type.
5712
* Uses the following facts:
5713
* 1) All TLVs are the same size
5714
* 2) Kernel implementation provides already sorted list.
5715
*
5716
* Returns table name or NULL.
5717
*/
5718
static char *
5719
object_search_ctlv(ipfw_obj_ctlv *ctlv, uint32_t idx, uint16_t type)
5720
{
5721
ipfw_obj_ntlv *ntlv;
5722
struct object_kt key;
5723
5724
key.uidx = idx;
5725
key.type = type;
5726
5727
ntlv = bsearch(&key, (ctlv + 1), ctlv->count, ctlv->objsize,
5728
compare_object_kntlv);
5729
5730
if (ntlv != NULL)
5731
return (ntlv->name);
5732
5733
return (NULL);
5734
}
5735
5736
static char *
5737
table_search_ctlv(ipfw_obj_ctlv *ctlv, uint32_t idx)
5738
{
5739
5740
return (object_search_ctlv(ctlv, idx, IPFW_TLV_TBL_NAME));
5741
}
5742
5743
/*
5744
* Adds one or more rules to ipfw chain.
5745
* Data layout:
5746
* Request:
5747
* [
5748
* ip_fw3_opheader
5749
* [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
5750
* [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ] (*2) (*3)
5751
* ]
5752
* Reply:
5753
* [
5754
* ip_fw3_opheader
5755
* [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
5756
* [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ]
5757
* ]
5758
*
5759
* Rules in reply are modified to store their actual ruleset number.
5760
*
5761
* (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
5762
* according to their idx field and there has to be no duplicates.
5763
* (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
5764
* (*3) Each ip_fw structure needs to be aligned to u64 boundary.
5765
*/
5766
void
5767
ipfw_add(char *av[])
5768
{
5769
uint32_t rulebuf[1024];
5770
int rbufsize, default_off, tlen, rlen;
5771
size_t sz;
5772
struct tidx ts;
5773
struct ip_fw_rule *rule;
5774
caddr_t tbuf;
5775
ip_fw3_opheader *op3;
5776
ipfw_obj_ctlv *ctlv, *tstate;
5777
5778
rbufsize = sizeof(rulebuf);
5779
memset(rulebuf, 0, rbufsize);
5780
memset(&ts, 0, sizeof(ts));
5781
5782
/* Optimize case with no tables */
5783
default_off = sizeof(ipfw_obj_ctlv) + sizeof(ip_fw3_opheader);
5784
op3 = (ip_fw3_opheader *)rulebuf;
5785
ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5786
rule = (struct ip_fw_rule *)(ctlv + 1);
5787
rbufsize -= default_off;
5788
5789
compile_rule(av, (uint32_t *)rule, &rbufsize, &ts);
5790
/* Align rule size to u64 boundary */
5791
rlen = roundup2(rbufsize, sizeof(uint64_t));
5792
5793
tbuf = NULL;
5794
sz = 0;
5795
tstate = NULL;
5796
if (ts.count != 0) {
5797
/* Some tables. We have to alloc more data */
5798
tlen = ts.count * sizeof(ipfw_obj_ntlv);
5799
sz = default_off + sizeof(ipfw_obj_ctlv) + tlen + rlen;
5800
5801
if ((tbuf = calloc(1, sz)) == NULL)
5802
err(EX_UNAVAILABLE, "malloc() failed for IP_FW_XADD");
5803
op3 = (ip_fw3_opheader *)tbuf;
5804
/* Tables first */
5805
ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5806
ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
5807
ctlv->head.length = sizeof(ipfw_obj_ctlv) + tlen;
5808
ctlv->count = ts.count;
5809
ctlv->objsize = sizeof(ipfw_obj_ntlv);
5810
memcpy(ctlv + 1, ts.idx, tlen);
5811
object_sort_ctlv(ctlv);
5812
tstate = ctlv;
5813
/* Rule next */
5814
ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
5815
ctlv->head.type = IPFW_TLV_RULE_LIST;
5816
ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5817
ctlv->count = 1;
5818
memcpy(ctlv + 1, rule, rbufsize);
5819
} else {
5820
/* Simply add header */
5821
sz = rlen + default_off;
5822
memset(ctlv, 0, sizeof(*ctlv));
5823
ctlv->head.type = IPFW_TLV_RULE_LIST;
5824
ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5825
ctlv->count = 1;
5826
}
5827
5828
if (do_get3(IP_FW_XADD, op3, &sz) != 0)
5829
err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_XADD");
5830
5831
if (!g_co.do_quiet) {
5832
struct format_opts sfo;
5833
struct buf_pr bp;
5834
memset(&sfo, 0, sizeof(sfo));
5835
sfo.tstate = tstate;
5836
sfo.set_mask = (uint32_t)(-1);
5837
bp_alloc(&bp, 4096);
5838
show_static_rule(&g_co, &sfo, &bp, rule, NULL);
5839
printf("%s", bp.buf);
5840
bp_free(&bp);
5841
}
5842
5843
if (tbuf != NULL)
5844
free(tbuf);
5845
5846
if (ts.idx != NULL)
5847
free(ts.idx);
5848
}
5849
5850
/*
5851
* clear the counters or the log counters.
5852
* optname has the following values:
5853
* 0 (zero both counters and logging)
5854
* 1 (zero logging only)
5855
*/
5856
void
5857
ipfw_zero(int ac, char *av[], int optname)
5858
{
5859
ipfw_range_tlv rt;
5860
char const *errstr;
5861
char const *name = optname ? "RESETLOG" : "ZERO";
5862
uint32_t arg;
5863
int failed = EX_OK;
5864
5865
optname = optname ? IP_FW_XRESETLOG : IP_FW_XZERO;
5866
av++; ac--;
5867
5868
if (ac == 0) {
5869
/* clear all entries */
5870
memset(&rt, 0, sizeof(rt));
5871
rt.flags = IPFW_RCFLAG_ALL;
5872
if (do_range_cmd(optname, &rt) < 0)
5873
err(EX_UNAVAILABLE, "setsockopt(IP_FW_X%s)", name);
5874
if (!g_co.do_quiet)
5875
printf("%s.\n", optname == IP_FW_XZERO ?
5876
"Accounting cleared":"Logging counts reset");
5877
5878
return;
5879
}
5880
5881
while (ac) {
5882
/* Rule number */
5883
if (isdigit(**av)) {
5884
arg = strtonum(*av, 0, 0xffff, &errstr);
5885
if (errstr)
5886
errx(EX_DATAERR,
5887
"invalid rule number %s\n", *av);
5888
memset(&rt, 0, sizeof(rt));
5889
rt.start_rule = arg;
5890
rt.end_rule = arg;
5891
rt.flags |= IPFW_RCFLAG_RANGE;
5892
if (g_co.use_set != 0) {
5893
rt.set = g_co.use_set - 1;
5894
rt.flags |= IPFW_RCFLAG_SET;
5895
}
5896
if (do_range_cmd(optname, &rt) != 0) {
5897
warn("rule %u: setsockopt(IP_FW_X%s)",
5898
arg, name);
5899
failed = EX_UNAVAILABLE;
5900
} else if (rt.new_set == 0) {
5901
printf("Entry %d not found\n", arg);
5902
failed = EX_UNAVAILABLE;
5903
} else if (!g_co.do_quiet)
5904
printf("Entry %d %s.\n", arg,
5905
optname == IP_FW_XZERO ?
5906
"cleared" : "logging count reset");
5907
} else {
5908
errx(EX_USAGE, "invalid rule number ``%s''", *av);
5909
}
5910
av++; ac--;
5911
}
5912
if (failed != EX_OK)
5913
exit(failed);
5914
}
5915
5916
void
5917
ipfw_flush(int force)
5918
{
5919
ipfw_range_tlv rt;
5920
5921
if (!force && !g_co.do_quiet) { /* need to ask user */
5922
int c;
5923
5924
printf("Are you sure? [yn] ");
5925
fflush(stdout);
5926
do {
5927
c = toupper(getc(stdin));
5928
while (c != '\n' && getc(stdin) != '\n')
5929
if (feof(stdin))
5930
return; /* and do not flush */
5931
} while (c != 'Y' && c != 'N');
5932
printf("\n");
5933
if (c == 'N') /* user said no */
5934
return;
5935
}
5936
if (g_co.do_pipe) {
5937
dummynet_flush();
5938
return;
5939
}
5940
/* `ipfw set N flush` - is the same that `ipfw delete set N` */
5941
memset(&rt, 0, sizeof(rt));
5942
if (g_co.use_set != 0) {
5943
rt.set = g_co.use_set - 1;
5944
rt.flags = IPFW_RCFLAG_SET;
5945
} else
5946
rt.flags = IPFW_RCFLAG_ALL;
5947
if (do_range_cmd(IP_FW_XDEL, &rt) != 0)
5948
err(EX_UNAVAILABLE, "setsockopt(IP_FW_XDEL)");
5949
if (!g_co.do_quiet)
5950
printf("Flushed all %s.\n", g_co.do_pipe ? "pipes" : "rules");
5951
}
5952
5953
static struct _s_x intcmds[] = {
5954
{ "talist", TOK_TALIST },
5955
{ "iflist", TOK_IFLIST },
5956
{ "olist", TOK_OLIST },
5957
{ "vlist", TOK_VLIST },
5958
{ "monitor", TOK_MONITOR },
5959
{ NULL, 0 }
5960
};
5961
5962
static struct _s_x otypes[] = {
5963
{ "EACTION", IPFW_TLV_EACTION },
5964
{ "DYNSTATE", IPFW_TLV_STATE_NAME },
5965
{ NULL, 0 }
5966
};
5967
5968
static const char*
5969
lookup_eaction_name(ipfw_obj_ntlv *ntlv, int cnt, uint16_t type)
5970
{
5971
const char *name;
5972
int i;
5973
5974
name = NULL;
5975
for (i = 0; i < cnt; i++) {
5976
if (ntlv[i].head.type != IPFW_TLV_EACTION)
5977
continue;
5978
if (IPFW_TLV_EACTION_NAME(ntlv[i].idx) != type)
5979
continue;
5980
name = ntlv[i].name;
5981
break;
5982
}
5983
return (name);
5984
}
5985
5986
static void
5987
ipfw_list_objects(int ac __unused, char *av[] __unused)
5988
{
5989
ipfw_obj_lheader req, *olh;
5990
ipfw_obj_ntlv *ntlv;
5991
const char *name;
5992
size_t sz;
5993
uint32_t i;
5994
5995
memset(&req, 0, sizeof(req));
5996
sz = sizeof(req);
5997
if (do_get3(IP_FW_DUMP_SRVOBJECTS, &req.opheader, &sz) != 0)
5998
if (errno != ENOMEM)
5999
return;
6000
6001
sz = req.size;
6002
if ((olh = calloc(1, sz)) == NULL)
6003
return;
6004
6005
olh->size = sz;
6006
if (do_get3(IP_FW_DUMP_SRVOBJECTS, &olh->opheader, &sz) != 0) {
6007
free(olh);
6008
return;
6009
}
6010
6011
if (olh->count > 0)
6012
printf("Objects list:\n");
6013
else
6014
printf("There are no objects\n");
6015
ntlv = (ipfw_obj_ntlv *)(olh + 1);
6016
for (i = 0; i < olh->count; i++) {
6017
name = match_value(otypes, ntlv->head.type);
6018
if (name == NULL)
6019
name = lookup_eaction_name(
6020
(ipfw_obj_ntlv *)(olh + 1), olh->count,
6021
ntlv->head.type);
6022
if (name == NULL)
6023
printf(" kidx: %4d\ttype: %10d\tname: %s\n",
6024
ntlv->idx, ntlv->head.type, ntlv->name);
6025
else
6026
printf(" kidx: %4d\ttype: %10s\tname: %s\n",
6027
ntlv->idx, name, ntlv->name);
6028
ntlv++;
6029
}
6030
free(olh);
6031
}
6032
6033
static void
6034
bprint_sa(struct buf_pr *bp, const struct sockaddr *sa)
6035
{
6036
struct sockaddr_storage ss;
6037
char buf[INET6_ADDRSTRLEN];
6038
6039
memset(&ss, 0, sizeof(ss));
6040
if (sa->sa_len == 0)
6041
ss.ss_family = sa->sa_family;
6042
else
6043
memcpy(&ss, sa, sa->sa_len);
6044
6045
/* set ss_len in case it was shortened */
6046
switch (sa->sa_family) {
6047
case AF_INET:
6048
ss.ss_len = sizeof(struct sockaddr_in);
6049
break;
6050
default:
6051
ss.ss_len = sizeof(struct sockaddr_in6);
6052
}
6053
if (getnameinfo((const struct sockaddr *)&ss, ss.ss_len,
6054
buf, sizeof(buf), NULL, 0, NI_NUMERICHOST) != 0) {
6055
bprintf(bp, "bad-addr");
6056
return;
6057
}
6058
bprintf(bp, "%s", buf);
6059
}
6060
6061
static void
6062
ipfw_rtsock_monitor(const char *filter)
6063
{
6064
char msg[2048], buf[32];
6065
struct timespec tp;
6066
struct tm tm;
6067
struct buf_pr bp;
6068
struct rt_msghdr *hdr;
6069
struct sockaddr *sa;
6070
struct sockaddr_dl *sdl;
6071
ipfwlog_rtsock_hdr_v2 *loghdr;
6072
ssize_t nread;
6073
size_t msglen;
6074
int rtsock;
6075
6076
rtsock = socket(PF_ROUTE, SOCK_RAW, AF_IPFWLOG);
6077
if (rtsock < 0)
6078
err(EX_UNAVAILABLE, "socket(AF_IPFWLOG)");
6079
bp_alloc(&bp, 4096);
6080
for (;;) {
6081
nread = read(rtsock, msg, sizeof(msg));
6082
if (nread < 0) {
6083
warn("read()");
6084
continue;
6085
}
6086
msglen = nread;
6087
if (msglen < sizeof(*hdr))
6088
continue;
6089
6090
hdr = (struct rt_msghdr *)msg;
6091
if (hdr->rtm_version != RTM_VERSION ||
6092
hdr->rtm_type != RTM_IPFWLOG ||
6093
(hdr->rtm_addrs & (1 << RTAX_DST)) == 0 ||
6094
(hdr->rtm_addrs & (1 << RTAX_GATEWAY)) == 0 ||
6095
(hdr->rtm_addrs & (1 << RTAX_NETMASK)) == 0)
6096
continue;
6097
6098
msglen -= sizeof(*hdr);
6099
sdl = (struct sockaddr_dl *)(hdr + 1);
6100
if (msglen < sizeof(*sdl) || msglen < SA_SIZE(sdl) ||
6101
sdl->sdl_family != AF_IPFWLOG ||
6102
sdl->sdl_type != 2 /* version */ ||
6103
sdl->sdl_alen != sizeof(*loghdr))
6104
continue;
6105
6106
msglen -= SA_SIZE(sdl);
6107
loghdr = (ipfwlog_rtsock_hdr_v2 *)sdl->sdl_data;
6108
/* filter by rule comment. MAX_COMMENT_LEN = 80 */
6109
if (filter != NULL &&
6110
strncmp(filter, loghdr->comment, 80) != 0)
6111
continue;
6112
6113
sa = (struct sockaddr *)((char *)sdl + SA_SIZE(sdl));
6114
if (msglen < SA_SIZE(sa))
6115
continue;
6116
6117
msglen -= SA_SIZE(sa);
6118
bp_flush(&bp);
6119
6120
clock_gettime(CLOCK_REALTIME, &tp);
6121
localtime_r(&tp.tv_sec, &tm);
6122
strftime(buf, sizeof(buf), "%T", &tm);
6123
bprintf(&bp, "%s.%03ld AF %s", buf, tp.tv_nsec / 1000000,
6124
sa->sa_family == AF_INET ? "IPv4" : "IPv6");
6125
6126
bprintf(&bp, " %s >",
6127
ether_ntoa((const struct ether_addr *)loghdr->ether_shost));
6128
bprintf(&bp, " %s, ",
6129
ether_ntoa((const struct ether_addr *)loghdr->ether_dhost));
6130
bprint_sa(&bp, sa);
6131
6132
sa = (struct sockaddr *)((char *)sa + SA_SIZE(sa));
6133
if (msglen < SA_SIZE(sa))
6134
continue;
6135
6136
msglen -= SA_SIZE(sa);
6137
bprintf(&bp, " > ");
6138
bprint_sa(&bp, sa);
6139
bprintf(&bp, ", set %u, rulenum %u, targ 0x%08x, "
6140
"%scmd[op %d, len %d, arg1 0x%04x], mark 0x%08x",
6141
sdl->sdl_index, loghdr->rulenum, loghdr->tablearg,
6142
(loghdr->cmd.len & F_NOT) ? "!": "",
6143
loghdr->cmd.opcode, F_LEN(&loghdr->cmd),
6144
loghdr->cmd.arg1, loghdr->mark);
6145
6146
sa = (struct sockaddr *)((char *)sa + SA_SIZE(sa));
6147
if ((hdr->rtm_addrs & (1 << RTAX_GENMASK)) != 0 &&
6148
msglen >= SA_SIZE(sa)) {
6149
msglen -= SA_SIZE(sa);
6150
bprintf(&bp, ", nh ");
6151
bprint_sa(&bp, sa);
6152
}
6153
if (sdl->sdl_nlen > 0)
6154
bprintf(&bp, " // %s", loghdr->comment);
6155
printf("%s\n", bp.buf);
6156
}
6157
bp_free(&bp);
6158
close(rtsock);
6159
}
6160
6161
void
6162
ipfw_internal_handler(int ac, char *av[])
6163
{
6164
int tcmd;
6165
6166
ac--; av++;
6167
NEED1("internal cmd required");
6168
6169
if ((tcmd = match_token(intcmds, *av)) == -1)
6170
errx(EX_USAGE, "invalid internal sub-cmd: %s", *av);
6171
6172
switch (tcmd) {
6173
case TOK_IFLIST:
6174
ipfw_list_tifaces();
6175
break;
6176
case TOK_TALIST:
6177
ipfw_list_ta(ac, av);
6178
break;
6179
case TOK_OLIST:
6180
ipfw_list_objects(ac, av);
6181
break;
6182
case TOK_VLIST:
6183
ipfw_list_values(ac, av);
6184
break;
6185
case TOK_MONITOR:
6186
av++;
6187
ipfw_rtsock_monitor(*av);
6188
break;
6189
}
6190
}
6191
6192
static int
6193
ipfw_get_tracked_ifaces(ipfw_obj_lheader **polh)
6194
{
6195
ipfw_obj_lheader req, *olh;
6196
size_t sz;
6197
6198
memset(&req, 0, sizeof(req));
6199
sz = sizeof(req);
6200
6201
if (do_get3(IP_FW_XIFLIST, &req.opheader, &sz) != 0) {
6202
if (errno != ENOMEM)
6203
return (errno);
6204
}
6205
6206
sz = req.size;
6207
if ((olh = calloc(1, sz)) == NULL)
6208
return (ENOMEM);
6209
6210
olh->size = sz;
6211
if (do_get3(IP_FW_XIFLIST, &olh->opheader, &sz) != 0) {
6212
free(olh);
6213
return (errno);
6214
}
6215
6216
*polh = olh;
6217
return (0);
6218
}
6219
6220
static int
6221
ifinfo_cmp(const void *a, const void *b)
6222
{
6223
const ipfw_iface_info *ia, *ib;
6224
6225
ia = (const ipfw_iface_info *)a;
6226
ib = (const ipfw_iface_info *)b;
6227
6228
return (stringnum_cmp(ia->ifname, ib->ifname));
6229
}
6230
6231
/*
6232
* Retrieves table list from kernel,
6233
* optionally sorts it and calls requested function for each table.
6234
* Returns 0 on success.
6235
*/
6236
static void
6237
ipfw_list_tifaces(void)
6238
{
6239
ipfw_obj_lheader *olh = NULL;
6240
ipfw_iface_info *info;
6241
uint32_t i;
6242
int error;
6243
6244
if ((error = ipfw_get_tracked_ifaces(&olh)) != 0)
6245
err(EX_OSERR, "Unable to request ipfw tracked interface list");
6246
6247
qsort(olh + 1, olh->count, olh->objsize, ifinfo_cmp);
6248
6249
info = (ipfw_iface_info *)(olh + 1);
6250
for (i = 0; i < olh->count; i++) {
6251
if (info->flags & IPFW_IFFLAG_RESOLVED)
6252
printf("%s ifindex: %d refcount: %u changes: %u\n",
6253
info->ifname, info->ifindex, info->refcnt,
6254
info->gencnt);
6255
else
6256
printf("%s ifindex: unresolved refcount: %u changes: %u\n",
6257
info->ifname, info->refcnt, info->gencnt);
6258
info = (ipfw_iface_info *)((caddr_t)info + olh->objsize);
6259
}
6260
6261
free(olh);
6262
}
6263
6264