libc - nmalloc: Continue in a do/while(0) loop exits the loop, making the mtmagazine...
[dragonfly.git] / sys / net / pf / pf.c
CommitLineData
05ac5751 1/* $OpenBSD: pf.c,v 1.552.2.1 2007/11/27 16:37:57 henning Exp $ */
21fe214d
JL
2/* add $OpenBSD: pf.c,v 1.553 2007/08/23 11:15:49 dhartmei Exp $ */
3/* add $OpenBSD: pf.c,v 1.554 2007/08/28 16:09:12 henning Exp $ */
4
02742ec6
JS
5
6/*
7 * Copyright (c) 2004 The DragonFly Project. All rights reserved.
8 *
9 * Copyright (c) 2001 Daniel Hartmeier
10 * Copyright (c) 2002,2003 Henning Brauer
11 * All rights reserved.
12 *
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
15 * are met:
16 *
17 * - Redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer.
19 * - Redistributions in binary form must reproduce the above
20 * copyright notice, this list of conditions and the following
21 * disclaimer in the documentation and/or other materials provided
22 * with the distribution.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35 * POSSIBILITY OF SUCH DAMAGE.
36 *
37 * Effort sponsored in part by the Defense Advanced Research Projects
38 * Agency (DARPA) and Air Force Research Laboratory, Air Force
39 * Materiel Command, USAF, under agreement number F30602-01-2-0537.
40 *
41 */
42
43#include "opt_inet.h"
44#include "opt_inet6.h"
45#include "use_pfsync.h"
46
47#include <sys/param.h>
48#include <sys/systm.h>
49#include <sys/malloc.h>
50#include <sys/mbuf.h>
51#include <sys/filio.h>
52#include <sys/socket.h>
53#include <sys/socketvar.h>
54#include <sys/kernel.h>
55#include <sys/time.h>
56#include <sys/sysctl.h>
57#include <sys/endian.h>
58#include <vm/vm_zone.h>
70224baa
JL
59#include <sys/proc.h>
60#include <sys/kthread.h>
02742ec6 61
cd8ab232
MD
62#include <sys/mplock2.h>
63
02742ec6
JS
64#include <machine/inttypes.h>
65
66#include <net/if.h>
67#include <net/if_types.h>
68#include <net/bpf.h>
4599cf19 69#include <net/netisr.h>
02742ec6
JS
70#include <net/route.h>
71
72#include <netinet/in.h>
73#include <netinet/in_var.h>
74#include <netinet/in_systm.h>
75#include <netinet/ip.h>
76#include <netinet/ip_var.h>
77#include <netinet/tcp.h>
78#include <netinet/tcp_seq.h>
79#include <netinet/udp.h>
80#include <netinet/ip_icmp.h>
81#include <netinet/in_pcb.h>
82#include <netinet/tcp_timer.h>
83#include <netinet/tcp_var.h>
84#include <netinet/udp_var.h>
85#include <netinet/icmp_var.h>
70224baa 86#include <netinet/if_ether.h>
02742ec6
JS
87
88#include <net/pf/pfvar.h>
89#include <net/pf/if_pflog.h>
90
91#if NPFSYNC > 0
92#include <net/pf/if_pfsync.h>
93#endif /* NPFSYNC > 0 */
94
95#ifdef INET6
96#include <netinet/ip6.h>
97#include <netinet/in_pcb.h>
98#include <netinet/icmp6.h>
99#include <netinet6/nd6.h>
100#include <netinet6/ip6_var.h>
101#include <netinet6/in6_pcb.h>
102#endif /* INET6 */
103
104#include <sys/in_cksum.h>
4599cf19 105#include <sys/ucred.h>
02742ec6
JS
106#include <machine/limits.h>
107#include <sys/msgport2.h>
4599cf19 108#include <net/netmsg2.h>
02742ec6
JS
109
110extern int ip_optcopy(struct ip *, struct ip *);
70224baa 111extern int debug_pfugidhack;
02742ec6 112
2a7a2b1c
JL
113struct lwkt_token pf_token = LWKT_TOKEN_MP_INITIALIZER(pf_token);
114
4b1cf444 115#define DPFPRINTF(n, x) if (pf_status.debug >= (n)) kprintf x
02742ec6
JS
116
117/*
118 * Global variables
119 */
120
315a7da3
JL
121/* state tables */
122struct pf_state_tree_lan_ext pf_statetbl_lan_ext;
123struct pf_state_tree_ext_gwy pf_statetbl_ext_gwy;
124
02742ec6
JS
125struct pf_altqqueue pf_altqs[2];
126struct pf_palist pf_pabuf;
127struct pf_altqqueue *pf_altqs_active;
128struct pf_altqqueue *pf_altqs_inactive;
129struct pf_status pf_status;
130
131u_int32_t ticket_altqs_active;
132u_int32_t ticket_altqs_inactive;
133int altqs_inactive_open;
134u_int32_t ticket_pabuf;
135
70224baa
JL
136struct pf_anchor_stackframe {
137 struct pf_ruleset *rs;
138 struct pf_rule *r;
139 struct pf_anchor_node *parent;
140 struct pf_anchor *child;
141} pf_anchor_stack[64];
02742ec6 142
315a7da3
JL
143vm_zone_t pf_src_tree_pl, pf_rule_pl, pf_pooladdr_pl;
144vm_zone_t pf_state_pl, pf_state_key_pl;
145vm_zone_t pf_altq_pl;
02742ec6
JS
146
147void pf_print_host(struct pf_addr *, u_int16_t, u_int8_t);
02742ec6 148
70224baa
JL
149void pf_init_threshold(struct pf_threshold *, u_int32_t,
150 u_int32_t);
151void pf_add_threshold(struct pf_threshold *);
152int pf_check_threshold(struct pf_threshold *);
153
02742ec6
JS
154void pf_change_ap(struct pf_addr *, u_int16_t *,
155 u_int16_t *, u_int16_t *, struct pf_addr *,
156 u_int16_t, u_int8_t, sa_family_t);
70224baa
JL
157int pf_modulate_sack(struct mbuf *, int, struct pf_pdesc *,
158 struct tcphdr *, struct pf_state_peer *);
02742ec6
JS
159#ifdef INET6
160void pf_change_a6(struct pf_addr *, u_int16_t *,
161 struct pf_addr *, u_int8_t);
162#endif /* INET6 */
163void pf_change_icmp(struct pf_addr *, u_int16_t *,
164 struct pf_addr *, struct pf_addr *, u_int16_t,
165 u_int16_t *, u_int16_t *, u_int16_t *,
166 u_int16_t *, u_int8_t, sa_family_t);
167void pf_send_tcp(const struct pf_rule *, sa_family_t,
168 const struct pf_addr *, const struct pf_addr *,
169 u_int16_t, u_int16_t, u_int32_t, u_int32_t,
70224baa
JL
170 u_int8_t, u_int16_t, u_int16_t, u_int8_t, int,
171 u_int16_t, struct ether_header *, struct ifnet *);
02742ec6
JS
172void pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
173 sa_family_t, struct pf_rule *);
174struct pf_rule *pf_match_translation(struct pf_pdesc *, struct mbuf *,
175 int, int, struct pfi_kif *,
176 struct pf_addr *, u_int16_t, struct pf_addr *,
177 u_int16_t, int);
178struct pf_rule *pf_get_translation(struct pf_pdesc *, struct mbuf *,
179 int, int, struct pfi_kif *, struct pf_src_node **,
180 struct pf_addr *, u_int16_t,
181 struct pf_addr *, u_int16_t,
182 struct pf_addr *, u_int16_t *);
315a7da3
JL
183void pf_attach_state(struct pf_state_key *,
184 struct pf_state *, int);
185void pf_detach_state(struct pf_state *, int);
186int pf_test_rule(struct pf_rule **, struct pf_state **,
02742ec6
JS
187 int, struct pfi_kif *, struct mbuf *, int,
188 void *, struct pf_pdesc *, struct pf_rule **,
70224baa 189 struct pf_ruleset **, struct ifqueue *, struct inpcb *);
02742ec6
JS
190int pf_test_fragment(struct pf_rule **, int,
191 struct pfi_kif *, struct mbuf *, void *,
192 struct pf_pdesc *, struct pf_rule **,
193 struct pf_ruleset **);
194int pf_test_state_tcp(struct pf_state **, int,
195 struct pfi_kif *, struct mbuf *, int,
196 void *, struct pf_pdesc *, u_short *);
197int pf_test_state_udp(struct pf_state **, int,
198 struct pfi_kif *, struct mbuf *, int,
199 void *, struct pf_pdesc *);
200int pf_test_state_icmp(struct pf_state **, int,
201 struct pfi_kif *, struct mbuf *, int,
70224baa 202 void *, struct pf_pdesc *, u_short *);
02742ec6
JS
203int pf_test_state_other(struct pf_state **, int,
204 struct pfi_kif *, struct pf_pdesc *);
315a7da3
JL
205int pf_match_tag(struct mbuf *, struct pf_rule *, int *);
206void pf_step_into_anchor(int *, struct pf_ruleset **, int,
207 struct pf_rule **, struct pf_rule **, int *);
70224baa
JL
208int pf_step_out_of_anchor(int *, struct pf_ruleset **,
209 int, struct pf_rule **, struct pf_rule **,
210 int *);
02742ec6
JS
211void pf_hash(struct pf_addr *, struct pf_addr *,
212 struct pf_poolhashkey *, sa_family_t);
213int pf_map_addr(u_int8_t, struct pf_rule *,
214 struct pf_addr *, struct pf_addr *,
215 struct pf_addr *, struct pf_src_node **);
216int pf_get_sport(sa_family_t, u_int8_t, struct pf_rule *,
217 struct pf_addr *, struct pf_addr *, u_int16_t,
218 struct pf_addr *, u_int16_t*, u_int16_t, u_int16_t,
219 struct pf_src_node **);
220void pf_route(struct mbuf **, struct pf_rule *, int,
70224baa
JL
221 struct ifnet *, struct pf_state *,
222 struct pf_pdesc *);
02742ec6 223void pf_route6(struct mbuf **, struct pf_rule *, int,
70224baa
JL
224 struct ifnet *, struct pf_state *,
225 struct pf_pdesc *);
02742ec6
JS
226u_int8_t pf_get_wscale(struct mbuf *, int, u_int16_t,
227 sa_family_t);
228u_int16_t pf_get_mss(struct mbuf *, int, u_int16_t,
229 sa_family_t);
230u_int16_t pf_calc_mss(struct pf_addr *, sa_family_t,
231 u_int16_t);
232void pf_set_rt_ifp(struct pf_state *,
233 struct pf_addr *);
234int pf_check_proto_cksum(struct mbuf *, int, int,
235 u_int8_t, sa_family_t);
236int pf_addr_wrap_neq(struct pf_addr_wrap *,
237 struct pf_addr_wrap *);
315a7da3
JL
238struct pf_state *pf_find_state(struct pfi_kif *,
239 struct pf_state_key_cmp *, u_int8_t);
70224baa 240int pf_src_connlimit(struct pf_state **);
315a7da3
JL
241void pf_stateins_err(const char *, struct pf_state *,
242 struct pfi_kif *);
70224baa
JL
243int pf_check_congestion(struct ifqueue *);
244
245extern int pf_end_threads;
246
247struct pf_pool_limit pf_pool_limits[PF_LIMIT_MAX] = {
248 { &pf_state_pl, PFSTATE_HIWAT },
249 { &pf_src_tree_pl, PFSNODE_HIWAT },
250 { &pf_frent_pl, PFFRAG_FRENT_HIWAT },
251 { &pfr_ktable_pl, PFR_KTABLE_HIWAT },
252 { &pfr_kentry_pl, PFR_KENTRY_HIWAT }
253};
02742ec6
JS
254
255#define STATE_LOOKUP() \
256 do { \
257 if (direction == PF_IN) \
315a7da3 258 *state = pf_find_state(kif, &key, PF_EXT_GWY); \
02742ec6 259 else \
315a7da3 260 *state = pf_find_state(kif, &key, PF_LAN_EXT); \
70224baa 261 if (*state == NULL || (*state)->timeout == PFTM_PURGE) \
02742ec6
JS
262 return (PF_DROP); \
263 if (direction == PF_OUT && \
264 (((*state)->rule.ptr->rt == PF_ROUTETO && \
265 (*state)->rule.ptr->direction == PF_OUT) || \
266 ((*state)->rule.ptr->rt == PF_REPLYTO && \
267 (*state)->rule.ptr->direction == PF_IN)) && \
268 (*state)->rt_kif != NULL && \
269 (*state)->rt_kif != kif) \
270 return (PF_PASS); \
271 } while (0)
272
315a7da3
JL
273#define STATE_TRANSLATE(sk) \
274 (sk)->lan.addr.addr32[0] != (sk)->gwy.addr.addr32[0] || \
275 ((sk)->af == AF_INET6 && \
276 ((sk)->lan.addr.addr32[1] != (sk)->gwy.addr.addr32[1] || \
277 (sk)->lan.addr.addr32[2] != (sk)->gwy.addr.addr32[2] || \
278 (sk)->lan.addr.addr32[3] != (sk)->gwy.addr.addr32[3])) || \
279 (sk)->lan.port != (sk)->gwy.port
02742ec6 280
70224baa
JL
281#define BOUND_IFACE(r, k) \
282 ((r)->rule_flag & PFRULE_IFBOUND) ? (k) : pfi_all
283
284#define STATE_INC_COUNTERS(s) \
285 do { \
286 s->rule.ptr->states++; \
287 if (s->anchor.ptr != NULL) \
288 s->anchor.ptr->states++; \
289 if (s->nat_rule.ptr != NULL) \
290 s->nat_rule.ptr->states++; \
291 } while (0)
292
293#define STATE_DEC_COUNTERS(s) \
294 do { \
295 if (s->nat_rule.ptr != NULL) \
296 s->nat_rule.ptr->states--; \
297 if (s->anchor.ptr != NULL) \
298 s->anchor.ptr->states--; \
299 s->rule.ptr->states--; \
300 } while (0)
02742ec6 301
70224baa 302static __inline int pf_src_compare(struct pf_src_node *, struct pf_src_node *);
315a7da3
JL
303static __inline int pf_state_compare_lan_ext(struct pf_state_key *,
304 struct pf_state_key *);
305static __inline int pf_state_compare_ext_gwy(struct pf_state_key *,
306 struct pf_state_key *);
70224baa 307static __inline int pf_state_compare_id(struct pf_state *,
02742ec6
JS
308 struct pf_state *);
309
310struct pf_src_tree tree_src_tracking;
311
312struct pf_state_tree_id tree_id;
70224baa 313struct pf_state_queue state_list;
02742ec6
JS
314
315RB_GENERATE(pf_src_tree, pf_src_node, entry, pf_src_compare);
315a7da3
JL
316RB_GENERATE(pf_state_tree_lan_ext, pf_state_key,
317 entry_lan_ext, pf_state_compare_lan_ext);
318RB_GENERATE(pf_state_tree_ext_gwy, pf_state_key,
319 entry_ext_gwy, pf_state_compare_ext_gwy);
02742ec6 320RB_GENERATE(pf_state_tree_id, pf_state,
315a7da3
JL
321 entry_id, pf_state_compare_id);
322
323#define PF_DT_SKIP_LANEXT 0x01
324#define PF_DT_SKIP_EXTGWY 0x02
02742ec6 325
70224baa 326static __inline int
02742ec6
JS
327pf_src_compare(struct pf_src_node *a, struct pf_src_node *b)
328{
329 int diff;
330
331 if (a->rule.ptr > b->rule.ptr)
332 return (1);
333 if (a->rule.ptr < b->rule.ptr)
334 return (-1);
335 if ((diff = a->af - b->af) != 0)
336 return (diff);
337 switch (a->af) {
338#ifdef INET
339 case AF_INET:
340 if (a->addr.addr32[0] > b->addr.addr32[0])
341 return (1);
342 if (a->addr.addr32[0] < b->addr.addr32[0])
343 return (-1);
344 break;
345#endif /* INET */
346#ifdef INET6
347 case AF_INET6:
348 if (a->addr.addr32[3] > b->addr.addr32[3])
349 return (1);
350 if (a->addr.addr32[3] < b->addr.addr32[3])
351 return (-1);
352 if (a->addr.addr32[2] > b->addr.addr32[2])
353 return (1);
354 if (a->addr.addr32[2] < b->addr.addr32[2])
355 return (-1);
356 if (a->addr.addr32[1] > b->addr.addr32[1])
357 return (1);
358 if (a->addr.addr32[1] < b->addr.addr32[1])
359 return (-1);
360 if (a->addr.addr32[0] > b->addr.addr32[0])
361 return (1);
362 if (a->addr.addr32[0] < b->addr.addr32[0])
363 return (-1);
364 break;
365#endif /* INET6 */
366 }
367 return (0);
368}
369
a814431a 370u_int32_t
315a7da3 371pf_state_hash(struct pf_state_key *sk)
5950bf01 372{
315a7da3 373 u_int32_t hv = (intptr_t)sk / sizeof(*sk);
5950bf01 374
315a7da3
JL
375 hv ^= crc32(&sk->lan, sizeof(sk->lan));
376 hv ^= crc32(&sk->gwy, sizeof(sk->gwy));
377 hv ^= crc32(&sk->ext, sizeof(sk->ext));
a814431a
MD
378 if (hv == 0) /* disallow 0 */
379 hv = 1;
5950bf01
MD
380 return(hv);
381}
382
70224baa 383static __inline int
315a7da3 384pf_state_compare_lan_ext(struct pf_state_key *a, struct pf_state_key *b)
02742ec6
JS
385{
386 int diff;
387
388 if ((diff = a->proto - b->proto) != 0)
389 return (diff);
390 if ((diff = a->af - b->af) != 0)
391 return (diff);
392 switch (a->af) {
393#ifdef INET
394 case AF_INET:
395 if (a->lan.addr.addr32[0] > b->lan.addr.addr32[0])
396 return (1);
397 if (a->lan.addr.addr32[0] < b->lan.addr.addr32[0])
398 return (-1);
399 if (a->ext.addr.addr32[0] > b->ext.addr.addr32[0])
400 return (1);
401 if (a->ext.addr.addr32[0] < b->ext.addr.addr32[0])
402 return (-1);
403 break;
404#endif /* INET */
405#ifdef INET6
406 case AF_INET6:
407 if (a->lan.addr.addr32[3] > b->lan.addr.addr32[3])
408 return (1);
409 if (a->lan.addr.addr32[3] < b->lan.addr.addr32[3])
410 return (-1);
411 if (a->ext.addr.addr32[3] > b->ext.addr.addr32[3])
412 return (1);
413 if (a->ext.addr.addr32[3] < b->ext.addr.addr32[3])
414 return (-1);
415 if (a->lan.addr.addr32[2] > b->lan.addr.addr32[2])
416 return (1);
417 if (a->lan.addr.addr32[2] < b->lan.addr.addr32[2])
418 return (-1);
419 if (a->ext.addr.addr32[2] > b->ext.addr.addr32[2])
420 return (1);
421 if (a->ext.addr.addr32[2] < b->ext.addr.addr32[2])
422 return (-1);
423 if (a->lan.addr.addr32[1] > b->lan.addr.addr32[1])
424 return (1);
425 if (a->lan.addr.addr32[1] < b->lan.addr.addr32[1])
426 return (-1);
427 if (a->ext.addr.addr32[1] > b->ext.addr.addr32[1])
428 return (1);
429 if (a->ext.addr.addr32[1] < b->ext.addr.addr32[1])
430 return (-1);
431 if (a->lan.addr.addr32[0] > b->lan.addr.addr32[0])
432 return (1);
433 if (a->lan.addr.addr32[0] < b->lan.addr.addr32[0])
434 return (-1);
435 if (a->ext.addr.addr32[0] > b->ext.addr.addr32[0])
436 return (1);
437 if (a->ext.addr.addr32[0] < b->ext.addr.addr32[0])
438 return (-1);
439 break;
440#endif /* INET6 */
441 }
442
443 if ((diff = a->lan.port - b->lan.port) != 0)
444 return (diff);
445 if ((diff = a->ext.port - b->ext.port) != 0)
446 return (diff);
447
448 return (0);
449}
450
70224baa 451static __inline int
315a7da3 452pf_state_compare_ext_gwy(struct pf_state_key *a, struct pf_state_key *b)
02742ec6
JS
453{
454 int diff;
455
456 if ((diff = a->proto - b->proto) != 0)
457 return (diff);
458 if ((diff = a->af - b->af) != 0)
459 return (diff);
460 switch (a->af) {
461#ifdef INET
462 case AF_INET:
463 if (a->ext.addr.addr32[0] > b->ext.addr.addr32[0])
464 return (1);
465 if (a->ext.addr.addr32[0] < b->ext.addr.addr32[0])
466 return (-1);
467 if (a->gwy.addr.addr32[0] > b->gwy.addr.addr32[0])
468 return (1);
469 if (a->gwy.addr.addr32[0] < b->gwy.addr.addr32[0])
470 return (-1);
471 break;
472#endif /* INET */
473#ifdef INET6
474 case AF_INET6:
475 if (a->ext.addr.addr32[3] > b->ext.addr.addr32[3])
476 return (1);
477 if (a->ext.addr.addr32[3] < b->ext.addr.addr32[3])
478 return (-1);
479 if (a->gwy.addr.addr32[3] > b->gwy.addr.addr32[3])
480 return (1);
481 if (a->gwy.addr.addr32[3] < b->gwy.addr.addr32[3])
482 return (-1);
483 if (a->ext.addr.addr32[2] > b->ext.addr.addr32[2])
484 return (1);
485 if (a->ext.addr.addr32[2] < b->ext.addr.addr32[2])
486 return (-1);
487 if (a->gwy.addr.addr32[2] > b->gwy.addr.addr32[2])
488 return (1);
489 if (a->gwy.addr.addr32[2] < b->gwy.addr.addr32[2])
490 return (-1);
491 if (a->ext.addr.addr32[1] > b->ext.addr.addr32[1])
492 return (1);
493 if (a->ext.addr.addr32[1] < b->ext.addr.addr32[1])
494 return (-1);
495 if (a->gwy.addr.addr32[1] > b->gwy.addr.addr32[1])
496 return (1);
497 if (a->gwy.addr.addr32[1] < b->gwy.addr.addr32[1])
498 return (-1);
499 if (a->ext.addr.addr32[0] > b->ext.addr.addr32[0])
500 return (1);
501 if (a->ext.addr.addr32[0] < b->ext.addr.addr32[0])
502 return (-1);
503 if (a->gwy.addr.addr32[0] > b->gwy.addr.addr32[0])
504 return (1);
505 if (a->gwy.addr.addr32[0] < b->gwy.addr.addr32[0])
506 return (-1);
507 break;
508#endif /* INET6 */
509 }
510
511 if ((diff = a->ext.port - b->ext.port) != 0)
512 return (diff);
513 if ((diff = a->gwy.port - b->gwy.port) != 0)
514 return (diff);
515
516 return (0);
517}
518
70224baa 519static __inline int
02742ec6
JS
520pf_state_compare_id(struct pf_state *a, struct pf_state *b)
521{
522 if (a->id > b->id)
523 return (1);
524 if (a->id < b->id)
525 return (-1);
526 if (a->creatorid > b->creatorid)
527 return (1);
528 if (a->creatorid < b->creatorid)
529 return (-1);
530
531 return (0);
532}
533
534#ifdef INET6
535void
536pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
537{
538 switch (af) {
539#ifdef INET
540 case AF_INET:
541 dst->addr32[0] = src->addr32[0];
542 break;
543#endif /* INET */
544 case AF_INET6:
545 dst->addr32[0] = src->addr32[0];
546 dst->addr32[1] = src->addr32[1];
547 dst->addr32[2] = src->addr32[2];
548 dst->addr32[3] = src->addr32[3];
549 break;
550 }
551}
70224baa 552#endif /* INET6 */
02742ec6
JS
553
554struct pf_state *
70224baa 555pf_find_state_byid(struct pf_state_cmp *key)
02742ec6
JS
556{
557 pf_status.fcounters[FCNT_STATE_SEARCH]++;
315a7da3 558
70224baa 559 return (RB_FIND(pf_state_tree_id, &tree_id, (struct pf_state *)key));
02742ec6
JS
560}
561
562struct pf_state *
315a7da3 563pf_find_state(struct pfi_kif *kif, struct pf_state_key_cmp *key, u_int8_t tree)
02742ec6 564{
315a7da3
JL
565 struct pf_state_key *sk;
566 struct pf_state *s;
02742ec6
JS
567
568 pf_status.fcounters[FCNT_STATE_SEARCH]++;
569
570 switch (tree) {
571 case PF_LAN_EXT:
315a7da3
JL
572 sk = RB_FIND(pf_state_tree_lan_ext, &pf_statetbl_lan_ext,
573 (struct pf_state_key *)key);
574 break;
02742ec6 575 case PF_EXT_GWY:
315a7da3
JL
576 sk = RB_FIND(pf_state_tree_ext_gwy, &pf_statetbl_ext_gwy,
577 (struct pf_state_key *)key);
578 break;
02742ec6 579 default:
315a7da3 580 panic("pf_find_state");
02742ec6 581 }
315a7da3
JL
582
583 /* list is sorted, if-bound states before floating ones */
584 if (sk != NULL)
585 TAILQ_FOREACH(s, &sk->states, next)
586 if (s->kif == pfi_all || s->kif == kif)
587 return (s);
588
589 return (NULL);
02742ec6
JS
590}
591
592struct pf_state *
315a7da3 593pf_find_state_all(struct pf_state_key_cmp *key, u_int8_t tree, int *more)
02742ec6 594{
315a7da3
JL
595 struct pf_state_key *sk;
596 struct pf_state *s, *ret = NULL;
02742ec6
JS
597
598 pf_status.fcounters[FCNT_STATE_SEARCH]++;
599
600 switch (tree) {
601 case PF_LAN_EXT:
315a7da3
JL
602 sk = RB_FIND(pf_state_tree_lan_ext,
603 &pf_statetbl_lan_ext, (struct pf_state_key *)key);
604 break;
02742ec6 605 case PF_EXT_GWY:
315a7da3
JL
606 sk = RB_FIND(pf_state_tree_ext_gwy,
607 &pf_statetbl_ext_gwy, (struct pf_state_key *)key);
608 break;
02742ec6
JS
609 default:
610 panic("pf_find_state_all");
611 }
315a7da3
JL
612
613 if (sk != NULL) {
614 ret = TAILQ_FIRST(&sk->states);
615 if (more == NULL)
616 return (ret);
617
618 TAILQ_FOREACH(s, &sk->states, next)
619 (*more)++;
620 }
621
622 return (ret);
02742ec6
JS
623}
624
70224baa
JL
625void
626pf_init_threshold(struct pf_threshold *threshold,
627 u_int32_t limit, u_int32_t seconds)
628{
629 threshold->limit = limit * PF_THRESHOLD_MULT;
630 threshold->seconds = seconds;
631 threshold->count = 0;
632 threshold->last = time_second;
633}
634
635void
636pf_add_threshold(struct pf_threshold *threshold)
637{
638 u_int32_t t = time_second, diff = t - threshold->last;
639
640 if (diff >= threshold->seconds)
641 threshold->count = 0;
642 else
643 threshold->count -= threshold->count * diff /
644 threshold->seconds;
645 threshold->count += PF_THRESHOLD_MULT;
646 threshold->last = t;
647}
648
649int
650pf_check_threshold(struct pf_threshold *threshold)
651{
652 return (threshold->count > threshold->limit);
653}
654
655int
656pf_src_connlimit(struct pf_state **state)
657{
70224baa
JL
658 int bad = 0;
659
660 (*state)->src_node->conn++;
661 (*state)->src.tcp_est = 1;
662 pf_add_threshold(&(*state)->src_node->conn_rate);
663
664 if ((*state)->rule.ptr->max_src_conn &&
665 (*state)->rule.ptr->max_src_conn <
666 (*state)->src_node->conn) {
667 pf_status.lcounters[LCNT_SRCCONN]++;
668 bad++;
669 }
670
671 if ((*state)->rule.ptr->max_src_conn_rate.limit &&
672 pf_check_threshold(&(*state)->src_node->conn_rate)) {
673 pf_status.lcounters[LCNT_SRCCONNRATE]++;
674 bad++;
675 }
676
677 if (!bad)
678 return (0);
679
680 if ((*state)->rule.ptr->overload_tbl) {
681 struct pfr_addr p;
682 u_int32_t killed = 0;
683
684 pf_status.lcounters[LCNT_OVERLOAD_TABLE]++;
685 if (pf_status.debug >= PF_DEBUG_MISC) {
686 kprintf("pf_src_connlimit: blocking address ");
687 pf_print_host(&(*state)->src_node->addr, 0,
315a7da3 688 (*state)->state_key->af);
70224baa
JL
689 }
690
691 bzero(&p, sizeof(p));
315a7da3
JL
692 p.pfra_af = (*state)->state_key->af;
693 switch ((*state)->state_key->af) {
70224baa
JL
694#ifdef INET
695 case AF_INET:
696 p.pfra_net = 32;
697 p.pfra_ip4addr = (*state)->src_node->addr.v4;
698 break;
699#endif /* INET */
700#ifdef INET6
701 case AF_INET6:
702 p.pfra_net = 128;
703 p.pfra_ip6addr = (*state)->src_node->addr.v6;
704 break;
705#endif /* INET6 */
706 }
707
708 pfr_insert_kentry((*state)->rule.ptr->overload_tbl,
709 &p, time_second);
710
711 /* kill existing states if that's required. */
712 if ((*state)->rule.ptr->flush) {
315a7da3
JL
713 struct pf_state_key *sk;
714 struct pf_state *st;
70224baa 715
315a7da3
JL
716 pf_status.lcounters[LCNT_OVERLOAD_FLUSH]++;
717 RB_FOREACH(st, pf_state_tree_id, &tree_id) {
718 sk = st->state_key;
70224baa
JL
719 /*
720 * Kill states from this source. (Only those
721 * from the same rule if PF_FLUSH_GLOBAL is not
722 * set)
723 */
315a7da3
JL
724 if (sk->af ==
725 (*state)->state_key->af &&
726 (((*state)->state_key->direction ==
727 PF_OUT &&
70224baa 728 PF_AEQ(&(*state)->src_node->addr,
315a7da3
JL
729 &sk->lan.addr, sk->af)) ||
730 ((*state)->state_key->direction == PF_IN &&
70224baa 731 PF_AEQ(&(*state)->src_node->addr,
315a7da3 732 &sk->ext.addr, sk->af))) &&
70224baa
JL
733 ((*state)->rule.ptr->flush &
734 PF_FLUSH_GLOBAL ||
315a7da3
JL
735 (*state)->rule.ptr == st->rule.ptr)) {
736 st->timeout = PFTM_PURGE;
737 st->src.state = st->dst.state =
70224baa
JL
738 TCPS_CLOSED;
739 killed++;
740 }
741 }
742 if (pf_status.debug >= PF_DEBUG_MISC)
743 kprintf(", %u states killed", killed);
744 }
745 if (pf_status.debug >= PF_DEBUG_MISC)
746 kprintf("\n");
747 }
748
749 /* kill this state */
750 (*state)->timeout = PFTM_PURGE;
751 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
752 return (1);
753}
754
02742ec6
JS
755int
756pf_insert_src_node(struct pf_src_node **sn, struct pf_rule *rule,
757 struct pf_addr *src, sa_family_t af)
758{
759 struct pf_src_node k;
760
761 if (*sn == NULL) {
762 k.af = af;
763 PF_ACPY(&k.addr, src, af);
764 if (rule->rule_flag & PFRULE_RULESRCTRACK ||
765 rule->rpool.opts & PF_POOL_STICKYADDR)
766 k.rule.ptr = rule;
767 else
768 k.rule.ptr = NULL;
769 pf_status.scounters[SCNT_SRC_NODE_SEARCH]++;
770 *sn = RB_FIND(pf_src_tree, &tree_src_tracking, &k);
771 }
772 if (*sn == NULL) {
773 if (!rule->max_src_nodes ||
774 rule->src_nodes < rule->max_src_nodes)
775 (*sn) = pool_get(&pf_src_tree_pl, PR_NOWAIT);
70224baa
JL
776 else
777 pf_status.lcounters[LCNT_SRCNODES]++;
02742ec6
JS
778 if ((*sn) == NULL)
779 return (-1);
780 bzero(*sn, sizeof(struct pf_src_node));
70224baa
JL
781
782 pf_init_threshold(&(*sn)->conn_rate,
783 rule->max_src_conn_rate.limit,
784 rule->max_src_conn_rate.seconds);
785
02742ec6
JS
786 (*sn)->af = af;
787 if (rule->rule_flag & PFRULE_RULESRCTRACK ||
788 rule->rpool.opts & PF_POOL_STICKYADDR)
789 (*sn)->rule.ptr = rule;
790 else
791 (*sn)->rule.ptr = NULL;
792 PF_ACPY(&(*sn)->addr, src, af);
793 if (RB_INSERT(pf_src_tree,
794 &tree_src_tracking, *sn) != NULL) {
795 if (pf_status.debug >= PF_DEBUG_MISC) {
4b1cf444 796 kprintf("pf: src_tree insert failed: ");
02742ec6 797 pf_print_host(&(*sn)->addr, 0, af);
4b1cf444 798 kprintf("\n");
02742ec6
JS
799 }
800 pool_put(&pf_src_tree_pl, *sn);
801 return (-1);
802 }
803 (*sn)->creation = time_second;
804 (*sn)->ruletype = rule->action;
805 if ((*sn)->rule.ptr != NULL)
806 (*sn)->rule.ptr->src_nodes++;
807 pf_status.scounters[SCNT_SRC_NODE_INSERT]++;
808 pf_status.src_nodes++;
809 } else {
810 if (rule->max_src_states &&
70224baa
JL
811 (*sn)->states >= rule->max_src_states) {
812 pf_status.lcounters[LCNT_SRCSTATES]++;
02742ec6 813 return (-1);
70224baa 814 }
02742ec6
JS
815 }
816 return (0);
817}
818
315a7da3
JL
819void
820pf_stateins_err(const char *tree, struct pf_state *s, struct pfi_kif *kif)
821{
822 struct pf_state_key *sk = s->state_key;
823
824 if (pf_status.debug >= PF_DEBUG_MISC) {
825 kprintf("pf: state insert failed: %s %s", tree, kif->pfik_name);
826 kprintf(" lan: ");
827 pf_print_host(&sk->lan.addr, sk->lan.port,
828 sk->af);
829 kprintf(" gwy: ");
830 pf_print_host(&sk->gwy.addr, sk->gwy.port,
831 sk->af);
832 kprintf(" ext: ");
833 pf_print_host(&sk->ext.addr, sk->ext.port,
834 sk->af);
835 if (s->sync_flags & PFSTATE_FROMSYNC)
836 kprintf(" (from sync)");
837 kprintf("\n");
838 }
839}
840
02742ec6 841int
315a7da3 842pf_insert_state(struct pfi_kif *kif, struct pf_state *s)
02742ec6 843{
315a7da3
JL
844 struct pf_state_key *cur;
845 struct pf_state *sp;
846
847 KKASSERT(s->state_key != NULL);
848 s->kif = kif;
849
850 if ((cur = RB_INSERT(pf_state_tree_lan_ext, &pf_statetbl_lan_ext,
851 s->state_key)) != NULL) {
852 /* key exists. check for same kif, if none, add to key */
853 TAILQ_FOREACH(sp, &cur->states, next)
854 if (sp->kif == kif) { /* collision! */
855 pf_stateins_err("tree_lan_ext", s, kif);
05ac5751
JL
856 pf_detach_state(s,
857 PF_DT_SKIP_LANEXT|PF_DT_SKIP_EXTGWY);
315a7da3
JL
858 return (-1);
859 }
860 pf_detach_state(s, PF_DT_SKIP_LANEXT|PF_DT_SKIP_EXTGWY);
861 pf_attach_state(cur, s, kif == pfi_all ? 1 : 0);
02742ec6
JS
862 }
863
315a7da3
JL
864 /* if cur != NULL, we already found a state key and attached to it */
865 if (cur == NULL && (cur = RB_INSERT(pf_state_tree_ext_gwy,
866 &pf_statetbl_ext_gwy, s->state_key)) != NULL) {
867 /* must not happen. we must have found the sk above! */
868 pf_stateins_err("tree_ext_gwy", s, kif);
869 pf_detach_state(s, PF_DT_SKIP_EXTGWY);
02742ec6
JS
870 return (-1);
871 }
872
315a7da3
JL
873 if (s->id == 0 && s->creatorid == 0) {
874 s->id = htobe64(pf_status.stateid++);
875 s->creatorid = pf_status.hostid;
02742ec6 876 }
315a7da3 877 if (RB_INSERT(pf_state_tree_id, &tree_id, s) != NULL) {
02742ec6 878 if (pf_status.debug >= PF_DEBUG_MISC) {
4b1cf444 879 kprintf("pf: state insert failed: "
2e5b1311
SW
880 "id: %016jx creatorid: %08x",
881 (uintmax_t)be64toh(s->id), ntohl(s->creatorid));
315a7da3 882 if (s->sync_flags & PFSTATE_FROMSYNC)
4b1cf444
SW
883 kprintf(" (from sync)");
884 kprintf("\n");
02742ec6 885 }
315a7da3 886 pf_detach_state(s, 0);
02742ec6
JS
887 return (-1);
888 }
315a7da3 889 TAILQ_INSERT_TAIL(&state_list, s, entry_list);
02742ec6
JS
890 pf_status.fcounters[FCNT_STATE_INSERT]++;
891 pf_status.states++;
70224baa 892 pfi_kif_ref(kif, PFI_KIF_REF_STATE);
02742ec6 893#if NPFSYNC
315a7da3 894 pfsync_insert_state(s);
02742ec6
JS
895#endif
896 return (0);
897}
898
899void
70224baa 900pf_purge_thread(void *v)
02742ec6 901{
70224baa
JL
902 int nloops = 0;
903 int locked = 0;
904
cd8ab232 905 get_mplock();
70224baa
JL
906 for (;;) {
907 tsleep(pf_purge_thread, PWAIT, "pftm", 1 * hz);
908
909 lockmgr(&pf_consistency_lock, LK_EXCLUSIVE);
910
911 if (pf_end_threads) {
912 pf_purge_expired_states(pf_status.states, 1);
913 pf_purge_expired_fragments();
914 pf_purge_expired_src_nodes(1);
915 pf_end_threads++;
916
917 lockmgr(&pf_consistency_lock, LK_RELEASE);
918 wakeup(pf_purge_thread);
919 kthread_exit();
920 }
921 crit_enter();
922
923 /* process a fraction of the state table every second */
924 if(!pf_purge_expired_states(1 + (pf_status.states
925 / pf_default_rule.timeout[PFTM_INTERVAL]), 0)) {
02742ec6 926
70224baa
JL
927 pf_purge_expired_states(1 + (pf_status.states
928 / pf_default_rule.timeout[PFTM_INTERVAL]), 1);
929 }
02742ec6 930
70224baa
JL
931 /* purge other expired types every PFTM_INTERVAL seconds */
932 if (++nloops >= pf_default_rule.timeout[PFTM_INTERVAL]) {
933 pf_purge_expired_fragments();
934 if (!pf_purge_expired_src_nodes(locked)) {
935 pf_purge_expired_src_nodes(1);
936 }
937 nloops = 0;
938 }
939 crit_exit();
940 lockmgr(&pf_consistency_lock, LK_RELEASE);
941 }
cd8ab232 942 rel_mplock();
02742ec6
JS
943}
944
945u_int32_t
946pf_state_expires(const struct pf_state *state)
947{
948 u_int32_t timeout;
949 u_int32_t start;
950 u_int32_t end;
951 u_int32_t states;
952
953 /* handle all PFTM_* > PFTM_MAX here */
954 if (state->timeout == PFTM_PURGE)
955 return (time_second);
956 if (state->timeout == PFTM_UNTIL_PACKET)
957 return (0);
70224baa
JL
958 KKASSERT(state->timeout != PFTM_UNLINKED);
959 KASSERT((state->timeout < PFTM_MAX),
960 ("pf_state_expires: timeout > PFTM_MAX"));
02742ec6
JS
961 timeout = state->rule.ptr->timeout[state->timeout];
962 if (!timeout)
963 timeout = pf_default_rule.timeout[state->timeout];
964 start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
965 if (start) {
966 end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
967 states = state->rule.ptr->states;
968 } else {
969 start = pf_default_rule.timeout[PFTM_ADAPTIVE_START];
970 end = pf_default_rule.timeout[PFTM_ADAPTIVE_END];
971 states = pf_status.states;
972 }
973 if (end && states > start && start < end) {
974 if (states < end)
975 return (state->expire + timeout * (end - states) /
976 (end - start));
977 else
978 return (time_second);
979 }
980 return (state->expire + timeout);
981}
982
70224baa
JL
983int
984pf_purge_expired_src_nodes(int waslocked)
02742ec6
JS
985{
986 struct pf_src_node *cur, *next;
70224baa 987 int locked = waslocked;
02742ec6
JS
988
989 for (cur = RB_MIN(pf_src_tree, &tree_src_tracking); cur; cur = next) {
990 next = RB_NEXT(pf_src_tree, &tree_src_tracking, cur);
991
992 if (cur->states <= 0 && cur->expire <= time_second) {
70224baa
JL
993 if (! locked) {
994 lockmgr(&pf_consistency_lock, LK_EXCLUSIVE);
995 next = RB_NEXT(pf_src_tree,
996 &tree_src_tracking, cur);
997 locked = 1;
998 }
02742ec6
JS
999 if (cur->rule.ptr != NULL) {
1000 cur->rule.ptr->src_nodes--;
1001 if (cur->rule.ptr->states <= 0 &&
1002 cur->rule.ptr->max_src_nodes <= 0)
1003 pf_rm_rule(NULL, cur->rule.ptr);
1004 }
1005 RB_REMOVE(pf_src_tree, &tree_src_tracking, cur);
1006 pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
1007 pf_status.src_nodes--;
1008 pool_put(&pf_src_tree_pl, cur);
1009 }
1010 }
70224baa
JL
1011
1012 if (locked && !waslocked)
1013 lockmgr(&pf_consistency_lock, LK_RELEASE);
1014 return(1);
02742ec6
JS
1015}
1016
1017void
1018pf_src_tree_remove_state(struct pf_state *s)
1019{
1020 u_int32_t timeout;
1021
1022 if (s->src_node != NULL) {
05ac5751
JL
1023 if (s->src.tcp_est)
1024 --s->src_node->conn;
02742ec6
JS
1025 if (--s->src_node->states <= 0) {
1026 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1027 if (!timeout)
1028 timeout =
1029 pf_default_rule.timeout[PFTM_SRC_NODE];
1030 s->src_node->expire = time_second + timeout;
1031 }
1032 }
1033 if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1034 if (--s->nat_src_node->states <= 0) {
1035 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1036 if (!timeout)
1037 timeout =
1038 pf_default_rule.timeout[PFTM_SRC_NODE];
1039 s->nat_src_node->expire = time_second + timeout;
1040 }
1041 }
1042 s->src_node = s->nat_src_node = NULL;
1043}
1044
70224baa
JL
1045/* callers should be at crit_enter() */
1046void
1047pf_unlink_state(struct pf_state *cur)
02742ec6 1048{
70224baa 1049 if (cur->src.state == PF_TCPS_PROXY_DST) {
315a7da3
JL
1050 pf_send_tcp(cur->rule.ptr, cur->state_key->af,
1051 &cur->state_key->ext.addr, &cur->state_key->lan.addr,
1052 cur->state_key->ext.port, cur->state_key->lan.port,
70224baa
JL
1053 cur->src.seqhi, cur->src.seqlo + 1,
1054 TH_RST|TH_ACK, 0, 0, 0, 1, cur->tag, NULL, NULL);
1055 }
70224baa 1056 RB_REMOVE(pf_state_tree_id, &tree_id, cur);
02742ec6 1057#if NPFSYNC
70224baa 1058 if (cur->creatorid == pf_status.hostid)
f0ea6854 1059 pfsync_delete_state(cur);
02742ec6 1060#endif
70224baa
JL
1061 cur->timeout = PFTM_UNLINKED;
1062 pf_src_tree_remove_state(cur);
315a7da3 1063 pf_detach_state(cur, 0);
02742ec6
JS
1064}
1065
70224baa
JL
1066/* callers should be at crit_enter() and hold the
1067 * write_lock on pf_consistency_lock */
f0ea6854 1068void
70224baa 1069pf_free_state(struct pf_state *cur)
f0ea6854 1070{
70224baa
JL
1071#if NPFSYNC
1072 if (pfsyncif != NULL &&
1073 (pfsyncif->sc_bulk_send_next == cur ||
1074 pfsyncif->sc_bulk_terminator == cur))
1075 return;
1076#endif
1077 KKASSERT(cur->timeout == PFTM_UNLINKED);
1078 if (--cur->rule.ptr->states <= 0 &&
1079 cur->rule.ptr->src_nodes <= 0)
1080 pf_rm_rule(NULL, cur->rule.ptr);
1081 if (cur->nat_rule.ptr != NULL)
1082 if (--cur->nat_rule.ptr->states <= 0 &&
1083 cur->nat_rule.ptr->src_nodes <= 0)
1084 pf_rm_rule(NULL, cur->nat_rule.ptr);
1085 if (cur->anchor.ptr != NULL)
1086 if (--cur->anchor.ptr->states <= 0)
1087 pf_rm_rule(NULL, cur->anchor.ptr);
1088 pf_normalize_tcp_cleanup(cur);
315a7da3
JL
1089 pfi_kif_unref(cur->kif, PFI_KIF_REF_STATE);
1090 TAILQ_REMOVE(&state_list, cur, entry_list);
70224baa
JL
1091 if (cur->tag)
1092 pf_tag_unref(cur->tag);
1093 pool_put(&pf_state_pl, cur);
1094 pf_status.fcounters[FCNT_STATE_REMOVALS]++;
1095 pf_status.states--;
f0ea6854
MD
1096}
1097
70224baa
JL
1098int
1099pf_purge_expired_states(u_int32_t maxcheck, int waslocked)
1100{
1101 static struct pf_state *cur = NULL;
1102 struct pf_state *next;
1103 int locked = waslocked;
1104
1105 while (maxcheck--) {
1106 /* wrap to start of list when we hit the end */
1107 if (cur == NULL) {
1108 cur = TAILQ_FIRST(&state_list);
1109 if (cur == NULL)
1110 break; /* list empty */
1111 }
1112
1113 /* get next state, as cur may get deleted */
315a7da3 1114 next = TAILQ_NEXT(cur, entry_list);
70224baa
JL
1115
1116 if (cur->timeout == PFTM_UNLINKED) {
1117 /* free unlinked state */
1118 if (! locked) {
1119 lockmgr(&pf_consistency_lock, LK_EXCLUSIVE);
1120 locked = 1;
1121 }
1122 pf_free_state(cur);
1123 } else if (pf_state_expires(cur) <= time_second) {
1124 /* unlink and free expired state */
1125 pf_unlink_state(cur);
1126 if (! locked) {
1127 if (!lockmgr(&pf_consistency_lock, LK_EXCLUSIVE))
1128 return (0);
1129 locked = 1;
1130 }
1131 pf_free_state(cur);
1132 }
1133 cur = next;
1134 }
1135
1136 if (locked)
1137 lockmgr(&pf_consistency_lock, LK_RELEASE);
1138 return (1);
1139}
f0ea6854 1140
02742ec6
JS
1141int
1142pf_tbladdr_setup(struct pf_ruleset *rs, struct pf_addr_wrap *aw)
1143{
1144 if (aw->type != PF_ADDR_TABLE)
1145 return (0);
1146 if ((aw->p.tbl = pfr_attach_table(rs, aw->v.tblname)) == NULL)
1147 return (1);
1148 return (0);
1149}
1150
1151void
1152pf_tbladdr_remove(struct pf_addr_wrap *aw)
1153{
1154 if (aw->type != PF_ADDR_TABLE || aw->p.tbl == NULL)
1155 return;
1156 pfr_detach_table(aw->p.tbl);
1157 aw->p.tbl = NULL;
1158}
1159
1160void
1161pf_tbladdr_copyout(struct pf_addr_wrap *aw)
1162{
1163 struct pfr_ktable *kt = aw->p.tbl;
1164
1165 if (aw->type != PF_ADDR_TABLE || kt == NULL)
1166 return;
1167 if (!(kt->pfrkt_flags & PFR_TFLAG_ACTIVE) && kt->pfrkt_root != NULL)
1168 kt = kt->pfrkt_root;
1169 aw->p.tbl = NULL;
1170 aw->p.tblcnt = (kt->pfrkt_flags & PFR_TFLAG_ACTIVE) ?
1171 kt->pfrkt_cnt : -1;
1172}
1173
1174void
1175pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1176{
1177 switch (af) {
1178#ifdef INET
1179 case AF_INET: {
1180 u_int32_t a = ntohl(addr->addr32[0]);
4b1cf444 1181 kprintf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
02742ec6
JS
1182 (a>>8)&255, a&255);
1183 if (p) {
1184 p = ntohs(p);
4b1cf444 1185 kprintf(":%u", p);
02742ec6
JS
1186 }
1187 break;
1188 }
1189#endif /* INET */
1190#ifdef INET6
1191 case AF_INET6: {
1192 u_int16_t b;
1193 u_int8_t i, curstart = 255, curend = 0,
1194 maxstart = 0, maxend = 0;
1195 for (i = 0; i < 8; i++) {
1196 if (!addr->addr16[i]) {
1197 if (curstart == 255)
1198 curstart = i;
1199 else
1200 curend = i;
1201 } else {
1202 if (curstart) {
1203 if ((curend - curstart) >
1204 (maxend - maxstart)) {
1205 maxstart = curstart;
1206 maxend = curend;
1207 curstart = 255;
1208 }
1209 }
1210 }
1211 }
1212 for (i = 0; i < 8; i++) {
1213 if (i >= maxstart && i <= maxend) {
1214 if (maxend != 7) {
1215 if (i == maxstart)
4b1cf444 1216 kprintf(":");
02742ec6
JS
1217 } else {
1218 if (i == maxend)
4b1cf444 1219 kprintf(":");
02742ec6
JS
1220 }
1221 } else {
1222 b = ntohs(addr->addr16[i]);
4b1cf444 1223 kprintf("%x", b);
02742ec6 1224 if (i < 7)
4b1cf444 1225 kprintf(":");
02742ec6
JS
1226 }
1227 }
1228 if (p) {
1229 p = ntohs(p);
4b1cf444 1230 kprintf("[%u]", p);
02742ec6
JS
1231 }
1232 break;
1233 }
1234#endif /* INET6 */
1235 }
1236}
1237
1238void
1239pf_print_state(struct pf_state *s)
1240{
315a7da3
JL
1241 struct pf_state_key *sk = s->state_key;
1242 switch (sk->proto) {
02742ec6 1243 case IPPROTO_TCP:
4b1cf444 1244 kprintf("TCP ");
02742ec6
JS
1245 break;
1246 case IPPROTO_UDP:
4b1cf444 1247 kprintf("UDP ");
02742ec6
JS
1248 break;
1249 case IPPROTO_ICMP:
4b1cf444 1250 kprintf("ICMP ");
02742ec6
JS
1251 break;
1252 case IPPROTO_ICMPV6:
4b1cf444 1253 kprintf("ICMPV6 ");
02742ec6
JS
1254 break;
1255 default:
315a7da3 1256 kprintf("%u ", sk->proto);
02742ec6
JS
1257 break;
1258 }
315a7da3 1259 pf_print_host(&sk->lan.addr, sk->lan.port, sk->af);
4b1cf444 1260 kprintf(" ");
315a7da3 1261 pf_print_host(&sk->gwy.addr, sk->gwy.port, sk->af);
4b1cf444 1262 kprintf(" ");
315a7da3 1263 pf_print_host(&sk->ext.addr, sk->ext.port, sk->af);
4b1cf444 1264 kprintf(" [lo=%u high=%u win=%u modulator=%u", s->src.seqlo,
02742ec6
JS
1265 s->src.seqhi, s->src.max_win, s->src.seqdiff);
1266 if (s->src.wscale && s->dst.wscale)
4b1cf444
SW
1267 kprintf(" wscale=%u", s->src.wscale & PF_WSCALE_MASK);
1268 kprintf("]");
1269 kprintf(" [lo=%u high=%u win=%u modulator=%u", s->dst.seqlo,
02742ec6
JS
1270 s->dst.seqhi, s->dst.max_win, s->dst.seqdiff);
1271 if (s->src.wscale && s->dst.wscale)
4b1cf444
SW
1272 kprintf(" wscale=%u", s->dst.wscale & PF_WSCALE_MASK);
1273 kprintf("]");
1274 kprintf(" %u:%u", s->src.state, s->dst.state);
02742ec6
JS
1275}
1276
1277void
1278pf_print_flags(u_int8_t f)
1279{
1280 if (f)
4b1cf444 1281 kprintf(" ");
02742ec6 1282 if (f & TH_FIN)
4b1cf444 1283 kprintf("F");
02742ec6 1284 if (f & TH_SYN)
4b1cf444 1285 kprintf("S");
02742ec6 1286 if (f & TH_RST)
4b1cf444 1287 kprintf("R");
02742ec6 1288 if (f & TH_PUSH)
4b1cf444 1289 kprintf("P");
02742ec6 1290 if (f & TH_ACK)
4b1cf444 1291 kprintf("A");
02742ec6 1292 if (f & TH_URG)
4b1cf444 1293 kprintf("U");
02742ec6 1294 if (f & TH_ECE)
4b1cf444 1295 kprintf("E");
02742ec6 1296 if (f & TH_CWR)
4b1cf444 1297 kprintf("W");
02742ec6
JS
1298}
1299
1300#define PF_SET_SKIP_STEPS(i) \
1301 do { \
1302 while (head[i] != cur) { \
1303 head[i]->skip[i].ptr = cur; \
1304 head[i] = TAILQ_NEXT(head[i], entries); \
1305 } \
1306 } while (0)
1307
1308void
1309pf_calc_skip_steps(struct pf_rulequeue *rules)
1310{
1311 struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
1312 int i;
1313
1314 cur = TAILQ_FIRST(rules);
1315 prev = cur;
1316 for (i = 0; i < PF_SKIP_COUNT; ++i)
1317 head[i] = cur;
1318 while (cur != NULL) {
1319
1320 if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
1321 PF_SET_SKIP_STEPS(PF_SKIP_IFP);
1322 if (cur->direction != prev->direction)
1323 PF_SET_SKIP_STEPS(PF_SKIP_DIR);
1324 if (cur->af != prev->af)
1325 PF_SET_SKIP_STEPS(PF_SKIP_AF);
1326 if (cur->proto != prev->proto)
1327 PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
70224baa 1328 if (cur->src.neg != prev->src.neg ||
02742ec6
JS
1329 pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
1330 PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
1331 if (cur->src.port[0] != prev->src.port[0] ||
1332 cur->src.port[1] != prev->src.port[1] ||
1333 cur->src.port_op != prev->src.port_op)
1334 PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
70224baa 1335 if (cur->dst.neg != prev->dst.neg ||
02742ec6
JS
1336 pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
1337 PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
1338 if (cur->dst.port[0] != prev->dst.port[0] ||
1339 cur->dst.port[1] != prev->dst.port[1] ||
1340 cur->dst.port_op != prev->dst.port_op)
1341 PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
1342
1343 prev = cur;
1344 cur = TAILQ_NEXT(cur, entries);
1345 }
1346 for (i = 0; i < PF_SKIP_COUNT; ++i)
1347 PF_SET_SKIP_STEPS(i);
1348}
1349
1350int
1351pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
1352{
1353 if (aw1->type != aw2->type)
1354 return (1);
1355 switch (aw1->type) {
1356 case PF_ADDR_ADDRMASK:
1357 if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, 0))
1358 return (1);
1359 if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, 0))
1360 return (1);
1361 return (0);
1362 case PF_ADDR_DYNIFTL:
1363 return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
1364 case PF_ADDR_NOROUTE:
70224baa 1365 case PF_ADDR_URPFFAILED:
02742ec6
JS
1366 return (0);
1367 case PF_ADDR_TABLE:
1368 return (aw1->p.tbl != aw2->p.tbl);
70224baa
JL
1369 case PF_ADDR_RTLABEL:
1370 return (aw1->v.rtlabel != aw2->v.rtlabel);
02742ec6 1371 default:
4b1cf444 1372 kprintf("invalid address type: %d\n", aw1->type);
02742ec6
JS
1373 return (1);
1374 }
1375}
1376
02742ec6
JS
1377u_int16_t
1378pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
1379{
1380 u_int32_t l;
1381
1382 if (udp && !cksum)
1383 return (0x0000);
1384 l = cksum + old - new;
1385 l = (l >> 16) + (l & 65535);
1386 l = l & 65535;
1387 if (udp && !l)
1388 return (0xFFFF);
1389 return (l);
1390}
1391
1392void
1393pf_change_ap(struct pf_addr *a, u_int16_t *p, u_int16_t *ic, u_int16_t *pc,
1394 struct pf_addr *an, u_int16_t pn, u_int8_t u, sa_family_t af)
1395{
1396 struct pf_addr ao;
1397 u_int16_t po = *p;
1398
1399 PF_ACPY(&ao, a, af);
1400 PF_ACPY(a, an, af);
1401
1402 *p = pn;
1403
1404 switch (af) {
1405#ifdef INET
1406 case AF_INET:
1407 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
1408 ao.addr16[0], an->addr16[0], 0),
1409 ao.addr16[1], an->addr16[1], 0);
1410 *p = pn;
1411 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
1412 ao.addr16[0], an->addr16[0], u),
1413 ao.addr16[1], an->addr16[1], u),
1414 po, pn, u);
1415 break;
1416#endif /* INET */
1417#ifdef INET6
1418 case AF_INET6:
1419 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1420 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1421 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
1422 ao.addr16[0], an->addr16[0], u),
1423 ao.addr16[1], an->addr16[1], u),
1424 ao.addr16[2], an->addr16[2], u),
1425 ao.addr16[3], an->addr16[3], u),
1426 ao.addr16[4], an->addr16[4], u),
1427 ao.addr16[5], an->addr16[5], u),
1428 ao.addr16[6], an->addr16[6], u),
1429 ao.addr16[7], an->addr16[7], u),
1430 po, pn, u);
1431 break;
1432#endif /* INET6 */
1433 }
1434}
1435
1436
1437/* Changes a u_int32_t. Uses a void * so there are no align restrictions */
1438void
1439pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
1440{
1441 u_int32_t ao;
1442
1443 memcpy(&ao, a, sizeof(ao));
1444 memcpy(a, &an, sizeof(u_int32_t));
1445 *c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
1446 ao % 65536, an % 65536, u);
1447}
1448
1449#ifdef INET6
1450void
1451pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
1452{
1453 struct pf_addr ao;
1454
1455 PF_ACPY(&ao, a, AF_INET6);
1456 PF_ACPY(a, an, AF_INET6);
1457
1458 *c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1459 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1460 pf_cksum_fixup(pf_cksum_fixup(*c,
1461 ao.addr16[0], an->addr16[0], u),
1462 ao.addr16[1], an->addr16[1], u),
1463 ao.addr16[2], an->addr16[2], u),
1464 ao.addr16[3], an->addr16[3], u),
1465 ao.addr16[4], an->addr16[4], u),
1466 ao.addr16[5], an->addr16[5], u),
1467 ao.addr16[6], an->addr16[6], u),
1468 ao.addr16[7], an->addr16[7], u);
1469}
1470#endif /* INET6 */
1471
1472void
1473pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
1474 struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
1475 u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
1476{
1477 struct pf_addr oia, ooa;
1478
1479 PF_ACPY(&oia, ia, af);
1480 PF_ACPY(&ooa, oa, af);
1481
1482 /* Change inner protocol port, fix inner protocol checksum. */
1483 if (ip != NULL) {
1484 u_int16_t oip = *ip;
1485 u_int32_t opc = 0;
1486
1487 if (pc != NULL)
1488 opc = *pc;
1489 *ip = np;
1490 if (pc != NULL)
1491 *pc = pf_cksum_fixup(*pc, oip, *ip, u);
1492 *ic = pf_cksum_fixup(*ic, oip, *ip, 0);
1493 if (pc != NULL)
1494 *ic = pf_cksum_fixup(*ic, opc, *pc, 0);
1495 }
1496 /* Change inner ip address, fix inner ip and icmp checksums. */
1497 PF_ACPY(ia, na, af);
1498 switch (af) {
1499#ifdef INET
1500 case AF_INET: {
1501 u_int32_t oh2c = *h2c;
1502
1503 *h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
1504 oia.addr16[0], ia->addr16[0], 0),
1505 oia.addr16[1], ia->addr16[1], 0);
1506 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
1507 oia.addr16[0], ia->addr16[0], 0),
1508 oia.addr16[1], ia->addr16[1], 0);
1509 *ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
1510 break;
1511 }
1512#endif /* INET */
1513#ifdef INET6
1514 case AF_INET6:
1515 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1516 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1517 pf_cksum_fixup(pf_cksum_fixup(*ic,
1518 oia.addr16[0], ia->addr16[0], u),
1519 oia.addr16[1], ia->addr16[1], u),
1520 oia.addr16[2], ia->addr16[2], u),
1521 oia.addr16[3], ia->addr16[3], u),
1522 oia.addr16[4], ia->addr16[4], u),
1523 oia.addr16[5], ia->addr16[5], u),
1524 oia.addr16[6], ia->addr16[6], u),
1525 oia.addr16[7], ia->addr16[7], u);
1526 break;
1527#endif /* INET6 */
1528 }
1529 /* Change outer ip address, fix outer ip or icmpv6 checksum. */
1530 PF_ACPY(oa, na, af);
1531 switch (af) {
1532#ifdef INET
1533 case AF_INET:
1534 *hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
1535 ooa.addr16[0], oa->addr16[0], 0),
1536 ooa.addr16[1], oa->addr16[1], 0);
1537 break;
1538#endif /* INET */
1539#ifdef INET6
1540 case AF_INET6:
1541 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1542 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1543 pf_cksum_fixup(pf_cksum_fixup(*ic,
1544 ooa.addr16[0], oa->addr16[0], u),
1545 ooa.addr16[1], oa->addr16[1], u),
1546 ooa.addr16[2], oa->addr16[2], u),
1547 ooa.addr16[3], oa->addr16[3], u),
1548 ooa.addr16[4], oa->addr16[4], u),
1549 ooa.addr16[5], oa->addr16[5], u),
1550 ooa.addr16[6], oa->addr16[6], u),
1551 ooa.addr16[7], oa->addr16[7], u);
1552 break;
1553#endif /* INET6 */
1554 }
1555}
1556
70224baa
JL
1557
1558/*
1559 * Need to modulate the sequence numbers in the TCP SACK option
1560 * (credits to Krzysztof Pfaff for report and patch)
1561 */
1562int
1563pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
1564 struct tcphdr *th, struct pf_state_peer *dst)
1565{
1566 int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
1567 u_int8_t opts[TCP_MAXOLEN], *opt = opts;
1568 int copyback = 0, i, olen;
1569 struct raw_sackblock sack;
1570
1571#define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
1572 if (hlen < TCPOLEN_SACKLEN ||
1573 !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
1574 return 0;
1575
1576 while (hlen >= TCPOLEN_SACKLEN) {
1577 olen = opt[1];
1578 switch (*opt) {
1579 case TCPOPT_EOL: /* FALLTHROUGH */
1580 case TCPOPT_NOP:
1581 opt++;
1582 hlen--;
1583 break;
1584 case TCPOPT_SACK:
1585 if (olen > hlen)
1586 olen = hlen;
1587 if (olen >= TCPOLEN_SACKLEN) {
1588 for (i = 2; i + TCPOLEN_SACK <= olen;
1589 i += TCPOLEN_SACK) {
1590 memcpy(&sack, &opt[i], sizeof(sack));
1591 pf_change_a(&sack.rblk_start, &th->th_sum,
4fc5aa1c 1592 htonl(ntohl(sack.rblk_start) -
70224baa
JL
1593 dst->seqdiff), 0);
1594 pf_change_a(&sack.rblk_end, &th->th_sum,
4fc5aa1c 1595 htonl(ntohl(sack.rblk_end) -
70224baa
JL
1596 dst->seqdiff), 0);
1597 memcpy(&opt[i], &sack, sizeof(sack));
1598 }
1599 copyback = 1;
1600 }
1601 /* FALLTHROUGH */
1602 default:
1603 if (olen < 2)
1604 olen = 2;
1605 hlen -= olen;
1606 opt += olen;
1607 }
1608 }
1609
1610 if (copyback)
1611 m_copyback(m, off + sizeof(*th), thoptlen, opts);
1612 return (copyback);
1613}
1614
02742ec6
JS
1615void
1616pf_send_tcp(const struct pf_rule *r, sa_family_t af,
1617 const struct pf_addr *saddr, const struct pf_addr *daddr,
1618 u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
70224baa
JL
1619 u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
1620 u_int16_t rtag, struct ether_header *eh, struct ifnet *ifp)
02742ec6
JS
1621{
1622 struct mbuf *m;
1623 int len = 0, tlen;
1624#ifdef INET
1625 struct ip *h = NULL;
1626#endif /* INET */
1627#ifdef INET6
1628 struct ip6_hdr *h6 = NULL;
1629#endif /* INET6 */
1630 struct tcphdr *th = NULL;
70224baa 1631 char *opt;
02742ec6 1632
2a7a2b1c
JL
1633 ASSERT_LWKT_TOKEN_HELD(&pf_token);
1634
02742ec6
JS
1635 /* maximum segment size tcp option */
1636 tlen = sizeof(struct tcphdr);
1637 if (mss)
1638 tlen += 4;
1639
1640 switch (af) {
1641#ifdef INET
1642 case AF_INET:
1643 len = sizeof(struct ip) + tlen;
1644 break;
1645#endif /* INET */
1646#ifdef INET6
1647 case AF_INET6:
1648 len = sizeof(struct ip6_hdr) + tlen;
1649 break;
1650#endif /* INET6 */
1651 }
1652
1653 /* create outgoing mbuf */
1654 m = m_gethdr(MB_DONTWAIT, MT_HEADER);
2a7a2b1c 1655 if (m == NULL) {
02742ec6 1656 return;
2a7a2b1c 1657 }
70224baa 1658 if (tag)
315a7da3
JL
1659 m->m_pkthdr.pf.flags |= PF_TAG_GENERATED;
1660 m->m_pkthdr.pf.tag = rtag;
70224baa
JL
1661
1662 if (r != NULL && r->rtableid >= 0)
02dd99a9 1663 m->m_pkthdr.pf.rtableid = r->rtableid;
70224baa 1664
02742ec6
JS
1665#ifdef ALTQ
1666 if (r != NULL && r->qid) {
315a7da3
JL
1667 m->m_pkthdr.fw_flags |= PF_MBUF_STRUCTURE;
1668 m->m_pkthdr.pf.qid = r->qid;
1669 m->m_pkthdr.pf.ecn_af = af;
1670 m->m_pkthdr.pf.hdr = mtod(m, struct ip *);
02742ec6 1671 }
70224baa 1672#endif /* ALTQ */
02742ec6
JS
1673 m->m_data += max_linkhdr;
1674 m->m_pkthdr.len = m->m_len = len;
1675 m->m_pkthdr.rcvif = NULL;
1676 bzero(m->m_data, len);
1677 switch (af) {
1678#ifdef INET
1679 case AF_INET:
1680 h = mtod(m, struct ip *);
1681
1682 /* IP header fields included in the TCP checksum */
1683 h->ip_p = IPPROTO_TCP;
1684 h->ip_len = tlen;
1685 h->ip_src.s_addr = saddr->v4.s_addr;
1686 h->ip_dst.s_addr = daddr->v4.s_addr;
1687
1688 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
1689 break;
1690#endif /* INET */
1691#ifdef INET6
1692 case AF_INET6:
1693 h6 = mtod(m, struct ip6_hdr *);
1694
1695 /* IP header fields included in the TCP checksum */
1696 h6->ip6_nxt = IPPROTO_TCP;
1697 h6->ip6_plen = htons(tlen);
1698 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
1699 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
1700
1701 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
1702 break;
1703#endif /* INET6 */
1704 }
1705
1706 /* TCP header */
1707 th->th_sport = sport;
1708 th->th_dport = dport;
1709 th->th_seq = htonl(seq);
1710 th->th_ack = htonl(ack);
1711 th->th_off = tlen >> 2;
1712 th->th_flags = flags;
1713 th->th_win = htons(win);
1714
1715 if (mss) {
1716 opt = (char *)(th + 1);
1717 opt[0] = TCPOPT_MAXSEG;
1718 opt[1] = 4;
1719 mss = htons(mss);
1720 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
1721 }
1722
1723 switch (af) {
1724#ifdef INET
1725 case AF_INET:
1726 /* TCP checksum */
1727 th->th_sum = in_cksum(m, len);
1728
1729 /* Finish the IP header */
1730 h->ip_v = 4;
1731 h->ip_hl = sizeof(*h) >> 2;
1732 h->ip_tos = IPTOS_LOWDELAY;
1733 h->ip_len = len;
1734 h->ip_off = path_mtu_discovery ? IP_DF : 0;
1735 h->ip_ttl = ttl ? ttl : ip_defttl;
1736 h->ip_sum = 0;
70224baa 1737 if (eh == NULL) {
2a7a2b1c 1738 lwkt_reltoken(&pf_token);
70224baa 1739 ip_output(m, NULL, NULL, 0, NULL, NULL);
2a7a2b1c 1740 lwkt_gettoken(&pf_token);
70224baa
JL
1741 } else {
1742 struct route ro;
1743 struct rtentry rt;
1744 struct ether_header *e = (void *)ro.ro_dst.sa_data;
1745
1746 if (ifp == NULL) {
1747 m_freem(m);
1748 return;
1749 }
1750 rt.rt_ifp = ifp;
1751 ro.ro_rt = &rt;
1752 ro.ro_dst.sa_len = sizeof(ro.ro_dst);
1753 ro.ro_dst.sa_family = pseudo_AF_HDRCMPLT;
1754 bcopy(eh->ether_dhost, e->ether_shost, ETHER_ADDR_LEN);
1755 bcopy(eh->ether_shost, e->ether_dhost, ETHER_ADDR_LEN);
1756 e->ether_type = eh->ether_type;
1757 /* XXX_IMPORT: later */
2a7a2b1c 1758 lwkt_reltoken(&pf_token);
70224baa
JL
1759 ip_output(m, (void *)NULL, &ro, 0,
1760 (void *)NULL, (void *)NULL);
2a7a2b1c 1761 lwkt_gettoken(&pf_token);
70224baa 1762 }
02742ec6
JS
1763 break;
1764#endif /* INET */
1765#ifdef INET6
1766 case AF_INET6:
1767 /* TCP checksum */
1768 th->th_sum = in6_cksum(m, IPPROTO_TCP,
1769 sizeof(struct ip6_hdr), tlen);
1770
1771 h6->ip6_vfc |= IPV6_VERSION;
1772 h6->ip6_hlim = IPV6_DEFHLIM;
1773
2a7a2b1c 1774 lwkt_reltoken(&pf_token);
02742ec6 1775 ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
2a7a2b1c 1776 lwkt_gettoken(&pf_token);
02742ec6
JS
1777 break;
1778#endif /* INET6 */
1779 }
1780}
1781
1782void
1783pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
1784 struct pf_rule *r)
1785{
1786 struct mbuf *m0;
1787
70224baa 1788 m0 = m_copy(m, 0, M_COPYALL);
315a7da3 1789 m0->m_pkthdr.pf.flags |= PF_TAG_GENERATED;
70224baa
JL
1790
1791 if (r->rtableid >= 0)
315a7da3 1792 m0->m_pkthdr.pf.rtableid = r->rtableid;
02742ec6
JS
1793
1794#ifdef ALTQ
1795 if (r->qid) {
315a7da3
JL
1796 m->m_pkthdr.fw_flags |= PF_MBUF_STRUCTURE;
1797 m0->m_pkthdr.pf.qid = r->qid;
1798 m0->m_pkthdr.pf.ecn_af = af;
1799 m0->m_pkthdr.pf.hdr = mtod(m0, struct ip *);
02742ec6 1800 }
70224baa 1801#endif /* ALTQ */
02742ec6
JS
1802
1803 switch (af) {
1804#ifdef INET
1805 case AF_INET:
745a4a5d 1806 icmp_error(m0, type, code, 0, 0);
02742ec6
JS
1807 break;
1808#endif /* INET */
1809#ifdef INET6
1810 case AF_INET6:
1811 icmp6_error(m0, type, code, 0);
1812 break;
1813#endif /* INET6 */
1814 }
1815}
1816
1817/*
1818 * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
1819 * If n is 0, they match if they are equal. If n is != 0, they match if they
1820 * are different.
1821 */
1822int
1823pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
1824 struct pf_addr *b, sa_family_t af)
1825{
1826 int match = 0;
1827
1828 switch (af) {
1829#ifdef INET
1830 case AF_INET:
1831 if ((a->addr32[0] & m->addr32[0]) ==
1832 (b->addr32[0] & m->addr32[0]))
1833 match++;
1834 break;
1835#endif /* INET */
1836#ifdef INET6
1837 case AF_INET6:
1838 if (((a->addr32[0] & m->addr32[0]) ==
1839 (b->addr32[0] & m->addr32[0])) &&
1840 ((a->addr32[1] & m->addr32[1]) ==
1841 (b->addr32[1] & m->addr32[1])) &&
1842 ((a->addr32[2] & m->addr32[2]) ==
1843 (b->addr32[2] & m->addr32[2])) &&
1844 ((a->addr32[3] & m->addr32[3]) ==
1845 (b->addr32[3] & m->addr32[3])))
1846 match++;
1847 break;
1848#endif /* INET6 */
1849 }
1850 if (match) {
1851 if (n)
1852 return (0);
1853 else
1854 return (1);
1855 } else {
1856 if (n)
1857 return (1);
1858 else
1859 return (0);
1860 }
1861}
1862
1863int
1864pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
1865{
1866 switch (op) {
1867 case PF_OP_IRG:
1868 return ((p > a1) && (p < a2));
1869 case PF_OP_XRG:
1870 return ((p < a1) || (p > a2));
1871 case PF_OP_RRG:
1872 return ((p >= a1) && (p <= a2));
1873 case PF_OP_EQ:
1874 return (p == a1);
1875 case PF_OP_NE:
1876 return (p != a1);
1877 case PF_OP_LT:
1878 return (p < a1);
1879 case PF_OP_LE:
1880 return (p <= a1);
1881 case PF_OP_GT:
1882 return (p > a1);
1883 case PF_OP_GE:
1884 return (p >= a1);
1885 }
1886 return (0); /* never reached */
1887}
1888
1889int
1890pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
1891{
1892 a1 = ntohs(a1);
1893 a2 = ntohs(a2);
1894 p = ntohs(p);
1895 return (pf_match(op, a1, a2, p));
1896}
1897
1898int
1899pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
1900{
1901 if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
1902 return (0);
1903 return (pf_match(op, a1, a2, u));
1904}
1905
1906int
1907pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
1908{
1909 if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
1910 return (0);
1911 return (pf_match(op, a1, a2, g));
1912}
1913
70224baa 1914int
315a7da3 1915pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag)
70224baa
JL
1916{
1917 if (*tag == -1)
315a7da3 1918 *tag = m->m_pkthdr.pf.tag;
70224baa 1919
02742ec6
JS
1920 return ((!r->match_tag_not && r->match_tag == *tag) ||
1921 (r->match_tag_not && r->match_tag != *tag));
1922}
1923
70224baa 1924int
315a7da3 1925pf_tag_packet(struct mbuf *m, int tag, int rtableid)
02742ec6 1926{
70224baa
JL
1927 if (tag <= 0 && rtableid < 0)
1928 return (0);
1929
70224baa 1930 if (tag > 0)
315a7da3 1931 m->m_pkthdr.pf.tag = tag;
70224baa 1932 if (rtableid >= 0)
315a7da3 1933 m->m_pkthdr.pf.rtableid = rtableid;
02742ec6 1934
70224baa 1935 return (0);
02742ec6
JS
1936}
1937
315a7da3 1938void
70224baa
JL
1939pf_step_into_anchor(int *depth, struct pf_ruleset **rs, int n,
1940 struct pf_rule **r, struct pf_rule **a, int *match)
1941{
1942 struct pf_anchor_stackframe *f;
1943
1944 (*r)->anchor->match = 0;
1945 if (match)
1946 *match = 0;
1947 if (*depth >= sizeof(pf_anchor_stack) /
1948 sizeof(pf_anchor_stack[0])) {
1949 kprintf("pf_step_into_anchor: stack overflow\n");
1950 *r = TAILQ_NEXT(*r, entries);
1951 return;
1952 } else if (*depth == 0 && a != NULL)
1953 *a = *r;
1954 f = pf_anchor_stack + (*depth)++;
1955 f->rs = *rs;
1956 f->r = *r;
1957 if ((*r)->anchor_wildcard) {
1958 f->parent = &(*r)->anchor->children;
1959 if ((f->child = RB_MIN(pf_anchor_node, f->parent)) ==
1960 NULL) {
1961 *r = NULL;
1962 return;
1963 }
1964 *rs = &f->child->ruleset;
1965 } else {
1966 f->parent = NULL;
1967 f->child = NULL;
1968 *rs = &(*r)->anchor->ruleset;
1969 }
1970 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
1971}
02742ec6 1972
70224baa
JL
1973int
1974pf_step_out_of_anchor(int *depth, struct pf_ruleset **rs, int n,
1975 struct pf_rule **r, struct pf_rule **a, int *match)
1976{
1977 struct pf_anchor_stackframe *f;
1978 int quick = 0;
1979
1980 do {
1981 if (*depth <= 0)
1982 break;
1983 f = pf_anchor_stack + *depth - 1;
1984 if (f->parent != NULL && f->child != NULL) {
1985 if (f->child->match ||
1986 (match != NULL && *match)) {
1987 f->r->anchor->match = 1;
1988 *match = 0;
1989 }
1990 f->child = RB_NEXT(pf_anchor_node, f->parent, f->child);
1991 if (f->child != NULL) {
1992 *rs = &f->child->ruleset;
1993 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
1994 if (*r == NULL)
1995 continue;
1996 else
1997 break;
1998 }
1999 }
2000 (*depth)--;
2001 if (*depth == 0 && a != NULL)
2002 *a = NULL;
2003 *rs = f->rs;
2004 if (f->r->anchor->match || (match != NULL && *match))
2005 quick = f->r->quick;
2006 *r = TAILQ_NEXT(f->r, entries);
2007 } while (*r == NULL);
2008
2009 return (quick);
2010}
02742ec6
JS
2011
2012#ifdef INET6
2013void
2014pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2015 struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2016{
2017 switch (af) {
2018#ifdef INET
2019 case AF_INET:
2020 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2021 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2022 break;
2023#endif /* INET */
2024 case AF_INET6:
2025 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2026 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2027 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2028 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2029 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2030 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2031 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2032 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2033 break;
2034 }
2035}
2036
2037void
2038pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2039{
2040 switch (af) {
2041#ifdef INET
2042 case AF_INET:
2043 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2044 break;
2045#endif /* INET */
2046 case AF_INET6:
2047 if (addr->addr32[3] == 0xffffffff) {
2048 addr->addr32[3] = 0;
2049 if (addr->addr32[2] == 0xffffffff) {
2050 addr->addr32[2] = 0;
2051 if (addr->addr32[1] == 0xffffffff) {
2052 addr->addr32[1] = 0;
2053 addr->addr32[0] =
2054 htonl(ntohl(addr->addr32[0]) + 1);
2055 } else
2056 addr->addr32[1] =
2057 htonl(ntohl(addr->addr32[1]) + 1);
2058 } else
2059 addr->addr32[2] =
2060 htonl(ntohl(addr->addr32[2]) + 1);
2061 } else
2062 addr->addr32[3] =
2063 htonl(ntohl(addr->addr32[3]) + 1);
2064 break;
2065 }
2066}
2067#endif /* INET6 */
2068
2069#define mix(a,b,c) \
2070 do { \
2071 a -= b; a -= c; a ^= (c >> 13); \
2072 b -= c; b -= a; b ^= (a << 8); \
2073 c -= a; c -= b; c ^= (b >> 13); \
2074 a -= b; a -= c; a ^= (c >> 12); \
2075 b -= c; b -= a; b ^= (a << 16); \
2076 c -= a; c -= b; c ^= (b >> 5); \
2077 a -= b; a -= c; a ^= (c >> 3); \
2078 b -= c; b -= a; b ^= (a << 10); \
2079 c -= a; c -= b; c ^= (b >> 15); \
2080 } while (0)
2081
2082/*
2083 * hash function based on bridge_hash in if_bridge.c
2084 */
2085void
2086pf_hash(struct pf_addr *inaddr, struct pf_addr *hash,
2087 struct pf_poolhashkey *key, sa_family_t af)
2088{
2089 u_int32_t a = 0x9e3779b9, b = 0x9e3779b9, c = key->key32[0];
2090
2091 switch (af) {
2092#ifdef INET
2093 case AF_INET:
2094 a += inaddr->addr32[0];
2095 b += key->key32[1];
2096 mix(a, b, c);
2097 hash->addr32[0] = c + key->key32[2];
2098 break;
2099#endif /* INET */
2100#ifdef INET6
2101 case AF_INET6:
2102 a += inaddr->addr32[0];
2103 b += inaddr->addr32[2];
2104 mix(a, b, c);
2105 hash->addr32[0] = c;
2106 a += inaddr->addr32[1];
2107 b += inaddr->addr32[3];
2108 c += key->key32[1];
2109 mix(a, b, c);
2110 hash->addr32[1] = c;
2111 a += inaddr->addr32[2];
2112 b += inaddr->addr32[1];
2113 c += key->key32[2];
2114 mix(a, b, c);
2115 hash->addr32[2] = c;
2116 a += inaddr->addr32[3];
2117 b += inaddr->addr32[0];
2118 c += key->key32[3];
2119 mix(a, b, c);
2120 hash->addr32[3] = c;
2121 break;
2122#endif /* INET6 */
2123 }
2124}
2125
2126int
2127pf_map_addr(sa_family_t af, struct pf_rule *r, struct pf_addr *saddr,
2128 struct pf_addr *naddr, struct pf_addr *init_addr, struct pf_src_node **sn)
2129{
2130 unsigned char hash[16];
2131 struct pf_pool *rpool = &r->rpool;
2132 struct pf_addr *raddr = &rpool->cur->addr.v.a.addr;
2133 struct pf_addr *rmask = &rpool->cur->addr.v.a.mask;
2134 struct pf_pooladdr *acur = rpool->cur;
2135 struct pf_src_node k;
2136
2137 if (*sn == NULL && r->rpool.opts & PF_POOL_STICKYADDR &&
2138 (r->rpool.opts & PF_POOL_TYPEMASK) != PF_POOL_NONE) {
2139 k.af = af;
2140 PF_ACPY(&k.addr, saddr, af);
2141 if (r->rule_flag & PFRULE_RULESRCTRACK ||
2142 r->rpool.opts & PF_POOL_STICKYADDR)
2143 k.rule.ptr = r;
2144 else
2145 k.rule.ptr = NULL;
2146 pf_status.scounters[SCNT_SRC_NODE_SEARCH]++;
2147 *sn = RB_FIND(pf_src_tree, &tree_src_tracking, &k);
2148 if (*sn != NULL && !PF_AZERO(&(*sn)->raddr, af)) {
2149 PF_ACPY(naddr, &(*sn)->raddr, af);
2150 if (pf_status.debug >= PF_DEBUG_MISC) {
4b1cf444 2151 kprintf("pf_map_addr: src tracking maps ");
02742ec6 2152 pf_print_host(&k.addr, 0, af);
4b1cf444 2153 kprintf(" to ");
02742ec6 2154 pf_print_host(naddr, 0, af);
4b1cf444 2155 kprintf("\n");
02742ec6
JS
2156 }
2157 return (0);
2158 }
2159 }
2160
2161 if (rpool->cur->addr.type == PF_ADDR_NOROUTE)
2162 return (1);
2163 if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
70224baa
JL
2164 switch (af) {
2165#ifdef INET
2166 case AF_INET:
02742ec6
JS
2167 if (rpool->cur->addr.p.dyn->pfid_acnt4 < 1 &&
2168 (rpool->opts & PF_POOL_TYPEMASK) !=
2169 PF_POOL_ROUNDROBIN)
2170 return (1);
2171 raddr = &rpool->cur->addr.p.dyn->pfid_addr4;
2172 rmask = &rpool->cur->addr.p.dyn->pfid_mask4;
70224baa
JL
2173 break;
2174#endif /* INET */
2175#ifdef INET6
2176 case AF_INET6:
02742ec6
JS
2177 if (rpool->cur->addr.p.dyn->pfid_acnt6 < 1 &&
2178 (rpool->opts & PF_POOL_TYPEMASK) !=
2179 PF_POOL_ROUNDROBIN)
2180 return (1);
2181 raddr = &rpool->cur->addr.p.dyn->pfid_addr6;
2182 rmask = &rpool->cur->addr.p.dyn->pfid_mask6;
70224baa
JL
2183 break;
2184#endif /* INET6 */
02742ec6
JS
2185 }
2186 } else if (rpool->cur->addr.type == PF_ADDR_TABLE) {
2187 if ((rpool->opts & PF_POOL_TYPEMASK) != PF_POOL_ROUNDROBIN)
2188 return (1); /* unsupported */
2189 } else {
2190 raddr = &rpool->cur->addr.v.a.addr;
2191 rmask = &rpool->cur->addr.v.a.mask;
2192 }
2193
2194 switch (rpool->opts & PF_POOL_TYPEMASK) {
2195 case PF_POOL_NONE:
2196 PF_ACPY(naddr, raddr, af);
2197 break;
2198 case PF_POOL_BITMASK:
2199 PF_POOLMASK(naddr, raddr, rmask, saddr, af);
2200 break;
2201 case PF_POOL_RANDOM:
2202 if (init_addr != NULL && PF_AZERO(init_addr, af)) {
2203 switch (af) {
2204#ifdef INET
2205 case AF_INET:
4fc5aa1c 2206 rpool->counter.addr32[0] = htonl(karc4random());
02742ec6
JS
2207 break;
2208#endif /* INET */
2209#ifdef INET6
2210 case AF_INET6:
2211 if (rmask->addr32[3] != 0xffffffff)
70224baa 2212 rpool->counter.addr32[3] =
4fc5aa1c 2213 htonl(karc4random());
02742ec6
JS
2214 else
2215 break;
2216 if (rmask->addr32[2] != 0xffffffff)
70224baa 2217 rpool->counter.addr32[2] =
4fc5aa1c 2218 htonl(karc4random());
02742ec6
JS
2219 else
2220 break;
2221 if (rmask->addr32[1] != 0xffffffff)
70224baa 2222 rpool->counter.addr32[1] =
4fc5aa1c 2223 htonl(karc4random());
02742ec6
JS
2224 else
2225 break;
2226 if (rmask->addr32[0] != 0xffffffff)
70224baa 2227 rpool->counter.addr32[0] =
4fc5aa1c 2228 htonl(karc4random());
02742ec6
JS
2229 break;
2230#endif /* INET6 */
2231 }
2232 PF_POOLMASK(naddr, raddr, rmask, &rpool->counter, af);
2233 PF_ACPY(init_addr, naddr, af);
2234
2235 } else {
2236 PF_AINC(&rpool->counter, af);
2237 PF_POOLMASK(naddr, raddr, rmask, &rpool->counter, af);
2238 }
2239 break;
2240 case PF_POOL_SRCHASH:
2241 pf_hash(saddr, (struct pf_addr *)&hash, &rpool->key, af);
2242 PF_POOLMASK(naddr, raddr, rmask, (struct pf_addr *)&hash, af);
2243 break;
2244 case PF_POOL_ROUNDROBIN:
2245 if (rpool->cur->addr.type == PF_ADDR_TABLE) {
2246 if (!pfr_pool_get(rpool->cur->addr.p.tbl,
2247 &rpool->tblidx, &rpool->counter,
2248 &raddr, &rmask, af))
2249 goto get_addr;
2250 } else if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
2251 if (!pfr_pool_get(rpool->cur->addr.p.dyn->pfid_kt,
2252 &rpool->tblidx, &rpool->counter,
2253 &raddr, &rmask, af))
2254 goto get_addr;
2255 } else if (pf_match_addr(0, raddr, rmask, &rpool->counter, af))
2256 goto get_addr;
2257
2258 try_next:
2259 if ((rpool->cur = TAILQ_NEXT(rpool->cur, entries)) == NULL)
2260 rpool->cur = TAILQ_FIRST(&rpool->list);
2261 if (rpool->cur->addr.type == PF_ADDR_TABLE) {
2262 rpool->tblidx = -1;
2263 if (pfr_pool_get(rpool->cur->addr.p.tbl,
2264 &rpool->tblidx, &rpool->counter,
2265 &raddr, &rmask, af)) {
2266 /* table contains no address of type 'af' */
2267 if (rpool->cur != acur)
2268 goto try_next;
2269 return (1);
2270 }
2271 } else if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
2272 rpool->tblidx = -1;
2273 if (pfr_pool_get(rpool->cur->addr.p.dyn->pfid_kt,
2274 &rpool->tblidx, &rpool->counter,
2275 &raddr, &rmask, af)) {
2276 /* table contains no address of type 'af' */
2277 if (rpool->cur != acur)
2278 goto try_next;
2279 return (1);
2280 }
2281 } else {
2282 raddr = &rpool->cur->addr.v.a.addr;
2283 rmask = &rpool->cur->addr.v.a.mask;
2284 PF_ACPY(&rpool->counter, raddr, af);
2285 }
2286
2287 get_addr:
2288 PF_ACPY(naddr, &rpool->counter, af);
70224baa
JL
2289 if (init_addr != NULL && PF_AZERO(init_addr, af))
2290 PF_ACPY(init_addr, naddr, af);
02742ec6
JS
2291 PF_AINC(&rpool->counter, af);
2292 break;
2293 }
2294 if (*sn != NULL)
2295 PF_ACPY(&(*sn)->raddr, naddr, af);
2296
2297 if (pf_status.debug >= PF_DEBUG_MISC &&
2298 (rpool->opts & PF_POOL_TYPEMASK) != PF_POOL_NONE) {
4b1cf444 2299 kprintf("pf_map_addr: selected address ");
02742ec6 2300 pf_print_host(naddr, 0, af);
4b1cf444 2301 kprintf("\n");
02742ec6
JS
2302 }
2303
2304 return (0);
2305}
2306
2307int
2308pf_get_sport(sa_family_t af, u_int8_t proto, struct pf_rule *r,
2309 struct pf_addr *saddr, struct pf_addr *daddr, u_int16_t dport,
2310 struct pf_addr *naddr, u_int16_t *nport, u_int16_t low, u_int16_t high,
2311 struct pf_src_node **sn)
2312{
315a7da3 2313 struct pf_state_key_cmp key;
02742ec6
JS
2314 struct pf_addr init_addr;
2315 u_int16_t cut;
2316
2317 bzero(&init_addr, sizeof(init_addr));
2318 if (pf_map_addr(af, r, saddr, naddr, &init_addr, sn))
2319 return (1);
2320
70224baa
JL
2321 if (proto == IPPROTO_ICMP) {
2322 low = 1;
2323 high = 65535;
2324 }
2325
02742ec6
JS
2326 do {
2327 key.af = af;
2328 key.proto = proto;
2329 PF_ACPY(&key.ext.addr, daddr, key.af);
2330 PF_ACPY(&key.gwy.addr, naddr, key.af);
2331 key.ext.port = dport;
2332
2333 /*
2334 * port search; start random, step;
2335 * similar 2 portloop in in_pcbbind
2336 */
70224baa
JL
2337 if (!(proto == IPPROTO_TCP || proto == IPPROTO_UDP ||
2338 proto == IPPROTO_ICMP)) {
2339 key.gwy.port = dport;
02742ec6
JS
2340 if (pf_find_state_all(&key, PF_EXT_GWY, NULL) == NULL)
2341 return (0);
2342 } else if (low == 0 && high == 0) {
2343 key.gwy.port = *nport;
2344 if (pf_find_state_all(&key, PF_EXT_GWY, NULL) == NULL)
2345 return (0);
2346 } else if (low == high) {
2347 key.gwy.port = htons(low);
2348 if (pf_find_state_all(&key, PF_EXT_GWY, NULL) == NULL) {
2349 *nport = htons(low);
2350 return (0);
2351 }
2352 } else {
2353 u_int16_t tmp;
2354
2355 if (low > high) {
2356 tmp = low;
2357 low = high;
2358 high = tmp;
2359 }
2360 /* low < high */
4fc5aa1c 2361 cut = htonl(karc4random()) % (1 + high - low) + low;
02742ec6
JS
2362 /* low <= cut <= high */
2363 for (tmp = cut; tmp <= high; ++(tmp)) {
2364 key.gwy.port = htons(tmp);
2365 if (pf_find_state_all(&key, PF_EXT_GWY, NULL) ==
2366 NULL) {
2367 *nport = htons(tmp);
2368 return (0);
2369 }
2370 }
2371 for (tmp = cut - 1; tmp >= low; --(tmp)) {
2372 key.gwy.port = htons(tmp);
2373 if (pf_find_state_all(&key, PF_EXT_GWY, NULL) ==
2374 NULL) {
2375 *nport = htons(tmp);
2376 return (0);
2377 }
2378 }
2379 }
2380
2381 switch (r->rpool.opts & PF_POOL_TYPEMASK) {
2382 case PF_POOL_RANDOM:
2383 case PF_POOL_ROUNDROBIN:
2384 if (pf_map_addr(af, r, saddr, naddr, &init_addr, sn))
2385 return (1);
2386 break;
2387 case PF_POOL_NONE:
2388 case PF_POOL_SRCHASH:
2389 case PF_POOL_BITMASK:
2390 default:
2391 return (1);
2392 }
2393 } while (! PF_AEQ(&init_addr, naddr, af) );
2394
2395 return (1); /* none available */
2396}
2397
2398struct pf_rule *
2399pf_match_translation(struct pf_pdesc *pd, struct mbuf *m, int off,
2400 int direction, struct pfi_kif *kif, struct pf_addr *saddr, u_int16_t sport,
2401 struct pf_addr *daddr, u_int16_t dport, int rs_num)
2402{
70224baa 2403 struct pf_rule *r, *rm = NULL;
02742ec6 2404 struct pf_ruleset *ruleset = NULL;
70224baa
JL
2405 int tag = -1;
2406 int rtableid = -1;
2407 int asd = 0;
02742ec6
JS
2408
2409 r = TAILQ_FIRST(pf_main_ruleset.rules[rs_num].active.ptr);
2410 while (r && rm == NULL) {
2411 struct pf_rule_addr *src = NULL, *dst = NULL;
2412 struct pf_addr_wrap *xdst = NULL;
2413
2414 if (r->action == PF_BINAT && direction == PF_IN) {
2415 src = &r->dst;
2416 if (r->rpool.cur != NULL)
2417 xdst = &r->rpool.cur->addr;
2418 } else {
2419 src = &r->src;
2420 dst = &r->dst;
2421 }
2422
2423 r->evaluations++;
70224baa 2424 if (pfi_kif_match(r->kif, kif) == r->ifnot)
02742ec6
JS
2425 r = r->skip[PF_SKIP_IFP].ptr;
2426 else if (r->direction && r->direction != direction)
2427 r = r->skip[PF_SKIP_DIR].ptr;
2428 else if (r->af && r->af != pd->af)
2429 r = r->skip[PF_SKIP_AF].ptr;
2430 else if (r->proto && r->proto != pd->proto)
2431 r = r->skip[PF_SKIP_PROTO].ptr;
70224baa
JL
2432 else if (PF_MISMATCHAW(&src->addr, saddr, pd->af,
2433 src->neg, kif))
02742ec6
JS
2434 r = r->skip[src == &r->src ? PF_SKIP_SRC_ADDR :
2435 PF_SKIP_DST_ADDR].ptr;
2436 else if (src->port_op && !pf_match_port(src->port_op,
2437 src->port[0], src->port[1], sport))
2438 r = r->skip[src == &r->src ? PF_SKIP_SRC_PORT :
2439 PF_SKIP_DST_PORT].ptr;
2440 else if (dst != NULL &&
70224baa 2441 PF_MISMATCHAW(&dst->addr, daddr, pd->af, dst->neg, NULL))
02742ec6 2442 r = r->skip[PF_SKIP_DST_ADDR].ptr;
70224baa
JL
2443 else if (xdst != NULL && PF_MISMATCHAW(xdst, daddr, pd->af,
2444 0, NULL))
02742ec6
JS
2445 r = TAILQ_NEXT(r, entries);
2446 else if (dst != NULL && dst->port_op &&
2447 !pf_match_port(dst->port_op, dst->port[0],
2448 dst->port[1], dport))
2449 r = r->skip[PF_SKIP_DST_PORT].ptr;
315a7da3 2450 else if (r->match_tag && !pf_match_tag(m, r, &tag))
70224baa 2451 r = TAILQ_NEXT(r, entries);
02742ec6
JS
2452 else if (r->os_fingerprint != PF_OSFP_ANY && (pd->proto !=
2453 IPPROTO_TCP || !pf_osfp_match(pf_osfp_fingerprint(pd, m,
2454 off, pd->hdr.tcp), r->os_fingerprint)))
2455 r = TAILQ_NEXT(r, entries);
70224baa
JL
2456 else {
2457 if (r->tag)
2458 tag = r->tag;
2459 if (r->rtableid >= 0)
2460 rtableid = r->rtableid;
2461 if (r->anchor == NULL) {
02742ec6 2462 rm = r;
70224baa
JL
2463 } else
2464 pf_step_into_anchor(&asd, &ruleset, rs_num,
2465 &r, NULL, NULL);
2466 }
2467 if (r == NULL)
2468 pf_step_out_of_anchor(&asd, &ruleset, rs_num, &r,
2469 NULL, NULL);
02742ec6 2470 }
315a7da3 2471 if (pf_tag_packet(m, tag, rtableid))
70224baa 2472 return (NULL);
02742ec6
JS
2473 if (rm != NULL && (rm->action == PF_NONAT ||
2474 rm->action == PF_NORDR || rm->action == PF_NOBINAT))
2475 return (NULL);
2476 return (rm);
2477}
2478
2479struct pf_rule *
2480pf_get_translation(struct pf_pdesc *pd, struct mbuf *m, int off, int direction,
2481 struct pfi_kif *kif, struct pf_src_node **sn,
2482 struct pf_addr *saddr, u_int16_t sport,
2483 struct pf_addr *daddr, u_int16_t dport,
2484 struct pf_addr *naddr, u_int16_t *nport)
2485{
2486 struct pf_rule *r = NULL;
2487
2488 if (direction == PF_OUT) {
2489 r = pf_match_translation(pd, m, off, direction, kif, saddr,
2490 sport, daddr, dport, PF_RULESET_BINAT);
2491 if (r == NULL)
2492 r = pf_match_translation(pd, m, off, direction, kif,
2493 saddr, sport, daddr, dport, PF_RULESET_NAT);
2494 } else {
2495 r = pf_match_translation(pd, m, off, direction, kif, saddr,
2496 sport, daddr, dport, PF_RULESET_RDR);
2497 if (r == NULL)
2498 r = pf_match_translation(pd, m, off, direction, kif,
2499 saddr, sport, daddr, dport, PF_RULESET_BINAT);
2500 }
2501
2502 if (r != NULL) {
2503 switch (r->action) {
2504 case PF_NONAT:
2505 case PF_NOBINAT:
2506 case PF_NORDR:
2507 return (NULL);
2508 case PF_NAT:
2509 if (pf_get_sport(pd->af, pd->proto, r, saddr,
2510 daddr, dport, naddr, nport, r->rpool.proxy_port[0],
2511 r->rpool.proxy_port[1], sn)) {
2512 DPFPRINTF(PF_DEBUG_MISC,
2513 ("pf: NAT proxy port allocation "
2514 "(%u-%u) failed\n",
2515 r->rpool.proxy_port[0],
2516 r->rpool.proxy_port[1]));
2517 return (NULL);
2518 }
2519 break;
2520 case PF_BINAT:
2521 switch (direction) {
2522 case PF_OUT:
2523 if (r->rpool.cur->addr.type == PF_ADDR_DYNIFTL){
70224baa
JL
2524 switch (pd->af) {
2525#ifdef INET
2526 case AF_INET:
02742ec6
JS
2527 if (r->rpool.cur->addr.p.dyn->
2528 pfid_acnt4 < 1)
2529 return (NULL);
2530 PF_POOLMASK(naddr,
2531 &r->rpool.cur->addr.p.dyn->
2532 pfid_addr4,
2533 &r->rpool.cur->addr.p.dyn->
2534 pfid_mask4,
2535 saddr, AF_INET);
70224baa
JL
2536 break;
2537#endif /* INET */
2538#ifdef INET6
2539 case AF_INET6:
02742ec6
JS
2540 if (r->rpool.cur->addr.p.dyn->
2541 pfid_acnt6 < 1)
2542 return (NULL);
2543 PF_POOLMASK(naddr,
2544 &r->rpool.cur->addr.p.dyn->
2545 pfid_addr6,
2546 &r->rpool.cur->addr.p.dyn->
2547 pfid_mask6,
2548 saddr, AF_INET6);
70224baa
JL
2549 break;
2550#endif /* INET6 */
02742ec6
JS
2551 }
2552 } else
2553 PF_POOLMASK(naddr,
2554 &r->rpool.cur->addr.v.a.addr,
2555 &r->rpool.cur->addr.v.a.mask,
2556 saddr, pd->af);
2557 break;
2558 case PF_IN:
70224baa
JL
2559 if (r->src.addr.type == PF_ADDR_DYNIFTL) {
2560 switch (pd->af) {
2561#ifdef INET
2562 case AF_INET:
02742ec6
JS
2563 if (r->src.addr.p.dyn->
2564 pfid_acnt4 < 1)
2565 return (NULL);
2566 PF_POOLMASK(naddr,
2567 &r->src.addr.p.dyn->
2568 pfid_addr4,
2569 &r->src.addr.p.dyn->
2570 pfid_mask4,
2571 daddr, AF_INET);
70224baa
JL
2572 break;
2573#endif /* INET */
2574#ifdef INET6
2575 case AF_INET6:
02742ec6
JS
2576 if (r->src.addr.p.dyn->
2577 pfid_acnt6 < 1)
2578 return (NULL);
2579 PF_POOLMASK(naddr,
2580 &r->src.addr.p.dyn->
2581 pfid_addr6,
2582 &r->src.addr.p.dyn->
2583 pfid_mask6,
2584 daddr, AF_INET6);
70224baa
JL
2585 break;
2586#endif /* INET6 */
02742ec6
JS
2587 }
2588 } else
2589 PF_POOLMASK(naddr,
2590 &r->src.addr.v.a.addr,
2591 &r->src.addr.v.a.mask, daddr,
2592 pd->af);
2593 break;
2594 }
2595 break;
2596 case PF_RDR: {
70224baa 2597 if (pf_map_addr(pd->af, r, saddr, naddr, NULL, sn))
02742ec6 2598 return (NULL);
70224baa
JL
2599 if ((r->rpool.opts & PF_POOL_TYPEMASK) ==
2600 PF_POOL_BITMASK)
2601 PF_POOLMASK(naddr, naddr,
2602 &r->rpool.cur->addr.v.a.mask, daddr,
2603 pd->af);
315a7da3 2604
02742ec6
JS
2605 if (r->rpool.proxy_port[1]) {
2606 u_int32_t tmp_nport;
2607
2608 tmp_nport = ((ntohs(dport) -
2609 ntohs(r->dst.port[0])) %
2610 (r->rpool.proxy_port[1] -
2611 r->rpool.proxy_port[0] + 1)) +
2612 r->rpool.proxy_port[0];
2613
2614 /* wrap around if necessary */
2615 if (tmp_nport > 65535)
2616 tmp_nport -= 65535;
2617 *nport = htons((u_int16_t)tmp_nport);
2618 } else if (r->rpool.proxy_port[0])
2619 *nport = htons(r->rpool.proxy_port[0]);
2620 break;
2621 }
2622 default:
2623 return (NULL);
2624 }
2625 }
2626
2627 return (r);
2628}
2629
2630#ifdef SMP
2631struct netmsg_hashlookup {
002c1265 2632 struct netmsg_base base;
02742ec6
JS
2633 struct inpcb **nm_pinp;
2634 struct inpcbinfo *nm_pcbinfo;
2635 struct pf_addr *nm_saddr;
2636 struct pf_addr *nm_daddr;
2637 uint16_t nm_sport;
2638 uint16_t nm_dport;
2639 sa_family_t nm_af;
2640};
2641
4599cf19 2642static void
002c1265 2643in_pcblookup_hash_handler(netmsg_t msg)
02742ec6 2644{
002c1265 2645 struct netmsg_hashlookup *rmsg = (struct netmsg_hashlookup *)msg;
02742ec6 2646
002c1265
MD
2647 if (rmsg->nm_af == AF_INET)
2648 *rmsg->nm_pinp = in_pcblookup_hash(rmsg->nm_pcbinfo,
2649 rmsg->nm_saddr->v4, rmsg->nm_sport, rmsg->nm_daddr->v4,
2650 rmsg->nm_dport, INPLOOKUP_WILDCARD, NULL);
02742ec6
JS
2651#ifdef INET6
2652 else
002c1265
MD
2653 *rmsg->nm_pinp = in6_pcblookup_hash(rmsg->nm_pcbinfo,
2654 &rmsg->nm_saddr->v6, rmsg->nm_sport, &rmsg->nm_daddr->v6,
2655 rmsg->nm_dport, INPLOOKUP_WILDCARD, NULL);
02742ec6 2656#endif /* INET6 */
002c1265 2657 lwkt_replymsg(&rmsg->base.lmsg, 0);
02742ec6
JS
2658}
2659#endif /* SMP */
2660
2661int
315a7da3 2662pf_socket_lookup(int direction, struct pf_pdesc *pd)
02742ec6
JS
2663{
2664 struct pf_addr *saddr, *daddr;
2665 u_int16_t sport, dport;
2666 struct inpcbinfo *pi;
2667 struct inpcb *inp;
2668#ifdef SMP
2669 struct netmsg_hashlookup *msg = NULL;
2670#endif
2671 int pi_cpu = 0;
2672
70224baa
JL
2673 if (pd == NULL)
2674 return (-1);
2675 pd->lookup.uid = UID_MAX;
2676 pd->lookup.gid = GID_MAX;
2677 pd->lookup.pid = NO_PID;
02742ec6
JS
2678 if (direction == PF_IN) {
2679 saddr = pd->src;
2680 daddr = pd->dst;
2681 } else {
2682 saddr = pd->dst;
2683 daddr = pd->src;
2684 }
2685 switch (pd->proto) {
2686 case IPPROTO_TCP:
315a7da3
JL
2687 if (pd->hdr.tcp == NULL)
2688 return (-1);
02742ec6
JS
2689 sport = pd->hdr.tcp->th_sport;
2690 dport = pd->hdr.tcp->th_dport;
2691
2692 pi_cpu = tcp_addrcpu(saddr->v4.s_addr, sport, daddr->v4.s_addr, dport);
2693 pi = &tcbinfo[pi_cpu];
2694#ifdef SMP
2695 /*
2696 * Our netstack runs lockless on MP systems
2697 * (only for TCP connections at the moment).
2698 *
2699 * As we are not allowed to read another CPU's tcbinfo,
2700 * we have to ask that CPU via remote call to search the
2701 * table for us.
2702 *
2703 * Prepare a msg iff data belongs to another CPU.
2704 */
2705 if (pi_cpu != mycpu->gd_cpuid) {
efda3bd0 2706 msg = kmalloc(sizeof(*msg), M_LWKTMSG, M_INTWAIT);
002c1265 2707 netmsg_init(&msg->base, NULL, &netisr_afree_rport,
48e7b118 2708 0, in_pcblookup_hash_handler);
02742ec6
JS
2709 msg->nm_pinp = &inp;
2710 msg->nm_pcbinfo = pi;
2711 msg->nm_saddr = saddr;
2712 msg->nm_sport = sport;
2713 msg->nm_daddr = daddr;
2714 msg->nm_dport = dport;
2715 msg->nm_af = pd->af;
2716 }
2717#endif /* SMP */
2718 break;
2719 case IPPROTO_UDP:
315a7da3
JL
2720 if (pd->hdr.udp == NULL)
2721 return (-1);
02742ec6
JS
2722 sport = pd->hdr.udp->uh_sport;
2723 dport = pd->hdr.udp->uh_dport;
2724 pi = &udbinfo;
2725 break;
2726 default:
315a7da3 2727 return (-1);
02742ec6
JS
2728 }
2729 if (direction != PF_IN) {
2730 u_int16_t p;
2731
2732 p = sport;
2733 sport = dport;
2734 dport = p;
2735 }
2736 switch (pd->af) {
2737#ifdef INET6
2738 case AF_INET6:
2739#ifdef SMP
2740 /*
2741 * Query other CPU, second part
2742 *
2743 * msg only gets initialized when:
2744 * 1) packet is TCP
2745 * 2) the info belongs to another CPU
2746 *
2747 * Use some switch/case magic to avoid code duplication.
2748 */
2749 if (msg == NULL)
2750#endif /* SMP */
2751 {
2752 inp = in6_pcblookup_hash(pi, &saddr->v6, sport,
2753 &daddr->v6, dport, INPLOOKUP_WILDCARD, NULL);
2754
2755 if (inp == NULL)
70224baa 2756 return (-1);
02742ec6
JS
2757 break;
2758 }
2759 /* FALLTHROUGH if SMP and on other CPU */
2760#endif /* INET6 */
2761 case AF_INET:
2762#ifdef SMP
2763 if (msg != NULL) {
2a7a2b1c 2764 lwkt_domsg(cpu_portfn(pi_cpu),
002c1265 2765 &msg->base.lmsg, 0);
02742ec6
JS
2766 } else
2767#endif /* SMP */
2768 {
2769 inp = in_pcblookup_hash(pi, saddr->v4, sport, daddr->v4,
2770 dport, INPLOOKUP_WILDCARD, NULL);
2771 }
2772 if (inp == NULL)
315a7da3 2773 return (-1);
02742ec6
JS
2774 break;
2775
2776 default:
70224baa 2777 return (-1);
02742ec6 2778 }
70224baa
JL
2779 pd->lookup.uid = inp->inp_socket->so_cred->cr_uid;
2780 pd->lookup.gid = inp->inp_socket->so_cred->cr_groups[0];
02742ec6
JS
2781 return (1);
2782}
2783
2784u_int8_t
2785pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2786{
2787 int hlen;
2788 u_int8_t hdr[60];
2789 u_int8_t *opt, optlen;
2790 u_int8_t wscale = 0;
2791
2792 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
2793 if (hlen <= sizeof(struct tcphdr))
2794 return (0);
2795 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2796 return (0);
2797 opt = hdr + sizeof(struct tcphdr);
2798 hlen -= sizeof(struct tcphdr);
2799 while (hlen >= 3) {
2800 switch (*opt) {
2801 case TCPOPT_EOL:
2802 case TCPOPT_NOP:
2803 ++opt;
2804 --hlen;
2805 break;
2806 case TCPOPT_WINDOW:
2807 wscale = opt[2];
2808 if (wscale > TCP_MAX_WINSHIFT)
2809 wscale = TCP_MAX_WINSHIFT;
2810 wscale |= PF_WSCALE_FLAG;
2811 /* FALLTHROUGH */
2812 default:
2813 optlen = opt[1];
2814 if (optlen < 2)
2815 optlen = 2;
2816 hlen -= optlen;
2817 opt += optlen;
2818 break;
2819 }
2820 }
2821 return (wscale);
2822}
2823
2824u_int16_t
2825pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2826{
2827 int hlen;
2828 u_int8_t hdr[60];
2829 u_int8_t *opt, optlen;
2830 u_int16_t mss = tcp_mssdflt;
2831
2832 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
2833 if (hlen <= sizeof(struct tcphdr))
2834 return (0);
2835 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2836 return (0);
2837 opt = hdr + sizeof(struct tcphdr);
2838 hlen -= sizeof(struct tcphdr);
2839 while (hlen >= TCPOLEN_MAXSEG) {
2840 switch (*opt) {
2841 case TCPOPT_EOL:
2842 case TCPOPT_NOP:
2843 ++opt;
2844 --hlen;
2845 break;
2846 case TCPOPT_MAXSEG:
2847 bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
2848 /* FALLTHROUGH */
2849 default:
2850 optlen = opt[1];
2851 if (optlen < 2)
2852 optlen = 2;
2853 hlen -= optlen;
2854 opt += optlen;
2855 break;
2856 }
2857 }
2858 return (mss);
2859}
2860
2861u_int16_t
2862pf_calc_mss(struct pf_addr *addr, sa_family_t af, u_int16_t offer)
2863{
2864#ifdef INET
2865 struct sockaddr_in *dst;
2866 struct route ro;
2867#endif /* INET */
2868#ifdef INET6
2869 struct sockaddr_in6 *dst6;
2870 struct route_in6 ro6;
2871#endif /* INET6 */
2872 struct rtentry *rt = NULL;
2873 int hlen = 0;
2874 u_int16_t mss = tcp_mssdflt;
2875
2876 switch (af) {
2877#ifdef INET
2878 case AF_INET:
2879 hlen = sizeof(struct ip);
2880 bzero(&ro, sizeof(ro));
2881 dst = (struct sockaddr_in *)&ro.ro_dst;
2882 dst->sin_family = AF_INET;
2883 dst->sin_len = sizeof(*dst);
2884 dst->sin_addr = addr->v4;
2885 rtalloc_ign(&ro, (RTF_CLONING | RTF_PRCLONING));
2886 rt = ro.ro_rt;
2887 break;
2888#endif /* INET */
2889#ifdef INET6
2890 case AF_INET6:
2891 hlen = sizeof(struct ip6_hdr);
2892 bzero(&ro6, sizeof(ro6));
2893 dst6 = (struct sockaddr_in6 *)&ro6.ro_dst;
2894 dst6->sin6_family = AF_INET6;
2895 dst6->sin6_len = sizeof(*dst6);
2896 dst6->sin6_addr = addr->v6;
2897 rtalloc_ign((struct route *)&ro6, (RTF_CLONING | RTF_PRCLONING));
2898 rt = ro6.ro_rt;
2899 break;
2900#endif /* INET6 */
2901 }
2902
2903 if (rt && rt->rt_ifp) {
2904 mss = rt->rt_ifp->if_mtu - hlen - sizeof(struct tcphdr);
2905 mss = max(tcp_mssdflt, mss);
2906 RTFREE(rt);
2907 }
2908 mss = min(mss, offer);
2909 mss = max(mss, 64); /* sanity - at least max opt space */
2910 return (mss);
2911}
2912
2913void
2914pf_set_rt_ifp(struct pf_state *s, struct pf_addr *saddr)
2915{
2916 struct pf_rule *r = s->rule.ptr;
2917
2918 s->rt_kif = NULL;
2919 if (!r->rt || r->rt == PF_FASTROUTE)
2920 return;
315a7da3 2921 switch (s->state_key->af) {
02742ec6
JS
2922#ifdef INET
2923 case AF_INET:
2924 pf_map_addr(AF_INET, r, saddr, &s->rt_addr, NULL,
2925 &s->nat_src_node);
2926 s->rt_kif = r->rpool.cur->kif;
2927 break;
2928#endif /* INET */
2929#ifdef INET6
2930 case AF_INET6:
2931 pf_map_addr(AF_INET6, r, saddr, &s->rt_addr, NULL,
2932 &s->nat_src_node);
2933 s->rt_kif = r->rpool.cur->kif;
2934 break;
2935#endif /* INET6 */
2936 }
2937}
2938
315a7da3
JL
2939void
2940pf_attach_state(struct pf_state_key *sk, struct pf_state *s, int tail)
2941{
2942 s->state_key = sk;
2943 sk->refcnt++;
2944
2945 /* list is sorted, if-bound states before floating */
2946 if (tail)
2947 TAILQ_INSERT_TAIL(&sk->states, s, next);
2948 else
2949 TAILQ_INSERT_HEAD(&sk->states, s, next);
2950}
2951
2952void
2953pf_detach_state(struct pf_state *s, int flags)
2954{
2955 struct pf_state_key *sk = s->state_key;
2956
2957 if (sk == NULL)
2958 return;
2959
2960 s->state_key = NULL;
2961 TAILQ_REMOVE(&sk->states, s, next);
2962 if (--sk->refcnt == 0) {
2963 if (!(flags & PF_DT_SKIP_EXTGWY))
2964 RB_REMOVE(pf_state_tree_ext_gwy,
2965 &pf_statetbl_ext_gwy, sk);
2966 if (!(flags & PF_DT_SKIP_LANEXT))
2967 RB_REMOVE(pf_state_tree_lan_ext,
2968 &pf_statetbl_lan_ext, sk);
2969 pool_put(&pf_state_key_pl, sk);
2970 }
2971}
2972
2973struct pf_state_key *
2974pf_alloc_state_key(struct pf_state *s)
2975{
2976 struct pf_state_key *sk;
2977
2978 if ((sk = pool_get(&pf_state_key_pl, PR_NOWAIT)) == NULL)
2979 return (NULL);
2980 bzero(sk, sizeof(*sk));
2981 TAILQ_INIT(&sk->states);
2982 pf_attach_state(sk, s, 0);
2983
2984 return (sk);
2985}
2986
02742ec6 2987int
315a7da3 2988pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
02742ec6 2989 struct pfi_kif *kif, struct mbuf *m, int off, void *h,
70224baa
JL
2990 struct pf_pdesc *pd, struct pf_rule **am, struct pf_ruleset **rsm,
2991 struct ifqueue *ifq, struct inpcb *inp)
02742ec6
JS
2992{
2993 struct pf_rule *nr = NULL;
2994 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
02742ec6
JS
2995 u_int16_t bport, nport = 0;
2996 sa_family_t af = pd->af;
02742ec6
JS
2997 struct pf_rule *r, *a = NULL;
2998 struct pf_ruleset *ruleset = NULL;
2999 struct pf_src_node *nsn = NULL;
315a7da3 3000 struct tcphdr *th = pd->hdr.tcp;
02742ec6 3001 u_short reason;
315a7da3 3002 int rewrite = 0, hdrlen = 0;
70224baa 3003 int tag = -1, rtableid = -1;
70224baa
JL
3004 int asd = 0;
3005 int match = 0;
315a7da3
JL
3006 int state_icmp = 0;
3007 u_int16_t mss = tcp_mssdflt;
3008 u_int16_t sport, dport;
3009 u_int8_t icmptype = 0, icmpcode = 0;
70224baa 3010
315a7da3 3011 if (direction == PF_IN && pf_check_congestion(ifq)) {
70224baa
JL
3012 REASON_SET(&reason, PFRES_CONGEST);
3013 return (PF_DROP);
3014 }
3015
3016 if (inp != NULL)
315a7da3
JL
3017 pd->lookup.done = pf_socket_lookup(direction, pd);
3018 else if (debug_pfugidhack) {
70224baa 3019 DPFPRINTF(PF_DEBUG_MISC, ("pf: unlocked lookup\n"));
315a7da3 3020 pd->lookup.done = pf_socket_lookup(direction, pd);
70224baa 3021 }
315a7da3
JL
3022
3023 sport = dport = hdrlen = 0;
3024
3025 switch (pd->proto) {
3026 case IPPROTO_TCP:
3027 sport = th->th_sport;
3028 dport = th->th_dport;
3029 hdrlen = sizeof(*th);
3030 break;
3031 case IPPROTO_UDP:
3032 sport = pd->hdr.udp->uh_sport;
3033 dport = pd->hdr.udp->uh_dport;
3034 hdrlen = sizeof(*pd->hdr.udp);
3035 break;
3036#ifdef INET
3037 case IPPROTO_ICMP:
3038 if (pd->af != AF_INET)
3039 break;
3040 sport = dport = pd->hdr.icmp->icmp_id;
3041 icmptype = pd->hdr.icmp->icmp_type;
3042 icmpcode = pd->hdr.icmp->icmp_code;
3043
3044 if (icmptype == ICMP_UNREACH ||
3045 icmptype == ICMP_SOURCEQUENCH ||
3046 icmptype == ICMP_REDIRECT ||
3047 icmptype == ICMP_TIMXCEED ||
3048 icmptype == ICMP_PARAMPROB)
3049 state_icmp++;
3050 break;
3051#endif /* INET */
3052#ifdef INET6
3053 case IPPROTO_ICMPV6:
3054 if (pd->af != AF_INET6)
3055 break;
3056 sport = dport = pd->hdr.icmp6->icmp6_id;
3057 hdrlen = sizeof(*pd->hdr.icmp6);
3058 icmptype = pd->hdr.icmp6->icmp6_type;
3059 icmpcode = pd->hdr.icmp6->icmp6_code;
3060
3061 if (icmptype == ICMP6_DST_UNREACH ||
3062 icmptype == ICMP6_PACKET_TOO_BIG ||
3063 icmptype == ICMP6_TIME_EXCEEDED ||
3064 icmptype == ICMP6_PARAM_PROB)
3065 state_icmp++;
3066 break;
3067#endif /* INET6 */
3068 }
02742ec6
JS
3069
3070 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3071
3072 if (direction == PF_OUT) {
315a7da3 3073 bport = nport = sport;
02742ec6
JS
3074 /* check outgoing packet for BINAT/NAT */
3075 if ((nr = pf_get_translation(pd, m, off, PF_OUT, kif, &nsn,
315a7da3 3076 saddr, sport, daddr, dport, &pd->naddr, &nport)) != NULL) {
02742ec6 3077 PF_ACPY(&pd->baddr, saddr, af);
315a7da3
JL
3078 switch (pd->proto) {
3079 case IPPROTO_TCP:
3080 pf_change_ap(saddr, &th->th_sport, pd->ip_sum,
3081 &th->th_sum, &pd->naddr, nport, 0, af);
3082 sport = th->th_sport;
3083 rewrite++;
3084 break;
3085 case IPPROTO_UDP:
3086 pf_change_ap(saddr, &pd->hdr.udp->uh_sport,
3087 pd->ip_sum, &pd->hdr.udp->uh_sum,
3088 &pd->naddr, nport, 1, af);
3089 sport = pd->hdr.udp->uh_sport;
3090 rewrite++;
3091 break;
3092#ifdef INET
3093 case IPPROTO_ICMP:
3094 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3095 pd->naddr.v4.s_addr, 0);
3096 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3097 pd->hdr.icmp->icmp_cksum, sport, nport, 0);
3098 pd->hdr.icmp->icmp_id = nport;
3099 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3100 break;
3101#endif /* INET */
3102#ifdef INET6
3103 case IPPROTO_ICMPV6:
3104 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3105 &pd->naddr, 0);
3106 rewrite++;
3107 break;
3108#endif /* INET */
3109 default:
3110 switch (af) {
3111#ifdef INET
3112 case AF_INET:
3113 pf_change_a(&saddr->v4.s_addr,
3114 pd->ip_sum, pd->naddr.v4.s_addr, 0);
3115 break;
3116#endif /* INET */
3117#ifdef INET6
3118 case AF_INET6:
3119 PF_ACPY(saddr, &pd->naddr, af);
3120 break;
3121#endif /* INET */
3122 }
3123 break;
3124 }
3125
02742ec6
JS
3126 if (nr->natpass)
3127 r = NULL;
3128 pd->nat_rule = nr;
3129 }
3130 } else {
315a7da3 3131 bport = nport = dport;
02742ec6
JS
3132 /* check incoming packet for BINAT/RDR */
3133 if ((nr = pf_get_translation(pd, m, off, PF_IN, kif, &nsn,
315a7da3 3134 saddr, sport, daddr, dport, &pd->naddr, &nport)) != NULL) {
02742ec6 3135 PF_ACPY(&pd->baddr, daddr, af);
315a7da3
JL
3136 switch (pd->proto) {
3137 case IPPROTO_TCP:
3138 pf_change_ap(daddr, &th->th_dport, pd->ip_sum,
3139 &th->th_sum, &pd->naddr, nport, 0, af);
3140 dport = th->th_dport;
3141 rewrite++;
3142 break;
3143 case IPPROTO_UDP:
3144 pf_change_ap(daddr, &pd->hdr.udp->uh_dport,
3145 pd->ip_sum, &pd->hdr.udp->uh_sum,
3146 &pd->naddr, nport, 1, af);
3147 dport = pd->hdr.udp->uh_dport;
3148 rewrite++;
3149 break;
3150#ifdef INET
3151 case IPPROTO_ICMP:
3152 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3153 pd->naddr.v4.s_addr, 0);
3154 break;
3155#endif /* INET */
3156#ifdef INET6
3157 case IPPROTO_ICMPV6:
3158 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3159 &pd->naddr, 0);
3160 rewrite++;
3161 break;
3162#endif /* INET6 */
3163 default:
3164 switch (af) {
3165#ifdef INET
3166 case AF_INET:
3167 pf_change_a(&daddr->v4.s_addr,
3168 pd->ip_sum, pd->naddr.v4.s_addr, 0);
3169 break;
3170#endif /* INET */
3171#ifdef INET6
3172 case AF_INET6:
3173 PF_ACPY(daddr, &pd->naddr, af);
3174 break;
3175#endif /* INET */
3176 }
3177 break;
3178 }
3179
02742ec6
JS
3180 if (nr->natpass)
3181 r = NULL;
3182 pd->nat_rule = nr;
3183 }
3184 }
3185
3186 while (r != NULL) {
3187 r->evaluations++;
70224baa 3188 if (pfi_kif_match(r->kif, kif) == r->ifnot)
02742ec6
JS
3189 r = r->skip[PF_SKIP_IFP].ptr;
3190 else if (r->direction && r->direction != direction)
3191 r = r->skip[PF_SKIP_DIR].ptr;
3192 else if (r->af && r->af != af)
3193 r = r->skip[PF_SKIP_AF].ptr;
315a7da3 3194 else if (r->proto && r->proto != pd->proto)
02742ec6 3195 r = r->skip[PF_SKIP_PROTO].ptr;
70224baa
JL
3196 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3197 r->src.neg, kif))
02742ec6 3198 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
315a7da3 3199 /* tcp/udp only. port_op always 0 in other cases */
02742ec6 3200 else if (r->src.port_op && !pf_match_port(r->src.port_op,
315a7da3 3201 r->src.port[0], r->src.port[1], sport))
02742ec6 3202 r = r->skip[PF_SKIP_SRC_PORT].ptr;
70224baa
JL
3203 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3204 r->dst.neg, NULL))
02742ec6 3205 r = r->skip[PF_SKIP_DST_ADDR].ptr;
315a7da3 3206 /* tcp/udp only. port_op always 0 in other cases */
02742ec6 3207 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
315a7da3 3208 r->dst.port[0], r->dst.port[1], dport))
02742ec6 3209 r = r->skip[PF_SKIP_DST_PORT].ptr;
315a7da3
JL
3210 /* icmp only. type always 0 in other cases */
3211 else if (r->type && r->type != icmptype + 1)
3212 r = TAILQ_NEXT(r, entries);
3213 /* icmp only. type always 0 in other cases */
3214 else if (r->code && r->code != icmpcode + 1)
3215 r = TAILQ_NEXT(r, entries);
70224baa 3216 else if (r->tos && !(r->tos == pd->tos))
02742ec6
JS
3217 r = TAILQ_NEXT(r, entries);
3218 else if (r->rule_flag & PFRULE_FRAGMENT)
3219 r = TAILQ_NEXT(r, entries);
315a7da3
JL
3220 else if (pd->proto == IPPROTO_TCP &&
3221 (r->flagset & th->th_flags) != r->flags)
02742ec6 3222 r = TAILQ_NEXT(r, entries);
315a7da3 3223 /* tcp/udp only. uid.op always 0 in other cases */
70224baa 3224 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
315a7da3 3225 pf_socket_lookup(direction, pd), 1)) &&
02742ec6 3226 !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
70224baa 3227 pd->lookup.uid))
02742ec6 3228 r = TAILQ_NEXT(r, entries);
315a7da3 3229 /* tcp/udp only. gid.op always 0 in other cases */
70224baa 3230 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
315a7da3 3231 pf_socket_lookup(direction, pd), 1)) &&
02742ec6 3232 !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
70224baa 3233 pd->lookup.gid))
02742ec6 3234 r = TAILQ_NEXT(r, entries);
75fda04a
MD
3235 else if (r->prob && r->prob <= karc4random())
3236 r = TAILQ_NEXT(r, entries);
315a7da3 3237 else if (r->match_tag && !pf_match_tag(m, r, &tag))
02742ec6 3238 r = TAILQ_NEXT(r, entries);
315a7da3
JL
3239 else if (r->os_fingerprint != PF_OSFP_ANY &&
3240 (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3241 pf_osfp_fingerprint(pd, m, off, th),
3242 r->os_fingerprint)))
02742ec6
JS
3243 r = TAILQ_NEXT(r, entries);
3244 else {
3245 if (r->tag)
3246 tag = r->tag;
70224baa
JL
3247 if (r->rtableid >= 0)
3248 rtableid = r->rtableid;
02742ec6 3249 if (r->anchor == NULL) {
70224baa 3250 match = 1;
02742ec6
JS
3251 *rm = r;
3252 *am = a;
3253 *rsm = ruleset;
3254 if ((*rm)->quick)
3255 break;
3256 r = TAILQ_NEXT(r, entries);
3257 } else
70224baa
JL
3258 pf_step_into_anchor(&asd, &ruleset,
3259 PF_RULESET_FILTER, &r, &a, &match);
02742ec6 3260 }
70224baa
JL
3261 if (r == NULL && pf_step_out_of_anchor(&asd, &ruleset,
3262 PF_RULESET_FILTER, &r, &a, &match))
3263 break;
02742ec6
JS
3264 }
3265 r = *rm;
3266 a = *am;
3267 ruleset = *rsm;
3268
3269 REASON_SET(&reason, PFRES_MATCH);
3270
315a7da3 3271 if (r->log || (nr != NULL && nr->log)) {
02742ec6 3272 if (rewrite)
315a7da3 3273 m_copyback(m, off, hdrlen, pd->hdr.any);
70224baa
JL
3274 PFLOG_PACKET(kif, h, m, af, direction, reason, r->log ? r : nr,
3275 a, ruleset, pd);
02742ec6
JS
3276 }
3277
3278 if ((r->action == PF_DROP) &&
3279 ((r->rule_flag & PFRULE_RETURNRST) ||
3280 (r->rule_flag & PFRULE_RETURNICMP) ||
3281 (r->rule_flag & PFRULE_RETURN))) {
3282 /* undo NAT changes, if they have taken place */
3283 if (nr != NULL) {
3284 if (direction == PF_OUT) {
315a7da3
JL
3285 switch (pd->proto) {
3286 case IPPROTO_TCP:
3287 pf_change_ap(saddr, &th->th_sport,
3288 pd->ip_sum, &th->th_sum,
3289 &pd->baddr, bport, 0, af);
3290 sport = th->th_sport;
3291 rewrite++;
3292 break;
3293 case IPPROTO_UDP:
3294 pf_change_ap(saddr,
3295 &pd->hdr.udp->uh_sport, pd->ip_sum,
3296 &pd->hdr.udp->uh_sum, &pd->baddr,
3297 bport, 1, af);
3298 sport = pd->hdr.udp->uh_sport;
3299 rewrite++;
3300 break;
3301 case IPPROTO_ICMP:
3302#ifdef INET6
3303 case IPPROTO_ICMPV6:
3304#endif
3305 /* nothing! */
3306 break;
3307 default:
3308 switch (af) {
3309 case AF_INET:
3310 pf_change_a(&saddr->v4.s_addr,
3311 pd->ip_sum,
3312 pd->baddr.v4.s_addr, 0);
3313 break;
3314 case AF_INET6:
3315 PF_ACPY(saddr, &pd->baddr, af);
3316 break;
3317 }
3318 }
02742ec6 3319 } else {
315a7da3
JL
3320 switch (pd->proto) {
3321 case IPPROTO_TCP:
3322 pf_change_ap(daddr, &th->th_dport,
3323 pd->ip_sum, &th->th_sum,
3324 &pd->baddr, bport, 0, af);
3325 dport = th->th_dport;
3326 rewrite++;
3327 break;
3328 case IPPROTO_UDP:
3329 pf_change_ap(daddr,
3330 &pd->hdr.udp->uh_dport, pd->ip_sum,
3331 &pd->hdr.udp->uh_sum, &pd->baddr,
3332 bport, 1, af);
3333 dport = pd->hdr.udp->uh_dport;
3334 rewrite++;
3335 break;
3336 case IPPROTO_ICMP:
3337#ifdef INET6
3338 case IPPROTO_ICMPV6:
3339#endif
3340 /* nothing! */
3341 break;
3342 default:
3343 switch (af) {
3344 case AF_INET:
3345 pf_change_a(&daddr->v4.s_addr,
3346 pd->ip_sum,
3347 pd->baddr.v4.s_addr, 0);
3348 break;
3349 case AF_INET6:
3350 PF_ACPY(daddr, &pd->baddr, af);
3351 break;
3352 }
3353 }
02742ec6
JS
3354 }
3355 }
315a7da3
JL
3356 if (pd->proto == IPPROTO_TCP &&
3357 ((r->rule_flag & PFRULE_RETURNRST) ||
02742ec6
JS
3358 (r->rule_flag & PFRULE_RETURN)) &&
3359 !(th->th_flags & TH_RST)) {
315a7da3
JL
3360 u_int32_t ack = ntohl(th->th_seq) + pd->p_len;
3361 struct ip *h = mtod(m, struct ip *);
02742ec6 3362
315a7da3
JL
3363 if (pf_check_proto_cksum(m, off,
3364 h->ip_len - off, IPPROTO_TCP, AF_INET))
3365 REASON_SET(&reason, PFRES_PROTCKSUM);
3366 else {
3367 if (th->th_flags & TH_SYN)
3368 ack++;
3369 if (th->th_flags & TH_FIN)
3370 ack++;
3371 pf_send_tcp(r, af, pd->dst,
3372 pd->src, th->th_dport, th->th_sport,
3373 ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
3374 r->return_ttl, 1, 0, pd->eh, kif->pfik_ifp);
3375 }
02742ec6
JS
3376 } else if ((af == AF_INET) && r->return_icmp)
3377 pf_send_icmp(m, r->return_icmp >> 8,
3378 r->return_icmp & 255, af, r);
3379 else if ((af == AF_INET6) && r->return_icmp6)
3380 pf_send_icmp(m, r->return_icmp6 >> 8,
3381 r->return_icmp6 & 255, af, r);
3382 }
3383
315a7da3 3384 if (r->action == PF_DROP)
02742ec6
JS
3385 return (PF_DROP);
3386
315a7da3 3387 if (pf_tag_packet(m, tag, rtableid)) {
70224baa
JL
3388 REASON_SET(&reason, PFRES_MEMORY);
3389 return (PF_DROP);
3390 }
02742ec6 3391
315a7da3
JL
3392 if (!state_icmp && (r->keep_state || nr != NULL ||
3393 (pd->flags & PFDESC_TCP_NORM))) {
02742ec6 3394 /* create new state */
315a7da3 3395 u_int16_t len = 0;
02742ec6 3396 struct pf_state *s = NULL;
315a7da3 3397 struct pf_state_key *sk = NULL;
02742ec6
JS
3398 struct pf_src_node *sn = NULL;
3399
02742ec6 3400 /* check maximums */
70224baa
JL
3401 if (r->max_states && (r->states >= r->max_states)) {
3402 pf_status.lcounters[LCNT_STATES]++;
3403 REASON_SET(&reason, PFRES_MAXSTATES);
02742ec6 3404 goto cleanup;
70224baa
JL
3405 }
3406 /* src node for filter rule */
02742ec6
JS
3407 if ((r->rule_flag & PFRULE_SRCTRACK ||
3408 r->rpool.opts & PF_POOL_STICKYADDR) &&
70224baa
JL
3409 pf_insert_src_node(&sn, r, saddr, af) != 0) {
3410 REASON_SET(&reason, PFRES_SRCLIMIT);
02742ec6 3411 goto cleanup;
70224baa 3412 }
02742ec6
JS
3413 /* src node for translation rule */
3414 if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3415 ((direction == PF_OUT &&
3416 pf_insert_src_node(&nsn, nr, &pd->baddr, af) != 0) ||
70224baa
JL
3417 (pf_insert_src_node(&nsn, nr, saddr, af) != 0))) {
3418 REASON_SET(&reason, PFRES_SRCLIMIT);
02742ec6 3419 goto cleanup;
70224baa 3420 }
02742ec6
JS
3421 s = pool_get(&pf_state_pl, PR_NOWAIT);
3422 if (s == NULL) {
70224baa 3423 REASON_SET(&reason, PFRES_MEMORY);
02742ec6
JS
3424cleanup:
3425 if (sn != NULL && sn->states == 0 && sn->expire == 0) {
3426 RB_REMOVE(pf_src_tree, &tree_src_tracking, sn);
3427 pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
3428 pf_status.src_nodes--;
3429 pool_put(&pf_src_tree_pl, sn);
3430 }
3431 if (nsn != sn && nsn != NULL && nsn->states == 0 &&
3432 nsn->expire == 0) {
3433 RB_REMOVE(pf_src_tree, &tree_src_tracking, nsn);
3434 pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
3435 pf_status.src_nodes--;
3436 pool_put(&pf_src_tree_pl, nsn);
3437 }
315a7da3
JL
3438 if (sk != NULL) {
3439 pool_put(&pf_state_key_pl, sk);
3440 }
02742ec6
JS
3441 return (PF_DROP);
3442 }
3443 bzero(s, sizeof(*s));
02742ec6
JS
3444 s->rule.ptr = r;
3445 s->nat_rule.ptr = nr;
02742ec6 3446 s->anchor.ptr = a;
70224baa 3447 STATE_INC_COUNTERS(s);
02742ec6 3448 s->allow_opts = r->allow_opts;
70224baa
JL
3449 s->log = r->log & PF_LOG_ALL;
3450 if (nr != NULL)
3451 s->log |= nr->log & PF_LOG_ALL;
315a7da3
JL
3452 switch (pd->proto) {
3453 case IPPROTO_TCP:
3454 len = pd->tot_len - off - (th->th_off << 2);
3455 s->src.seqlo = ntohl(th->th_seq);
3456 s->src.seqhi = s->src.seqlo + len + 1;
3457 if ((th->th_flags & (TH_SYN|TH_ACK)) ==
3458 TH_SYN && r->keep_state == PF_STATE_MODULATE) {
3459 /* Generate sequence number modulator */
3460 while ((s->src.seqdiff =
3461 pf_new_isn(sk) - s->src.seqlo) == 0)
3462 ;
3463 pf_change_a(&th->th_seq, &th->th_sum,
3464 htonl(s->src.seqlo + s->src.seqdiff), 0);
3465 rewrite = 1;
3466 } else
3467 s->src.seqdiff = 0;
3468 if (th->th_flags & TH_SYN) {
3469 s->src.seqhi++;
3470 s->src.wscale = pf_get_wscale(m, off,
3471 th->th_off, af);
02742ec6 3472 }
315a7da3
JL
3473 s->src.max_win = MAX(ntohs(th->th_win), 1);
3474 if (s->src.wscale & PF_WSCALE_MASK) {
3475 /* Remove scale factor from initial window */
3476 int win = s->src.max_win;
3477 win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3478 s->src.max_win = (win - 1) >>
3479 (s->src.wscale & PF_WSCALE_MASK);
02742ec6 3480 }
315a7da3
JL
3481 if (th->th_flags & TH_FIN)
3482 s->src.seqhi++;
3483 s->dst.seqhi = 1;
3484 s->dst.max_win = 1;
3485 s->src.state = TCPS_SYN_SENT;
3486 s->dst.state = TCPS_CLOSED;
3487 s->timeout = PFTM_TCP_FIRST_PACKET;
70224baa 3488 break;
315a7da3
JL
3489 case IPPROTO_UDP:
3490 s->src.state = PFUDPS_SINGLE;
3491 s->dst.state = PFUDPS_NO_TRAFFIC;
3492 s->timeout = PFTM_UDP_FIRST_PACKET;
3493 break;
3494 case IPPROTO_ICMP:
02742ec6 3495#ifdef INET6
315a7da3
JL
3496 case IPPROTO_ICMPV6:
3497#endif
3498 s->timeout = PFTM_ICMP_FIRST_PACKET;
3499 break;
3500 default:
3501 s->src.state = PFOTHERS_SINGLE;
3502 s->dst.state = PFOTHERS_NO_TRAFFIC;
3503 s->timeout = PFTM_OTHER_FIRST_PACKET;
02742ec6 3504 }
02742ec6 3505
02742ec6
JS
3506 s->creation = time_second;
3507 s->expire = time_second;
315a7da3 3508
02742ec6
JS
3509 if (sn != NULL) {
3510 s->src_node = sn;
3511 s->src_node->states++;
3512 }
3513 if (nsn != NULL) {
3514 PF_ACPY(&nsn->raddr, &pd->naddr, af);
3515 s->nat_src_node = nsn;
3516 s->nat_src_node->states++;
3517 }
315a7da3
JL
3518 if (pd->proto == IPPROTO_TCP) {
3519 if ((pd->flags & PFDESC_TCP_NORM) &&
3520 pf_normalize_tcp_init(m, off, pd, th, &s->src,
3521 &s->dst)) {
3522 REASON_SET(&reason, PFRES_MEMORY);
3523 pf_src_tree_remove_state(s);
3524 STATE_DEC_COUNTERS(s);
3525 pool_put(&pf_state_pl, s);
3526 return (PF_DROP);
3527 }
3528 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3529 pf_normalize_tcp_stateful(m, off, pd, &reason,
3530 th, s, &s->src, &s->dst, &rewrite)) {
3531 /* This really shouldn't happen!!! */
3532 DPFPRINTF(PF_DEBUG_URGENT,
3533 ("pf_normalize_tcp_stateful failed on "
3534 "first pkt"));
3535 pf_normalize_tcp_cleanup(s);
3536 pf_src_tree_remove_state(s);
3537 STATE_DEC_COUNTERS(s);
3538 pool_put(&pf_state_pl, s);
3539 return (PF_DROP);
3540 }
3541 }
3542
3543 if ((sk = pf_alloc_state_key(s)) == NULL) {
3544 REASON_SET(&reason, PFRES_MEMORY);
3545 goto cleanup;
3546 }
3547
3548 sk->proto = pd->proto;
3549 sk->direction = direction;
3550 sk->af = af;
3551 if (direction == PF_OUT) {
3552 PF_ACPY(&sk->gwy.addr, saddr, af);
3553 PF_ACPY(&sk->ext.addr, daddr, af);
3554 switch (pd->proto) {
3555 case IPPROTO_ICMP:
3556#ifdef INET6
3557 case IPPROTO_ICMPV6:
3558#endif
3559 sk->gwy.port = nport;
3560 sk->ext.port = 0;
3561 break;
3562 default:
3563 sk->gwy.port = sport;
3564 sk->ext.port = dport;
3565 }
3566 if (nr != NULL) {
3567 PF_ACPY(&sk->lan.addr, &pd->baddr, af);
3568 sk->lan.port = bport;
3569 } else {
3570 PF_ACPY(&sk->lan.addr, &sk->gwy.addr, af);
3571 sk->lan.port = sk->gwy.port;
3572 }
3573 } else {
3574 PF_ACPY(&sk->lan.addr, daddr, af);
3575 PF_ACPY(&sk->ext.addr, saddr, af);
3576 switch (pd->proto) {
3577 case IPPROTO_ICMP:
3578#ifdef INET6
3579 case IPPROTO_ICMPV6:
3580#endif
3581 sk->lan.port = nport;
3582 sk->ext.port = 0;
3583 break;
3584 default:
3585 sk->lan.port = dport;
3586 sk->ext.port = sport;
3587 }
3588 if (nr != NULL) {
3589 PF_ACPY(&sk->gwy.addr, &pd->baddr, af);
3590 sk->gwy.port = bport;
3591 } else {
3592 PF_ACPY(&sk->gwy.addr, &sk->lan.addr, af);
3593 sk->gwy.port = sk->lan.port;
3594 }
3595 }
3596
3597 s->hash = pf_state_hash(sk);
3598 s->pickup_mode = r->pickup_mode;
3599
3600 pf_set_rt_ifp(s, saddr); /* needs s->state_key set */
3601
02742ec6 3602 if (pf_insert_state(BOUND_IFACE(r, kif), s)) {
315a7da3
JL
3603 if (pd->proto == IPPROTO_TCP)
3604 pf_normalize_tcp_cleanup(s);
70224baa 3605 REASON_SET(&reason, PFRES_STATEINS);
02742ec6 3606 pf_src_tree_remove_state(s);
70224baa 3607 STATE_DEC_COUNTERS(s);
02742ec6
JS
3608 pool_put(&pf_state_pl, s);
3609 return (PF_DROP);
3610 } else
3611 *sm = s;
70224baa
JL
3612 if (tag > 0) {
3613 pf_tag_ref(tag);
3614 s->tag = tag;
3615 }
315a7da3
JL
3616 if (pd->proto == IPPROTO_TCP &&
3617 (th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3618 r->keep_state == PF_STATE_SYNPROXY) {
3619 s->src.state = PF_TCPS_PROXY_SRC;
3620 if (nr != NULL) {
3621 if (direction == PF_OUT) {
3622 pf_change_ap(saddr, &th->th_sport,
3623 pd->ip_sum, &th->th_sum, &pd->baddr,
3624 bport, 0, af);
3625 sport = th->th_sport;
3626 } else {
3627 pf_change_ap(daddr, &th->th_dport,
3628 pd->ip_sum, &th->th_sum, &pd->baddr,
3629 bport, 0, af);
3630 sport = th->th_dport;
3631 }
3632 }
4fc5aa1c 3633 s->src.seqhi = htonl(karc4random());
315a7da3
JL
3634 /* Find mss option */
3635 mss = pf_get_mss(m, off, th->th_off, af);
3636 mss = pf_calc_mss(saddr, af, mss);
3637 mss = pf_calc_mss(daddr, af, mss);
3638 s->src.mss = mss;
3639 pf_send_tcp(r, af, daddr, saddr, th->th_dport,
3640 th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3641 TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL, NULL);
3642 REASON_SET(&reason, PFRES_SYNPROXY);
3643 return (PF_SYNPROXY_DROP);
3644 }
02742ec6
JS
3645 }
3646
315a7da3
JL
3647 /* copy back packet headers if we performed NAT operations */
3648 if (rewrite)
3649 m_copyback(m, off, hdrlen, pd->hdr.any);
3650
02742ec6
JS
3651 return (PF_PASS);
3652}
3653
3654int
3655pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3656 struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3657 struct pf_ruleset **rsm)
3658{
3659 struct pf_rule *r, *a = NULL;
3660 struct pf_ruleset *ruleset = NULL;
3661 sa_family_t af = pd->af;
3662 u_short reason;
3663 int tag = -1;
70224baa
JL
3664 int asd = 0;
3665 int match = 0;
02742ec6
JS
3666
3667 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3668 while (r != NULL) {
3669 r->evaluations++;
70224baa 3670 if (pfi_kif_match(r->kif, kif) == r->ifnot)
02742ec6
JS
3671 r = r->skip[PF_SKIP_IFP].ptr;
3672 else if (r->direction && r->direction != direction)
3673 r = r->skip[PF_SKIP_DIR].ptr;
3674 else if (r->af && r->af != af)
3675 r = r->skip[PF_SKIP_AF].ptr;
3676 else if (r->proto && r->proto != pd->proto)
3677 r = r->skip[PF_SKIP_PROTO].ptr;
70224baa
JL
3678 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3679 r->src.neg, kif))
02742ec6 3680 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
70224baa
JL
3681 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3682 r->dst.neg, NULL))
02742ec6 3683 r = r->skip[PF_SKIP_DST_ADDR].ptr;
70224baa 3684 else if (r->tos && !(r->tos == pd->tos))
02742ec6 3685 r = TAILQ_NEXT(r, entries);
a814431a
MD
3686 else if (r->os_fingerprint != PF_OSFP_ANY)
3687 r = TAILQ_NEXT(r, entries);
3688 else if (pd->proto == IPPROTO_UDP &&
3689 (r->src.port_op || r->dst.port_op))
3690 r = TAILQ_NEXT(r, entries);
3691 else if (pd->proto == IPPROTO_TCP &&
3692 (r->src.port_op || r->dst.port_op || r->flagset))
3693 r = TAILQ_NEXT(r, entries);
3694 else if ((pd->proto == IPPROTO_ICMP ||
3695 pd->proto == IPPROTO_ICMPV6) &&
3696 (r->type || r->code))
02742ec6 3697 r = TAILQ_NEXT(r, entries);
75fda04a
MD
3698 else if (r->prob && r->prob <= karc4random())
3699 r = TAILQ_NEXT(r, entries);
315a7da3 3700 else if (r->match_tag && !pf_match_tag(m, r, &tag))
02742ec6 3701 r = TAILQ_NEXT(r, entries);
02742ec6
JS
3702 else {
3703 if (r->anchor == NULL) {
70224baa 3704 match = 1;
02742ec6
JS
3705 *rm = r;
3706 *am = a;
3707 *rsm = ruleset;
3708 if ((*rm)->quick)
3709 break;
3710 r = TAILQ_NEXT(r, entries);
3711 } else
70224baa
JL
3712 pf_step_into_anchor(&asd, &ruleset,
3713 PF_RULESET_FILTER, &r, &a, &match);
02742ec6 3714 }
70224baa
JL
3715 if (r == NULL && pf_step_out_of_anchor(&asd, &ruleset,
3716 PF_RULESET_FILTER, &r, &a, &match))
3717 break;
02742ec6
JS
3718 }
3719 r = *rm;
3720 a = *am;
3721 ruleset = *rsm;
3722
3723 REASON_SET(&reason, PFRES_MATCH);
3724
3725 if (r->log)
70224baa
JL
3726 PFLOG_PACKET(kif, h, m, af, direction, reason, r, a, ruleset,
3727 pd);
02742ec6
JS
3728
3729 if (r->action != PF_PASS)
3730 return (PF_DROP);
3731
315a7da3 3732 if (pf_tag_packet(m, tag, -1)) {
70224baa
JL
3733 REASON_SET(&reason, PFRES_MEMORY);
3734 return (PF_DROP);
3735 }
02742ec6
JS
3736
3737 return (PF_PASS);
3738}
3739
3740int
3741pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
3742 struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
3743 u_short *reason)
3744{
315a7da3 3745 struct pf_state_key_cmp key;
02742ec6
JS
3746 struct tcphdr *th = pd->hdr.tcp;
3747 u_int16_t win = ntohs(th->th_win);
70224baa 3748 u_int32_t ack, end, seq, orig_seq;
02742ec6
JS
3749 u_int8_t sws, dws;
3750 int ackskew;
3751 int copyback = 0;
3752 struct pf_state_peer *src, *dst;
3753
3754 key.af = pd->af;
3755 key.proto = IPPROTO_TCP;
3756 if (direction == PF_IN) {
3757 PF_ACPY(&key.ext.addr, pd->src, key.af);
3758 PF_ACPY(&key.gwy.addr, pd->dst, key.af);
3759 key.ext.port = th->th_sport;
3760 key.gwy.port = th->th_dport;
3761 } else {
3762 PF_ACPY(&key.lan.addr, pd->src, key.af);
3763 PF_ACPY(&key.ext.addr, pd->dst, key.af);
3764 key.lan.port = th->th_sport;
3765 key.ext.port = th->th_dport;
3766 }
3767
3768 STATE_LOOKUP();
3769
315a7da3 3770 if (direction == (*state)->state_key->direction) {
02742ec6
JS
3771 src = &(*state)->src;
3772 dst = &(*state)->dst;
3773 } else {
3774 src = &(*state)->dst;
3775 dst = &(*state)->src;
3776 }
3777
3778 if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
315a7da3 3779 if (direction != (*state)->state_key->direction) {
70224baa 3780 REASON_SET(reason, PFRES_SYNPROXY);
02742ec6 3781 return (PF_SYNPROXY_DROP);
70224baa 3782 }
02742ec6 3783 if (th->th_flags & TH_SYN) {
70224baa
JL
3784 if (ntohl(th->th_seq) != (*state)->src.seqlo) {
3785 REASON_SET(reason, PFRES_SYNPROXY);
02742ec6 3786 return (PF_DROP);
70224baa 3787 }
02742ec6
JS
3788 pf_send_tcp((*state)->rule.ptr, pd->af, pd->dst,
3789 pd->src, th->th_dport, th->th_sport,
3790 (*state)->src.seqhi, ntohl(th->th_seq) + 1,
70224baa
JL
3791 TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1,
3792 0, NULL, NULL);
3793 REASON_SET(reason, PFRES_SYNPROXY);
02742ec6
JS
3794 return (PF_SYNPROXY_DROP);
3795 } else if (!(th->th_flags & TH_ACK) ||
3796 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
70224baa
JL
3797 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
3798 REASON_SET(reason, PFRES_SYNPROXY);
02742ec6 3799 return (PF_DROP);
70224baa
JL
3800 } else if ((*state)->src_node != NULL &&
3801 pf_src_connlimit(state)) {
3802 REASON_SET(reason, PFRES_SRCLIMIT);
3803 return (PF_DROP);
3804 } else
02742ec6
JS
3805 (*state)->src.state = PF_TCPS_PROXY_DST;
3806 }
3807 if ((*state)->src.state == PF_TCPS_PROXY_DST) {
3808 struct pf_state_host *src, *dst;
3809
3810 if (direction == PF_OUT) {
315a7da3
JL
3811 src = &(*state)->state_key->gwy;
3812 dst = &(*state)->state_key->ext;
02742ec6 3813 } else {
315a7da3
JL
3814 src = &(*state)->state_key->ext;
3815 dst = &(*state)->state_key->lan;
02742ec6 3816 }
315a7da3 3817 if (direction == (*state)->state_key->direction) {
02742ec6
JS
3818 if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
3819 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
70224baa
JL
3820 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
3821 REASON_SET(reason, PFRES_SYNPROXY);
02742ec6 3822 return (PF_DROP);
70224baa 3823 }
02742ec6
JS
3824 (*state)->src.max_win = MAX(ntohs(th->th_win), 1);
3825 if ((*state)->dst.seqhi == 1)
4fc5aa1c 3826 (*state)->dst.seqhi = htonl(karc4random());
02742ec6
JS
3827 pf_send_tcp((*state)->rule.ptr, pd->af, &src->addr,
3828 &dst->addr, src->port, dst->port,
3829 (*state)->dst.seqhi, 0, TH_SYN, 0,
70224baa
JL
3830 (*state)->src.mss, 0, 0, (*state)->tag, NULL, NULL);
3831 REASON_SET(reason, PFRES_SYNPROXY);
02742ec6
JS
3832 return (PF_SYNPROXY_DROP);
3833 } else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
3834 (TH_SYN|TH_ACK)) ||
70224baa
JL
3835 (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
3836 REASON_SET(reason, PFRES_SYNPROXY);
02742ec6 3837 return (PF_DROP);
70224baa 3838 } else {
02742ec6
JS
3839 (*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
3840 (*state)->dst.seqlo = ntohl(th->th_seq);
3841 pf_send_tcp((*state)->rule.ptr, pd->af, pd->dst,
3842 pd->src, th->th_dport, th->th_sport,
3843 ntohl(th->th_ack), ntohl(th->th_seq) + 1,
70224baa
JL
3844 TH_ACK, (*state)->src.max_win, 0, 0, 0,
3845 (*state)->tag, NULL, NULL);
02742ec6
JS
3846 pf_send_tcp((*state)->rule.ptr, pd->af, &src->addr,
3847 &dst->addr, src->port, dst->port,
3848 (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
70224baa
JL
3849 TH_ACK, (*state)->dst.max_win, 0, 0, 1,
3850 0, NULL, NULL);
02742ec6
JS
3851 (*state)->src.seqdiff = (*state)->dst.seqhi -
3852 (*state)->src.seqlo;
3853 (*state)->dst.seqdiff = (*state)->src.seqhi -
3854 (*state)->dst.seqlo;
3855 (*state)->src.seqhi = (*state)->src.seqlo +
02742ec6 3856 (*state)->dst.max_win;
9aa13ad5
MD
3857 (*state)->dst.seqhi = (*state)->dst.seqlo +
3858 (*state)->src.max_win;
02742ec6
JS
3859 (*state)->src.wscale = (*state)->dst.wscale = 0;
3860 (*state)->src.state = (*state)->dst.state =
3861 TCPS_ESTABLISHED;
70224baa 3862 REASON_SET(reason, PFRES_SYNPROXY);
02742ec6
JS
3863 return (PF_SYNPROXY_DROP);
3864 }
3865 }
3866
3867 if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3868 sws = src->wscale & PF_WSCALE_MASK;
3869 dws = dst->wscale & PF_WSCALE_MASK;
3870 } else
3871 sws = dws = 0;
3872
3873 /*
3874 * Sequence tracking algorithm from Guido van Rooij's paper:
3875 * http://www.madison-gurkha.com/publications/tcp_filtering/
3876 * tcp_filtering.ps
3877 */
3878
70224baa 3879 orig_seq = seq = ntohl(th->th_seq);
02742ec6 3880 if (src->seqlo == 0) {
70224baa
JL
3881 /* First packet from this end. Set its state */
3882
02742ec6
JS
3883 if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
3884 src->scrub == NULL) {
3885 if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
3886 REASON_SET(reason, PFRES_MEMORY);
3887 return (PF_DROP);
3888 }
3889 }
3890
3891 /* Deferred generation of sequence number modulator */
3892 if (dst->seqdiff && !src->seqdiff) {
315a7da3
JL
3893
3894 while ((src->seqdiff = pf_new_isn((struct pf_state_key *)&key) - seq) == 0)
02742ec6
JS
3895 ;
3896 ack = ntohl(th->th_ack) - dst->seqdiff;