Merge branch 'master' of ssh://crater.dragonflybsd.org/repository/git/dragonfly
[dragonfly.git] / sys / net / pf / pf.c
1 /*      $OpenBSD: pf.c,v 1.614 2008/08/02 12:34:37 henning Exp $ */
2
3 /*
4  * Copyright (c) 2004 The DragonFly Project.  All rights reserved.
5  *
6  * Copyright (c) 2001 Daniel Hartmeier
7  * Copyright (c) 2002 - 2008 Henning Brauer
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  *
14  *    - Redistributions of source code must retain the above copyright
15  *      notice, this list of conditions and the following disclaimer.
16  *    - Redistributions in binary form must reproduce the above
17  *      copyright notice, this list of conditions and the following
18  *      disclaimer in the documentation and/or other materials provided
19  *      with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
29  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGE.
33  *
34  * Effort sponsored in part by the Defense Advanced Research Projects
35  * Agency (DARPA) and Air Force Research Laboratory, Air Force
36  * Materiel Command, USAF, under agreement number F30602-01-2-0537.
37  *
38  */
39
40 #include "opt_inet.h"
41 #include "opt_inet6.h"
42
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/malloc.h>
46 #include <sys/mbuf.h>
47 #include <sys/filio.h>
48 #include <sys/socket.h>
49 #include <sys/socketvar.h>
50 #include <sys/kernel.h>
51 #include <sys/time.h>
52 #include <sys/sysctl.h>
53 #include <sys/endian.h>
54 #include <vm/vm_zone.h>
55 #include <sys/proc.h>
56 #include <sys/kthread.h>
57
58 #include <machine/inttypes.h>
59
60 #include <sys/md5.h>
61
62 #include <net/if.h>
63 #include <net/if_types.h>
64 #include <net/bpf.h>
65 #include <net/netisr.h>
66 #include <net/route.h>
67
68 #include <netinet/in.h>
69 #include <netinet/in_var.h>
70 #include <netinet/in_systm.h>
71 #include <netinet/ip.h>
72 #include <netinet/ip_var.h>
73 #include <netinet/tcp.h>
74 #include <netinet/tcp_seq.h>
75 #include <netinet/udp.h>
76 #include <netinet/ip_icmp.h>
77 #include <netinet/in_pcb.h>
78 #include <netinet/tcp_timer.h>
79 #include <netinet/tcp_var.h>
80 #include <netinet/udp_var.h>
81 #include <netinet/icmp_var.h>
82 #include <netinet/if_ether.h>
83
84 #include <net/pf/pfvar.h>
85 #include <net/pf/if_pflog.h>
86
87 #include <net/pf/if_pfsync.h>
88
89 #ifdef INET6
90 #include <netinet/ip6.h>
91 #include <netinet/in_pcb.h>
92 #include <netinet/icmp6.h>
93 #include <netinet6/nd6.h>
94 #include <netinet6/ip6_var.h>
95 #include <netinet6/in6_pcb.h>
96 #endif /* INET6 */
97
98 #include <sys/in_cksum.h>
99 #include <sys/ucred.h>
100 #include <machine/limits.h>
101 #include <sys/msgport2.h>
102 #include <net/netmsg2.h>
103
104 extern int ip_optcopy(struct ip *, struct ip *);
105 extern int debug_pfugidhack;
106
107 struct lwkt_token pf_token = LWKT_TOKEN_INITIALIZER(pf_token);
108
109 #define DPFPRINTF(n, x) if (pf_status.debug >= (n)) kprintf x
110
111 /*
112  * Global variables
113  */
114
115 /* mask radix tree */
116 struct radix_node_head  *pf_maskhead;
117
118 /* state tables */
119 struct pf_state_tree     pf_statetbl;
120
121 struct pf_altqqueue      pf_altqs[2];
122 struct pf_palist         pf_pabuf;
123 struct pf_altqqueue     *pf_altqs_active;
124 struct pf_altqqueue     *pf_altqs_inactive;
125 struct pf_status         pf_status;
126
127 u_int32_t                ticket_altqs_active;
128 u_int32_t                ticket_altqs_inactive;
129 int                      altqs_inactive_open;
130 u_int32_t                ticket_pabuf;
131
132 MD5_CTX                  pf_tcp_secret_ctx;
133 u_char                   pf_tcp_secret[16];
134 int                      pf_tcp_secret_init;
135 int                      pf_tcp_iss_off;
136
137 struct pf_anchor_stackframe {
138         struct pf_ruleset                       *rs;
139         struct pf_rule                          *r;
140         struct pf_anchor_node                   *parent;
141         struct pf_anchor                        *child;
142 } pf_anchor_stack[64];
143
144 vm_zone_t                pf_src_tree_pl, pf_rule_pl, pf_pooladdr_pl;
145 vm_zone_t                pf_state_pl, pf_state_key_pl, pf_state_item_pl;
146 vm_zone_t                pf_altq_pl;
147
148 void                     pf_print_host(struct pf_addr *, u_int16_t, u_int8_t);
149
150 void                     pf_init_threshold(struct pf_threshold *, u_int32_t,
151                             u_int32_t);
152 void                     pf_add_threshold(struct pf_threshold *);
153 int                      pf_check_threshold(struct pf_threshold *);
154
155 void                     pf_change_ap(struct pf_addr *, u_int16_t *,
156                             u_int16_t *, u_int16_t *, struct pf_addr *,
157                             u_int16_t, u_int8_t, sa_family_t);
158 int                      pf_modulate_sack(struct mbuf *, int, struct pf_pdesc *,
159                             struct tcphdr *, struct pf_state_peer *);
160 #ifdef INET6
161 void                     pf_change_a6(struct pf_addr *, u_int16_t *,
162                             struct pf_addr *, u_int8_t);
163 #endif /* INET6 */
164 void                     pf_change_icmp(struct pf_addr *, u_int16_t *,
165                             struct pf_addr *, struct pf_addr *, u_int16_t,
166                             u_int16_t *, u_int16_t *, u_int16_t *,
167                             u_int16_t *, u_int8_t, sa_family_t);
168 void                     pf_send_tcp(const struct pf_rule *, sa_family_t,
169                             const struct pf_addr *, const struct pf_addr *,
170                             u_int16_t, u_int16_t, u_int32_t, u_int32_t,
171                             u_int8_t, u_int16_t, u_int16_t, u_int8_t, int,
172                             u_int16_t, struct ether_header *, struct ifnet *);
173 void                     pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
174                             sa_family_t, struct pf_rule *);
175 struct pf_rule          *pf_match_translation(struct pf_pdesc *, struct mbuf *,
176                             int, int, struct pfi_kif *,
177                             struct pf_addr *, u_int16_t, struct pf_addr *,
178                             u_int16_t, int);
179 struct pf_rule          *pf_get_translation(struct pf_pdesc *, struct mbuf *,
180                             int, int, struct pfi_kif *, struct pf_src_node **,
181                             struct pf_state_key **, struct pf_state_key **,
182                             struct pf_state_key **, struct pf_state_key **,
183                             struct pf_addr *, struct pf_addr *,
184                             u_int16_t, u_int16_t);
185 void                     pf_detach_state(struct pf_state *);
186 int                      pf_state_key_setup(struct pf_pdesc *, struct pf_rule *,
187                             struct pf_state_key **, struct pf_state_key **,
188                             struct pf_state_key **, struct pf_state_key **,
189                             struct pf_addr *, struct pf_addr *,
190                             u_int16_t, u_int16_t);
191 void                     pf_state_key_detach(struct pf_state *, int);
192 u_int32_t                pf_tcp_iss(struct pf_pdesc *);
193 int                      pf_test_rule(struct pf_rule **, struct pf_state **,
194                             int, struct pfi_kif *, struct mbuf *, int,
195                             void *, struct pf_pdesc *, struct pf_rule **,
196                             struct pf_ruleset **, struct ifqueue *, struct inpcb *);
197 static __inline int      pf_create_state(struct pf_rule *, struct pf_rule *,
198                             struct pf_rule *, struct pf_pdesc *,
199                             struct pf_src_node *, struct pf_state_key *,
200                             struct pf_state_key *, struct pf_state_key *,
201                             struct pf_state_key *, struct mbuf *, int,
202                             u_int16_t, u_int16_t, int *, struct pfi_kif *,
203                             struct pf_state **, int, u_int16_t, u_int16_t,
204                             int);
205 int                      pf_test_fragment(struct pf_rule **, int,
206                             struct pfi_kif *, struct mbuf *, void *,
207                             struct pf_pdesc *, struct pf_rule **,
208                             struct pf_ruleset **);
209 int                      pf_tcp_track_full(struct pf_state_peer *,
210                             struct pf_state_peer *, struct pf_state **,
211                             struct pfi_kif *, struct mbuf *, int,
212                             struct pf_pdesc *, u_short *, int *);
213 int                     pf_tcp_track_sloppy(struct pf_state_peer *,
214                             struct pf_state_peer *, struct pf_state **,
215                             struct pf_pdesc *, u_short *);
216 int                      pf_test_state_tcp(struct pf_state **, int,
217                             struct pfi_kif *, struct mbuf *, int,
218                             void *, struct pf_pdesc *, u_short *);
219 int                      pf_test_state_udp(struct pf_state **, int,
220                             struct pfi_kif *, struct mbuf *, int,
221                             void *, struct pf_pdesc *);
222 int                      pf_test_state_icmp(struct pf_state **, int,
223                             struct pfi_kif *, struct mbuf *, int,
224                             void *, struct pf_pdesc *, u_short *);
225 int                      pf_test_state_other(struct pf_state **, int,
226                             struct pfi_kif *, struct mbuf *, struct pf_pdesc *);
227 void                     pf_step_into_anchor(int *, struct pf_ruleset **, int,
228                             struct pf_rule **, struct pf_rule **, int *);
229 int                      pf_step_out_of_anchor(int *, struct pf_ruleset **,
230                              int, struct pf_rule **, struct pf_rule **,
231                              int *);
232 void                     pf_hash(struct pf_addr *, struct pf_addr *,
233                             struct pf_poolhashkey *, sa_family_t);
234 int                      pf_map_addr(u_int8_t, struct pf_rule *,
235                             struct pf_addr *, struct pf_addr *,
236                             struct pf_addr *, struct pf_src_node **);
237 int                      pf_get_sport(sa_family_t, u_int8_t, struct pf_rule *,
238                             struct pf_addr *, struct pf_addr *, u_int16_t,
239                             struct pf_addr *, u_int16_t*, u_int16_t, u_int16_t,
240                             struct pf_src_node **);
241 void                     pf_route(struct mbuf **, struct pf_rule *, int,
242                             struct ifnet *, struct pf_state *,
243                             struct pf_pdesc *);
244 void                     pf_route6(struct mbuf **, struct pf_rule *, int,
245                             struct ifnet *, struct pf_state *,
246                             struct pf_pdesc *);
247 u_int8_t                 pf_get_wscale(struct mbuf *, int, u_int16_t,
248                             sa_family_t);
249 u_int16_t                pf_get_mss(struct mbuf *, int, u_int16_t,
250                             sa_family_t);
251 u_int16_t                pf_calc_mss(struct pf_addr *, sa_family_t,
252                                 u_int16_t);
253 void                     pf_set_rt_ifp(struct pf_state *,
254                             struct pf_addr *);
255 int                      pf_check_proto_cksum(struct mbuf *, int, int,
256                             u_int8_t, sa_family_t);
257 struct pf_divert        *pf_get_divert(struct mbuf *);
258 void                     pf_print_state_parts(struct pf_state *,
259                             struct pf_state_key *, struct pf_state_key *);
260 int                      pf_addr_wrap_neq(struct pf_addr_wrap *,
261                             struct pf_addr_wrap *);
262 struct pf_state         *pf_find_state(struct pfi_kif *,
263                             struct pf_state_key_cmp *, u_int, struct mbuf *);
264 int                      pf_src_connlimit(struct pf_state **);
265 int                      pf_check_congestion(struct ifqueue *);
266
267 extern int pf_end_threads;
268
269 struct pf_pool_limit pf_pool_limits[PF_LIMIT_MAX] = {
270         { &pf_state_pl, PFSTATE_HIWAT },
271         { &pf_src_tree_pl, PFSNODE_HIWAT },
272         { &pf_frent_pl, PFFRAG_FRENT_HIWAT },
273         { &pfr_ktable_pl, PFR_KTABLE_HIWAT },
274         { &pfr_kentry_pl, PFR_KENTRY_HIWAT }
275 };
276
277 #define STATE_LOOKUP(i, k, d, s, m)                                     \
278         do {                                                            \
279                 s = pf_find_state(i, k, d, m);                  \
280                 if (s == NULL || (s)->timeout == PFTM_PURGE)            \
281                         return (PF_DROP);                               \
282                 if (d == PF_OUT &&                                      \
283                     (((s)->rule.ptr->rt == PF_ROUTETO &&                \
284                     (s)->rule.ptr->direction == PF_OUT) ||              \
285                     ((s)->rule.ptr->rt == PF_REPLYTO &&                 \
286                     (s)->rule.ptr->direction == PF_IN)) &&              \
287                     (s)->rt_kif != NULL &&                              \
288                     (s)->rt_kif != i)                                   \
289                         return (PF_PASS);                               \
290         } while (0)
291
292 #define BOUND_IFACE(r, k) \
293         ((r)->rule_flag & PFRULE_IFBOUND) ? (k) : pfi_all
294
295 #define STATE_INC_COUNTERS(s)                           \
296         do {                                            \
297                 s->rule.ptr->states_cur++;              \
298                 s->rule.ptr->states_tot++;              \
299                 if (s->anchor.ptr != NULL) {            \
300                         s->anchor.ptr->states_cur++;    \
301                         s->anchor.ptr->states_tot++;    \
302                 }                                       \
303                 if (s->nat_rule.ptr != NULL) {          \
304                         s->nat_rule.ptr->states_cur++;  \
305                         s->nat_rule.ptr->states_tot++;  \
306                 }                                       \
307         } while (0)
308
309 #define STATE_DEC_COUNTERS(s)                           \
310         do {                                            \
311                 if (s->nat_rule.ptr != NULL)            \
312                         s->nat_rule.ptr->states_cur--;  \
313                 if (s->anchor.ptr != NULL)              \
314                         s->anchor.ptr->states_cur--;    \
315                 s->rule.ptr->states_cur--;              \
316         } while (0)
317
318 static __inline int pf_src_compare(struct pf_src_node *, struct pf_src_node *);
319 static __inline int pf_state_compare_key(struct pf_state_key *,
320         struct pf_state_key *);
321 static __inline int pf_state_compare_id(struct pf_state *,
322         struct pf_state *);
323
324 struct pf_src_tree tree_src_tracking;
325
326 struct pf_state_tree_id tree_id;
327 struct pf_state_queue state_list;
328
329 RB_GENERATE(pf_src_tree, pf_src_node, entry, pf_src_compare);
330 RB_GENERATE(pf_state_tree, pf_state_key, entry, pf_state_compare_key);
331 RB_GENERATE(pf_state_tree_id, pf_state,
332     entry_id, pf_state_compare_id);
333
334 static __inline int
335 pf_src_compare(struct pf_src_node *a, struct pf_src_node *b)
336 {
337         int     diff;
338
339         if (a->rule.ptr > b->rule.ptr)
340                 return (1);
341         if (a->rule.ptr < b->rule.ptr)
342                 return (-1);
343         if ((diff = a->af - b->af) != 0)
344                 return (diff);
345         switch (a->af) {
346 #ifdef INET
347         case AF_INET:
348                 if (a->addr.addr32[0] > b->addr.addr32[0])
349                         return (1);
350                 if (a->addr.addr32[0] < b->addr.addr32[0])
351                         return (-1);
352                 break;
353 #endif /* INET */
354 #ifdef INET6
355         case AF_INET6:
356                 if (a->addr.addr32[3] > b->addr.addr32[3])
357                         return (1);
358                 if (a->addr.addr32[3] < b->addr.addr32[3])
359                         return (-1);
360                 if (a->addr.addr32[2] > b->addr.addr32[2])
361                         return (1);
362                 if (a->addr.addr32[2] < b->addr.addr32[2])
363                         return (-1);
364                 if (a->addr.addr32[1] > b->addr.addr32[1])
365                         return (1);
366                 if (a->addr.addr32[1] < b->addr.addr32[1])
367                         return (-1);
368                 if (a->addr.addr32[0] > b->addr.addr32[0])
369                         return (1);
370                 if (a->addr.addr32[0] < b->addr.addr32[0])
371                         return (-1);
372                 break;
373 #endif /* INET6 */
374         }
375         return (0);
376 }
377
378 u_int32_t
379 pf_state_hash(struct pf_state_key *sk)
380 {
381         u_int32_t hv = (u_int32_t)(((intptr_t)sk >> 6) ^ ((intptr_t)sk >> 15));
382         if (hv == 0)    /* disallow 0 */
383                 hv = 1;
384         return(hv);
385 }
386
387 #ifdef INET6
388 void
389 pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
390 {
391         switch (af) {
392 #ifdef INET
393         case AF_INET:
394                 dst->addr32[0] = src->addr32[0];
395                 break;
396 #endif /* INET */
397         case AF_INET6:
398                 dst->addr32[0] = src->addr32[0];
399                 dst->addr32[1] = src->addr32[1];
400                 dst->addr32[2] = src->addr32[2];
401                 dst->addr32[3] = src->addr32[3];
402                 break;
403         }
404 }
405 #endif /* INET6 */
406
407 void
408 pf_init_threshold(struct pf_threshold *threshold,
409     u_int32_t limit, u_int32_t seconds)
410 {
411         threshold->limit = limit * PF_THRESHOLD_MULT;
412         threshold->seconds = seconds;
413         threshold->count = 0;
414         threshold->last = time_second;
415 }
416
417 void
418 pf_add_threshold(struct pf_threshold *threshold)
419 {
420         u_int32_t t = time_second, diff = t - threshold->last;
421
422         if (diff >= threshold->seconds)
423                 threshold->count = 0;
424         else
425                 threshold->count -= threshold->count * diff /
426                     threshold->seconds;
427         threshold->count += PF_THRESHOLD_MULT;
428         threshold->last = t;
429 }
430
431 int
432 pf_check_threshold(struct pf_threshold *threshold)
433 {
434         return (threshold->count > threshold->limit);
435 }
436
437 int
438 pf_src_connlimit(struct pf_state **state)
439 {
440         int bad = 0;
441
442         (*state)->src_node->conn++;
443         (*state)->src.tcp_est = 1;
444         pf_add_threshold(&(*state)->src_node->conn_rate);
445
446         if ((*state)->rule.ptr->max_src_conn &&
447             (*state)->rule.ptr->max_src_conn <
448             (*state)->src_node->conn) {
449                 pf_status.lcounters[LCNT_SRCCONN]++;
450                 bad++;
451         }
452
453         if ((*state)->rule.ptr->max_src_conn_rate.limit &&
454             pf_check_threshold(&(*state)->src_node->conn_rate)) {
455                 pf_status.lcounters[LCNT_SRCCONNRATE]++;
456                 bad++;
457         }
458
459         if (!bad)
460                 return (0);
461
462         if ((*state)->rule.ptr->overload_tbl) {
463                 struct pfr_addr p;
464                 u_int32_t       killed = 0;
465
466                 pf_status.lcounters[LCNT_OVERLOAD_TABLE]++;
467                 if (pf_status.debug >= PF_DEBUG_MISC) {
468                         kprintf("pf_src_connlimit: blocking address ");
469                         pf_print_host(&(*state)->src_node->addr, 0,
470                             (*state)->key[PF_SK_WIRE]->af);
471                 }
472
473                 bzero(&p, sizeof(p));
474                 p.pfra_af = (*state)->key[PF_SK_WIRE]->af;
475                 switch ((*state)->key[PF_SK_WIRE]->af) {
476 #ifdef INET
477                 case AF_INET:
478                         p.pfra_net = 32;
479                         p.pfra_ip4addr = (*state)->src_node->addr.v4;
480                         break;
481 #endif /* INET */
482 #ifdef INET6
483                 case AF_INET6:
484                         p.pfra_net = 128;
485                         p.pfra_ip6addr = (*state)->src_node->addr.v6;
486                         break;
487 #endif /* INET6 */
488                 }
489
490                 pfr_insert_kentry((*state)->rule.ptr->overload_tbl,
491                     &p, time_second);
492
493                 /* kill existing states if that's required. */
494                 if ((*state)->rule.ptr->flush) {
495                         struct pf_state_key *sk;
496                         struct pf_state *st;
497
498                         pf_status.lcounters[LCNT_OVERLOAD_FLUSH]++;
499                         RB_FOREACH(st, pf_state_tree_id, &tree_id) {
500                                 sk = st->key[PF_SK_WIRE];
501                                 /*
502                                  * Kill states from this source.  (Only those
503                                  * from the same rule if PF_FLUSH_GLOBAL is not
504                                  * set)
505                                  */
506                                 if (sk->af ==
507                                     (*state)->key[PF_SK_WIRE]->af &&
508                                     (((*state)->direction == PF_OUT &&
509                                     PF_AEQ(&(*state)->src_node->addr,
510                                         &sk->addr[0], sk->af)) ||
511                                     ((*state)->direction == PF_IN &&
512                                     PF_AEQ(&(*state)->src_node->addr,
513                                         &sk->addr[1], sk->af))) &&
514                                     ((*state)->rule.ptr->flush &
515                                     PF_FLUSH_GLOBAL ||
516                                     (*state)->rule.ptr == st->rule.ptr)) {
517                                         st->timeout = PFTM_PURGE;
518                                         st->src.state = st->dst.state =
519                                             TCPS_CLOSED;
520                                         killed++;
521                                 }
522                         }
523                         if (pf_status.debug >= PF_DEBUG_MISC)
524                                 kprintf(", %u states killed", killed);
525                 }
526                 if (pf_status.debug >= PF_DEBUG_MISC)
527                         kprintf("\n");
528         }
529
530         /* kill this state */
531         (*state)->timeout = PFTM_PURGE;
532         (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
533         return (1);
534 }
535
536 int
537 pf_insert_src_node(struct pf_src_node **sn, struct pf_rule *rule,
538     struct pf_addr *src, sa_family_t af)
539 {
540         struct pf_src_node      k;
541
542         if (*sn == NULL) {
543                 k.af = af;
544                 PF_ACPY(&k.addr, src, af);
545                 if (rule->rule_flag & PFRULE_RULESRCTRACK ||
546                     rule->rpool.opts & PF_POOL_STICKYADDR)
547                         k.rule.ptr = rule;
548                 else
549                         k.rule.ptr = NULL;
550                 pf_status.scounters[SCNT_SRC_NODE_SEARCH]++;
551                 *sn = RB_FIND(pf_src_tree, &tree_src_tracking, &k);
552         }
553         if (*sn == NULL) {
554                 if (!rule->max_src_nodes ||
555                     rule->src_nodes < rule->max_src_nodes)
556                         (*sn) = pool_get(&pf_src_tree_pl, PR_NOWAIT | PR_ZERO);
557                 else
558                         pf_status.lcounters[LCNT_SRCNODES]++;
559                 if ((*sn) == NULL)
560                         return (-1);
561
562                 pf_init_threshold(&(*sn)->conn_rate,
563                     rule->max_src_conn_rate.limit,
564                     rule->max_src_conn_rate.seconds);
565
566                 (*sn)->af = af;
567                 if (rule->rule_flag & PFRULE_RULESRCTRACK ||
568                     rule->rpool.opts & PF_POOL_STICKYADDR)
569                         (*sn)->rule.ptr = rule;
570                 else
571                         (*sn)->rule.ptr = NULL;
572                 PF_ACPY(&(*sn)->addr, src, af);
573                 if (RB_INSERT(pf_src_tree,
574                     &tree_src_tracking, *sn) != NULL) {
575                         if (pf_status.debug >= PF_DEBUG_MISC) {
576                                 kprintf("pf: src_tree insert failed: ");
577                                 pf_print_host(&(*sn)->addr, 0, af);
578                                 kprintf("\n");
579                         }
580                         pool_put(&pf_src_tree_pl, *sn);
581                         return (-1);
582                 }
583                 (*sn)->creation = time_second;
584                 (*sn)->ruletype = rule->action;
585                 if ((*sn)->rule.ptr != NULL)
586                         (*sn)->rule.ptr->src_nodes++;
587                 pf_status.scounters[SCNT_SRC_NODE_INSERT]++;
588                 pf_status.src_nodes++;
589         } else {
590                 if (rule->max_src_states &&
591                     (*sn)->states >= rule->max_src_states) {
592                         pf_status.lcounters[LCNT_SRCSTATES]++;
593                         return (-1);
594                 }
595         }
596         return (0);
597 }
598
599 /* state table stuff */
600
601 static __inline int
602 pf_state_compare_key(struct pf_state_key *a, struct pf_state_key *b)
603 {
604         int     diff;
605
606         if ((diff = a->proto - b->proto) != 0)
607                 return (diff);
608         if ((diff = a->af - b->af) != 0)
609                 return (diff);
610         switch (a->af) {
611 #ifdef INET
612         case AF_INET:
613                 if (a->addr[0].addr32[0] > b->addr[0].addr32[0])
614                         return (1);
615                 if (a->addr[0].addr32[0] < b->addr[0].addr32[0])
616                         return (-1);
617                 if (a->addr[1].addr32[0] > b->addr[1].addr32[0])
618                         return (1);
619                 if (a->addr[1].addr32[0] < b->addr[1].addr32[0])
620                         return (-1);
621                 break;
622 #endif /* INET */
623 #ifdef INET6
624         case AF_INET6:
625                 if (a->addr[0].addr32[3] > b->addr[0].addr32[3])
626                         return (1);
627                 if (a->addr[0].addr32[3] < b->addr[0].addr32[3])
628                         return (-1);
629                 if (a->addr[1].addr32[3] > b->addr[1].addr32[3])
630                         return (1);
631                 if (a->addr[1].addr32[3] < b->addr[1].addr32[3])
632                         return (-1);
633                 if (a->addr[0].addr32[2] > b->addr[0].addr32[2])
634                         return (1);
635                 if (a->addr[0].addr32[2] < b->addr[0].addr32[2])
636                         return (-1);
637                 if (a->addr[1].addr32[2] > b->addr[1].addr32[2])
638                         return (1);
639                 if (a->addr[1].addr32[2] < b->addr[1].addr32[2])
640                         return (-1);
641                 if (a->addr[0].addr32[1] > b->addr[0].addr32[1])
642                         return (1);
643                 if (a->addr[0].addr32[1] < b->addr[0].addr32[1])
644                         return (-1);
645                 if (a->addr[1].addr32[1] > b->addr[1].addr32[1])
646                         return (1);
647                 if (a->addr[1].addr32[1] < b->addr[1].addr32[1])
648                         return (-1);
649                 if (a->addr[0].addr32[0] > b->addr[0].addr32[0])
650                         return (1);
651                 if (a->addr[0].addr32[0] < b->addr[0].addr32[0])
652                         return (-1);
653                 if (a->addr[1].addr32[0] > b->addr[1].addr32[0])
654                         return (1);
655                 if (a->addr[1].addr32[0] < b->addr[1].addr32[0])
656                         return (-1);
657                 break;
658 #endif /* INET6 */
659         }
660
661         if ((diff = a->port[0] - b->port[0]) != 0)
662                 return (diff);
663         if ((diff = a->port[1] - b->port[1]) != 0)
664                 return (diff);
665
666         return (0);
667 }
668
669 static __inline int
670 pf_state_compare_id(struct pf_state *a, struct pf_state *b)
671 {
672         if (a->id > b->id)
673                 return (1);
674         if (a->id < b->id)
675                 return (-1);
676         if (a->creatorid > b->creatorid)
677                 return (1);
678         if (a->creatorid < b->creatorid)
679                 return (-1);
680
681         return (0);
682 }
683
684 int
685 pf_state_key_attach(struct pf_state_key *sk, struct pf_state *s, int idx)
686 {
687         struct pf_state_item    *si;
688         struct pf_state_key     *cur;
689
690         KKASSERT(s->key[idx] == NULL);  /* XXX handle this? */
691
692         if ((cur = RB_INSERT(pf_state_tree, &pf_statetbl, sk)) != NULL) {
693                 /* key exists. check for same kif, if none, add to key */
694                 TAILQ_FOREACH(si, &cur->states, entry)
695                         if (si->s->kif == s->kif &&
696                             si->s->direction == s->direction) {
697                                 if (pf_status.debug >= PF_DEBUG_MISC) {
698                                         kprintf(
699                                             "pf: %s key attach failed on %s: ",
700                                             (idx == PF_SK_WIRE) ?
701                                             "wire" : "stack",
702                                             s->kif->pfik_name);
703                                         pf_print_state_parts(s,
704                                             (idx == PF_SK_WIRE) ? sk : NULL,
705                                             (idx == PF_SK_STACK) ? sk : NULL);
706                                         kprintf("\n");
707                                 }
708                                 pool_put(&pf_state_key_pl, sk);
709                                 return (-1);    /* collision! */
710                         }
711                 pool_put(&pf_state_key_pl, sk);
712                 s->key[idx] = cur;
713         } else
714                 s->key[idx] = sk;
715
716         if ((si = pool_get(&pf_state_item_pl, PR_NOWAIT)) == NULL) {
717                 pf_state_key_detach(s, idx);
718                 return (-1);
719         }
720         si->s = s;
721
722         /* list is sorted, if-bound states before floating */
723         if (s->kif == pfi_all)
724                 TAILQ_INSERT_TAIL(&s->key[idx]->states, si, entry);
725         else
726                 TAILQ_INSERT_HEAD(&s->key[idx]->states, si, entry);
727         return (0);
728 }
729
730 void
731 pf_detach_state(struct pf_state *s)
732 {
733         if (s->key[PF_SK_WIRE] == s->key[PF_SK_STACK])
734                 s->key[PF_SK_WIRE] = NULL;
735
736         if (s->key[PF_SK_STACK] != NULL)
737                 pf_state_key_detach(s, PF_SK_STACK);
738
739         if (s->key[PF_SK_WIRE] != NULL)
740                 pf_state_key_detach(s, PF_SK_WIRE);
741 }
742
743 void
744 pf_state_key_detach(struct pf_state *s, int idx)
745 {
746         struct pf_state_item    *si;
747
748         si = TAILQ_FIRST(&s->key[idx]->states);
749         while (si && si->s != s)
750             si = TAILQ_NEXT(si, entry);
751
752         if (si) {
753                 TAILQ_REMOVE(&s->key[idx]->states, si, entry);
754                 pool_put(&pf_state_item_pl, si);
755         }
756
757         if (TAILQ_EMPTY(&s->key[idx]->states)) {
758                 RB_REMOVE(pf_state_tree, &pf_statetbl, s->key[idx]);
759                 if (s->key[idx]->reverse)
760                         s->key[idx]->reverse->reverse = NULL;
761                 if (s->key[idx]->inp)
762                         s->key[idx]->inp->inp_pf_sk = NULL;
763                 pool_put(&pf_state_key_pl, s->key[idx]);
764         }
765         s->key[idx] = NULL;
766 }
767
768 struct pf_state_key *
769 pf_alloc_state_key(int pool_flags)
770 {
771         struct pf_state_key     *sk;
772
773         if ((sk = pool_get(&pf_state_key_pl, pool_flags)) == NULL)
774                 return (NULL);
775         TAILQ_INIT(&sk->states);
776
777         return (sk);
778 }
779
780 int
781 pf_state_key_setup(struct pf_pdesc *pd, struct pf_rule *nr,
782         struct pf_state_key **skw, struct pf_state_key **sks,
783         struct pf_state_key **skp, struct pf_state_key **nkp,
784         struct pf_addr *saddr, struct pf_addr *daddr,
785         u_int16_t sport, u_int16_t dport)
786 {
787         KKASSERT((*skp == NULL && *nkp == NULL));
788
789         if ((*skp = pf_alloc_state_key(PR_NOWAIT | PR_ZERO)) == NULL)
790                 return (ENOMEM);
791
792         PF_ACPY(&(*skp)->addr[pd->sidx], saddr, pd->af);
793         PF_ACPY(&(*skp)->addr[pd->didx], daddr, pd->af);
794         (*skp)->port[pd->sidx] = sport;
795         (*skp)->port[pd->didx] = dport;
796         (*skp)->proto = pd->proto;
797         (*skp)->af = pd->af;
798
799         if (nr != NULL) {
800                 if ((*nkp = pf_alloc_state_key(PR_NOWAIT | PR_ZERO)) == NULL)
801                         return (ENOMEM); /* caller must handle cleanup */
802
803                 /* XXX maybe just bcopy and TAILQ_INIT(&(*nkp)->states) */
804                 PF_ACPY(&(*nkp)->addr[0], &(*skp)->addr[0], pd->af);
805                 PF_ACPY(&(*nkp)->addr[1], &(*skp)->addr[1], pd->af);
806                 (*nkp)->port[0] = (*skp)->port[0];
807                 (*nkp)->port[1] = (*skp)->port[1];
808                 (*nkp)->proto = pd->proto;
809                 (*nkp)->af = pd->af;
810         } else
811                 *nkp = *skp;
812
813         if (pd->dir == PF_IN) {
814                 *skw = *skp;
815                 *sks = *nkp;
816         } else {
817                 *sks = *skp;
818                 *skw = *nkp;
819         }
820         return (0);
821 }
822
823
824 int
825 pf_state_insert(struct pfi_kif *kif, struct pf_state_key *skw,
826     struct pf_state_key *sks, struct pf_state *s)
827 {
828         s->kif = kif;
829
830         if (skw == sks) {
831                 if (pf_state_key_attach(skw, s, PF_SK_WIRE))
832                         return (-1);
833                 s->key[PF_SK_STACK] = s->key[PF_SK_WIRE];
834         } else {
835                 if (pf_state_key_attach(skw, s, PF_SK_WIRE)) {
836                         pool_put(&pf_state_key_pl, sks);
837                         return (-1);
838                 }
839                 if (pf_state_key_attach(sks, s, PF_SK_STACK)) {
840                         pf_state_key_detach(s, PF_SK_WIRE);
841                         return (-1);
842                 }
843         }
844
845         if (s->id == 0 && s->creatorid == 0) {
846                 s->id = htobe64(pf_status.stateid++);
847                 s->creatorid = pf_status.hostid;
848         }
849         if (RB_INSERT(pf_state_tree_id, &tree_id, s) != NULL) {
850                 if (pf_status.debug >= PF_DEBUG_MISC) {
851                         kprintf("pf: state insert failed: "
852                             "id: %016jx creatorid: %08x",
853                               (uintmax_t)be64toh(s->id), ntohl(s->creatorid));
854                         if (s->sync_flags & PFSTATE_FROMSYNC)
855                                 kprintf(" (from sync)");
856                         kprintf("\n");
857                 }
858                 pf_detach_state(s);
859                 return (-1);
860         }
861         TAILQ_INSERT_TAIL(&state_list, s, entry_list);
862         pf_status.fcounters[FCNT_STATE_INSERT]++;
863         pf_status.states++;
864         pfi_kif_ref(kif, PFI_KIF_REF_STATE);
865         pfsync_insert_state(s);
866         return (0);
867 }
868
869 struct pf_state *
870 pf_find_state_byid(struct pf_state_cmp *key)
871 {
872         pf_status.fcounters[FCNT_STATE_SEARCH]++;
873
874         return (RB_FIND(pf_state_tree_id, &tree_id, (struct pf_state *)key));
875 }
876
877 struct pf_state *
878 pf_find_state(struct pfi_kif *kif, struct pf_state_key_cmp *key, u_int dir,
879     struct mbuf *m)
880 {
881         struct pf_state_key     *sk;
882         struct pf_state_item    *si;
883
884         pf_status.fcounters[FCNT_STATE_SEARCH]++;
885
886         if (dir == PF_OUT && m->m_pkthdr.pf.statekey &&
887             ((struct pf_state_key *)m->m_pkthdr.pf.statekey)->reverse)
888                 sk = ((struct pf_state_key *)m->m_pkthdr.pf.statekey)->reverse;
889         else {
890                 if ((sk = RB_FIND(pf_state_tree, &pf_statetbl,
891                     (struct pf_state_key *)key)) == NULL)
892                         return (NULL);
893                 if (dir == PF_OUT && m->m_pkthdr.pf.statekey) {
894                         ((struct pf_state_key *)
895                             m->m_pkthdr.pf.statekey)->reverse = sk;
896                         sk->reverse = m->m_pkthdr.pf.statekey;
897                 }
898         }
899
900         if (dir == PF_OUT)
901                 m->m_pkthdr.pf.statekey = NULL;
902
903         /* list is sorted, if-bound states before floating ones */
904         TAILQ_FOREACH(si, &sk->states, entry)
905                 if ((si->s->kif == pfi_all || si->s->kif == kif) &&
906                     sk == (dir == PF_IN ? si->s->key[PF_SK_WIRE] :
907                     si->s->key[PF_SK_STACK]))
908                         return (si->s);
909
910         return (NULL);
911 }
912
913 struct pf_state *
914 pf_find_state_all(struct pf_state_key_cmp *key, u_int dir, int *more)
915 {
916         struct pf_state_key     *sk;
917         struct pf_state_item    *si, *ret = NULL;
918
919         pf_status.fcounters[FCNT_STATE_SEARCH]++;
920
921         sk = RB_FIND(pf_state_tree, &pf_statetbl, (struct pf_state_key *)key);
922
923         if (sk != NULL) {
924                 TAILQ_FOREACH(si, &sk->states, entry)
925                         if (dir == PF_INOUT ||
926                             (sk == (dir == PF_IN ? si->s->key[PF_SK_WIRE] :
927                             si->s->key[PF_SK_STACK]))) {
928                                 if (more == NULL)
929                                         return (si->s);
930
931                                 if (ret)
932                                         (*more)++;
933                                 else
934                                         ret = si;
935                         }
936         }
937         return (ret ? ret->s : NULL);
938 }
939
940 /* END state table stuff */
941
942
943 void
944 pf_purge_thread(void *v)
945 {
946         int nloops = 0;
947         int locked = 0;
948
949         lwkt_gettoken(&pf_token);
950         for (;;) {
951                 tsleep(pf_purge_thread, PWAIT, "pftm", 1 * hz);
952
953                 lockmgr(&pf_consistency_lock, LK_EXCLUSIVE);
954
955                 if (pf_end_threads) {
956                         pf_purge_expired_states(pf_status.states, 1);
957                         pf_purge_expired_fragments();
958                         pf_purge_expired_src_nodes(1);
959                         pf_end_threads++;
960
961                         lockmgr(&pf_consistency_lock, LK_RELEASE);
962                         wakeup(pf_purge_thread);
963                         kthread_exit();
964                 }
965                 crit_enter();
966
967                 /* process a fraction of the state table every second */
968                 if(!pf_purge_expired_states(1 + (pf_status.states
969                     / pf_default_rule.timeout[PFTM_INTERVAL]), 0)) {
970
971                         pf_purge_expired_states(1 + (pf_status.states
972                             / pf_default_rule.timeout[PFTM_INTERVAL]), 1);
973                 }
974
975                 /* purge other expired types every PFTM_INTERVAL seconds */
976                 if (++nloops >= pf_default_rule.timeout[PFTM_INTERVAL]) {
977                         pf_purge_expired_fragments();
978                         if (!pf_purge_expired_src_nodes(locked)) {
979                                 pf_purge_expired_src_nodes(1);
980                         }
981                         nloops = 0;
982                 }
983                 crit_exit();
984                 lockmgr(&pf_consistency_lock, LK_RELEASE);
985         }
986         lwkt_reltoken(&pf_token);
987 }
988
989 u_int32_t
990 pf_state_expires(const struct pf_state *state)
991 {
992         u_int32_t       timeout;
993         u_int32_t       start;
994         u_int32_t       end;
995         u_int32_t       states;
996
997         /* handle all PFTM_* > PFTM_MAX here */
998         if (state->timeout == PFTM_PURGE)
999                 return (time_second);
1000         if (state->timeout == PFTM_UNTIL_PACKET)
1001                 return (0);
1002         KKASSERT(state->timeout != PFTM_UNLINKED);
1003         KKASSERT(state->timeout < PFTM_MAX);
1004         timeout = state->rule.ptr->timeout[state->timeout];
1005         if (!timeout)
1006                 timeout = pf_default_rule.timeout[state->timeout];
1007         start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1008         if (start) {
1009                 end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1010                 states = state->rule.ptr->states_cur;
1011         } else {
1012                 start = pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1013                 end = pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1014                 states = pf_status.states;
1015         }
1016         if (end && states > start && start < end) {
1017                 if (states < end)
1018                         return (state->expire + timeout * (end - states) /
1019                             (end - start));
1020                 else
1021                         return (time_second);
1022         }
1023         return (state->expire + timeout);
1024 }
1025
1026 int
1027 pf_purge_expired_src_nodes(int waslocked)
1028 {
1029          struct pf_src_node             *cur, *next;
1030          int                             locked = waslocked;
1031
1032          for (cur = RB_MIN(pf_src_tree, &tree_src_tracking); cur; cur = next) {
1033                  next = RB_NEXT(pf_src_tree, &tree_src_tracking, cur);
1034
1035                  if (cur->states <= 0 && cur->expire <= time_second) {
1036                          if (! locked) {
1037                                  lockmgr(&pf_consistency_lock, LK_EXCLUSIVE);
1038                                  next = RB_NEXT(pf_src_tree,
1039                                      &tree_src_tracking, cur);
1040                                  locked = 1;
1041                          }
1042                          if (cur->rule.ptr != NULL) {
1043                                  cur->rule.ptr->src_nodes--;
1044                                  if (cur->rule.ptr->states_cur <= 0 &&
1045                                      cur->rule.ptr->max_src_nodes <= 0)
1046                                          pf_rm_rule(NULL, cur->rule.ptr);
1047                          }
1048                          RB_REMOVE(pf_src_tree, &tree_src_tracking, cur);
1049                          pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
1050                          pf_status.src_nodes--;
1051                          pool_put(&pf_src_tree_pl, cur);
1052                  }
1053          }
1054
1055          if (locked && !waslocked)
1056                 lockmgr(&pf_consistency_lock, LK_RELEASE);
1057         return(1);
1058 }
1059
1060 void
1061 pf_src_tree_remove_state(struct pf_state *s)
1062 {
1063         u_int32_t timeout;
1064
1065         if (s->src_node != NULL) {
1066                 if (s->src.tcp_est)
1067                         --s->src_node->conn;
1068                 if (--s->src_node->states <= 0) {
1069                         timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1070                         if (!timeout)
1071                                 timeout =
1072                                     pf_default_rule.timeout[PFTM_SRC_NODE];
1073                         s->src_node->expire = time_second + timeout;
1074                 }
1075         }
1076         if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1077                 if (--s->nat_src_node->states <= 0) {
1078                         timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1079                         if (!timeout)
1080                                 timeout =
1081                                     pf_default_rule.timeout[PFTM_SRC_NODE];
1082                         s->nat_src_node->expire = time_second + timeout;
1083                 }
1084         }
1085         s->src_node = s->nat_src_node = NULL;
1086 }
1087
1088 /* callers should be at crit_enter() */
1089 void
1090 pf_unlink_state(struct pf_state *cur)
1091 {
1092         if (cur->src.state == PF_TCPS_PROXY_DST) {
1093                 /* XXX wire key the right one? */
1094                 pf_send_tcp(cur->rule.ptr, cur->key[PF_SK_WIRE]->af,
1095                     &cur->key[PF_SK_WIRE]->addr[1],
1096                     &cur->key[PF_SK_WIRE]->addr[0],
1097                     cur->key[PF_SK_WIRE]->port[1],
1098                     cur->key[PF_SK_WIRE]->port[0],
1099                     cur->src.seqhi, cur->src.seqlo + 1,
1100                     TH_RST|TH_ACK, 0, 0, 0, 1, cur->tag, NULL, NULL);
1101         }
1102         RB_REMOVE(pf_state_tree_id, &tree_id, cur);
1103         if (cur->creatorid == pf_status.hostid)
1104                 pfsync_delete_state(cur);
1105         cur->timeout = PFTM_UNLINKED;
1106         pf_src_tree_remove_state(cur);
1107         pf_detach_state(cur);
1108 }
1109
1110 static struct pf_state  *purge_cur;
1111
1112 /* callers should be at crit_enter() and hold the
1113  * write_lock on pf_consistency_lock */
1114 void
1115 pf_free_state(struct pf_state *cur)
1116 {
1117         if (pfsyncif != NULL &&
1118             (pfsyncif->sc_bulk_send_next == cur ||
1119             pfsyncif->sc_bulk_terminator == cur))
1120                 return;
1121         KKASSERT(cur->timeout == PFTM_UNLINKED);
1122         if (--cur->rule.ptr->states_cur <= 0 &&
1123             cur->rule.ptr->src_nodes <= 0)
1124                 pf_rm_rule(NULL, cur->rule.ptr);
1125         if (cur->nat_rule.ptr != NULL)
1126                 if (--cur->nat_rule.ptr->states_cur <= 0 &&
1127                         cur->nat_rule.ptr->src_nodes <= 0)
1128                         pf_rm_rule(NULL, cur->nat_rule.ptr);
1129         if (cur->anchor.ptr != NULL)
1130                 if (--cur->anchor.ptr->states_cur <= 0)
1131                         pf_rm_rule(NULL, cur->anchor.ptr);
1132         pf_normalize_tcp_cleanup(cur);
1133         pfi_kif_unref(cur->kif, PFI_KIF_REF_STATE);
1134
1135         /*
1136          * We may be freeing pf_purge_expired_states()'s saved scan entry,
1137          * adjust it if necessary.
1138          */
1139         if (purge_cur == cur) {
1140                 kprintf("PURGE CONFLICT\n");
1141                 purge_cur = TAILQ_NEXT(purge_cur, entry_list);
1142         }
1143         TAILQ_REMOVE(&state_list, cur, entry_list);
1144         if (cur->tag)
1145                 pf_tag_unref(cur->tag);
1146         pool_put(&pf_state_pl, cur);
1147         pf_status.fcounters[FCNT_STATE_REMOVALS]++;
1148         pf_status.states--;
1149 }
1150
1151 int
1152 pf_purge_expired_states(u_int32_t maxcheck, int waslocked)
1153 {
1154         struct pf_state         *cur;
1155         int                      locked = waslocked;
1156
1157         while (maxcheck--) {
1158                 /*
1159                  * Wrap to start of list when we hit the end
1160                  */
1161                 cur = purge_cur;
1162                 if (cur == NULL) {
1163                         cur = TAILQ_FIRST(&state_list);
1164                         if (cur == NULL)
1165                                 break;  /* list empty */
1166                 }
1167
1168                 /*
1169                  * Setup next (purge_cur) while we process this one.  If we block and
1170                  * something else deletes purge_cur, pf_free_state() will adjust it further
1171                  * ahead.
1172                  */
1173                 purge_cur = TAILQ_NEXT(cur, entry_list);
1174
1175                 if (cur->timeout == PFTM_UNLINKED) {
1176                         /* free unlinked state */
1177                         if (! locked) {
1178                                 lockmgr(&pf_consistency_lock, LK_EXCLUSIVE);
1179                                 locked = 1;
1180                         }
1181                         pf_free_state(cur);
1182                 } else if (pf_state_expires(cur) <= time_second) {
1183                         /* unlink and free expired state */
1184                         pf_unlink_state(cur);
1185                         if (! locked) {
1186                                 if (!lockmgr(&pf_consistency_lock, LK_EXCLUSIVE))
1187                                         return (0);
1188                                 locked = 1;
1189                         }
1190                         pf_free_state(cur);
1191                 }
1192         }
1193
1194         if (locked)
1195                 lockmgr(&pf_consistency_lock, LK_RELEASE);
1196         return (1);
1197 }
1198
1199 int
1200 pf_tbladdr_setup(struct pf_ruleset *rs, struct pf_addr_wrap *aw)
1201 {
1202         if (aw->type != PF_ADDR_TABLE)
1203                 return (0);
1204         if ((aw->p.tbl = pfr_attach_table(rs, aw->v.tblname)) == NULL)
1205                 return (1);
1206         return (0);
1207 }
1208
1209 void
1210 pf_tbladdr_remove(struct pf_addr_wrap *aw)
1211 {
1212         if (aw->type != PF_ADDR_TABLE || aw->p.tbl == NULL)
1213                 return;
1214         pfr_detach_table(aw->p.tbl);
1215         aw->p.tbl = NULL;
1216 }
1217
1218 void
1219 pf_tbladdr_copyout(struct pf_addr_wrap *aw)
1220 {
1221         struct pfr_ktable *kt = aw->p.tbl;
1222
1223         if (aw->type != PF_ADDR_TABLE || kt == NULL)
1224                 return;
1225         if (!(kt->pfrkt_flags & PFR_TFLAG_ACTIVE) && kt->pfrkt_root != NULL)
1226                 kt = kt->pfrkt_root;
1227         aw->p.tbl = NULL;
1228         aw->p.tblcnt = (kt->pfrkt_flags & PFR_TFLAG_ACTIVE) ?
1229                 kt->pfrkt_cnt : -1;
1230 }
1231
1232 void
1233 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1234 {
1235         switch (af) {
1236 #ifdef INET
1237         case AF_INET: {
1238                 u_int32_t a = ntohl(addr->addr32[0]);
1239                 kprintf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1240                     (a>>8)&255, a&255);
1241                 if (p) {
1242                         p = ntohs(p);
1243                         kprintf(":%u", p);
1244                 }
1245                 break;
1246         }
1247 #endif /* INET */
1248 #ifdef INET6
1249         case AF_INET6: {
1250                 u_int16_t b;
1251                 u_int8_t i, curstart = 255, curend = 0,
1252                     maxstart = 0, maxend = 0;
1253                 for (i = 0; i < 8; i++) {
1254                         if (!addr->addr16[i]) {
1255                                 if (curstart == 255)
1256                                         curstart = i;
1257                                 else
1258                                         curend = i;
1259                         } else {
1260                                 if (curstart) {
1261                                         if ((curend - curstart) >
1262                                             (maxend - maxstart)) {
1263                                                 maxstart = curstart;
1264                                                 maxend = curend;
1265                                                 curstart = 255;
1266                                         }
1267                                 }
1268                         }
1269                 }
1270                 for (i = 0; i < 8; i++) {
1271                         if (i >= maxstart && i <= maxend) {
1272                                 if (maxend != 7) {
1273                                         if (i == maxstart)
1274                                                 kprintf(":");
1275                                 } else {
1276                                         if (i == maxend)
1277                                                 kprintf(":");
1278                                 }
1279                         } else {
1280                                 b = ntohs(addr->addr16[i]);
1281                                 kprintf("%x", b);
1282                                 if (i < 7)
1283                                         kprintf(":");
1284                         }
1285                 }
1286                 if (p) {
1287                         p = ntohs(p);
1288                         kprintf("[%u]", p);
1289                 }
1290                 break;
1291         }
1292 #endif /* INET6 */
1293         }
1294 }
1295
1296 void
1297 pf_print_state(struct pf_state *s)
1298 {
1299         pf_print_state_parts(s, NULL, NULL);
1300 }
1301
1302 void
1303 pf_print_state_parts(struct pf_state *s,
1304     struct pf_state_key *skwp, struct pf_state_key *sksp)
1305 {
1306         struct pf_state_key *skw, *sks;
1307         u_int8_t proto, dir;
1308
1309         /* Do our best to fill these, but they're skipped if NULL */
1310         skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1311         sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1312         proto = skw ? skw->proto : (sks ? sks->proto : 0);
1313         dir = s ? s->direction : 0;
1314
1315         switch (proto) {
1316         case IPPROTO_TCP:
1317                 kprintf("TCP ");
1318                 break;
1319         case IPPROTO_UDP:
1320                 kprintf("UDP ");
1321                 break;
1322         case IPPROTO_ICMP:
1323                 kprintf("ICMP ");
1324                 break;
1325         case IPPROTO_ICMPV6:
1326                 kprintf("ICMPV6 ");
1327                 break;
1328         default:
1329                 kprintf("%u ", skw->proto);
1330                 break;
1331         }
1332         switch (dir) {
1333         case PF_IN:
1334                 kprintf(" in");
1335                 break;
1336         case PF_OUT:
1337                 kprintf(" out");
1338                 break;
1339         }
1340         if (skw) {
1341                 kprintf(" wire: ");
1342                 pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1343                 kprintf(" ");
1344                 pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1345         }
1346         if (sks) {
1347                 kprintf(" stack: ");
1348                 if (sks != skw) {
1349                         pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1350                         kprintf(" ");
1351                         pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1352                 } else
1353                         kprintf("-");
1354         }
1355         if (s) {
1356                 if (proto == IPPROTO_TCP) {
1357                         kprintf(" [lo=%u high=%u win=%u modulator=%u",
1358                             s->src.seqlo, s->src.seqhi,
1359                             s->src.max_win, s->src.seqdiff);
1360                         if (s->src.wscale && s->dst.wscale)
1361                                 kprintf(" wscale=%u",
1362                                     s->src.wscale & PF_WSCALE_MASK);
1363                         kprintf("]");
1364                         kprintf(" [lo=%u high=%u win=%u modulator=%u",
1365                             s->dst.seqlo, s->dst.seqhi,
1366                             s->dst.max_win, s->dst.seqdiff);
1367                         if (s->src.wscale && s->dst.wscale)
1368                                 kprintf(" wscale=%u",
1369                                 s->dst.wscale & PF_WSCALE_MASK);
1370                         kprintf("]");
1371                 }
1372                 kprintf(" %u:%u", s->src.state, s->dst.state);
1373         }
1374 }
1375
1376 void
1377 pf_print_flags(u_int8_t f)
1378 {
1379         if (f)
1380                 kprintf(" ");
1381         if (f & TH_FIN)
1382                 kprintf("F");
1383         if (f & TH_SYN)
1384                 kprintf("S");
1385         if (f & TH_RST)
1386                 kprintf("R");
1387         if (f & TH_PUSH)
1388                 kprintf("P");
1389         if (f & TH_ACK)
1390                 kprintf("A");
1391         if (f & TH_URG)
1392                 kprintf("U");
1393         if (f & TH_ECE)
1394                 kprintf("E");
1395         if (f & TH_CWR)
1396                 kprintf("W");
1397 }
1398
1399 #define PF_SET_SKIP_STEPS(i)                                    \
1400         do {                                                    \
1401                 while (head[i] != cur) {                        \
1402                         head[i]->skip[i].ptr = cur;             \
1403                         head[i] = TAILQ_NEXT(head[i], entries); \
1404                 }                                               \
1405         } while (0)
1406
1407 void
1408 pf_calc_skip_steps(struct pf_rulequeue *rules)
1409 {
1410         struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
1411         int i;
1412
1413         cur = TAILQ_FIRST(rules);
1414         prev = cur;
1415         for (i = 0; i < PF_SKIP_COUNT; ++i)
1416                 head[i] = cur;
1417         while (cur != NULL) {
1418
1419                 if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
1420                         PF_SET_SKIP_STEPS(PF_SKIP_IFP);
1421                 if (cur->direction != prev->direction)
1422                         PF_SET_SKIP_STEPS(PF_SKIP_DIR);
1423                 if (cur->af != prev->af)
1424                         PF_SET_SKIP_STEPS(PF_SKIP_AF);
1425                 if (cur->proto != prev->proto)
1426                         PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
1427                 if (cur->src.neg != prev->src.neg ||
1428                     pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
1429                         PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
1430                 if (cur->src.port[0] != prev->src.port[0] ||
1431                     cur->src.port[1] != prev->src.port[1] ||
1432                     cur->src.port_op != prev->src.port_op)
1433                         PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
1434                 if (cur->dst.neg != prev->dst.neg ||
1435                     pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
1436                         PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
1437                 if (cur->dst.port[0] != prev->dst.port[0] ||
1438                     cur->dst.port[1] != prev->dst.port[1] ||
1439                     cur->dst.port_op != prev->dst.port_op)
1440                         PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
1441
1442                 prev = cur;
1443                 cur = TAILQ_NEXT(cur, entries);
1444         }
1445         for (i = 0; i < PF_SKIP_COUNT; ++i)
1446                 PF_SET_SKIP_STEPS(i);
1447 }
1448
1449 int
1450 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
1451 {
1452         if (aw1->type != aw2->type)
1453                 return (1);
1454         switch (aw1->type) {
1455         case PF_ADDR_ADDRMASK:
1456         case PF_ADDR_RANGE:
1457                 if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, 0))
1458                         return (1);
1459                 if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, 0))
1460                         return (1);
1461                 return (0);
1462         case PF_ADDR_DYNIFTL:
1463                 return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
1464         case PF_ADDR_NOROUTE:
1465         case PF_ADDR_URPFFAILED:
1466                 return (0);
1467         case PF_ADDR_TABLE:
1468                 return (aw1->p.tbl != aw2->p.tbl);
1469         case PF_ADDR_RTLABEL:
1470                 return (aw1->v.rtlabel != aw2->v.rtlabel);
1471         default:
1472                 kprintf("invalid address type: %d\n", aw1->type);
1473                 return (1);
1474         }
1475 }
1476
1477 u_int16_t
1478 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
1479 {
1480         u_int32_t       l;
1481
1482         if (udp && !cksum)
1483                 return (0x0000);
1484         l = cksum + old - new;
1485         l = (l >> 16) + (l & 65535);
1486         l = l & 65535;
1487         if (udp && !l)
1488                 return (0xFFFF);
1489         return (l);
1490 }
1491
1492 void
1493 pf_change_ap(struct pf_addr *a, u_int16_t *p, u_int16_t *ic, u_int16_t *pc,
1494     struct pf_addr *an, u_int16_t pn, u_int8_t u, sa_family_t af)
1495 {
1496         struct pf_addr  ao;
1497         u_int16_t       po = *p;
1498
1499         PF_ACPY(&ao, a, af);
1500         PF_ACPY(a, an, af);
1501
1502         *p = pn;
1503
1504         switch (af) {
1505 #ifdef INET
1506         case AF_INET:
1507                 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
1508                     ao.addr16[0], an->addr16[0], 0),
1509                     ao.addr16[1], an->addr16[1], 0);
1510                 *p = pn;
1511                 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
1512                     ao.addr16[0], an->addr16[0], u),
1513                     ao.addr16[1], an->addr16[1], u),
1514                     po, pn, u);
1515                 break;
1516 #endif /* INET */
1517 #ifdef INET6
1518         case AF_INET6:
1519                 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1520                     pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1521                     pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
1522                     ao.addr16[0], an->addr16[0], u),
1523                     ao.addr16[1], an->addr16[1], u),
1524                     ao.addr16[2], an->addr16[2], u),
1525                     ao.addr16[3], an->addr16[3], u),
1526                     ao.addr16[4], an->addr16[4], u),
1527                     ao.addr16[5], an->addr16[5], u),
1528                     ao.addr16[6], an->addr16[6], u),
1529                     ao.addr16[7], an->addr16[7], u),
1530                     po, pn, u);
1531                 break;
1532 #endif /* INET6 */
1533         }
1534 }
1535
1536
1537 /* Changes a u_int32_t.  Uses a void * so there are no align restrictions */
1538 void
1539 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
1540 {
1541         u_int32_t       ao;
1542
1543         memcpy(&ao, a, sizeof(ao));
1544         memcpy(a, &an, sizeof(u_int32_t));
1545         *c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
1546             ao % 65536, an % 65536, u);
1547 }
1548
1549 #ifdef INET6
1550 void
1551 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
1552 {
1553         struct pf_addr  ao;
1554
1555         PF_ACPY(&ao, a, AF_INET6);
1556         PF_ACPY(a, an, AF_INET6);
1557
1558         *c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1559             pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1560             pf_cksum_fixup(pf_cksum_fixup(*c,
1561             ao.addr16[0], an->addr16[0], u),
1562             ao.addr16[1], an->addr16[1], u),
1563             ao.addr16[2], an->addr16[2], u),
1564             ao.addr16[3], an->addr16[3], u),
1565             ao.addr16[4], an->addr16[4], u),
1566             ao.addr16[5], an->addr16[5], u),
1567             ao.addr16[6], an->addr16[6], u),
1568             ao.addr16[7], an->addr16[7], u);
1569 }
1570 #endif /* INET6 */
1571
1572 void
1573 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
1574     struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
1575     u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
1576 {
1577         struct pf_addr  oia, ooa;
1578
1579         PF_ACPY(&oia, ia, af);
1580         if (oa)
1581                 PF_ACPY(&ooa, oa, af);
1582
1583         /* Change inner protocol port, fix inner protocol checksum. */
1584         if (ip != NULL) {
1585                 u_int16_t       oip = *ip;
1586                 u_int32_t       opc = 0;
1587
1588                 if (pc != NULL)
1589                         opc = *pc;
1590                 *ip = np;
1591                 if (pc != NULL)
1592                         *pc = pf_cksum_fixup(*pc, oip, *ip, u);
1593                 *ic = pf_cksum_fixup(*ic, oip, *ip, 0);
1594                 if (pc != NULL)
1595                         *ic = pf_cksum_fixup(*ic, opc, *pc, 0);
1596         }
1597         /* Change inner ip address, fix inner ip and icmp checksums. */
1598         PF_ACPY(ia, na, af);
1599         switch (af) {
1600 #ifdef INET
1601         case AF_INET: {
1602                 u_int32_t        oh2c = *h2c;
1603
1604                 *h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
1605                     oia.addr16[0], ia->addr16[0], 0),
1606                     oia.addr16[1], ia->addr16[1], 0);
1607                 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
1608                     oia.addr16[0], ia->addr16[0], 0),
1609                     oia.addr16[1], ia->addr16[1], 0);
1610                 *ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
1611                 break;
1612         }
1613 #endif /* INET */
1614 #ifdef INET6
1615         case AF_INET6:
1616                 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1617                     pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1618                     pf_cksum_fixup(pf_cksum_fixup(*ic,
1619                     oia.addr16[0], ia->addr16[0], u),
1620                     oia.addr16[1], ia->addr16[1], u),
1621                     oia.addr16[2], ia->addr16[2], u),
1622                     oia.addr16[3], ia->addr16[3], u),
1623                     oia.addr16[4], ia->addr16[4], u),
1624                     oia.addr16[5], ia->addr16[5], u),
1625                     oia.addr16[6], ia->addr16[6], u),
1626                     oia.addr16[7], ia->addr16[7], u);
1627                 break;
1628 #endif /* INET6 */
1629         }
1630         /* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
1631         if (oa) {
1632                 PF_ACPY(oa, na, af);
1633                 switch (af) {
1634 #ifdef INET
1635                 case AF_INET:
1636                         *hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
1637                             ooa.addr16[0], oa->addr16[0], 0),
1638                             ooa.addr16[1], oa->addr16[1], 0);
1639                         break;
1640 #endif /* INET */
1641 #ifdef INET6
1642                 case AF_INET6:
1643                         *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1644                             pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1645                             pf_cksum_fixup(pf_cksum_fixup(*ic,
1646                             ooa.addr16[0], oa->addr16[0], u),
1647                             ooa.addr16[1], oa->addr16[1], u),
1648                             ooa.addr16[2], oa->addr16[2], u),
1649                             ooa.addr16[3], oa->addr16[3], u),
1650                             ooa.addr16[4], oa->addr16[4], u),
1651                             ooa.addr16[5], oa->addr16[5], u),
1652                             ooa.addr16[6], oa->addr16[6], u),
1653                             ooa.addr16[7], oa->addr16[7], u);
1654                         break;
1655 #endif /* INET6 */
1656                 }
1657         }
1658 }
1659
1660
1661 /*
1662  * Need to modulate the sequence numbers in the TCP SACK option
1663  * (credits to Krzysztof Pfaff for report and patch)
1664  */
1665 int
1666 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
1667     struct tcphdr *th, struct pf_state_peer *dst)
1668 {
1669         int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
1670         u_int8_t opts[TCP_MAXOLEN], *opt = opts;
1671         int copyback = 0, i, olen;
1672         struct raw_sackblock sack;
1673
1674 #define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
1675         if (hlen < TCPOLEN_SACKLEN ||
1676             !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
1677                 return 0;
1678
1679         while (hlen >= TCPOLEN_SACKLEN) {
1680                 olen = opt[1];
1681                 switch (*opt) {
1682                 case TCPOPT_EOL:        /* FALLTHROUGH */
1683                 case TCPOPT_NOP:
1684                         opt++;
1685                         hlen--;
1686                         break;
1687                 case TCPOPT_SACK:
1688                         if (olen > hlen)
1689                                 olen = hlen;
1690                         if (olen >= TCPOLEN_SACKLEN) {
1691                                 for (i = 2; i + TCPOLEN_SACK <= olen;
1692                                     i += TCPOLEN_SACK) {
1693                                         memcpy(&sack, &opt[i], sizeof(sack));
1694                                         pf_change_a(&sack.rblk_start, &th->th_sum,
1695                                             htonl(ntohl(sack.rblk_start) -
1696                                             dst->seqdiff), 0);
1697                                         pf_change_a(&sack.rblk_end, &th->th_sum,
1698                                             htonl(ntohl(sack.rblk_end) -
1699                                             dst->seqdiff), 0);
1700                                         memcpy(&opt[i], &sack, sizeof(sack));
1701                                 }
1702                                 copyback = 1;
1703                         }
1704                         /* FALLTHROUGH */
1705                 default:
1706                         if (olen < 2)
1707                                 olen = 2;
1708                         hlen -= olen;
1709                         opt += olen;
1710                 }
1711         }
1712
1713         if (copyback)
1714                 m_copyback(m, off + sizeof(*th), thoptlen, opts);
1715         return (copyback);
1716 }
1717
1718 void
1719 pf_send_tcp(const struct pf_rule *r, sa_family_t af,
1720     const struct pf_addr *saddr, const struct pf_addr *daddr,
1721     u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
1722     u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
1723     u_int16_t rtag, struct ether_header *eh, struct ifnet *ifp)
1724 {
1725         struct mbuf     *m;
1726         int              len = 0, tlen;
1727 #ifdef INET
1728         struct ip       *h = NULL;
1729 #endif /* INET */
1730 #ifdef INET6
1731         struct ip6_hdr  *h6 = NULL;
1732 #endif /* INET6 */
1733         struct tcphdr   *th = NULL;
1734         char            *opt;
1735
1736         ASSERT_LWKT_TOKEN_HELD(&pf_token);
1737
1738         /* maximum segment size tcp option */
1739         tlen = sizeof(struct tcphdr);
1740         if (mss)
1741                 tlen += 4;
1742
1743         switch (af) {
1744 #ifdef INET
1745         case AF_INET:
1746                 len = sizeof(struct ip) + tlen;
1747                 break;
1748 #endif /* INET */
1749 #ifdef INET6
1750         case AF_INET6:
1751                 len = sizeof(struct ip6_hdr) + tlen;
1752                 break;
1753 #endif /* INET6 */
1754         }
1755
1756         /*
1757          * Create outgoing mbuf.
1758          *
1759          * DragonFly doesn't zero the auxillary pkghdr fields, only fw_flags,
1760          * so make sure pf.flags is clear.
1761          */
1762         m = m_gethdr(MB_DONTWAIT, MT_HEADER);
1763         if (m == NULL) {
1764                 return;
1765         }
1766         if (tag)
1767                 m->m_pkthdr.fw_flags |= PF_MBUF_TAGGED;
1768         m->m_pkthdr.pf.flags = 0;
1769         m->m_pkthdr.pf.tag = rtag;
1770         /* XXX Recheck when upgrading to > 4.4 */
1771         m->m_pkthdr.pf.statekey = NULL;
1772         if (r != NULL && r->rtableid >= 0)
1773                 m->m_pkthdr.pf.rtableid = r->rtableid;
1774
1775 #ifdef ALTQ
1776         if (r != NULL && r->qid) {
1777                 m->m_pkthdr.fw_flags |= PF_MBUF_STRUCTURE;
1778                 m->m_pkthdr.pf.qid = r->qid;
1779                 m->m_pkthdr.pf.ecn_af = af;
1780                 m->m_pkthdr.pf.hdr = mtod(m, struct ip *);
1781         }
1782 #endif /* ALTQ */
1783         m->m_data += max_linkhdr;
1784         m->m_pkthdr.len = m->m_len = len;
1785         m->m_pkthdr.rcvif = NULL;
1786         bzero(m->m_data, len);
1787         switch (af) {
1788 #ifdef INET
1789         case AF_INET:
1790                 h = mtod(m, struct ip *);
1791
1792                 /* IP header fields included in the TCP checksum */
1793                 h->ip_p = IPPROTO_TCP;
1794                 h->ip_len = tlen;
1795                 h->ip_src.s_addr = saddr->v4.s_addr;
1796                 h->ip_dst.s_addr = daddr->v4.s_addr;
1797
1798                 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
1799                 break;
1800 #endif /* INET */
1801 #ifdef INET6
1802         case AF_INET6:
1803                 h6 = mtod(m, struct ip6_hdr *);
1804
1805                 /* IP header fields included in the TCP checksum */
1806                 h6->ip6_nxt = IPPROTO_TCP;
1807                 h6->ip6_plen = htons(tlen);
1808                 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
1809                 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
1810
1811                 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
1812                 break;
1813 #endif /* INET6 */
1814         }
1815
1816         /* TCP header */
1817         th->th_sport = sport;
1818         th->th_dport = dport;
1819         th->th_seq = htonl(seq);
1820         th->th_ack = htonl(ack);
1821         th->th_off = tlen >> 2;
1822         th->th_flags = flags;
1823         th->th_win = htons(win);
1824
1825         if (mss) {
1826                 opt = (char *)(th + 1);
1827                 opt[0] = TCPOPT_MAXSEG;
1828                 opt[1] = 4;
1829                 mss = htons(mss);
1830                 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
1831         }
1832
1833         switch (af) {
1834 #ifdef INET
1835         case AF_INET:
1836                 /* TCP checksum */
1837                 th->th_sum = in_cksum(m, len);
1838
1839                 /* Finish the IP header */
1840                 h->ip_v = 4;
1841                 h->ip_hl = sizeof(*h) >> 2;
1842                 h->ip_tos = IPTOS_LOWDELAY;
1843                 h->ip_len = len;
1844                 h->ip_off = path_mtu_discovery ? IP_DF : 0;
1845                 h->ip_ttl = ttl ? ttl : ip_defttl;
1846                 h->ip_sum = 0;
1847                 if (eh == NULL) {
1848                         lwkt_reltoken(&pf_token);
1849                         ip_output(m, NULL, NULL, 0, NULL, NULL);
1850                         lwkt_gettoken(&pf_token);
1851                 } else {
1852                         struct route             ro;
1853                         struct rtentry           rt;
1854                         struct ether_header     *e = (void *)ro.ro_dst.sa_data;
1855
1856                         if (ifp == NULL) {
1857                                 m_freem(m);
1858                                 return;
1859                         }
1860                         rt.rt_ifp = ifp;
1861                         ro.ro_rt = &rt;
1862                         ro.ro_dst.sa_len = sizeof(ro.ro_dst);
1863                         ro.ro_dst.sa_family = pseudo_AF_HDRCMPLT;
1864                         bcopy(eh->ether_dhost, e->ether_shost, ETHER_ADDR_LEN);
1865                         bcopy(eh->ether_shost, e->ether_dhost, ETHER_ADDR_LEN);
1866                         e->ether_type = eh->ether_type;
1867                         /* XXX_IMPORT: later */
1868                         lwkt_reltoken(&pf_token);
1869                         ip_output(m, (void *)NULL, &ro, 0,
1870                             (void *)NULL, (void *)NULL);
1871                         lwkt_gettoken(&pf_token);
1872                 }
1873                 break;
1874 #endif /* INET */
1875 #ifdef INET6
1876         case AF_INET6:
1877                 /* TCP checksum */
1878                 th->th_sum = in6_cksum(m, IPPROTO_TCP,
1879                     sizeof(struct ip6_hdr), tlen);
1880
1881                 h6->ip6_vfc |= IPV6_VERSION;
1882                 h6->ip6_hlim = IPV6_DEFHLIM;
1883
1884                 lwkt_reltoken(&pf_token);
1885                 ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
1886                 lwkt_gettoken(&pf_token);
1887                 break;
1888 #endif /* INET6 */
1889         }
1890 }
1891
1892 void
1893 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
1894     struct pf_rule *r)
1895 {
1896         struct mbuf     *m0;
1897
1898         /*
1899          * DragonFly doesn't zero the auxillary pkghdr fields, only fw_flags,
1900          * so make sure pf.flags is clear.
1901          */
1902         if ((m0 = m_copy(m, 0, M_COPYALL)) == NULL)
1903                 return;
1904
1905         m0->m_pkthdr.fw_flags |= PF_MBUF_TAGGED;
1906         m0->m_pkthdr.pf.flags = 0;
1907         /* XXX Re-Check when Upgrading to > 4.4 */
1908         m0->m_pkthdr.pf.statekey = NULL;
1909
1910         if (r->rtableid >= 0)
1911                 m0->m_pkthdr.pf.rtableid = r->rtableid;
1912
1913 #ifdef ALTQ
1914         if (r->qid) {
1915                 m->m_pkthdr.fw_flags |= PF_MBUF_STRUCTURE;
1916                 m0->m_pkthdr.pf.qid = r->qid;
1917                 m0->m_pkthdr.pf.ecn_af = af;
1918                 m0->m_pkthdr.pf.hdr = mtod(m0, struct ip *);
1919         }
1920 #endif /* ALTQ */
1921
1922         switch (af) {
1923 #ifdef INET
1924         case AF_INET:
1925                 icmp_error(m0, type, code, 0, 0);
1926                 break;
1927 #endif /* INET */
1928 #ifdef INET6
1929         case AF_INET6:
1930                 icmp6_error(m0, type, code, 0);
1931                 break;
1932 #endif /* INET6 */
1933         }
1934 }
1935
1936 /*
1937  * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
1938  * If n is 0, they match if they are equal. If n is != 0, they match if they
1939  * are different.
1940  */
1941 int
1942 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
1943     struct pf_addr *b, sa_family_t af)
1944 {
1945         int     match = 0;
1946
1947         switch (af) {
1948 #ifdef INET
1949         case AF_INET:
1950                 if ((a->addr32[0] & m->addr32[0]) ==
1951                     (b->addr32[0] & m->addr32[0]))
1952                         match++;
1953                 break;
1954 #endif /* INET */
1955 #ifdef INET6
1956         case AF_INET6:
1957                 if (((a->addr32[0] & m->addr32[0]) ==
1958                      (b->addr32[0] & m->addr32[0])) &&
1959                     ((a->addr32[1] & m->addr32[1]) ==
1960                      (b->addr32[1] & m->addr32[1])) &&
1961                     ((a->addr32[2] & m->addr32[2]) ==
1962                      (b->addr32[2] & m->addr32[2])) &&
1963                     ((a->addr32[3] & m->addr32[3]) ==
1964                      (b->addr32[3] & m->addr32[3])))
1965                         match++;
1966                 break;
1967 #endif /* INET6 */
1968         }
1969         if (match) {
1970                 if (n)
1971                         return (0);
1972                 else
1973                         return (1);
1974         } else {
1975                 if (n)
1976                         return (1);
1977                 else
1978                         return (0);
1979         }
1980 }
1981
1982 /*
1983  * Return 1 if b <= a <= e, otherwise return 0.
1984  */
1985 int
1986 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
1987     struct pf_addr *a, sa_family_t af)
1988 {
1989         switch (af) {
1990 #ifdef INET
1991         case AF_INET:
1992                 if ((a->addr32[0] < b->addr32[0]) ||
1993                     (a->addr32[0] > e->addr32[0]))
1994                         return (0);
1995                 break;
1996 #endif /* INET */
1997 #ifdef INET6
1998         case AF_INET6: {
1999                 int     i;
2000
2001                 /* check a >= b */
2002                 for (i = 0; i < 4; ++i)
2003                         if (a->addr32[i] > b->addr32[i])
2004                                 break;
2005                         else if (a->addr32[i] < b->addr32[i])
2006                                 return (0);
2007                 /* check a <= e */
2008                 for (i = 0; i < 4; ++i)
2009                         if (a->addr32[i] < e->addr32[i])
2010                                 break;
2011                         else if (a->addr32[i] > e->addr32[i])
2012                                 return (0);
2013                 break;
2014         }
2015 #endif /* INET6 */
2016         }
2017         return (1);
2018 }
2019
2020 int
2021 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2022 {
2023         switch (op) {
2024         case PF_OP_IRG:
2025                 return ((p > a1) && (p < a2));
2026         case PF_OP_XRG:
2027                 return ((p < a1) || (p > a2));
2028         case PF_OP_RRG:
2029                 return ((p >= a1) && (p <= a2));
2030         case PF_OP_EQ:
2031                 return (p == a1);
2032         case PF_OP_NE:
2033                 return (p != a1);
2034         case PF_OP_LT:
2035                 return (p < a1);
2036         case PF_OP_LE:
2037                 return (p <= a1);
2038         case PF_OP_GT:
2039                 return (p > a1);
2040         case PF_OP_GE:
2041                 return (p >= a1);
2042         }
2043         return (0); /* never reached */
2044 }
2045
2046 int
2047 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2048 {
2049         a1 = ntohs(a1);
2050         a2 = ntohs(a2);
2051         p = ntohs(p);
2052         return (pf_match(op, a1, a2, p));
2053 }
2054
2055 int
2056 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2057 {
2058         if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2059                 return (0);
2060         return (pf_match(op, a1, a2, u));
2061 }
2062
2063 int
2064 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2065 {
2066         if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2067                 return (0);
2068         return (pf_match(op, a1, a2, g));
2069 }
2070
2071 int
2072 pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag)
2073 {
2074         if (*tag == -1)
2075                 *tag = m->m_pkthdr.pf.tag;
2076
2077         return ((!r->match_tag_not && r->match_tag == *tag) ||
2078             (r->match_tag_not && r->match_tag != *tag));
2079 }
2080
2081 int
2082 pf_tag_packet(struct mbuf *m, int tag, int rtableid)
2083 {
2084         if (tag <= 0 && rtableid < 0)
2085                 return (0);
2086
2087         if (tag > 0)
2088                 m->m_pkthdr.pf.tag = tag;
2089         if (rtableid >= 0)
2090                 m->m_pkthdr.pf.rtableid = rtableid;
2091
2092         return (0);
2093 }
2094
2095 void
2096 pf_step_into_anchor(int *depth, struct pf_ruleset **rs, int n,
2097     struct pf_rule **r, struct pf_rule **a, int *match)
2098 {
2099         struct pf_anchor_stackframe     *f;
2100
2101         (*r)->anchor->match = 0;
2102         if (match)
2103                 *match = 0;
2104         if (*depth >= sizeof(pf_anchor_stack) /
2105             sizeof(pf_anchor_stack[0])) {
2106                 kprintf("pf_step_into_anchor: stack overflow\n");
2107                 *r = TAILQ_NEXT(*r, entries);
2108                 return;
2109         } else if (*depth == 0 && a != NULL)
2110                 *a = *r;
2111         f = pf_anchor_stack + (*depth)++;
2112         f->rs = *rs;
2113         f->r = *r;
2114         if ((*r)->anchor_wildcard) {
2115                 f->parent = &(*r)->anchor->children;
2116                 if ((f->child = RB_MIN(pf_anchor_node, f->parent)) ==
2117                     NULL) {
2118                         *r = NULL;
2119                         return;
2120                 }
2121                 *rs = &f->child->ruleset;
2122         } else {
2123                 f->parent = NULL;
2124                 f->child = NULL;
2125                 *rs = &(*r)->anchor->ruleset;
2126         }
2127         *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2128 }
2129
2130 int
2131 pf_step_out_of_anchor(int *depth, struct pf_ruleset **rs, int n,
2132     struct pf_rule **r, struct pf_rule **a, int *match)
2133 {
2134         struct pf_anchor_stackframe     *f;
2135         int quick = 0;
2136
2137         do {
2138                 if (*depth <= 0)
2139                         break;
2140                 f = pf_anchor_stack + *depth - 1;
2141                 if (f->parent != NULL && f->child != NULL) {
2142                         if (f->child->match ||
2143                             (match != NULL && *match)) {
2144                                 f->r->anchor->match = 1;
2145                                 *match = 0;
2146                         }
2147                         f->child = RB_NEXT(pf_anchor_node, f->parent, f->child);
2148                         if (f->child != NULL) {
2149                                 *rs = &f->child->ruleset;
2150                                 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2151                                 if (*r == NULL)
2152                                         continue;
2153                                 else
2154                                         break;
2155                         }
2156                 }
2157                 (*depth)--;
2158                 if (*depth == 0 && a != NULL)
2159                         *a = NULL;
2160                 *rs = f->rs;
2161                 if (f->r->anchor->match || (match != NULL && *match))
2162                         quick = f->r->quick;
2163                 *r = TAILQ_NEXT(f->r, entries);
2164         } while (*r == NULL);
2165
2166         return (quick);
2167 }
2168
2169 #ifdef INET6
2170 void
2171 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2172     struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2173 {
2174         switch (af) {
2175 #ifdef INET
2176         case AF_INET:
2177                 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2178                 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2179                 break;
2180 #endif /* INET */
2181         case AF_INET6:
2182                 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2183                 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2184                 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2185                 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2186                 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2187                 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2188                 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2189                 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2190                 break;
2191         }
2192 }
2193
2194 void
2195 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2196 {
2197         switch (af) {
2198 #ifdef INET
2199         case AF_INET:
2200                 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2201                 break;
2202 #endif /* INET */
2203         case AF_INET6:
2204                 if (addr->addr32[3] == 0xffffffff) {
2205                         addr->addr32[3] = 0;
2206                         if (addr->addr32[2] == 0xffffffff) {
2207                                 addr->addr32[2] = 0;
2208                                 if (addr->addr32[1] == 0xffffffff) {
2209                                         addr->addr32[1] = 0;
2210                                         addr->addr32[0] =
2211                                             htonl(ntohl(addr->addr32[0]) + 1);
2212                                 } else
2213                                         addr->addr32[1] =
2214                                             htonl(ntohl(addr->addr32[1]) + 1);
2215                         } else
2216                                 addr->addr32[2] =
2217                                     htonl(ntohl(addr->addr32[2]) + 1);
2218                 } else
2219                         addr->addr32[3] =
2220                             htonl(ntohl(addr->addr32[3]) + 1);
2221                 break;
2222         }
2223 }
2224 #endif /* INET6 */
2225
2226 #define mix(a,b,c) \
2227         do {                                    \
2228                 a -= b; a -= c; a ^= (c >> 13); \
2229                 b -= c; b -= a; b ^= (a << 8);  \
2230                 c -= a; c -= b; c ^= (b >> 13); \
2231                 a -= b; a -= c; a ^= (c >> 12); \
2232                 b -= c; b -= a; b ^= (a << 16); \
2233                 c -= a; c -= b; c ^= (b >> 5);  \
2234                 a -= b; a -= c; a ^= (c >> 3);  \
2235                 b -= c; b -= a; b ^= (a << 10); \
2236                 c -= a; c -= b; c ^= (b >> 15); \
2237         } while (0)
2238
2239 /*
2240  * hash function based on bridge_hash in if_bridge.c
2241  */
2242 void
2243 pf_hash(struct pf_addr *inaddr, struct pf_addr *hash,
2244     struct pf_poolhashkey *key, sa_family_t af)
2245 {
2246         u_int32_t       a = 0x9e3779b9, b = 0x9e3779b9, c = key->key32[0];
2247
2248         switch (af) {
2249 #ifdef INET
2250         case AF_INET:
2251                 a += inaddr->addr32[0];
2252                 b += key->key32[1];
2253                 mix(a, b, c);
2254                 hash->addr32[0] = c + key->key32[2];
2255                 break;
2256 #endif /* INET */
2257 #ifdef INET6
2258         case AF_INET6:
2259                 a += inaddr->addr32[0];
2260                 b += inaddr->addr32[2];
2261                 mix(a, b, c);
2262                 hash->addr32[0] = c;
2263                 a += inaddr->addr32[1];
2264                 b += inaddr->addr32[3];
2265                 c += key->key32[1];
2266                 mix(a, b, c);
2267                 hash->addr32[1] = c;
2268                 a += inaddr->addr32[2];
2269                 b += inaddr->addr32[1];
2270                 c += key->key32[2];
2271                 mix(a, b, c);
2272                 hash->addr32[2] = c;
2273                 a += inaddr->addr32[3];
2274                 b += inaddr->addr32[0];
2275                 c += key->key32[3];
2276                 mix(a, b, c);
2277                 hash->addr32[3] = c;
2278                 break;
2279 #endif /* INET6 */
2280         }
2281 }
2282
2283 int
2284 pf_map_addr(sa_family_t af, struct pf_rule *r, struct pf_addr *saddr,
2285     struct pf_addr *naddr, struct pf_addr *init_addr, struct pf_src_node **sn)
2286 {
2287         unsigned char            hash[16];
2288         struct pf_pool          *rpool = &r->rpool;
2289         struct pf_addr          *raddr = &rpool->cur->addr.v.a.addr;
2290         struct pf_addr          *rmask = &rpool->cur->addr.v.a.mask;
2291         struct pf_pooladdr      *acur = rpool->cur;
2292         struct pf_src_node       k;
2293
2294         if (*sn == NULL && r->rpool.opts & PF_POOL_STICKYADDR &&
2295             (r->rpool.opts & PF_POOL_TYPEMASK) != PF_POOL_NONE) {
2296                 k.af = af;
2297                 PF_ACPY(&k.addr, saddr, af);
2298                 if (r->rule_flag & PFRULE_RULESRCTRACK ||
2299                     r->rpool.opts & PF_POOL_STICKYADDR)
2300                         k.rule.ptr = r;
2301                 else
2302                         k.rule.ptr = NULL;
2303                 pf_status.scounters[SCNT_SRC_NODE_SEARCH]++;
2304                 *sn = RB_FIND(pf_src_tree, &tree_src_tracking, &k);
2305                 if (*sn != NULL && !PF_AZERO(&(*sn)->raddr, af)) {
2306                         PF_ACPY(naddr, &(*sn)->raddr, af);
2307                         if (pf_status.debug >= PF_DEBUG_MISC) {
2308                                 kprintf("pf_map_addr: src tracking maps ");
2309                                 pf_print_host(&k.addr, 0, af);
2310                                 kprintf(" to ");
2311                                 pf_print_host(naddr, 0, af);
2312                                 kprintf("\n");
2313                         }
2314                         return (0);
2315                 }
2316         }
2317
2318         if (rpool->cur->addr.type == PF_ADDR_NOROUTE)
2319                 return (1);
2320         if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
2321                 switch (af) {
2322 #ifdef INET
2323                 case AF_INET:
2324                         if (rpool->cur->addr.p.dyn->pfid_acnt4 < 1 &&
2325                             (rpool->opts & PF_POOL_TYPEMASK) !=
2326                             PF_POOL_ROUNDROBIN)
2327                                 return (1);
2328                          raddr = &rpool->cur->addr.p.dyn->pfid_addr4;
2329                          rmask = &rpool->cur->addr.p.dyn->pfid_mask4;
2330                         break;
2331 #endif /* INET */
2332 #ifdef INET6
2333                 case AF_INET6:
2334                         if (rpool->cur->addr.p.dyn->pfid_acnt6 < 1 &&
2335                             (rpool->opts & PF_POOL_TYPEMASK) !=
2336                             PF_POOL_ROUNDROBIN)
2337                                 return (1);
2338                         raddr = &rpool->cur->addr.p.dyn->pfid_addr6;
2339                         rmask = &rpool->cur->addr.p.dyn->pfid_mask6;
2340                         break;
2341 #endif /* INET6 */
2342                 }
2343         } else if (rpool->cur->addr.type == PF_ADDR_TABLE) {
2344                 if ((rpool->opts & PF_POOL_TYPEMASK) != PF_POOL_ROUNDROBIN)
2345                         return (1); /* unsupported */
2346         } else {
2347                 raddr = &rpool->cur->addr.v.a.addr;
2348                 rmask = &rpool->cur->addr.v.a.mask;
2349         }
2350
2351         switch (rpool->opts & PF_POOL_TYPEMASK) {
2352         case PF_POOL_NONE:
2353                 PF_ACPY(naddr, raddr, af);
2354                 break;
2355         case PF_POOL_BITMASK:
2356                 PF_POOLMASK(naddr, raddr, rmask, saddr, af);
2357                 break;
2358         case PF_POOL_RANDOM:
2359                 if (init_addr != NULL && PF_AZERO(init_addr, af)) {
2360                         switch (af) {
2361 #ifdef INET
2362                         case AF_INET:
2363                                 rpool->counter.addr32[0] = htonl(karc4random());
2364                                 break;
2365 #endif /* INET */
2366 #ifdef INET6
2367                         case AF_INET6:
2368                                 if (rmask->addr32[3] != 0xffffffff)
2369                                         rpool->counter.addr32[3] =
2370                                             htonl(karc4random());
2371                                 else
2372                                         break;
2373                                 if (rmask->addr32[2] != 0xffffffff)
2374                                         rpool->counter.addr32[2] =
2375                                             htonl(karc4random());
2376                                 else
2377                                         break;
2378                                 if (rmask->addr32[1] != 0xffffffff)
2379                                         rpool->counter.addr32[1] =
2380                                             htonl(karc4random());
2381                                 else
2382                                         break;
2383                                 if (rmask->addr32[0] != 0xffffffff)
2384                                         rpool->counter.addr32[0] =
2385                                             htonl(karc4random());
2386                                 break;
2387 #endif /* INET6 */
2388                         }
2389                         PF_POOLMASK(naddr, raddr, rmask, &rpool->counter, af);
2390                         PF_ACPY(init_addr, naddr, af);
2391
2392                 } else {
2393                         PF_AINC(&rpool->counter, af);
2394                         PF_POOLMASK(naddr, raddr, rmask, &rpool->counter, af);
2395                 }
2396                 break;
2397         case PF_POOL_SRCHASH:
2398                 pf_hash(saddr, (struct pf_addr *)&hash, &rpool->key, af);
2399                 PF_POOLMASK(naddr, raddr, rmask, (struct pf_addr *)&hash, af);
2400                 break;
2401         case PF_POOL_ROUNDROBIN:
2402                 if (rpool->cur->addr.type == PF_ADDR_TABLE) {
2403                         if (!pfr_pool_get(rpool->cur->addr.p.tbl,
2404                             &rpool->tblidx, &rpool->counter,
2405                             &raddr, &rmask, af))
2406                                 goto get_addr;
2407                 } else if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
2408                         if (!pfr_pool_get(rpool->cur->addr.p.dyn->pfid_kt,
2409                             &rpool->tblidx, &rpool->counter,
2410                             &raddr, &rmask, af))
2411                                 goto get_addr;
2412                 } else if (pf_match_addr(0, raddr, rmask, &rpool->counter, af))
2413                         goto get_addr;
2414
2415         try_next:
2416                 if ((rpool->cur = TAILQ_NEXT(rpool->cur, entries)) == NULL)
2417                         rpool->cur = TAILQ_FIRST(&rpool->list);
2418                 if (rpool->cur->addr.type == PF_ADDR_TABLE) {
2419                         rpool->tblidx = -1;
2420                         if (pfr_pool_get(rpool->cur->addr.p.tbl,
2421                             &rpool->tblidx, &rpool->counter,
2422                             &raddr, &rmask, af)) {
2423                                 /* table contains no address of type 'af' */
2424                                 if (rpool->cur != acur)
2425                                         goto try_next;
2426                                 return (1);
2427                         }
2428                 } else if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
2429                         rpool->tblidx = -1;
2430                         if (pfr_pool_get(rpool->cur->addr.p.dyn->pfid_kt,
2431                             &rpool->tblidx, &rpool->counter,
2432                             &raddr, &rmask, af)) {
2433                                 /* table contains no address of type 'af' */
2434                                 if (rpool->cur != acur)
2435                                         goto try_next;
2436                                 return (1);
2437                         }
2438                 } else {
2439                         raddr = &rpool->cur->addr.v.a.addr;
2440                         rmask = &rpool->cur->addr.v.a.mask;
2441                         PF_ACPY(&rpool->counter, raddr, af);
2442                 }
2443
2444         get_addr:
2445                 PF_ACPY(naddr, &rpool->counter, af);
2446                 if (init_addr != NULL && PF_AZERO(init_addr, af))
2447                         PF_ACPY(init_addr, naddr, af);
2448                 PF_AINC(&rpool->counter, af);
2449                 break;
2450         }
2451         if (*sn != NULL)
2452                 PF_ACPY(&(*sn)->raddr, naddr, af);
2453
2454         if (pf_status.debug >= PF_DEBUG_MISC &&
2455             (rpool->opts & PF_POOL_TYPEMASK) != PF_POOL_NONE) {
2456                 kprintf("pf_map_addr: selected address ");
2457                 pf_print_host(naddr, 0, af);
2458                 kprintf("\n");
2459         }
2460
2461         return (0);
2462 }
2463
2464 int
2465 pf_get_sport(sa_family_t af, u_int8_t proto, struct pf_rule *r,
2466     struct pf_addr *saddr, struct pf_addr *daddr, u_int16_t dport,
2467     struct pf_addr *naddr, u_int16_t *nport, u_int16_t low, u_int16_t high,
2468     struct pf_src_node **sn)
2469 {
2470         struct pf_state_key_cmp key;
2471         struct pf_addr          init_addr;
2472         u_int16_t               cut;
2473
2474         bzero(&init_addr, sizeof(init_addr));
2475         if (pf_map_addr(af, r, saddr, naddr, &init_addr, sn))
2476                 return (1);
2477
2478         if (proto == IPPROTO_ICMP) {
2479                 low = 1;
2480                 high = 65535;
2481         }
2482
2483         do {
2484                 key.af = af;
2485                 key.proto = proto;
2486                 PF_ACPY(&key.addr[1], daddr, key.af);
2487                 PF_ACPY(&key.addr[0], naddr, key.af);
2488                 key.port[1] = dport;
2489
2490                 /*
2491                  * port search; start random, step;
2492                  * similar 2 portloop in in_pcbbind
2493                  */
2494                 if (!(proto == IPPROTO_TCP || proto == IPPROTO_UDP ||
2495                     proto == IPPROTO_ICMP)) {
2496                         key.port[0] = dport;
2497                         if (pf_find_state_all(&key, PF_IN, NULL) == NULL)
2498                                 return (0);
2499                 } else if (low == 0 && high == 0) {
2500                         key.port[0] = *nport;
2501                         if (pf_find_state_all(&key, PF_IN, NULL) == NULL)
2502                                 return (0);
2503                 } else if (low == high) {
2504                         key.port[0] = htons(low);
2505                         if (pf_find_state_all(&key, PF_IN, NULL) == NULL) {
2506                                 *nport = htons(low);
2507                                 return (0);
2508                         }
2509                 } else {
2510                         u_int16_t tmp;
2511
2512                         if (low > high) {
2513                                 tmp = low;
2514                                 low = high;
2515                                 high = tmp;
2516                         }
2517                         /* low < high */
2518                         cut = htonl(karc4random()) % (1 + high - low) + low;
2519                         /* low <= cut <= high */
2520                         for (tmp = cut; tmp <= high; ++(tmp)) {
2521                                 key.port[0] = htons(tmp);
2522                                 if (pf_find_state_all(&key, PF_IN, NULL) ==
2523                                     NULL && !in_baddynamic(tmp, proto)) {
2524                                         *nport = htons(tmp);
2525                                         return (0);
2526                                 }
2527                         }
2528                         for (tmp = cut - 1; tmp >= low; --(tmp)) {
2529                                 key.port[0] = htons(tmp);
2530                                 if (pf_find_state_all(&key, PF_IN, NULL) ==
2531                                     NULL && !in_baddynamic(tmp, proto)) {
2532                                         *nport = htons(tmp);
2533                                         return (0);
2534                                 }
2535                         }
2536                 }
2537
2538                 switch (r->rpool.opts & PF_POOL_TYPEMASK) {
2539                 case PF_POOL_RANDOM:
2540                 case PF_POOL_ROUNDROBIN:
2541                         if (pf_map_addr(af, r, saddr, naddr, &init_addr, sn))
2542                                 return (1);
2543                         break;
2544                 case PF_POOL_NONE:
2545                 case PF_POOL_SRCHASH:
2546                 case PF_POOL_BITMASK:
2547                 default:
2548                         return (1);
2549                 }
2550         } while (! PF_AEQ(&init_addr, naddr, af) );
2551         return (1);                                     /* none available */
2552 }
2553
2554 struct pf_rule *
2555 pf_match_translation(struct pf_pdesc *pd, struct mbuf *m, int off,
2556     int direction, struct pfi_kif *kif, struct pf_addr *saddr, u_int16_t sport,
2557     struct pf_addr *daddr, u_int16_t dport, int rs_num)
2558 {
2559         struct pf_rule          *r, *rm = NULL;
2560         struct pf_ruleset       *ruleset = NULL;
2561         int                      tag = -1;
2562         int                      rtableid = -1;
2563         int                      asd = 0;
2564
2565         r = TAILQ_FIRST(pf_main_ruleset.rules[rs_num].active.ptr);
2566         while (r && rm == NULL) {
2567                 struct pf_rule_addr     *src = NULL, *dst = NULL;
2568                 struct pf_addr_wrap     *xdst = NULL;
2569
2570                 if (r->action == PF_BINAT && direction == PF_IN) {
2571                         src = &r->dst;
2572                         if (r->rpool.cur != NULL)
2573                                 xdst = &r->rpool.cur->addr;
2574                 } else {
2575                         src = &r->src;
2576                         dst = &r->dst;
2577                 }
2578
2579                 r->evaluations++;
2580                 if (pfi_kif_match(r->kif, kif) == r->ifnot)
2581                         r = r->skip[PF_SKIP_IFP].ptr;
2582                 else if (r->direction && r->direction != direction)
2583                         r = r->skip[PF_SKIP_DIR].ptr;
2584                 else if (r->af && r->af != pd->af)
2585                         r = r->skip[PF_SKIP_AF].ptr;
2586                 else if (r->proto && r->proto != pd->proto)
2587                         r = r->skip[PF_SKIP_PROTO].ptr;
2588                 else if (PF_MISMATCHAW(&src->addr, saddr, pd->af,
2589                     src->neg, kif))
2590                         r = r->skip[src == &r->src ? PF_SKIP_SRC_ADDR :
2591                             PF_SKIP_DST_ADDR].ptr;
2592                 else if (src->port_op && !pf_match_port(src->port_op,
2593                     src->port[0], src->port[1], sport))
2594                         r = r->skip[src == &r->src ? PF_SKIP_SRC_PORT :
2595                             PF_SKIP_DST_PORT].ptr;
2596                 else if (dst != NULL &&
2597                     PF_MISMATCHAW(&dst->addr, daddr, pd->af, dst->neg, NULL))
2598                         r = r->skip[PF_SKIP_DST_ADDR].ptr;
2599                 else if (xdst != NULL && PF_MISMATCHAW(xdst, daddr, pd->af,
2600                     0, NULL))
2601                         r = TAILQ_NEXT(r, entries);
2602                 else if (dst != NULL && dst->port_op &&
2603                     !pf_match_port(dst->port_op, dst->port[0],
2604                     dst->port[1], dport))
2605                         r = r->skip[PF_SKIP_DST_PORT].ptr;
2606                 else if (r->match_tag && !pf_match_tag(m, r, &tag))
2607                         r = TAILQ_NEXT(r, entries);
2608                 else if (r->os_fingerprint != PF_OSFP_ANY && (pd->proto !=
2609                     IPPROTO_TCP || !pf_osfp_match(pf_osfp_fingerprint(pd, m,
2610                     off, pd->hdr.tcp), r->os_fingerprint)))
2611                         r = TAILQ_NEXT(r, entries);
2612                 else {
2613                         if (r->tag)
2614                                 tag = r->tag;
2615                         if (r->rtableid >= 0)
2616                                 rtableid = r->rtableid;
2617                         if (r->anchor == NULL) {
2618                                 rm = r;
2619                         } else
2620                                 pf_step_into_anchor(&asd, &ruleset, rs_num,
2621                                     &r, NULL, NULL);
2622                 }
2623                 if (r == NULL)
2624                         pf_step_out_of_anchor(&asd, &ruleset, rs_num, &r,
2625                             NULL, NULL);
2626         }
2627         if (pf_tag_packet(m, tag, rtableid))
2628                 return (NULL);
2629         if (rm != NULL && (rm->action == PF_NONAT ||
2630             rm->action == PF_NORDR || rm->action == PF_NOBINAT))
2631                 return (NULL);
2632         return (rm);
2633 }
2634
2635 struct pf_rule *
2636 pf_get_translation(struct pf_pdesc *pd, struct mbuf *m, int off, int direction,
2637     struct pfi_kif *kif, struct pf_src_node **sn,
2638     struct pf_state_key **skw, struct pf_state_key **sks,
2639     struct pf_state_key **skp, struct pf_state_key **nkp,
2640     struct pf_addr *saddr, struct pf_addr *daddr,
2641     u_int16_t sport, u_int16_t dport)
2642 {
2643         struct pf_rule  *r = NULL;
2644
2645
2646         if (direction == PF_OUT) {
2647                 r = pf_match_translation(pd, m, off, direction, kif, saddr,
2648                     sport, daddr, dport, PF_RULESET_BINAT);
2649                 if (r == NULL)
2650                         r = pf_match_translation(pd, m, off, direction, kif,
2651                             saddr, sport, daddr, dport, PF_RULESET_NAT);
2652         } else {
2653                 r = pf_match_translation(pd, m, off, direction, kif, saddr,
2654                     sport, daddr, dport, PF_RULESET_RDR);
2655                 if (r == NULL)
2656                         r = pf_match_translation(pd, m, off, direction, kif,
2657                             saddr, sport, daddr, dport, PF_RULESET_BINAT);
2658         }
2659
2660         if (r != NULL) {
2661                 struct pf_addr  *naddr;
2662                 u_int16_t       *nport;
2663
2664                 if (pf_state_key_setup(pd, r, skw, sks, skp, nkp,
2665                     saddr, daddr, sport, dport))
2666                         return r;
2667
2668                 /* XXX We only modify one side for now. */
2669                 naddr = &(*nkp)->addr[1];
2670                 nport = &(*nkp)->port[1];
2671
2672                 switch (r->action) {
2673                 case PF_NONAT:
2674                 case PF_NOBINAT:
2675                 case PF_NORDR:
2676                         return (NULL);
2677                 case PF_NAT:
2678                         if (pf_get_sport(pd->af, pd->proto, r, saddr,
2679                             daddr, dport, naddr, nport, r->rpool.proxy_port[0],
2680                             r->rpool.proxy_port[1], sn)) {
2681                                 DPFPRINTF(PF_DEBUG_MISC,
2682                                     ("pf: NAT proxy port allocation "
2683                                     "(%u-%u) failed\n",
2684                                     r->rpool.proxy_port[0],
2685                                     r->rpool.proxy_port[1]));
2686                                 return (NULL);
2687                         }
2688                         break;
2689                 case PF_BINAT:
2690                         switch (direction) {
2691                         case PF_OUT:
2692                                 if (r->rpool.cur->addr.type == PF_ADDR_DYNIFTL){
2693                                         switch (pd->af) {
2694 #ifdef INET
2695                                         case AF_INET:
2696                                                 if (r->rpool.cur->addr.p.dyn->
2697                                                     pfid_acnt4 < 1)
2698                                                         return (NULL);
2699                                                 PF_POOLMASK(naddr,
2700                                                     &r->rpool.cur->addr.p.dyn->
2701                                                     pfid_addr4,
2702                                                     &r->rpool.cur->addr.p.dyn->
2703                                                     pfid_mask4,
2704                                                     saddr, AF_INET);
2705                                                 break;
2706 #endif /* INET */
2707 #ifdef INET6
2708                                         case AF_INET6:
2709                                                 if (r->rpool.cur->addr.p.dyn->
2710                                                     pfid_acnt6 < 1)
2711                                                         return (NULL);
2712                                                 PF_POOLMASK(naddr,
2713                                                     &r->rpool.cur->addr.p.dyn->
2714                                                     pfid_addr6,
2715                                                     &r->rpool.cur->addr.p.dyn->
2716                                                     pfid_mask6,
2717                                                     saddr, AF_INET6);
2718                                                 break;
2719 #endif /* INET6 */
2720                                         }
2721                                 } else
2722                                         PF_POOLMASK(naddr,
2723                                             &r->rpool.cur->addr.v.a.addr,
2724                                             &r->rpool.cur->addr.v.a.mask,
2725                                             saddr, pd->af);
2726                                 break;
2727                         case PF_IN:
2728                                 if (r->src.addr.type == PF_ADDR_DYNIFTL) {
2729                                         switch (pd->af) {
2730 #ifdef INET
2731                                         case AF_INET:
2732                                                 if (r->src.addr.p.dyn->
2733                                                     pfid_acnt4 < 1)
2734                                                         return (NULL);
2735                                                 PF_POOLMASK(naddr,
2736                                                     &r->src.addr.p.dyn->
2737                                                     pfid_addr4,
2738                                                     &r->src.addr.p.dyn->
2739                                                     pfid_mask4,
2740                                                     daddr, AF_INET);
2741                                                 break;
2742 #endif /* INET */
2743 #ifdef INET6
2744                                         case AF_INET6:
2745                                                 if (r->src.addr.p.dyn->
2746                                                     pfid_acnt6 < 1)
2747                                                         return (NULL);
2748                                                 PF_POOLMASK(naddr,
2749                                                     &r->src.addr.p.dyn->
2750                                                     pfid_addr6,
2751                                                     &r->src.addr.p.dyn->
2752                                                     pfid_mask6,
2753                                                     daddr, AF_INET6);
2754                                                 break;
2755 #endif /* INET6 */
2756                                         }
2757                                 } else
2758                                         PF_POOLMASK(naddr,
2759                                             &r->src.addr.v.a.addr,
2760                                             &r->src.addr.v.a.mask, daddr,
2761                                             pd->af);
2762                                 break;
2763                         }
2764                         break;
2765                 case PF_RDR: {
2766                         if (pf_map_addr(pd->af, r, saddr, naddr, NULL, sn))
2767                                 return (NULL);
2768                         if ((r->rpool.opts & PF_POOL_TYPEMASK) ==
2769                             PF_POOL_BITMASK)
2770                                 PF_POOLMASK(naddr, naddr,
2771                                     &r->rpool.cur->addr.v.a.mask, daddr,
2772                                     pd->af);
2773
2774                         if (r->rpool.proxy_port[1]) {
2775                                 u_int32_t       tmp_nport;
2776
2777                                 tmp_nport = ((ntohs(dport) -
2778                                     ntohs(r->dst.port[0])) %
2779                                     (r->rpool.proxy_port[1] -
2780                                     r->rpool.proxy_port[0] + 1)) +
2781                                     r->rpool.proxy_port[0];
2782
2783                                 /* wrap around if necessary */
2784                                 if (tmp_nport > 65535)
2785                                         tmp_nport -= 65535;
2786                                 *nport = htons((u_int16_t)tmp_nport);
2787                         } else if (r->rpool.proxy_port[0])
2788                                 *nport = htons(r->rpool.proxy_port[0]);
2789                         break;
2790                 }
2791                 default:
2792                         return (NULL);
2793                 }
2794         }
2795
2796         return (r);
2797 }
2798
2799 #ifdef SMP
2800 struct netmsg_hashlookup {
2801         struct netmsg_base      base;
2802         struct inpcb            **nm_pinp;
2803         struct inpcbinfo        *nm_pcbinfo;
2804         struct pf_addr          *nm_saddr;
2805         struct pf_addr          *nm_daddr;
2806         uint16_t                nm_sport;
2807         uint16_t                nm_dport;
2808         sa_family_t             nm_af;
2809 };
2810
2811 #ifdef PF_SOCKET_LOOKUP_DOMSG
2812 static void
2813 in_pcblookup_hash_handler(netmsg_t msg)
2814 {
2815         struct netmsg_hashlookup *rmsg = (struct netmsg_hashlookup *)msg;
2816
2817         if (rmsg->nm_af == AF_INET)
2818                 *rmsg->nm_pinp = in_pcblookup_hash(rmsg->nm_pcbinfo,
2819                     rmsg->nm_saddr->v4, rmsg->nm_sport, rmsg->nm_daddr->v4,
2820                     rmsg->nm_dport, INPLOOKUP_WILDCARD, NULL);
2821 #ifdef INET6
2822         else
2823                 *rmsg->nm_pinp = in6_pcblookup_hash(rmsg->nm_pcbinfo,
2824                     &rmsg->nm_saddr->v6, rmsg->nm_sport, &rmsg->nm_daddr->v6,
2825                     rmsg->nm_dport, INPLOOKUP_WILDCARD, NULL);
2826 #endif /* INET6 */
2827         lwkt_replymsg(&rmsg->base.lmsg, 0);
2828 }
2829 #endif  /* PF_SOCKET_LOOKUP_DOMSG */
2830
2831 #endif /* SMP */
2832
2833 int
2834 pf_socket_lookup(int direction, struct pf_pdesc *pd)
2835 {
2836         struct pf_addr          *saddr, *daddr;
2837         u_int16_t                sport, dport;
2838         struct inpcbinfo        *pi;
2839         struct inpcb            *inp;
2840 #ifdef SMP
2841         struct netmsg_hashlookup *msg = NULL;
2842 #ifdef PF_SOCKET_LOOKUP_DOMSG
2843         struct netmsg_hashlookup msg0;
2844 #endif
2845 #endif
2846         int                      pi_cpu = 0;
2847
2848         if (pd == NULL)
2849                 return (-1);
2850         pd->lookup.uid = UID_MAX;
2851         pd->lookup.gid = GID_MAX;
2852         pd->lookup.pid = NO_PID;
2853         if (direction == PF_IN) {
2854                 saddr = pd->src;
2855                 daddr = pd->dst;
2856         } else {
2857                 saddr = pd->dst;
2858                 daddr = pd->src;
2859         }
2860         switch (pd->proto) {
2861         case IPPROTO_TCP:
2862                 if (pd->hdr.tcp == NULL)
2863                         return (-1);
2864                 sport = pd->hdr.tcp->th_sport;
2865                 dport = pd->hdr.tcp->th_dport;
2866
2867                 pi_cpu = tcp_addrcpu(saddr->v4.s_addr, sport, daddr->v4.s_addr, dport);
2868                 pi = &tcbinfo[pi_cpu];
2869 #ifdef SMP
2870                 /*
2871                  * Our netstack runs lockless on MP systems
2872                  * (only for TCP connections at the moment).
2873                  * 
2874                  * As we are not allowed to read another CPU's tcbinfo,
2875                  * we have to ask that CPU via remote call to search the
2876                  * table for us.
2877                  * 
2878                  * Prepare a msg iff data belongs to another CPU.
2879                  */
2880                 if (pi_cpu != mycpu->gd_cpuid) {
2881 #ifdef PF_SOCKET_LOOKUP_DOMSG
2882                         /*
2883                          * NOTE:
2884                          *
2885                          * Following lwkt_domsg() is dangerous and could
2886                          * lockup the network system, e.g.
2887                          *
2888                          * On 2 CPU system:
2889                          * netisr0 domsg to netisr1 (due to lookup)
2890                          * netisr1 domsg to netisr0 (due to lookup)
2891                          *
2892                          * We simply return -1 here, since we are probably
2893                          * called before NAT, so the TCP packet should
2894                          * already be on the correct CPU.
2895                          */
2896                         msg = &msg0;
2897                         netmsg_init(&msg->base, NULL, &curthread->td_msgport,
2898                                     0, in_pcblookup_hash_handler);
2899                         msg->nm_pinp = &inp;
2900                         msg->nm_pcbinfo = pi;
2901                         msg->nm_saddr = saddr;
2902                         msg->nm_sport = sport;
2903                         msg->nm_daddr = daddr;
2904                         msg->nm_dport = dport;
2905                         msg->nm_af = pd->af;
2906 #else   /* !PF_SOCKET_LOOKUP_DOMSG */
2907                         kprintf("pf_socket_lookup: tcp packet not on the "
2908                                 "correct cpu %d, cur cpu %d\n",
2909                                 pi_cpu, mycpuid);
2910                         print_backtrace(-1);
2911                         return -1;
2912 #endif  /* PF_SOCKET_LOOKUP_DOMSG */
2913                 }
2914 #endif /* SMP */
2915                 break;
2916         case IPPROTO_UDP:
2917                 if (pd->hdr.udp == NULL)
2918                         return (-1);
2919                 sport = pd->hdr.udp->uh_sport;
2920                 dport = pd->hdr.udp->uh_dport;
2921                 pi = &udbinfo;
2922                 break;
2923         default:
2924                 return (-1);
2925         }
2926         if (direction != PF_IN) {
2927                 u_int16_t       p;
2928
2929                 p = sport;
2930                 sport = dport;
2931                 dport = p;
2932         }
2933         switch (pd->af) {
2934 #ifdef INET6
2935         case AF_INET6:
2936 #ifdef SMP
2937                 /*
2938                  * Query other CPU, second part
2939                  * 
2940                  * msg only gets initialized when:
2941                  * 1) packet is TCP
2942                  * 2) the info belongs to another CPU
2943                  *
2944                  * Use some switch/case magic to avoid code duplication.
2945                  */
2946                 if (msg == NULL)
2947 #endif /* SMP */
2948                 {
2949                         inp = in6_pcblookup_hash(pi, &saddr->v6, sport,
2950                             &daddr->v6, dport, INPLOOKUP_WILDCARD, NULL);
2951
2952                         if (inp == NULL)
2953                                 return (-1);
2954                         break;
2955                 }
2956                 /* FALLTHROUGH if SMP and on other CPU */
2957 #endif /* INET6 */
2958         case AF_INET:
2959 #ifdef SMP
2960                 if (msg != NULL) {
2961                         lwkt_domsg(cpu_portfn(pi_cpu),
2962                                      &msg->base.lmsg, 0);
2963                 } else
2964 #endif /* SMP */
2965                 {
2966                         inp = in_pcblookup_hash(pi, saddr->v4, sport, daddr->v4,
2967                             dport, INPLOOKUP_WILDCARD, NULL);
2968                 }
2969                 if (inp == NULL)
2970                         return (-1);
2971                 break;
2972
2973         default:
2974                 return (-1);
2975         }
2976         pd->lookup.uid = inp->inp_socket->so_cred->cr_uid;
2977         pd->lookup.gid = inp->inp_socket->so_cred->cr_groups[0];
2978         return (1);
2979 }
2980
2981 u_int8_t
2982 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2983 {
2984         int              hlen;
2985         u_int8_t         hdr[60];
2986         u_int8_t        *opt, optlen;
2987         u_int8_t         wscale = 0;
2988
2989         hlen = th_off << 2;             /* hlen <= sizeof(hdr) */
2990         if (hlen <= sizeof(struct tcphdr))
2991                 return (0);
2992         if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2993                 return (0);
2994         opt = hdr + sizeof(struct tcphdr);
2995         hlen -= sizeof(struct tcphdr);
2996         while (hlen >= 3) {
2997                 switch (*opt) {
2998                 case TCPOPT_EOL:
2999                 case TCPOPT_NOP:
3000                         ++opt;
3001                         --hlen;
3002                         break;
3003                 case TCPOPT_WINDOW:
3004                         wscale = opt[2];
3005                         if (wscale > TCP_MAX_WINSHIFT)
3006                                 wscale = TCP_MAX_WINSHIFT;
3007                         wscale |= PF_WSCALE_FLAG;
3008                         /* FALLTHROUGH */
3009                 default:
3010                         optlen = opt[1];
3011                         if (optlen < 2)
3012                                 optlen = 2;
3013                         hlen -= optlen;
3014                         opt += optlen;
3015                         break;
3016                 }
3017         }
3018         return (wscale);
3019 }
3020
3021 u_int16_t
3022 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3023 {
3024         int              hlen;
3025         u_int8_t         hdr[60];
3026         u_int8_t        *opt, optlen;
3027         u_int16_t        mss = tcp_mssdflt;
3028
3029         hlen = th_off << 2;     /* hlen <= sizeof(hdr) */
3030         if (hlen <= sizeof(struct tcphdr))
3031                 return (0);
3032         if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3033                 return (0);
3034         opt = hdr + sizeof(struct tcphdr);
3035         hlen -= sizeof(struct tcphdr);
3036         while (hlen >= TCPOLEN_MAXSEG) {
3037                 switch (*opt) {
3038                 case TCPOPT_EOL:
3039                 case TCPOPT_NOP:
3040                         ++opt;
3041                         --hlen;
3042                         break;
3043                 case TCPOPT_MAXSEG:
3044                         bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
3045                         /* FALLTHROUGH */
3046                 default:
3047                         optlen = opt[1];
3048                         if (optlen < 2)
3049                                 optlen = 2;
3050                         hlen -= optlen;
3051                         opt += optlen;
3052                         break;
3053                 }
3054         }
3055         return (mss);
3056 }
3057
3058 u_int16_t
3059 pf_calc_mss(struct pf_addr *addr, sa_family_t af, u_int16_t offer)
3060 {
3061 #ifdef INET
3062         struct sockaddr_in      *dst;
3063         struct route             ro;
3064 #endif /* INET */
3065 #ifdef INET6
3066         struct sockaddr_in6     *dst6;
3067         struct route_in6         ro6;
3068 #endif /* INET6 */
3069         struct rtentry          *rt = NULL;
3070         int                      hlen = 0;
3071         u_int16_t                mss = tcp_mssdflt;
3072
3073         switch (af) {
3074 #ifdef INET
3075         case AF_INET:
3076                 hlen = sizeof(struct ip);
3077                 bzero(&ro, sizeof(ro));
3078                 dst = (struct sockaddr_in *)&ro.ro_dst;
3079                 dst->sin_family = AF_INET;
3080                 dst->sin_len = sizeof(*dst);
3081                 dst->sin_addr = addr->v4;
3082                 rtalloc_ign(&ro, (RTF_CLONING | RTF_PRCLONING));
3083                 rt = ro.ro_rt;
3084                 break;
3085 #endif /* INET */
3086 #ifdef INET6
3087         case AF_INET6:
3088                 hlen = sizeof(struct ip6_hdr);
3089                 bzero(&ro6, sizeof(ro6));
3090                 dst6 = (struct sockaddr_in6 *)&ro6.ro_dst;
3091                 dst6->sin6_family = AF_INET6;
3092                 dst6->sin6_len = sizeof(*dst6);
3093                 dst6->sin6_addr = addr->v6;
3094                 rtalloc_ign((struct route *)&ro6, (RTF_CLONING | RTF_PRCLONING));
3095                 rt = ro6.ro_rt;
3096                 break;
3097 #endif /* INET6 */
3098         }
3099
3100         if (rt && rt->rt_ifp) {
3101                 mss = rt->rt_ifp->if_mtu - hlen - sizeof(struct tcphdr);
3102                 mss = max(tcp_mssdflt, mss);
3103                 RTFREE(rt);
3104         }
3105         mss = min(mss, offer);
3106         mss = max(mss, 64);             /* sanity - at least max opt space */
3107         return (mss);
3108 }
3109
3110 void
3111 pf_set_rt_ifp(struct pf_state *s, struct pf_addr *saddr)
3112 {
3113         struct pf_rule *r = s->rule.ptr;
3114
3115         s->rt_kif = NULL;
3116         if (!r->rt || r->rt == PF_FASTROUTE)
3117                 return;
3118         switch (s->key[PF_SK_WIRE]->af) {
3119 #ifdef INET
3120         case AF_INET:
3121                 pf_map_addr(AF_INET, r, saddr, &s->rt_addr, NULL,
3122                     &s->nat_src_node);
3123                 s->rt_kif = r->rpool.cur->kif;
3124                 break;
3125 #endif /* INET */
3126 #ifdef INET6
3127         case AF_INET6:
3128                 pf_map_addr(AF_INET6, r, saddr, &s->rt_addr, NULL,
3129                     &s->nat_src_node);
3130                 s->rt_kif = r->rpool.cur->kif;
3131                 break;
3132 #endif /* INET6 */
3133         }
3134 }
3135
3136 u_int32_t
3137 pf_tcp_iss(struct pf_pdesc *pd)
3138 {
3139         MD5_CTX ctx;
3140         u_int32_t digest[4];
3141
3142         if (pf_tcp_secret_init == 0) {
3143                 karc4rand(pf_tcp_secret, sizeof(pf_tcp_secret));
3144                 MD5Init(&pf_tcp_secret_ctx);
3145                 MD5Update(&pf_tcp_secret_ctx, pf_tcp_secret,
3146                     sizeof(pf_tcp_secret));
3147                 pf_tcp_secret_init = 1;
3148         }
3149         ctx = pf_tcp_secret_ctx;
3150
3151         MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
3152         MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
3153         if (pd->af == AF_INET6) {
3154                 MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
3155                 MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
3156         } else {
3157                 MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
3158                 MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
3159         }
3160         MD5Final((u_char *)digest, &ctx);
3161         pf_tcp_iss_off += 4096;
3162         return (digest[0] + pd->hdr.tcp->th_seq + pf_tcp_iss_off);
3163 }
3164
3165 int
3166 pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
3167     struct pfi_kif *kif, struct mbuf *m, int off, void *h,
3168     struct pf_pdesc *pd, struct pf_rule **am, struct pf_ruleset **rsm,
3169     struct ifqueue *ifq, struct inpcb *inp)
3170 {
3171         struct pf_rule          *nr = NULL;
3172         struct pf_addr          *saddr = pd->src, *daddr = pd->dst;
3173         sa_family_t              af = pd->af;
3174         struct pf_rule          *r, *a = NULL;
3175         struct pf_ruleset       *ruleset = NULL;
3176         struct pf_src_node      *nsn = NULL;
3177         struct tcphdr           *th = pd->hdr.tcp;
3178         struct pf_state_key     *skw = NULL, *sks = NULL;
3179         struct pf_state_key     *sk = NULL, *nk = NULL;
3180         u_short                  reason;
3181         int                      rewrite = 0, hdrlen = 0;
3182         int                      tag = -1, rtableid = -1;
3183         int                      asd = 0;
3184         int                      match = 0;
3185         int                      state_icmp = 0;
3186         u_int16_t                sport = 0, dport = 0;
3187         u_int16_t                nport = 0, bport = 0;
3188         u_int16_t                bproto_sum = 0, bip_sum = 0;
3189         u_int8_t                 icmptype = 0, icmpcode = 0;
3190
3191
3192         if (direction == PF_IN && pf_check_congestion(ifq)) {
3193                 REASON_SET(&reason, PFRES_CONGEST);
3194                 return (PF_DROP);
3195         }
3196
3197         if (inp != NULL)
3198                 pd->lookup.done = pf_socket_lookup(direction, pd);
3199         else if (debug_pfugidhack) { 
3200                 DPFPRINTF(PF_DEBUG_MISC, ("pf: unlocked lookup\n"));
3201                 pd->lookup.done = pf_socket_lookup(direction, pd);
3202         }
3203
3204         switch (pd->proto) {
3205         case IPPROTO_TCP:
3206                 sport = th->th_sport;
3207                 dport = th->th_dport;
3208                 hdrlen = sizeof(*th);
3209                 break;
3210         case IPPROTO_UDP:
3211                 sport = pd->hdr.udp->uh_sport;
3212                 dport = pd->hdr.udp->uh_dport;
3213                 hdrlen = sizeof(*pd->hdr.udp);
3214                 break;
3215 #ifdef INET
3216         case IPPROTO_ICMP:
3217                 if (pd->af != AF_INET)
3218                         break;
3219                 sport = dport = pd->hdr.icmp->icmp_id;
3220                 hdrlen = sizeof(*pd->hdr.icmp);
3221                 icmptype = pd->hdr.icmp->icmp_type;
3222                 icmpcode = pd->hdr.icmp->icmp_code;
3223
3224                 if (icmptype == ICMP_UNREACH ||
3225                     icmptype == ICMP_SOURCEQUENCH ||
3226                     icmptype == ICMP_REDIRECT ||
3227                     icmptype == ICMP_TIMXCEED ||
3228                     icmptype == ICMP_PARAMPROB)
3229                         state_icmp++;
3230                 break;
3231 #endif /* INET */
3232 #ifdef INET6
3233         case IPPROTO_ICMPV6:
3234                 if (af != AF_INET6)
3235                         break;
3236                 sport = dport = pd->hdr.icmp6->icmp6_id;
3237                 hdrlen = sizeof(*pd->hdr.icmp6);
3238                 icmptype = pd->hdr.icmp6->icmp6_type;
3239                 icmpcode = pd->hdr.icmp6->icmp6_code;
3240
3241                 if (icmptype == ICMP6_DST_UNREACH ||
3242                     icmptype == ICMP6_PACKET_TOO_BIG ||
3243                     icmptype == ICMP6_TIME_EXCEEDED ||
3244                     icmptype == ICMP6_PARAM_PROB)
3245                         state_icmp++;
3246                 break;
3247 #endif /* INET6 */
3248         default:
3249                 sport = dport = hdrlen = 0;
3250                 break;
3251         }
3252
3253         r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3254
3255         bport = nport = sport;
3256         /* check packet for BINAT/NAT/RDR */
3257         if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn,
3258             &skw, &sks, &sk, &nk, saddr, daddr, sport, dport)) != NULL) {
3259                 if (nk == NULL || sk == NULL) {
3260                         REASON_SET(&reason, PFRES_MEMORY);
3261                         goto cleanup;
3262                 }
3263
3264                 if (pd->ip_sum)
3265                         bip_sum = *pd->ip_sum;
3266
3267                 switch (pd->proto) {
3268                 case IPPROTO_TCP:
3269                         bproto_sum = th->th_sum;
3270                         pd->proto_sum = &th->th_sum;
3271
3272                         if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3273                             nk->port[pd->sidx] != sport) {
3274                                 pf_change_ap(saddr, &th->th_sport, pd->ip_sum,
3275                                     &th->th_sum, &nk->addr[pd->sidx],
3276                                     nk->port[pd->sidx], 0, af);
3277                                 pd->sport = &th->th_sport;
3278                                 sport = th->th_sport;
3279                         }
3280
3281                         if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3282                             nk->port[pd->didx] != dport) {
3283                                 pf_change_ap(daddr, &th->th_dport, pd->ip_sum,
3284                                     &th->th_sum, &nk->addr[pd->didx],
3285                                     nk->port[pd->didx], 0, af);
3286                                 dport = th->th_dport;
3287                                 pd->dport = &th->th_dport;
3288                         }
3289                         rewrite++;
3290                         break;
3291                 case IPPROTO_UDP:
3292                         bproto_sum = pd->hdr.udp->uh_sum;
3293                         pd->proto_sum = &pd->hdr.udp->uh_sum;
3294
3295                         if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3296                             nk->port[pd->sidx] != sport) {
3297                                 pf_change_ap(saddr, &pd->hdr.udp->uh_sport,
3298                                     pd->ip_sum, &pd->hdr.udp->uh_sum,
3299                                     &nk->addr[pd->sidx],
3300                                     nk->port[pd->sidx], 1, af);
3301                                 sport = pd->hdr.udp->uh_sport;
3302                                 pd->sport = &pd->hdr.udp->uh_sport;
3303                         }
3304
3305                         if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3306                             nk->port[pd->didx] != dport) {
3307                                 pf_change_ap(daddr, &pd->hdr.udp->uh_dport,
3308                                     pd->ip_sum, &pd->hdr.udp->uh_sum,
3309                                     &nk->addr[pd->didx],
3310                                     nk->port[pd->didx], 1, af);
3311                                 dport = pd->hdr.udp->uh_dport;
3312                                 pd->dport = &pd->hdr.udp->uh_dport;
3313                         }
3314                         rewrite++;
3315                         break;
3316 #ifdef INET
3317                 case IPPROTO_ICMP:
3318                         nk->port[0] = nk->port[1];
3319                         if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3320                                 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3321                                     nk->addr[pd->sidx].v4.s_addr, 0);
3322
3323                         if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3324                                 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3325                                     nk->addr[pd->didx].v4.s_addr, 0);
3326
3327                         if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3328                                 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3329                                     pd->hdr.icmp->icmp_cksum, sport,
3330                                     nk->port[1], 0);
3331                                 pd->hdr.icmp->icmp_id = nk->port[1];
3332                                 pd->sport = &pd->hdr.icmp->icmp_id;
3333                         }
3334                         m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3335                         break;
3336 #endif /* INET */
3337 #ifdef INET6
3338                 case IPPROTO_ICMPV6:
3339                         nk->port[0] = nk->port[1];
3340                         if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3341                                 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3342                                     &nk->addr[pd->sidx], 0);
3343
3344                         if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3345                                 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3346                                     &nk->addr[pd->didx], 0);
3347                         rewrite++;
3348                         break;
3349 #endif /* INET */
3350                 default:
3351                         switch (af) {
3352 #ifdef INET
3353                         case AF_INET:
3354                                 if (PF_ANEQ(saddr,
3355                                     &nk->addr[pd->sidx], AF_INET))
3356                                         pf_change_a(&saddr->v4.s_addr,
3357                                             pd->ip_sum,
3358                                             nk->addr[pd->sidx].v4.s_addr, 0);
3359
3360                                 if (PF_ANEQ(daddr,
3361                                     &nk->addr[pd->didx], AF_INET))
3362                                         pf_change_a(&daddr->v4.s_addr,
3363                                             pd->ip_sum,
3364                                             nk->addr[pd->didx].v4.s_addr, 0);
3365                                 break;
3366 #endif /* INET */
3367 #ifdef INET6
3368                         case AF_INET6:
3369                                 if (PF_ANEQ(saddr,
3370                                     &nk->addr[pd->sidx], AF_INET6))
3371                                         PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3372
3373                                 if (PF_ANEQ(daddr,
3374                                     &nk->addr[pd->didx], AF_INET6))
3375                                         PF_ACPY(saddr, &nk->addr[pd->didx], af);
3376                                 break;
3377 #endif /* INET */
3378                         }
3379                         break;
3380                 }
3381                 if (nr->natpass)
3382                         r = NULL;
3383                 pd->nat_rule = nr;
3384         }
3385
3386         while (r != NULL) {
3387                 r->evaluations++;
3388                 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3389                         r = r->skip[PF_SKIP_IFP].ptr;
3390                 else if (r->direction && r->direction != direction)
3391                         r = r->skip[PF_SKIP_DIR].ptr;
3392                 else if (r->af && r->af != af)
3393                         r = r->skip[PF_SKIP_AF].ptr;
3394                 else if (r->proto && r->proto != pd->proto)
3395                         r = r->skip[PF_SKIP_PROTO].ptr;
3396                 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3397                     r->src.neg, kif))
3398                         r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3399                 /* tcp/udp only. port_op always 0 in other cases */
3400                 else if (r->src.port_op && !pf_match_port(r->src.port_op,
3401                     r->src.port[0], r->src.port[1], sport))
3402                         r = r->skip[PF_SKIP_SRC_PORT].ptr;
3403                 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3404                     r->dst.neg, NULL))
3405                         r = r->skip[PF_SKIP_DST_ADDR].ptr;
3406                 /* tcp/udp only. port_op always 0 in other cases */
3407                 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3408                     r->dst.port[0], r->dst.port[1], dport))
3409                         r = r->skip[PF_SKIP_DST_PORT].ptr;
3410                 /* icmp only. type always 0 in other cases */
3411                 else if (r->type && r->type != icmptype + 1)
3412                         r = TAILQ_NEXT(r, entries);
3413                 /* icmp only. type always 0 in other cases */
3414                 else if (r->code && r->code != icmpcode + 1)
3415                         r = TAILQ_NEXT(r, entries);
3416                 else if (r->tos && !(r->tos == pd->tos))
3417                         r = TAILQ_NEXT(r, entries);
3418                 else if (r->rule_flag & PFRULE_FRAGMENT)
3419                         r = TAILQ_NEXT(r, entries);
3420                 else if (pd->proto == IPPROTO_TCP &&
3421                     (r->flagset & th->th_flags) != r->flags)
3422                         r = TAILQ_NEXT(r, entries);
3423                 /* tcp/udp only. uid.op always 0 in other cases */
3424                 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3425                     pf_socket_lookup(direction, pd), 1)) &&
3426                     !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3427                     pd->lookup.uid))
3428                         r = TAILQ_NEXT(r, entries);
3429                 /* tcp/udp only. gid.op always 0 in other cases */
3430                 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3431                     pf_socket_lookup(direction, pd), 1)) &&
3432                     !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3433                     pd->lookup.gid))
3434                         r = TAILQ_NEXT(r, entries);
3435                 else if (r->prob &&
3436                   r->prob <= karc4random())
3437                         r = TAILQ_NEXT(r, entries);
3438                 else if (r->match_tag && !pf_match_tag(m, r, &tag))
3439                         r = TAILQ_NEXT(r, entries);
3440                 else if (r->os_fingerprint != PF_OSFP_ANY &&
3441                     (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3442                     pf_osfp_fingerprint(pd, m, off, th),
3443                     r->os_fingerprint)))
3444                         r = TAILQ_NEXT(r, entries);
3445                 else {
3446                         if (r->tag)
3447                                 tag = r->tag;
3448                         if (r->rtableid >= 0)
3449                                 rtableid = r->rtableid;
3450                         if (r->anchor == NULL) {
3451                                 match = 1;
3452                                 *rm = r;
3453                                 *am = a;
3454                                 *rsm = ruleset;
3455                                 if ((*rm)->quick)
3456                                         break;
3457                                 r = TAILQ_NEXT(r, entries);
3458                         } else
3459                                 pf_step_into_anchor(&asd, &ruleset,
3460                                     PF_RULESET_FILTER, &r, &a, &match);
3461                 }
3462                 if (r == NULL && pf_step_out_of_anchor(&asd, &ruleset,
3463                     PF_RULESET_FILTER, &r, &a, &match))
3464                         break;
3465         }
3466         r = *rm;
3467         a = *am;
3468         ruleset = *rsm;
3469
3470         REASON_SET(&reason, PFRES_MATCH);
3471
3472         if (r->log || (nr != NULL && nr->log)) {
3473                 if (rewrite)
3474                         m_copyback(m, off, hdrlen, pd->hdr.any);
3475                 PFLOG_PACKET(kif, h, m, af, direction, reason, r->log ? r : nr,
3476                     a, ruleset, pd);
3477         }
3478
3479         if ((r->action == PF_DROP) &&
3480             ((r->rule_flag & PFRULE_RETURNRST) ||
3481             (r->rule_flag & PFRULE_RETURNICMP) ||
3482             (r->rule_flag & PFRULE_RETURN))) {
3483                 /* undo NAT changes, if they have taken place */
3484                 if (nr != NULL) {
3485                         PF_ACPY(saddr, &sk->addr[pd->sidx], af);
3486                         PF_ACPY(daddr, &sk->addr[pd->didx], af);
3487                         if (pd->sport)
3488                                 *pd->sport = sk->port[pd->sidx];
3489                         if (pd->dport)
3490                                 *pd->dport = sk->port[pd->didx];
3491                         if (pd->proto_sum)
3492                                 *pd->proto_sum = bproto_sum;
3493                         if (pd->ip_sum)
3494                                 *pd->ip_sum = bip_sum;
3495                         m_copyback(m, off, hdrlen, pd->hdr.any);
3496                 }
3497                 if (pd->proto == IPPROTO_TCP &&
3498                     ((r->rule_flag & PFRULE_RETURNRST) ||
3499                     (r->rule_flag & PFRULE_RETURN)) &&
3500                     !(th->th_flags & TH_RST)) {
3501                         u_int32_t        ack = ntohl(th->th_seq) + pd->p_len;
3502                         int              len = 0;
3503                         struct ip       *h4;
3504                         struct ip6_hdr  *h6;
3505
3506                         switch (af) {
3507                         case AF_INET:
3508                                 h4 = mtod(m, struct ip *);
3509                                 len = h4->ip_len - off;
3510                                 break;
3511 #ifdef INET6
3512                         case AF_INET6:
3513                                 h6 = mtod(m, struct ip6_hdr *);
3514                                 len = h6->ip6_plen - (off - sizeof(*h6));
3515                                 break;
3516 #endif
3517                         }
3518
3519                         if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
3520                                 REASON_SET(&reason, PFRES_PROTCKSUM);
3521                         else {
3522                                 if (th->th_flags & TH_SYN)
3523                                         ack++;
3524                                 if (th->th_flags & TH_FIN)
3525                                         ack++;
3526                                 pf_send_tcp(r, af, pd->dst,
3527                                     pd->src, th->th_dport, th->th_sport,
3528                                     ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
3529                                     r->return_ttl, 1, 0, pd->eh, kif->pfik_ifp);
3530                         }
3531                 } else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
3532                     r->return_icmp)
3533                         pf_send_icmp(m, r->return_icmp >> 8,
3534                             r->return_icmp & 255, af, r);
3535                 else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
3536                     r->return_icmp6)
3537                         pf_send_icmp(m, r->return_icmp6 >> 8,
3538                             r->return_icmp6 & 255, af, r);
3539         }
3540
3541         if (r->action == PF_DROP)
3542                 goto cleanup;
3543
3544         if (pf_tag_packet(m, tag, rtableid)) {
3545                 REASON_SET(&reason, PFRES_MEMORY);
3546                 goto cleanup;
3547         }
3548
3549         if (!state_icmp && (r->keep_state || nr != NULL ||
3550             (pd->flags & PFDESC_TCP_NORM))) {
3551                 int action;
3552                 action = pf_create_state(r, nr, a, pd, nsn, skw, sks, nk, sk, m,
3553                     off, sport, dport, &rewrite, kif, sm, tag, bproto_sum,
3554                     bip_sum, hdrlen);
3555                 if (action != PF_PASS)
3556                         return (action);
3557         }
3558
3559         /* copy back packet headers if we performed NAT operations */
3560         if (rewrite)
3561                 m_copyback(m, off, hdrlen, pd->hdr.any);
3562
3563         return (PF_PASS);
3564
3565 cleanup:
3566         if (sk != NULL)
3567                 pool_put(&pf_state_key_pl, sk);
3568         if (nk != NULL)
3569                 pool_put(&pf_state_key_pl, nk);
3570         return (PF_DROP);
3571 }
3572
3573 static __inline int
3574 pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3575     struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *skw,
3576     struct pf_state_key *sks, struct pf_state_key *nk, struct pf_state_key *sk,
3577     struct mbuf *m, int off, u_int16_t sport, u_int16_t dport, int *rewrite,
3578     struct pfi_kif *kif, struct pf_state **sm, int tag, u_int16_t bproto_sum,
3579     u_int16_t bip_sum, int hdrlen)
3580 {
3581         struct pf_state         *s = NULL;
3582         struct pf_src_node      *sn = NULL;
3583         struct tcphdr           *th = pd->hdr.tcp;
3584         u_int16_t                mss = tcp_mssdflt;
3585         u_short                  reason;
3586
3587         /* check maximums */
3588         if (r->max_states && (r->states_cur >= r->max_states)) {
3589                 pf_status.lcounters[LCNT_STATES]++;
3590                 REASON_SET(&reason, PFRES_MAXSTATES);
3591                 return (PF_DROP);
3592         }
3593         /* src node for filter rule */
3594         if ((r->rule_flag & PFRULE_SRCTRACK ||
3595             r->rpool.opts & PF_POOL_STICKYADDR) &&
3596             pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3597                 REASON_SET(&reason, PFRES_SRCLIMIT);
3598                 goto csfailed;
3599         }
3600         /* src node for translation rule */
3601         if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3602             pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3603                 REASON_SET(&reason, PFRES_SRCLIMIT);
3604                 goto csfailed;
3605         }
3606         s = pool_get(&pf_state_pl, PR_NOWAIT | PR_ZERO);
3607         if (s == NULL) {
3608                 REASON_SET(&reason, PFRES_MEMORY);
3609                 goto csfailed;
3610         }
3611         s->id = 0; /* XXX Do we really need that? not in OpenBSD */
3612         s->creatorid = 0;
3613         s->rule.ptr = r;
3614         s->nat_rule.ptr = nr;
3615         s->anchor.ptr = a;
3616         STATE_INC_COUNTERS(s);
3617         if (r->allow_opts)
3618                 s->state_flags |= PFSTATE_ALLOWOPTS;
3619         if (r->rule_flag & PFRULE_STATESLOPPY)
3620                 s->state_flags |= PFSTATE_SLOPPY;
3621         s->log = r->log & PF_LOG_ALL;
3622         if (nr != NULL)
3623                 s->log |= nr->log & PF_LOG_ALL;
3624         switch (pd->proto) {
3625         case IPPROTO_TCP:
3626                 s->src.seqlo = ntohl(th->th_seq);
3627                 s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3628                 if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3629                     r->keep_state == PF_STATE_MODULATE) {
3630                         /* Generate sequence number modulator */
3631                         if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3632                             0)
3633                                 s->src.seqdiff = 1;
3634                         pf_change_a(&th->th_seq, &th->th_sum,
3635                             htonl(s->src.seqlo + s->src.seqdiff), 0);
3636                         *rewrite = 1;
3637                 } else
3638                         s->src.seqdiff = 0;
3639                 if (th->th_flags & TH_SYN) {
3640                         s->src.seqhi++;
3641                         s->src.wscale = pf_get_wscale(m, off,
3642                             th->th_off, pd->af);
3643                 }
3644                 s->src.max_win = MAX(ntohs(th->th_win), 1);
3645                 if (s->src.wscale & PF_WSCALE_MASK) {
3646                         /* Remove scale factor from initial window */
3647                         int win = s->src.max_win;
3648                         win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3649                         s->src.max_win = (win - 1) >>
3650                             (s->src.wscale & PF_WSCALE_MASK);
3651                 }
3652                 if (th->th_flags & TH_FIN)
3653                         s->src.seqhi++;
3654                 s->dst.seqhi = 1;
3655                 s->dst.max_win = 1;
3656                 s->src.state = TCPS_SYN_SENT;
3657                 s->dst.state = TCPS_CLOSED;
3658                 s->timeout = PFTM_TCP_FIRST_PACKET;
3659                 break;
3660         case IPPROTO_UDP:
3661                 s->src.state = PFUDPS_SINGLE;
3662                 s->dst.state = PFUDPS_NO_TRAFFIC;
3663                 s->timeout = PFTM_UDP_FIRST_PACKET;
3664                 break;
3665         case IPPROTO_ICMP:
3666 #ifdef INET6
3667         case IPPROTO_ICMPV6:
3668 #endif
3669                 s->timeout = PFTM_ICMP_FIRST_PACKET;
3670                 break;
3671         default:
3672                 s->src.state = PFOTHERS_SINGLE;
3673                 s->dst.state = PFOTHERS_NO_TRAFFIC;
3674                 s->timeout = PFTM_OTHER_FIRST_PACKET;
3675         }
3676
3677         s->creation = time_second;
3678         s->expire = time_second;
3679
3680         if (sn != NULL) {
3681                 s->src_node = sn;
3682                 s->src_node->states++;
3683         }
3684         if (nsn != NULL) {
3685                 /* XXX We only modify one side for now. */
3686                 PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3687                 s->nat_src_node = nsn;
3688                 s->nat_src_node->states++;
3689         }
3690         if (pd->proto == IPPROTO_TCP) {
3691                 if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3692                     off, pd, th, &s->src, &s->dst)) {
3693                         REASON_SET(&reason, PFRES_MEMORY);
3694                         pf_src_tree_remove_state(s);
3695                         STATE_DEC_COUNTERS(s);
3696                         pool_put(&pf_state_pl, s);
3697                         return (PF_DROP);
3698                 }
3699                 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3700                     pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3701                     &s->src, &s->dst, rewrite)) {
3702                         /* This really shouldn't happen!!! */
3703                         DPFPRINTF(PF_DEBUG_URGENT,
3704                             ("pf_normalize_tcp_stateful failed on first pkt"));
3705                         pf_normalize_tcp_cleanup(s);
3706                         pf_src_tree_remove_state(s);
3707                         STATE_DEC_COUNTERS(s);
3708                         pool_put(&pf_state_pl, s);
3709                         return (PF_DROP);
3710                 }
3711         }
3712         s->direction = pd->dir;
3713
3714         if (sk == NULL && pf_state_key_setup(pd, nr, &skw, &sks, &sk, &nk,
3715             pd->src, pd->dst, sport, dport))
3716                 goto csfailed;
3717
3718         if (pf_state_insert(BOUND_IFACE(r, kif), skw, sks, s)) {
3719                 if (pd->proto == IPPROTO_TCP)
3720                         pf_normalize_tcp_cleanup(s);
3721                 REASON_SET(&reason, PFRES_STATEINS);
3722                 pf_src_tree_remove_state(s);
3723                 STATE_DEC_COUNTERS(s);
3724                 pool_put(&pf_state_pl, s);
3725                 return (PF_DROP);
3726         } else
3727                 *sm = s;
3728
3729         pf_set_rt_ifp(s, pd->src);      /* needs s->state_key set */
3730         if (tag > 0) {
3731                 pf_tag_ref(tag);
3732                 s->tag = tag;
3733         }
3734         if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
3735             TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
3736                 s->src.state = PF_TCPS_PROXY_SRC;
3737                 /* undo NAT changes, if they have taken place */
3738                 if (nr != NULL) {
3739                         struct pf_state_key *skt = s->key[PF_SK_WIRE];
3740                         if (pd->dir == PF_OUT)
3741                                 skt = s->key[PF_SK_STACK];
3742                         PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
3743                         PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
3744                         if (pd->sport)
3745                                 *pd->sport = skt->port[pd->sidx];
3746                         if (pd->dport)
3747                                 *pd->dport = skt->port[pd->didx];
3748                         if (pd->proto_sum)
3749                                 *pd->proto_sum = bproto_sum;
3750                         if (pd->ip_sum)
3751                                 *pd->ip_sum = bip_sum;
3752                         m_copyback(m, off, hdrlen, pd->hdr.any);
3753                 }
3754                 s->src.seqhi = htonl(karc4random());
3755                 /* Find mss option */
3756                 mss = pf_get_mss(m, off, th->th_off, pd->af);
3757                 mss = pf_calc_mss(pd->src, pd->af, mss);
3758                 mss = pf_calc_mss(pd->dst, pd->af, mss);
3759                 s->src.mss = mss;
3760                 pf_send_tcp(r, pd->af, pd->dst, pd->src, th->th_dport,
3761                     th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3762                     TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL, NULL);
3763                 REASON_SET(&reason, PFRES_SYNPROXY);
3764                 return (PF_SYNPROXY_DROP);
3765         }
3766
3767         return (PF_PASS);
3768
3769 csfailed:
3770         if (sk != NULL)
3771                 pool_put(&pf_state_key_pl, sk);
3772         if (nk != NULL)
3773                 pool_put(&pf_state_key_pl, nk);
3774
3775         if (sn != NULL && sn->states == 0 && sn->expire == 0) {
3776                 RB_REMOVE(pf_src_tree, &tree_src_tracking, sn);
3777                 pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
3778                 pf_status.src_nodes--;
3779                 pool_put(&pf_src_tree_pl, sn);
3780         }
3781         if (nsn != sn && nsn != NULL && nsn->states == 0 && nsn->expire == 0) {
3782                 RB_REMOVE(pf_src_tree, &tree_src_tracking, nsn);
3783                 pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
3784                 pf_status.src_nodes--;
3785                 pool_put(&pf_src_tree_pl, nsn);
3786         }
3787         return (PF_DROP);
3788 }
3789
3790 int
3791 pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3792     struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3793     struct pf_ruleset **rsm)
3794 {
3795         struct pf_rule          *r, *a = NULL;
3796         struct pf_ruleset       *ruleset = NULL;
3797         sa_family_t              af = pd->af;
3798         u_short                  reason;
3799         int                      tag = -1;
3800         int                      asd = 0;
3801         int                      match = 0;
3802
3803         r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3804         while (r != NULL) {
3805                 r->evaluations++;
3806                 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3807                         r = r->skip[PF_SKIP_IFP].ptr;
3808                 else if (r->direction && r->direction != direction)
3809                         r = r->skip[PF_SKIP_DIR].ptr;
3810                 else if (r->af && r->af != af)
3811                         r = r->skip[PF_SKIP_AF].ptr;
3812                 else if (r->proto && r->proto != pd->proto)
3813                         r = r->skip[PF_SKIP_PROTO].ptr;
3814                 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3815                     r->src.neg, kif))
3816                         r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3817                 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3818                     r->dst.neg, NULL))
3819                         r = r->skip[PF_SKIP_DST_ADDR].ptr;
3820                 else if (r->tos && !(r->tos == pd->tos))
3821                         r = TAILQ_NEXT(r, entries);
3822                 else if (r->os_fingerprint != PF_OSFP_ANY)
3823                         r = TAILQ_NEXT(r, entries);
3824                 else if (pd->proto == IPPROTO_UDP &&
3825                     (r->src.port_op || r->dst.port_op))
3826                         r = TAILQ_NEXT(r, entries);
3827                 else if (pd->proto == IPPROTO_TCP &&
3828                     (r->src.port_op || r->dst.port_op || r->flagset))
3829                         r = TAILQ_NEXT(r, entries);
3830                 else if ((pd->proto == IPPROTO_ICMP ||
3831                     pd->proto == IPPROTO_ICMPV6) &&
3832                     (r->type || r->code))
3833                         r = TAILQ_NEXT(r, entries);
3834                 else if (r->prob && r->prob <= karc4random())
3835                         r = TAILQ_NEXT(r, entries);
3836                 else if (r->match_tag && !pf_match_tag(m, r, &tag))
3837                         r = TAILQ_NEXT(r, entries);
3838                 else {
3839                         if (r->anchor == NULL) {
3840                                 match = 1;
3841                                 *rm = r;
3842                                 *am = a;
3843                                 *rsm = ruleset;
3844                                 if ((*rm)->quick)
3845                                         break;
3846                                 r = TAILQ_NEXT(r, entries);
3847                         } else
3848                                 pf_step_into_anchor(&asd, &ruleset,
3849                                     PF_RULESET_FILTER, &r, &a, &match);
3850                 }
3851                 if (r == NULL && pf_step_out_of_anchor(&asd, &ruleset,
3852                     PF_RULESET_FILTER, &r, &a, &match))
3853                         break;
3854         }
3855         r = *rm;
3856         a = *am;
3857         ruleset = *rsm;
3858
3859         REASON_SET(&reason, PFRES_MATCH);
3860
3861         if (r->log)
3862                 PFLOG_PACKET(kif, h, m, af, direction, reason, r, a, ruleset,
3863                     pd);
3864
3865         if (r->action != PF_PASS)
3866                 return (PF_DROP);
3867
3868         if (pf_tag_packet(m, tag, -1)) {
3869                 REASON_SET(&reason, PFRES_MEMORY);
3870                 return (PF_DROP);
3871         }
3872
3873         return (PF_PASS);
3874 }
3875
3876 int
3877 pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
3878         struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
3879         struct pf_pdesc *pd, u_short *reason, int *copyback)
3880 {
3881         struct tcphdr           *th = pd->hdr.tcp;
3882         u_int16_t                win = ntohs(th->th_win);
3883         u_int32_t                ack, end, seq, orig_seq;
3884         u_int8_t                 sws, dws;
3885         int                      ackskew;
3886
3887         if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3888                 sws = src->wscale & PF_WSCALE_MASK;
3889                 dws = dst->wscale & PF_WSCALE_MASK;
3890         } else
3891                 sws = dws = 0;
3892
3893         /*
3894          * Sequence tracking algorithm from Guido van Rooij's paper:
3895          *   http://www.madison-gurkha.com/publications/tcp_filtering/
3896          *      tcp_filtering.ps
3897          */
3898
3899         orig_seq = seq = ntohl(th->th_seq);
3900         if (src->seqlo == 0) {
3901                 /* First packet from this end. Set its state */
3902
3903                 if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
3904                     src->scrub == NULL) {
3905                         if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
3906                                 REASON_SET(reason, PFRES_MEMORY);
3907                                 return (PF_DROP);
3908                         }
3909                 }
3910
3911                 /* Deferred generation of sequence number modulator */
3912                 if (dst->seqdiff && !src->seqdiff) {
3913                         /* use random iss for the TCP server */
3914                         while ((src->seqdiff = karc4random() - seq) == 0)
3915                                 ;
3916                         ack = ntohl(th->th_ack) - dst->seqdiff;
3917                         pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
3918                             src->seqdiff), 0);
3919                         pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
3920                         *copyback = 1;
3921                 } else {
3922                         ack = ntohl(th->th_ack);
3923                 }
3924
3925                 end = seq + pd->p_len;
3926                 if (th->th_flags & TH_SYN) {
3927                         end++;
3928                         (*state)->sync_flags |= PFSTATE_GOT_SYN2;
3929                         if (dst->wscale & PF_WSCALE_FLAG) {
3930                                 src->wscale = pf_get_wscale(m, off, th->th_off,
3931                                     pd->af);
3932                                 if (src->wscale & PF_WSCALE_FLAG) {
3933                                         /* Remove scale factor from initial
3934                                          * window */
3935                                         sws = src->wscale & PF_WSCALE_MASK;
3936                                         win = ((u_int32_t)win + (1 << sws) - 1)
3937                                             >> sws;
3938                                         dws = dst->wscale & PF_WSCALE_MASK;
3939                                 } else {
3940                                         /* fixup other window */
3941                                         dst->max_win <<= dst->wscale &
3942                                             PF_WSCALE_MASK;
3943                                         /* in case of a retrans SYN|ACK */
3944                                         dst->wscale = 0;
3945                                 }
3946                         }
3947                 }
3948                 if (th->th_flags & TH_FIN)
3949                         end++;
3950
3951                 src->seqlo = seq;
3952                 if (src->state < TCPS_SYN_SENT)
3953                         src->state = TCPS_SYN_SENT;
3954
3955                 /*
3956                  * May need to slide the window (seqhi may have been set by
3957                  * the crappy stack check or if we picked up the connection
3958                  * after establishment)
3959                  */
3960                 if (src->seqhi == 1 ||
3961                     SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
3962                         src->seqhi = end + MAX(1, dst->max_win << dws);
3963                 if (win > src->max_win)
3964                         src->max_win = win;
3965
3966         } else {
3967                 ack = ntohl(th->th_ack) - dst->seqdiff;
3968                 if (src->seqdiff) {
3969                         /* Modulate sequence numbers */
3970                         pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
3971                             src->seqdiff), 0);
3972                         pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
3973                         *copyback = 1;
3974                 }
3975                 end = seq + pd->p_len;
3976                 if (th->th_flags & TH_SYN)
3977                         end++;
3978                 if (th->th_flags & TH_FIN)
3979                         end++;
3980         }
3981
3982         if ((th->th_flags & TH_ACK) == 0) {
3983                 /* Let it pass through the ack skew check */
3984                 ack = dst->seqlo;
3985         } else if ((ack == 0 &&
3986             (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
3987             /* broken tcp stacks do not set ack */
3988             (dst->state < TCPS_SYN_SENT)) {
3989                 /*
3990                  * Many stacks (ours included) will set the ACK number in an
3991                  * FIN|ACK if the SYN times out -- no sequence to ACK.
3992                  */
3993                 ack = dst->seqlo;
3994         }
3995
3996         if (seq == end) {
3997                 /* Ease sequencing restrictions on no data packets */
3998                 seq = src->seqlo;
3999                 end = seq;
4000         }
4001
4002         ackskew = dst->seqlo - ack;
4003
4004
4005         /*
4006          * Need to demodulate the sequence numbers in any TCP SACK options
4007          * (Selective ACK). We could optionally validate the SACK values
4008          * against the current ACK window, either forwards or backwards, but
4009          * I'm not confident that SACK has been implemented properly
4010          * everywhere. It wouldn't surprise me if several stacks accidently
4011          * SACK too far backwards of previously ACKed data. There really aren't
4012          * any security implications of bad SACKing unless the target stack
4013          * doesn't validate the option length correctly. Someone trying to
4014          * spoof into a TCP connection won't bother blindly sending SACK
4015          * options anyway.
4016          */
4017         if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
4018                 if (pf_modulate_sack(m, off, pd, th, dst))
4019                         *copyback = 1;
4020         }
4021
4022
4023 #define MAXACKWINDOW (0xffff + 1500)    /* 1500 is an arbitrary fudge factor */
4024         if (SEQ_GEQ(src->seqhi, end) &&
4025             /* Last octet inside other's window space */
4026             SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
4027             /* Retrans: not more than one window back */
4028             (ackskew >= -MAXACKWINDOW) &&
4029             /* Acking not more than one reassembled fragment backwards */
4030             (ackskew <= (MAXACKWINDOW << sws)) &&
4031             /* Acking not more than one window forward */
4032             ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
4033             (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
4034             (pd->flags & PFDESC_IP_REAS) == 0)) {
4035             /* Require an exact/+1 sequence match on resets when possible */
4036
4037                 if (dst->scrub || src->scrub) {
4038                         if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4039                             *state, src, dst, copyback))
4040                                 return (PF_DROP);
4041                 }
4042
4043                 /* update max window */
4044                 if (src->max_win < win)
4045                         src->max_win = win;
4046                 /* synchronize sequencing */
4047                 if (SEQ_GT(end, src->seqlo))
4048                         src->seqlo = end;
4049                 /* slide the window of what the other end can send */
4050                 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4051                         dst->seqhi = ack + MAX((win << sws), 1);
4052
4053
4054                 /* update states */
4055                 if (th->th_flags & TH_SYN)
4056                         if (src->state < TCPS_SYN_SENT)
4057                                 src->state = TCPS_SYN_SENT;
4058                 if (th->th_flags & TH_FIN)
4059                         if (src->state < TCPS_CLOSING)
4060                                 src->state = TCPS_CLOSING;
4061                 if (th->th_flags & TH_ACK) {
4062                         if (dst->state == TCPS_SYN_SENT) {
4063                                 dst->state = TCPS_ESTABLISHED;
4064                                 if (src->state == TCPS_ESTABLISHED &&
4065                                     (*state)->src_node != NULL &&
4066                                     pf_src_connlimit(state)) {
4067                                         REASON_SET(reason, PFRES_SRCLIMIT);
4068                                         return (PF_DROP);
4069                                 }
4070                         } else if (dst->state == TCPS_CLOSING)
4071                                 dst->state = TCPS_FIN_WAIT_2;
4072                 }
4073                 if (th->th_flags & TH_RST)
4074                         src->state = dst->state = TCPS_TIME_WAIT;
4075
4076                 /* update expire time */
4077                 (*state)->expire = time_second;
4078                 if (src->state >= TCPS_FIN_WAIT_2 &&
4079                     dst->state >= TCPS_FIN_WAIT_2)
4080                         (*state)->timeout = PFTM_TCP_CLOSED;
4081                 else if (src->state >= TCPS_CLOSING &&
4082                     dst->state >= TCPS_CLOSING)
4083                         (*state)->timeout = PFTM_TCP_FIN_WAIT;
4084                 else if (src->state < TCPS_ESTABLISHED ||
4085                     dst->state < TCPS_ESTABLISHED)
4086                         (*state)->timeout = PFTM_TCP_OPENING;
4087                 else if (src->state >= TCPS_CLOSING ||
4088                     dst->state >= TCPS_CLOSING)
4089                         (*state)->timeout = PFTM_TCP_CLOSING;
4090                 else
4091                         (*state)->timeout = PFTM_TCP_ESTABLISHED;
4092
4093                 /* Fall through to PASS packet */
4094
4095         } else if ((dst->state < TCPS_SYN_SENT ||
4096                 dst->state >= TCPS_FIN_WAIT_2 ||
4097                 src->state >= TCPS_FIN_WAIT_2) &&
4098             SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
4099             /* Within a window forward of the originating packet */
4100             SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
4101             /* Within a window backward of the originating packet */
4102
4103                 /*
4104                  * This currently handles three situations:
4105                  *  1) Stupid stacks will shotgun SYNs before their peer
4106                  *     replies.
4107                  *  2) When PF catches an already established stream (the
4108                  *     firewall rebooted, the state table was flushed, routes
4109                  *     changed...)
4110                  *  3) Packets get funky immediately after the connection
4111                  *     closes (this should catch Solaris spurious ACK|FINs
4112                  *     that web servers like to spew after a close)
4113                  *
4114                  * This must be a little more careful than the above code
4115                  * since packet floods will also be caught here. We don't
4116                  * update the TTL here to mitigate the damage of a packet
4117                  * flood and so the same code can handle awkward establishment
4118                  * and a loosened connection close.
4119                  * In the establishment case, a correct peer response will
4120                  * validate the connection, go through the normal state code
4121                  * and keep updating the state TTL.
4122                  */
4123
4124                 if (pf_status.debug >= PF_DEBUG_MISC) {
4125                         kprintf("pf: loose state match: ");
4126                         pf_print_state(*state);
4127                         pf_print_flags(th->th_flags);
4128                         kprintf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4129                             "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack, pd->p_len,
4130                             ackskew, (unsigned long long)(*state)->packets[0],
4131                             (unsigned long long)(*state)->packets[1],
4132                             pd->dir == PF_IN ? "in" : "out",
4133                             pd->dir == (*state)->direction ? "fwd" : "rev");
4134                 }
4135
4136                 if (dst->scrub || src->scrub) {
4137                         if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4138                             *state, src, dst, copyback))
4139                                 return (PF_DROP);
4140                 }
4141
4142                 /* update max window */
4143                 if (src->max_win < win)
4144                         src->max_win = win;
4145                 /* synchronize sequencing */
4146                 if (SEQ_GT(end, src->seqlo))
4147                         src->seqlo = end;
4148                 /* slide the window of what the other end can send */
4149                 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4150                         dst->seqhi = ack + MAX((win << sws), 1);
4151
4152                 /*
4153                  * Cannot set dst->seqhi here since this could be a shotgunned
4154                  * SYN and not an already established connection.
4155                  */
4156
4157                 if (th->th_flags & TH_FIN)
4158                         if (src->state < TCPS_CLOSING)
4159                                 src->state = TCPS_CLOSING;
4160                 if (th->th_flags & TH_RST)
4161                         src->state = dst->state = TCPS_TIME_WAIT;
4162
4163                 /* Fall through to PASS packet */
4164
4165         } else if ((*state)->pickup_mode == PF_PICKUPS_HASHONLY ||
4166                     ((*state)->pickup_mode == PF_PICKUPS_ENABLED &&
4167                      ((*state)->sync_flags & PFSTATE_GOT_SYN_MASK) !=
4168                       PFSTATE_GOT_SYN_MASK)) {
4169                 /*
4170                  * If pickup mode is hash only, do not fail on sequence checks.
4171                  *
4172                  * If pickup mode is enabled and we did not see the SYN in
4173                  * both direction, do not fail on sequence checks because
4174                  * we do not have complete information on window scale.
4175                  *
4176                  * Adjust expiration and fall through to PASS packet.
4177                  * XXX Add a FIN check to reduce timeout?
4178                  */
4179                 (*state)->expire = time_second;
4180         } else  {
4181                 /*
4182                  * Failure processing
4183                  */
4184                 if ((*state)->dst.state == TCPS_SYN_SENT &&
4185                     (*state)->src.state == TCPS_SYN_SENT) {
4186                         /* Send RST for state mismatches during handshake */
4187                         if (!(th->th_flags & TH_RST))
4188                                 pf_send_tcp((*state)->rule.ptr, pd->af,
4189                                     pd->dst, pd->src, th->th_dport,
4190                                     th->th_sport, ntohl(th->th_ack), 0,
4191                                     TH_RST, 0, 0,
4192                                     (*state)->rule.ptr->return_ttl, 1, 0,
4193                                     pd->eh, kif->pfik_ifp);
4194                         src->seqlo = 0;
4195                         src->seqhi = 1;
4196                         src->max_win = 1;
4197                 } else if (pf_status.debug >= PF_DEBUG_MISC) {
4198                         kprintf("pf: BAD state: ");
4199                         pf_print_state(*state);
4200                         pf_print_flags(th->th_flags);
4201                         kprintf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4202                             "pkts=%llu:%llu dir=%s,%s\n",
4203                             seq, orig_seq, ack, pd->p_len, ackskew,
4204                             (unsigned long long)(*state)->packets[0],
4205                                 (unsigned long long)(*state)->packets[1],
4206                             pd->dir == PF_IN ? "in" : "out",
4207                             pd->dir == (*state)->direction ? "fwd" : "rev");
4208                         kprintf("pf: State failure on: %c %c %c %c | %c %c\n",
4209                             SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4210                             SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4211                             ' ': '2',
4212                             (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4213                             (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4214                             SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4215                             SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4216                 }
4217                 REASON_SET(reason, PFRES_BADSTATE);
4218                 return (PF_DROP);
4219         }
4220
4221         return (PF_PASS);
4222 }
4223
4224 int
4225 pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4226         struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4227 {
4228         struct tcphdr           *th = pd->hdr.tcp;
4229
4230         if (th->th_flags & TH_SYN)
4231                 if (src->state < TCPS_SYN_SENT)
4232                         src->state = TCPS_SYN_SENT;
4233         if (th->th_flags & TH_FIN)
4234                 if (src->state < TCPS_CLOSING)
4235                         src->state = TCPS_CLOSING;
4236         if (th->th_flags & TH_ACK) {
4237                 if (dst->state == TCPS_SYN_SENT) {
4238                         dst->state = TCPS_ESTABLISHED;
4239                         if (src->state == TCPS_ESTABLISHED &&
4240                             (*state)->src_node != NULL &&
4241                             pf_src_connlimit(state)) {
4242                                 REASON_SET(reason, PFRES_SRCLIMIT);
4243                                 return (PF_DROP);
4244                         }
4245                 } else if (dst->state == TCPS_CLOSING) {
4246                         dst->state = TCPS_FIN_WAIT_2;
4247                 } else if (src->state == TCPS_SYN_SENT &&
4248                     dst->state < TCPS_SYN_SENT) {
4249                         /*
4250                          * Handle a special sloppy case where we only see one
4251                          * half of the connection. If there is a ACK after
4252                          * the initial SYN without ever seeing a packet from
4253                          * the destination, set the connection to established.
4254                          */
4255                         dst->state = src->state = TCPS_ESTABLISHED;
4256                         if ((*state)->src_node != NULL &&
4257                             pf_src_connlimit(state)) {
4258                                 REASON_SET(reason, PFRES_SRCLIMIT);
4259                                 return (PF_DROP);
4260                         }
4261                 } else if (src->state == TCPS_CLOSING &&
4262                     dst->state == TCPS_ESTABLISHED &&
4263                     dst->seqlo == 0) {
4264                         /*
4265                          * Handle the closing of half connections where we
4266                          * don't see the full bidirectional FIN/ACK+ACK
4267                          * handshake.
4268                          */
4269                         dst->state = TCPS_CLOSING;
4270                 }
4271         }
4272         if (th->th_flags & TH_RST)
4273                 src->state = dst->state = TCPS_TIME_WAIT;
4274
4275         /* update expire time */
4276         (*state)->expire = time_second;
4277         if (src->state >= TCPS_FIN_WAIT_2 &&
4278             dst->state >= TCPS_FIN_WAIT_2)
4279                 (*state)->timeout = PFTM_TCP_CLOSED;
4280         else if (src->state >= TCPS_CLOSING &&
4281             dst->state >= TCPS_CLOSING)
4282                 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4283         else if (src->state < TCPS_ESTABLISHED ||
4284             dst->state < TCPS_ESTABLISHED)
4285                 (*state)->timeout = PFTM_TCP_OPENING;
4286         else if (src->state >= TCPS_CLOSING ||
4287             dst->state >= TCPS_CLOSING)
4288                 (*state)->timeout = PFTM_TCP_CLOSING;
4289         else
4290                 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4291
4292         return (PF_PASS);
4293 }
4294
4295 int
4296 pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4297     struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4298     u_short *reason)
4299 {
4300         struct pf_state_key_cmp  key;
4301         struct tcphdr           *th = pd->hdr.tcp;
4302         int                      copyback = 0;
4303         struct pf_state_peer    *src, *dst;
4304         struct pf_state_key     *sk;
4305
4306         key.af = pd->af;
4307         key.proto = IPPROTO_TCP;
4308         if (direction == PF_IN) {       /* wire side, straight */
4309                 PF_ACPY(&key.addr[0], pd->src, key.af);
4310                 PF_ACPY(&key.addr[1], pd->dst, key.af);
4311                 key.port[0] = th->th_sport;
4312                 key.port[1] = th->th_dport;
4313         } else {                        /* stack side, reverse */
4314                 PF_ACPY(&key.addr[1], pd->src, key.af);
4315                 PF_ACPY(&key.addr[0], pd->dst, key.af);
4316                 key.port[1] = th->th_sport;
4317                 key.port[0] = th->th_dport;
4318         }
4319
4320         STATE_LOOKUP(kif, &key, direction, *state, m);
4321
4322         if (direction == (*state)->direction) {
4323                 src = &(*state)->src;
4324                 dst = &(*state)->dst;
4325         } else {
4326                 src = &(*state)->dst;
4327                 dst = &(*state)->src;
4328         }
4329
4330         sk = (*state)->key[pd->didx];
4331
4332         if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4333                 if (direction != (*state)->direction) {
4334                         REASON_SET(reason, PFRES_SYNPROXY);
4335                         return (PF_SYNPROXY_DROP);
4336                 }
4337                 if (th->th_flags & TH_SYN) {
4338                         if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4339                                 REASON_SET(reason, PFRES_SYNPROXY);
4340                                 return (PF_DROP);
4341                         }
4342                         pf_send_tcp((*state)->rule.ptr, pd->af, pd->dst,
4343                             pd->src, th->th_dport, th->th_sport,
4344                             (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4345                             TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1,
4346                             0, NULL, NULL);
4347                         REASON_SET(reason, PFRES_SYNPROXY);
4348                         return (PF_SYNPROXY_DROP);
4349                 } else if (!(th->th_flags & TH_ACK) ||
4350                     (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4351                     (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4352                         REASON_SET(reason, PFRES_SYNPROXY);
4353                         return (PF_DROP);
4354                 } else if ((*state)->src_node != NULL &&
4355                     pf_src_connlimit(state)) {
4356                         REASON_SET(reason, PFRES_SRCLIMIT);
4357                         return (PF_DROP);
4358                 } else
4359                         (*state)->src.state = PF_TCPS_PROXY_DST;
4360         }
4361         if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4362                 if (direction == (*state)->direction) {
4363                         if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4364                             (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4365                             (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4366                                 REASON_SET(reason, PFRES_SYNPROXY);
4367                                 return (PF_DROP);
4368                         }
4369                         (*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4370                         if ((*state)->dst.seqhi == 1)
4371                                 (*state)->dst.seqhi = htonl(karc4random());
4372                         pf_send_tcp((*state)->rule.ptr, pd->af,
4373                             &sk->addr[pd->sidx], &sk->addr[pd->didx],
4374                             sk->port[pd->sidx], sk->port[pd->didx],
4375                             (*state)->dst.seqhi, 0, TH_SYN, 0,
4376                             (*state)->src.mss, 0, 0, (*state)->tag, NULL, NULL);
4377                         REASON_SET(reason, PFRES_SYNPROXY);
4378                         return (PF_SYNPROXY_DROP);
4379                 } else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4380                     (TH_SYN|TH_ACK)) ||
4381                     (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4382                         REASON_SET(reason, PFRES_SYNPROXY);
4383                         return (PF_DROP);
4384                 } else {
4385                         (*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4386                         (*state)->dst.seqlo = ntohl(th->th_seq);
4387                         pf_send_tcp((*state)->rule.ptr, pd->af, pd->dst,
4388                             pd->src, th->th_dport, th->th_sport,
4389                             ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4390                             TH_ACK, (*state)->src.max_win, 0, 0, 0,
4391                             (*state)->tag, NULL, NULL);
4392                         pf_send_tcp((*state)->rule.ptr, pd->af,
4393                             &sk->addr[pd->sidx], &sk->addr[pd->didx],
4394                             sk->port[pd->sidx], sk->port[pd->didx],
4395                             (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4396                             TH_ACK, (*state)->dst.max_win, 0, 0, 1,
4397                             0, NULL, NULL);
4398                         (*state)->src.seqdiff = (*state)->dst.seqhi -
4399                             (*state)->src.seqlo;
4400                         (*state)->dst.seqdiff = (*state)->src.seqhi -
4401                             (*state)->dst.seqlo;
4402                         (*state)->src.seqhi = (*state)->src.seqlo +
4403                             (*state)->dst.max_win;
4404                         (*state)->dst.seqhi = (*state)->dst.seqlo +
4405                             (*state)->src.max_win;
4406                         (*state)->src.wscale = (*state)->dst.wscale = 0;
4407                         (*state)->src.state = (*state)->dst.state =
4408                             TCPS_ESTABLISHED;
4409                         REASON_SET(reason, PFRES_SYNPROXY);
4410                         return (PF_SYNPROXY_DROP);
4411                 }
4412         }
4413
4414         if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4415             dst->state >= TCPS_FIN_WAIT_2 &&
4416             src->state >= TCPS_FIN_WAIT_2) {
4417                 if (pf_status.debug >= PF_DEBUG_MISC) {
4418                         kprintf("pf: state reuse ");
4419                         pf_print_state(*state);
4420                         pf_print_flags(th->th_flags);
4421                         kprintf("\n");
4422                 }
4423                 /* XXX make sure it's the same direction ?? */
4424                 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4425                 pf_unlink_state(*state);
4426                 *state = NULL;
4427                 return (PF_DROP);
4428         }
4429
4430         if ((*state)->state_flags & PFSTATE_SLOPPY) {
4431                 if (pf_tcp_track_sloppy(src, dst, state, pd, reason) == PF_DROP)
4432                         return (PF_DROP);
4433         } else {
4434                 if (pf_tcp_track_full(src, dst, state, kif, m, off, pd, reason,
4435                     &copyback) == PF_DROP)
4436                         return (PF_DROP);
4437         }
4438
4439         /* translate source/destination address, if necessary */
4440         if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4441                 struct pf_state_key *nk = (*state)->key[pd->didx];
4442
4443                 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4444                     nk->port[pd->sidx] != th->th_sport) 
4445                         pf_change_ap(pd->src, &th->th_sport, pd->ip_sum,
4446                             &th->th_sum, &nk->addr[pd->sidx],
4447                             nk->port[pd->sidx], 0, pd->af);
4448
4449                 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4450                     nk->port[pd->didx] != th->th_dport) {
4451                         /*
4452                          * If we don't redispatch the packet will go into
4453                          * the protocol stack on the wrong cpu for the
4454                          * post-translated address.
4455                          */
4456                         m->m_flags &= ~M_HASH;
4457                         pf_change_ap(pd->dst, &th->th_dport, pd->ip_sum,
4458                             &th->th_sum, &nk->addr[pd->didx],
4459                             nk->port[pd->didx], 0, pd->af);
4460                 }
4461                 copyback = 1;
4462         }
4463
4464         /* Copyback sequence modulation or stateful scrub changes if needed */
4465         if (copyback)
4466                 m_copyback(m, off, sizeof(*th), (caddr_t)th);
4467
4468         return (PF_PASS);
4469 }
4470
4471 int
4472 pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4473     struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4474 {
4475         struct pf_state_peer    *src, *dst;
4476         struct pf_state_key_cmp  key;
4477         struct udphdr           *uh = pd->hdr.udp;
4478
4479         key.af = pd->af;
4480         key.proto = IPPROTO_UDP;
4481         if (direction == PF_IN) {       /* wire side, straight */
4482                 PF_ACPY(&key.addr[0], pd->src, key.af);
4483                 PF_ACPY(&key.addr[1], pd->dst, key.af);
4484                 key.port[0] = uh->uh_sport;
4485                 key.port[1] = uh->uh_dport;
4486         } else {                        /* stack side, reverse */
4487                 PF_ACPY(&key.addr[1], pd->src, key.af);
4488                 PF_ACPY(&key.addr[0], pd->dst, key.af);
4489                 key.port[1] = uh->uh_sport;
4490                 key.port[0] = uh->uh_dport;
4491         }
4492
4493         STATE_LOOKUP(kif, &key, direction, *state, m);
4494
4495         if (direction == (*state)->direction) {
4496                 src = &(*state)->src;
4497                 dst = &(*state)->dst;
4498         } else {
4499                 src = &(*state)->dst;
4500                 dst = &(*state)->src;
4501         }
4502
4503         /* update states */
4504         if (src->state < PFUDPS_SINGLE)
4505                 src->state = PFUDPS_SINGLE;
4506         if (dst->state == PFUDPS_SINGLE)
4507                 dst->state = PFUDPS_MULTIPLE;
4508
4509         /* update expire time */
4510         (*state)->expire = time_second;
4511         if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4512                 (*state)->timeout = PFTM_UDP_MULTIPLE;
4513         else
4514                 (*state)->timeout = PFTM_UDP_SINGLE;
4515
4516         /* translate source/destination address, if necessary */
4517         if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4518                 struct pf_state_key *nk = (*state)->key[pd->didx];
4519
4520                 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4521                     nk->port[pd->sidx] != uh->uh_sport)
4522                         pf_change_ap(pd->src, &uh->uh_sport, pd->ip_sum,
4523                             &uh->uh_sum, &nk->addr[pd->sidx],
4524                             nk->port[pd->sidx], 1, pd->af);
4525
4526                 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4527                     nk->port[pd->didx] != uh->uh_dport) {
4528                         /*
4529                          * If we don't redispatch the packet will go into
4530                          * the protocol stack on the wrong cpu for the
4531                          * post-translated address.
4532                          */
4533                         m->m_flags &= ~M_HASH;
4534                         pf_change_ap(pd->dst, &uh->uh_dport, pd->ip_sum,
4535                             &uh->uh_sum, &nk->addr[pd->didx],
4536                             nk->port[pd->didx], 1, pd->af);
4537                 }
4538                 m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4539         }
4540
4541         return (PF_PASS);
4542 }
4543
4544 int
4545 pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4546     struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
4547 {
4548         struct pf_addr  *saddr = pd->src, *daddr = pd->dst;
4549         u_int16_t        icmpid = 0, *icmpsum;
4550         u_int8_t         icmptype;
4551         int              state_icmp = 0;
4552         struct pf_state_key_cmp key;
4553
4554         switch (pd->proto) {
4555 #ifdef INET
4556         case IPPROTO_ICMP:
4557                 icmptype = pd->hdr.icmp->icmp_type;
4558                 icmpid = pd->hdr.icmp->icmp_id;
4559                 icmpsum = &pd->hdr.icmp->icmp_cksum;
4560
4561                 if (icmptype == ICMP_UNREACH ||
4562                     icmptype == ICMP_SOURCEQUENCH ||
4563                     icmptype == ICMP_REDIRECT ||
4564                     icmptype == ICMP_TIMXCEED ||
4565                     icmptype == ICMP_PARAMPROB)
4566                         state_icmp++;
4567                 break;
4568 #endif /* INET */
4569 #ifdef INET6
4570         case IPPROTO_ICMPV6:
4571                 icmptype = pd->hdr.icmp6->icmp6_type;
4572                 icmpid = pd->hdr.icmp6->icmp6_id;
4573                 icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4574
4575                 if (icmptype == ICMP6_DST_UNREACH ||
4576                     icmptype == ICMP6_PACKET_TOO_BIG ||
4577                     icmptype == ICMP6_TIME_EXCEEDED ||
4578                     icmptype == ICMP6_PARAM_PROB)
4579                         state_icmp++;
4580                 break;
4581 #endif /* INET6 */
4582         }
4583
4584         if (!state_icmp) {
4585
4586                 /*
4587                  * ICMP query/reply message not related to a TCP/UDP packet.
4588                  * Search for an ICMP state.
4589                  */
4590                 key.af = pd->af;
4591                 key.proto = pd->proto;
4592                 key.port[0] = key.port[1] = icmpid;
4593                 if (direction == PF_IN) {       /* wire side, straight */
4594                         PF_ACPY(&key.addr[0], pd->src, key.af);
4595                         PF_ACPY(&key.addr[1], pd->dst, key.af);
4596                 } else {                        /* stack side, reverse */
4597                         PF_ACPY(&key.addr[1], pd->src, key.af);
4598                         PF_ACPY(&key.addr[0], pd->dst, key.af);
4599                 }
4600
4601                 STATE_LOOKUP(kif, &key, direction, *state, m);
4602
4603                 (*state)->expire = time_second;
4604                 (*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4605
4606                 /* translate source/destination address, if necessary */
4607                 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4608                         struct pf_state_key *nk = (*state)->key[pd->didx];
4609
4610                         switch (pd->af) {
4611 #ifdef INET
4612                         case AF_INET:
4613                                 if (PF_ANEQ(pd->src,
4614                                     &nk->addr[pd->sidx], AF_INET))
4615                                         pf_change_a(&saddr->v4.s_addr,
4616                                             pd->ip_sum,
4617                                             nk->addr[pd->sidx].v4.s_addr, 0);
4618
4619                                 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
4620                                     AF_INET))
4621                                         pf_change_a(&daddr->v4.s_addr,
4622                                             pd->ip_sum,
4623                                             nk->addr[pd->didx].v4.s_addr, 0);
4624
4625                                 if (nk->port[0] !=
4626                                     pd->hdr.icmp->icmp_id) {
4627                                         pd->hdr.icmp->icmp_cksum =
4628                                             pf_cksum_fixup(
4629                                             pd->hdr.icmp->icmp_cksum, icmpid,
4630                                             nk->port[pd->sidx], 0);
4631                                         pd->hdr.icmp->icmp_id =
4632                                             nk->port[pd->sidx];
4633                                 }
4634
4635                                 m_copyback(m, off, ICMP_MINLEN,
4636                                     (caddr_t)pd->hdr.icmp);
4637                                 break;
4638 #endif /* INET */
4639 #ifdef INET6
4640                         case AF_INET6:
4641                                 if (PF_ANEQ(pd->src,
4642                                     &nk->addr[pd->sidx], AF_INET6))
4643                                         pf_change_a6(saddr,
4644                                             &pd->hdr.icmp6->icmp6_cksum,
4645                                             &nk->addr[pd->sidx], 0);
4646
4647                                 if (PF_ANEQ(pd->dst,
4648                                     &nk->addr[pd->didx], AF_INET6))
4649                                         pf_change_a6(daddr,
4650                                             &pd->hdr.icmp6->icmp6_cksum,
4651                                             &nk->addr[pd->didx], 0);
4652
4653                                 m_copyback(m, off,
4654                                         sizeof(struct icmp6_hdr),
4655                                         (caddr_t)pd->hdr.icmp6);
4656                                 break;
4657 #endif /* INET6 */
4658                         }
4659                 }
4660                 return (PF_PASS);
4661
4662         } else {
4663                 /*
4664                  * ICMP error message in response to a TCP/UDP packet.
4665                  * Extract the inner TCP/UDP header and search for that state.
4666                  */
4667
4668                 struct pf_pdesc pd2;
4669 #ifdef INET
4670                 struct ip       h2;
4671 #endif /* INET */
4672 #ifdef INET6
4673                 struct ip6_hdr  h2_6;
4674                 int             terminal = 0;
4675 #endif /* INET6 */
4676                 int             ipoff2;
4677                 int             off2;
4678
4679                 pd2.af = pd->af;
4680                 /* Payload packet is from the opposite direction. */
4681                 pd2.sidx = (direction == PF_IN) ? 1 : 0;
4682                 pd2.didx = (direction == PF_IN) ? 0 : 1;
4683                 switch (pd->af) {
4684 #ifdef INET
4685                 case AF_INET:
4686                         /* offset of h2 in mbuf chain */
4687                         ipoff2 = off + ICMP_MINLEN;
4688
4689                         if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
4690                             NULL, reason, pd2.af)) {
4691                                 DPFPRINTF(PF_DEBUG_MISC,
4692                                     ("pf: ICMP error message too short "
4693                                     "(ip)\n"));
4694                                 return (PF_DROP);
4695                         }
4696                         /*
4697                          * ICMP error messages don't refer to non-first
4698                          * fragments
4699                          */
4700                         if (h2.ip_off & htons(IP_OFFMASK)) {
4701                                 REASON_SET(reason, PFRES_FRAG);
4702                                 return (PF_DROP);
4703                         }
4704
4705                         /* offset of protocol header that follows h2 */
4706                         off2 = ipoff2 + (h2.ip_hl << 2);
4707
4708                         pd2.proto = h2.ip_p;
4709                         pd2.src = (struct pf_addr *)&h2.ip_src;
4710                         pd2.dst = (struct pf_addr *)&h2.ip_dst;
4711                         pd2.ip_sum = &h2.ip_sum;
4712                         break;
4713 #endif /* INET */
4714 #ifdef INET6
4715                 case AF_INET6:
4716                         ipoff2 = off + sizeof(struct icmp6_hdr);
4717
4718                         if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
4719                             NULL, reason, pd2.af)) {
4720                                 DPFPRINTF(PF_DEBUG_MISC,
4721                                     ("pf: ICMP error message too short "
4722                                     "(ip6)\n"));
4723                                 return (PF_DROP);
4724                         }
4725                         pd2.proto = h2_6.ip6_nxt;
4726                         pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4727                         pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4728                         pd2.ip_sum = NULL;
4729                         off2 = ipoff2 + sizeof(h2_6);
4730                         do {
4731                                 switch (pd2.proto) {
4732                                 case IPPROTO_FRAGMENT:
4733                                         /*
4734                                          * ICMPv6 error messages for
4735                                          * non-first fragments
4736                                          */
4737                                         REASON_SET(reason, PFRES_FRAG);
4738                                         return (PF_DROP);
4739                                 case IPPROTO_AH:
4740                                 case IPPROTO_HOPOPTS:
4741                                 case IPPROTO_ROUTING:
4742                                 case IPPROTO_DSTOPTS: {
4743                                         /* get next header and header length */
4744                                         struct ip6_ext opt6;
4745
4746                                         if (!pf_pull_hdr(m, off2, &opt6,
4747                                             sizeof(opt6), NULL, reason,
4748                                             pd2.af)) {
4749                                                 DPFPRINTF(PF_DEBUG_MISC,
4750                                                     ("pf: ICMPv6 short opt\n"));
4751                                                 return (PF_DROP);
4752                                         }
4753                                         if (pd2.proto == IPPROTO_AH)
4754                                                 off2 += (opt6.ip6e_len + 2) * 4;
4755                                         else
4756                                                 off2 += (opt6.ip6e_len + 1) * 8;
4757                                         pd2.proto = opt6.ip6e_nxt;
4758                                         /* goto the next header */
4759                                         break;
4760                                 }
4761                                 default:
4762                                         terminal++;
4763                                         break;
4764                                 }
4765                         } while (!terminal);
4766                         break;
4767 #endif /* INET6 */
4768                 default:
4769                         DPFPRINTF(PF_DEBUG_MISC,
4770                             ("pf: ICMP AF %d unknown (ip6)\n", pd->af));
4771                         return (PF_DROP);
4772                         break;
4773                 }
4774
4775                 switch (pd2.proto) {
4776                 case IPPROTO_TCP: {
4777                         struct tcphdr            th;
4778                         u_int32_t                seq;
4779                         struct pf_state_peer    *src, *dst;
4780                         u_int8_t                 dws;
4781                         int                      copyback = 0;
4782
4783                         /*
4784                          * Only the first 8 bytes of the TCP header can be
4785                          * expected. Don't access any TCP header fields after
4786                          * th_seq, an ackskew test is not possible.
4787                          */
4788                         if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
4789                             pd2.af)) {
4790                                 DPFPRINTF(PF_DEBUG_MISC,
4791                                     ("pf: ICMP error message too short "
4792                                     "(tcp)\n"));
4793                                 return (PF_DROP);
4794                         }
4795
4796                         key.af = pd2.af;
4797                         key.proto = IPPROTO_TCP;
4798                         PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4799                         PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4800                         key.port[pd2.sidx] = th.th_sport;
4801                         key.port[pd2.didx] = th.th_dport;
4802
4803                         STATE_LOOKUP(kif, &key, direction, *state, m);
4804
4805                         if (direction == (*state)->direction) {
4806                                 src = &(*state)->dst;
4807                                 dst = &(*state)->src;
4808                         } else {
4809                                 src = &(*state)->src;
4810                                 dst = &(*state)->dst;
4811                         }
4812
4813                         if (src->wscale && dst->wscale)
4814                                 dws = dst->wscale & PF_WSCALE_MASK;
4815                         else
4816                                 dws = 0;
4817
4818                         /* Demodulate sequence number */
4819                         seq = ntohl(th.th_seq) - src->seqdiff;
4820                         if (src->seqdiff) {
4821                                 pf_change_a(&th.th_seq, icmpsum,
4822                                     htonl(seq), 0);
4823                                 copyback = 1;
4824                         }
4825
4826                         if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
4827                             (!SEQ_GEQ(src->seqhi, seq) ||
4828                             !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
4829                                 if (pf_status.debug >= PF_DEBUG_MISC) {
4830                                         kprintf("pf: BAD ICMP %d:%d ",
4831                                             icmptype, pd->hdr.icmp->icmp_code);
4832                                         pf_print_host(pd->src, 0, pd->af);
4833                                         kprintf(" -> ");
4834                                         pf_print_host(pd->dst, 0, pd->af);
4835                                         kprintf(" state: ");
4836                                         pf_print_state(*state);
4837                                         kprintf(" seq=%u\n", seq);
4838                                 }
4839                                 REASON_SET(reason, PFRES_BADSTATE);
4840                                 return (PF_DROP);
4841                         } else {
4842                                 if (pf_status.debug >= PF_DEBUG_MISC) {
4843                                         kprintf("pf: OK ICMP %d:%d ",
4844                                             icmptype, pd->hdr.icmp->icmp_code);
4845                                         pf_print_host(pd->src, 0, pd->af);
4846                                         kprintf(" -> ");
4847                                         pf_print_host(pd->dst, 0, pd->af);
4848                                         kprintf(" state: ");
4849                                         pf_print_state(*state);
4850                                         kprintf(" seq=%u\n", seq);
4851                                 }
4852                         }
4853
4854                         /* translate source/destination address, if necessary */
4855                         if ((*state)->key[PF_SK_WIRE] !=
4856                             (*state)->key[PF_SK_STACK]) {
4857                                 struct pf_state_key *nk =
4858                                     (*state)->key[pd->didx];
4859
4860                                 if (PF_ANEQ(pd2.src,
4861                                     &nk->addr[pd2.sidx], pd2.af) ||
4862                                     nk->port[pd2.sidx] != th.th_sport)
4863                                         pf_change_icmp(pd2.src, &th.th_sport,
4864                                             daddr, &nk->addr[pd2.sidx],
4865                                             nk->port[pd2.sidx], NULL,
4866                                             pd2.ip_sum, icmpsum,
4867                                             pd->ip_sum, 0, pd2.af);
4868
4869                                 if (PF_ANEQ(pd2.dst,
4870                                     &nk->addr[pd2.didx], pd2.af) ||
4871                                     nk->port[pd2.didx] != th.th_dport)
4872                                         pf_change_icmp(pd2.dst, &th.th_dport,
4873                                             NULL, /* XXX Inbound NAT? */
4874                                             &nk->addr[pd2.didx],
4875                                             nk->port[pd2.didx], NULL,
4876                                             pd2.ip_sum, icmpsum,
4877                                             pd->ip_sum, 0, pd2.af);
4878                                 copyback = 1;
4879                         }
4880
4881                         if (copyback) {
4882                                 switch (pd2.af) {
4883 #ifdef INET
4884                                 case AF_INET:
4885                                         m_copyback(m, off, ICMP_MINLEN,
4886                                             (caddr_t)pd->hdr.icmp);
4887                                         m_copyback(m, ipoff2, sizeof(h2),
4888                                             (caddr_t)&h2);
4889                                         break;
4890 #endif /* INET */
4891 #ifdef INET6
4892                                 case AF_INET6:
4893                                         m_copyback(m, off,
4894                                             sizeof(struct icmp6_hdr),
4895                                             (caddr_t)pd->hdr.icmp6);
4896                                         m_copyback(m, ipoff2, sizeof(h2_6),
4897                                             (caddr_t)&h2_6);
4898                                         break;
4899 #endif /* INET6 */
4900                                 }
4901                                 m_copyback(m, off2, 8, (caddr_t)&th);
4902                         }
4903
4904                         return (PF_PASS);
4905                         break;
4906                 }
4907                 case IPPROTO_UDP: {
4908                         struct udphdr           uh;
4909
4910                         if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
4911                             NULL, reason, pd2.af)) {
4912                                 DPFPRINTF(PF_DEBUG_MISC,
4913                                     ("pf: ICMP error message too short "
4914                                     "(udp)\n"));
4915                                 return (PF_DROP);
4916                         }
4917
4918                         key.af = pd2.af;
4919                         key.proto = IPPROTO_UDP;
4920                         PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4921                         PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4922                         key.port[pd2.sidx] = uh.uh_sport;
4923                         key.port[pd2.didx] = uh.uh_dport;
4924
4925                         STATE_LOOKUP(kif, &key, direction, *state, m);
4926
4927                         /* translate source/destination address, if necessary */
4928                         if ((*state)->key[PF_SK_WIRE] !=
4929                             (*state)->key[PF_SK_STACK]) {
4930                                 struct pf_state_key *nk =
4931                                     (*state)->key[pd->didx];
4932
4933                                 if (PF_ANEQ(pd2.src,
4934                                     &nk->addr[pd2.sidx], pd2.af) ||
4935                                     nk->port[pd2.sidx] != uh.uh_sport)
4936                                         pf_change_icmp(pd2.src, &uh.uh_sport,
4937                                             daddr, &nk->addr[pd2.sidx],
4938                                             nk->port[pd2.sidx], &uh.uh_sum,
4939                                             pd2.ip_sum, icmpsum,
4940                                             pd->ip_sum, 1, pd2.af);
4941
4942                                 if (PF_ANEQ(pd2.dst,
4943                                     &nk->addr[pd2.didx], pd2.af) ||
4944                                     nk->port[pd2.didx] != uh.uh_dport)
4945                                         pf_change_icmp(pd2.dst, &uh.uh_dport,
4946                                             NULL, /* XXX Inbound NAT? */
4947                                             &nk->addr[pd2.didx],
4948                                             nk->port[pd2.didx], &uh.uh_sum,
4949                                             pd2.ip_sum, icmpsum,
4950                                             pd->ip_sum, 1, pd2.af);
4951
4952                                 switch (pd2.af) {
4953 #ifdef INET
4954                                 case AF_INET:
4955                                         m_copyback(m, off, ICMP_MINLEN,
4956                                             (caddr_t)pd->hdr.icmp);
4957                                         m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4958                                         break;
4959 #endif /* INET */
4960 #ifdef INET6
4961                                 case AF_INET6:
4962                                         m_copyback(m, off,
4963                                             sizeof(struct icmp6_hdr),
4964                                             (caddr_t)pd->hdr.icmp6);
4965                                         m_copyback(m, ipoff2, sizeof(h2_6),
4966                                             (caddr_t)&h2_6);
4967                                         break;
4968 #endif /* INET6 */
4969                                 }
4970                                 m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
4971                         }
4972
4973                         return (PF_PASS);
4974                         break;
4975                 }
4976 #ifdef INET
4977                 case IPPROTO_ICMP: {
4978                         struct icmp             iih;
4979
4980                         if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
4981                             NULL, reason, pd2.af)) {
4982                                 DPFPRINTF(PF_DEBUG_MISC,
4983                                     ("pf: ICMP error message too short i"
4984                                     "(icmp)\n"));
4985                                 return (PF_DROP);
4986                         }
4987
4988                         key.af = pd2.af;
4989                         key.proto = IPPROTO_ICMP;
4990                         PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4991                         PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4992                         key.port[0] = key.port[1] = iih.icmp_id;
4993
4994                         STATE_LOOKUP(kif, &key, direction, *state, m);
4995
4996                         /* translate source/destination address, if necessary */
4997                         if ((*state)->key[PF_SK_WIRE] !=
4998                             (*state)->key[PF_SK_STACK]) {
4999                                 struct pf_state_key *nk =
5000                                     (*state)->key[pd->didx];
5001
5002                                 if (PF_ANEQ(pd2.src,
5003                                     &nk->addr[pd2.sidx], pd2.af) ||
5004                                     nk->port[pd2.sidx] != iih.icmp_id)
5005                                         pf_change_icmp(pd2.src, &iih.icmp_id,
5006                                             daddr, &nk->addr[pd2.sidx],
5007                                             nk->port[pd2.sidx], NULL,
5008                                             pd2.ip_sum, icmpsum,
5009                                             pd->ip_sum, 0, AF_INET);
5010
5011                                 if (PF_ANEQ(pd2.dst,
5012                                     &nk->addr[pd2.didx], pd2.af) ||
5013                                     nk->port[pd2.didx] != iih.icmp_id)
5014                                         pf_change_icmp(pd2.dst, &iih.icmp_id,
5015                                             NULL, /* XXX Inbound NAT? */
5016                                             &nk->addr[pd2.didx],
5017                                             nk->port[pd2.didx], NULL,
5018                                             pd2.ip_sum, icmpsum,
5019                                             pd->ip_sum, 0, AF_INET);
5020
5021                                 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
5022                                 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5023                                 m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
5024                         }
5025                         return (PF_PASS);
5026                         break;
5027                 }
5028 #endif /* INET */
5029 #ifdef INET6
5030                 case IPPROTO_ICMPV6: {
5031                         struct icmp6_hdr        iih;
5032
5033                         if (!pf_pull_hdr(m, off2, &iih,
5034                             sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
5035                                 DPFPRINTF(PF_DEBUG_MISC,
5036                                     ("pf: ICMP error message too short "
5037                                     "(icmp6)\n"));
5038                                 return (PF_DROP);
5039                         }
5040
5041                         key.af = pd2.af;
5042                         key.proto = IPPROTO_ICMPV6;
5043                         PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5044                         PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5045                         key.port[0] = key.port[1] = iih.icmp6_id;
5046
5047                         STATE_LOOKUP(kif, &key, direction, *state, m);
5048
5049                         /* translate source/destination address, if necessary */
5050                         if ((*state)->key[PF_SK_WIRE] !=
5051                             (*state)->key[PF_SK_STACK]) {
5052                                 struct pf_state_key *nk =
5053                                     (*state)->key[pd->didx];
5054
5055                                 if (PF_ANEQ(pd2.src,
5056                                     &nk->addr[pd2.sidx], pd2.af) ||
5057                                     nk->port[pd2.sidx] != iih.icmp6_id)
5058                                         pf_change_icmp(pd2.src, &iih.icmp6_id,
5059                                             daddr, &nk->addr[pd2.sidx],
5060                                             nk->port[pd2.sidx], NULL,
5061                                             pd2.ip_sum, icmpsum,
5062                                             pd->ip_sum, 0, AF_INET6);
5063
5064                                 if (PF_ANEQ(pd2.dst,
5065                                     &nk->addr[pd2.didx], pd2.af) ||
5066                                     nk->port[pd2.didx] != iih.icmp6_id)
5067                                         pf_change_icmp(pd2.dst, &iih.icmp6_id,
5068                                             NULL, /* XXX Inbound NAT? */
5069                                             &nk->addr[pd2.didx],
5070                                             nk->port[pd2.didx], NULL,
5071                                             pd2.ip_sum, icmpsum,
5072                                             pd->ip_sum, 0, AF_INET6);
5073
5074                                 m_copyback(m, off, sizeof(struct icmp6_hdr),
5075                                     (caddr_t)pd->hdr.icmp6);
5076                                 m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
5077                                 m_copyback(m, off2, sizeof(struct icmp6_hdr),
5078                                     (caddr_t)&iih);
5079                         }
5080
5081                         return (PF_PASS);
5082                         break;
5083                 }
5084 #endif /* INET6 */
5085                 default: {
5086                         key.af = pd2.af;
5087                         key.proto = pd2.proto;
5088                         PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5089                         PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5090                         key.port[0] = key.port[1] = 0;
5091
5092                         STATE_LOOKUP(kif, &key, direction, *state, m);
5093
5094                         /* translate source/destination address, if necessary */
5095                         if ((*state)->key[PF_SK_WIRE] !=
5096                             (*state)->key[PF_SK_STACK]) {
5097                                 struct pf_state_key *nk =
5098                                     (*state)->key[pd->didx];
5099
5100                                 if (PF_ANEQ(pd2.src,
5101                                     &nk->addr[pd2.sidx], pd2.af))
5102                                         pf_change_icmp(pd2.src, NULL, daddr,
5103                                             &nk->addr[pd2.sidx], 0, NULL,
5104                                             pd2.ip_sum, icmpsum,
5105                                             pd->ip_sum, 0, pd2.af);
5106
5107                                 if (PF_ANEQ(pd2.dst,
5108                                     &nk->addr[pd2.didx], pd2.af))
5109                                         pf_change_icmp(pd2.src, NULL,
5110                                             NULL, /* XXX Inbound NAT? */
5111                                             &nk->addr[pd2.didx], 0, NULL,
5112                                             pd2.ip_sum, icmpsum,
5113                                             pd->ip_sum, 0, pd2.af);
5114
5115                                 switch (pd2.af) {
5116 #ifdef INET
5117                                 case AF_INET:
5118                                         m_copyback(m, off, ICMP_MINLEN,
5119                                             (caddr_t)pd->hdr.icmp);
5120                                         m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5121                                         break;
5122 #endif /* INET */
5123 #ifdef INET6
5124                                 case AF_INET6:
5125                                         m_copyback(m, off,
5126                                             sizeof(struct icmp6_hdr),
5127                                             (caddr_t)pd->hdr.icmp6);
5128                                         m_copyback(m, ipoff2, sizeof(h2_6),
5129                                             (caddr_t)&h2_6);
5130                                         break;
5131 #endif /* INET6 */
5132                                 }
5133                         }
5134                         return (PF_PASS);
5135                         break;
5136                 }
5137                 }
5138         }
5139 }
5140
5141 int
5142 pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
5143     struct mbuf *m, struct pf_pdesc *pd)
5144 {
5145         struct pf_state_peer    *src, *dst;
5146         struct pf_state_key_cmp  key;
5147
5148         key.af = pd->af;
5149         key.proto = pd->proto;
5150         if (direction == PF_IN) {
5151                 PF_ACPY(&key.addr[0], pd->src, key.af);
5152                 PF_ACPY(&key.addr[1], pd->dst, key.af);
5153                 key.port[0] = key.port[1] = 0;
5154         } else {
5155                 PF_ACPY(&key.addr[1], pd->src, key.af);
5156                 PF_ACPY(&key.addr[0], pd->dst, key.af);
5157                 key.port[1] = key.port[0] = 0;
5158         }
5159
5160         STATE_LOOKUP(kif, &key, direction, *state, m);
5161
5162         if (direction == (*state)->direction) {
5163                 src = &(*state)->src;
5164                 dst = &(*state)->dst;
5165         } else {
5166                 src = &(*state)->dst;
5167                 dst = &(*state)->src;
5168         }
5169
5170         /* update states */
5171         if (src->state < PFOTHERS_SINGLE)
5172                 src->state = PFOTHERS_SINGLE;
5173         if (dst->state == PFOTHERS_SINGLE)
5174                 dst->state = PFOTHERS_MULTIPLE;
5175
5176         /* update expire time */
5177         (*state)->expire = time_second;
5178         if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5179                 (*state)->timeout = PFTM_OTHER_MULTIPLE;
5180         else
5181                 (*state)->timeout = PFTM_OTHER_SINGLE;
5182
5183         /* translate source/destination address, if necessary */
5184         if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5185                 struct pf_state_key *nk = (*state)->key[pd->didx];
5186
5187                 KKASSERT(nk);
5188                 KKASSERT(pd);
5189                 KKASSERT(pd->src);
5190                 KKASSERT(pd->dst);
5191                 switch (pd->af) {
5192 #ifdef INET
5193                 case AF_INET:
5194                         if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5195                                 pf_change_a(&pd->src->v4.s_addr,
5196                                     pd->ip_sum,
5197                                     nk->addr[pd->sidx].v4.s_addr,
5198                                     0);
5199
5200
5201                         if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5202                                 pf_change_a(&pd->dst->v4.s_addr,
5203                                     pd->ip_sum,
5204                                     nk->addr[pd->didx].v4.s_addr,
5205                                     0);
5206
5207                                 break;
5208 #endif /* INET */
5209 #ifdef INET6
5210                 case AF_INET6:
5211                         if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5212                                 PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5213
5214                         if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5215                                 PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5216 #endif /* INET6 */
5217                 }
5218         }
5219         return (PF_PASS);
5220 }
5221
5222 /*
5223  * ipoff and off are measured from the start of the mbuf chain.
5224  * h must be at "ipoff" on the mbuf chain.
5225  */
5226 void *
5227 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5228     u_short *actionp, u_short *reasonp, sa_family_t af)
5229 {
5230         switch (af) {
5231 #ifdef INET
5232         case AF_INET: {
5233                 struct ip       *h = mtod(m, struct ip *);
5234                 u_int16_t        fragoff = (h->ip_off & IP_OFFMASK) << 3;
5235
5236                 if (fragoff) {
5237                         if (fragoff >= len)
5238                                 ACTION_SET(actionp, PF_PASS);
5239                         else {
5240                                 ACTION_SET(actionp, PF_DROP);
5241                                 REASON_SET(reasonp, PFRES_FRAG);
5242                         }
5243                         return (NULL);
5244                 }
5245                 if (m->m_pkthdr.len < off + len ||
5246                     h->ip_len < off + len) {
5247                         ACTION_SET(actionp, PF_DROP);
5248                         REASON_SET(reasonp, PFRES_SHORT);
5249                         return (NULL);
5250                 }
5251                 break;
5252         }
5253 #endif /* INET */
5254 #ifdef INET6
5255         case AF_INET6: {
5256                 struct ip6_hdr  *h = mtod(m, struct ip6_hdr *);
5257
5258                 if (m->m_pkthdr.len < off + len ||
5259                     (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5260                     (unsigned)(off + len)) {
5261                         ACTION_SET(actionp, PF_DROP);
5262                         REASON_SET(reasonp, PFRES_SHORT);
5263                         return (NULL);
5264                 }
5265                 break;
5266         }
5267 #endif /* INET6 */
5268         }
5269         m_copydata(m, off, len, p);
5270         return (p);
5271 }
5272
5273 int
5274 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif)
5275 {
5276         struct sockaddr_in      *dst;
5277         int                      ret = 1;
5278         int                      check_mpath;
5279 #ifdef INET6
5280         struct sockaddr_in6     *dst6;
5281         struct route_in6         ro;
5282 #else
5283         struct route             ro;
5284 #endif
5285         struct radix_node       *rn;
5286         struct rtentry          *rt;
5287         struct ifnet            *ifp;
5288
5289         check_mpath = 0;
5290         bzero(&ro, sizeof(ro));
5291         switch (af) {
5292         case AF_INET:
5293                 dst = satosin(&ro.ro_dst);
5294                 dst->sin_family = AF_INET;
5295                 dst->sin_len = sizeof(*dst);
5296                 dst->sin_addr = addr->v4;
5297                 break;
5298 #ifdef INET6
5299         case AF_INET6:
5300                 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5301                 dst6->sin6_family = AF_INET6;
5302                 dst6->sin6_len = sizeof(*dst6);
5303                 dst6->sin6_addr = addr->v6;
5304                 break;
5305 #endif /* INET6 */
5306         default:
5307                 return (0);
5308         }
5309
5310         /* Skip checks for ipsec interfaces */
5311         if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5312                 goto out;
5313
5314         rtalloc_ign((struct route *)&ro, 0);
5315
5316         if (ro.ro_rt != NULL) {
5317                 /* No interface given, this is a no-route check */
5318                 if (kif == NULL)
5319                         goto out;
5320
5321                 if (kif->pfik_ifp == NULL) {
5322                         ret = 0;
5323                         goto out;
5324                 }
5325
5326                 /* Perform uRPF check if passed input interface */
5327                 ret = 0;
5328                 rn = (struct radix_node *)ro.ro_rt;
5329                 do {
5330                         rt = (struct rtentry *)rn;
5331                         ifp = rt->rt_ifp;
5332
5333                         if (kif->pfik_ifp == ifp)
5334                                 ret = 1;
5335                         rn = NULL;
5336                 } while (check_mpath == 1 && rn != NULL && ret == 0);
5337         } else
5338                 ret = 0;
5339 out:
5340         if (ro.ro_rt != NULL)
5341                 RTFREE(ro.ro_rt);
5342         return (ret);
5343 }
5344
5345 int
5346 pf_rtlabel_match(struct pf_addr *addr, sa_family_t af, struct pf_addr_wrap *aw)
5347 {
5348         struct sockaddr_in      *dst;
5349 #ifdef INET6
5350         struct sockaddr_in6     *dst6;
5351         struct route_in6         ro;
5352 #else
5353         struct route             ro;
5354 #endif
5355         int                      ret = 0;
5356
5357         ASSERT_LWKT_TOKEN_HELD(&pf_token);
5358
5359         bzero(&ro, sizeof(ro));
5360         switch (af) {
5361         case AF_INET:
5362                 dst = satosin(&ro.ro_dst);
5363                 dst->sin_family = AF_INET;
5364                 dst->sin_len = sizeof(*dst);
5365                 dst->sin_addr = addr->v4;
5366                 break;
5367 #ifdef INET6
5368         case AF_INET6:
5369                 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5370                 dst6->sin6_family = AF_INET6;
5371                 dst6->sin6_len = sizeof(*dst6);
5372                 dst6->sin6_addr = addr->v6;
5373                 break;
5374 #endif /* INET6 */
5375         default:
5376                 return (0);
5377         }
5378
5379 rtalloc_ign((struct route *)&ro, (RTF_CLONING | RTF_PRCLONING));
5380
5381         if (ro.ro_rt != NULL) {
5382                 RTFREE(ro.ro_rt);
5383         }
5384
5385         return (ret);
5386 }
5387
5388 #ifdef INET
5389 void
5390 pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5391     struct pf_state *s, struct pf_pdesc *pd)
5392 {
5393         struct mbuf             *m0, *m1;
5394         struct route             iproute;
5395         struct route            *ro = NULL;
5396         struct sockaddr_in      *dst;
5397         struct ip               *ip;
5398         struct ifnet            *ifp = NULL;
5399         struct pf_addr           naddr;
5400         struct pf_src_node      *sn = NULL;
5401         int                      error = 0;
5402         int sw_csum;
5403 #ifdef IPSEC
5404         struct m_tag            *mtag;
5405 #endif /* IPSEC */
5406
5407         ASSERT_LWKT_TOKEN_HELD(&pf_token);
5408
5409         if (m == NULL || *m == NULL || r == NULL ||
5410             (dir != PF_IN && dir != PF_OUT) || oifp == NULL)
5411                 panic("pf_route: invalid parameters");
5412
5413         if (((*m)->m_pkthdr.fw_flags & PF_MBUF_ROUTED) == 0) {
5414                 (*m)->m_pkthdr.fw_flags |= PF_MBUF_ROUTED;
5415                 (*m)->m_pkthdr.pf.routed = 1;
5416         } else {
5417                 if ((*m)->m_pkthdr.pf.routed++ > 3) {
5418                         m0 = *m;
5419                         *m = NULL;
5420                         goto bad;
5421                 }
5422         }
5423
5424         if (r->rt == PF_DUPTO) {
5425                 if ((m0 = m_dup(*m, MB_DONTWAIT)) == NULL) {
5426                         return;
5427                 }
5428         } else {
5429                 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5430                         return;
5431                 }
5432                 m0 = *m;
5433         }
5434
5435         if (m0->m_len < sizeof(struct ip)) {
5436                 DPFPRINTF(PF_DEBUG_URGENT,
5437                     ("pf_route: m0->m_len < sizeof(struct ip)\n"));
5438                 goto bad;
5439         }
5440
5441         ip = mtod(m0, struct ip *);
5442
5443         ro = &iproute;
5444         bzero((caddr_t)ro, sizeof(*ro));
5445         dst = satosin(&ro->ro_dst);
5446         dst->sin_family = AF_INET;
5447         dst->sin_len = sizeof(*dst);
5448         dst->sin_addr = ip->ip_dst;
5449
5450         if (r->rt == PF_FASTROUTE) {
5451                 rtalloc(ro);
5452                 if (ro->ro_rt == 0) {
5453                         ipstat.ips_noroute++;
5454                         goto bad;
5455                 }
5456
5457                 ifp = ro->ro_rt->rt_ifp;
5458                 ro->ro_rt->rt_use++;
5459
5460                 if (ro->ro_rt->rt_flags & RTF_GATEWAY)
5461                         dst = satosin(ro->ro_rt->rt_gateway);
5462         } else {
5463                 if (TAILQ_EMPTY(&r->rpool.list)) {
5464                         DPFPRINTF(PF_DEBUG_URGENT,
5465                             ("pf_route: TAILQ_EMPTY(&r->rpool.list)\n"));
5466                         goto bad;
5467                 }
5468                 if (s == NULL) {
5469                         pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5470                             &naddr, NULL, &sn);
5471                         if (!PF_AZERO(&naddr, AF_INET))
5472                                 dst->sin_addr.s_addr = naddr.v4.s_addr;
5473                         ifp = r->rpool.cur->kif ?
5474                             r->rpool.cur->kif->pfik_ifp : NULL;
5475                 } else {
5476                         if (!PF_AZERO(&s->rt_addr, AF_INET))
5477                                 dst->sin_addr.s_addr =
5478                                     s->rt_addr.v4.s_addr;
5479                         ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5480                 }
5481         }
5482         if (ifp == NULL)
5483                 goto bad;
5484
5485         if (oifp != ifp) {
5486                 if (pf_test(PF_OUT, ifp, &m0, NULL, NULL) != PF_PASS) {
5487                         goto bad;
5488                 } else if (m0 == NULL) {
5489                         goto done;
5490                 }
5491                 if (m0->m_len < sizeof(struct ip)) {
5492                         DPFPRINTF(PF_DEBUG_URGENT,
5493                             ("pf_route: m0->m_len < sizeof(struct ip)\n"));
5494                         goto bad;
5495                 }
5496                 ip = mtod(m0, struct ip *);
5497         }
5498
5499         /* Copied from FreeBSD 5.1-CURRENT ip_output. */
5500         m0->m_pkthdr.csum_flags |= CSUM_IP;
5501         sw_csum = m0->m_pkthdr.csum_flags & ~ifp->if_hwassist;
5502         if (sw_csum & CSUM_DELAY_DATA) {
5503                 in_delayed_cksum(m0);
5504                 sw_csum &= ~CSUM_DELAY_DATA;
5505         }
5506         m0->m_pkthdr.csum_flags &= ifp->if_hwassist;
5507
5508         if (ip->ip_len <= ifp->if_mtu ||
5509             (ifp->if_hwassist & CSUM_FRAGMENT &&
5510                 (ip->ip_off & IP_DF) == 0)) {
5511                 ip->ip_len = htons(ip->ip_len);
5512                 ip->ip_off = htons(ip->ip_off);
5513                 ip->ip_sum = 0;
5514                 if (sw_csum & CSUM_DELAY_IP) {
5515                         /* From KAME */
5516                         if (ip->ip_v == IPVERSION &&
5517                             (ip->ip_hl << 2) == sizeof(*ip)) {
5518                                 ip->ip_sum = in_cksum_hdr(ip);
5519                         } else {
5520                                 ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5521                         }
5522                 }
5523                 lwkt_reltoken(&pf_token);
5524                 error = ifp->if_output(ifp, m0, sintosa(dst), ro->ro_rt);
5525                 lwkt_gettoken(&pf_token);
5526                 goto done;
5527         }
5528
5529         /*
5530          * Too large for interface; fragment if possible.
5531          * Must be able to put at least 8 bytes per fragment.
5532          */
5533         if (ip->ip_off & IP_DF) {
5534                 ipstat.ips_cantfrag++;
5535                 if (r->rt != PF_DUPTO) {
5536                         icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5537                             ifp->if_mtu);
5538                         goto done;
5539                 } else
5540                         goto bad;
5541         }
5542
5543         m1 = m0;
5544         error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist, sw_csum);
5545         if (error) {
5546                 goto bad;
5547         }
5548
5549         for (m0 = m1; m0; m0 = m1) {
5550                 m1 = m0->m_nextpkt;
5551                 m0->m_nextpkt = 0;
5552                 if (error == 0) {
5553                         lwkt_reltoken(&pf_token);
5554                         error = (*ifp->if_output)(ifp, m0, sintosa(dst),
5555                                                   NULL);
5556                         lwkt_gettoken(&pf_token);
5557                 } else
5558                         m_freem(m0);
5559         }
5560
5561         if (error == 0)
5562                 ipstat.ips_fragmented++;
5563
5564 done:
5565         if (r->rt != PF_DUPTO)
5566                 *m = NULL;
5567         if (ro == &iproute && ro->ro_rt)
5568                 RTFREE(ro->ro_rt);
5569         return;
5570
5571 bad:
5572         m_freem(m0);
5573         goto done;
5574 }
5575 #endif /* INET */
5576
5577 #ifdef INET6
5578 void
5579 pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5580     struct pf_state *s, struct pf_pdesc *pd)
5581 {
5582         struct mbuf             *m0;
5583         struct route_in6         ip6route;
5584         struct route_in6        *ro;
5585         struct sockaddr_in6     *dst;
5586         struct ip6_hdr          *ip6;
5587         struct ifnet            *ifp = NULL;
5588         struct pf_addr           naddr;
5589         struct pf_src_node      *sn = NULL;
5590         int                      error = 0;
5591
5592         if (m == NULL || *m == NULL || r == NULL ||
5593             (dir != PF_IN && dir != PF_OUT) || oifp == NULL)
5594                 panic("pf_route6: invalid parameters");
5595
5596         if (((*m)->m_pkthdr.fw_flags & PF_MBUF_ROUTED) == 0) {
5597                 (*m)->m_pkthdr.fw_flags |= PF_MBUF_ROUTED;
5598                 (*m)->m_pkthdr.pf.routed = 1;
5599         } else {
5600                 if ((*m)->m_pkthdr.pf.routed++ > 3) {
5601                         m0 = *m;
5602                         *m = NULL;
5603                         goto bad;
5604                 }
5605         }
5606
5607         if (r->rt == PF_DUPTO) {
5608                 if ((m0 = m_dup(*m, MB_DONTWAIT)) == NULL)
5609                         return;
5610         } else {
5611                 if ((r->rt == PF_REPLYTO) == (r->direction == dir))
5612                         return;
5613                 m0 = *m;
5614         }
5615
5616         if (m0->m_len < sizeof(struct ip6_hdr)) {
5617                 DPFPRINTF(PF_DEBUG_URGENT,
5618                     ("pf_route6: m0->m_len < sizeof(struct ip6_hdr)\n"));
5619                 goto bad;
5620         }
5621         ip6 = mtod(m0, struct ip6_hdr *);
5622
5623         ro = &ip6route;
5624         bzero((caddr_t)ro, sizeof(*ro));
5625         dst = (struct sockaddr_in6 *)&ro->ro_dst;
5626         dst->sin6_family = AF_INET6;
5627         dst->sin6_len = sizeof(*dst);
5628         dst->sin6_addr = ip6->ip6_dst;
5629
5630         /*
5631          * DragonFly doesn't zero the auxillary pkghdr fields, only fw_flags,
5632          * so make sure pf.flags is clear.
5633          *
5634          * Cheat. XXX why only in the v6 case???
5635          */
5636         if (r->rt == PF_FASTROUTE) {
5637                 m0->m_pkthdr.fw_flags |= PF_MBUF_TAGGED;
5638                 m0->m_pkthdr.pf.flags = 0;
5639                 /* XXX Re-Check when Upgrading to > 4.4 */
5640                 m0->m_pkthdr.pf.statekey = NULL;
5641                 ip6_output(m0, NULL, NULL, 0, NULL, NULL, NULL);
5642                 return;
5643         }
5644
5645         if (TAILQ_EMPTY(&r->rpool.list)) {
5646                 DPFPRINTF(PF_DEBUG_URGENT,
5647                     ("pf_route6: TAILQ_EMPTY(&r->rpool.list)\n"));
5648                 goto bad;
5649         }
5650         if (s == NULL) {
5651                 pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5652                     &naddr, NULL, &sn);
5653                 if (!PF_AZERO(&naddr, AF_INET6))
5654                         PF_ACPY((struct pf_addr *)&dst->sin6_addr,
5655                             &naddr, AF_INET6);
5656                 ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
5657         } else {
5658                 if (!PF_AZERO(&s->rt_addr, AF_INET6))
5659                         PF_ACPY((struct pf_addr *)&dst->sin6_addr,
5660                             &s->rt_addr, AF_INET6);
5661                 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5662         }
5663         if (ifp == NULL)
5664                 goto bad;
5665
5666         if (oifp != ifp) {
5667                 if (pf_test6(PF_OUT, ifp, &m0, NULL, NULL) != PF_PASS) {
5668                         goto bad;
5669                 } else if (m0 == NULL) {
5670                         goto done;
5671                 }
5672                 if (m0->m_len < sizeof(struct ip6_hdr)) {
5673                         DPFPRINTF(PF_DEBUG_URGENT,
5674                             ("pf_route6: m0->m_len < sizeof(struct ip6_hdr)\n"));
5675                         goto bad;
5676                 }
5677                 ip6 = mtod(m0, struct ip6_hdr *);
5678         }
5679
5680         /*
5681          * If the packet is too large for the outgoing interface,
5682          * send back an icmp6 error.
5683          */
5684         if (IN6_IS_ADDR_LINKLOCAL(&dst->sin6_addr))
5685                 dst->sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5686         if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu) {
5687                 error = nd6_output(ifp, ifp, m0, dst, NULL);
5688         } else {
5689                 in6_ifstat_inc(ifp, ifs6_in_toobig);
5690                 if (r->rt != PF_DUPTO)
5691                         icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5692                 else
5693                         goto bad;
5694         }
5695
5696 done:
5697         if (r->rt != PF_DUPTO)
5698                 *m = NULL;
5699         return;
5700
5701 bad:
5702         m_freem(m0);
5703         goto done;
5704 }
5705 #endif /* INET6 */
5706
5707
5708 /*
5709  * check protocol (tcp/udp/icmp/icmp6) checksum and set mbuf flag
5710  *   off is the offset where the protocol header starts
5711  *   len is the total length of protocol header plus payload
5712  * returns 0 when the checksum is valid, otherwise returns 1.
5713  */
5714 /*
5715  * XXX
5716  * FreeBSD supports cksum offload for the following drivers.
5717  * em(4), gx(4), lge(4), nge(4), ti(4), xl(4)
5718  * If we can make full use of it we would outperform ipfw/ipfilter in
5719  * very heavy traffic. 
5720  * I have not tested 'cause I don't have NICs that supports cksum offload.
5721  * (There might be problems. Typical phenomena would be
5722  *   1. No route message for UDP packet.
5723  *   2. No connection acceptance from external hosts regardless of rule set.)
5724  */
5725 int
5726 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p,
5727     sa_family_t af)
5728 {
5729         u_int16_t sum = 0;
5730         int hw_assist = 0;
5731         struct ip *ip;
5732
5733         if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
5734                 return (1);
5735         if (m->m_pkthdr.len < off + len)
5736                 return (1);
5737
5738         switch (p) {
5739         case IPPROTO_TCP:
5740         case IPPROTO_UDP:
5741                 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5742                         if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5743                                 sum = m->m_pkthdr.csum_data;
5744                         } else {
5745                                 ip = mtod(m, struct ip *);      
5746                                 sum = in_pseudo(ip->ip_src.s_addr,
5747                                         ip->ip_dst.s_addr, htonl((u_short)len +
5748                                         m->m_pkthdr.csum_data + p));
5749                         }
5750                         sum ^= 0xffff;
5751                         ++hw_assist;
5752                 }
5753                 break;
5754         case IPPROTO_ICMP:
5755 #ifdef INET6
5756         case IPPROTO_ICMPV6:
5757 #endif /* INET6 */
5758                 break;
5759         default:
5760                 return (1);
5761         }
5762
5763         if (!hw_assist) {
5764                 switch (af) {
5765                 case AF_INET:
5766                         if (p == IPPROTO_ICMP) {
5767                                 if (m->m_len < off)
5768                                         return (1);
5769                                 m->m_data += off;
5770                                 m->m_len -= off;
5771                                 sum = in_cksum(m, len);
5772                                 m->m_data -= off;
5773                                 m->m_len += off;
5774                         } else {
5775                                 if (m->m_len < sizeof(struct ip))
5776                                         return (1);
5777                                 sum = in_cksum_range(m, p, off, len);
5778                                 if (sum == 0) {
5779                                         m->m_pkthdr.csum_flags |=
5780                                             (CSUM_DATA_VALID |
5781                                              CSUM_PSEUDO_HDR);
5782                                         m->m_pkthdr.csum_data = 0xffff;
5783                                 }
5784                         }
5785                         break;
5786 #ifdef INET6
5787                 case AF_INET6:
5788                         if (m->m_len < sizeof(struct ip6_hdr))
5789                                 return (1);
5790                         sum = in6_cksum(m, p, off, len);
5791                         /*
5792                          * XXX
5793                          * IPv6 H/W cksum off-load not supported yet!
5794                          *
5795                          * if (sum == 0) {
5796                          *      m->m_pkthdr.csum_flags |=
5797                          *          (CSUM_DATA_VALID|CSUM_PSEUDO_HDR);
5798                          *      m->m_pkthdr.csum_data = 0xffff;
5799                          *}
5800                          */
5801                         break;
5802 #endif /* INET6 */
5803                 default:
5804                         return (1);
5805                 }
5806         }
5807         if (sum) {
5808                 switch (p) {
5809                 case IPPROTO_TCP:
5810                         tcpstat.tcps_rcvbadsum++;
5811                         break;
5812                 case IPPROTO_UDP:
5813                         udpstat.udps_badsum++;
5814                         break;
5815                 case IPPROTO_ICMP:
5816                         icmpstat.icps_checksum++;
5817                         break;
5818 #ifdef INET6
5819                 case IPPROTO_ICMPV6:
5820                         icmp6stat.icp6s_checksum++;
5821                         break;
5822 #endif /* INET6 */
5823                 }
5824                 return (1);
5825         }
5826         return (0);
5827 }
5828
5829 struct pf_divert *
5830 pf_find_divert(struct mbuf *m)
5831 {
5832         struct m_tag    *mtag;
5833
5834         if ((mtag = m_tag_find(m, PACKET_TAG_PF_DIVERT, NULL)) == NULL)
5835                 return (NULL);
5836
5837         return ((struct pf_divert *)(mtag + 1));
5838 }
5839
5840 struct pf_divert *
5841 pf_get_divert(struct mbuf *m)
5842 {
5843         struct m_tag    *mtag;
5844
5845         if ((mtag = m_tag_find(m, PACKET_TAG_PF_DIVERT, NULL)) == NULL) {
5846                 mtag = m_tag_get(PACKET_TAG_PF_DIVERT, sizeof(struct pf_divert),
5847                     M_NOWAIT);
5848                 if (mtag == NULL)
5849                         return (NULL);
5850                 bzero(mtag + 1, sizeof(struct pf_divert));
5851                 m_tag_prepend(m, mtag);
5852         }
5853
5854         return ((struct pf_divert *)(mtag + 1));
5855 }
5856
5857 #ifdef INET
5858 int
5859 pf_test(int dir, struct ifnet *ifp, struct mbuf **m0,
5860     struct ether_header *eh, struct inpcb *inp)
5861 {
5862         struct pfi_kif          *kif;
5863         u_short                  action, reason = 0, log = 0;
5864         struct mbuf             *m = *m0;
5865         struct ip               *h = NULL;
5866         struct pf_rule          *a = NULL, *r = &pf_default_rule, *tr, *nr;
5867         struct pf_state         *s = NULL;
5868         struct pf_ruleset       *ruleset = NULL;
5869         struct pf_pdesc          pd;
5870         int                      off, dirndx, pqid = 0;
5871
5872         if (!pf_status.running)
5873                 return (PF_PASS);
5874
5875         memset(&pd, 0, sizeof(pd));
5876         if (ifp->if_type == IFT_CARP && ifp->if_carpdev)
5877                 kif = (struct pfi_kif *)ifp->if_carpdev->if_pf_kif;
5878         else
5879                 kif = (struct pfi_kif *)ifp->if_pf_kif;
5880
5881         if (kif == NULL) {
5882                 DPFPRINTF(PF_DEBUG_URGENT,
5883                     ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
5884                 return (PF_DROP);
5885         }
5886         if (kif->pfik_flags & PFI_IFLAG_SKIP)
5887                 return (PF_PASS);
5888
5889 #ifdef DIAGNOSTIC
5890         if ((m->m_flags & M_PKTHDR) == 0)
5891                 panic("non-M_PKTHDR is passed to pf_test");
5892 #endif /* DIAGNOSTIC */
5893
5894         if (m->m_pkthdr.len < (int)sizeof(*h)) {
5895                 action = PF_DROP;
5896                 REASON_SET(&reason, PFRES_SHORT);
5897                 log = 1;
5898                 goto done;
5899         }
5900
5901         /*
5902          * DragonFly doesn't zero the auxillary pkghdr fields, only fw_flags,
5903          * so make sure pf.flags is clear.
5904          */
5905         if (m->m_pkthdr.fw_flags & PF_MBUF_TAGGED)
5906                 return (PF_PASS);
5907         m->m_pkthdr.pf.flags = 0;
5908         /* Re-Check when updating to > 4.4 */
5909         m->m_pkthdr.pf.statekey = NULL;
5910
5911         /* We do IP header normalization and packet reassembly here */
5912         if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
5913                 action = PF_DROP;
5914                 goto done;
5915         }
5916         m = *m0;        /* pf_normalize messes with m0 */
5917         h = mtod(m, struct ip *);
5918
5919         off = h->ip_hl << 2;
5920         if (off < (int)sizeof(*h)) {
5921                 action = PF_DROP;
5922                 REASON_SET(&reason, PFRES_SHORT);
5923                 log = 1;
5924                 goto done;
5925         }
5926
5927         pd.src = (struct pf_addr *)&h->ip_src;
5928         pd.dst = (struct pf_addr *)&h->ip_dst;
5929         pd.sport = pd.dport = NULL;
5930         pd.ip_sum = &h->ip_sum;
5931         pd.proto_sum = NULL;
5932         pd.proto = h->ip_p;
5933         pd.dir = dir;
5934         pd.sidx = (dir == PF_IN) ? 0 : 1;
5935         pd.didx = (dir == PF_IN) ? 1 : 0;
5936         pd.af = AF_INET;
5937         pd.tos = h->ip_tos;
5938         pd.tot_len = h->ip_len;
5939         pd.eh = eh;
5940
5941         /* handle fragments that didn't get reassembled by normalization */
5942         if (h->ip_off & (IP_MF | IP_OFFMASK)) {
5943                 action = pf_test_fragment(&r, dir, kif, m, h,
5944                     &pd, &a, &ruleset);
5945                 goto done;
5946         }
5947
5948         switch (h->ip_p) {
5949
5950         case IPPROTO_TCP: {
5951                 struct tcphdr   th;
5952
5953                 pd.hdr.tcp = &th;
5954                 if (!pf_pull_hdr(m, off, &th, sizeof(th),
5955                     &action, &reason, AF_INET)) {
5956                         log = action != PF_PASS;
5957                         goto done;
5958                 }
5959                 pd.p_len = pd.tot_len - off - (th.th_off << 2);
5960                 if ((th.th_flags & TH_ACK) && pd.p_len == 0)
5961                         pqid = 1;
5962                 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
5963                 if (action == PF_DROP)
5964                         goto done;
5965                 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
5966                     &reason);
5967                 if (action == PF_PASS) {
5968                         pfsync_update_state(s);
5969                         r = s->rule.ptr;
5970                         a = s->anchor.ptr;
5971                         log = s->log;
5972                 } else if (s == NULL)
5973                         action = pf_test_rule(&r, &s, dir, kif,
5974                             m, off, h, &pd, &a, &ruleset, NULL, inp);
5975                 break;
5976         }
5977
5978         case IPPROTO_UDP: {
5979                 struct udphdr   uh;
5980
5981                 pd.hdr.udp = &uh;
5982                 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
5983                     &action, &reason, AF_INET)) {
5984                         log = action != PF_PASS;
5985                         goto done;
5986                 }
5987                 if (uh.uh_dport == 0 ||
5988                     ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
5989                     ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
5990                         action = PF_DROP;
5991                         REASON_SET(&reason, PFRES_SHORT);
5992                         goto done;
5993                 }
5994                 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
5995                 if (action == PF_PASS) {
5996                         pfsync_update_state(s);
5997                         r = s->rule.ptr;
5998                         a = s->anchor.ptr;
5999                         log = s->log;
6000                 } else if (s == NULL)
6001                         action = pf_test_rule(&r, &s, dir, kif,
6002                             m, off, h, &pd, &a, &ruleset, NULL, inp);
6003                 break;
6004         }
6005
6006         case IPPROTO_ICMP: {
6007                 struct icmp     ih;
6008
6009                 pd.hdr.icmp = &ih;
6010                 if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
6011                     &action, &reason, AF_INET)) {
6012                         log = action != PF_PASS;
6013                         goto done;
6014                 }
6015                 action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
6016                     &reason);
6017                 if (action == PF_PASS) {
6018                         pfsync_update_state(s);
6019                         r = s->rule.ptr;
6020                         a = s->anchor.ptr;
6021                         log = s->log;
6022                 } else if (s == NULL)
6023                         action = pf_test_rule(&r, &s, dir, kif,
6024                             m, off, h, &pd, &a, &ruleset, NULL, inp);
6025                 break;
6026         }
6027
6028         default:
6029                 action = pf_test_state_other(&s, dir, kif, m, &pd);
6030                 if (action == PF_PASS) {
6031                         pfsync_update_state(s);
6032                         r = s->rule.ptr;
6033                         a = s->anchor.ptr;
6034                         log = s->log;
6035                 } else if (s == NULL)
6036                         action = pf_test_rule(&r, &s, dir, kif, m, off, h,
6037                             &pd, &a, &ruleset, NULL, inp);
6038                 break;
6039         }
6040
6041 done:
6042         if (action == PF_PASS && h->ip_hl > 5 &&
6043             !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6044                 action = PF_DROP;
6045                 REASON_SET(&reason, PFRES_IPOPTIONS);
6046                 log = 1;
6047                 DPFPRINTF(PF_DEBUG_MISC,
6048                     ("pf: dropping packet with ip options\n"));
6049         }
6050
6051         if ((s && s->tag) || r->rtableid)
6052                 pf_tag_packet(m, s ? s->tag : 0, r->rtableid);
6053
6054 #if 0
6055         if (dir == PF_IN && s && s->key[PF_SK_STACK])
6056                 m->m_pkthdr.pf.statekey = s->key[PF_SK_STACK];
6057 #endif
6058
6059 #ifdef ALTQ
6060         if (action == PF_PASS && r->qid) {
6061                 m->m_pkthdr.fw_flags |= PF_MBUF_STRUCTURE;
6062                 if (pqid || (pd.tos & IPTOS_LOWDELAY))
6063                         m->m_pkthdr.pf.qid = r->pqid;
6064                 else
6065                         m->m_pkthdr.pf.qid = r->qid;
6066                 m->m_pkthdr.pf.ecn_af = AF_INET;
6067                 m->m_pkthdr.pf.hdr = h;
6068                 /* add connection hash for fairq */
6069                 if (s) {
6070                         /* for fairq */
6071                         m->m_pkthdr.pf.state_hash = s->hash;
6072                         m->m_pkthdr.pf.flags |= PF_TAG_STATE_HASHED;
6073                 }
6074         }
6075 #endif /* ALTQ */
6076
6077         /*
6078          * connections redirected to loopback should not match sockets
6079          * bound specifically to loopback due to security implications,
6080          * see tcp_input() and in_pcblookup_listen().
6081          */
6082         if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6083             pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6084             (s->nat_rule.ptr->action == PF_RDR ||
6085             s->nat_rule.ptr->action == PF_BINAT) &&
6086             (ntohl(pd.dst->v4.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
6087                 m->m_pkthdr.pf.flags |= PF_TAG_TRANSLATE_LOCALHOST;
6088
6089         if (dir == PF_IN && action == PF_PASS && r->divert.port) {
6090                 struct pf_divert *divert;
6091
6092                 if ((divert = pf_get_divert(m))) {
6093                         m->m_pkthdr.pf.flags |= PF_TAG_DIVERTED;
6094                         divert->port = r->divert.port;
6095                         divert->addr.ipv4 = r->divert.addr.v4;
6096                 }
6097         }
6098
6099         if (log) {
6100                 struct pf_rule *lr;
6101
6102                 if (s != NULL && s->nat_rule.ptr != NULL &&
6103                     s->nat_rule.ptr->log & PF_LOG_ALL)
6104                         lr = s->nat_rule.ptr;
6105                 else
6106                         lr = r;
6107                 PFLOG_PACKET(kif, h, m, AF_INET, dir, reason, lr, a, ruleset,
6108                     &pd);
6109         }
6110
6111         kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6112         kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
6113
6114         if (action == PF_PASS || r->action == PF_DROP) {
6115                 dirndx = (dir == PF_OUT);
6116                 r->packets[dirndx]++;
6117                 r->bytes[dirndx] += pd.tot_len;
6118                 if (a != NULL) {
6119                         a->packets[dirndx]++;
6120                         a->bytes[dirndx] += pd.tot_len;
6121                 }
6122                 if (s != NULL) {
6123                         if (s->nat_rule.ptr != NULL) {
6124                                 s->nat_rule.ptr->packets[dirndx]++;
6125                                 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6126                         }
6127                         if (s->src_node != NULL) {
6128                                 s->src_node->packets[dirndx]++;
6129                                 s->src_node->bytes[dirndx] += pd.tot_len;
6130                         }
6131                         if (s->nat_src_node != NULL) {
6132                                 s->nat_src_node->packets[dirndx]++;
6133                                 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6134                         }
6135                         dirndx = (dir == s->direction) ? 0 : 1;
6136                         s->packets[dirndx]++;
6137                         s->bytes[dirndx] += pd.tot_len;
6138                 }
6139                 tr = r;
6140                 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6141                 if (nr != NULL && r == &pf_default_rule)
6142                         tr = nr;
6143                 if (tr->src.addr.type == PF_ADDR_TABLE)
6144                         pfr_update_stats(tr->src.addr.p.tbl,
6145                             (s == NULL) ? pd.src :
6146                             &s->key[(s->direction == PF_IN)]->
6147                                 addr[(s->direction == PF_OUT)],
6148                             pd.af, pd.tot_len, dir == PF_OUT,
6149                             r->action == PF_PASS, tr->src.neg);
6150                 if (tr->dst.addr.type == PF_ADDR_TABLE)
6151                         pfr_update_stats(tr->dst.addr.p.tbl,
6152                             (s == NULL) ? pd.dst :
6153                             &s->key[(s->direction == PF_IN)]->
6154                                 addr[(s->direction == PF_IN)],
6155                             pd.af, pd.tot_len, dir == PF_OUT,
6156                             r->action == PF_PASS, tr->dst.neg);
6157         }
6158
6159
6160         if (action == PF_SYNPROXY_DROP) {
6161                 m_freem(*m0);
6162                 *m0 = NULL;
6163                 action = PF_PASS;
6164         } else if (r->rt)
6165                 /* pf_route can free the mbuf causing *m0 to become NULL */
6166                 pf_route(m0, r, dir, kif->pfik_ifp, s, &pd);
6167
6168         return (action);
6169 }
6170 #endif /* INET */
6171
6172 #ifdef INET6
6173 int
6174 pf_test6(int dir, struct ifnet *ifp, struct mbuf **m0,
6175     struct ether_header *eh, struct inpcb *inp)
6176 {
6177         struct pfi_kif          *kif;
6178         u_short                  action, reason = 0, log = 0;
6179         struct mbuf             *m = *m0, *n = NULL;
6180         struct ip6_hdr          *h = NULL;
6181         struct pf_rule          *a = NULL, *r = &pf_default_rule, *tr, *nr;
6182         struct pf_state         *s = NULL;
6183         struct pf_ruleset       *ruleset = NULL;
6184         struct pf_pdesc          pd;
6185         int                      off, terminal = 0, dirndx, rh_cnt = 0;
6186
6187         if (!pf_status.running)
6188                 return (PF_PASS);
6189
6190         memset(&pd, 0, sizeof(pd));
6191         if (ifp->if_type == IFT_CARP && ifp->if_carpdev)
6192                 kif = (struct pfi_kif *)ifp->if_carpdev->if_pf_kif;
6193         else
6194                 kif = (struct pfi_kif *)ifp->if_pf_kif;
6195
6196         if (kif == NULL) {
6197                 DPFPRINTF(PF_DEBUG_URGENT,
6198                     ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6199                 return (PF_DROP);
6200         }
6201         if (kif->pfik_flags & PFI_IFLAG_SKIP)
6202                 return (PF_PASS);
6203
6204 #ifdef DIAGNOSTIC
6205         if ((m->m_flags & M_PKTHDR) == 0)
6206                 panic("non-M_PKTHDR is passed to pf_test6");
6207 #endif /* DIAGNOSTIC */
6208
6209         if (m->m_pkthdr.len < (int)sizeof(*h)) {
6210                 action = PF_DROP;
6211                 REASON_SET(&reason, PFRES_SHORT);
6212                 log = 1;
6213                 goto done;
6214         }
6215
6216         /*
6217          * DragonFly doesn't zero the auxillary pkghdr fields, only fw_flags,
6218          * so make sure pf.flags is clear.
6219          */
6220         if (m->m_pkthdr.fw_flags & PF_MBUF_TAGGED)
6221                 return (PF_PASS);
6222         m->m_pkthdr.pf.flags = 0;
6223         /* Re-Check when updating to > 4.4 */
6224         m->m_pkthdr.pf.statekey = NULL;
6225
6226         /* We do IP header normalization and packet reassembly here */
6227         if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6228                 action = PF_DROP;
6229                 goto done;
6230         }
6231         m = *m0;        /* pf_normalize messes with m0 */
6232         h = mtod(m, struct ip6_hdr *);
6233
6234 #if 1
6235         /*
6236          * we do not support jumbogram yet.  if we keep going, zero ip6_plen
6237          * will do something bad, so drop the packet for now.
6238          */
6239         if (htons(h->ip6_plen) == 0) {
6240                 action = PF_DROP;
6241                 REASON_SET(&reason, PFRES_NORM);        /*XXX*/
6242                 goto done;
6243         }
6244 #endif
6245
6246         pd.src = (struct pf_addr *)&h->ip6_src;
6247         pd.dst = (struct pf_addr *)&h->ip6_dst;
6248         pd.sport = pd.dport = NULL;
6249         pd.ip_sum = NULL;
6250         pd.proto_sum = NULL;
6251         pd.dir = dir;
6252         pd.sidx = (dir == PF_IN) ? 0 : 1;
6253         pd.didx = (dir == PF_IN) ? 1 : 0;
6254         pd.af = AF_INET6;
6255         pd.tos = 0;
6256         pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6257         pd.eh = eh;
6258
6259         off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6260         pd.proto = h->ip6_nxt;
6261         do {
6262                 switch (pd.proto) {
6263                 case IPPROTO_FRAGMENT:
6264                         action = pf_test_fragment(&r, dir, kif, m, h,
6265                             &pd, &a, &ruleset);
6266                         if (action == PF_DROP)
6267                                 REASON_SET(&reason, PFRES_FRAG);
6268                         goto done;
6269                 case IPPROTO_ROUTING: {
6270                         struct ip6_rthdr rthdr;
6271
6272                         if (rh_cnt++) {
6273                                 DPFPRINTF(PF_DEBUG_MISC,
6274                                     ("pf: IPv6 more than one rthdr\n"));
6275                                 action = PF_DROP;
6276                                 REASON_SET(&reason, PFRES_IPOPTIONS);
6277                                 log = 1;
6278                                 goto done;
6279                         }
6280                         if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6281                             &reason, pd.af)) {
6282                                 DPFPRINTF(PF_DEBUG_MISC,
6283                                     ("pf: IPv6 short rthdr\n"));
6284                                 action = PF_DROP;
6285                                 REASON_SET(&reason, PFRES_SHORT);
6286                                 log = 1;
6287                                 goto done;
6288                         }
6289                         if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6290                                 DPFPRINTF(PF_DEBUG_MISC,
6291                                     ("pf: IPv6 rthdr0\n"));
6292                                 action = PF_DROP;
6293                                 REASON_SET(&reason, PFRES_IPOPTIONS);
6294                                 log = 1;
6295                                 goto done;
6296                         }
6297                         /* FALLTHROUGH */
6298                 }
6299                 case IPPROTO_AH:
6300                 case IPPROTO_HOPOPTS:
6301                 case IPPROTO_DSTOPTS: {
6302                         /* get next header and header length */
6303                         struct ip6_ext  opt6;
6304
6305                         if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6306                             NULL, &reason, pd.af)) {
6307                                 DPFPRINTF(PF_DEBUG_MISC,
6308                                     ("pf: IPv6 short opt\n"));
6309                                 action = PF_DROP;
6310                                 log = 1;
6311                                 goto done;
6312                         }
6313                         if (pd.proto == IPPROTO_AH)
6314                                 off += (opt6.ip6e_len + 2) * 4;
6315                         else
6316                                 off += (opt6.ip6e_len + 1) * 8;
6317                         pd.proto = opt6.ip6e_nxt;
6318                         /* goto the next header */
6319                         break;
6320                 }
6321                 default:
6322                         terminal++;
6323                         break;
6324                 }
6325         } while (!terminal);
6326
6327         /* if there's no routing header, use unmodified mbuf for checksumming */
6328         if (!n)
6329                 n = m;
6330
6331         switch (pd.proto) {
6332
6333         case IPPROTO_TCP: {
6334                 struct tcphdr   th;
6335
6336                 pd.hdr.tcp = &th;
6337                 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6338                     &action, &reason, AF_INET6)) {
6339                         log = action != PF_PASS;
6340                         goto done;
6341                 }
6342                 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6343                 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6344                 if (action == PF_DROP)
6345                         goto done;
6346                 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6347                     &reason);
6348                 if (action == PF_PASS) {
6349                         pfsync_update_state(s);
6350                         r = s->rule.ptr;
6351                         a = s->anchor.ptr;
6352                         log = s->log;
6353                 } else if (s == NULL)
6354                         action = pf_test_rule(&r, &s, dir, kif,
6355                             m, off, h, &pd, &a, &ruleset, NULL, inp);
6356                 break;
6357         }
6358
6359         case IPPROTO_UDP: {
6360                 struct udphdr   uh;
6361
6362                 pd.hdr.udp = &uh;
6363                 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6364                     &action, &reason, AF_INET6)) {
6365                         log = action != PF_PASS;
6366                         goto done;
6367                 }
6368                 if (uh.uh_dport == 0 ||
6369                     ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6370                     ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6371                         action = PF_DROP;
6372                         REASON_SET(&reason, PFRES_SHORT);
6373                         goto done;
6374                 }
6375                 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6376                 if (action == PF_PASS) {
6377                         pfsync_update_state(s);
6378                         r = s->rule.ptr;
6379                         a = s->anchor.ptr;
6380                         log = s->log;
6381                 } else if (s == NULL)
6382                         action = pf_test_rule(&r, &s, dir, kif,
6383                             m, off, h, &pd, &a, &ruleset, NULL, inp);
6384                 break;
6385         }
6386
6387         case IPPROTO_ICMPV6: {
6388                 struct icmp6_hdr        ih;
6389
6390                 pd.hdr.icmp6 = &ih;
6391                 if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6392                     &action, &reason, AF_INET6)) {
6393                         log = action != PF_PASS;
6394                         goto done;
6395                 }
6396                 action = pf_test_state_icmp(&s, dir, kif,
6397                     m, off, h, &pd, &reason);
6398                 if (action == PF_PASS) {
6399                         pfsync_update_state(s);
6400                         r = s->rule.ptr;
6401                         a = s->anchor.ptr;
6402                         log = s->log;
6403                 } else if (s == NULL)
6404                         action = pf_test_rule(&r, &s, dir, kif,
6405                             m, off, h, &pd, &a, &ruleset, NULL, inp);
6406                 break;
6407         }
6408
6409         default:
6410                 action = pf_test_state_other(&s, dir, kif, m, &pd);
6411                 if (action == PF_PASS) {
6412                         pfsync_update_state(s);
6413                         r = s->rule.ptr;
6414                         a = s->anchor.ptr;
6415                         log = s->log;
6416                 } else if (s == NULL)
6417                         action = pf_test_rule(&r, &s, dir, kif, m, off, h,
6418                             &pd, &a, &ruleset, NULL, inp);
6419                 break;
6420         }
6421
6422 done:
6423         if (n != m) {
6424                 m_freem(n);
6425                 n = NULL;
6426         }
6427
6428         /* handle dangerous IPv6 extension headers. */
6429         if (action == PF_PASS && rh_cnt &&
6430             !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6431                 action = PF_DROP;
6432                 REASON_SET(&reason, PFRES_IPOPTIONS);
6433                 log = 1;
6434                 DPFPRINTF(PF_DEBUG_MISC,
6435                     ("pf: dropping packet with dangerous v6 headers\n"));
6436         }
6437
6438         if ((s && s->tag) || r->rtableid)
6439                 pf_tag_packet(m, s ? s->tag : 0, r->rtableid);
6440
6441 #if 0
6442         if (dir == PF_IN && s && s->key[PF_SK_STACK])
6443                 m->m_pkthdr.pf.statekey = s->key[PF_SK_STACK];
6444 #endif
6445
6446 #ifdef ALTQ
6447         if (action == PF_PASS && r->qid) {
6448                 m->m_pkthdr.fw_flags |= PF_MBUF_STRUCTURE;
6449                 if (pd.tos & IPTOS_LOWDELAY)
6450                         m->m_pkthdr.pf.qid = r->pqid;
6451                 else
6452                         m->m_pkthdr.pf.qid = r->qid;
6453                 m->m_pkthdr.pf.ecn_af = AF_INET6;
6454                 m->m_pkthdr.pf.hdr = h;
6455                 if (s) {
6456                         /* for fairq */
6457                         m->m_pkthdr.pf.state_hash = s->hash;
6458                         m->m_pkthdr.pf.flags |= PF_TAG_STATE_HASHED;
6459                 }
6460         }
6461 #endif /* ALTQ */
6462
6463         if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6464             pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6465             (s->nat_rule.ptr->action == PF_RDR ||
6466             s->nat_rule.ptr->action == PF_BINAT) &&
6467             IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6468                 m->m_pkthdr.pf.flags |= PF_TAG_TRANSLATE_LOCALHOST;
6469
6470         if (dir == PF_IN && action == PF_PASS && r->divert.port) {
6471                 struct pf_divert *divert;
6472
6473                 if ((divert = pf_get_divert(m))) {
6474                         m->m_pkthdr.pf.flags |= PF_TAG_DIVERTED;
6475                         divert->port = r->divert.port;
6476                         divert->addr.ipv6 = r->divert.addr.v6;
6477                 }
6478         }
6479
6480         if (log) {
6481                 struct pf_rule *lr;
6482
6483                 if (s != NULL && s->nat_rule.ptr != NULL &&
6484                     s->nat_rule.ptr->log & PF_LOG_ALL)
6485                         lr = s->nat_rule.ptr;
6486                 else
6487                         lr = r;
6488                 PFLOG_PACKET(kif, h, m, AF_INET6, dir, reason, lr, a, ruleset,
6489                     &pd);
6490         }
6491
6492         kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6493         kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6494
6495         if (action == PF_PASS || r->action == PF_DROP) {
6496                 dirndx = (dir == PF_OUT);
6497                 r->packets[dirndx]++;
6498                 r->bytes[dirndx] += pd.tot_len;
6499                 if (a != NULL) {
6500                         a->packets[dirndx]++;
6501                         a->bytes[dirndx] += pd.tot_len;
6502                 }
6503                 if (s != NULL) {
6504                         if (s->nat_rule.ptr != NULL) {
6505                                 s->nat_rule.ptr->packets[dirndx]++;
6506                                 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6507                         }
6508                         if (s->src_node != NULL) {
6509                                 s->src_node->packets[dirndx]++;
6510                                 s->src_node->bytes[dirndx] += pd.tot_len;
6511                         }
6512                         if (s->nat_src_node != NULL) {
6513                                 s->nat_src_node->packets[dirndx]++;
6514                                 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6515                         }
6516                         dirndx = (dir == s->direction) ? 0 : 1;
6517                         s->packets[dirndx]++;
6518                         s->bytes[dirndx] += pd.tot_len;
6519                 }
6520                 tr = r;
6521                 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6522                 if (nr != NULL && r == &pf_default_rule)
6523                         tr = nr;
6524                 if (tr->src.addr.type == PF_ADDR_TABLE)
6525                         pfr_update_stats(tr->src.addr.p.tbl,
6526                             (s == NULL) ? pd.src :
6527                             &s->key[(s->direction == PF_IN)]->addr[0],
6528                             pd.af, pd.tot_len, dir == PF_OUT,
6529                             r->action == PF_PASS, tr->src.neg);
6530                 if (tr->dst.addr.type == PF_ADDR_TABLE)
6531                         pfr_update_stats(tr->dst.addr.p.tbl,
6532                             (s == NULL) ? pd.dst :
6533                             &s->key[(s->direction == PF_IN)]->addr[1],
6534                             pd.af, pd.tot_len, dir == PF_OUT,
6535                             r->action == PF_PASS, tr->dst.neg);
6536         }
6537
6538
6539         if (action == PF_SYNPROXY_DROP) {
6540                 m_freem(*m0);
6541                 *m0 = NULL;
6542                 action = PF_PASS;
6543         } else if (r->rt)
6544                 /* pf_route6 can free the mbuf causing *m0 to become NULL */
6545                 pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd);
6546
6547         return (action);
6548 }
6549 #endif /* INET6 */
6550
6551 int
6552 pf_check_congestion(struct ifqueue *ifq)
6553 {
6554                 return (0);
6555 }