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