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