xref: /freebsd/lib/libpfctl/libpfctl.c (revision 105fd928b0b5b35ab529e5f6914788dc49582901)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2021 Rubicon Communications, LLC (Netgate)
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  *    - Redistributions of source code must retain the above copyright
12  *      notice, this list of conditions and the following disclaimer.
13  *    - Redistributions in binary form must reproduce the above
14  *      copyright notice, this list of conditions and the following
15  *      disclaimer in the documentation and/or other materials provided
16  *      with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
21  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
22  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
24  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  *
31  * $FreeBSD$
32  */
33 
34 #include <sys/cdefs.h>
35 
36 #include <sys/ioctl.h>
37 #include <sys/nv.h>
38 #include <sys/queue.h>
39 #include <sys/types.h>
40 
41 #include <net/if.h>
42 #include <net/pfvar.h>
43 #include <netinet/in.h>
44 
45 #include <assert.h>
46 #include <err.h>
47 #include <errno.h>
48 #include <stdlib.h>
49 #include <string.h>
50 
51 #include "libpfctl.h"
52 
53 const char* PFCTL_SYNCOOKIES_MODE_NAMES[] = {
54 	"never",
55 	"always",
56 	"adaptive"
57 };
58 
59 static int	_pfctl_clear_states(int , const struct pfctl_kill *,
60 		    unsigned int *, uint64_t);
61 
62 static void
63 pf_nvuint_8_array(const nvlist_t *nvl, const char *name, size_t maxelems,
64     u_int8_t *numbers, size_t *nelems)
65 {
66 	const uint64_t *tmp;
67 	size_t elems;
68 
69 	tmp = nvlist_get_number_array(nvl, name, &elems);
70 	assert(elems <= maxelems);
71 
72 	for (size_t i = 0; i < elems; i++)
73 		numbers[i] = tmp[i];
74 
75 	if (nelems)
76 		*nelems = elems;
77 }
78 
79 static void
80 pf_nvuint_16_array(const nvlist_t *nvl, const char *name, size_t maxelems,
81     u_int16_t *numbers, size_t *nelems)
82 {
83 	const uint64_t *tmp;
84 	size_t elems;
85 
86 	tmp = nvlist_get_number_array(nvl, name, &elems);
87 	assert(elems <= maxelems);
88 
89 	for (size_t i = 0; i < elems; i++)
90 		numbers[i] = tmp[i];
91 
92 	if (nelems)
93 		*nelems = elems;
94 }
95 
96 static void
97 pf_nvuint_32_array(const nvlist_t *nvl, const char *name, size_t maxelems,
98     u_int32_t *numbers, size_t *nelems)
99 {
100 	const uint64_t *tmp;
101 	size_t elems;
102 
103 	tmp = nvlist_get_number_array(nvl, name, &elems);
104 	assert(elems <= maxelems);
105 
106 	for (size_t i = 0; i < elems; i++)
107 		numbers[i] = tmp[i];
108 
109 	if (nelems)
110 		*nelems = elems;
111 }
112 
113 static void
114 pf_nvuint_64_array(const nvlist_t *nvl, const char *name, size_t maxelems,
115     u_int64_t *numbers, size_t *nelems)
116 {
117 	const uint64_t *tmp;
118 	size_t elems;
119 
120 	tmp = nvlist_get_number_array(nvl, name, &elems);
121 	assert(elems <= maxelems);
122 
123 	for (size_t i = 0; i < elems; i++)
124 		numbers[i] = tmp[i];
125 
126 	if (nelems)
127 		*nelems = elems;
128 }
129 
130 static void
131 _pfctl_get_status_counters(const nvlist_t *nvl,
132     struct pfctl_status_counters *counters)
133 {
134 	const uint64_t		*ids, *counts;
135 	const char *const	*names;
136 	size_t id_len, counter_len, names_len;
137 
138 	ids = nvlist_get_number_array(nvl, "ids", &id_len);
139 	counts = nvlist_get_number_array(nvl, "counters", &counter_len);
140 	names = nvlist_get_string_array(nvl, "names", &names_len);
141 	assert(id_len == counter_len);
142 	assert(counter_len == names_len);
143 
144 	TAILQ_INIT(counters);
145 
146 	for (size_t i = 0; i < id_len; i++) {
147 		struct pfctl_status_counter *c;
148 
149 		c = malloc(sizeof(*c));
150 
151 		c->id = ids[i];
152 		c->counter = counts[i];
153 		c->name = strdup(names[i]);
154 
155 		TAILQ_INSERT_TAIL(counters, c, entry);
156 	}
157 }
158 
159 struct pfctl_status *
160 pfctl_get_status(int dev)
161 {
162 	struct pfioc_nv	 nv;
163 	struct pfctl_status	*status;
164 	nvlist_t	*nvl;
165 	size_t		 len;
166 	const void	*chksum;
167 
168 	status = calloc(1, sizeof(*status));
169 	if (status == NULL)
170 		return (NULL);
171 
172 	nv.data = malloc(4096);
173 	nv.len = nv.size = 4096;
174 
175 	if (ioctl(dev, DIOCGETSTATUSNV, &nv)) {
176 		free(nv.data);
177 		free(status);
178 		return (NULL);
179 	}
180 
181 	nvl = nvlist_unpack(nv.data, nv.len, 0);
182 	free(nv.data);
183 	if (nvl == NULL) {
184 		free(status);
185 		return (NULL);
186 	}
187 
188 	status->running = nvlist_get_bool(nvl, "running");
189 	status->since = nvlist_get_number(nvl, "since");
190 	status->debug = nvlist_get_number(nvl, "debug");
191 	status->hostid = nvlist_get_number(nvl, "hostid");
192 	status->states = nvlist_get_number(nvl, "states");
193 	status->src_nodes = nvlist_get_number(nvl, "src_nodes");
194 
195 	strlcpy(status->ifname, nvlist_get_string(nvl, "ifname"),
196 	    IFNAMSIZ);
197 	chksum = nvlist_get_binary(nvl, "chksum", &len);
198 	assert(len == PF_MD5_DIGEST_LENGTH);
199 	memcpy(status->pf_chksum, chksum, len);
200 
201 	_pfctl_get_status_counters(nvlist_get_nvlist(nvl, "counters"),
202 	    &status->counters);
203 	_pfctl_get_status_counters(nvlist_get_nvlist(nvl, "lcounters"),
204 	    &status->lcounters);
205 	_pfctl_get_status_counters(nvlist_get_nvlist(nvl, "fcounters"),
206 	    &status->fcounters);
207 	_pfctl_get_status_counters(nvlist_get_nvlist(nvl, "scounters"),
208 	    &status->scounters);
209 
210 	pf_nvuint_64_array(nvl, "pcounters", 2 * 2 * 3,
211 	    (uint64_t *)status->pcounters, NULL);
212 	pf_nvuint_64_array(nvl, "bcounters", 2 * 2,
213 	    (uint64_t *)status->bcounters, NULL);
214 
215 	nvlist_destroy(nvl);
216 
217 	return (status);
218 }
219 
220 void
221 pfctl_free_status(struct pfctl_status *status)
222 {
223 	struct pfctl_status_counter *c, *tmp;
224 
225 	TAILQ_FOREACH_SAFE(c, &status->counters, entry, tmp) {
226 		free(c->name);
227 		free(c);
228 	}
229 	TAILQ_FOREACH_SAFE(c, &status->lcounters, entry, tmp) {
230 		free(c->name);
231 		free(c);
232 	}
233 	TAILQ_FOREACH_SAFE(c, &status->fcounters, entry, tmp) {
234 		free(c->name);
235 		free(c);
236 	}
237 	TAILQ_FOREACH_SAFE(c, &status->scounters, entry, tmp) {
238 		free(c->name);
239 		free(c);
240 	}
241 
242 	free(status);
243 }
244 
245 static void
246 pfctl_nv_add_addr(nvlist_t *nvparent, const char *name,
247     const struct pf_addr *addr)
248 {
249 	nvlist_t *nvl = nvlist_create(0);
250 
251 	nvlist_add_binary(nvl, "addr", addr, sizeof(*addr));
252 
253 	nvlist_add_nvlist(nvparent, name, nvl);
254 	nvlist_destroy(nvl);
255 }
256 
257 static void
258 pf_nvaddr_to_addr(const nvlist_t *nvl, struct pf_addr *addr)
259 {
260 	size_t len;
261 	const void *data;
262 
263 	data = nvlist_get_binary(nvl, "addr", &len);
264 	assert(len == sizeof(struct pf_addr));
265 	memcpy(addr, data, len);
266 }
267 
268 static void
269 pfctl_nv_add_addr_wrap(nvlist_t *nvparent, const char *name,
270     const struct pf_addr_wrap *addr)
271 {
272 	nvlist_t *nvl = nvlist_create(0);
273 
274 	nvlist_add_number(nvl, "type", addr->type);
275 	nvlist_add_number(nvl, "iflags", addr->iflags);
276 	if (addr->type == PF_ADDR_DYNIFTL)
277 		nvlist_add_string(nvl, "ifname", addr->v.ifname);
278 	if (addr->type == PF_ADDR_TABLE)
279 		nvlist_add_string(nvl, "tblname", addr->v.tblname);
280 	pfctl_nv_add_addr(nvl, "addr", &addr->v.a.addr);
281 	pfctl_nv_add_addr(nvl, "mask", &addr->v.a.mask);
282 
283 	nvlist_add_nvlist(nvparent, name, nvl);
284 	nvlist_destroy(nvl);
285 }
286 
287 static void
288 pf_nvaddr_wrap_to_addr_wrap(const nvlist_t *nvl, struct pf_addr_wrap *addr)
289 {
290 	addr->type = nvlist_get_number(nvl, "type");
291 	addr->iflags = nvlist_get_number(nvl, "iflags");
292 	if (addr->type == PF_ADDR_DYNIFTL)
293 		strlcpy(addr->v.ifname, nvlist_get_string(nvl, "ifname"),
294 		    IFNAMSIZ);
295 	if (addr->type == PF_ADDR_TABLE)
296 		strlcpy(addr->v.tblname, nvlist_get_string(nvl, "tblname"),
297 		    PF_TABLE_NAME_SIZE);
298 
299 	pf_nvaddr_to_addr(nvlist_get_nvlist(nvl, "addr"), &addr->v.a.addr);
300 	pf_nvaddr_to_addr(nvlist_get_nvlist(nvl, "mask"), &addr->v.a.mask);
301 }
302 
303 static void
304 pfctl_nv_add_rule_addr(nvlist_t *nvparent, const char *name,
305     const struct pf_rule_addr *addr)
306 {
307 	u_int64_t ports[2];
308 	nvlist_t *nvl = nvlist_create(0);
309 
310 	pfctl_nv_add_addr_wrap(nvl, "addr", &addr->addr);
311 	ports[0] = addr->port[0];
312 	ports[1] = addr->port[1];
313 	nvlist_add_number_array(nvl, "port", ports, 2);
314 	nvlist_add_number(nvl, "neg", addr->neg);
315 	nvlist_add_number(nvl, "port_op", addr->port_op);
316 
317 	nvlist_add_nvlist(nvparent, name, nvl);
318 	nvlist_destroy(nvl);
319 }
320 
321 static void
322 pf_nvrule_addr_to_rule_addr(const nvlist_t *nvl, struct pf_rule_addr *addr)
323 {
324 	pf_nvaddr_wrap_to_addr_wrap(nvlist_get_nvlist(nvl, "addr"), &addr->addr);
325 
326 	pf_nvuint_16_array(nvl, "port", 2, addr->port, NULL);
327 	addr->neg = nvlist_get_number(nvl, "neg");
328 	addr->port_op = nvlist_get_number(nvl, "port_op");
329 }
330 
331 static void
332 pfctl_nv_add_mape(nvlist_t *nvparent, const char *name,
333     const struct pf_mape_portset *mape)
334 {
335 	nvlist_t *nvl = nvlist_create(0);
336 
337 	nvlist_add_number(nvl, "offset", mape->offset);
338 	nvlist_add_number(nvl, "psidlen", mape->psidlen);
339 	nvlist_add_number(nvl, "psid", mape->psid);
340 	nvlist_add_nvlist(nvparent, name, nvl);
341 	nvlist_destroy(nvl);
342 }
343 
344 static void
345 pfctl_nv_add_pool(nvlist_t *nvparent, const char *name,
346     const struct pfctl_pool *pool)
347 {
348 	u_int64_t ports[2];
349 	nvlist_t *nvl = nvlist_create(0);
350 
351 	nvlist_add_binary(nvl, "key", &pool->key, sizeof(pool->key));
352 	pfctl_nv_add_addr(nvl, "counter", &pool->counter);
353 	nvlist_add_number(nvl, "tblidx", pool->tblidx);
354 
355 	ports[0] = pool->proxy_port[0];
356 	ports[1] = pool->proxy_port[1];
357 	nvlist_add_number_array(nvl, "proxy_port", ports, 2);
358 	nvlist_add_number(nvl, "opts", pool->opts);
359 	pfctl_nv_add_mape(nvl, "mape", &pool->mape);
360 
361 	nvlist_add_nvlist(nvparent, name, nvl);
362 	nvlist_destroy(nvl);
363 }
364 
365 static void
366 pf_nvmape_to_mape(const nvlist_t *nvl, struct pf_mape_portset *mape)
367 {
368 	mape->offset = nvlist_get_number(nvl, "offset");
369 	mape->psidlen = nvlist_get_number(nvl, "psidlen");
370 	mape->psid = nvlist_get_number(nvl, "psid");
371 }
372 
373 static void
374 pf_nvpool_to_pool(const nvlist_t *nvl, struct pfctl_pool *pool)
375 {
376 	size_t len;
377 	const void *data;
378 
379 	data = nvlist_get_binary(nvl, "key", &len);
380 	assert(len == sizeof(pool->key));
381 	memcpy(&pool->key, data, len);
382 
383 	pf_nvaddr_to_addr(nvlist_get_nvlist(nvl, "counter"), &pool->counter);
384 
385 	pool->tblidx = nvlist_get_number(nvl, "tblidx");
386 	pf_nvuint_16_array(nvl, "proxy_port", 2, pool->proxy_port, NULL);
387 	pool->opts = nvlist_get_number(nvl, "opts");
388 
389 	if (nvlist_exists_nvlist(nvl, "mape"))
390 		pf_nvmape_to_mape(nvlist_get_nvlist(nvl, "mape"), &pool->mape);
391 }
392 
393 static void
394 pfctl_nv_add_uid(nvlist_t *nvparent, const char *name,
395     const struct pf_rule_uid *uid)
396 {
397 	u_int64_t uids[2];
398 	nvlist_t *nvl = nvlist_create(0);
399 
400 	uids[0] = uid->uid[0];
401 	uids[1] = uid->uid[1];
402 	nvlist_add_number_array(nvl, "uid", uids, 2);
403 	nvlist_add_number(nvl, "op", uid->op);
404 
405 	nvlist_add_nvlist(nvparent, name, nvl);
406 	nvlist_destroy(nvl);
407 }
408 
409 static void
410 pf_nvrule_uid_to_rule_uid(const nvlist_t *nvl, struct pf_rule_uid *uid)
411 {
412 	pf_nvuint_32_array(nvl, "uid", 2, uid->uid, NULL);
413 	uid->op = nvlist_get_number(nvl, "op");
414 }
415 
416 static void
417 pfctl_nv_add_divert(nvlist_t *nvparent, const char *name,
418     const struct pfctl_rule *r)
419 {
420 	nvlist_t *nvl = nvlist_create(0);
421 
422 	pfctl_nv_add_addr(nvl, "addr", &r->divert.addr);
423 	nvlist_add_number(nvl, "port", r->divert.port);
424 
425 	nvlist_add_nvlist(nvparent, name, nvl);
426 	nvlist_destroy(nvl);
427 }
428 
429 static void
430 pf_nvdivert_to_divert(const nvlist_t *nvl, struct pfctl_rule *rule)
431 {
432 	pf_nvaddr_to_addr(nvlist_get_nvlist(nvl, "addr"), &rule->divert.addr);
433 	rule->divert.port = nvlist_get_number(nvl, "port");
434 }
435 
436 static void
437 pf_nvrule_to_rule(const nvlist_t *nvl, struct pfctl_rule *rule)
438 {
439 	const uint64_t *skip;
440 	const char *const *labels;
441 	size_t skipcount, labelcount;
442 
443 	rule->nr = nvlist_get_number(nvl, "nr");
444 
445 	pf_nvrule_addr_to_rule_addr(nvlist_get_nvlist(nvl, "src"), &rule->src);
446 	pf_nvrule_addr_to_rule_addr(nvlist_get_nvlist(nvl, "dst"), &rule->dst);
447 
448 	skip = nvlist_get_number_array(nvl, "skip", &skipcount);
449 	assert(skip);
450 	assert(skipcount == PF_SKIP_COUNT);
451 	for (int i = 0; i < PF_SKIP_COUNT; i++)
452 		rule->skip[i].nr = skip[i];
453 
454 	labels = nvlist_get_string_array(nvl, "labels", &labelcount);
455 	assert(labelcount <= PF_RULE_MAX_LABEL_COUNT);
456 	for (size_t i = 0; i < labelcount; i++)
457 		strlcpy(rule->label[i], labels[i], PF_RULE_LABEL_SIZE);
458 	strlcpy(rule->ifname, nvlist_get_string(nvl, "ifname"), IFNAMSIZ);
459 	strlcpy(rule->qname, nvlist_get_string(nvl, "qname"), PF_QNAME_SIZE);
460 	strlcpy(rule->pqname, nvlist_get_string(nvl, "pqname"), PF_QNAME_SIZE);
461 	strlcpy(rule->tagname, nvlist_get_string(nvl, "tagname"),
462 	    PF_TAG_NAME_SIZE);
463 	strlcpy(rule->match_tagname, nvlist_get_string(nvl, "match_tagname"),
464 	    PF_TAG_NAME_SIZE);
465 
466 	strlcpy(rule->overload_tblname, nvlist_get_string(nvl, "overload_tblname"),
467 	    PF_TABLE_NAME_SIZE);
468 
469 	pf_nvpool_to_pool(nvlist_get_nvlist(nvl, "rpool"), &rule->rpool);
470 
471 	rule->evaluations = nvlist_get_number(nvl, "evaluations");
472 	pf_nvuint_64_array(nvl, "packets", 2, rule->packets, NULL);
473 	pf_nvuint_64_array(nvl, "bytes", 2, rule->bytes, NULL);
474 
475 	rule->os_fingerprint = nvlist_get_number(nvl, "os_fingerprint");
476 
477 	rule->rtableid = nvlist_get_number(nvl, "rtableid");
478 	pf_nvuint_32_array(nvl, "timeout", PFTM_MAX, rule->timeout, NULL);
479 	rule->max_states = nvlist_get_number(nvl, "max_states");
480 	rule->max_src_nodes = nvlist_get_number(nvl, "max_src_nodes");
481 	rule->max_src_states = nvlist_get_number(nvl, "max_src_states");
482 	rule->max_src_conn = nvlist_get_number(nvl, "max_src_conn");
483 	rule->max_src_conn_rate.limit =
484 	    nvlist_get_number(nvl, "max_src_conn_rate.limit");
485 	rule->max_src_conn_rate.seconds =
486 	    nvlist_get_number(nvl, "max_src_conn_rate.seconds");
487 	rule->qid = nvlist_get_number(nvl, "qid");
488 	rule->pqid = nvlist_get_number(nvl, "pqid");
489 	rule->dnpipe = nvlist_get_number(nvl, "dnpipe");
490 	rule->dnrpipe = nvlist_get_number(nvl, "dnrpipe");
491 	rule->free_flags = nvlist_get_number(nvl, "dnflags");
492 	rule->prob = nvlist_get_number(nvl, "prob");
493 	rule->cuid = nvlist_get_number(nvl, "cuid");
494 	rule->cpid = nvlist_get_number(nvl, "cpid");
495 
496 	rule->return_icmp = nvlist_get_number(nvl, "return_icmp");
497 	rule->return_icmp6 = nvlist_get_number(nvl, "return_icmp6");
498 	rule->max_mss = nvlist_get_number(nvl, "max_mss");
499 	rule->scrub_flags = nvlist_get_number(nvl, "scrub_flags");
500 
501 	pf_nvrule_uid_to_rule_uid(nvlist_get_nvlist(nvl, "uid"), &rule->uid);
502 	pf_nvrule_uid_to_rule_uid(nvlist_get_nvlist(nvl, "gid"),
503 	    (struct pf_rule_uid *)&rule->gid);
504 
505 	rule->rule_flag = nvlist_get_number(nvl, "rule_flag");
506 	rule->action = nvlist_get_number(nvl, "action");
507 	rule->direction = nvlist_get_number(nvl, "direction");
508 	rule->log = nvlist_get_number(nvl, "log");
509 	rule->logif = nvlist_get_number(nvl, "logif");
510 	rule->quick = nvlist_get_number(nvl, "quick");
511 	rule->ifnot = nvlist_get_number(nvl, "ifnot");
512 	rule->match_tag_not = nvlist_get_number(nvl, "match_tag_not");
513 	rule->natpass = nvlist_get_number(nvl, "natpass");
514 
515 	rule->keep_state = nvlist_get_number(nvl, "keep_state");
516 	rule->af = nvlist_get_number(nvl, "af");
517 	rule->proto = nvlist_get_number(nvl, "proto");
518 	rule->type = nvlist_get_number(nvl, "type");
519 	rule->code = nvlist_get_number(nvl, "code");
520 	rule->flags = nvlist_get_number(nvl, "flags");
521 	rule->flagset = nvlist_get_number(nvl, "flagset");
522 	rule->min_ttl = nvlist_get_number(nvl, "min_ttl");
523 	rule->allow_opts = nvlist_get_number(nvl, "allow_opts");
524 	rule->rt = nvlist_get_number(nvl, "rt");
525 	rule->return_ttl  = nvlist_get_number(nvl, "return_ttl");
526 	rule->tos = nvlist_get_number(nvl, "tos");
527 	rule->set_tos = nvlist_get_number(nvl, "set_tos");
528 	rule->anchor_relative = nvlist_get_number(nvl, "anchor_relative");
529 	rule->anchor_wildcard = nvlist_get_number(nvl, "anchor_wildcard");
530 
531 	rule->flush = nvlist_get_number(nvl, "flush");
532 	rule->prio = nvlist_get_number(nvl, "prio");
533 	pf_nvuint_8_array(nvl, "set_prio", 2, rule->set_prio, NULL);
534 
535 	pf_nvdivert_to_divert(nvlist_get_nvlist(nvl, "divert"), rule);
536 
537 	rule->states_cur = nvlist_get_number(nvl, "states_cur");
538 	rule->states_tot = nvlist_get_number(nvl, "states_tot");
539 	rule->src_nodes = nvlist_get_number(nvl, "src_nodes");
540 }
541 
542 int
543 pfctl_add_rule(int dev, const struct pfctl_rule *r, const char *anchor,
544     const char *anchor_call, u_int32_t ticket, u_int32_t pool_ticket)
545 {
546 	struct pfioc_nv nv;
547 	u_int64_t timeouts[PFTM_MAX];
548 	u_int64_t set_prio[2];
549 	nvlist_t *nvl, *nvlr;
550 	size_t labelcount;
551 	int ret;
552 
553 	nvl = nvlist_create(0);
554 	nvlr = nvlist_create(0);
555 
556 	nvlist_add_number(nvl, "ticket", ticket);
557 	nvlist_add_number(nvl, "pool_ticket", pool_ticket);
558 	nvlist_add_string(nvl, "anchor", anchor);
559 	nvlist_add_string(nvl, "anchor_call", anchor_call);
560 
561 	nvlist_add_number(nvlr, "nr", r->nr);
562 	pfctl_nv_add_rule_addr(nvlr, "src", &r->src);
563 	pfctl_nv_add_rule_addr(nvlr, "dst", &r->dst);
564 
565 	labelcount = 0;
566 	while (r->label[labelcount][0] != 0 &&
567 	    labelcount < PF_RULE_MAX_LABEL_COUNT) {
568 		nvlist_append_string_array(nvlr, "labels",
569 		    r->label[labelcount]);
570 		labelcount++;
571 	}
572 
573 	nvlist_add_string(nvlr, "ifname", r->ifname);
574 	nvlist_add_string(nvlr, "qname", r->qname);
575 	nvlist_add_string(nvlr, "pqname", r->pqname);
576 	nvlist_add_string(nvlr, "tagname", r->tagname);
577 	nvlist_add_string(nvlr, "match_tagname", r->match_tagname);
578 	nvlist_add_string(nvlr, "overload_tblname", r->overload_tblname);
579 
580 	pfctl_nv_add_pool(nvlr, "rpool", &r->rpool);
581 
582 	nvlist_add_number(nvlr, "os_fingerprint", r->os_fingerprint);
583 
584 	nvlist_add_number(nvlr, "rtableid", r->rtableid);
585 	for (int i = 0; i < PFTM_MAX; i++)
586 		timeouts[i] = r->timeout[i];
587 	nvlist_add_number_array(nvlr, "timeout", timeouts, PFTM_MAX);
588 	nvlist_add_number(nvlr, "max_states", r->max_states);
589 	nvlist_add_number(nvlr, "max_src_nodes", r->max_src_nodes);
590 	nvlist_add_number(nvlr, "max_src_states", r->max_src_states);
591 	nvlist_add_number(nvlr, "max_src_conn", r->max_src_conn);
592 	nvlist_add_number(nvlr, "max_src_conn_rate.limit",
593 	    r->max_src_conn_rate.limit);
594 	nvlist_add_number(nvlr, "max_src_conn_rate.seconds",
595 	    r->max_src_conn_rate.seconds);
596 	nvlist_add_number(nvlr, "dnpipe", r->dnpipe);
597 	nvlist_add_number(nvlr, "dnrpipe", r->dnrpipe);
598 	nvlist_add_number(nvlr, "dnflags", r->free_flags);
599 	nvlist_add_number(nvlr, "prob", r->prob);
600 	nvlist_add_number(nvlr, "cuid", r->cuid);
601 	nvlist_add_number(nvlr, "cpid", r->cpid);
602 
603 	nvlist_add_number(nvlr, "return_icmp", r->return_icmp);
604 	nvlist_add_number(nvlr, "return_icmp6", r->return_icmp6);
605 
606 	nvlist_add_number(nvlr, "max_mss", r->max_mss);
607 	nvlist_add_number(nvlr, "scrub_flags", r->scrub_flags);
608 
609 	pfctl_nv_add_uid(nvlr, "uid", &r->uid);
610 	pfctl_nv_add_uid(nvlr, "gid", (const struct pf_rule_uid *)&r->gid);
611 
612 	nvlist_add_number(nvlr, "rule_flag", r->rule_flag);
613 	nvlist_add_number(nvlr, "action", r->action);
614 	nvlist_add_number(nvlr, "direction", r->direction);
615 	nvlist_add_number(nvlr, "log", r->log);
616 	nvlist_add_number(nvlr, "logif", r->logif);
617 	nvlist_add_number(nvlr, "quick", r->quick);
618 	nvlist_add_number(nvlr, "ifnot", r->ifnot);
619 	nvlist_add_number(nvlr, "match_tag_not", r->match_tag_not);
620 	nvlist_add_number(nvlr, "natpass", r->natpass);
621 
622 	nvlist_add_number(nvlr, "keep_state", r->keep_state);
623 	nvlist_add_number(nvlr, "af", r->af);
624 	nvlist_add_number(nvlr, "proto", r->proto);
625 	nvlist_add_number(nvlr, "type", r->type);
626 	nvlist_add_number(nvlr, "code", r->code);
627 	nvlist_add_number(nvlr, "flags", r->flags);
628 	nvlist_add_number(nvlr, "flagset", r->flagset);
629 	nvlist_add_number(nvlr, "min_ttl", r->min_ttl);
630 	nvlist_add_number(nvlr, "allow_opts", r->allow_opts);
631 	nvlist_add_number(nvlr, "rt", r->rt);
632 	nvlist_add_number(nvlr, "return_ttl", r->return_ttl);
633 	nvlist_add_number(nvlr, "tos", r->tos);
634 	nvlist_add_number(nvlr, "set_tos", r->set_tos);
635 	nvlist_add_number(nvlr, "anchor_relative", r->anchor_relative);
636 	nvlist_add_number(nvlr, "anchor_wildcard", r->anchor_wildcard);
637 
638 	nvlist_add_number(nvlr, "flush", r->flush);
639 
640 	nvlist_add_number(nvlr, "prio", r->prio);
641 	set_prio[0] = r->set_prio[0];
642 	set_prio[1] = r->set_prio[1];
643 	nvlist_add_number_array(nvlr, "set_prio", set_prio, 2);
644 
645 	pfctl_nv_add_divert(nvlr, "divert", r);
646 
647 	nvlist_add_nvlist(nvl, "rule", nvlr);
648 	nvlist_destroy(nvlr);
649 
650 	/* Now do the call. */
651 	nv.data = nvlist_pack(nvl, &nv.len);
652 	nv.size = nv.len;
653 
654 	ret = ioctl(dev, DIOCADDRULENV, &nv);
655 
656 	free(nv.data);
657 	nvlist_destroy(nvl);
658 
659 	return (ret);
660 }
661 
662 int
663 pfctl_get_rule(int dev, u_int32_t nr, u_int32_t ticket, const char *anchor,
664     u_int32_t ruleset, struct pfctl_rule *rule, char *anchor_call)
665 {
666 	return (pfctl_get_clear_rule(dev, nr, ticket, anchor, ruleset, rule,
667 	    anchor_call, false));
668 }
669 
670 int	pfctl_get_clear_rule(int dev, u_int32_t nr, u_int32_t ticket,
671 	    const char *anchor, u_int32_t ruleset, struct pfctl_rule *rule,
672 	    char *anchor_call, bool clear)
673 {
674 	struct pfioc_nv nv;
675 	nvlist_t *nvl;
676 	void *nvlpacked;
677 	int ret;
678 
679 	nvl = nvlist_create(0);
680 	if (nvl == 0)
681 		return (ENOMEM);
682 
683 	nvlist_add_number(nvl, "nr", nr);
684 	nvlist_add_number(nvl, "ticket", ticket);
685 	nvlist_add_string(nvl, "anchor", anchor);
686 	nvlist_add_number(nvl, "ruleset", ruleset);
687 
688 	if (clear)
689 		nvlist_add_bool(nvl, "clear_counter", true);
690 
691 	nvlpacked = nvlist_pack(nvl, &nv.len);
692 	if (nvlpacked == NULL) {
693 		nvlist_destroy(nvl);
694 		return (ENOMEM);
695 	}
696 	nv.data = malloc(8182);
697 	nv.size = 8192;
698 	assert(nv.len <= nv.size);
699 	memcpy(nv.data, nvlpacked, nv.len);
700 	nvlist_destroy(nvl);
701 	nvl = NULL;
702 	free(nvlpacked);
703 
704 	ret = ioctl(dev, DIOCGETRULENV, &nv);
705 	if (ret != 0) {
706 		free(nv.data);
707 		return (ret);
708 	}
709 
710 	nvl = nvlist_unpack(nv.data, nv.len, 0);
711 	if (nvl == NULL) {
712 		free(nv.data);
713 		return (EIO);
714 	}
715 
716 	pf_nvrule_to_rule(nvlist_get_nvlist(nvl, "rule"), rule);
717 
718 	if (anchor_call)
719 		strlcpy(anchor_call, nvlist_get_string(nvl, "anchor_call"),
720 		    MAXPATHLEN);
721 
722 	free(nv.data);
723 	nvlist_destroy(nvl);
724 
725 	return (0);
726 }
727 
728 int
729 pfctl_set_keepcounters(int dev, bool keep)
730 {
731 	struct pfioc_nv	 nv;
732 	nvlist_t	*nvl;
733 	int		 ret;
734 
735 	nvl = nvlist_create(0);
736 
737 	nvlist_add_bool(nvl, "keep_counters", keep);
738 
739 	nv.data = nvlist_pack(nvl, &nv.len);
740 	nv.size = nv.len;
741 
742 	nvlist_destroy(nvl);
743 
744 	ret = ioctl(dev, DIOCKEEPCOUNTERS, &nv);
745 
746 	free(nv.data);
747 	return (ret);
748 }
749 
750 static void
751 pfctl_nv_add_state_cmp(nvlist_t *nvl, const char *name,
752     const struct pfctl_state_cmp *cmp)
753 {
754 	nvlist_t	*nv;
755 
756 	nv = nvlist_create(0);
757 
758 	nvlist_add_number(nv, "id", cmp->id);
759 	nvlist_add_number(nv, "creatorid", cmp->creatorid);
760 	nvlist_add_number(nv, "direction", cmp->direction);
761 
762 	nvlist_add_nvlist(nvl, name, nv);
763 	nvlist_destroy(nv);
764 }
765 
766 static void
767 pf_state_key_export_to_state_key(struct pfctl_state_key *ps,
768     const struct pf_state_key_export *s)
769 {
770 	bcopy(s->addr, ps->addr, sizeof(ps->addr[0]) * 2);
771 	ps->port[0] = s->port[0];
772 	ps->port[1] = s->port[1];
773 }
774 
775 static void
776 pf_state_peer_export_to_state_peer(struct pfctl_state_peer *ps,
777     const struct pf_state_peer_export *s)
778 {
779 	/* Ignore scrub. */
780 	ps->seqlo = s->seqlo;
781 	ps->seqhi = s->seqhi;
782 	ps->seqdiff = s->seqdiff;
783 	/* Ignore max_win & mss */
784 	ps->state = s->state;
785 	ps->wscale = s->wscale;
786 }
787 
788 static void
789 pf_state_export_to_state(struct pfctl_state *ps, const struct pf_state_export *s)
790 {
791 	assert(s->version >= PF_STATE_VERSION);
792 
793 	ps->id = s->id;
794 	strlcpy(ps->ifname, s->ifname, sizeof(ps->ifname));
795 	strlcpy(ps->orig_ifname, s->orig_ifname, sizeof(ps->orig_ifname));
796 	pf_state_key_export_to_state_key(&ps->key[0], &s->key[0]);
797 	pf_state_key_export_to_state_key(&ps->key[1], &s->key[1]);
798 	pf_state_peer_export_to_state_peer(&ps->src, &s->src);
799 	pf_state_peer_export_to_state_peer(&ps->dst, &s->dst);
800 	bcopy(&s->rt_addr, &ps->rt_addr, sizeof(ps->rt_addr));
801 	ps->rule = ntohl(s->rule);
802 	ps->anchor = ntohl(s->anchor);
803 	ps->nat_rule = ntohl(s->nat_rule);
804 	ps->creation = ntohl(s->creation);
805 	ps->expire = ntohl(s->expire);
806 	ps->packets[0] = s->packets[0];
807 	ps->packets[1] = s->packets[1];
808 	ps->bytes[0] = s->bytes[0];
809 	ps->bytes[1] = s->bytes[1];
810 	ps->creatorid = s->creatorid;
811 	ps->key[0].proto = s->proto;
812 	ps->key[1].proto = s->proto;
813 	ps->key[0].af = s->af;
814 	ps->key[1].af = s->af;
815 	ps->direction = s->direction;
816 	ps->state_flags = s->state_flags;
817 	ps->sync_flags = s->sync_flags;
818 }
819 
820 int
821 pfctl_get_states(int dev, struct pfctl_states *states)
822 {
823 	struct pfioc_states_v2 ps;
824 	struct pf_state_export *p;
825 	char *inbuf = NULL, *newinbuf = NULL;
826 	unsigned int len = 0;
827 	int i, error;
828 
829 	bzero(&ps, sizeof(ps));
830 	ps.ps_req_version = PF_STATE_VERSION;
831 
832 	bzero(states, sizeof(*states));
833 	TAILQ_INIT(&states->states);
834 
835 	for (;;) {
836 		ps.ps_len = len;
837 		if (len) {
838 			newinbuf = realloc(inbuf, len);
839 			if (newinbuf == NULL)
840 				return (ENOMEM);
841 			ps.ps_buf = inbuf = newinbuf;
842 		}
843 		if ((error = ioctl(dev, DIOCGETSTATESV2, &ps)) < 0) {
844 			free(inbuf);
845 			return (error);
846 		}
847 		if (ps.ps_len + sizeof(struct pfioc_states_v2) < len)
848 			break;
849 		if (len == 0 && ps.ps_len == 0)
850 			goto out;
851 		if (len == 0 && ps.ps_len != 0)
852 			len = ps.ps_len;
853 		if (ps.ps_len == 0)
854 			goto out;      /* no states */
855 		len *= 2;
856 	}
857 	p = ps.ps_states;
858 
859 	for (i = 0; i < ps.ps_len; i += sizeof(*p), p++) {
860 		struct pfctl_state *s = malloc(sizeof(*s));
861 		if (s == NULL) {
862 			pfctl_free_states(states);
863 			error = ENOMEM;
864 			goto out;
865 		}
866 
867 		pf_state_export_to_state(s, p);
868 		TAILQ_INSERT_TAIL(&states->states, s, entry);
869 	}
870 
871 out:
872 	free(inbuf);
873 	return (error);
874 }
875 
876 void
877 pfctl_free_states(struct pfctl_states *states)
878 {
879 	struct pfctl_state *s, *tmp;
880 
881 	TAILQ_FOREACH_SAFE(s, &states->states, entry, tmp) {
882 		free(s);
883 	}
884 
885 	bzero(states, sizeof(*states));
886 }
887 
888 static int
889 _pfctl_clear_states(int dev, const struct pfctl_kill *kill,
890     unsigned int *killed, uint64_t ioctlval)
891 {
892 	struct pfioc_nv	 nv;
893 	nvlist_t	*nvl;
894 	int		 ret;
895 
896 	nvl = nvlist_create(0);
897 
898 	pfctl_nv_add_state_cmp(nvl, "cmp", &kill->cmp);
899 	nvlist_add_number(nvl, "af", kill->af);
900 	nvlist_add_number(nvl, "proto", kill->proto);
901 	pfctl_nv_add_rule_addr(nvl, "src", &kill->src);
902 	pfctl_nv_add_rule_addr(nvl, "dst", &kill->dst);
903 	pfctl_nv_add_rule_addr(nvl, "rt_addr", &kill->rt_addr);
904 	nvlist_add_string(nvl, "ifname", kill->ifname);
905 	nvlist_add_string(nvl, "label", kill->label);
906 	nvlist_add_bool(nvl, "kill_match", kill->kill_match);
907 
908 	nv.data = nvlist_pack(nvl, &nv.len);
909 	nv.size = nv.len;
910 	nvlist_destroy(nvl);
911 	nvl = NULL;
912 
913 	ret = ioctl(dev, ioctlval, &nv);
914 	if (ret != 0) {
915 		free(nv.data);
916 		return (ret);
917 	}
918 
919 	nvl = nvlist_unpack(nv.data, nv.len, 0);
920 	if (nvl == NULL) {
921 		free(nv.data);
922 		return (EIO);
923 	}
924 
925 	if (killed)
926 		*killed = nvlist_get_number(nvl, "killed");
927 
928 	nvlist_destroy(nvl);
929 	free(nv.data);
930 
931 	return (ret);
932 }
933 
934 int
935 pfctl_clear_states(int dev, const struct pfctl_kill *kill,
936     unsigned int *killed)
937 {
938 	return (_pfctl_clear_states(dev, kill, killed, DIOCCLRSTATESNV));
939 }
940 
941 int
942 pfctl_kill_states(int dev, const struct pfctl_kill *kill, unsigned int *killed)
943 {
944 	return (_pfctl_clear_states(dev, kill, killed, DIOCKILLSTATESNV));
945 }
946 
947 static int
948 pfctl_get_limit(int dev, const int index, u_int *limit)
949 {
950 	struct pfioc_limit pl;
951 
952 	bzero(&pl, sizeof(pl));
953 	pl.index = index;
954 
955 	if (ioctl(dev, DIOCGETLIMIT, &pl) == -1)
956 		return (errno);
957 
958 	*limit = pl.limit;
959 
960 	return (0);
961 }
962 
963 int
964 pfctl_set_syncookies(int dev, const struct pfctl_syncookies *s)
965 {
966 	struct pfioc_nv	 nv;
967 	nvlist_t	*nvl;
968 	int		 ret;
969 	u_int		 state_limit;
970 
971 	ret = pfctl_get_limit(dev, PF_LIMIT_STATES, &state_limit);
972 	if (ret != 0)
973 		return (ret);
974 
975 	nvl = nvlist_create(0);
976 
977 	nvlist_add_bool(nvl, "enabled", s->mode != PFCTL_SYNCOOKIES_NEVER);
978 	nvlist_add_bool(nvl, "adaptive", s->mode == PFCTL_SYNCOOKIES_ADAPTIVE);
979 	nvlist_add_number(nvl, "highwater", state_limit * s->highwater / 100);
980 	nvlist_add_number(nvl, "lowwater", state_limit * s->lowwater / 100);
981 
982 	nv.data = nvlist_pack(nvl, &nv.len);
983 	nv.size = nv.len;
984 	nvlist_destroy(nvl);
985 	nvl = NULL;
986 
987 	ret = ioctl(dev, DIOCSETSYNCOOKIES, &nv);
988 
989 	free(nv.data);
990 	return (ret);
991 }
992 
993 int
994 pfctl_get_syncookies(int dev, struct pfctl_syncookies *s)
995 {
996 	struct pfioc_nv	 nv;
997 	nvlist_t	*nvl;
998 	int		 ret;
999 	u_int		 state_limit;
1000 	bool		 enabled, adaptive;
1001 
1002 	ret = pfctl_get_limit(dev, PF_LIMIT_STATES, &state_limit);
1003 	if (ret != 0)
1004 		return (ret);
1005 
1006 	bzero(s, sizeof(*s));
1007 
1008 	nv.data = malloc(256);
1009 	nv.len = nv.size = 256;
1010 
1011 	if (ioctl(dev, DIOCGETSYNCOOKIES, &nv)) {
1012 		free(nv.data);
1013 		return (errno);
1014 	}
1015 
1016 	nvl = nvlist_unpack(nv.data, nv.len, 0);
1017 	free(nv.data);
1018 	if (nvl == NULL) {
1019 		return (EIO);
1020 	}
1021 
1022 	enabled = nvlist_get_bool(nvl, "enabled");
1023 	adaptive = nvlist_get_bool(nvl, "adaptive");
1024 
1025 	if (enabled) {
1026 		if (adaptive)
1027 			s->mode = PFCTL_SYNCOOKIES_ADAPTIVE;
1028 		else
1029 			s->mode = PFCTL_SYNCOOKIES_ALWAYS;
1030 	} else {
1031 		s->mode = PFCTL_SYNCOOKIES_NEVER;
1032 	}
1033 
1034 	s->highwater = nvlist_get_number(nvl, "highwater") * 100 / state_limit;
1035 	s->lowwater = nvlist_get_number(nvl, "lowwater") * 100 / state_limit;
1036 
1037 	nvlist_destroy(nvl);
1038 
1039 	return (0);
1040 }
1041