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