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