Deleted Added
full compact
pf.c (284577) pf.c (285940)
1/*-
2 * Copyright (c) 2001 Daniel Hartmeier
3 * Copyright (c) 2002 - 2008 Henning Brauer
4 * Copyright (c) 2012 Gleb Smirnoff <glebius@FreeBSD.org>
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 *
11 * - Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * - Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
21 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
22 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
24 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 *
31 * Effort sponsored in part by the Defense Advanced Research Projects
32 * Agency (DARPA) and Air Force Research Laboratory, Air Force
33 * Materiel Command, USAF, under agreement number F30602-01-2-0537.
34 *
35 * $OpenBSD: pf.c,v 1.634 2009/02/27 12:37:45 henning Exp $
36 */
37
38#include <sys/cdefs.h>
1/*-
2 * Copyright (c) 2001 Daniel Hartmeier
3 * Copyright (c) 2002 - 2008 Henning Brauer
4 * Copyright (c) 2012 Gleb Smirnoff <glebius@FreeBSD.org>
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 *
11 * - Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * - Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
21 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
22 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
24 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 *
31 * Effort sponsored in part by the Defense Advanced Research Projects
32 * Agency (DARPA) and Air Force Research Laboratory, Air Force
33 * Materiel Command, USAF, under agreement number F30602-01-2-0537.
34 *
35 * $OpenBSD: pf.c,v 1.634 2009/02/27 12:37:45 henning Exp $
36 */
37
38#include <sys/cdefs.h>
39__FBSDID("$FreeBSD: stable/10/sys/netpfil/pf/pf.c 284577 2015-06-18 20:59:48Z kp $");
39__FBSDID("$FreeBSD: stable/10/sys/netpfil/pf/pf.c 285940 2015-07-28 09:13:55Z glebius $");
40
41#include "opt_inet.h"
42#include "opt_inet6.h"
43#include "opt_bpf.h"
44#include "opt_pf.h"
45
46#include <sys/param.h>
47#include <sys/bus.h>
48#include <sys/endian.h>
49#include <sys/hash.h>
50#include <sys/interrupt.h>
51#include <sys/kernel.h>
52#include <sys/kthread.h>
53#include <sys/limits.h>
54#include <sys/mbuf.h>
55#include <sys/md5.h>
56#include <sys/random.h>
57#include <sys/refcount.h>
58#include <sys/socket.h>
59#include <sys/sysctl.h>
60#include <sys/taskqueue.h>
61#include <sys/ucred.h>
62
63#include <net/if.h>
64#include <net/if_types.h>
65#include <net/route.h>
66#include <net/radix_mpath.h>
67#include <net/vnet.h>
68
69#include <net/pfvar.h>
70#include <net/if_pflog.h>
71#include <net/if_pfsync.h>
72
73#include <netinet/in_pcb.h>
74#include <netinet/in_var.h>
75#include <netinet/ip.h>
76#include <netinet/ip_fw.h>
77#include <netinet/ip_icmp.h>
78#include <netinet/icmp_var.h>
79#include <netinet/ip_var.h>
80#include <netinet/tcp.h>
81#include <netinet/tcp_fsm.h>
82#include <netinet/tcp_seq.h>
83#include <netinet/tcp_timer.h>
84#include <netinet/tcp_var.h>
85#include <netinet/udp.h>
86#include <netinet/udp_var.h>
87
88#include <netpfil/ipfw/ip_fw_private.h> /* XXX: only for DIR_IN/DIR_OUT */
89
90#ifdef INET6
91#include <netinet/ip6.h>
92#include <netinet/icmp6.h>
93#include <netinet6/nd6.h>
94#include <netinet6/ip6_var.h>
95#include <netinet6/in6_pcb.h>
96#endif /* INET6 */
97
98#include <machine/in_cksum.h>
99#include <security/mac/mac_framework.h>
100
101#define DPFPRINTF(n, x) if (V_pf_status.debug >= (n)) printf x
102
103/*
104 * Global variables
105 */
106
107/* state tables */
108VNET_DEFINE(struct pf_altqqueue, pf_altqs[2]);
109VNET_DEFINE(struct pf_palist, pf_pabuf);
110VNET_DEFINE(struct pf_altqqueue *, pf_altqs_active);
111VNET_DEFINE(struct pf_altqqueue *, pf_altqs_inactive);
112VNET_DEFINE(struct pf_kstatus, pf_status);
113
114VNET_DEFINE(u_int32_t, ticket_altqs_active);
115VNET_DEFINE(u_int32_t, ticket_altqs_inactive);
116VNET_DEFINE(int, altqs_inactive_open);
117VNET_DEFINE(u_int32_t, ticket_pabuf);
118
119VNET_DEFINE(MD5_CTX, pf_tcp_secret_ctx);
120#define V_pf_tcp_secret_ctx VNET(pf_tcp_secret_ctx)
121VNET_DEFINE(u_char, pf_tcp_secret[16]);
122#define V_pf_tcp_secret VNET(pf_tcp_secret)
123VNET_DEFINE(int, pf_tcp_secret_init);
124#define V_pf_tcp_secret_init VNET(pf_tcp_secret_init)
125VNET_DEFINE(int, pf_tcp_iss_off);
126#define V_pf_tcp_iss_off VNET(pf_tcp_iss_off)
127
128/*
129 * Queue for pf_intr() sends.
130 */
131static MALLOC_DEFINE(M_PFTEMP, "pf_temp", "pf(4) temporary allocations");
132struct pf_send_entry {
133 STAILQ_ENTRY(pf_send_entry) pfse_next;
134 struct mbuf *pfse_m;
135 enum {
136 PFSE_IP,
137 PFSE_IP6,
138 PFSE_ICMP,
139 PFSE_ICMP6,
140 } pfse_type;
141 union {
142 struct route ro;
143 struct {
144 int type;
145 int code;
146 int mtu;
147 } icmpopts;
148 } u;
149#define pfse_ro u.ro
150#define pfse_icmp_type u.icmpopts.type
151#define pfse_icmp_code u.icmpopts.code
152#define pfse_icmp_mtu u.icmpopts.mtu
153};
154
155STAILQ_HEAD(pf_send_head, pf_send_entry);
156static VNET_DEFINE(struct pf_send_head, pf_sendqueue);
157#define V_pf_sendqueue VNET(pf_sendqueue)
158
159static struct mtx pf_sendqueue_mtx;
160#define PF_SENDQ_LOCK() mtx_lock(&pf_sendqueue_mtx)
161#define PF_SENDQ_UNLOCK() mtx_unlock(&pf_sendqueue_mtx)
162
163/*
164 * Queue for pf_overload_task() tasks.
165 */
166struct pf_overload_entry {
167 SLIST_ENTRY(pf_overload_entry) next;
168 struct pf_addr addr;
169 sa_family_t af;
170 uint8_t dir;
171 struct pf_rule *rule;
172};
173
174SLIST_HEAD(pf_overload_head, pf_overload_entry);
175static VNET_DEFINE(struct pf_overload_head, pf_overloadqueue);
176#define V_pf_overloadqueue VNET(pf_overloadqueue)
177static VNET_DEFINE(struct task, pf_overloadtask);
178#define V_pf_overloadtask VNET(pf_overloadtask)
179
180static struct mtx pf_overloadqueue_mtx;
181#define PF_OVERLOADQ_LOCK() mtx_lock(&pf_overloadqueue_mtx)
182#define PF_OVERLOADQ_UNLOCK() mtx_unlock(&pf_overloadqueue_mtx)
183
184VNET_DEFINE(struct pf_rulequeue, pf_unlinked_rules);
185struct mtx pf_unlnkdrules_mtx;
186
187static VNET_DEFINE(uma_zone_t, pf_sources_z);
188#define V_pf_sources_z VNET(pf_sources_z)
189uma_zone_t pf_mtag_z;
190VNET_DEFINE(uma_zone_t, pf_state_z);
191VNET_DEFINE(uma_zone_t, pf_state_key_z);
192
193VNET_DEFINE(uint64_t, pf_stateid[MAXCPU]);
194#define PFID_CPUBITS 8
195#define PFID_CPUSHIFT (sizeof(uint64_t) * NBBY - PFID_CPUBITS)
196#define PFID_CPUMASK ((uint64_t)((1 << PFID_CPUBITS) - 1) << PFID_CPUSHIFT)
197#define PFID_MAXID (~PFID_CPUMASK)
198CTASSERT((1 << PFID_CPUBITS) >= MAXCPU);
199
200static void pf_src_tree_remove_state(struct pf_state *);
201static void pf_init_threshold(struct pf_threshold *, u_int32_t,
202 u_int32_t);
203static void pf_add_threshold(struct pf_threshold *);
204static int pf_check_threshold(struct pf_threshold *);
205
206static void pf_change_ap(struct pf_addr *, u_int16_t *,
207 u_int16_t *, u_int16_t *, struct pf_addr *,
208 u_int16_t, u_int8_t, sa_family_t);
209static int pf_modulate_sack(struct mbuf *, int, struct pf_pdesc *,
210 struct tcphdr *, struct pf_state_peer *);
211static void pf_change_icmp(struct pf_addr *, u_int16_t *,
212 struct pf_addr *, struct pf_addr *, u_int16_t,
213 u_int16_t *, u_int16_t *, u_int16_t *,
214 u_int16_t *, u_int8_t, sa_family_t);
215static void pf_send_tcp(struct mbuf *,
216 const struct pf_rule *, sa_family_t,
217 const struct pf_addr *, const struct pf_addr *,
218 u_int16_t, u_int16_t, u_int32_t, u_int32_t,
219 u_int8_t, u_int16_t, u_int16_t, u_int8_t, int,
220 u_int16_t, struct ifnet *);
221static void pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
222 sa_family_t, struct pf_rule *);
223static void pf_detach_state(struct pf_state *);
224static int pf_state_key_attach(struct pf_state_key *,
225 struct pf_state_key *, struct pf_state *);
226static void pf_state_key_detach(struct pf_state *, int);
227static int pf_state_key_ctor(void *, int, void *, int);
228static u_int32_t pf_tcp_iss(struct pf_pdesc *);
229static int pf_test_rule(struct pf_rule **, struct pf_state **,
230 int, struct pfi_kif *, struct mbuf *, int,
231 struct pf_pdesc *, struct pf_rule **,
232 struct pf_ruleset **, struct inpcb *);
233static int pf_create_state(struct pf_rule *, struct pf_rule *,
234 struct pf_rule *, struct pf_pdesc *,
235 struct pf_src_node *, struct pf_state_key *,
236 struct pf_state_key *, struct mbuf *, int,
237 u_int16_t, u_int16_t, int *, struct pfi_kif *,
238 struct pf_state **, int, u_int16_t, u_int16_t,
239 int);
240static int pf_test_fragment(struct pf_rule **, int,
241 struct pfi_kif *, struct mbuf *, void *,
242 struct pf_pdesc *, struct pf_rule **,
243 struct pf_ruleset **);
244static int pf_tcp_track_full(struct pf_state_peer *,
245 struct pf_state_peer *, struct pf_state **,
246 struct pfi_kif *, struct mbuf *, int,
247 struct pf_pdesc *, u_short *, int *);
248static int pf_tcp_track_sloppy(struct pf_state_peer *,
249 struct pf_state_peer *, struct pf_state **,
250 struct pf_pdesc *, u_short *);
251static int pf_test_state_tcp(struct pf_state **, int,
252 struct pfi_kif *, struct mbuf *, int,
253 void *, struct pf_pdesc *, u_short *);
254static int pf_test_state_udp(struct pf_state **, int,
255 struct pfi_kif *, struct mbuf *, int,
256 void *, struct pf_pdesc *);
257static int pf_test_state_icmp(struct pf_state **, int,
258 struct pfi_kif *, struct mbuf *, int,
259 void *, struct pf_pdesc *, u_short *);
260static int pf_test_state_other(struct pf_state **, int,
261 struct pfi_kif *, struct mbuf *, struct pf_pdesc *);
262static u_int8_t pf_get_wscale(struct mbuf *, int, u_int16_t,
263 sa_family_t);
264static u_int16_t pf_get_mss(struct mbuf *, int, u_int16_t,
265 sa_family_t);
266static u_int16_t pf_calc_mss(struct pf_addr *, sa_family_t,
267 int, u_int16_t);
268static int pf_check_proto_cksum(struct mbuf *, int, int,
269 u_int8_t, sa_family_t);
270static void pf_print_state_parts(struct pf_state *,
271 struct pf_state_key *, struct pf_state_key *);
272static int pf_addr_wrap_neq(struct pf_addr_wrap *,
273 struct pf_addr_wrap *);
274static struct pf_state *pf_find_state(struct pfi_kif *,
275 struct pf_state_key_cmp *, u_int);
276static int pf_src_connlimit(struct pf_state **);
277static void pf_overload_task(void *v, int pending);
278static int pf_insert_src_node(struct pf_src_node **,
279 struct pf_rule *, struct pf_addr *, sa_family_t);
280static u_int pf_purge_expired_states(u_int, int);
281static void pf_purge_unlinked_rules(void);
282static int pf_mtag_uminit(void *, int, int);
283static void pf_mtag_free(struct m_tag *);
284#ifdef INET
285static void pf_route(struct mbuf **, struct pf_rule *, int,
286 struct ifnet *, struct pf_state *,
287 struct pf_pdesc *);
288#endif /* INET */
289#ifdef INET6
290static void pf_change_a6(struct pf_addr *, u_int16_t *,
291 struct pf_addr *, u_int8_t);
292static void pf_route6(struct mbuf **, struct pf_rule *, int,
293 struct ifnet *, struct pf_state *,
294 struct pf_pdesc *);
295#endif /* INET6 */
296
297int in4_cksum(struct mbuf *m, u_int8_t nxt, int off, int len);
298
299VNET_DECLARE(int, pf_end_threads);
300
301VNET_DEFINE(struct pf_limit, pf_limits[PF_LIMIT_MAX]);
302
303#define PACKET_LOOPED(pd) ((pd)->pf_mtag && \
304 (pd)->pf_mtag->flags & PF_PACKET_LOOPED)
305
306#define STATE_LOOKUP(i, k, d, s, pd) \
307 do { \
308 (s) = pf_find_state((i), (k), (d)); \
309 if ((s) == NULL) \
310 return (PF_DROP); \
311 if (PACKET_LOOPED(pd)) \
312 return (PF_PASS); \
313 if ((d) == PF_OUT && \
314 (((s)->rule.ptr->rt == PF_ROUTETO && \
315 (s)->rule.ptr->direction == PF_OUT) || \
316 ((s)->rule.ptr->rt == PF_REPLYTO && \
317 (s)->rule.ptr->direction == PF_IN)) && \
318 (s)->rt_kif != NULL && \
319 (s)->rt_kif != (i)) \
320 return (PF_PASS); \
321 } while (0)
322
323#define BOUND_IFACE(r, k) \
324 ((r)->rule_flag & PFRULE_IFBOUND) ? (k) : V_pfi_all
325
326#define STATE_INC_COUNTERS(s) \
327 do { \
328 counter_u64_add(s->rule.ptr->states_cur, 1); \
329 counter_u64_add(s->rule.ptr->states_tot, 1); \
330 if (s->anchor.ptr != NULL) { \
331 counter_u64_add(s->anchor.ptr->states_cur, 1); \
332 counter_u64_add(s->anchor.ptr->states_tot, 1); \
333 } \
334 if (s->nat_rule.ptr != NULL) { \
335 counter_u64_add(s->nat_rule.ptr->states_cur, 1);\
336 counter_u64_add(s->nat_rule.ptr->states_tot, 1);\
337 } \
338 } while (0)
339
340#define STATE_DEC_COUNTERS(s) \
341 do { \
342 if (s->nat_rule.ptr != NULL) \
343 counter_u64_add(s->nat_rule.ptr->states_cur, -1);\
344 if (s->anchor.ptr != NULL) \
345 counter_u64_add(s->anchor.ptr->states_cur, -1); \
346 counter_u64_add(s->rule.ptr->states_cur, -1); \
347 } while (0)
348
349static MALLOC_DEFINE(M_PFHASH, "pf_hash", "pf(4) hash header structures");
350VNET_DEFINE(struct pf_keyhash *, pf_keyhash);
351VNET_DEFINE(struct pf_idhash *, pf_idhash);
352VNET_DEFINE(struct pf_srchash *, pf_srchash);
353
354SYSCTL_NODE(_net, OID_AUTO, pf, CTLFLAG_RW, 0, "pf(4)");
355
356u_long pf_hashmask;
357u_long pf_srchashmask;
358static u_long pf_hashsize;
359static u_long pf_srchashsize;
360
361SYSCTL_ULONG(_net_pf, OID_AUTO, states_hashsize, CTLFLAG_RDTUN,
362 &pf_hashsize, 0, "Size of pf(4) states hashtable");
363SYSCTL_ULONG(_net_pf, OID_AUTO, source_nodes_hashsize, CTLFLAG_RDTUN,
364 &pf_srchashsize, 0, "Size of pf(4) source nodes hashtable");
365
366VNET_DEFINE(void *, pf_swi_cookie);
367
368VNET_DEFINE(uint32_t, pf_hashseed);
369#define V_pf_hashseed VNET(pf_hashseed)
370
371int
372pf_addr_cmp(struct pf_addr *a, struct pf_addr *b, sa_family_t af)
373{
374
375 switch (af) {
376#ifdef INET
377 case AF_INET:
378 if (a->addr32[0] > b->addr32[0])
379 return (1);
380 if (a->addr32[0] < b->addr32[0])
381 return (-1);
382 break;
383#endif /* INET */
384#ifdef INET6
385 case AF_INET6:
386 if (a->addr32[3] > b->addr32[3])
387 return (1);
388 if (a->addr32[3] < b->addr32[3])
389 return (-1);
390 if (a->addr32[2] > b->addr32[2])
391 return (1);
392 if (a->addr32[2] < b->addr32[2])
393 return (-1);
394 if (a->addr32[1] > b->addr32[1])
395 return (1);
396 if (a->addr32[1] < b->addr32[1])
397 return (-1);
398 if (a->addr32[0] > b->addr32[0])
399 return (1);
400 if (a->addr32[0] < b->addr32[0])
401 return (-1);
402 break;
403#endif /* INET6 */
404 default:
405 panic("%s: unknown address family %u", __func__, af);
406 }
407 return (0);
408}
409
410static __inline uint32_t
411pf_hashkey(struct pf_state_key *sk)
412{
413 uint32_t h;
414
415 h = murmur3_aligned_32((uint32_t *)sk,
416 sizeof(struct pf_state_key_cmp),
417 V_pf_hashseed);
418
419 return (h & pf_hashmask);
420}
421
422static __inline uint32_t
423pf_hashsrc(struct pf_addr *addr, sa_family_t af)
424{
425 uint32_t h;
426
427 switch (af) {
428 case AF_INET:
429 h = murmur3_aligned_32((uint32_t *)&addr->v4,
430 sizeof(addr->v4), V_pf_hashseed);
431 break;
432 case AF_INET6:
433 h = murmur3_aligned_32((uint32_t *)&addr->v6,
434 sizeof(addr->v6), V_pf_hashseed);
435 break;
436 default:
437 panic("%s: unknown address family %u", __func__, af);
438 }
439
440 return (h & pf_srchashmask);
441}
442
443#ifdef INET6
444void
445pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
446{
447 switch (af) {
448#ifdef INET
449 case AF_INET:
450 dst->addr32[0] = src->addr32[0];
451 break;
452#endif /* INET */
453 case AF_INET6:
454 dst->addr32[0] = src->addr32[0];
455 dst->addr32[1] = src->addr32[1];
456 dst->addr32[2] = src->addr32[2];
457 dst->addr32[3] = src->addr32[3];
458 break;
459 }
460}
461#endif /* INET6 */
462
463static void
464pf_init_threshold(struct pf_threshold *threshold,
465 u_int32_t limit, u_int32_t seconds)
466{
467 threshold->limit = limit * PF_THRESHOLD_MULT;
468 threshold->seconds = seconds;
469 threshold->count = 0;
470 threshold->last = time_uptime;
471}
472
473static void
474pf_add_threshold(struct pf_threshold *threshold)
475{
476 u_int32_t t = time_uptime, diff = t - threshold->last;
477
478 if (diff >= threshold->seconds)
479 threshold->count = 0;
480 else
481 threshold->count -= threshold->count * diff /
482 threshold->seconds;
483 threshold->count += PF_THRESHOLD_MULT;
484 threshold->last = t;
485}
486
487static int
488pf_check_threshold(struct pf_threshold *threshold)
489{
490 return (threshold->count > threshold->limit);
491}
492
493static int
494pf_src_connlimit(struct pf_state **state)
495{
496 struct pf_overload_entry *pfoe;
497 int bad = 0;
498
499 PF_STATE_LOCK_ASSERT(*state);
500
501 (*state)->src_node->conn++;
502 (*state)->src.tcp_est = 1;
503 pf_add_threshold(&(*state)->src_node->conn_rate);
504
505 if ((*state)->rule.ptr->max_src_conn &&
506 (*state)->rule.ptr->max_src_conn <
507 (*state)->src_node->conn) {
508 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONN], 1);
509 bad++;
510 }
511
512 if ((*state)->rule.ptr->max_src_conn_rate.limit &&
513 pf_check_threshold(&(*state)->src_node->conn_rate)) {
514 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONNRATE], 1);
515 bad++;
516 }
517
518 if (!bad)
519 return (0);
520
521 /* Kill this state. */
522 (*state)->timeout = PFTM_PURGE;
523 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
524
525 if ((*state)->rule.ptr->overload_tbl == NULL)
526 return (1);
527
528 /* Schedule overloading and flushing task. */
529 pfoe = malloc(sizeof(*pfoe), M_PFTEMP, M_NOWAIT);
530 if (pfoe == NULL)
531 return (1); /* too bad :( */
532
533 bcopy(&(*state)->src_node->addr, &pfoe->addr, sizeof(pfoe->addr));
534 pfoe->af = (*state)->key[PF_SK_WIRE]->af;
535 pfoe->rule = (*state)->rule.ptr;
536 pfoe->dir = (*state)->direction;
537 PF_OVERLOADQ_LOCK();
538 SLIST_INSERT_HEAD(&V_pf_overloadqueue, pfoe, next);
539 PF_OVERLOADQ_UNLOCK();
540 taskqueue_enqueue(taskqueue_swi, &V_pf_overloadtask);
541
542 return (1);
543}
544
545static void
546pf_overload_task(void *v, int pending)
547{
548 struct pf_overload_head queue;
549 struct pfr_addr p;
550 struct pf_overload_entry *pfoe, *pfoe1;
551 uint32_t killed = 0;
552
553 CURVNET_SET((struct vnet *)v);
554
555 PF_OVERLOADQ_LOCK();
556 queue = V_pf_overloadqueue;
557 SLIST_INIT(&V_pf_overloadqueue);
558 PF_OVERLOADQ_UNLOCK();
559
560 bzero(&p, sizeof(p));
561 SLIST_FOREACH(pfoe, &queue, next) {
562 counter_u64_add(V_pf_status.lcounters[LCNT_OVERLOAD_TABLE], 1);
563 if (V_pf_status.debug >= PF_DEBUG_MISC) {
564 printf("%s: blocking address ", __func__);
565 pf_print_host(&pfoe->addr, 0, pfoe->af);
566 printf("\n");
567 }
568
569 p.pfra_af = pfoe->af;
570 switch (pfoe->af) {
571#ifdef INET
572 case AF_INET:
573 p.pfra_net = 32;
574 p.pfra_ip4addr = pfoe->addr.v4;
575 break;
576#endif
577#ifdef INET6
578 case AF_INET6:
579 p.pfra_net = 128;
580 p.pfra_ip6addr = pfoe->addr.v6;
581 break;
582#endif
583 }
584
585 PF_RULES_WLOCK();
586 pfr_insert_kentry(pfoe->rule->overload_tbl, &p, time_second);
587 PF_RULES_WUNLOCK();
588 }
589
590 /*
591 * Remove those entries, that don't need flushing.
592 */
593 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
594 if (pfoe->rule->flush == 0) {
595 SLIST_REMOVE(&queue, pfoe, pf_overload_entry, next);
596 free(pfoe, M_PFTEMP);
597 } else
598 counter_u64_add(
599 V_pf_status.lcounters[LCNT_OVERLOAD_FLUSH], 1);
600
601 /* If nothing to flush, return. */
602 if (SLIST_EMPTY(&queue)) {
603 CURVNET_RESTORE();
604 return;
605 }
606
607 for (int i = 0; i <= pf_hashmask; i++) {
608 struct pf_idhash *ih = &V_pf_idhash[i];
609 struct pf_state_key *sk;
610 struct pf_state *s;
611
612 PF_HASHROW_LOCK(ih);
613 LIST_FOREACH(s, &ih->states, entry) {
614 sk = s->key[PF_SK_WIRE];
615 SLIST_FOREACH(pfoe, &queue, next)
616 if (sk->af == pfoe->af &&
617 ((pfoe->rule->flush & PF_FLUSH_GLOBAL) ||
618 pfoe->rule == s->rule.ptr) &&
619 ((pfoe->dir == PF_OUT &&
620 PF_AEQ(&pfoe->addr, &sk->addr[1], sk->af)) ||
621 (pfoe->dir == PF_IN &&
622 PF_AEQ(&pfoe->addr, &sk->addr[0], sk->af)))) {
623 s->timeout = PFTM_PURGE;
624 s->src.state = s->dst.state = TCPS_CLOSED;
625 killed++;
626 }
627 }
628 PF_HASHROW_UNLOCK(ih);
629 }
630 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
631 free(pfoe, M_PFTEMP);
632 if (V_pf_status.debug >= PF_DEBUG_MISC)
633 printf("%s: %u states killed", __func__, killed);
634
635 CURVNET_RESTORE();
636}
637
638/*
639 * Can return locked on failure, so that we can consistently
640 * allocate and insert a new one.
641 */
642struct pf_src_node *
643pf_find_src_node(struct pf_addr *src, struct pf_rule *rule, sa_family_t af,
644 int returnlocked)
645{
646 struct pf_srchash *sh;
647 struct pf_src_node *n;
648
649 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_SEARCH], 1);
650
651 sh = &V_pf_srchash[pf_hashsrc(src, af)];
652 PF_HASHROW_LOCK(sh);
653 LIST_FOREACH(n, &sh->nodes, entry)
654 if (n->rule.ptr == rule && n->af == af &&
655 ((af == AF_INET && n->addr.v4.s_addr == src->v4.s_addr) ||
656 (af == AF_INET6 && bcmp(&n->addr, src, sizeof(*src)) == 0)))
657 break;
40
41#include "opt_inet.h"
42#include "opt_inet6.h"
43#include "opt_bpf.h"
44#include "opt_pf.h"
45
46#include <sys/param.h>
47#include <sys/bus.h>
48#include <sys/endian.h>
49#include <sys/hash.h>
50#include <sys/interrupt.h>
51#include <sys/kernel.h>
52#include <sys/kthread.h>
53#include <sys/limits.h>
54#include <sys/mbuf.h>
55#include <sys/md5.h>
56#include <sys/random.h>
57#include <sys/refcount.h>
58#include <sys/socket.h>
59#include <sys/sysctl.h>
60#include <sys/taskqueue.h>
61#include <sys/ucred.h>
62
63#include <net/if.h>
64#include <net/if_types.h>
65#include <net/route.h>
66#include <net/radix_mpath.h>
67#include <net/vnet.h>
68
69#include <net/pfvar.h>
70#include <net/if_pflog.h>
71#include <net/if_pfsync.h>
72
73#include <netinet/in_pcb.h>
74#include <netinet/in_var.h>
75#include <netinet/ip.h>
76#include <netinet/ip_fw.h>
77#include <netinet/ip_icmp.h>
78#include <netinet/icmp_var.h>
79#include <netinet/ip_var.h>
80#include <netinet/tcp.h>
81#include <netinet/tcp_fsm.h>
82#include <netinet/tcp_seq.h>
83#include <netinet/tcp_timer.h>
84#include <netinet/tcp_var.h>
85#include <netinet/udp.h>
86#include <netinet/udp_var.h>
87
88#include <netpfil/ipfw/ip_fw_private.h> /* XXX: only for DIR_IN/DIR_OUT */
89
90#ifdef INET6
91#include <netinet/ip6.h>
92#include <netinet/icmp6.h>
93#include <netinet6/nd6.h>
94#include <netinet6/ip6_var.h>
95#include <netinet6/in6_pcb.h>
96#endif /* INET6 */
97
98#include <machine/in_cksum.h>
99#include <security/mac/mac_framework.h>
100
101#define DPFPRINTF(n, x) if (V_pf_status.debug >= (n)) printf x
102
103/*
104 * Global variables
105 */
106
107/* state tables */
108VNET_DEFINE(struct pf_altqqueue, pf_altqs[2]);
109VNET_DEFINE(struct pf_palist, pf_pabuf);
110VNET_DEFINE(struct pf_altqqueue *, pf_altqs_active);
111VNET_DEFINE(struct pf_altqqueue *, pf_altqs_inactive);
112VNET_DEFINE(struct pf_kstatus, pf_status);
113
114VNET_DEFINE(u_int32_t, ticket_altqs_active);
115VNET_DEFINE(u_int32_t, ticket_altqs_inactive);
116VNET_DEFINE(int, altqs_inactive_open);
117VNET_DEFINE(u_int32_t, ticket_pabuf);
118
119VNET_DEFINE(MD5_CTX, pf_tcp_secret_ctx);
120#define V_pf_tcp_secret_ctx VNET(pf_tcp_secret_ctx)
121VNET_DEFINE(u_char, pf_tcp_secret[16]);
122#define V_pf_tcp_secret VNET(pf_tcp_secret)
123VNET_DEFINE(int, pf_tcp_secret_init);
124#define V_pf_tcp_secret_init VNET(pf_tcp_secret_init)
125VNET_DEFINE(int, pf_tcp_iss_off);
126#define V_pf_tcp_iss_off VNET(pf_tcp_iss_off)
127
128/*
129 * Queue for pf_intr() sends.
130 */
131static MALLOC_DEFINE(M_PFTEMP, "pf_temp", "pf(4) temporary allocations");
132struct pf_send_entry {
133 STAILQ_ENTRY(pf_send_entry) pfse_next;
134 struct mbuf *pfse_m;
135 enum {
136 PFSE_IP,
137 PFSE_IP6,
138 PFSE_ICMP,
139 PFSE_ICMP6,
140 } pfse_type;
141 union {
142 struct route ro;
143 struct {
144 int type;
145 int code;
146 int mtu;
147 } icmpopts;
148 } u;
149#define pfse_ro u.ro
150#define pfse_icmp_type u.icmpopts.type
151#define pfse_icmp_code u.icmpopts.code
152#define pfse_icmp_mtu u.icmpopts.mtu
153};
154
155STAILQ_HEAD(pf_send_head, pf_send_entry);
156static VNET_DEFINE(struct pf_send_head, pf_sendqueue);
157#define V_pf_sendqueue VNET(pf_sendqueue)
158
159static struct mtx pf_sendqueue_mtx;
160#define PF_SENDQ_LOCK() mtx_lock(&pf_sendqueue_mtx)
161#define PF_SENDQ_UNLOCK() mtx_unlock(&pf_sendqueue_mtx)
162
163/*
164 * Queue for pf_overload_task() tasks.
165 */
166struct pf_overload_entry {
167 SLIST_ENTRY(pf_overload_entry) next;
168 struct pf_addr addr;
169 sa_family_t af;
170 uint8_t dir;
171 struct pf_rule *rule;
172};
173
174SLIST_HEAD(pf_overload_head, pf_overload_entry);
175static VNET_DEFINE(struct pf_overload_head, pf_overloadqueue);
176#define V_pf_overloadqueue VNET(pf_overloadqueue)
177static VNET_DEFINE(struct task, pf_overloadtask);
178#define V_pf_overloadtask VNET(pf_overloadtask)
179
180static struct mtx pf_overloadqueue_mtx;
181#define PF_OVERLOADQ_LOCK() mtx_lock(&pf_overloadqueue_mtx)
182#define PF_OVERLOADQ_UNLOCK() mtx_unlock(&pf_overloadqueue_mtx)
183
184VNET_DEFINE(struct pf_rulequeue, pf_unlinked_rules);
185struct mtx pf_unlnkdrules_mtx;
186
187static VNET_DEFINE(uma_zone_t, pf_sources_z);
188#define V_pf_sources_z VNET(pf_sources_z)
189uma_zone_t pf_mtag_z;
190VNET_DEFINE(uma_zone_t, pf_state_z);
191VNET_DEFINE(uma_zone_t, pf_state_key_z);
192
193VNET_DEFINE(uint64_t, pf_stateid[MAXCPU]);
194#define PFID_CPUBITS 8
195#define PFID_CPUSHIFT (sizeof(uint64_t) * NBBY - PFID_CPUBITS)
196#define PFID_CPUMASK ((uint64_t)((1 << PFID_CPUBITS) - 1) << PFID_CPUSHIFT)
197#define PFID_MAXID (~PFID_CPUMASK)
198CTASSERT((1 << PFID_CPUBITS) >= MAXCPU);
199
200static void pf_src_tree_remove_state(struct pf_state *);
201static void pf_init_threshold(struct pf_threshold *, u_int32_t,
202 u_int32_t);
203static void pf_add_threshold(struct pf_threshold *);
204static int pf_check_threshold(struct pf_threshold *);
205
206static void pf_change_ap(struct pf_addr *, u_int16_t *,
207 u_int16_t *, u_int16_t *, struct pf_addr *,
208 u_int16_t, u_int8_t, sa_family_t);
209static int pf_modulate_sack(struct mbuf *, int, struct pf_pdesc *,
210 struct tcphdr *, struct pf_state_peer *);
211static void pf_change_icmp(struct pf_addr *, u_int16_t *,
212 struct pf_addr *, struct pf_addr *, u_int16_t,
213 u_int16_t *, u_int16_t *, u_int16_t *,
214 u_int16_t *, u_int8_t, sa_family_t);
215static void pf_send_tcp(struct mbuf *,
216 const struct pf_rule *, sa_family_t,
217 const struct pf_addr *, const struct pf_addr *,
218 u_int16_t, u_int16_t, u_int32_t, u_int32_t,
219 u_int8_t, u_int16_t, u_int16_t, u_int8_t, int,
220 u_int16_t, struct ifnet *);
221static void pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
222 sa_family_t, struct pf_rule *);
223static void pf_detach_state(struct pf_state *);
224static int pf_state_key_attach(struct pf_state_key *,
225 struct pf_state_key *, struct pf_state *);
226static void pf_state_key_detach(struct pf_state *, int);
227static int pf_state_key_ctor(void *, int, void *, int);
228static u_int32_t pf_tcp_iss(struct pf_pdesc *);
229static int pf_test_rule(struct pf_rule **, struct pf_state **,
230 int, struct pfi_kif *, struct mbuf *, int,
231 struct pf_pdesc *, struct pf_rule **,
232 struct pf_ruleset **, struct inpcb *);
233static int pf_create_state(struct pf_rule *, struct pf_rule *,
234 struct pf_rule *, struct pf_pdesc *,
235 struct pf_src_node *, struct pf_state_key *,
236 struct pf_state_key *, struct mbuf *, int,
237 u_int16_t, u_int16_t, int *, struct pfi_kif *,
238 struct pf_state **, int, u_int16_t, u_int16_t,
239 int);
240static int pf_test_fragment(struct pf_rule **, int,
241 struct pfi_kif *, struct mbuf *, void *,
242 struct pf_pdesc *, struct pf_rule **,
243 struct pf_ruleset **);
244static int pf_tcp_track_full(struct pf_state_peer *,
245 struct pf_state_peer *, struct pf_state **,
246 struct pfi_kif *, struct mbuf *, int,
247 struct pf_pdesc *, u_short *, int *);
248static int pf_tcp_track_sloppy(struct pf_state_peer *,
249 struct pf_state_peer *, struct pf_state **,
250 struct pf_pdesc *, u_short *);
251static int pf_test_state_tcp(struct pf_state **, int,
252 struct pfi_kif *, struct mbuf *, int,
253 void *, struct pf_pdesc *, u_short *);
254static int pf_test_state_udp(struct pf_state **, int,
255 struct pfi_kif *, struct mbuf *, int,
256 void *, struct pf_pdesc *);
257static int pf_test_state_icmp(struct pf_state **, int,
258 struct pfi_kif *, struct mbuf *, int,
259 void *, struct pf_pdesc *, u_short *);
260static int pf_test_state_other(struct pf_state **, int,
261 struct pfi_kif *, struct mbuf *, struct pf_pdesc *);
262static u_int8_t pf_get_wscale(struct mbuf *, int, u_int16_t,
263 sa_family_t);
264static u_int16_t pf_get_mss(struct mbuf *, int, u_int16_t,
265 sa_family_t);
266static u_int16_t pf_calc_mss(struct pf_addr *, sa_family_t,
267 int, u_int16_t);
268static int pf_check_proto_cksum(struct mbuf *, int, int,
269 u_int8_t, sa_family_t);
270static void pf_print_state_parts(struct pf_state *,
271 struct pf_state_key *, struct pf_state_key *);
272static int pf_addr_wrap_neq(struct pf_addr_wrap *,
273 struct pf_addr_wrap *);
274static struct pf_state *pf_find_state(struct pfi_kif *,
275 struct pf_state_key_cmp *, u_int);
276static int pf_src_connlimit(struct pf_state **);
277static void pf_overload_task(void *v, int pending);
278static int pf_insert_src_node(struct pf_src_node **,
279 struct pf_rule *, struct pf_addr *, sa_family_t);
280static u_int pf_purge_expired_states(u_int, int);
281static void pf_purge_unlinked_rules(void);
282static int pf_mtag_uminit(void *, int, int);
283static void pf_mtag_free(struct m_tag *);
284#ifdef INET
285static void pf_route(struct mbuf **, struct pf_rule *, int,
286 struct ifnet *, struct pf_state *,
287 struct pf_pdesc *);
288#endif /* INET */
289#ifdef INET6
290static void pf_change_a6(struct pf_addr *, u_int16_t *,
291 struct pf_addr *, u_int8_t);
292static void pf_route6(struct mbuf **, struct pf_rule *, int,
293 struct ifnet *, struct pf_state *,
294 struct pf_pdesc *);
295#endif /* INET6 */
296
297int in4_cksum(struct mbuf *m, u_int8_t nxt, int off, int len);
298
299VNET_DECLARE(int, pf_end_threads);
300
301VNET_DEFINE(struct pf_limit, pf_limits[PF_LIMIT_MAX]);
302
303#define PACKET_LOOPED(pd) ((pd)->pf_mtag && \
304 (pd)->pf_mtag->flags & PF_PACKET_LOOPED)
305
306#define STATE_LOOKUP(i, k, d, s, pd) \
307 do { \
308 (s) = pf_find_state((i), (k), (d)); \
309 if ((s) == NULL) \
310 return (PF_DROP); \
311 if (PACKET_LOOPED(pd)) \
312 return (PF_PASS); \
313 if ((d) == PF_OUT && \
314 (((s)->rule.ptr->rt == PF_ROUTETO && \
315 (s)->rule.ptr->direction == PF_OUT) || \
316 ((s)->rule.ptr->rt == PF_REPLYTO && \
317 (s)->rule.ptr->direction == PF_IN)) && \
318 (s)->rt_kif != NULL && \
319 (s)->rt_kif != (i)) \
320 return (PF_PASS); \
321 } while (0)
322
323#define BOUND_IFACE(r, k) \
324 ((r)->rule_flag & PFRULE_IFBOUND) ? (k) : V_pfi_all
325
326#define STATE_INC_COUNTERS(s) \
327 do { \
328 counter_u64_add(s->rule.ptr->states_cur, 1); \
329 counter_u64_add(s->rule.ptr->states_tot, 1); \
330 if (s->anchor.ptr != NULL) { \
331 counter_u64_add(s->anchor.ptr->states_cur, 1); \
332 counter_u64_add(s->anchor.ptr->states_tot, 1); \
333 } \
334 if (s->nat_rule.ptr != NULL) { \
335 counter_u64_add(s->nat_rule.ptr->states_cur, 1);\
336 counter_u64_add(s->nat_rule.ptr->states_tot, 1);\
337 } \
338 } while (0)
339
340#define STATE_DEC_COUNTERS(s) \
341 do { \
342 if (s->nat_rule.ptr != NULL) \
343 counter_u64_add(s->nat_rule.ptr->states_cur, -1);\
344 if (s->anchor.ptr != NULL) \
345 counter_u64_add(s->anchor.ptr->states_cur, -1); \
346 counter_u64_add(s->rule.ptr->states_cur, -1); \
347 } while (0)
348
349static MALLOC_DEFINE(M_PFHASH, "pf_hash", "pf(4) hash header structures");
350VNET_DEFINE(struct pf_keyhash *, pf_keyhash);
351VNET_DEFINE(struct pf_idhash *, pf_idhash);
352VNET_DEFINE(struct pf_srchash *, pf_srchash);
353
354SYSCTL_NODE(_net, OID_AUTO, pf, CTLFLAG_RW, 0, "pf(4)");
355
356u_long pf_hashmask;
357u_long pf_srchashmask;
358static u_long pf_hashsize;
359static u_long pf_srchashsize;
360
361SYSCTL_ULONG(_net_pf, OID_AUTO, states_hashsize, CTLFLAG_RDTUN,
362 &pf_hashsize, 0, "Size of pf(4) states hashtable");
363SYSCTL_ULONG(_net_pf, OID_AUTO, source_nodes_hashsize, CTLFLAG_RDTUN,
364 &pf_srchashsize, 0, "Size of pf(4) source nodes hashtable");
365
366VNET_DEFINE(void *, pf_swi_cookie);
367
368VNET_DEFINE(uint32_t, pf_hashseed);
369#define V_pf_hashseed VNET(pf_hashseed)
370
371int
372pf_addr_cmp(struct pf_addr *a, struct pf_addr *b, sa_family_t af)
373{
374
375 switch (af) {
376#ifdef INET
377 case AF_INET:
378 if (a->addr32[0] > b->addr32[0])
379 return (1);
380 if (a->addr32[0] < b->addr32[0])
381 return (-1);
382 break;
383#endif /* INET */
384#ifdef INET6
385 case AF_INET6:
386 if (a->addr32[3] > b->addr32[3])
387 return (1);
388 if (a->addr32[3] < b->addr32[3])
389 return (-1);
390 if (a->addr32[2] > b->addr32[2])
391 return (1);
392 if (a->addr32[2] < b->addr32[2])
393 return (-1);
394 if (a->addr32[1] > b->addr32[1])
395 return (1);
396 if (a->addr32[1] < b->addr32[1])
397 return (-1);
398 if (a->addr32[0] > b->addr32[0])
399 return (1);
400 if (a->addr32[0] < b->addr32[0])
401 return (-1);
402 break;
403#endif /* INET6 */
404 default:
405 panic("%s: unknown address family %u", __func__, af);
406 }
407 return (0);
408}
409
410static __inline uint32_t
411pf_hashkey(struct pf_state_key *sk)
412{
413 uint32_t h;
414
415 h = murmur3_aligned_32((uint32_t *)sk,
416 sizeof(struct pf_state_key_cmp),
417 V_pf_hashseed);
418
419 return (h & pf_hashmask);
420}
421
422static __inline uint32_t
423pf_hashsrc(struct pf_addr *addr, sa_family_t af)
424{
425 uint32_t h;
426
427 switch (af) {
428 case AF_INET:
429 h = murmur3_aligned_32((uint32_t *)&addr->v4,
430 sizeof(addr->v4), V_pf_hashseed);
431 break;
432 case AF_INET6:
433 h = murmur3_aligned_32((uint32_t *)&addr->v6,
434 sizeof(addr->v6), V_pf_hashseed);
435 break;
436 default:
437 panic("%s: unknown address family %u", __func__, af);
438 }
439
440 return (h & pf_srchashmask);
441}
442
443#ifdef INET6
444void
445pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
446{
447 switch (af) {
448#ifdef INET
449 case AF_INET:
450 dst->addr32[0] = src->addr32[0];
451 break;
452#endif /* INET */
453 case AF_INET6:
454 dst->addr32[0] = src->addr32[0];
455 dst->addr32[1] = src->addr32[1];
456 dst->addr32[2] = src->addr32[2];
457 dst->addr32[3] = src->addr32[3];
458 break;
459 }
460}
461#endif /* INET6 */
462
463static void
464pf_init_threshold(struct pf_threshold *threshold,
465 u_int32_t limit, u_int32_t seconds)
466{
467 threshold->limit = limit * PF_THRESHOLD_MULT;
468 threshold->seconds = seconds;
469 threshold->count = 0;
470 threshold->last = time_uptime;
471}
472
473static void
474pf_add_threshold(struct pf_threshold *threshold)
475{
476 u_int32_t t = time_uptime, diff = t - threshold->last;
477
478 if (diff >= threshold->seconds)
479 threshold->count = 0;
480 else
481 threshold->count -= threshold->count * diff /
482 threshold->seconds;
483 threshold->count += PF_THRESHOLD_MULT;
484 threshold->last = t;
485}
486
487static int
488pf_check_threshold(struct pf_threshold *threshold)
489{
490 return (threshold->count > threshold->limit);
491}
492
493static int
494pf_src_connlimit(struct pf_state **state)
495{
496 struct pf_overload_entry *pfoe;
497 int bad = 0;
498
499 PF_STATE_LOCK_ASSERT(*state);
500
501 (*state)->src_node->conn++;
502 (*state)->src.tcp_est = 1;
503 pf_add_threshold(&(*state)->src_node->conn_rate);
504
505 if ((*state)->rule.ptr->max_src_conn &&
506 (*state)->rule.ptr->max_src_conn <
507 (*state)->src_node->conn) {
508 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONN], 1);
509 bad++;
510 }
511
512 if ((*state)->rule.ptr->max_src_conn_rate.limit &&
513 pf_check_threshold(&(*state)->src_node->conn_rate)) {
514 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONNRATE], 1);
515 bad++;
516 }
517
518 if (!bad)
519 return (0);
520
521 /* Kill this state. */
522 (*state)->timeout = PFTM_PURGE;
523 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
524
525 if ((*state)->rule.ptr->overload_tbl == NULL)
526 return (1);
527
528 /* Schedule overloading and flushing task. */
529 pfoe = malloc(sizeof(*pfoe), M_PFTEMP, M_NOWAIT);
530 if (pfoe == NULL)
531 return (1); /* too bad :( */
532
533 bcopy(&(*state)->src_node->addr, &pfoe->addr, sizeof(pfoe->addr));
534 pfoe->af = (*state)->key[PF_SK_WIRE]->af;
535 pfoe->rule = (*state)->rule.ptr;
536 pfoe->dir = (*state)->direction;
537 PF_OVERLOADQ_LOCK();
538 SLIST_INSERT_HEAD(&V_pf_overloadqueue, pfoe, next);
539 PF_OVERLOADQ_UNLOCK();
540 taskqueue_enqueue(taskqueue_swi, &V_pf_overloadtask);
541
542 return (1);
543}
544
545static void
546pf_overload_task(void *v, int pending)
547{
548 struct pf_overload_head queue;
549 struct pfr_addr p;
550 struct pf_overload_entry *pfoe, *pfoe1;
551 uint32_t killed = 0;
552
553 CURVNET_SET((struct vnet *)v);
554
555 PF_OVERLOADQ_LOCK();
556 queue = V_pf_overloadqueue;
557 SLIST_INIT(&V_pf_overloadqueue);
558 PF_OVERLOADQ_UNLOCK();
559
560 bzero(&p, sizeof(p));
561 SLIST_FOREACH(pfoe, &queue, next) {
562 counter_u64_add(V_pf_status.lcounters[LCNT_OVERLOAD_TABLE], 1);
563 if (V_pf_status.debug >= PF_DEBUG_MISC) {
564 printf("%s: blocking address ", __func__);
565 pf_print_host(&pfoe->addr, 0, pfoe->af);
566 printf("\n");
567 }
568
569 p.pfra_af = pfoe->af;
570 switch (pfoe->af) {
571#ifdef INET
572 case AF_INET:
573 p.pfra_net = 32;
574 p.pfra_ip4addr = pfoe->addr.v4;
575 break;
576#endif
577#ifdef INET6
578 case AF_INET6:
579 p.pfra_net = 128;
580 p.pfra_ip6addr = pfoe->addr.v6;
581 break;
582#endif
583 }
584
585 PF_RULES_WLOCK();
586 pfr_insert_kentry(pfoe->rule->overload_tbl, &p, time_second);
587 PF_RULES_WUNLOCK();
588 }
589
590 /*
591 * Remove those entries, that don't need flushing.
592 */
593 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
594 if (pfoe->rule->flush == 0) {
595 SLIST_REMOVE(&queue, pfoe, pf_overload_entry, next);
596 free(pfoe, M_PFTEMP);
597 } else
598 counter_u64_add(
599 V_pf_status.lcounters[LCNT_OVERLOAD_FLUSH], 1);
600
601 /* If nothing to flush, return. */
602 if (SLIST_EMPTY(&queue)) {
603 CURVNET_RESTORE();
604 return;
605 }
606
607 for (int i = 0; i <= pf_hashmask; i++) {
608 struct pf_idhash *ih = &V_pf_idhash[i];
609 struct pf_state_key *sk;
610 struct pf_state *s;
611
612 PF_HASHROW_LOCK(ih);
613 LIST_FOREACH(s, &ih->states, entry) {
614 sk = s->key[PF_SK_WIRE];
615 SLIST_FOREACH(pfoe, &queue, next)
616 if (sk->af == pfoe->af &&
617 ((pfoe->rule->flush & PF_FLUSH_GLOBAL) ||
618 pfoe->rule == s->rule.ptr) &&
619 ((pfoe->dir == PF_OUT &&
620 PF_AEQ(&pfoe->addr, &sk->addr[1], sk->af)) ||
621 (pfoe->dir == PF_IN &&
622 PF_AEQ(&pfoe->addr, &sk->addr[0], sk->af)))) {
623 s->timeout = PFTM_PURGE;
624 s->src.state = s->dst.state = TCPS_CLOSED;
625 killed++;
626 }
627 }
628 PF_HASHROW_UNLOCK(ih);
629 }
630 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
631 free(pfoe, M_PFTEMP);
632 if (V_pf_status.debug >= PF_DEBUG_MISC)
633 printf("%s: %u states killed", __func__, killed);
634
635 CURVNET_RESTORE();
636}
637
638/*
639 * Can return locked on failure, so that we can consistently
640 * allocate and insert a new one.
641 */
642struct pf_src_node *
643pf_find_src_node(struct pf_addr *src, struct pf_rule *rule, sa_family_t af,
644 int returnlocked)
645{
646 struct pf_srchash *sh;
647 struct pf_src_node *n;
648
649 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_SEARCH], 1);
650
651 sh = &V_pf_srchash[pf_hashsrc(src, af)];
652 PF_HASHROW_LOCK(sh);
653 LIST_FOREACH(n, &sh->nodes, entry)
654 if (n->rule.ptr == rule && n->af == af &&
655 ((af == AF_INET && n->addr.v4.s_addr == src->v4.s_addr) ||
656 (af == AF_INET6 && bcmp(&n->addr, src, sizeof(*src)) == 0)))
657 break;
658 if (n != NULL || returnlocked == 0)
658 if (n != NULL) {
659 n->states++;
659 PF_HASHROW_UNLOCK(sh);
660 PF_HASHROW_UNLOCK(sh);
661 } else if (returnlocked == 0)
662 PF_HASHROW_UNLOCK(sh);
660
661 return (n);
662}
663
664static int
665pf_insert_src_node(struct pf_src_node **sn, struct pf_rule *rule,
666 struct pf_addr *src, sa_family_t af)
667{
668
669 KASSERT((rule->rule_flag & PFRULE_RULESRCTRACK ||
670 rule->rpool.opts & PF_POOL_STICKYADDR),
671 ("%s for non-tracking rule %p", __func__, rule));
672
673 if (*sn == NULL)
674 *sn = pf_find_src_node(src, rule, af, 1);
675
676 if (*sn == NULL) {
677 struct pf_srchash *sh = &V_pf_srchash[pf_hashsrc(src, af)];
678
679 PF_HASHROW_ASSERT(sh);
680
681 if (!rule->max_src_nodes ||
682 counter_u64_fetch(rule->src_nodes) < rule->max_src_nodes)
683 (*sn) = uma_zalloc(V_pf_sources_z, M_NOWAIT | M_ZERO);
684 else
685 counter_u64_add(V_pf_status.lcounters[LCNT_SRCNODES],
686 1);
687 if ((*sn) == NULL) {
688 PF_HASHROW_UNLOCK(sh);
689 return (-1);
690 }
691
692 pf_init_threshold(&(*sn)->conn_rate,
693 rule->max_src_conn_rate.limit,
694 rule->max_src_conn_rate.seconds);
695
696 (*sn)->af = af;
697 (*sn)->rule.ptr = rule;
698 PF_ACPY(&(*sn)->addr, src, af);
699 LIST_INSERT_HEAD(&sh->nodes, *sn, entry);
700 (*sn)->creation = time_uptime;
701 (*sn)->ruletype = rule->action;
663
664 return (n);
665}
666
667static int
668pf_insert_src_node(struct pf_src_node **sn, struct pf_rule *rule,
669 struct pf_addr *src, sa_family_t af)
670{
671
672 KASSERT((rule->rule_flag & PFRULE_RULESRCTRACK ||
673 rule->rpool.opts & PF_POOL_STICKYADDR),
674 ("%s for non-tracking rule %p", __func__, rule));
675
676 if (*sn == NULL)
677 *sn = pf_find_src_node(src, rule, af, 1);
678
679 if (*sn == NULL) {
680 struct pf_srchash *sh = &V_pf_srchash[pf_hashsrc(src, af)];
681
682 PF_HASHROW_ASSERT(sh);
683
684 if (!rule->max_src_nodes ||
685 counter_u64_fetch(rule->src_nodes) < rule->max_src_nodes)
686 (*sn) = uma_zalloc(V_pf_sources_z, M_NOWAIT | M_ZERO);
687 else
688 counter_u64_add(V_pf_status.lcounters[LCNT_SRCNODES],
689 1);
690 if ((*sn) == NULL) {
691 PF_HASHROW_UNLOCK(sh);
692 return (-1);
693 }
694
695 pf_init_threshold(&(*sn)->conn_rate,
696 rule->max_src_conn_rate.limit,
697 rule->max_src_conn_rate.seconds);
698
699 (*sn)->af = af;
700 (*sn)->rule.ptr = rule;
701 PF_ACPY(&(*sn)->addr, src, af);
702 LIST_INSERT_HEAD(&sh->nodes, *sn, entry);
703 (*sn)->creation = time_uptime;
704 (*sn)->ruletype = rule->action;
705 (*sn)->states = 1;
702 if ((*sn)->rule.ptr != NULL)
703 counter_u64_add((*sn)->rule.ptr->src_nodes, 1);
704 PF_HASHROW_UNLOCK(sh);
705 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_INSERT], 1);
706 } else {
707 if (rule->max_src_states &&
708 (*sn)->states >= rule->max_src_states) {
709 counter_u64_add(V_pf_status.lcounters[LCNT_SRCSTATES],
710 1);
711 return (-1);
712 }
713 }
714 return (0);
715}
716
717void
706 if ((*sn)->rule.ptr != NULL)
707 counter_u64_add((*sn)->rule.ptr->src_nodes, 1);
708 PF_HASHROW_UNLOCK(sh);
709 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_INSERT], 1);
710 } else {
711 if (rule->max_src_states &&
712 (*sn)->states >= rule->max_src_states) {
713 counter_u64_add(V_pf_status.lcounters[LCNT_SRCSTATES],
714 1);
715 return (-1);
716 }
717 }
718 return (0);
719}
720
721void
718pf_unlink_src_node_locked(struct pf_src_node *src)
722pf_unlink_src_node(struct pf_src_node *src)
719{
723{
720#ifdef INVARIANTS
721 struct pf_srchash *sh;
722
724
723 sh = &V_pf_srchash[pf_hashsrc(&src->addr, src->af)];
724 PF_HASHROW_ASSERT(sh);
725#endif
725 PF_HASHROW_ASSERT(&V_pf_srchash[pf_hashsrc(&src->addr, src->af)]);
726 LIST_REMOVE(src, entry);
727 if (src->rule.ptr)
728 counter_u64_add(src->rule.ptr->src_nodes, -1);
726 LIST_REMOVE(src, entry);
727 if (src->rule.ptr)
728 counter_u64_add(src->rule.ptr->src_nodes, -1);
729 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
730}
731
729}
730
732void
733pf_unlink_src_node(struct pf_src_node *src)
734{
735 struct pf_srchash *sh;
736
737 sh = &V_pf_srchash[pf_hashsrc(&src->addr, src->af)];
738 PF_HASHROW_LOCK(sh);
739 pf_unlink_src_node_locked(src);
740 PF_HASHROW_UNLOCK(sh);
741}
742
743static void
744pf_free_src_node(struct pf_src_node *sn)
745{
746
747 KASSERT(sn->states == 0, ("%s: %p has refs", __func__, sn));
748 uma_zfree(V_pf_sources_z, sn);
749}
750
751u_int
752pf_free_src_nodes(struct pf_src_node_list *head)
753{
754 struct pf_src_node *sn, *tmp;
755 u_int count = 0;
756
757 LIST_FOREACH_SAFE(sn, head, entry, tmp) {
731u_int
732pf_free_src_nodes(struct pf_src_node_list *head)
733{
734 struct pf_src_node *sn, *tmp;
735 u_int count = 0;
736
737 LIST_FOREACH_SAFE(sn, head, entry, tmp) {
758 pf_free_src_node(sn);
738 uma_zfree(V_pf_sources_z, sn);
759 count++;
760 }
761
739 count++;
740 }
741
742 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], count);
743
762 return (count);
763}
764
765void
766pf_mtag_initialize()
767{
768
769 pf_mtag_z = uma_zcreate("pf mtags", sizeof(struct m_tag) +
770 sizeof(struct pf_mtag), NULL, NULL, pf_mtag_uminit, NULL,
771 UMA_ALIGN_PTR, 0);
772}
773
774/* Per-vnet data storage structures initialization. */
775void
776pf_initialize()
777{
778 struct pf_keyhash *kh;
779 struct pf_idhash *ih;
780 struct pf_srchash *sh;
781 u_int i;
782
783 TUNABLE_ULONG_FETCH("net.pf.states_hashsize", &pf_hashsize);
784 if (pf_hashsize == 0 || !powerof2(pf_hashsize))
785 pf_hashsize = PF_HASHSIZ;
786 TUNABLE_ULONG_FETCH("net.pf.source_nodes_hashsize", &pf_srchashsize);
787 if (pf_srchashsize == 0 || !powerof2(pf_srchashsize))
788 pf_srchashsize = PF_HASHSIZ / 4;
789
790 V_pf_hashseed = arc4random();
791
792 /* States and state keys storage. */
793 V_pf_state_z = uma_zcreate("pf states", sizeof(struct pf_state),
794 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
795 V_pf_limits[PF_LIMIT_STATES].zone = V_pf_state_z;
796 uma_zone_set_max(V_pf_state_z, PFSTATE_HIWAT);
797 uma_zone_set_warning(V_pf_state_z, "PF states limit reached");
798
799 V_pf_state_key_z = uma_zcreate("pf state keys",
800 sizeof(struct pf_state_key), pf_state_key_ctor, NULL, NULL, NULL,
801 UMA_ALIGN_PTR, 0);
802 V_pf_keyhash = malloc(pf_hashsize * sizeof(struct pf_keyhash),
803 M_PFHASH, M_WAITOK | M_ZERO);
804 V_pf_idhash = malloc(pf_hashsize * sizeof(struct pf_idhash),
805 M_PFHASH, M_WAITOK | M_ZERO);
806 pf_hashmask = pf_hashsize - 1;
807 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
808 i++, kh++, ih++) {
809 mtx_init(&kh->lock, "pf_keyhash", NULL, MTX_DEF | MTX_DUPOK);
810 mtx_init(&ih->lock, "pf_idhash", NULL, MTX_DEF);
811 }
812
813 /* Source nodes. */
814 V_pf_sources_z = uma_zcreate("pf source nodes",
815 sizeof(struct pf_src_node), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
816 0);
817 V_pf_limits[PF_LIMIT_SRC_NODES].zone = V_pf_sources_z;
818 uma_zone_set_max(V_pf_sources_z, PFSNODE_HIWAT);
819 uma_zone_set_warning(V_pf_sources_z, "PF source nodes limit reached");
820 V_pf_srchash = malloc(pf_srchashsize * sizeof(struct pf_srchash),
821 M_PFHASH, M_WAITOK|M_ZERO);
822 pf_srchashmask = pf_srchashsize - 1;
823 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++)
824 mtx_init(&sh->lock, "pf_srchash", NULL, MTX_DEF);
825
826 /* ALTQ */
827 TAILQ_INIT(&V_pf_altqs[0]);
828 TAILQ_INIT(&V_pf_altqs[1]);
829 TAILQ_INIT(&V_pf_pabuf);
830 V_pf_altqs_active = &V_pf_altqs[0];
831 V_pf_altqs_inactive = &V_pf_altqs[1];
832
833
834 /* Send & overload+flush queues. */
835 STAILQ_INIT(&V_pf_sendqueue);
836 SLIST_INIT(&V_pf_overloadqueue);
837 TASK_INIT(&V_pf_overloadtask, 0, pf_overload_task, curvnet);
838 mtx_init(&pf_sendqueue_mtx, "pf send queue", NULL, MTX_DEF);
839 mtx_init(&pf_overloadqueue_mtx, "pf overload/flush queue", NULL,
840 MTX_DEF);
841
842 /* Unlinked, but may be referenced rules. */
843 TAILQ_INIT(&V_pf_unlinked_rules);
844 mtx_init(&pf_unlnkdrules_mtx, "pf unlinked rules", NULL, MTX_DEF);
845}
846
847void
848pf_mtag_cleanup()
849{
850
851 uma_zdestroy(pf_mtag_z);
852}
853
854void
855pf_cleanup()
856{
857 struct pf_keyhash *kh;
858 struct pf_idhash *ih;
859 struct pf_srchash *sh;
860 struct pf_send_entry *pfse, *next;
861 u_int i;
862
863 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
864 i++, kh++, ih++) {
865 KASSERT(LIST_EMPTY(&kh->keys), ("%s: key hash not empty",
866 __func__));
867 KASSERT(LIST_EMPTY(&ih->states), ("%s: id hash not empty",
868 __func__));
869 mtx_destroy(&kh->lock);
870 mtx_destroy(&ih->lock);
871 }
872 free(V_pf_keyhash, M_PFHASH);
873 free(V_pf_idhash, M_PFHASH);
874
875 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
876 KASSERT(LIST_EMPTY(&sh->nodes),
877 ("%s: source node hash not empty", __func__));
878 mtx_destroy(&sh->lock);
879 }
880 free(V_pf_srchash, M_PFHASH);
881
882 STAILQ_FOREACH_SAFE(pfse, &V_pf_sendqueue, pfse_next, next) {
883 m_freem(pfse->pfse_m);
884 free(pfse, M_PFTEMP);
885 }
886
887 mtx_destroy(&pf_sendqueue_mtx);
888 mtx_destroy(&pf_overloadqueue_mtx);
889 mtx_destroy(&pf_unlnkdrules_mtx);
890
891 uma_zdestroy(V_pf_sources_z);
892 uma_zdestroy(V_pf_state_z);
893 uma_zdestroy(V_pf_state_key_z);
894}
895
896static int
897pf_mtag_uminit(void *mem, int size, int how)
898{
899 struct m_tag *t;
900
901 t = (struct m_tag *)mem;
902 t->m_tag_cookie = MTAG_ABI_COMPAT;
903 t->m_tag_id = PACKET_TAG_PF;
904 t->m_tag_len = sizeof(struct pf_mtag);
905 t->m_tag_free = pf_mtag_free;
906
907 return (0);
908}
909
910static void
911pf_mtag_free(struct m_tag *t)
912{
913
914 uma_zfree(pf_mtag_z, t);
915}
916
917struct pf_mtag *
918pf_get_mtag(struct mbuf *m)
919{
920 struct m_tag *mtag;
921
922 if ((mtag = m_tag_find(m, PACKET_TAG_PF, NULL)) != NULL)
923 return ((struct pf_mtag *)(mtag + 1));
924
925 mtag = uma_zalloc(pf_mtag_z, M_NOWAIT);
926 if (mtag == NULL)
927 return (NULL);
928 bzero(mtag + 1, sizeof(struct pf_mtag));
929 m_tag_prepend(m, mtag);
930
931 return ((struct pf_mtag *)(mtag + 1));
932}
933
934static int
935pf_state_key_attach(struct pf_state_key *skw, struct pf_state_key *sks,
936 struct pf_state *s)
937{
938 struct pf_keyhash *khs, *khw, *kh;
939 struct pf_state_key *sk, *cur;
940 struct pf_state *si, *olds = NULL;
941 int idx;
942
943 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
944 KASSERT(s->key[PF_SK_WIRE] == NULL, ("%s: state has key", __func__));
945 KASSERT(s->key[PF_SK_STACK] == NULL, ("%s: state has key", __func__));
946
947 /*
948 * We need to lock hash slots of both keys. To avoid deadlock
949 * we always lock the slot with lower address first. Unlock order
950 * isn't important.
951 *
952 * We also need to lock ID hash slot before dropping key
953 * locks. On success we return with ID hash slot locked.
954 */
955
956 if (skw == sks) {
957 khs = khw = &V_pf_keyhash[pf_hashkey(skw)];
958 PF_HASHROW_LOCK(khs);
959 } else {
960 khs = &V_pf_keyhash[pf_hashkey(sks)];
961 khw = &V_pf_keyhash[pf_hashkey(skw)];
962 if (khs == khw) {
963 PF_HASHROW_LOCK(khs);
964 } else if (khs < khw) {
965 PF_HASHROW_LOCK(khs);
966 PF_HASHROW_LOCK(khw);
967 } else {
968 PF_HASHROW_LOCK(khw);
969 PF_HASHROW_LOCK(khs);
970 }
971 }
972
973#define KEYS_UNLOCK() do { \
974 if (khs != khw) { \
975 PF_HASHROW_UNLOCK(khs); \
976 PF_HASHROW_UNLOCK(khw); \
977 } else \
978 PF_HASHROW_UNLOCK(khs); \
979} while (0)
980
981 /*
982 * First run: start with wire key.
983 */
984 sk = skw;
985 kh = khw;
986 idx = PF_SK_WIRE;
987
988keyattach:
989 LIST_FOREACH(cur, &kh->keys, entry)
990 if (bcmp(cur, sk, sizeof(struct pf_state_key_cmp)) == 0)
991 break;
992
993 if (cur != NULL) {
994 /* Key exists. Check for same kif, if none, add to key. */
995 TAILQ_FOREACH(si, &cur->states[idx], key_list[idx]) {
996 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(si)];
997
998 PF_HASHROW_LOCK(ih);
999 if (si->kif == s->kif &&
1000 si->direction == s->direction) {
1001 if (sk->proto == IPPROTO_TCP &&
1002 si->src.state >= TCPS_FIN_WAIT_2 &&
1003 si->dst.state >= TCPS_FIN_WAIT_2) {
1004 /*
1005 * New state matches an old >FIN_WAIT_2
1006 * state. We can't drop key hash locks,
1007 * thus we can't unlink it properly.
1008 *
1009 * As a workaround we drop it into
1010 * TCPS_CLOSED state, schedule purge
1011 * ASAP and push it into the very end
1012 * of the slot TAILQ, so that it won't
1013 * conflict with our new state.
1014 */
1015 si->src.state = si->dst.state =
1016 TCPS_CLOSED;
1017 si->timeout = PFTM_PURGE;
1018 olds = si;
1019 } else {
1020 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1021 printf("pf: %s key attach "
1022 "failed on %s: ",
1023 (idx == PF_SK_WIRE) ?
1024 "wire" : "stack",
1025 s->kif->pfik_name);
1026 pf_print_state_parts(s,
1027 (idx == PF_SK_WIRE) ?
1028 sk : NULL,
1029 (idx == PF_SK_STACK) ?
1030 sk : NULL);
1031 printf(", existing: ");
1032 pf_print_state_parts(si,
1033 (idx == PF_SK_WIRE) ?
1034 sk : NULL,
1035 (idx == PF_SK_STACK) ?
1036 sk : NULL);
1037 printf("\n");
1038 }
1039 PF_HASHROW_UNLOCK(ih);
1040 KEYS_UNLOCK();
1041 uma_zfree(V_pf_state_key_z, sk);
1042 if (idx == PF_SK_STACK)
1043 pf_detach_state(s);
1044 return (EEXIST); /* collision! */
1045 }
1046 }
1047 PF_HASHROW_UNLOCK(ih);
1048 }
1049 uma_zfree(V_pf_state_key_z, sk);
1050 s->key[idx] = cur;
1051 } else {
1052 LIST_INSERT_HEAD(&kh->keys, sk, entry);
1053 s->key[idx] = sk;
1054 }
1055
1056stateattach:
1057 /* List is sorted, if-bound states before floating. */
1058 if (s->kif == V_pfi_all)
1059 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], s, key_list[idx]);
1060 else
1061 TAILQ_INSERT_HEAD(&s->key[idx]->states[idx], s, key_list[idx]);
1062
1063 if (olds) {
1064 TAILQ_REMOVE(&s->key[idx]->states[idx], olds, key_list[idx]);
1065 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], olds,
1066 key_list[idx]);
1067 olds = NULL;
1068 }
1069
1070 /*
1071 * Attach done. See how should we (or should not?)
1072 * attach a second key.
1073 */
1074 if (sks == skw) {
1075 s->key[PF_SK_STACK] = s->key[PF_SK_WIRE];
1076 idx = PF_SK_STACK;
1077 sks = NULL;
1078 goto stateattach;
1079 } else if (sks != NULL) {
1080 /*
1081 * Continue attaching with stack key.
1082 */
1083 sk = sks;
1084 kh = khs;
1085 idx = PF_SK_STACK;
1086 sks = NULL;
1087 goto keyattach;
1088 }
1089
1090 PF_STATE_LOCK(s);
1091 KEYS_UNLOCK();
1092
1093 KASSERT(s->key[PF_SK_WIRE] != NULL && s->key[PF_SK_STACK] != NULL,
1094 ("%s failure", __func__));
1095
1096 return (0);
1097#undef KEYS_UNLOCK
1098}
1099
1100static void
1101pf_detach_state(struct pf_state *s)
1102{
1103 struct pf_state_key *sks = s->key[PF_SK_STACK];
1104 struct pf_keyhash *kh;
1105
1106 if (sks != NULL) {
1107 kh = &V_pf_keyhash[pf_hashkey(sks)];
1108 PF_HASHROW_LOCK(kh);
1109 if (s->key[PF_SK_STACK] != NULL)
1110 pf_state_key_detach(s, PF_SK_STACK);
1111 /*
1112 * If both point to same key, then we are done.
1113 */
1114 if (sks == s->key[PF_SK_WIRE]) {
1115 pf_state_key_detach(s, PF_SK_WIRE);
1116 PF_HASHROW_UNLOCK(kh);
1117 return;
1118 }
1119 PF_HASHROW_UNLOCK(kh);
1120 }
1121
1122 if (s->key[PF_SK_WIRE] != NULL) {
1123 kh = &V_pf_keyhash[pf_hashkey(s->key[PF_SK_WIRE])];
1124 PF_HASHROW_LOCK(kh);
1125 if (s->key[PF_SK_WIRE] != NULL)
1126 pf_state_key_detach(s, PF_SK_WIRE);
1127 PF_HASHROW_UNLOCK(kh);
1128 }
1129}
1130
1131static void
1132pf_state_key_detach(struct pf_state *s, int idx)
1133{
1134 struct pf_state_key *sk = s->key[idx];
1135#ifdef INVARIANTS
1136 struct pf_keyhash *kh = &V_pf_keyhash[pf_hashkey(sk)];
1137
1138 PF_HASHROW_ASSERT(kh);
1139#endif
1140 TAILQ_REMOVE(&sk->states[idx], s, key_list[idx]);
1141 s->key[idx] = NULL;
1142
1143 if (TAILQ_EMPTY(&sk->states[0]) && TAILQ_EMPTY(&sk->states[1])) {
1144 LIST_REMOVE(sk, entry);
1145 uma_zfree(V_pf_state_key_z, sk);
1146 }
1147}
1148
1149static int
1150pf_state_key_ctor(void *mem, int size, void *arg, int flags)
1151{
1152 struct pf_state_key *sk = mem;
1153
1154 bzero(sk, sizeof(struct pf_state_key_cmp));
1155 TAILQ_INIT(&sk->states[PF_SK_WIRE]);
1156 TAILQ_INIT(&sk->states[PF_SK_STACK]);
1157
1158 return (0);
1159}
1160
1161struct pf_state_key *
1162pf_state_key_setup(struct pf_pdesc *pd, struct pf_addr *saddr,
1163 struct pf_addr *daddr, u_int16_t sport, u_int16_t dport)
1164{
1165 struct pf_state_key *sk;
1166
1167 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1168 if (sk == NULL)
1169 return (NULL);
1170
1171 PF_ACPY(&sk->addr[pd->sidx], saddr, pd->af);
1172 PF_ACPY(&sk->addr[pd->didx], daddr, pd->af);
1173 sk->port[pd->sidx] = sport;
1174 sk->port[pd->didx] = dport;
1175 sk->proto = pd->proto;
1176 sk->af = pd->af;
1177
1178 return (sk);
1179}
1180
1181struct pf_state_key *
1182pf_state_key_clone(struct pf_state_key *orig)
1183{
1184 struct pf_state_key *sk;
1185
1186 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1187 if (sk == NULL)
1188 return (NULL);
1189
1190 bcopy(orig, sk, sizeof(struct pf_state_key_cmp));
1191
1192 return (sk);
1193}
1194
1195int
1196pf_state_insert(struct pfi_kif *kif, struct pf_state_key *skw,
1197 struct pf_state_key *sks, struct pf_state *s)
1198{
1199 struct pf_idhash *ih;
1200 struct pf_state *cur;
1201 int error;
1202
1203 KASSERT(TAILQ_EMPTY(&sks->states[0]) && TAILQ_EMPTY(&sks->states[1]),
1204 ("%s: sks not pristine", __func__));
1205 KASSERT(TAILQ_EMPTY(&skw->states[0]) && TAILQ_EMPTY(&skw->states[1]),
1206 ("%s: skw not pristine", __func__));
1207 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
1208
1209 s->kif = kif;
1210
1211 if (s->id == 0 && s->creatorid == 0) {
1212 /* XXX: should be atomic, but probability of collision low */
1213 if ((s->id = V_pf_stateid[curcpu]++) == PFID_MAXID)
1214 V_pf_stateid[curcpu] = 1;
1215 s->id |= (uint64_t )curcpu << PFID_CPUSHIFT;
1216 s->id = htobe64(s->id);
1217 s->creatorid = V_pf_status.hostid;
1218 }
1219
1220 /* Returns with ID locked on success. */
1221 if ((error = pf_state_key_attach(skw, sks, s)) != 0)
1222 return (error);
1223
1224 ih = &V_pf_idhash[PF_IDHASH(s)];
1225 PF_HASHROW_ASSERT(ih);
1226 LIST_FOREACH(cur, &ih->states, entry)
1227 if (cur->id == s->id && cur->creatorid == s->creatorid)
1228 break;
1229
1230 if (cur != NULL) {
1231 PF_HASHROW_UNLOCK(ih);
1232 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1233 printf("pf: state ID collision: "
1234 "id: %016llx creatorid: %08x\n",
1235 (unsigned long long)be64toh(s->id),
1236 ntohl(s->creatorid));
1237 }
1238 pf_detach_state(s);
1239 return (EEXIST);
1240 }
1241 LIST_INSERT_HEAD(&ih->states, s, entry);
1242 /* One for keys, one for ID hash. */
1243 refcount_init(&s->refs, 2);
1244
1245 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_INSERT], 1);
1246 if (pfsync_insert_state_ptr != NULL)
1247 pfsync_insert_state_ptr(s);
1248
1249 /* Returns locked. */
1250 return (0);
1251}
1252
1253/*
1254 * Find state by ID: returns with locked row on success.
1255 */
1256struct pf_state *
1257pf_find_state_byid(uint64_t id, uint32_t creatorid)
1258{
1259 struct pf_idhash *ih;
1260 struct pf_state *s;
1261
1262 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1263
1264 ih = &V_pf_idhash[(be64toh(id) % (pf_hashmask + 1))];
1265
1266 PF_HASHROW_LOCK(ih);
1267 LIST_FOREACH(s, &ih->states, entry)
1268 if (s->id == id && s->creatorid == creatorid)
1269 break;
1270
1271 if (s == NULL)
1272 PF_HASHROW_UNLOCK(ih);
1273
1274 return (s);
1275}
1276
1277/*
1278 * Find state by key.
1279 * Returns with ID hash slot locked on success.
1280 */
1281static struct pf_state *
1282pf_find_state(struct pfi_kif *kif, struct pf_state_key_cmp *key, u_int dir)
1283{
1284 struct pf_keyhash *kh;
1285 struct pf_state_key *sk;
1286 struct pf_state *s;
1287 int idx;
1288
1289 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1290
1291 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1292
1293 PF_HASHROW_LOCK(kh);
1294 LIST_FOREACH(sk, &kh->keys, entry)
1295 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1296 break;
1297 if (sk == NULL) {
1298 PF_HASHROW_UNLOCK(kh);
1299 return (NULL);
1300 }
1301
1302 idx = (dir == PF_IN ? PF_SK_WIRE : PF_SK_STACK);
1303
1304 /* List is sorted, if-bound states before floating ones. */
1305 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx])
1306 if (s->kif == V_pfi_all || s->kif == kif) {
1307 PF_STATE_LOCK(s);
1308 PF_HASHROW_UNLOCK(kh);
1309 if (s->timeout >= PFTM_MAX) {
1310 /*
1311 * State is either being processed by
1312 * pf_unlink_state() in an other thread, or
1313 * is scheduled for immediate expiry.
1314 */
1315 PF_STATE_UNLOCK(s);
1316 return (NULL);
1317 }
1318 return (s);
1319 }
1320 PF_HASHROW_UNLOCK(kh);
1321
1322 return (NULL);
1323}
1324
1325struct pf_state *
1326pf_find_state_all(struct pf_state_key_cmp *key, u_int dir, int *more)
1327{
1328 struct pf_keyhash *kh;
1329 struct pf_state_key *sk;
1330 struct pf_state *s, *ret = NULL;
1331 int idx, inout = 0;
1332
1333 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1334
1335 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1336
1337 PF_HASHROW_LOCK(kh);
1338 LIST_FOREACH(sk, &kh->keys, entry)
1339 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1340 break;
1341 if (sk == NULL) {
1342 PF_HASHROW_UNLOCK(kh);
1343 return (NULL);
1344 }
1345 switch (dir) {
1346 case PF_IN:
1347 idx = PF_SK_WIRE;
1348 break;
1349 case PF_OUT:
1350 idx = PF_SK_STACK;
1351 break;
1352 case PF_INOUT:
1353 idx = PF_SK_WIRE;
1354 inout = 1;
1355 break;
1356 default:
1357 panic("%s: dir %u", __func__, dir);
1358 }
1359second_run:
1360 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx]) {
1361 if (more == NULL) {
1362 PF_HASHROW_UNLOCK(kh);
1363 return (s);
1364 }
1365
1366 if (ret)
1367 (*more)++;
1368 else
1369 ret = s;
1370 }
1371 if (inout == 1) {
1372 inout = 0;
1373 idx = PF_SK_STACK;
1374 goto second_run;
1375 }
1376 PF_HASHROW_UNLOCK(kh);
1377
1378 return (ret);
1379}
1380
1381/* END state table stuff */
1382
1383static void
1384pf_send(struct pf_send_entry *pfse)
1385{
1386
1387 PF_SENDQ_LOCK();
1388 STAILQ_INSERT_TAIL(&V_pf_sendqueue, pfse, pfse_next);
1389 PF_SENDQ_UNLOCK();
1390 swi_sched(V_pf_swi_cookie, 0);
1391}
1392
1393void
1394pf_intr(void *v)
1395{
1396 struct pf_send_head queue;
1397 struct pf_send_entry *pfse, *next;
1398
1399 CURVNET_SET((struct vnet *)v);
1400
1401 PF_SENDQ_LOCK();
1402 queue = V_pf_sendqueue;
1403 STAILQ_INIT(&V_pf_sendqueue);
1404 PF_SENDQ_UNLOCK();
1405
1406 STAILQ_FOREACH_SAFE(pfse, &queue, pfse_next, next) {
1407 switch (pfse->pfse_type) {
1408#ifdef INET
1409 case PFSE_IP:
1410 ip_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL);
1411 break;
1412 case PFSE_ICMP:
1413 icmp_error(pfse->pfse_m, pfse->pfse_icmp_type,
1414 pfse->pfse_icmp_code, 0, pfse->pfse_icmp_mtu);
1415 break;
1416#endif /* INET */
1417#ifdef INET6
1418 case PFSE_IP6:
1419 ip6_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL,
1420 NULL);
1421 break;
1422 case PFSE_ICMP6:
1423 icmp6_error(pfse->pfse_m, pfse->pfse_icmp_type,
1424 pfse->pfse_icmp_code, pfse->pfse_icmp_mtu);
1425 break;
1426#endif /* INET6 */
1427 default:
1428 panic("%s: unknown type", __func__);
1429 }
1430 free(pfse, M_PFTEMP);
1431 }
1432 CURVNET_RESTORE();
1433}
1434
1435void
1436pf_purge_thread(void *v)
1437{
1438 u_int idx = 0;
1439
1440 CURVNET_SET((struct vnet *)v);
1441
1442 for (;;) {
1443 PF_RULES_RLOCK();
1444 rw_sleep(pf_purge_thread, &pf_rules_lock, 0, "pftm", hz / 10);
1445
1446 if (V_pf_end_threads) {
1447 /*
1448 * To cleanse up all kifs and rules we need
1449 * two runs: first one clears reference flags,
1450 * then pf_purge_expired_states() doesn't
1451 * raise them, and then second run frees.
1452 */
1453 PF_RULES_RUNLOCK();
1454 pf_purge_unlinked_rules();
1455 pfi_kif_purge();
1456
1457 /*
1458 * Now purge everything.
1459 */
1460 pf_purge_expired_states(0, pf_hashmask);
1461 pf_purge_expired_fragments();
1462 pf_purge_expired_src_nodes();
1463
1464 /*
1465 * Now all kifs & rules should be unreferenced,
1466 * thus should be successfully freed.
1467 */
1468 pf_purge_unlinked_rules();
1469 pfi_kif_purge();
1470
1471 /*
1472 * Announce success and exit.
1473 */
1474 PF_RULES_RLOCK();
1475 V_pf_end_threads++;
1476 PF_RULES_RUNLOCK();
1477 wakeup(pf_purge_thread);
1478 kproc_exit(0);
1479 }
1480 PF_RULES_RUNLOCK();
1481
1482 /* Process 1/interval fraction of the state table every run. */
1483 idx = pf_purge_expired_states(idx, pf_hashmask /
1484 (V_pf_default_rule.timeout[PFTM_INTERVAL] * 10));
1485
1486 /* Purge other expired types every PFTM_INTERVAL seconds. */
1487 if (idx == 0) {
1488 /*
1489 * Order is important:
1490 * - states and src nodes reference rules
1491 * - states and rules reference kifs
1492 */
1493 pf_purge_expired_fragments();
1494 pf_purge_expired_src_nodes();
1495 pf_purge_unlinked_rules();
1496 pfi_kif_purge();
1497 }
1498 }
1499 /* not reached */
1500 CURVNET_RESTORE();
1501}
1502
1503u_int32_t
1504pf_state_expires(const struct pf_state *state)
1505{
1506 u_int32_t timeout;
1507 u_int32_t start;
1508 u_int32_t end;
1509 u_int32_t states;
1510
1511 /* handle all PFTM_* > PFTM_MAX here */
1512 if (state->timeout == PFTM_PURGE)
1513 return (time_uptime);
1514 KASSERT(state->timeout != PFTM_UNLINKED,
1515 ("pf_state_expires: timeout == PFTM_UNLINKED"));
1516 KASSERT((state->timeout < PFTM_MAX),
1517 ("pf_state_expires: timeout > PFTM_MAX"));
1518 timeout = state->rule.ptr->timeout[state->timeout];
1519 if (!timeout)
1520 timeout = V_pf_default_rule.timeout[state->timeout];
1521 start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1522 if (start) {
1523 end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1524 states = counter_u64_fetch(state->rule.ptr->states_cur);
1525 } else {
1526 start = V_pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1527 end = V_pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1528 states = V_pf_status.states;
1529 }
1530 if (end && states > start && start < end) {
1531 if (states < end)
1532 return (state->expire + timeout * (end - states) /
1533 (end - start));
1534 else
1535 return (time_uptime);
1536 }
1537 return (state->expire + timeout);
1538}
1539
1540void
1541pf_purge_expired_src_nodes()
1542{
1543 struct pf_src_node_list freelist;
1544 struct pf_srchash *sh;
1545 struct pf_src_node *cur, *next;
1546 int i;
1547
1548 LIST_INIT(&freelist);
1549 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
1550 PF_HASHROW_LOCK(sh);
1551 LIST_FOREACH_SAFE(cur, &sh->nodes, entry, next)
1552 if (cur->states == 0 && cur->expire <= time_uptime) {
744 return (count);
745}
746
747void
748pf_mtag_initialize()
749{
750
751 pf_mtag_z = uma_zcreate("pf mtags", sizeof(struct m_tag) +
752 sizeof(struct pf_mtag), NULL, NULL, pf_mtag_uminit, NULL,
753 UMA_ALIGN_PTR, 0);
754}
755
756/* Per-vnet data storage structures initialization. */
757void
758pf_initialize()
759{
760 struct pf_keyhash *kh;
761 struct pf_idhash *ih;
762 struct pf_srchash *sh;
763 u_int i;
764
765 TUNABLE_ULONG_FETCH("net.pf.states_hashsize", &pf_hashsize);
766 if (pf_hashsize == 0 || !powerof2(pf_hashsize))
767 pf_hashsize = PF_HASHSIZ;
768 TUNABLE_ULONG_FETCH("net.pf.source_nodes_hashsize", &pf_srchashsize);
769 if (pf_srchashsize == 0 || !powerof2(pf_srchashsize))
770 pf_srchashsize = PF_HASHSIZ / 4;
771
772 V_pf_hashseed = arc4random();
773
774 /* States and state keys storage. */
775 V_pf_state_z = uma_zcreate("pf states", sizeof(struct pf_state),
776 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
777 V_pf_limits[PF_LIMIT_STATES].zone = V_pf_state_z;
778 uma_zone_set_max(V_pf_state_z, PFSTATE_HIWAT);
779 uma_zone_set_warning(V_pf_state_z, "PF states limit reached");
780
781 V_pf_state_key_z = uma_zcreate("pf state keys",
782 sizeof(struct pf_state_key), pf_state_key_ctor, NULL, NULL, NULL,
783 UMA_ALIGN_PTR, 0);
784 V_pf_keyhash = malloc(pf_hashsize * sizeof(struct pf_keyhash),
785 M_PFHASH, M_WAITOK | M_ZERO);
786 V_pf_idhash = malloc(pf_hashsize * sizeof(struct pf_idhash),
787 M_PFHASH, M_WAITOK | M_ZERO);
788 pf_hashmask = pf_hashsize - 1;
789 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
790 i++, kh++, ih++) {
791 mtx_init(&kh->lock, "pf_keyhash", NULL, MTX_DEF | MTX_DUPOK);
792 mtx_init(&ih->lock, "pf_idhash", NULL, MTX_DEF);
793 }
794
795 /* Source nodes. */
796 V_pf_sources_z = uma_zcreate("pf source nodes",
797 sizeof(struct pf_src_node), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
798 0);
799 V_pf_limits[PF_LIMIT_SRC_NODES].zone = V_pf_sources_z;
800 uma_zone_set_max(V_pf_sources_z, PFSNODE_HIWAT);
801 uma_zone_set_warning(V_pf_sources_z, "PF source nodes limit reached");
802 V_pf_srchash = malloc(pf_srchashsize * sizeof(struct pf_srchash),
803 M_PFHASH, M_WAITOK|M_ZERO);
804 pf_srchashmask = pf_srchashsize - 1;
805 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++)
806 mtx_init(&sh->lock, "pf_srchash", NULL, MTX_DEF);
807
808 /* ALTQ */
809 TAILQ_INIT(&V_pf_altqs[0]);
810 TAILQ_INIT(&V_pf_altqs[1]);
811 TAILQ_INIT(&V_pf_pabuf);
812 V_pf_altqs_active = &V_pf_altqs[0];
813 V_pf_altqs_inactive = &V_pf_altqs[1];
814
815
816 /* Send & overload+flush queues. */
817 STAILQ_INIT(&V_pf_sendqueue);
818 SLIST_INIT(&V_pf_overloadqueue);
819 TASK_INIT(&V_pf_overloadtask, 0, pf_overload_task, curvnet);
820 mtx_init(&pf_sendqueue_mtx, "pf send queue", NULL, MTX_DEF);
821 mtx_init(&pf_overloadqueue_mtx, "pf overload/flush queue", NULL,
822 MTX_DEF);
823
824 /* Unlinked, but may be referenced rules. */
825 TAILQ_INIT(&V_pf_unlinked_rules);
826 mtx_init(&pf_unlnkdrules_mtx, "pf unlinked rules", NULL, MTX_DEF);
827}
828
829void
830pf_mtag_cleanup()
831{
832
833 uma_zdestroy(pf_mtag_z);
834}
835
836void
837pf_cleanup()
838{
839 struct pf_keyhash *kh;
840 struct pf_idhash *ih;
841 struct pf_srchash *sh;
842 struct pf_send_entry *pfse, *next;
843 u_int i;
844
845 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
846 i++, kh++, ih++) {
847 KASSERT(LIST_EMPTY(&kh->keys), ("%s: key hash not empty",
848 __func__));
849 KASSERT(LIST_EMPTY(&ih->states), ("%s: id hash not empty",
850 __func__));
851 mtx_destroy(&kh->lock);
852 mtx_destroy(&ih->lock);
853 }
854 free(V_pf_keyhash, M_PFHASH);
855 free(V_pf_idhash, M_PFHASH);
856
857 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
858 KASSERT(LIST_EMPTY(&sh->nodes),
859 ("%s: source node hash not empty", __func__));
860 mtx_destroy(&sh->lock);
861 }
862 free(V_pf_srchash, M_PFHASH);
863
864 STAILQ_FOREACH_SAFE(pfse, &V_pf_sendqueue, pfse_next, next) {
865 m_freem(pfse->pfse_m);
866 free(pfse, M_PFTEMP);
867 }
868
869 mtx_destroy(&pf_sendqueue_mtx);
870 mtx_destroy(&pf_overloadqueue_mtx);
871 mtx_destroy(&pf_unlnkdrules_mtx);
872
873 uma_zdestroy(V_pf_sources_z);
874 uma_zdestroy(V_pf_state_z);
875 uma_zdestroy(V_pf_state_key_z);
876}
877
878static int
879pf_mtag_uminit(void *mem, int size, int how)
880{
881 struct m_tag *t;
882
883 t = (struct m_tag *)mem;
884 t->m_tag_cookie = MTAG_ABI_COMPAT;
885 t->m_tag_id = PACKET_TAG_PF;
886 t->m_tag_len = sizeof(struct pf_mtag);
887 t->m_tag_free = pf_mtag_free;
888
889 return (0);
890}
891
892static void
893pf_mtag_free(struct m_tag *t)
894{
895
896 uma_zfree(pf_mtag_z, t);
897}
898
899struct pf_mtag *
900pf_get_mtag(struct mbuf *m)
901{
902 struct m_tag *mtag;
903
904 if ((mtag = m_tag_find(m, PACKET_TAG_PF, NULL)) != NULL)
905 return ((struct pf_mtag *)(mtag + 1));
906
907 mtag = uma_zalloc(pf_mtag_z, M_NOWAIT);
908 if (mtag == NULL)
909 return (NULL);
910 bzero(mtag + 1, sizeof(struct pf_mtag));
911 m_tag_prepend(m, mtag);
912
913 return ((struct pf_mtag *)(mtag + 1));
914}
915
916static int
917pf_state_key_attach(struct pf_state_key *skw, struct pf_state_key *sks,
918 struct pf_state *s)
919{
920 struct pf_keyhash *khs, *khw, *kh;
921 struct pf_state_key *sk, *cur;
922 struct pf_state *si, *olds = NULL;
923 int idx;
924
925 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
926 KASSERT(s->key[PF_SK_WIRE] == NULL, ("%s: state has key", __func__));
927 KASSERT(s->key[PF_SK_STACK] == NULL, ("%s: state has key", __func__));
928
929 /*
930 * We need to lock hash slots of both keys. To avoid deadlock
931 * we always lock the slot with lower address first. Unlock order
932 * isn't important.
933 *
934 * We also need to lock ID hash slot before dropping key
935 * locks. On success we return with ID hash slot locked.
936 */
937
938 if (skw == sks) {
939 khs = khw = &V_pf_keyhash[pf_hashkey(skw)];
940 PF_HASHROW_LOCK(khs);
941 } else {
942 khs = &V_pf_keyhash[pf_hashkey(sks)];
943 khw = &V_pf_keyhash[pf_hashkey(skw)];
944 if (khs == khw) {
945 PF_HASHROW_LOCK(khs);
946 } else if (khs < khw) {
947 PF_HASHROW_LOCK(khs);
948 PF_HASHROW_LOCK(khw);
949 } else {
950 PF_HASHROW_LOCK(khw);
951 PF_HASHROW_LOCK(khs);
952 }
953 }
954
955#define KEYS_UNLOCK() do { \
956 if (khs != khw) { \
957 PF_HASHROW_UNLOCK(khs); \
958 PF_HASHROW_UNLOCK(khw); \
959 } else \
960 PF_HASHROW_UNLOCK(khs); \
961} while (0)
962
963 /*
964 * First run: start with wire key.
965 */
966 sk = skw;
967 kh = khw;
968 idx = PF_SK_WIRE;
969
970keyattach:
971 LIST_FOREACH(cur, &kh->keys, entry)
972 if (bcmp(cur, sk, sizeof(struct pf_state_key_cmp)) == 0)
973 break;
974
975 if (cur != NULL) {
976 /* Key exists. Check for same kif, if none, add to key. */
977 TAILQ_FOREACH(si, &cur->states[idx], key_list[idx]) {
978 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(si)];
979
980 PF_HASHROW_LOCK(ih);
981 if (si->kif == s->kif &&
982 si->direction == s->direction) {
983 if (sk->proto == IPPROTO_TCP &&
984 si->src.state >= TCPS_FIN_WAIT_2 &&
985 si->dst.state >= TCPS_FIN_WAIT_2) {
986 /*
987 * New state matches an old >FIN_WAIT_2
988 * state. We can't drop key hash locks,
989 * thus we can't unlink it properly.
990 *
991 * As a workaround we drop it into
992 * TCPS_CLOSED state, schedule purge
993 * ASAP and push it into the very end
994 * of the slot TAILQ, so that it won't
995 * conflict with our new state.
996 */
997 si->src.state = si->dst.state =
998 TCPS_CLOSED;
999 si->timeout = PFTM_PURGE;
1000 olds = si;
1001 } else {
1002 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1003 printf("pf: %s key attach "
1004 "failed on %s: ",
1005 (idx == PF_SK_WIRE) ?
1006 "wire" : "stack",
1007 s->kif->pfik_name);
1008 pf_print_state_parts(s,
1009 (idx == PF_SK_WIRE) ?
1010 sk : NULL,
1011 (idx == PF_SK_STACK) ?
1012 sk : NULL);
1013 printf(", existing: ");
1014 pf_print_state_parts(si,
1015 (idx == PF_SK_WIRE) ?
1016 sk : NULL,
1017 (idx == PF_SK_STACK) ?
1018 sk : NULL);
1019 printf("\n");
1020 }
1021 PF_HASHROW_UNLOCK(ih);
1022 KEYS_UNLOCK();
1023 uma_zfree(V_pf_state_key_z, sk);
1024 if (idx == PF_SK_STACK)
1025 pf_detach_state(s);
1026 return (EEXIST); /* collision! */
1027 }
1028 }
1029 PF_HASHROW_UNLOCK(ih);
1030 }
1031 uma_zfree(V_pf_state_key_z, sk);
1032 s->key[idx] = cur;
1033 } else {
1034 LIST_INSERT_HEAD(&kh->keys, sk, entry);
1035 s->key[idx] = sk;
1036 }
1037
1038stateattach:
1039 /* List is sorted, if-bound states before floating. */
1040 if (s->kif == V_pfi_all)
1041 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], s, key_list[idx]);
1042 else
1043 TAILQ_INSERT_HEAD(&s->key[idx]->states[idx], s, key_list[idx]);
1044
1045 if (olds) {
1046 TAILQ_REMOVE(&s->key[idx]->states[idx], olds, key_list[idx]);
1047 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], olds,
1048 key_list[idx]);
1049 olds = NULL;
1050 }
1051
1052 /*
1053 * Attach done. See how should we (or should not?)
1054 * attach a second key.
1055 */
1056 if (sks == skw) {
1057 s->key[PF_SK_STACK] = s->key[PF_SK_WIRE];
1058 idx = PF_SK_STACK;
1059 sks = NULL;
1060 goto stateattach;
1061 } else if (sks != NULL) {
1062 /*
1063 * Continue attaching with stack key.
1064 */
1065 sk = sks;
1066 kh = khs;
1067 idx = PF_SK_STACK;
1068 sks = NULL;
1069 goto keyattach;
1070 }
1071
1072 PF_STATE_LOCK(s);
1073 KEYS_UNLOCK();
1074
1075 KASSERT(s->key[PF_SK_WIRE] != NULL && s->key[PF_SK_STACK] != NULL,
1076 ("%s failure", __func__));
1077
1078 return (0);
1079#undef KEYS_UNLOCK
1080}
1081
1082static void
1083pf_detach_state(struct pf_state *s)
1084{
1085 struct pf_state_key *sks = s->key[PF_SK_STACK];
1086 struct pf_keyhash *kh;
1087
1088 if (sks != NULL) {
1089 kh = &V_pf_keyhash[pf_hashkey(sks)];
1090 PF_HASHROW_LOCK(kh);
1091 if (s->key[PF_SK_STACK] != NULL)
1092 pf_state_key_detach(s, PF_SK_STACK);
1093 /*
1094 * If both point to same key, then we are done.
1095 */
1096 if (sks == s->key[PF_SK_WIRE]) {
1097 pf_state_key_detach(s, PF_SK_WIRE);
1098 PF_HASHROW_UNLOCK(kh);
1099 return;
1100 }
1101 PF_HASHROW_UNLOCK(kh);
1102 }
1103
1104 if (s->key[PF_SK_WIRE] != NULL) {
1105 kh = &V_pf_keyhash[pf_hashkey(s->key[PF_SK_WIRE])];
1106 PF_HASHROW_LOCK(kh);
1107 if (s->key[PF_SK_WIRE] != NULL)
1108 pf_state_key_detach(s, PF_SK_WIRE);
1109 PF_HASHROW_UNLOCK(kh);
1110 }
1111}
1112
1113static void
1114pf_state_key_detach(struct pf_state *s, int idx)
1115{
1116 struct pf_state_key *sk = s->key[idx];
1117#ifdef INVARIANTS
1118 struct pf_keyhash *kh = &V_pf_keyhash[pf_hashkey(sk)];
1119
1120 PF_HASHROW_ASSERT(kh);
1121#endif
1122 TAILQ_REMOVE(&sk->states[idx], s, key_list[idx]);
1123 s->key[idx] = NULL;
1124
1125 if (TAILQ_EMPTY(&sk->states[0]) && TAILQ_EMPTY(&sk->states[1])) {
1126 LIST_REMOVE(sk, entry);
1127 uma_zfree(V_pf_state_key_z, sk);
1128 }
1129}
1130
1131static int
1132pf_state_key_ctor(void *mem, int size, void *arg, int flags)
1133{
1134 struct pf_state_key *sk = mem;
1135
1136 bzero(sk, sizeof(struct pf_state_key_cmp));
1137 TAILQ_INIT(&sk->states[PF_SK_WIRE]);
1138 TAILQ_INIT(&sk->states[PF_SK_STACK]);
1139
1140 return (0);
1141}
1142
1143struct pf_state_key *
1144pf_state_key_setup(struct pf_pdesc *pd, struct pf_addr *saddr,
1145 struct pf_addr *daddr, u_int16_t sport, u_int16_t dport)
1146{
1147 struct pf_state_key *sk;
1148
1149 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1150 if (sk == NULL)
1151 return (NULL);
1152
1153 PF_ACPY(&sk->addr[pd->sidx], saddr, pd->af);
1154 PF_ACPY(&sk->addr[pd->didx], daddr, pd->af);
1155 sk->port[pd->sidx] = sport;
1156 sk->port[pd->didx] = dport;
1157 sk->proto = pd->proto;
1158 sk->af = pd->af;
1159
1160 return (sk);
1161}
1162
1163struct pf_state_key *
1164pf_state_key_clone(struct pf_state_key *orig)
1165{
1166 struct pf_state_key *sk;
1167
1168 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1169 if (sk == NULL)
1170 return (NULL);
1171
1172 bcopy(orig, sk, sizeof(struct pf_state_key_cmp));
1173
1174 return (sk);
1175}
1176
1177int
1178pf_state_insert(struct pfi_kif *kif, struct pf_state_key *skw,
1179 struct pf_state_key *sks, struct pf_state *s)
1180{
1181 struct pf_idhash *ih;
1182 struct pf_state *cur;
1183 int error;
1184
1185 KASSERT(TAILQ_EMPTY(&sks->states[0]) && TAILQ_EMPTY(&sks->states[1]),
1186 ("%s: sks not pristine", __func__));
1187 KASSERT(TAILQ_EMPTY(&skw->states[0]) && TAILQ_EMPTY(&skw->states[1]),
1188 ("%s: skw not pristine", __func__));
1189 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
1190
1191 s->kif = kif;
1192
1193 if (s->id == 0 && s->creatorid == 0) {
1194 /* XXX: should be atomic, but probability of collision low */
1195 if ((s->id = V_pf_stateid[curcpu]++) == PFID_MAXID)
1196 V_pf_stateid[curcpu] = 1;
1197 s->id |= (uint64_t )curcpu << PFID_CPUSHIFT;
1198 s->id = htobe64(s->id);
1199 s->creatorid = V_pf_status.hostid;
1200 }
1201
1202 /* Returns with ID locked on success. */
1203 if ((error = pf_state_key_attach(skw, sks, s)) != 0)
1204 return (error);
1205
1206 ih = &V_pf_idhash[PF_IDHASH(s)];
1207 PF_HASHROW_ASSERT(ih);
1208 LIST_FOREACH(cur, &ih->states, entry)
1209 if (cur->id == s->id && cur->creatorid == s->creatorid)
1210 break;
1211
1212 if (cur != NULL) {
1213 PF_HASHROW_UNLOCK(ih);
1214 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1215 printf("pf: state ID collision: "
1216 "id: %016llx creatorid: %08x\n",
1217 (unsigned long long)be64toh(s->id),
1218 ntohl(s->creatorid));
1219 }
1220 pf_detach_state(s);
1221 return (EEXIST);
1222 }
1223 LIST_INSERT_HEAD(&ih->states, s, entry);
1224 /* One for keys, one for ID hash. */
1225 refcount_init(&s->refs, 2);
1226
1227 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_INSERT], 1);
1228 if (pfsync_insert_state_ptr != NULL)
1229 pfsync_insert_state_ptr(s);
1230
1231 /* Returns locked. */
1232 return (0);
1233}
1234
1235/*
1236 * Find state by ID: returns with locked row on success.
1237 */
1238struct pf_state *
1239pf_find_state_byid(uint64_t id, uint32_t creatorid)
1240{
1241 struct pf_idhash *ih;
1242 struct pf_state *s;
1243
1244 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1245
1246 ih = &V_pf_idhash[(be64toh(id) % (pf_hashmask + 1))];
1247
1248 PF_HASHROW_LOCK(ih);
1249 LIST_FOREACH(s, &ih->states, entry)
1250 if (s->id == id && s->creatorid == creatorid)
1251 break;
1252
1253 if (s == NULL)
1254 PF_HASHROW_UNLOCK(ih);
1255
1256 return (s);
1257}
1258
1259/*
1260 * Find state by key.
1261 * Returns with ID hash slot locked on success.
1262 */
1263static struct pf_state *
1264pf_find_state(struct pfi_kif *kif, struct pf_state_key_cmp *key, u_int dir)
1265{
1266 struct pf_keyhash *kh;
1267 struct pf_state_key *sk;
1268 struct pf_state *s;
1269 int idx;
1270
1271 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1272
1273 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1274
1275 PF_HASHROW_LOCK(kh);
1276 LIST_FOREACH(sk, &kh->keys, entry)
1277 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1278 break;
1279 if (sk == NULL) {
1280 PF_HASHROW_UNLOCK(kh);
1281 return (NULL);
1282 }
1283
1284 idx = (dir == PF_IN ? PF_SK_WIRE : PF_SK_STACK);
1285
1286 /* List is sorted, if-bound states before floating ones. */
1287 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx])
1288 if (s->kif == V_pfi_all || s->kif == kif) {
1289 PF_STATE_LOCK(s);
1290 PF_HASHROW_UNLOCK(kh);
1291 if (s->timeout >= PFTM_MAX) {
1292 /*
1293 * State is either being processed by
1294 * pf_unlink_state() in an other thread, or
1295 * is scheduled for immediate expiry.
1296 */
1297 PF_STATE_UNLOCK(s);
1298 return (NULL);
1299 }
1300 return (s);
1301 }
1302 PF_HASHROW_UNLOCK(kh);
1303
1304 return (NULL);
1305}
1306
1307struct pf_state *
1308pf_find_state_all(struct pf_state_key_cmp *key, u_int dir, int *more)
1309{
1310 struct pf_keyhash *kh;
1311 struct pf_state_key *sk;
1312 struct pf_state *s, *ret = NULL;
1313 int idx, inout = 0;
1314
1315 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1316
1317 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1318
1319 PF_HASHROW_LOCK(kh);
1320 LIST_FOREACH(sk, &kh->keys, entry)
1321 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1322 break;
1323 if (sk == NULL) {
1324 PF_HASHROW_UNLOCK(kh);
1325 return (NULL);
1326 }
1327 switch (dir) {
1328 case PF_IN:
1329 idx = PF_SK_WIRE;
1330 break;
1331 case PF_OUT:
1332 idx = PF_SK_STACK;
1333 break;
1334 case PF_INOUT:
1335 idx = PF_SK_WIRE;
1336 inout = 1;
1337 break;
1338 default:
1339 panic("%s: dir %u", __func__, dir);
1340 }
1341second_run:
1342 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx]) {
1343 if (more == NULL) {
1344 PF_HASHROW_UNLOCK(kh);
1345 return (s);
1346 }
1347
1348 if (ret)
1349 (*more)++;
1350 else
1351 ret = s;
1352 }
1353 if (inout == 1) {
1354 inout = 0;
1355 idx = PF_SK_STACK;
1356 goto second_run;
1357 }
1358 PF_HASHROW_UNLOCK(kh);
1359
1360 return (ret);
1361}
1362
1363/* END state table stuff */
1364
1365static void
1366pf_send(struct pf_send_entry *pfse)
1367{
1368
1369 PF_SENDQ_LOCK();
1370 STAILQ_INSERT_TAIL(&V_pf_sendqueue, pfse, pfse_next);
1371 PF_SENDQ_UNLOCK();
1372 swi_sched(V_pf_swi_cookie, 0);
1373}
1374
1375void
1376pf_intr(void *v)
1377{
1378 struct pf_send_head queue;
1379 struct pf_send_entry *pfse, *next;
1380
1381 CURVNET_SET((struct vnet *)v);
1382
1383 PF_SENDQ_LOCK();
1384 queue = V_pf_sendqueue;
1385 STAILQ_INIT(&V_pf_sendqueue);
1386 PF_SENDQ_UNLOCK();
1387
1388 STAILQ_FOREACH_SAFE(pfse, &queue, pfse_next, next) {
1389 switch (pfse->pfse_type) {
1390#ifdef INET
1391 case PFSE_IP:
1392 ip_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL);
1393 break;
1394 case PFSE_ICMP:
1395 icmp_error(pfse->pfse_m, pfse->pfse_icmp_type,
1396 pfse->pfse_icmp_code, 0, pfse->pfse_icmp_mtu);
1397 break;
1398#endif /* INET */
1399#ifdef INET6
1400 case PFSE_IP6:
1401 ip6_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL,
1402 NULL);
1403 break;
1404 case PFSE_ICMP6:
1405 icmp6_error(pfse->pfse_m, pfse->pfse_icmp_type,
1406 pfse->pfse_icmp_code, pfse->pfse_icmp_mtu);
1407 break;
1408#endif /* INET6 */
1409 default:
1410 panic("%s: unknown type", __func__);
1411 }
1412 free(pfse, M_PFTEMP);
1413 }
1414 CURVNET_RESTORE();
1415}
1416
1417void
1418pf_purge_thread(void *v)
1419{
1420 u_int idx = 0;
1421
1422 CURVNET_SET((struct vnet *)v);
1423
1424 for (;;) {
1425 PF_RULES_RLOCK();
1426 rw_sleep(pf_purge_thread, &pf_rules_lock, 0, "pftm", hz / 10);
1427
1428 if (V_pf_end_threads) {
1429 /*
1430 * To cleanse up all kifs and rules we need
1431 * two runs: first one clears reference flags,
1432 * then pf_purge_expired_states() doesn't
1433 * raise them, and then second run frees.
1434 */
1435 PF_RULES_RUNLOCK();
1436 pf_purge_unlinked_rules();
1437 pfi_kif_purge();
1438
1439 /*
1440 * Now purge everything.
1441 */
1442 pf_purge_expired_states(0, pf_hashmask);
1443 pf_purge_expired_fragments();
1444 pf_purge_expired_src_nodes();
1445
1446 /*
1447 * Now all kifs & rules should be unreferenced,
1448 * thus should be successfully freed.
1449 */
1450 pf_purge_unlinked_rules();
1451 pfi_kif_purge();
1452
1453 /*
1454 * Announce success and exit.
1455 */
1456 PF_RULES_RLOCK();
1457 V_pf_end_threads++;
1458 PF_RULES_RUNLOCK();
1459 wakeup(pf_purge_thread);
1460 kproc_exit(0);
1461 }
1462 PF_RULES_RUNLOCK();
1463
1464 /* Process 1/interval fraction of the state table every run. */
1465 idx = pf_purge_expired_states(idx, pf_hashmask /
1466 (V_pf_default_rule.timeout[PFTM_INTERVAL] * 10));
1467
1468 /* Purge other expired types every PFTM_INTERVAL seconds. */
1469 if (idx == 0) {
1470 /*
1471 * Order is important:
1472 * - states and src nodes reference rules
1473 * - states and rules reference kifs
1474 */
1475 pf_purge_expired_fragments();
1476 pf_purge_expired_src_nodes();
1477 pf_purge_unlinked_rules();
1478 pfi_kif_purge();
1479 }
1480 }
1481 /* not reached */
1482 CURVNET_RESTORE();
1483}
1484
1485u_int32_t
1486pf_state_expires(const struct pf_state *state)
1487{
1488 u_int32_t timeout;
1489 u_int32_t start;
1490 u_int32_t end;
1491 u_int32_t states;
1492
1493 /* handle all PFTM_* > PFTM_MAX here */
1494 if (state->timeout == PFTM_PURGE)
1495 return (time_uptime);
1496 KASSERT(state->timeout != PFTM_UNLINKED,
1497 ("pf_state_expires: timeout == PFTM_UNLINKED"));
1498 KASSERT((state->timeout < PFTM_MAX),
1499 ("pf_state_expires: timeout > PFTM_MAX"));
1500 timeout = state->rule.ptr->timeout[state->timeout];
1501 if (!timeout)
1502 timeout = V_pf_default_rule.timeout[state->timeout];
1503 start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1504 if (start) {
1505 end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1506 states = counter_u64_fetch(state->rule.ptr->states_cur);
1507 } else {
1508 start = V_pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1509 end = V_pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1510 states = V_pf_status.states;
1511 }
1512 if (end && states > start && start < end) {
1513 if (states < end)
1514 return (state->expire + timeout * (end - states) /
1515 (end - start));
1516 else
1517 return (time_uptime);
1518 }
1519 return (state->expire + timeout);
1520}
1521
1522void
1523pf_purge_expired_src_nodes()
1524{
1525 struct pf_src_node_list freelist;
1526 struct pf_srchash *sh;
1527 struct pf_src_node *cur, *next;
1528 int i;
1529
1530 LIST_INIT(&freelist);
1531 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
1532 PF_HASHROW_LOCK(sh);
1533 LIST_FOREACH_SAFE(cur, &sh->nodes, entry, next)
1534 if (cur->states == 0 && cur->expire <= time_uptime) {
1553 pf_unlink_src_node_locked(cur);
1535 pf_unlink_src_node(cur);
1554 LIST_INSERT_HEAD(&freelist, cur, entry);
1555 } else if (cur->rule.ptr != NULL)
1556 cur->rule.ptr->rule_flag |= PFRULE_REFS;
1557 PF_HASHROW_UNLOCK(sh);
1558 }
1559
1560 pf_free_src_nodes(&freelist);
1561
1562 V_pf_status.src_nodes = uma_zone_get_cur(V_pf_sources_z);
1563}
1564
1565static void
1566pf_src_tree_remove_state(struct pf_state *s)
1567{
1536 LIST_INSERT_HEAD(&freelist, cur, entry);
1537 } else if (cur->rule.ptr != NULL)
1538 cur->rule.ptr->rule_flag |= PFRULE_REFS;
1539 PF_HASHROW_UNLOCK(sh);
1540 }
1541
1542 pf_free_src_nodes(&freelist);
1543
1544 V_pf_status.src_nodes = uma_zone_get_cur(V_pf_sources_z);
1545}
1546
1547static void
1548pf_src_tree_remove_state(struct pf_state *s)
1549{
1568 u_int32_t timeout;
1550 struct pf_src_node *sn;
1551 struct pf_srchash *sh;
1552 uint32_t timeout;
1569
1553
1554 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE] ?
1555 s->rule.ptr->timeout[PFTM_SRC_NODE] :
1556 V_pf_default_rule.timeout[PFTM_SRC_NODE];
1557
1570 if (s->src_node != NULL) {
1558 if (s->src_node != NULL) {
1559 sn = s->src_node;
1560 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1561 PF_HASHROW_LOCK(sh);
1571 if (s->src.tcp_est)
1562 if (s->src.tcp_est)
1572 --s->src_node->conn;
1573 if (--s->src_node->states == 0) {
1574 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1575 if (!timeout)
1576 timeout =
1577 V_pf_default_rule.timeout[PFTM_SRC_NODE];
1578 s->src_node->expire = time_uptime + timeout;
1579 }
1563 --sn->conn;
1564 if (--sn->states == 0)
1565 sn->expire = time_uptime + timeout;
1566 PF_HASHROW_UNLOCK(sh);
1580 }
1581 if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1567 }
1568 if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1582 if (--s->nat_src_node->states == 0) {
1583 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1584 if (!timeout)
1585 timeout =
1586 V_pf_default_rule.timeout[PFTM_SRC_NODE];
1587 s->nat_src_node->expire = time_uptime + timeout;
1588 }
1569 sn = s->nat_src_node;
1570 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1571 PF_HASHROW_LOCK(sh);
1572 if (--sn->states == 0)
1573 sn->expire = time_uptime + timeout;
1574 PF_HASHROW_UNLOCK(sh);
1589 }
1590 s->src_node = s->nat_src_node = NULL;
1591}
1592
1593/*
1594 * Unlink and potentilly free a state. Function may be
1595 * called with ID hash row locked, but always returns
1596 * unlocked, since it needs to go through key hash locking.
1597 */
1598int
1599pf_unlink_state(struct pf_state *s, u_int flags)
1600{
1601 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(s)];
1602
1603 if ((flags & PF_ENTER_LOCKED) == 0)
1604 PF_HASHROW_LOCK(ih);
1605 else
1606 PF_HASHROW_ASSERT(ih);
1607
1608 if (s->timeout == PFTM_UNLINKED) {
1609 /*
1610 * State is being processed
1611 * by pf_unlink_state() in
1612 * an other thread.
1613 */
1614 PF_HASHROW_UNLOCK(ih);
1615 return (0); /* XXXGL: undefined actually */
1616 }
1617
1618 if (s->src.state == PF_TCPS_PROXY_DST) {
1619 /* XXX wire key the right one? */
1620 pf_send_tcp(NULL, s->rule.ptr, s->key[PF_SK_WIRE]->af,
1621 &s->key[PF_SK_WIRE]->addr[1],
1622 &s->key[PF_SK_WIRE]->addr[0],
1623 s->key[PF_SK_WIRE]->port[1],
1624 s->key[PF_SK_WIRE]->port[0],
1625 s->src.seqhi, s->src.seqlo + 1,
1626 TH_RST|TH_ACK, 0, 0, 0, 1, s->tag, NULL);
1627 }
1628
1629 LIST_REMOVE(s, entry);
1630 pf_src_tree_remove_state(s);
1631
1632 if (pfsync_delete_state_ptr != NULL)
1633 pfsync_delete_state_ptr(s);
1634
1635 STATE_DEC_COUNTERS(s);
1636
1637 s->timeout = PFTM_UNLINKED;
1638
1639 PF_HASHROW_UNLOCK(ih);
1640
1641 pf_detach_state(s);
1642 refcount_release(&s->refs);
1643
1644 return (pf_release_state(s));
1645}
1646
1647void
1648pf_free_state(struct pf_state *cur)
1649{
1650
1651 KASSERT(cur->refs == 0, ("%s: %p has refs", __func__, cur));
1652 KASSERT(cur->timeout == PFTM_UNLINKED, ("%s: timeout %u", __func__,
1653 cur->timeout));
1654
1655 pf_normalize_tcp_cleanup(cur);
1656 uma_zfree(V_pf_state_z, cur);
1657 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_REMOVALS], 1);
1658}
1659
1660/*
1661 * Called only from pf_purge_thread(), thus serialized.
1662 */
1663static u_int
1664pf_purge_expired_states(u_int i, int maxcheck)
1665{
1666 struct pf_idhash *ih;
1667 struct pf_state *s;
1668
1669 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1670
1671 /*
1672 * Go through hash and unlink states that expire now.
1673 */
1674 while (maxcheck > 0) {
1675
1676 ih = &V_pf_idhash[i];
1677relock:
1678 PF_HASHROW_LOCK(ih);
1679 LIST_FOREACH(s, &ih->states, entry) {
1680 if (pf_state_expires(s) <= time_uptime) {
1681 V_pf_status.states -=
1682 pf_unlink_state(s, PF_ENTER_LOCKED);
1683 goto relock;
1684 }
1685 s->rule.ptr->rule_flag |= PFRULE_REFS;
1686 if (s->nat_rule.ptr != NULL)
1687 s->nat_rule.ptr->rule_flag |= PFRULE_REFS;
1688 if (s->anchor.ptr != NULL)
1689 s->anchor.ptr->rule_flag |= PFRULE_REFS;
1690 s->kif->pfik_flags |= PFI_IFLAG_REFS;
1691 if (s->rt_kif)
1692 s->rt_kif->pfik_flags |= PFI_IFLAG_REFS;
1693 }
1694 PF_HASHROW_UNLOCK(ih);
1695
1696 /* Return when we hit end of hash. */
1697 if (++i > pf_hashmask) {
1698 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1699 return (0);
1700 }
1701
1702 maxcheck--;
1703 }
1704
1705 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1706
1707 return (i);
1708}
1709
1710static void
1711pf_purge_unlinked_rules()
1712{
1713 struct pf_rulequeue tmpq;
1714 struct pf_rule *r, *r1;
1715
1716 /*
1717 * If we have overloading task pending, then we'd
1718 * better skip purging this time. There is a tiny
1719 * probability that overloading task references
1720 * an already unlinked rule.
1721 */
1722 PF_OVERLOADQ_LOCK();
1723 if (!SLIST_EMPTY(&V_pf_overloadqueue)) {
1724 PF_OVERLOADQ_UNLOCK();
1725 return;
1726 }
1727 PF_OVERLOADQ_UNLOCK();
1728
1729 /*
1730 * Do naive mark-and-sweep garbage collecting of old rules.
1731 * Reference flag is raised by pf_purge_expired_states()
1732 * and pf_purge_expired_src_nodes().
1733 *
1734 * To avoid LOR between PF_UNLNKDRULES_LOCK/PF_RULES_WLOCK,
1735 * use a temporary queue.
1736 */
1737 TAILQ_INIT(&tmpq);
1738 PF_UNLNKDRULES_LOCK();
1739 TAILQ_FOREACH_SAFE(r, &V_pf_unlinked_rules, entries, r1) {
1740 if (!(r->rule_flag & PFRULE_REFS)) {
1741 TAILQ_REMOVE(&V_pf_unlinked_rules, r, entries);
1742 TAILQ_INSERT_TAIL(&tmpq, r, entries);
1743 } else
1744 r->rule_flag &= ~PFRULE_REFS;
1745 }
1746 PF_UNLNKDRULES_UNLOCK();
1747
1748 if (!TAILQ_EMPTY(&tmpq)) {
1749 PF_RULES_WLOCK();
1750 TAILQ_FOREACH_SAFE(r, &tmpq, entries, r1) {
1751 TAILQ_REMOVE(&tmpq, r, entries);
1752 pf_free_rule(r);
1753 }
1754 PF_RULES_WUNLOCK();
1755 }
1756}
1757
1758void
1759pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1760{
1761 switch (af) {
1762#ifdef INET
1763 case AF_INET: {
1764 u_int32_t a = ntohl(addr->addr32[0]);
1765 printf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1766 (a>>8)&255, a&255);
1767 if (p) {
1768 p = ntohs(p);
1769 printf(":%u", p);
1770 }
1771 break;
1772 }
1773#endif /* INET */
1774#ifdef INET6
1775 case AF_INET6: {
1776 u_int16_t b;
1777 u_int8_t i, curstart, curend, maxstart, maxend;
1778 curstart = curend = maxstart = maxend = 255;
1779 for (i = 0; i < 8; i++) {
1780 if (!addr->addr16[i]) {
1781 if (curstart == 255)
1782 curstart = i;
1783 curend = i;
1784 } else {
1785 if ((curend - curstart) >
1786 (maxend - maxstart)) {
1787 maxstart = curstart;
1788 maxend = curend;
1789 }
1790 curstart = curend = 255;
1791 }
1792 }
1793 if ((curend - curstart) >
1794 (maxend - maxstart)) {
1795 maxstart = curstart;
1796 maxend = curend;
1797 }
1798 for (i = 0; i < 8; i++) {
1799 if (i >= maxstart && i <= maxend) {
1800 if (i == 0)
1801 printf(":");
1802 if (i == maxend)
1803 printf(":");
1804 } else {
1805 b = ntohs(addr->addr16[i]);
1806 printf("%x", b);
1807 if (i < 7)
1808 printf(":");
1809 }
1810 }
1811 if (p) {
1812 p = ntohs(p);
1813 printf("[%u]", p);
1814 }
1815 break;
1816 }
1817#endif /* INET6 */
1818 }
1819}
1820
1821void
1822pf_print_state(struct pf_state *s)
1823{
1824 pf_print_state_parts(s, NULL, NULL);
1825}
1826
1827static void
1828pf_print_state_parts(struct pf_state *s,
1829 struct pf_state_key *skwp, struct pf_state_key *sksp)
1830{
1831 struct pf_state_key *skw, *sks;
1832 u_int8_t proto, dir;
1833
1834 /* Do our best to fill these, but they're skipped if NULL */
1835 skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1836 sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1837 proto = skw ? skw->proto : (sks ? sks->proto : 0);
1838 dir = s ? s->direction : 0;
1839
1840 switch (proto) {
1841 case IPPROTO_IPV4:
1842 printf("IPv4");
1843 break;
1844 case IPPROTO_IPV6:
1845 printf("IPv6");
1846 break;
1847 case IPPROTO_TCP:
1848 printf("TCP");
1849 break;
1850 case IPPROTO_UDP:
1851 printf("UDP");
1852 break;
1853 case IPPROTO_ICMP:
1854 printf("ICMP");
1855 break;
1856 case IPPROTO_ICMPV6:
1857 printf("ICMPv6");
1858 break;
1859 default:
1860 printf("%u", skw->proto);
1861 break;
1862 }
1863 switch (dir) {
1864 case PF_IN:
1865 printf(" in");
1866 break;
1867 case PF_OUT:
1868 printf(" out");
1869 break;
1870 }
1871 if (skw) {
1872 printf(" wire: ");
1873 pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1874 printf(" ");
1875 pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1876 }
1877 if (sks) {
1878 printf(" stack: ");
1879 if (sks != skw) {
1880 pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1881 printf(" ");
1882 pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1883 } else
1884 printf("-");
1885 }
1886 if (s) {
1887 if (proto == IPPROTO_TCP) {
1888 printf(" [lo=%u high=%u win=%u modulator=%u",
1889 s->src.seqlo, s->src.seqhi,
1890 s->src.max_win, s->src.seqdiff);
1891 if (s->src.wscale && s->dst.wscale)
1892 printf(" wscale=%u",
1893 s->src.wscale & PF_WSCALE_MASK);
1894 printf("]");
1895 printf(" [lo=%u high=%u win=%u modulator=%u",
1896 s->dst.seqlo, s->dst.seqhi,
1897 s->dst.max_win, s->dst.seqdiff);
1898 if (s->src.wscale && s->dst.wscale)
1899 printf(" wscale=%u",
1900 s->dst.wscale & PF_WSCALE_MASK);
1901 printf("]");
1902 }
1903 printf(" %u:%u", s->src.state, s->dst.state);
1904 }
1905}
1906
1907void
1908pf_print_flags(u_int8_t f)
1909{
1910 if (f)
1911 printf(" ");
1912 if (f & TH_FIN)
1913 printf("F");
1914 if (f & TH_SYN)
1915 printf("S");
1916 if (f & TH_RST)
1917 printf("R");
1918 if (f & TH_PUSH)
1919 printf("P");
1920 if (f & TH_ACK)
1921 printf("A");
1922 if (f & TH_URG)
1923 printf("U");
1924 if (f & TH_ECE)
1925 printf("E");
1926 if (f & TH_CWR)
1927 printf("W");
1928}
1929
1930#define PF_SET_SKIP_STEPS(i) \
1931 do { \
1932 while (head[i] != cur) { \
1933 head[i]->skip[i].ptr = cur; \
1934 head[i] = TAILQ_NEXT(head[i], entries); \
1935 } \
1936 } while (0)
1937
1938void
1939pf_calc_skip_steps(struct pf_rulequeue *rules)
1940{
1941 struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
1942 int i;
1943
1944 cur = TAILQ_FIRST(rules);
1945 prev = cur;
1946 for (i = 0; i < PF_SKIP_COUNT; ++i)
1947 head[i] = cur;
1948 while (cur != NULL) {
1949
1950 if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
1951 PF_SET_SKIP_STEPS(PF_SKIP_IFP);
1952 if (cur->direction != prev->direction)
1953 PF_SET_SKIP_STEPS(PF_SKIP_DIR);
1954 if (cur->af != prev->af)
1955 PF_SET_SKIP_STEPS(PF_SKIP_AF);
1956 if (cur->proto != prev->proto)
1957 PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
1958 if (cur->src.neg != prev->src.neg ||
1959 pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
1960 PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
1961 if (cur->src.port[0] != prev->src.port[0] ||
1962 cur->src.port[1] != prev->src.port[1] ||
1963 cur->src.port_op != prev->src.port_op)
1964 PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
1965 if (cur->dst.neg != prev->dst.neg ||
1966 pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
1967 PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
1968 if (cur->dst.port[0] != prev->dst.port[0] ||
1969 cur->dst.port[1] != prev->dst.port[1] ||
1970 cur->dst.port_op != prev->dst.port_op)
1971 PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
1972
1973 prev = cur;
1974 cur = TAILQ_NEXT(cur, entries);
1975 }
1976 for (i = 0; i < PF_SKIP_COUNT; ++i)
1977 PF_SET_SKIP_STEPS(i);
1978}
1979
1980static int
1981pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
1982{
1983 if (aw1->type != aw2->type)
1984 return (1);
1985 switch (aw1->type) {
1986 case PF_ADDR_ADDRMASK:
1987 case PF_ADDR_RANGE:
1988 if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, 0))
1989 return (1);
1990 if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, 0))
1991 return (1);
1992 return (0);
1993 case PF_ADDR_DYNIFTL:
1994 return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
1995 case PF_ADDR_NOROUTE:
1996 case PF_ADDR_URPFFAILED:
1997 return (0);
1998 case PF_ADDR_TABLE:
1999 return (aw1->p.tbl != aw2->p.tbl);
2000 default:
2001 printf("invalid address type: %d\n", aw1->type);
2002 return (1);
2003 }
2004}
2005
2006u_int16_t
2007pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
2008{
2009 u_int32_t l;
2010
2011 if (udp && !cksum)
2012 return (0x0000);
2013 l = cksum + old - new;
2014 l = (l >> 16) + (l & 65535);
2015 l = l & 65535;
2016 if (udp && !l)
2017 return (0xFFFF);
2018 return (l);
2019}
2020
2021static void
2022pf_change_ap(struct pf_addr *a, u_int16_t *p, u_int16_t *ic, u_int16_t *pc,
2023 struct pf_addr *an, u_int16_t pn, u_int8_t u, sa_family_t af)
2024{
2025 struct pf_addr ao;
2026 u_int16_t po = *p;
2027
2028 PF_ACPY(&ao, a, af);
2029 PF_ACPY(a, an, af);
2030
2031 *p = pn;
2032
2033 switch (af) {
2034#ifdef INET
2035 case AF_INET:
2036 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2037 ao.addr16[0], an->addr16[0], 0),
2038 ao.addr16[1], an->addr16[1], 0);
2039 *p = pn;
2040 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
2041 ao.addr16[0], an->addr16[0], u),
2042 ao.addr16[1], an->addr16[1], u),
2043 po, pn, u);
2044 break;
2045#endif /* INET */
2046#ifdef INET6
2047 case AF_INET6:
2048 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2049 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2050 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
2051 ao.addr16[0], an->addr16[0], u),
2052 ao.addr16[1], an->addr16[1], u),
2053 ao.addr16[2], an->addr16[2], u),
2054 ao.addr16[3], an->addr16[3], u),
2055 ao.addr16[4], an->addr16[4], u),
2056 ao.addr16[5], an->addr16[5], u),
2057 ao.addr16[6], an->addr16[6], u),
2058 ao.addr16[7], an->addr16[7], u),
2059 po, pn, u);
2060 break;
2061#endif /* INET6 */
2062 }
2063}
2064
2065
2066/* Changes a u_int32_t. Uses a void * so there are no align restrictions */
2067void
2068pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
2069{
2070 u_int32_t ao;
2071
2072 memcpy(&ao, a, sizeof(ao));
2073 memcpy(a, &an, sizeof(u_int32_t));
2074 *c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
2075 ao % 65536, an % 65536, u);
2076}
2077
2078#ifdef INET6
2079static void
2080pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
2081{
2082 struct pf_addr ao;
2083
2084 PF_ACPY(&ao, a, AF_INET6);
2085 PF_ACPY(a, an, AF_INET6);
2086
2087 *c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2088 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2089 pf_cksum_fixup(pf_cksum_fixup(*c,
2090 ao.addr16[0], an->addr16[0], u),
2091 ao.addr16[1], an->addr16[1], u),
2092 ao.addr16[2], an->addr16[2], u),
2093 ao.addr16[3], an->addr16[3], u),
2094 ao.addr16[4], an->addr16[4], u),
2095 ao.addr16[5], an->addr16[5], u),
2096 ao.addr16[6], an->addr16[6], u),
2097 ao.addr16[7], an->addr16[7], u);
2098}
2099#endif /* INET6 */
2100
2101static void
2102pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
2103 struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
2104 u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
2105{
2106 struct pf_addr oia, ooa;
2107
2108 PF_ACPY(&oia, ia, af);
2109 if (oa)
2110 PF_ACPY(&ooa, oa, af);
2111
2112 /* Change inner protocol port, fix inner protocol checksum. */
2113 if (ip != NULL) {
2114 u_int16_t oip = *ip;
2115 u_int32_t opc;
2116
2117 if (pc != NULL)
2118 opc = *pc;
2119 *ip = np;
2120 if (pc != NULL)
2121 *pc = pf_cksum_fixup(*pc, oip, *ip, u);
2122 *ic = pf_cksum_fixup(*ic, oip, *ip, 0);
2123 if (pc != NULL)
2124 *ic = pf_cksum_fixup(*ic, opc, *pc, 0);
2125 }
2126 /* Change inner ip address, fix inner ip and icmp checksums. */
2127 PF_ACPY(ia, na, af);
2128 switch (af) {
2129#ifdef INET
2130 case AF_INET: {
2131 u_int32_t oh2c = *h2c;
2132
2133 *h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
2134 oia.addr16[0], ia->addr16[0], 0),
2135 oia.addr16[1], ia->addr16[1], 0);
2136 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2137 oia.addr16[0], ia->addr16[0], 0),
2138 oia.addr16[1], ia->addr16[1], 0);
2139 *ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
2140 break;
2141 }
2142#endif /* INET */
2143#ifdef INET6
2144 case AF_INET6:
2145 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2146 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2147 pf_cksum_fixup(pf_cksum_fixup(*ic,
2148 oia.addr16[0], ia->addr16[0], u),
2149 oia.addr16[1], ia->addr16[1], u),
2150 oia.addr16[2], ia->addr16[2], u),
2151 oia.addr16[3], ia->addr16[3], u),
2152 oia.addr16[4], ia->addr16[4], u),
2153 oia.addr16[5], ia->addr16[5], u),
2154 oia.addr16[6], ia->addr16[6], u),
2155 oia.addr16[7], ia->addr16[7], u);
2156 break;
2157#endif /* INET6 */
2158 }
2159 /* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
2160 if (oa) {
2161 PF_ACPY(oa, na, af);
2162 switch (af) {
2163#ifdef INET
2164 case AF_INET:
2165 *hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
2166 ooa.addr16[0], oa->addr16[0], 0),
2167 ooa.addr16[1], oa->addr16[1], 0);
2168 break;
2169#endif /* INET */
2170#ifdef INET6
2171 case AF_INET6:
2172 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2173 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2174 pf_cksum_fixup(pf_cksum_fixup(*ic,
2175 ooa.addr16[0], oa->addr16[0], u),
2176 ooa.addr16[1], oa->addr16[1], u),
2177 ooa.addr16[2], oa->addr16[2], u),
2178 ooa.addr16[3], oa->addr16[3], u),
2179 ooa.addr16[4], oa->addr16[4], u),
2180 ooa.addr16[5], oa->addr16[5], u),
2181 ooa.addr16[6], oa->addr16[6], u),
2182 ooa.addr16[7], oa->addr16[7], u);
2183 break;
2184#endif /* INET6 */
2185 }
2186 }
2187}
2188
2189
2190/*
2191 * Need to modulate the sequence numbers in the TCP SACK option
2192 * (credits to Krzysztof Pfaff for report and patch)
2193 */
2194static int
2195pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
2196 struct tcphdr *th, struct pf_state_peer *dst)
2197{
2198 int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
2199 u_int8_t opts[TCP_MAXOLEN], *opt = opts;
2200 int copyback = 0, i, olen;
2201 struct sackblk sack;
2202
2203#define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
2204 if (hlen < TCPOLEN_SACKLEN ||
2205 !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
2206 return 0;
2207
2208 while (hlen >= TCPOLEN_SACKLEN) {
2209 olen = opt[1];
2210 switch (*opt) {
2211 case TCPOPT_EOL: /* FALLTHROUGH */
2212 case TCPOPT_NOP:
2213 opt++;
2214 hlen--;
2215 break;
2216 case TCPOPT_SACK:
2217 if (olen > hlen)
2218 olen = hlen;
2219 if (olen >= TCPOLEN_SACKLEN) {
2220 for (i = 2; i + TCPOLEN_SACK <= olen;
2221 i += TCPOLEN_SACK) {
2222 memcpy(&sack, &opt[i], sizeof(sack));
2223 pf_change_a(&sack.start, &th->th_sum,
2224 htonl(ntohl(sack.start) -
2225 dst->seqdiff), 0);
2226 pf_change_a(&sack.end, &th->th_sum,
2227 htonl(ntohl(sack.end) -
2228 dst->seqdiff), 0);
2229 memcpy(&opt[i], &sack, sizeof(sack));
2230 }
2231 copyback = 1;
2232 }
2233 /* FALLTHROUGH */
2234 default:
2235 if (olen < 2)
2236 olen = 2;
2237 hlen -= olen;
2238 opt += olen;
2239 }
2240 }
2241
2242 if (copyback)
2243 m_copyback(m, off + sizeof(*th), thoptlen, (caddr_t)opts);
2244 return (copyback);
2245}
2246
2247static void
2248pf_send_tcp(struct mbuf *replyto, const struct pf_rule *r, sa_family_t af,
2249 const struct pf_addr *saddr, const struct pf_addr *daddr,
2250 u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2251 u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2252 u_int16_t rtag, struct ifnet *ifp)
2253{
2254 struct pf_send_entry *pfse;
2255 struct mbuf *m;
2256 int len, tlen;
2257#ifdef INET
2258 struct ip *h = NULL;
2259#endif /* INET */
2260#ifdef INET6
2261 struct ip6_hdr *h6 = NULL;
2262#endif /* INET6 */
2263 struct tcphdr *th;
2264 char *opt;
2265 struct pf_mtag *pf_mtag;
2266
2267 len = 0;
2268 th = NULL;
2269
2270 /* maximum segment size tcp option */
2271 tlen = sizeof(struct tcphdr);
2272 if (mss)
2273 tlen += 4;
2274
2275 switch (af) {
2276#ifdef INET
2277 case AF_INET:
2278 len = sizeof(struct ip) + tlen;
2279 break;
2280#endif /* INET */
2281#ifdef INET6
2282 case AF_INET6:
2283 len = sizeof(struct ip6_hdr) + tlen;
2284 break;
2285#endif /* INET6 */
2286 default:
2287 panic("%s: unsupported af %d", __func__, af);
2288 }
2289
2290 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2291 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2292 if (pfse == NULL)
2293 return;
2294 m = m_gethdr(M_NOWAIT, MT_DATA);
2295 if (m == NULL) {
2296 free(pfse, M_PFTEMP);
2297 return;
2298 }
2299#ifdef MAC
2300 mac_netinet_firewall_send(m);
2301#endif
2302 if ((pf_mtag = pf_get_mtag(m)) == NULL) {
2303 free(pfse, M_PFTEMP);
2304 m_freem(m);
2305 return;
2306 }
2307 if (tag)
2308 m->m_flags |= M_SKIP_FIREWALL;
2309 pf_mtag->tag = rtag;
2310
2311 if (r != NULL && r->rtableid >= 0)
2312 M_SETFIB(m, r->rtableid);
2313
2314#ifdef ALTQ
2315 if (r != NULL && r->qid) {
2316 pf_mtag->qid = r->qid;
2317
2318 /* add hints for ecn */
2319 pf_mtag->hdr = mtod(m, struct ip *);
2320 }
2321#endif /* ALTQ */
2322 m->m_data += max_linkhdr;
2323 m->m_pkthdr.len = m->m_len = len;
2324 m->m_pkthdr.rcvif = NULL;
2325 bzero(m->m_data, len);
2326 switch (af) {
2327#ifdef INET
2328 case AF_INET:
2329 h = mtod(m, struct ip *);
2330
2331 /* IP header fields included in the TCP checksum */
2332 h->ip_p = IPPROTO_TCP;
2333 h->ip_len = htons(tlen);
2334 h->ip_src.s_addr = saddr->v4.s_addr;
2335 h->ip_dst.s_addr = daddr->v4.s_addr;
2336
2337 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2338 break;
2339#endif /* INET */
2340#ifdef INET6
2341 case AF_INET6:
2342 h6 = mtod(m, struct ip6_hdr *);
2343
2344 /* IP header fields included in the TCP checksum */
2345 h6->ip6_nxt = IPPROTO_TCP;
2346 h6->ip6_plen = htons(tlen);
2347 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2348 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2349
2350 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2351 break;
2352#endif /* INET6 */
2353 }
2354
2355 /* TCP header */
2356 th->th_sport = sport;
2357 th->th_dport = dport;
2358 th->th_seq = htonl(seq);
2359 th->th_ack = htonl(ack);
2360 th->th_off = tlen >> 2;
2361 th->th_flags = flags;
2362 th->th_win = htons(win);
2363
2364 if (mss) {
2365 opt = (char *)(th + 1);
2366 opt[0] = TCPOPT_MAXSEG;
2367 opt[1] = 4;
2368 HTONS(mss);
2369 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
2370 }
2371
2372 switch (af) {
2373#ifdef INET
2374 case AF_INET:
2375 /* TCP checksum */
2376 th->th_sum = in_cksum(m, len);
2377
2378 /* Finish the IP header */
2379 h->ip_v = 4;
2380 h->ip_hl = sizeof(*h) >> 2;
2381 h->ip_tos = IPTOS_LOWDELAY;
2382 h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
2383 h->ip_len = htons(len);
2384 h->ip_ttl = ttl ? ttl : V_ip_defttl;
2385 h->ip_sum = 0;
2386
2387 pfse->pfse_type = PFSE_IP;
2388 break;
2389#endif /* INET */
2390#ifdef INET6
2391 case AF_INET6:
2392 /* TCP checksum */
2393 th->th_sum = in6_cksum(m, IPPROTO_TCP,
2394 sizeof(struct ip6_hdr), tlen);
2395
2396 h6->ip6_vfc |= IPV6_VERSION;
2397 h6->ip6_hlim = IPV6_DEFHLIM;
2398
2399 pfse->pfse_type = PFSE_IP6;
2400 break;
2401#endif /* INET6 */
2402 }
2403 pfse->pfse_m = m;
2404 pf_send(pfse);
2405}
2406
2407static void
2408pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
2409 struct pf_rule *r)
2410{
2411 struct pf_send_entry *pfse;
2412 struct mbuf *m0;
2413 struct pf_mtag *pf_mtag;
2414
2415 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2416 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2417 if (pfse == NULL)
2418 return;
2419
2420 if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
2421 free(pfse, M_PFTEMP);
2422 return;
2423 }
2424
2425 if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
2426 free(pfse, M_PFTEMP);
2427 return;
2428 }
2429 /* XXX: revisit */
2430 m0->m_flags |= M_SKIP_FIREWALL;
2431
2432 if (r->rtableid >= 0)
2433 M_SETFIB(m0, r->rtableid);
2434
2435#ifdef ALTQ
2436 if (r->qid) {
2437 pf_mtag->qid = r->qid;
2438 /* add hints for ecn */
2439 pf_mtag->hdr = mtod(m0, struct ip *);
2440 }
2441#endif /* ALTQ */
2442
2443 switch (af) {
2444#ifdef INET
2445 case AF_INET:
2446 pfse->pfse_type = PFSE_ICMP;
2447 break;
2448#endif /* INET */
2449#ifdef INET6
2450 case AF_INET6:
2451 pfse->pfse_type = PFSE_ICMP6;
2452 break;
2453#endif /* INET6 */
2454 }
2455 pfse->pfse_m = m0;
2456 pfse->pfse_icmp_type = type;
2457 pfse->pfse_icmp_code = code;
2458 pf_send(pfse);
2459}
2460
2461/*
2462 * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
2463 * If n is 0, they match if they are equal. If n is != 0, they match if they
2464 * are different.
2465 */
2466int
2467pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
2468 struct pf_addr *b, sa_family_t af)
2469{
2470 int match = 0;
2471
2472 switch (af) {
2473#ifdef INET
2474 case AF_INET:
2475 if ((a->addr32[0] & m->addr32[0]) ==
2476 (b->addr32[0] & m->addr32[0]))
2477 match++;
2478 break;
2479#endif /* INET */
2480#ifdef INET6
2481 case AF_INET6:
2482 if (((a->addr32[0] & m->addr32[0]) ==
2483 (b->addr32[0] & m->addr32[0])) &&
2484 ((a->addr32[1] & m->addr32[1]) ==
2485 (b->addr32[1] & m->addr32[1])) &&
2486 ((a->addr32[2] & m->addr32[2]) ==
2487 (b->addr32[2] & m->addr32[2])) &&
2488 ((a->addr32[3] & m->addr32[3]) ==
2489 (b->addr32[3] & m->addr32[3])))
2490 match++;
2491 break;
2492#endif /* INET6 */
2493 }
2494 if (match) {
2495 if (n)
2496 return (0);
2497 else
2498 return (1);
2499 } else {
2500 if (n)
2501 return (1);
2502 else
2503 return (0);
2504 }
2505}
2506
2507/*
2508 * Return 1 if b <= a <= e, otherwise return 0.
2509 */
2510int
2511pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
2512 struct pf_addr *a, sa_family_t af)
2513{
2514 switch (af) {
2515#ifdef INET
2516 case AF_INET:
2517 if ((a->addr32[0] < b->addr32[0]) ||
2518 (a->addr32[0] > e->addr32[0]))
2519 return (0);
2520 break;
2521#endif /* INET */
2522#ifdef INET6
2523 case AF_INET6: {
2524 int i;
2525
2526 /* check a >= b */
2527 for (i = 0; i < 4; ++i)
2528 if (a->addr32[i] > b->addr32[i])
2529 break;
2530 else if (a->addr32[i] < b->addr32[i])
2531 return (0);
2532 /* check a <= e */
2533 for (i = 0; i < 4; ++i)
2534 if (a->addr32[i] < e->addr32[i])
2535 break;
2536 else if (a->addr32[i] > e->addr32[i])
2537 return (0);
2538 break;
2539 }
2540#endif /* INET6 */
2541 }
2542 return (1);
2543}
2544
2545static int
2546pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2547{
2548 switch (op) {
2549 case PF_OP_IRG:
2550 return ((p > a1) && (p < a2));
2551 case PF_OP_XRG:
2552 return ((p < a1) || (p > a2));
2553 case PF_OP_RRG:
2554 return ((p >= a1) && (p <= a2));
2555 case PF_OP_EQ:
2556 return (p == a1);
2557 case PF_OP_NE:
2558 return (p != a1);
2559 case PF_OP_LT:
2560 return (p < a1);
2561 case PF_OP_LE:
2562 return (p <= a1);
2563 case PF_OP_GT:
2564 return (p > a1);
2565 case PF_OP_GE:
2566 return (p >= a1);
2567 }
2568 return (0); /* never reached */
2569}
2570
2571int
2572pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2573{
2574 NTOHS(a1);
2575 NTOHS(a2);
2576 NTOHS(p);
2577 return (pf_match(op, a1, a2, p));
2578}
2579
2580static int
2581pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2582{
2583 if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2584 return (0);
2585 return (pf_match(op, a1, a2, u));
2586}
2587
2588static int
2589pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2590{
2591 if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2592 return (0);
2593 return (pf_match(op, a1, a2, g));
2594}
2595
2596int
2597pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag, int mtag)
2598{
2599 if (*tag == -1)
2600 *tag = mtag;
2601
2602 return ((!r->match_tag_not && r->match_tag == *tag) ||
2603 (r->match_tag_not && r->match_tag != *tag));
2604}
2605
2606int
2607pf_tag_packet(struct mbuf *m, struct pf_pdesc *pd, int tag)
2608{
2609
2610 KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
2611
2612 if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(m)) == NULL))
2613 return (ENOMEM);
2614
2615 pd->pf_mtag->tag = tag;
2616
2617 return (0);
2618}
2619
2620#define PF_ANCHOR_STACKSIZE 32
2621struct pf_anchor_stackframe {
2622 struct pf_ruleset *rs;
2623 struct pf_rule *r; /* XXX: + match bit */
2624 struct pf_anchor *child;
2625};
2626
2627/*
2628 * XXX: We rely on malloc(9) returning pointer aligned addresses.
2629 */
2630#define PF_ANCHORSTACK_MATCH 0x00000001
2631#define PF_ANCHORSTACK_MASK (PF_ANCHORSTACK_MATCH)
2632
2633#define PF_ANCHOR_MATCH(f) ((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
2634#define PF_ANCHOR_RULE(f) (struct pf_rule *) \
2635 ((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
2636#define PF_ANCHOR_SET_MATCH(f) do { (f)->r = (void *) \
2637 ((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH); \
2638} while (0)
2639
2640void
2641pf_step_into_anchor(struct pf_anchor_stackframe *stack, int *depth,
2642 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2643 int *match)
2644{
2645 struct pf_anchor_stackframe *f;
2646
2647 PF_RULES_RASSERT();
2648
2649 if (match)
2650 *match = 0;
2651 if (*depth >= PF_ANCHOR_STACKSIZE) {
2652 printf("%s: anchor stack overflow on %s\n",
2653 __func__, (*r)->anchor->name);
2654 *r = TAILQ_NEXT(*r, entries);
2655 return;
2656 } else if (*depth == 0 && a != NULL)
2657 *a = *r;
2658 f = stack + (*depth)++;
2659 f->rs = *rs;
2660 f->r = *r;
2661 if ((*r)->anchor_wildcard) {
2662 struct pf_anchor_node *parent = &(*r)->anchor->children;
2663
2664 if ((f->child = RB_MIN(pf_anchor_node, parent)) == NULL) {
2665 *r = NULL;
2666 return;
2667 }
2668 *rs = &f->child->ruleset;
2669 } else {
2670 f->child = NULL;
2671 *rs = &(*r)->anchor->ruleset;
2672 }
2673 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2674}
2675
2676int
2677pf_step_out_of_anchor(struct pf_anchor_stackframe *stack, int *depth,
2678 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2679 int *match)
2680{
2681 struct pf_anchor_stackframe *f;
2682 struct pf_rule *fr;
2683 int quick = 0;
2684
2685 PF_RULES_RASSERT();
2686
2687 do {
2688 if (*depth <= 0)
2689 break;
2690 f = stack + *depth - 1;
2691 fr = PF_ANCHOR_RULE(f);
2692 if (f->child != NULL) {
2693 struct pf_anchor_node *parent;
2694
2695 /*
2696 * This block traverses through
2697 * a wildcard anchor.
2698 */
2699 parent = &fr->anchor->children;
2700 if (match != NULL && *match) {
2701 /*
2702 * If any of "*" matched, then
2703 * "foo/ *" matched, mark frame
2704 * appropriately.
2705 */
2706 PF_ANCHOR_SET_MATCH(f);
2707 *match = 0;
2708 }
2709 f->child = RB_NEXT(pf_anchor_node, parent, f->child);
2710 if (f->child != NULL) {
2711 *rs = &f->child->ruleset;
2712 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2713 if (*r == NULL)
2714 continue;
2715 else
2716 break;
2717 }
2718 }
2719 (*depth)--;
2720 if (*depth == 0 && a != NULL)
2721 *a = NULL;
2722 *rs = f->rs;
2723 if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
2724 quick = fr->quick;
2725 *r = TAILQ_NEXT(fr, entries);
2726 } while (*r == NULL);
2727
2728 return (quick);
2729}
2730
2731#ifdef INET6
2732void
2733pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2734 struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2735{
2736 switch (af) {
2737#ifdef INET
2738 case AF_INET:
2739 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2740 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2741 break;
2742#endif /* INET */
2743 case AF_INET6:
2744 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2745 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2746 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2747 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2748 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2749 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2750 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2751 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2752 break;
2753 }
2754}
2755
2756void
2757pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2758{
2759 switch (af) {
2760#ifdef INET
2761 case AF_INET:
2762 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2763 break;
2764#endif /* INET */
2765 case AF_INET6:
2766 if (addr->addr32[3] == 0xffffffff) {
2767 addr->addr32[3] = 0;
2768 if (addr->addr32[2] == 0xffffffff) {
2769 addr->addr32[2] = 0;
2770 if (addr->addr32[1] == 0xffffffff) {
2771 addr->addr32[1] = 0;
2772 addr->addr32[0] =
2773 htonl(ntohl(addr->addr32[0]) + 1);
2774 } else
2775 addr->addr32[1] =
2776 htonl(ntohl(addr->addr32[1]) + 1);
2777 } else
2778 addr->addr32[2] =
2779 htonl(ntohl(addr->addr32[2]) + 1);
2780 } else
2781 addr->addr32[3] =
2782 htonl(ntohl(addr->addr32[3]) + 1);
2783 break;
2784 }
2785}
2786#endif /* INET6 */
2787
2788int
2789pf_socket_lookup(int direction, struct pf_pdesc *pd, struct mbuf *m)
2790{
2791 struct pf_addr *saddr, *daddr;
2792 u_int16_t sport, dport;
2793 struct inpcbinfo *pi;
2794 struct inpcb *inp;
2795
2796 pd->lookup.uid = UID_MAX;
2797 pd->lookup.gid = GID_MAX;
2798
2799 switch (pd->proto) {
2800 case IPPROTO_TCP:
2801 if (pd->hdr.tcp == NULL)
2802 return (-1);
2803 sport = pd->hdr.tcp->th_sport;
2804 dport = pd->hdr.tcp->th_dport;
2805 pi = &V_tcbinfo;
2806 break;
2807 case IPPROTO_UDP:
2808 if (pd->hdr.udp == NULL)
2809 return (-1);
2810 sport = pd->hdr.udp->uh_sport;
2811 dport = pd->hdr.udp->uh_dport;
2812 pi = &V_udbinfo;
2813 break;
2814 default:
2815 return (-1);
2816 }
2817 if (direction == PF_IN) {
2818 saddr = pd->src;
2819 daddr = pd->dst;
2820 } else {
2821 u_int16_t p;
2822
2823 p = sport;
2824 sport = dport;
2825 dport = p;
2826 saddr = pd->dst;
2827 daddr = pd->src;
2828 }
2829 switch (pd->af) {
2830#ifdef INET
2831 case AF_INET:
2832 inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
2833 dport, INPLOOKUP_RLOCKPCB, NULL, m);
2834 if (inp == NULL) {
2835 inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
2836 daddr->v4, dport, INPLOOKUP_WILDCARD |
2837 INPLOOKUP_RLOCKPCB, NULL, m);
2838 if (inp == NULL)
2839 return (-1);
2840 }
2841 break;
2842#endif /* INET */
2843#ifdef INET6
2844 case AF_INET6:
2845 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
2846 dport, INPLOOKUP_RLOCKPCB, NULL, m);
2847 if (inp == NULL) {
2848 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
2849 &daddr->v6, dport, INPLOOKUP_WILDCARD |
2850 INPLOOKUP_RLOCKPCB, NULL, m);
2851 if (inp == NULL)
2852 return (-1);
2853 }
2854 break;
2855#endif /* INET6 */
2856
2857 default:
2858 return (-1);
2859 }
2860 INP_RLOCK_ASSERT(inp);
2861 pd->lookup.uid = inp->inp_cred->cr_uid;
2862 pd->lookup.gid = inp->inp_cred->cr_groups[0];
2863 INP_RUNLOCK(inp);
2864
2865 return (1);
2866}
2867
2868static u_int8_t
2869pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2870{
2871 int hlen;
2872 u_int8_t hdr[60];
2873 u_int8_t *opt, optlen;
2874 u_int8_t wscale = 0;
2875
2876 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
2877 if (hlen <= sizeof(struct tcphdr))
2878 return (0);
2879 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2880 return (0);
2881 opt = hdr + sizeof(struct tcphdr);
2882 hlen -= sizeof(struct tcphdr);
2883 while (hlen >= 3) {
2884 switch (*opt) {
2885 case TCPOPT_EOL:
2886 case TCPOPT_NOP:
2887 ++opt;
2888 --hlen;
2889 break;
2890 case TCPOPT_WINDOW:
2891 wscale = opt[2];
2892 if (wscale > TCP_MAX_WINSHIFT)
2893 wscale = TCP_MAX_WINSHIFT;
2894 wscale |= PF_WSCALE_FLAG;
2895 /* FALLTHROUGH */
2896 default:
2897 optlen = opt[1];
2898 if (optlen < 2)
2899 optlen = 2;
2900 hlen -= optlen;
2901 opt += optlen;
2902 break;
2903 }
2904 }
2905 return (wscale);
2906}
2907
2908static u_int16_t
2909pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2910{
2911 int hlen;
2912 u_int8_t hdr[60];
2913 u_int8_t *opt, optlen;
2914 u_int16_t mss = V_tcp_mssdflt;
2915
2916 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
2917 if (hlen <= sizeof(struct tcphdr))
2918 return (0);
2919 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2920 return (0);
2921 opt = hdr + sizeof(struct tcphdr);
2922 hlen -= sizeof(struct tcphdr);
2923 while (hlen >= TCPOLEN_MAXSEG) {
2924 switch (*opt) {
2925 case TCPOPT_EOL:
2926 case TCPOPT_NOP:
2927 ++opt;
2928 --hlen;
2929 break;
2930 case TCPOPT_MAXSEG:
2931 bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
2932 NTOHS(mss);
2933 /* FALLTHROUGH */
2934 default:
2935 optlen = opt[1];
2936 if (optlen < 2)
2937 optlen = 2;
2938 hlen -= optlen;
2939 opt += optlen;
2940 break;
2941 }
2942 }
2943 return (mss);
2944}
2945
2946static u_int16_t
2947pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
2948{
2949#ifdef INET
2950 struct sockaddr_in *dst;
2951 struct route ro;
2952#endif /* INET */
2953#ifdef INET6
2954 struct sockaddr_in6 *dst6;
2955 struct route_in6 ro6;
2956#endif /* INET6 */
2957 struct rtentry *rt = NULL;
2958 int hlen = 0;
2959 u_int16_t mss = V_tcp_mssdflt;
2960
2961 switch (af) {
2962#ifdef INET
2963 case AF_INET:
2964 hlen = sizeof(struct ip);
2965 bzero(&ro, sizeof(ro));
2966 dst = (struct sockaddr_in *)&ro.ro_dst;
2967 dst->sin_family = AF_INET;
2968 dst->sin_len = sizeof(*dst);
2969 dst->sin_addr = addr->v4;
2970 in_rtalloc_ign(&ro, 0, rtableid);
2971 rt = ro.ro_rt;
2972 break;
2973#endif /* INET */
2974#ifdef INET6
2975 case AF_INET6:
2976 hlen = sizeof(struct ip6_hdr);
2977 bzero(&ro6, sizeof(ro6));
2978 dst6 = (struct sockaddr_in6 *)&ro6.ro_dst;
2979 dst6->sin6_family = AF_INET6;
2980 dst6->sin6_len = sizeof(*dst6);
2981 dst6->sin6_addr = addr->v6;
2982 in6_rtalloc_ign(&ro6, 0, rtableid);
2983 rt = ro6.ro_rt;
2984 break;
2985#endif /* INET6 */
2986 }
2987
2988 if (rt && rt->rt_ifp) {
2989 mss = rt->rt_ifp->if_mtu - hlen - sizeof(struct tcphdr);
2990 mss = max(V_tcp_mssdflt, mss);
2991 RTFREE(rt);
2992 }
2993 mss = min(mss, offer);
2994 mss = max(mss, 64); /* sanity - at least max opt space */
2995 return (mss);
2996}
2997
2998static u_int32_t
2999pf_tcp_iss(struct pf_pdesc *pd)
3000{
3001 MD5_CTX ctx;
3002 u_int32_t digest[4];
3003
3004 if (V_pf_tcp_secret_init == 0) {
3005 read_random(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
3006 MD5Init(&V_pf_tcp_secret_ctx);
3007 MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
3008 sizeof(V_pf_tcp_secret));
3009 V_pf_tcp_secret_init = 1;
3010 }
3011
3012 ctx = V_pf_tcp_secret_ctx;
3013
3014 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
3015 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
3016 if (pd->af == AF_INET6) {
3017 MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
3018 MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
3019 } else {
3020 MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
3021 MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
3022 }
3023 MD5Final((u_char *)digest, &ctx);
3024 V_pf_tcp_iss_off += 4096;
3025#define ISN_RANDOM_INCREMENT (4096 - 1)
3026 return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
3027 V_pf_tcp_iss_off);
3028#undef ISN_RANDOM_INCREMENT
3029}
3030
3031static int
3032pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
3033 struct pfi_kif *kif, struct mbuf *m, int off, struct pf_pdesc *pd,
3034 struct pf_rule **am, struct pf_ruleset **rsm, struct inpcb *inp)
3035{
3036 struct pf_rule *nr = NULL;
3037 struct pf_addr * const saddr = pd->src;
3038 struct pf_addr * const daddr = pd->dst;
3039 sa_family_t af = pd->af;
3040 struct pf_rule *r, *a = NULL;
3041 struct pf_ruleset *ruleset = NULL;
3042 struct pf_src_node *nsn = NULL;
3043 struct tcphdr *th = pd->hdr.tcp;
3044 struct pf_state_key *sk = NULL, *nk = NULL;
3045 u_short reason;
3046 int rewrite = 0, hdrlen = 0;
3047 int tag = -1, rtableid = -1;
3048 int asd = 0;
3049 int match = 0;
3050 int state_icmp = 0;
3051 u_int16_t sport = 0, dport = 0;
3052 u_int16_t bproto_sum = 0, bip_sum = 0;
3053 u_int8_t icmptype = 0, icmpcode = 0;
3054 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3055
3056 PF_RULES_RASSERT();
3057
3058 if (inp != NULL) {
3059 INP_LOCK_ASSERT(inp);
3060 pd->lookup.uid = inp->inp_cred->cr_uid;
3061 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3062 pd->lookup.done = 1;
3063 }
3064
3065 switch (pd->proto) {
3066 case IPPROTO_TCP:
3067 sport = th->th_sport;
3068 dport = th->th_dport;
3069 hdrlen = sizeof(*th);
3070 break;
3071 case IPPROTO_UDP:
3072 sport = pd->hdr.udp->uh_sport;
3073 dport = pd->hdr.udp->uh_dport;
3074 hdrlen = sizeof(*pd->hdr.udp);
3075 break;
3076#ifdef INET
3077 case IPPROTO_ICMP:
3078 if (pd->af != AF_INET)
3079 break;
3080 sport = dport = pd->hdr.icmp->icmp_id;
3081 hdrlen = sizeof(*pd->hdr.icmp);
3082 icmptype = pd->hdr.icmp->icmp_type;
3083 icmpcode = pd->hdr.icmp->icmp_code;
3084
3085 if (icmptype == ICMP_UNREACH ||
3086 icmptype == ICMP_SOURCEQUENCH ||
3087 icmptype == ICMP_REDIRECT ||
3088 icmptype == ICMP_TIMXCEED ||
3089 icmptype == ICMP_PARAMPROB)
3090 state_icmp++;
3091 break;
3092#endif /* INET */
3093#ifdef INET6
3094 case IPPROTO_ICMPV6:
3095 if (af != AF_INET6)
3096 break;
3097 sport = dport = pd->hdr.icmp6->icmp6_id;
3098 hdrlen = sizeof(*pd->hdr.icmp6);
3099 icmptype = pd->hdr.icmp6->icmp6_type;
3100 icmpcode = pd->hdr.icmp6->icmp6_code;
3101
3102 if (icmptype == ICMP6_DST_UNREACH ||
3103 icmptype == ICMP6_PACKET_TOO_BIG ||
3104 icmptype == ICMP6_TIME_EXCEEDED ||
3105 icmptype == ICMP6_PARAM_PROB)
3106 state_icmp++;
3107 break;
3108#endif /* INET6 */
3109 default:
3110 sport = dport = hdrlen = 0;
3111 break;
3112 }
3113
3114 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3115
3116 /* check packet for BINAT/NAT/RDR */
3117 if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn, &sk,
3118 &nk, saddr, daddr, sport, dport, anchor_stack)) != NULL) {
3119 KASSERT(sk != NULL, ("%s: null sk", __func__));
3120 KASSERT(nk != NULL, ("%s: null nk", __func__));
3121
3122 if (pd->ip_sum)
3123 bip_sum = *pd->ip_sum;
3124
3125 switch (pd->proto) {
3126 case IPPROTO_TCP:
3127 bproto_sum = th->th_sum;
3128 pd->proto_sum = &th->th_sum;
3129
3130 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3131 nk->port[pd->sidx] != sport) {
3132 pf_change_ap(saddr, &th->th_sport, pd->ip_sum,
3133 &th->th_sum, &nk->addr[pd->sidx],
3134 nk->port[pd->sidx], 0, af);
3135 pd->sport = &th->th_sport;
3136 sport = th->th_sport;
3137 }
3138
3139 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3140 nk->port[pd->didx] != dport) {
3141 pf_change_ap(daddr, &th->th_dport, pd->ip_sum,
3142 &th->th_sum, &nk->addr[pd->didx],
3143 nk->port[pd->didx], 0, af);
3144 dport = th->th_dport;
3145 pd->dport = &th->th_dport;
3146 }
3147 rewrite++;
3148 break;
3149 case IPPROTO_UDP:
3150 bproto_sum = pd->hdr.udp->uh_sum;
3151 pd->proto_sum = &pd->hdr.udp->uh_sum;
3152
3153 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3154 nk->port[pd->sidx] != sport) {
3155 pf_change_ap(saddr, &pd->hdr.udp->uh_sport,
3156 pd->ip_sum, &pd->hdr.udp->uh_sum,
3157 &nk->addr[pd->sidx],
3158 nk->port[pd->sidx], 1, af);
3159 sport = pd->hdr.udp->uh_sport;
3160 pd->sport = &pd->hdr.udp->uh_sport;
3161 }
3162
3163 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3164 nk->port[pd->didx] != dport) {
3165 pf_change_ap(daddr, &pd->hdr.udp->uh_dport,
3166 pd->ip_sum, &pd->hdr.udp->uh_sum,
3167 &nk->addr[pd->didx],
3168 nk->port[pd->didx], 1, af);
3169 dport = pd->hdr.udp->uh_dport;
3170 pd->dport = &pd->hdr.udp->uh_dport;
3171 }
3172 rewrite++;
3173 break;
3174#ifdef INET
3175 case IPPROTO_ICMP:
3176 nk->port[0] = nk->port[1];
3177 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3178 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3179 nk->addr[pd->sidx].v4.s_addr, 0);
3180
3181 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3182 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3183 nk->addr[pd->didx].v4.s_addr, 0);
3184
3185 if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3186 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3187 pd->hdr.icmp->icmp_cksum, sport,
3188 nk->port[1], 0);
3189 pd->hdr.icmp->icmp_id = nk->port[1];
3190 pd->sport = &pd->hdr.icmp->icmp_id;
3191 }
3192 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3193 break;
3194#endif /* INET */
3195#ifdef INET6
3196 case IPPROTO_ICMPV6:
3197 nk->port[0] = nk->port[1];
3198 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3199 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3200 &nk->addr[pd->sidx], 0);
3201
3202 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3203 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3204 &nk->addr[pd->didx], 0);
3205 rewrite++;
3206 break;
3207#endif /* INET */
3208 default:
3209 switch (af) {
3210#ifdef INET
3211 case AF_INET:
3212 if (PF_ANEQ(saddr,
3213 &nk->addr[pd->sidx], AF_INET))
3214 pf_change_a(&saddr->v4.s_addr,
3215 pd->ip_sum,
3216 nk->addr[pd->sidx].v4.s_addr, 0);
3217
3218 if (PF_ANEQ(daddr,
3219 &nk->addr[pd->didx], AF_INET))
3220 pf_change_a(&daddr->v4.s_addr,
3221 pd->ip_sum,
3222 nk->addr[pd->didx].v4.s_addr, 0);
3223 break;
3224#endif /* INET */
3225#ifdef INET6
3226 case AF_INET6:
3227 if (PF_ANEQ(saddr,
3228 &nk->addr[pd->sidx], AF_INET6))
3229 PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3230
3231 if (PF_ANEQ(daddr,
3232 &nk->addr[pd->didx], AF_INET6))
3233 PF_ACPY(saddr, &nk->addr[pd->didx], af);
3234 break;
3235#endif /* INET */
3236 }
3237 break;
3238 }
3239 if (nr->natpass)
3240 r = NULL;
3241 pd->nat_rule = nr;
3242 }
3243
3244 while (r != NULL) {
3245 r->evaluations++;
3246 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3247 r = r->skip[PF_SKIP_IFP].ptr;
3248 else if (r->direction && r->direction != direction)
3249 r = r->skip[PF_SKIP_DIR].ptr;
3250 else if (r->af && r->af != af)
3251 r = r->skip[PF_SKIP_AF].ptr;
3252 else if (r->proto && r->proto != pd->proto)
3253 r = r->skip[PF_SKIP_PROTO].ptr;
3254 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3255 r->src.neg, kif, M_GETFIB(m)))
3256 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3257 /* tcp/udp only. port_op always 0 in other cases */
3258 else if (r->src.port_op && !pf_match_port(r->src.port_op,
3259 r->src.port[0], r->src.port[1], sport))
3260 r = r->skip[PF_SKIP_SRC_PORT].ptr;
3261 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3262 r->dst.neg, NULL, M_GETFIB(m)))
3263 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3264 /* tcp/udp only. port_op always 0 in other cases */
3265 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3266 r->dst.port[0], r->dst.port[1], dport))
3267 r = r->skip[PF_SKIP_DST_PORT].ptr;
3268 /* icmp only. type always 0 in other cases */
3269 else if (r->type && r->type != icmptype + 1)
3270 r = TAILQ_NEXT(r, entries);
3271 /* icmp only. type always 0 in other cases */
3272 else if (r->code && r->code != icmpcode + 1)
3273 r = TAILQ_NEXT(r, entries);
3274 else if (r->tos && !(r->tos == pd->tos))
3275 r = TAILQ_NEXT(r, entries);
3276 else if (r->rule_flag & PFRULE_FRAGMENT)
3277 r = TAILQ_NEXT(r, entries);
3278 else if (pd->proto == IPPROTO_TCP &&
3279 (r->flagset & th->th_flags) != r->flags)
3280 r = TAILQ_NEXT(r, entries);
3281 /* tcp/udp only. uid.op always 0 in other cases */
3282 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3283 pf_socket_lookup(direction, pd, m), 1)) &&
3284 !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3285 pd->lookup.uid))
3286 r = TAILQ_NEXT(r, entries);
3287 /* tcp/udp only. gid.op always 0 in other cases */
3288 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3289 pf_socket_lookup(direction, pd, m), 1)) &&
3290 !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3291 pd->lookup.gid))
3292 r = TAILQ_NEXT(r, entries);
3293 else if (r->prob &&
3294 r->prob <= arc4random())
3295 r = TAILQ_NEXT(r, entries);
3296 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3297 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3298 r = TAILQ_NEXT(r, entries);
3299 else if (r->os_fingerprint != PF_OSFP_ANY &&
3300 (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3301 pf_osfp_fingerprint(pd, m, off, th),
3302 r->os_fingerprint)))
3303 r = TAILQ_NEXT(r, entries);
3304 else {
3305 if (r->tag)
3306 tag = r->tag;
3307 if (r->rtableid >= 0)
3308 rtableid = r->rtableid;
3309 if (r->anchor == NULL) {
3310 match = 1;
3311 *rm = r;
3312 *am = a;
3313 *rsm = ruleset;
3314 if ((*rm)->quick)
3315 break;
3316 r = TAILQ_NEXT(r, entries);
3317 } else
3318 pf_step_into_anchor(anchor_stack, &asd,
3319 &ruleset, PF_RULESET_FILTER, &r, &a,
3320 &match);
3321 }
3322 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3323 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3324 break;
3325 }
3326 r = *rm;
3327 a = *am;
3328 ruleset = *rsm;
3329
3330 REASON_SET(&reason, PFRES_MATCH);
3331
3332 if (r->log || (nr != NULL && nr->log)) {
3333 if (rewrite)
3334 m_copyback(m, off, hdrlen, pd->hdr.any);
3335 PFLOG_PACKET(kif, m, af, direction, reason, r->log ? r : nr, a,
3336 ruleset, pd, 1);
3337 }
3338
3339 if ((r->action == PF_DROP) &&
3340 ((r->rule_flag & PFRULE_RETURNRST) ||
3341 (r->rule_flag & PFRULE_RETURNICMP) ||
3342 (r->rule_flag & PFRULE_RETURN))) {
3343 /* undo NAT changes, if they have taken place */
3344 if (nr != NULL) {
3345 PF_ACPY(saddr, &sk->addr[pd->sidx], af);
3346 PF_ACPY(daddr, &sk->addr[pd->didx], af);
3347 if (pd->sport)
3348 *pd->sport = sk->port[pd->sidx];
3349 if (pd->dport)
3350 *pd->dport = sk->port[pd->didx];
3351 if (pd->proto_sum)
3352 *pd->proto_sum = bproto_sum;
3353 if (pd->ip_sum)
3354 *pd->ip_sum = bip_sum;
3355 m_copyback(m, off, hdrlen, pd->hdr.any);
3356 }
3357 if (pd->proto == IPPROTO_TCP &&
3358 ((r->rule_flag & PFRULE_RETURNRST) ||
3359 (r->rule_flag & PFRULE_RETURN)) &&
3360 !(th->th_flags & TH_RST)) {
3361 u_int32_t ack = ntohl(th->th_seq) + pd->p_len;
3362 int len = 0;
3363#ifdef INET
3364 struct ip *h4;
3365#endif
3366#ifdef INET6
3367 struct ip6_hdr *h6;
3368#endif
3369
3370 switch (af) {
3371#ifdef INET
3372 case AF_INET:
3373 h4 = mtod(m, struct ip *);
3374 len = ntohs(h4->ip_len) - off;
3375 break;
3376#endif
3377#ifdef INET6
3378 case AF_INET6:
3379 h6 = mtod(m, struct ip6_hdr *);
3380 len = ntohs(h6->ip6_plen) - (off - sizeof(*h6));
3381 break;
3382#endif
3383 }
3384
3385 if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
3386 REASON_SET(&reason, PFRES_PROTCKSUM);
3387 else {
3388 if (th->th_flags & TH_SYN)
3389 ack++;
3390 if (th->th_flags & TH_FIN)
3391 ack++;
3392 pf_send_tcp(m, r, af, pd->dst,
3393 pd->src, th->th_dport, th->th_sport,
3394 ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
3395 r->return_ttl, 1, 0, kif->pfik_ifp);
3396 }
3397 } else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
3398 r->return_icmp)
3399 pf_send_icmp(m, r->return_icmp >> 8,
3400 r->return_icmp & 255, af, r);
3401 else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
3402 r->return_icmp6)
3403 pf_send_icmp(m, r->return_icmp6 >> 8,
3404 r->return_icmp6 & 255, af, r);
3405 }
3406
3407 if (r->action == PF_DROP)
3408 goto cleanup;
3409
3410 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3411 REASON_SET(&reason, PFRES_MEMORY);
3412 goto cleanup;
3413 }
3414 if (rtableid >= 0)
3415 M_SETFIB(m, rtableid);
3416
3417 if (!state_icmp && (r->keep_state || nr != NULL ||
3418 (pd->flags & PFDESC_TCP_NORM))) {
3419 int action;
3420 action = pf_create_state(r, nr, a, pd, nsn, nk, sk, m, off,
3421 sport, dport, &rewrite, kif, sm, tag, bproto_sum, bip_sum,
3422 hdrlen);
3423 if (action != PF_PASS)
3424 return (action);
3425 } else {
3426 if (sk != NULL)
3427 uma_zfree(V_pf_state_key_z, sk);
3428 if (nk != NULL)
3429 uma_zfree(V_pf_state_key_z, nk);
3430 }
3431
3432 /* copy back packet headers if we performed NAT operations */
3433 if (rewrite)
3434 m_copyback(m, off, hdrlen, pd->hdr.any);
3435
3436 if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
3437 direction == PF_OUT &&
3438 pfsync_defer_ptr != NULL && pfsync_defer_ptr(*sm, m))
3439 /*
3440 * We want the state created, but we dont
3441 * want to send this in case a partner
3442 * firewall has to know about it to allow
3443 * replies through it.
3444 */
3445 return (PF_DEFER);
3446
3447 return (PF_PASS);
3448
3449cleanup:
3450 if (sk != NULL)
3451 uma_zfree(V_pf_state_key_z, sk);
3452 if (nk != NULL)
3453 uma_zfree(V_pf_state_key_z, nk);
3454 return (PF_DROP);
3455}
3456
3457static int
3458pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3459 struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *nk,
3460 struct pf_state_key *sk, struct mbuf *m, int off, u_int16_t sport,
3461 u_int16_t dport, int *rewrite, struct pfi_kif *kif, struct pf_state **sm,
3462 int tag, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen)
3463{
3464 struct pf_state *s = NULL;
3465 struct pf_src_node *sn = NULL;
3466 struct tcphdr *th = pd->hdr.tcp;
3467 u_int16_t mss = V_tcp_mssdflt;
3468 u_short reason;
3469
3470 /* check maximums */
3471 if (r->max_states &&
3472 (counter_u64_fetch(r->states_cur) >= r->max_states)) {
3473 counter_u64_add(V_pf_status.lcounters[LCNT_STATES], 1);
3474 REASON_SET(&reason, PFRES_MAXSTATES);
3475 return (PF_DROP);
3476 }
3477 /* src node for filter rule */
3478 if ((r->rule_flag & PFRULE_SRCTRACK ||
3479 r->rpool.opts & PF_POOL_STICKYADDR) &&
3480 pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3481 REASON_SET(&reason, PFRES_SRCLIMIT);
3482 goto csfailed;
3483 }
3484 /* src node for translation rule */
3485 if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3486 pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3487 REASON_SET(&reason, PFRES_SRCLIMIT);
3488 goto csfailed;
3489 }
3490 s = uma_zalloc(V_pf_state_z, M_NOWAIT | M_ZERO);
3491 if (s == NULL) {
3492 REASON_SET(&reason, PFRES_MEMORY);
3493 goto csfailed;
3494 }
3495 s->rule.ptr = r;
3496 s->nat_rule.ptr = nr;
3497 s->anchor.ptr = a;
3498 STATE_INC_COUNTERS(s);
3499 if (r->allow_opts)
3500 s->state_flags |= PFSTATE_ALLOWOPTS;
3501 if (r->rule_flag & PFRULE_STATESLOPPY)
3502 s->state_flags |= PFSTATE_SLOPPY;
3503 s->log = r->log & PF_LOG_ALL;
3504 s->sync_state = PFSYNC_S_NONE;
3505 if (nr != NULL)
3506 s->log |= nr->log & PF_LOG_ALL;
3507 switch (pd->proto) {
3508 case IPPROTO_TCP:
3509 s->src.seqlo = ntohl(th->th_seq);
3510 s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3511 if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3512 r->keep_state == PF_STATE_MODULATE) {
3513 /* Generate sequence number modulator */
3514 if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3515 0)
3516 s->src.seqdiff = 1;
3517 pf_change_a(&th->th_seq, &th->th_sum,
3518 htonl(s->src.seqlo + s->src.seqdiff), 0);
3519 *rewrite = 1;
3520 } else
3521 s->src.seqdiff = 0;
3522 if (th->th_flags & TH_SYN) {
3523 s->src.seqhi++;
3524 s->src.wscale = pf_get_wscale(m, off,
3525 th->th_off, pd->af);
3526 }
3527 s->src.max_win = MAX(ntohs(th->th_win), 1);
3528 if (s->src.wscale & PF_WSCALE_MASK) {
3529 /* Remove scale factor from initial window */
3530 int win = s->src.max_win;
3531 win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3532 s->src.max_win = (win - 1) >>
3533 (s->src.wscale & PF_WSCALE_MASK);
3534 }
3535 if (th->th_flags & TH_FIN)
3536 s->src.seqhi++;
3537 s->dst.seqhi = 1;
3538 s->dst.max_win = 1;
3539 s->src.state = TCPS_SYN_SENT;
3540 s->dst.state = TCPS_CLOSED;
3541 s->timeout = PFTM_TCP_FIRST_PACKET;
3542 break;
3543 case IPPROTO_UDP:
3544 s->src.state = PFUDPS_SINGLE;
3545 s->dst.state = PFUDPS_NO_TRAFFIC;
3546 s->timeout = PFTM_UDP_FIRST_PACKET;
3547 break;
3548 case IPPROTO_ICMP:
3549#ifdef INET6
3550 case IPPROTO_ICMPV6:
3551#endif
3552 s->timeout = PFTM_ICMP_FIRST_PACKET;
3553 break;
3554 default:
3555 s->src.state = PFOTHERS_SINGLE;
3556 s->dst.state = PFOTHERS_NO_TRAFFIC;
3557 s->timeout = PFTM_OTHER_FIRST_PACKET;
3558 }
3559
3560 if (r->rt && r->rt != PF_FASTROUTE) {
3561 if (pf_map_addr(pd->af, r, pd->src, &s->rt_addr, NULL, &sn)) {
3562 REASON_SET(&reason, PFRES_BADSTATE);
3563 pf_src_tree_remove_state(s);
3564 STATE_DEC_COUNTERS(s);
3565 uma_zfree(V_pf_state_z, s);
3566 goto csfailed;
3567 }
3568 s->rt_kif = r->rpool.cur->kif;
3569 }
3570
3571 s->creation = time_uptime;
3572 s->expire = time_uptime;
3573
1575 }
1576 s->src_node = s->nat_src_node = NULL;
1577}
1578
1579/*
1580 * Unlink and potentilly free a state. Function may be
1581 * called with ID hash row locked, but always returns
1582 * unlocked, since it needs to go through key hash locking.
1583 */
1584int
1585pf_unlink_state(struct pf_state *s, u_int flags)
1586{
1587 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(s)];
1588
1589 if ((flags & PF_ENTER_LOCKED) == 0)
1590 PF_HASHROW_LOCK(ih);
1591 else
1592 PF_HASHROW_ASSERT(ih);
1593
1594 if (s->timeout == PFTM_UNLINKED) {
1595 /*
1596 * State is being processed
1597 * by pf_unlink_state() in
1598 * an other thread.
1599 */
1600 PF_HASHROW_UNLOCK(ih);
1601 return (0); /* XXXGL: undefined actually */
1602 }
1603
1604 if (s->src.state == PF_TCPS_PROXY_DST) {
1605 /* XXX wire key the right one? */
1606 pf_send_tcp(NULL, s->rule.ptr, s->key[PF_SK_WIRE]->af,
1607 &s->key[PF_SK_WIRE]->addr[1],
1608 &s->key[PF_SK_WIRE]->addr[0],
1609 s->key[PF_SK_WIRE]->port[1],
1610 s->key[PF_SK_WIRE]->port[0],
1611 s->src.seqhi, s->src.seqlo + 1,
1612 TH_RST|TH_ACK, 0, 0, 0, 1, s->tag, NULL);
1613 }
1614
1615 LIST_REMOVE(s, entry);
1616 pf_src_tree_remove_state(s);
1617
1618 if (pfsync_delete_state_ptr != NULL)
1619 pfsync_delete_state_ptr(s);
1620
1621 STATE_DEC_COUNTERS(s);
1622
1623 s->timeout = PFTM_UNLINKED;
1624
1625 PF_HASHROW_UNLOCK(ih);
1626
1627 pf_detach_state(s);
1628 refcount_release(&s->refs);
1629
1630 return (pf_release_state(s));
1631}
1632
1633void
1634pf_free_state(struct pf_state *cur)
1635{
1636
1637 KASSERT(cur->refs == 0, ("%s: %p has refs", __func__, cur));
1638 KASSERT(cur->timeout == PFTM_UNLINKED, ("%s: timeout %u", __func__,
1639 cur->timeout));
1640
1641 pf_normalize_tcp_cleanup(cur);
1642 uma_zfree(V_pf_state_z, cur);
1643 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_REMOVALS], 1);
1644}
1645
1646/*
1647 * Called only from pf_purge_thread(), thus serialized.
1648 */
1649static u_int
1650pf_purge_expired_states(u_int i, int maxcheck)
1651{
1652 struct pf_idhash *ih;
1653 struct pf_state *s;
1654
1655 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1656
1657 /*
1658 * Go through hash and unlink states that expire now.
1659 */
1660 while (maxcheck > 0) {
1661
1662 ih = &V_pf_idhash[i];
1663relock:
1664 PF_HASHROW_LOCK(ih);
1665 LIST_FOREACH(s, &ih->states, entry) {
1666 if (pf_state_expires(s) <= time_uptime) {
1667 V_pf_status.states -=
1668 pf_unlink_state(s, PF_ENTER_LOCKED);
1669 goto relock;
1670 }
1671 s->rule.ptr->rule_flag |= PFRULE_REFS;
1672 if (s->nat_rule.ptr != NULL)
1673 s->nat_rule.ptr->rule_flag |= PFRULE_REFS;
1674 if (s->anchor.ptr != NULL)
1675 s->anchor.ptr->rule_flag |= PFRULE_REFS;
1676 s->kif->pfik_flags |= PFI_IFLAG_REFS;
1677 if (s->rt_kif)
1678 s->rt_kif->pfik_flags |= PFI_IFLAG_REFS;
1679 }
1680 PF_HASHROW_UNLOCK(ih);
1681
1682 /* Return when we hit end of hash. */
1683 if (++i > pf_hashmask) {
1684 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1685 return (0);
1686 }
1687
1688 maxcheck--;
1689 }
1690
1691 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1692
1693 return (i);
1694}
1695
1696static void
1697pf_purge_unlinked_rules()
1698{
1699 struct pf_rulequeue tmpq;
1700 struct pf_rule *r, *r1;
1701
1702 /*
1703 * If we have overloading task pending, then we'd
1704 * better skip purging this time. There is a tiny
1705 * probability that overloading task references
1706 * an already unlinked rule.
1707 */
1708 PF_OVERLOADQ_LOCK();
1709 if (!SLIST_EMPTY(&V_pf_overloadqueue)) {
1710 PF_OVERLOADQ_UNLOCK();
1711 return;
1712 }
1713 PF_OVERLOADQ_UNLOCK();
1714
1715 /*
1716 * Do naive mark-and-sweep garbage collecting of old rules.
1717 * Reference flag is raised by pf_purge_expired_states()
1718 * and pf_purge_expired_src_nodes().
1719 *
1720 * To avoid LOR between PF_UNLNKDRULES_LOCK/PF_RULES_WLOCK,
1721 * use a temporary queue.
1722 */
1723 TAILQ_INIT(&tmpq);
1724 PF_UNLNKDRULES_LOCK();
1725 TAILQ_FOREACH_SAFE(r, &V_pf_unlinked_rules, entries, r1) {
1726 if (!(r->rule_flag & PFRULE_REFS)) {
1727 TAILQ_REMOVE(&V_pf_unlinked_rules, r, entries);
1728 TAILQ_INSERT_TAIL(&tmpq, r, entries);
1729 } else
1730 r->rule_flag &= ~PFRULE_REFS;
1731 }
1732 PF_UNLNKDRULES_UNLOCK();
1733
1734 if (!TAILQ_EMPTY(&tmpq)) {
1735 PF_RULES_WLOCK();
1736 TAILQ_FOREACH_SAFE(r, &tmpq, entries, r1) {
1737 TAILQ_REMOVE(&tmpq, r, entries);
1738 pf_free_rule(r);
1739 }
1740 PF_RULES_WUNLOCK();
1741 }
1742}
1743
1744void
1745pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1746{
1747 switch (af) {
1748#ifdef INET
1749 case AF_INET: {
1750 u_int32_t a = ntohl(addr->addr32[0]);
1751 printf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1752 (a>>8)&255, a&255);
1753 if (p) {
1754 p = ntohs(p);
1755 printf(":%u", p);
1756 }
1757 break;
1758 }
1759#endif /* INET */
1760#ifdef INET6
1761 case AF_INET6: {
1762 u_int16_t b;
1763 u_int8_t i, curstart, curend, maxstart, maxend;
1764 curstart = curend = maxstart = maxend = 255;
1765 for (i = 0; i < 8; i++) {
1766 if (!addr->addr16[i]) {
1767 if (curstart == 255)
1768 curstart = i;
1769 curend = i;
1770 } else {
1771 if ((curend - curstart) >
1772 (maxend - maxstart)) {
1773 maxstart = curstart;
1774 maxend = curend;
1775 }
1776 curstart = curend = 255;
1777 }
1778 }
1779 if ((curend - curstart) >
1780 (maxend - maxstart)) {
1781 maxstart = curstart;
1782 maxend = curend;
1783 }
1784 for (i = 0; i < 8; i++) {
1785 if (i >= maxstart && i <= maxend) {
1786 if (i == 0)
1787 printf(":");
1788 if (i == maxend)
1789 printf(":");
1790 } else {
1791 b = ntohs(addr->addr16[i]);
1792 printf("%x", b);
1793 if (i < 7)
1794 printf(":");
1795 }
1796 }
1797 if (p) {
1798 p = ntohs(p);
1799 printf("[%u]", p);
1800 }
1801 break;
1802 }
1803#endif /* INET6 */
1804 }
1805}
1806
1807void
1808pf_print_state(struct pf_state *s)
1809{
1810 pf_print_state_parts(s, NULL, NULL);
1811}
1812
1813static void
1814pf_print_state_parts(struct pf_state *s,
1815 struct pf_state_key *skwp, struct pf_state_key *sksp)
1816{
1817 struct pf_state_key *skw, *sks;
1818 u_int8_t proto, dir;
1819
1820 /* Do our best to fill these, but they're skipped if NULL */
1821 skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1822 sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1823 proto = skw ? skw->proto : (sks ? sks->proto : 0);
1824 dir = s ? s->direction : 0;
1825
1826 switch (proto) {
1827 case IPPROTO_IPV4:
1828 printf("IPv4");
1829 break;
1830 case IPPROTO_IPV6:
1831 printf("IPv6");
1832 break;
1833 case IPPROTO_TCP:
1834 printf("TCP");
1835 break;
1836 case IPPROTO_UDP:
1837 printf("UDP");
1838 break;
1839 case IPPROTO_ICMP:
1840 printf("ICMP");
1841 break;
1842 case IPPROTO_ICMPV6:
1843 printf("ICMPv6");
1844 break;
1845 default:
1846 printf("%u", skw->proto);
1847 break;
1848 }
1849 switch (dir) {
1850 case PF_IN:
1851 printf(" in");
1852 break;
1853 case PF_OUT:
1854 printf(" out");
1855 break;
1856 }
1857 if (skw) {
1858 printf(" wire: ");
1859 pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1860 printf(" ");
1861 pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1862 }
1863 if (sks) {
1864 printf(" stack: ");
1865 if (sks != skw) {
1866 pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1867 printf(" ");
1868 pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1869 } else
1870 printf("-");
1871 }
1872 if (s) {
1873 if (proto == IPPROTO_TCP) {
1874 printf(" [lo=%u high=%u win=%u modulator=%u",
1875 s->src.seqlo, s->src.seqhi,
1876 s->src.max_win, s->src.seqdiff);
1877 if (s->src.wscale && s->dst.wscale)
1878 printf(" wscale=%u",
1879 s->src.wscale & PF_WSCALE_MASK);
1880 printf("]");
1881 printf(" [lo=%u high=%u win=%u modulator=%u",
1882 s->dst.seqlo, s->dst.seqhi,
1883 s->dst.max_win, s->dst.seqdiff);
1884 if (s->src.wscale && s->dst.wscale)
1885 printf(" wscale=%u",
1886 s->dst.wscale & PF_WSCALE_MASK);
1887 printf("]");
1888 }
1889 printf(" %u:%u", s->src.state, s->dst.state);
1890 }
1891}
1892
1893void
1894pf_print_flags(u_int8_t f)
1895{
1896 if (f)
1897 printf(" ");
1898 if (f & TH_FIN)
1899 printf("F");
1900 if (f & TH_SYN)
1901 printf("S");
1902 if (f & TH_RST)
1903 printf("R");
1904 if (f & TH_PUSH)
1905 printf("P");
1906 if (f & TH_ACK)
1907 printf("A");
1908 if (f & TH_URG)
1909 printf("U");
1910 if (f & TH_ECE)
1911 printf("E");
1912 if (f & TH_CWR)
1913 printf("W");
1914}
1915
1916#define PF_SET_SKIP_STEPS(i) \
1917 do { \
1918 while (head[i] != cur) { \
1919 head[i]->skip[i].ptr = cur; \
1920 head[i] = TAILQ_NEXT(head[i], entries); \
1921 } \
1922 } while (0)
1923
1924void
1925pf_calc_skip_steps(struct pf_rulequeue *rules)
1926{
1927 struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
1928 int i;
1929
1930 cur = TAILQ_FIRST(rules);
1931 prev = cur;
1932 for (i = 0; i < PF_SKIP_COUNT; ++i)
1933 head[i] = cur;
1934 while (cur != NULL) {
1935
1936 if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
1937 PF_SET_SKIP_STEPS(PF_SKIP_IFP);
1938 if (cur->direction != prev->direction)
1939 PF_SET_SKIP_STEPS(PF_SKIP_DIR);
1940 if (cur->af != prev->af)
1941 PF_SET_SKIP_STEPS(PF_SKIP_AF);
1942 if (cur->proto != prev->proto)
1943 PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
1944 if (cur->src.neg != prev->src.neg ||
1945 pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
1946 PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
1947 if (cur->src.port[0] != prev->src.port[0] ||
1948 cur->src.port[1] != prev->src.port[1] ||
1949 cur->src.port_op != prev->src.port_op)
1950 PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
1951 if (cur->dst.neg != prev->dst.neg ||
1952 pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
1953 PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
1954 if (cur->dst.port[0] != prev->dst.port[0] ||
1955 cur->dst.port[1] != prev->dst.port[1] ||
1956 cur->dst.port_op != prev->dst.port_op)
1957 PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
1958
1959 prev = cur;
1960 cur = TAILQ_NEXT(cur, entries);
1961 }
1962 for (i = 0; i < PF_SKIP_COUNT; ++i)
1963 PF_SET_SKIP_STEPS(i);
1964}
1965
1966static int
1967pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
1968{
1969 if (aw1->type != aw2->type)
1970 return (1);
1971 switch (aw1->type) {
1972 case PF_ADDR_ADDRMASK:
1973 case PF_ADDR_RANGE:
1974 if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, 0))
1975 return (1);
1976 if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, 0))
1977 return (1);
1978 return (0);
1979 case PF_ADDR_DYNIFTL:
1980 return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
1981 case PF_ADDR_NOROUTE:
1982 case PF_ADDR_URPFFAILED:
1983 return (0);
1984 case PF_ADDR_TABLE:
1985 return (aw1->p.tbl != aw2->p.tbl);
1986 default:
1987 printf("invalid address type: %d\n", aw1->type);
1988 return (1);
1989 }
1990}
1991
1992u_int16_t
1993pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
1994{
1995 u_int32_t l;
1996
1997 if (udp && !cksum)
1998 return (0x0000);
1999 l = cksum + old - new;
2000 l = (l >> 16) + (l & 65535);
2001 l = l & 65535;
2002 if (udp && !l)
2003 return (0xFFFF);
2004 return (l);
2005}
2006
2007static void
2008pf_change_ap(struct pf_addr *a, u_int16_t *p, u_int16_t *ic, u_int16_t *pc,
2009 struct pf_addr *an, u_int16_t pn, u_int8_t u, sa_family_t af)
2010{
2011 struct pf_addr ao;
2012 u_int16_t po = *p;
2013
2014 PF_ACPY(&ao, a, af);
2015 PF_ACPY(a, an, af);
2016
2017 *p = pn;
2018
2019 switch (af) {
2020#ifdef INET
2021 case AF_INET:
2022 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2023 ao.addr16[0], an->addr16[0], 0),
2024 ao.addr16[1], an->addr16[1], 0);
2025 *p = pn;
2026 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
2027 ao.addr16[0], an->addr16[0], u),
2028 ao.addr16[1], an->addr16[1], u),
2029 po, pn, u);
2030 break;
2031#endif /* INET */
2032#ifdef INET6
2033 case AF_INET6:
2034 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2035 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2036 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
2037 ao.addr16[0], an->addr16[0], u),
2038 ao.addr16[1], an->addr16[1], u),
2039 ao.addr16[2], an->addr16[2], u),
2040 ao.addr16[3], an->addr16[3], u),
2041 ao.addr16[4], an->addr16[4], u),
2042 ao.addr16[5], an->addr16[5], u),
2043 ao.addr16[6], an->addr16[6], u),
2044 ao.addr16[7], an->addr16[7], u),
2045 po, pn, u);
2046 break;
2047#endif /* INET6 */
2048 }
2049}
2050
2051
2052/* Changes a u_int32_t. Uses a void * so there are no align restrictions */
2053void
2054pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
2055{
2056 u_int32_t ao;
2057
2058 memcpy(&ao, a, sizeof(ao));
2059 memcpy(a, &an, sizeof(u_int32_t));
2060 *c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
2061 ao % 65536, an % 65536, u);
2062}
2063
2064#ifdef INET6
2065static void
2066pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
2067{
2068 struct pf_addr ao;
2069
2070 PF_ACPY(&ao, a, AF_INET6);
2071 PF_ACPY(a, an, AF_INET6);
2072
2073 *c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2074 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2075 pf_cksum_fixup(pf_cksum_fixup(*c,
2076 ao.addr16[0], an->addr16[0], u),
2077 ao.addr16[1], an->addr16[1], u),
2078 ao.addr16[2], an->addr16[2], u),
2079 ao.addr16[3], an->addr16[3], u),
2080 ao.addr16[4], an->addr16[4], u),
2081 ao.addr16[5], an->addr16[5], u),
2082 ao.addr16[6], an->addr16[6], u),
2083 ao.addr16[7], an->addr16[7], u);
2084}
2085#endif /* INET6 */
2086
2087static void
2088pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
2089 struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
2090 u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
2091{
2092 struct pf_addr oia, ooa;
2093
2094 PF_ACPY(&oia, ia, af);
2095 if (oa)
2096 PF_ACPY(&ooa, oa, af);
2097
2098 /* Change inner protocol port, fix inner protocol checksum. */
2099 if (ip != NULL) {
2100 u_int16_t oip = *ip;
2101 u_int32_t opc;
2102
2103 if (pc != NULL)
2104 opc = *pc;
2105 *ip = np;
2106 if (pc != NULL)
2107 *pc = pf_cksum_fixup(*pc, oip, *ip, u);
2108 *ic = pf_cksum_fixup(*ic, oip, *ip, 0);
2109 if (pc != NULL)
2110 *ic = pf_cksum_fixup(*ic, opc, *pc, 0);
2111 }
2112 /* Change inner ip address, fix inner ip and icmp checksums. */
2113 PF_ACPY(ia, na, af);
2114 switch (af) {
2115#ifdef INET
2116 case AF_INET: {
2117 u_int32_t oh2c = *h2c;
2118
2119 *h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
2120 oia.addr16[0], ia->addr16[0], 0),
2121 oia.addr16[1], ia->addr16[1], 0);
2122 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2123 oia.addr16[0], ia->addr16[0], 0),
2124 oia.addr16[1], ia->addr16[1], 0);
2125 *ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
2126 break;
2127 }
2128#endif /* INET */
2129#ifdef INET6
2130 case AF_INET6:
2131 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2132 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2133 pf_cksum_fixup(pf_cksum_fixup(*ic,
2134 oia.addr16[0], ia->addr16[0], u),
2135 oia.addr16[1], ia->addr16[1], u),
2136 oia.addr16[2], ia->addr16[2], u),
2137 oia.addr16[3], ia->addr16[3], u),
2138 oia.addr16[4], ia->addr16[4], u),
2139 oia.addr16[5], ia->addr16[5], u),
2140 oia.addr16[6], ia->addr16[6], u),
2141 oia.addr16[7], ia->addr16[7], u);
2142 break;
2143#endif /* INET6 */
2144 }
2145 /* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
2146 if (oa) {
2147 PF_ACPY(oa, na, af);
2148 switch (af) {
2149#ifdef INET
2150 case AF_INET:
2151 *hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
2152 ooa.addr16[0], oa->addr16[0], 0),
2153 ooa.addr16[1], oa->addr16[1], 0);
2154 break;
2155#endif /* INET */
2156#ifdef INET6
2157 case AF_INET6:
2158 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2159 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2160 pf_cksum_fixup(pf_cksum_fixup(*ic,
2161 ooa.addr16[0], oa->addr16[0], u),
2162 ooa.addr16[1], oa->addr16[1], u),
2163 ooa.addr16[2], oa->addr16[2], u),
2164 ooa.addr16[3], oa->addr16[3], u),
2165 ooa.addr16[4], oa->addr16[4], u),
2166 ooa.addr16[5], oa->addr16[5], u),
2167 ooa.addr16[6], oa->addr16[6], u),
2168 ooa.addr16[7], oa->addr16[7], u);
2169 break;
2170#endif /* INET6 */
2171 }
2172 }
2173}
2174
2175
2176/*
2177 * Need to modulate the sequence numbers in the TCP SACK option
2178 * (credits to Krzysztof Pfaff for report and patch)
2179 */
2180static int
2181pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
2182 struct tcphdr *th, struct pf_state_peer *dst)
2183{
2184 int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
2185 u_int8_t opts[TCP_MAXOLEN], *opt = opts;
2186 int copyback = 0, i, olen;
2187 struct sackblk sack;
2188
2189#define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
2190 if (hlen < TCPOLEN_SACKLEN ||
2191 !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
2192 return 0;
2193
2194 while (hlen >= TCPOLEN_SACKLEN) {
2195 olen = opt[1];
2196 switch (*opt) {
2197 case TCPOPT_EOL: /* FALLTHROUGH */
2198 case TCPOPT_NOP:
2199 opt++;
2200 hlen--;
2201 break;
2202 case TCPOPT_SACK:
2203 if (olen > hlen)
2204 olen = hlen;
2205 if (olen >= TCPOLEN_SACKLEN) {
2206 for (i = 2; i + TCPOLEN_SACK <= olen;
2207 i += TCPOLEN_SACK) {
2208 memcpy(&sack, &opt[i], sizeof(sack));
2209 pf_change_a(&sack.start, &th->th_sum,
2210 htonl(ntohl(sack.start) -
2211 dst->seqdiff), 0);
2212 pf_change_a(&sack.end, &th->th_sum,
2213 htonl(ntohl(sack.end) -
2214 dst->seqdiff), 0);
2215 memcpy(&opt[i], &sack, sizeof(sack));
2216 }
2217 copyback = 1;
2218 }
2219 /* FALLTHROUGH */
2220 default:
2221 if (olen < 2)
2222 olen = 2;
2223 hlen -= olen;
2224 opt += olen;
2225 }
2226 }
2227
2228 if (copyback)
2229 m_copyback(m, off + sizeof(*th), thoptlen, (caddr_t)opts);
2230 return (copyback);
2231}
2232
2233static void
2234pf_send_tcp(struct mbuf *replyto, const struct pf_rule *r, sa_family_t af,
2235 const struct pf_addr *saddr, const struct pf_addr *daddr,
2236 u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2237 u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2238 u_int16_t rtag, struct ifnet *ifp)
2239{
2240 struct pf_send_entry *pfse;
2241 struct mbuf *m;
2242 int len, tlen;
2243#ifdef INET
2244 struct ip *h = NULL;
2245#endif /* INET */
2246#ifdef INET6
2247 struct ip6_hdr *h6 = NULL;
2248#endif /* INET6 */
2249 struct tcphdr *th;
2250 char *opt;
2251 struct pf_mtag *pf_mtag;
2252
2253 len = 0;
2254 th = NULL;
2255
2256 /* maximum segment size tcp option */
2257 tlen = sizeof(struct tcphdr);
2258 if (mss)
2259 tlen += 4;
2260
2261 switch (af) {
2262#ifdef INET
2263 case AF_INET:
2264 len = sizeof(struct ip) + tlen;
2265 break;
2266#endif /* INET */
2267#ifdef INET6
2268 case AF_INET6:
2269 len = sizeof(struct ip6_hdr) + tlen;
2270 break;
2271#endif /* INET6 */
2272 default:
2273 panic("%s: unsupported af %d", __func__, af);
2274 }
2275
2276 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2277 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2278 if (pfse == NULL)
2279 return;
2280 m = m_gethdr(M_NOWAIT, MT_DATA);
2281 if (m == NULL) {
2282 free(pfse, M_PFTEMP);
2283 return;
2284 }
2285#ifdef MAC
2286 mac_netinet_firewall_send(m);
2287#endif
2288 if ((pf_mtag = pf_get_mtag(m)) == NULL) {
2289 free(pfse, M_PFTEMP);
2290 m_freem(m);
2291 return;
2292 }
2293 if (tag)
2294 m->m_flags |= M_SKIP_FIREWALL;
2295 pf_mtag->tag = rtag;
2296
2297 if (r != NULL && r->rtableid >= 0)
2298 M_SETFIB(m, r->rtableid);
2299
2300#ifdef ALTQ
2301 if (r != NULL && r->qid) {
2302 pf_mtag->qid = r->qid;
2303
2304 /* add hints for ecn */
2305 pf_mtag->hdr = mtod(m, struct ip *);
2306 }
2307#endif /* ALTQ */
2308 m->m_data += max_linkhdr;
2309 m->m_pkthdr.len = m->m_len = len;
2310 m->m_pkthdr.rcvif = NULL;
2311 bzero(m->m_data, len);
2312 switch (af) {
2313#ifdef INET
2314 case AF_INET:
2315 h = mtod(m, struct ip *);
2316
2317 /* IP header fields included in the TCP checksum */
2318 h->ip_p = IPPROTO_TCP;
2319 h->ip_len = htons(tlen);
2320 h->ip_src.s_addr = saddr->v4.s_addr;
2321 h->ip_dst.s_addr = daddr->v4.s_addr;
2322
2323 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2324 break;
2325#endif /* INET */
2326#ifdef INET6
2327 case AF_INET6:
2328 h6 = mtod(m, struct ip6_hdr *);
2329
2330 /* IP header fields included in the TCP checksum */
2331 h6->ip6_nxt = IPPROTO_TCP;
2332 h6->ip6_plen = htons(tlen);
2333 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2334 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2335
2336 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2337 break;
2338#endif /* INET6 */
2339 }
2340
2341 /* TCP header */
2342 th->th_sport = sport;
2343 th->th_dport = dport;
2344 th->th_seq = htonl(seq);
2345 th->th_ack = htonl(ack);
2346 th->th_off = tlen >> 2;
2347 th->th_flags = flags;
2348 th->th_win = htons(win);
2349
2350 if (mss) {
2351 opt = (char *)(th + 1);
2352 opt[0] = TCPOPT_MAXSEG;
2353 opt[1] = 4;
2354 HTONS(mss);
2355 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
2356 }
2357
2358 switch (af) {
2359#ifdef INET
2360 case AF_INET:
2361 /* TCP checksum */
2362 th->th_sum = in_cksum(m, len);
2363
2364 /* Finish the IP header */
2365 h->ip_v = 4;
2366 h->ip_hl = sizeof(*h) >> 2;
2367 h->ip_tos = IPTOS_LOWDELAY;
2368 h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
2369 h->ip_len = htons(len);
2370 h->ip_ttl = ttl ? ttl : V_ip_defttl;
2371 h->ip_sum = 0;
2372
2373 pfse->pfse_type = PFSE_IP;
2374 break;
2375#endif /* INET */
2376#ifdef INET6
2377 case AF_INET6:
2378 /* TCP checksum */
2379 th->th_sum = in6_cksum(m, IPPROTO_TCP,
2380 sizeof(struct ip6_hdr), tlen);
2381
2382 h6->ip6_vfc |= IPV6_VERSION;
2383 h6->ip6_hlim = IPV6_DEFHLIM;
2384
2385 pfse->pfse_type = PFSE_IP6;
2386 break;
2387#endif /* INET6 */
2388 }
2389 pfse->pfse_m = m;
2390 pf_send(pfse);
2391}
2392
2393static void
2394pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
2395 struct pf_rule *r)
2396{
2397 struct pf_send_entry *pfse;
2398 struct mbuf *m0;
2399 struct pf_mtag *pf_mtag;
2400
2401 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2402 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2403 if (pfse == NULL)
2404 return;
2405
2406 if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
2407 free(pfse, M_PFTEMP);
2408 return;
2409 }
2410
2411 if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
2412 free(pfse, M_PFTEMP);
2413 return;
2414 }
2415 /* XXX: revisit */
2416 m0->m_flags |= M_SKIP_FIREWALL;
2417
2418 if (r->rtableid >= 0)
2419 M_SETFIB(m0, r->rtableid);
2420
2421#ifdef ALTQ
2422 if (r->qid) {
2423 pf_mtag->qid = r->qid;
2424 /* add hints for ecn */
2425 pf_mtag->hdr = mtod(m0, struct ip *);
2426 }
2427#endif /* ALTQ */
2428
2429 switch (af) {
2430#ifdef INET
2431 case AF_INET:
2432 pfse->pfse_type = PFSE_ICMP;
2433 break;
2434#endif /* INET */
2435#ifdef INET6
2436 case AF_INET6:
2437 pfse->pfse_type = PFSE_ICMP6;
2438 break;
2439#endif /* INET6 */
2440 }
2441 pfse->pfse_m = m0;
2442 pfse->pfse_icmp_type = type;
2443 pfse->pfse_icmp_code = code;
2444 pf_send(pfse);
2445}
2446
2447/*
2448 * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
2449 * If n is 0, they match if they are equal. If n is != 0, they match if they
2450 * are different.
2451 */
2452int
2453pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
2454 struct pf_addr *b, sa_family_t af)
2455{
2456 int match = 0;
2457
2458 switch (af) {
2459#ifdef INET
2460 case AF_INET:
2461 if ((a->addr32[0] & m->addr32[0]) ==
2462 (b->addr32[0] & m->addr32[0]))
2463 match++;
2464 break;
2465#endif /* INET */
2466#ifdef INET6
2467 case AF_INET6:
2468 if (((a->addr32[0] & m->addr32[0]) ==
2469 (b->addr32[0] & m->addr32[0])) &&
2470 ((a->addr32[1] & m->addr32[1]) ==
2471 (b->addr32[1] & m->addr32[1])) &&
2472 ((a->addr32[2] & m->addr32[2]) ==
2473 (b->addr32[2] & m->addr32[2])) &&
2474 ((a->addr32[3] & m->addr32[3]) ==
2475 (b->addr32[3] & m->addr32[3])))
2476 match++;
2477 break;
2478#endif /* INET6 */
2479 }
2480 if (match) {
2481 if (n)
2482 return (0);
2483 else
2484 return (1);
2485 } else {
2486 if (n)
2487 return (1);
2488 else
2489 return (0);
2490 }
2491}
2492
2493/*
2494 * Return 1 if b <= a <= e, otherwise return 0.
2495 */
2496int
2497pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
2498 struct pf_addr *a, sa_family_t af)
2499{
2500 switch (af) {
2501#ifdef INET
2502 case AF_INET:
2503 if ((a->addr32[0] < b->addr32[0]) ||
2504 (a->addr32[0] > e->addr32[0]))
2505 return (0);
2506 break;
2507#endif /* INET */
2508#ifdef INET6
2509 case AF_INET6: {
2510 int i;
2511
2512 /* check a >= b */
2513 for (i = 0; i < 4; ++i)
2514 if (a->addr32[i] > b->addr32[i])
2515 break;
2516 else if (a->addr32[i] < b->addr32[i])
2517 return (0);
2518 /* check a <= e */
2519 for (i = 0; i < 4; ++i)
2520 if (a->addr32[i] < e->addr32[i])
2521 break;
2522 else if (a->addr32[i] > e->addr32[i])
2523 return (0);
2524 break;
2525 }
2526#endif /* INET6 */
2527 }
2528 return (1);
2529}
2530
2531static int
2532pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2533{
2534 switch (op) {
2535 case PF_OP_IRG:
2536 return ((p > a1) && (p < a2));
2537 case PF_OP_XRG:
2538 return ((p < a1) || (p > a2));
2539 case PF_OP_RRG:
2540 return ((p >= a1) && (p <= a2));
2541 case PF_OP_EQ:
2542 return (p == a1);
2543 case PF_OP_NE:
2544 return (p != a1);
2545 case PF_OP_LT:
2546 return (p < a1);
2547 case PF_OP_LE:
2548 return (p <= a1);
2549 case PF_OP_GT:
2550 return (p > a1);
2551 case PF_OP_GE:
2552 return (p >= a1);
2553 }
2554 return (0); /* never reached */
2555}
2556
2557int
2558pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2559{
2560 NTOHS(a1);
2561 NTOHS(a2);
2562 NTOHS(p);
2563 return (pf_match(op, a1, a2, p));
2564}
2565
2566static int
2567pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2568{
2569 if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2570 return (0);
2571 return (pf_match(op, a1, a2, u));
2572}
2573
2574static int
2575pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2576{
2577 if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2578 return (0);
2579 return (pf_match(op, a1, a2, g));
2580}
2581
2582int
2583pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag, int mtag)
2584{
2585 if (*tag == -1)
2586 *tag = mtag;
2587
2588 return ((!r->match_tag_not && r->match_tag == *tag) ||
2589 (r->match_tag_not && r->match_tag != *tag));
2590}
2591
2592int
2593pf_tag_packet(struct mbuf *m, struct pf_pdesc *pd, int tag)
2594{
2595
2596 KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
2597
2598 if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(m)) == NULL))
2599 return (ENOMEM);
2600
2601 pd->pf_mtag->tag = tag;
2602
2603 return (0);
2604}
2605
2606#define PF_ANCHOR_STACKSIZE 32
2607struct pf_anchor_stackframe {
2608 struct pf_ruleset *rs;
2609 struct pf_rule *r; /* XXX: + match bit */
2610 struct pf_anchor *child;
2611};
2612
2613/*
2614 * XXX: We rely on malloc(9) returning pointer aligned addresses.
2615 */
2616#define PF_ANCHORSTACK_MATCH 0x00000001
2617#define PF_ANCHORSTACK_MASK (PF_ANCHORSTACK_MATCH)
2618
2619#define PF_ANCHOR_MATCH(f) ((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
2620#define PF_ANCHOR_RULE(f) (struct pf_rule *) \
2621 ((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
2622#define PF_ANCHOR_SET_MATCH(f) do { (f)->r = (void *) \
2623 ((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH); \
2624} while (0)
2625
2626void
2627pf_step_into_anchor(struct pf_anchor_stackframe *stack, int *depth,
2628 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2629 int *match)
2630{
2631 struct pf_anchor_stackframe *f;
2632
2633 PF_RULES_RASSERT();
2634
2635 if (match)
2636 *match = 0;
2637 if (*depth >= PF_ANCHOR_STACKSIZE) {
2638 printf("%s: anchor stack overflow on %s\n",
2639 __func__, (*r)->anchor->name);
2640 *r = TAILQ_NEXT(*r, entries);
2641 return;
2642 } else if (*depth == 0 && a != NULL)
2643 *a = *r;
2644 f = stack + (*depth)++;
2645 f->rs = *rs;
2646 f->r = *r;
2647 if ((*r)->anchor_wildcard) {
2648 struct pf_anchor_node *parent = &(*r)->anchor->children;
2649
2650 if ((f->child = RB_MIN(pf_anchor_node, parent)) == NULL) {
2651 *r = NULL;
2652 return;
2653 }
2654 *rs = &f->child->ruleset;
2655 } else {
2656 f->child = NULL;
2657 *rs = &(*r)->anchor->ruleset;
2658 }
2659 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2660}
2661
2662int
2663pf_step_out_of_anchor(struct pf_anchor_stackframe *stack, int *depth,
2664 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2665 int *match)
2666{
2667 struct pf_anchor_stackframe *f;
2668 struct pf_rule *fr;
2669 int quick = 0;
2670
2671 PF_RULES_RASSERT();
2672
2673 do {
2674 if (*depth <= 0)
2675 break;
2676 f = stack + *depth - 1;
2677 fr = PF_ANCHOR_RULE(f);
2678 if (f->child != NULL) {
2679 struct pf_anchor_node *parent;
2680
2681 /*
2682 * This block traverses through
2683 * a wildcard anchor.
2684 */
2685 parent = &fr->anchor->children;
2686 if (match != NULL && *match) {
2687 /*
2688 * If any of "*" matched, then
2689 * "foo/ *" matched, mark frame
2690 * appropriately.
2691 */
2692 PF_ANCHOR_SET_MATCH(f);
2693 *match = 0;
2694 }
2695 f->child = RB_NEXT(pf_anchor_node, parent, f->child);
2696 if (f->child != NULL) {
2697 *rs = &f->child->ruleset;
2698 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2699 if (*r == NULL)
2700 continue;
2701 else
2702 break;
2703 }
2704 }
2705 (*depth)--;
2706 if (*depth == 0 && a != NULL)
2707 *a = NULL;
2708 *rs = f->rs;
2709 if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
2710 quick = fr->quick;
2711 *r = TAILQ_NEXT(fr, entries);
2712 } while (*r == NULL);
2713
2714 return (quick);
2715}
2716
2717#ifdef INET6
2718void
2719pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2720 struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2721{
2722 switch (af) {
2723#ifdef INET
2724 case AF_INET:
2725 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2726 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2727 break;
2728#endif /* INET */
2729 case AF_INET6:
2730 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2731 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2732 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2733 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2734 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2735 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2736 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2737 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2738 break;
2739 }
2740}
2741
2742void
2743pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2744{
2745 switch (af) {
2746#ifdef INET
2747 case AF_INET:
2748 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2749 break;
2750#endif /* INET */
2751 case AF_INET6:
2752 if (addr->addr32[3] == 0xffffffff) {
2753 addr->addr32[3] = 0;
2754 if (addr->addr32[2] == 0xffffffff) {
2755 addr->addr32[2] = 0;
2756 if (addr->addr32[1] == 0xffffffff) {
2757 addr->addr32[1] = 0;
2758 addr->addr32[0] =
2759 htonl(ntohl(addr->addr32[0]) + 1);
2760 } else
2761 addr->addr32[1] =
2762 htonl(ntohl(addr->addr32[1]) + 1);
2763 } else
2764 addr->addr32[2] =
2765 htonl(ntohl(addr->addr32[2]) + 1);
2766 } else
2767 addr->addr32[3] =
2768 htonl(ntohl(addr->addr32[3]) + 1);
2769 break;
2770 }
2771}
2772#endif /* INET6 */
2773
2774int
2775pf_socket_lookup(int direction, struct pf_pdesc *pd, struct mbuf *m)
2776{
2777 struct pf_addr *saddr, *daddr;
2778 u_int16_t sport, dport;
2779 struct inpcbinfo *pi;
2780 struct inpcb *inp;
2781
2782 pd->lookup.uid = UID_MAX;
2783 pd->lookup.gid = GID_MAX;
2784
2785 switch (pd->proto) {
2786 case IPPROTO_TCP:
2787 if (pd->hdr.tcp == NULL)
2788 return (-1);
2789 sport = pd->hdr.tcp->th_sport;
2790 dport = pd->hdr.tcp->th_dport;
2791 pi = &V_tcbinfo;
2792 break;
2793 case IPPROTO_UDP:
2794 if (pd->hdr.udp == NULL)
2795 return (-1);
2796 sport = pd->hdr.udp->uh_sport;
2797 dport = pd->hdr.udp->uh_dport;
2798 pi = &V_udbinfo;
2799 break;
2800 default:
2801 return (-1);
2802 }
2803 if (direction == PF_IN) {
2804 saddr = pd->src;
2805 daddr = pd->dst;
2806 } else {
2807 u_int16_t p;
2808
2809 p = sport;
2810 sport = dport;
2811 dport = p;
2812 saddr = pd->dst;
2813 daddr = pd->src;
2814 }
2815 switch (pd->af) {
2816#ifdef INET
2817 case AF_INET:
2818 inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
2819 dport, INPLOOKUP_RLOCKPCB, NULL, m);
2820 if (inp == NULL) {
2821 inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
2822 daddr->v4, dport, INPLOOKUP_WILDCARD |
2823 INPLOOKUP_RLOCKPCB, NULL, m);
2824 if (inp == NULL)
2825 return (-1);
2826 }
2827 break;
2828#endif /* INET */
2829#ifdef INET6
2830 case AF_INET6:
2831 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
2832 dport, INPLOOKUP_RLOCKPCB, NULL, m);
2833 if (inp == NULL) {
2834 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
2835 &daddr->v6, dport, INPLOOKUP_WILDCARD |
2836 INPLOOKUP_RLOCKPCB, NULL, m);
2837 if (inp == NULL)
2838 return (-1);
2839 }
2840 break;
2841#endif /* INET6 */
2842
2843 default:
2844 return (-1);
2845 }
2846 INP_RLOCK_ASSERT(inp);
2847 pd->lookup.uid = inp->inp_cred->cr_uid;
2848 pd->lookup.gid = inp->inp_cred->cr_groups[0];
2849 INP_RUNLOCK(inp);
2850
2851 return (1);
2852}
2853
2854static u_int8_t
2855pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2856{
2857 int hlen;
2858 u_int8_t hdr[60];
2859 u_int8_t *opt, optlen;
2860 u_int8_t wscale = 0;
2861
2862 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
2863 if (hlen <= sizeof(struct tcphdr))
2864 return (0);
2865 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2866 return (0);
2867 opt = hdr + sizeof(struct tcphdr);
2868 hlen -= sizeof(struct tcphdr);
2869 while (hlen >= 3) {
2870 switch (*opt) {
2871 case TCPOPT_EOL:
2872 case TCPOPT_NOP:
2873 ++opt;
2874 --hlen;
2875 break;
2876 case TCPOPT_WINDOW:
2877 wscale = opt[2];
2878 if (wscale > TCP_MAX_WINSHIFT)
2879 wscale = TCP_MAX_WINSHIFT;
2880 wscale |= PF_WSCALE_FLAG;
2881 /* FALLTHROUGH */
2882 default:
2883 optlen = opt[1];
2884 if (optlen < 2)
2885 optlen = 2;
2886 hlen -= optlen;
2887 opt += optlen;
2888 break;
2889 }
2890 }
2891 return (wscale);
2892}
2893
2894static u_int16_t
2895pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2896{
2897 int hlen;
2898 u_int8_t hdr[60];
2899 u_int8_t *opt, optlen;
2900 u_int16_t mss = V_tcp_mssdflt;
2901
2902 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
2903 if (hlen <= sizeof(struct tcphdr))
2904 return (0);
2905 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2906 return (0);
2907 opt = hdr + sizeof(struct tcphdr);
2908 hlen -= sizeof(struct tcphdr);
2909 while (hlen >= TCPOLEN_MAXSEG) {
2910 switch (*opt) {
2911 case TCPOPT_EOL:
2912 case TCPOPT_NOP:
2913 ++opt;
2914 --hlen;
2915 break;
2916 case TCPOPT_MAXSEG:
2917 bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
2918 NTOHS(mss);
2919 /* FALLTHROUGH */
2920 default:
2921 optlen = opt[1];
2922 if (optlen < 2)
2923 optlen = 2;
2924 hlen -= optlen;
2925 opt += optlen;
2926 break;
2927 }
2928 }
2929 return (mss);
2930}
2931
2932static u_int16_t
2933pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
2934{
2935#ifdef INET
2936 struct sockaddr_in *dst;
2937 struct route ro;
2938#endif /* INET */
2939#ifdef INET6
2940 struct sockaddr_in6 *dst6;
2941 struct route_in6 ro6;
2942#endif /* INET6 */
2943 struct rtentry *rt = NULL;
2944 int hlen = 0;
2945 u_int16_t mss = V_tcp_mssdflt;
2946
2947 switch (af) {
2948#ifdef INET
2949 case AF_INET:
2950 hlen = sizeof(struct ip);
2951 bzero(&ro, sizeof(ro));
2952 dst = (struct sockaddr_in *)&ro.ro_dst;
2953 dst->sin_family = AF_INET;
2954 dst->sin_len = sizeof(*dst);
2955 dst->sin_addr = addr->v4;
2956 in_rtalloc_ign(&ro, 0, rtableid);
2957 rt = ro.ro_rt;
2958 break;
2959#endif /* INET */
2960#ifdef INET6
2961 case AF_INET6:
2962 hlen = sizeof(struct ip6_hdr);
2963 bzero(&ro6, sizeof(ro6));
2964 dst6 = (struct sockaddr_in6 *)&ro6.ro_dst;
2965 dst6->sin6_family = AF_INET6;
2966 dst6->sin6_len = sizeof(*dst6);
2967 dst6->sin6_addr = addr->v6;
2968 in6_rtalloc_ign(&ro6, 0, rtableid);
2969 rt = ro6.ro_rt;
2970 break;
2971#endif /* INET6 */
2972 }
2973
2974 if (rt && rt->rt_ifp) {
2975 mss = rt->rt_ifp->if_mtu - hlen - sizeof(struct tcphdr);
2976 mss = max(V_tcp_mssdflt, mss);
2977 RTFREE(rt);
2978 }
2979 mss = min(mss, offer);
2980 mss = max(mss, 64); /* sanity - at least max opt space */
2981 return (mss);
2982}
2983
2984static u_int32_t
2985pf_tcp_iss(struct pf_pdesc *pd)
2986{
2987 MD5_CTX ctx;
2988 u_int32_t digest[4];
2989
2990 if (V_pf_tcp_secret_init == 0) {
2991 read_random(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
2992 MD5Init(&V_pf_tcp_secret_ctx);
2993 MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
2994 sizeof(V_pf_tcp_secret));
2995 V_pf_tcp_secret_init = 1;
2996 }
2997
2998 ctx = V_pf_tcp_secret_ctx;
2999
3000 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
3001 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
3002 if (pd->af == AF_INET6) {
3003 MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
3004 MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
3005 } else {
3006 MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
3007 MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
3008 }
3009 MD5Final((u_char *)digest, &ctx);
3010 V_pf_tcp_iss_off += 4096;
3011#define ISN_RANDOM_INCREMENT (4096 - 1)
3012 return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
3013 V_pf_tcp_iss_off);
3014#undef ISN_RANDOM_INCREMENT
3015}
3016
3017static int
3018pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
3019 struct pfi_kif *kif, struct mbuf *m, int off, struct pf_pdesc *pd,
3020 struct pf_rule **am, struct pf_ruleset **rsm, struct inpcb *inp)
3021{
3022 struct pf_rule *nr = NULL;
3023 struct pf_addr * const saddr = pd->src;
3024 struct pf_addr * const daddr = pd->dst;
3025 sa_family_t af = pd->af;
3026 struct pf_rule *r, *a = NULL;
3027 struct pf_ruleset *ruleset = NULL;
3028 struct pf_src_node *nsn = NULL;
3029 struct tcphdr *th = pd->hdr.tcp;
3030 struct pf_state_key *sk = NULL, *nk = NULL;
3031 u_short reason;
3032 int rewrite = 0, hdrlen = 0;
3033 int tag = -1, rtableid = -1;
3034 int asd = 0;
3035 int match = 0;
3036 int state_icmp = 0;
3037 u_int16_t sport = 0, dport = 0;
3038 u_int16_t bproto_sum = 0, bip_sum = 0;
3039 u_int8_t icmptype = 0, icmpcode = 0;
3040 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3041
3042 PF_RULES_RASSERT();
3043
3044 if (inp != NULL) {
3045 INP_LOCK_ASSERT(inp);
3046 pd->lookup.uid = inp->inp_cred->cr_uid;
3047 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3048 pd->lookup.done = 1;
3049 }
3050
3051 switch (pd->proto) {
3052 case IPPROTO_TCP:
3053 sport = th->th_sport;
3054 dport = th->th_dport;
3055 hdrlen = sizeof(*th);
3056 break;
3057 case IPPROTO_UDP:
3058 sport = pd->hdr.udp->uh_sport;
3059 dport = pd->hdr.udp->uh_dport;
3060 hdrlen = sizeof(*pd->hdr.udp);
3061 break;
3062#ifdef INET
3063 case IPPROTO_ICMP:
3064 if (pd->af != AF_INET)
3065 break;
3066 sport = dport = pd->hdr.icmp->icmp_id;
3067 hdrlen = sizeof(*pd->hdr.icmp);
3068 icmptype = pd->hdr.icmp->icmp_type;
3069 icmpcode = pd->hdr.icmp->icmp_code;
3070
3071 if (icmptype == ICMP_UNREACH ||
3072 icmptype == ICMP_SOURCEQUENCH ||
3073 icmptype == ICMP_REDIRECT ||
3074 icmptype == ICMP_TIMXCEED ||
3075 icmptype == ICMP_PARAMPROB)
3076 state_icmp++;
3077 break;
3078#endif /* INET */
3079#ifdef INET6
3080 case IPPROTO_ICMPV6:
3081 if (af != AF_INET6)
3082 break;
3083 sport = dport = pd->hdr.icmp6->icmp6_id;
3084 hdrlen = sizeof(*pd->hdr.icmp6);
3085 icmptype = pd->hdr.icmp6->icmp6_type;
3086 icmpcode = pd->hdr.icmp6->icmp6_code;
3087
3088 if (icmptype == ICMP6_DST_UNREACH ||
3089 icmptype == ICMP6_PACKET_TOO_BIG ||
3090 icmptype == ICMP6_TIME_EXCEEDED ||
3091 icmptype == ICMP6_PARAM_PROB)
3092 state_icmp++;
3093 break;
3094#endif /* INET6 */
3095 default:
3096 sport = dport = hdrlen = 0;
3097 break;
3098 }
3099
3100 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3101
3102 /* check packet for BINAT/NAT/RDR */
3103 if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn, &sk,
3104 &nk, saddr, daddr, sport, dport, anchor_stack)) != NULL) {
3105 KASSERT(sk != NULL, ("%s: null sk", __func__));
3106 KASSERT(nk != NULL, ("%s: null nk", __func__));
3107
3108 if (pd->ip_sum)
3109 bip_sum = *pd->ip_sum;
3110
3111 switch (pd->proto) {
3112 case IPPROTO_TCP:
3113 bproto_sum = th->th_sum;
3114 pd->proto_sum = &th->th_sum;
3115
3116 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3117 nk->port[pd->sidx] != sport) {
3118 pf_change_ap(saddr, &th->th_sport, pd->ip_sum,
3119 &th->th_sum, &nk->addr[pd->sidx],
3120 nk->port[pd->sidx], 0, af);
3121 pd->sport = &th->th_sport;
3122 sport = th->th_sport;
3123 }
3124
3125 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3126 nk->port[pd->didx] != dport) {
3127 pf_change_ap(daddr, &th->th_dport, pd->ip_sum,
3128 &th->th_sum, &nk->addr[pd->didx],
3129 nk->port[pd->didx], 0, af);
3130 dport = th->th_dport;
3131 pd->dport = &th->th_dport;
3132 }
3133 rewrite++;
3134 break;
3135 case IPPROTO_UDP:
3136 bproto_sum = pd->hdr.udp->uh_sum;
3137 pd->proto_sum = &pd->hdr.udp->uh_sum;
3138
3139 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3140 nk->port[pd->sidx] != sport) {
3141 pf_change_ap(saddr, &pd->hdr.udp->uh_sport,
3142 pd->ip_sum, &pd->hdr.udp->uh_sum,
3143 &nk->addr[pd->sidx],
3144 nk->port[pd->sidx], 1, af);
3145 sport = pd->hdr.udp->uh_sport;
3146 pd->sport = &pd->hdr.udp->uh_sport;
3147 }
3148
3149 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3150 nk->port[pd->didx] != dport) {
3151 pf_change_ap(daddr, &pd->hdr.udp->uh_dport,
3152 pd->ip_sum, &pd->hdr.udp->uh_sum,
3153 &nk->addr[pd->didx],
3154 nk->port[pd->didx], 1, af);
3155 dport = pd->hdr.udp->uh_dport;
3156 pd->dport = &pd->hdr.udp->uh_dport;
3157 }
3158 rewrite++;
3159 break;
3160#ifdef INET
3161 case IPPROTO_ICMP:
3162 nk->port[0] = nk->port[1];
3163 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3164 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3165 nk->addr[pd->sidx].v4.s_addr, 0);
3166
3167 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3168 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3169 nk->addr[pd->didx].v4.s_addr, 0);
3170
3171 if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3172 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3173 pd->hdr.icmp->icmp_cksum, sport,
3174 nk->port[1], 0);
3175 pd->hdr.icmp->icmp_id = nk->port[1];
3176 pd->sport = &pd->hdr.icmp->icmp_id;
3177 }
3178 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3179 break;
3180#endif /* INET */
3181#ifdef INET6
3182 case IPPROTO_ICMPV6:
3183 nk->port[0] = nk->port[1];
3184 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3185 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3186 &nk->addr[pd->sidx], 0);
3187
3188 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3189 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3190 &nk->addr[pd->didx], 0);
3191 rewrite++;
3192 break;
3193#endif /* INET */
3194 default:
3195 switch (af) {
3196#ifdef INET
3197 case AF_INET:
3198 if (PF_ANEQ(saddr,
3199 &nk->addr[pd->sidx], AF_INET))
3200 pf_change_a(&saddr->v4.s_addr,
3201 pd->ip_sum,
3202 nk->addr[pd->sidx].v4.s_addr, 0);
3203
3204 if (PF_ANEQ(daddr,
3205 &nk->addr[pd->didx], AF_INET))
3206 pf_change_a(&daddr->v4.s_addr,
3207 pd->ip_sum,
3208 nk->addr[pd->didx].v4.s_addr, 0);
3209 break;
3210#endif /* INET */
3211#ifdef INET6
3212 case AF_INET6:
3213 if (PF_ANEQ(saddr,
3214 &nk->addr[pd->sidx], AF_INET6))
3215 PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3216
3217 if (PF_ANEQ(daddr,
3218 &nk->addr[pd->didx], AF_INET6))
3219 PF_ACPY(saddr, &nk->addr[pd->didx], af);
3220 break;
3221#endif /* INET */
3222 }
3223 break;
3224 }
3225 if (nr->natpass)
3226 r = NULL;
3227 pd->nat_rule = nr;
3228 }
3229
3230 while (r != NULL) {
3231 r->evaluations++;
3232 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3233 r = r->skip[PF_SKIP_IFP].ptr;
3234 else if (r->direction && r->direction != direction)
3235 r = r->skip[PF_SKIP_DIR].ptr;
3236 else if (r->af && r->af != af)
3237 r = r->skip[PF_SKIP_AF].ptr;
3238 else if (r->proto && r->proto != pd->proto)
3239 r = r->skip[PF_SKIP_PROTO].ptr;
3240 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3241 r->src.neg, kif, M_GETFIB(m)))
3242 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3243 /* tcp/udp only. port_op always 0 in other cases */
3244 else if (r->src.port_op && !pf_match_port(r->src.port_op,
3245 r->src.port[0], r->src.port[1], sport))
3246 r = r->skip[PF_SKIP_SRC_PORT].ptr;
3247 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3248 r->dst.neg, NULL, M_GETFIB(m)))
3249 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3250 /* tcp/udp only. port_op always 0 in other cases */
3251 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3252 r->dst.port[0], r->dst.port[1], dport))
3253 r = r->skip[PF_SKIP_DST_PORT].ptr;
3254 /* icmp only. type always 0 in other cases */
3255 else if (r->type && r->type != icmptype + 1)
3256 r = TAILQ_NEXT(r, entries);
3257 /* icmp only. type always 0 in other cases */
3258 else if (r->code && r->code != icmpcode + 1)
3259 r = TAILQ_NEXT(r, entries);
3260 else if (r->tos && !(r->tos == pd->tos))
3261 r = TAILQ_NEXT(r, entries);
3262 else if (r->rule_flag & PFRULE_FRAGMENT)
3263 r = TAILQ_NEXT(r, entries);
3264 else if (pd->proto == IPPROTO_TCP &&
3265 (r->flagset & th->th_flags) != r->flags)
3266 r = TAILQ_NEXT(r, entries);
3267 /* tcp/udp only. uid.op always 0 in other cases */
3268 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3269 pf_socket_lookup(direction, pd, m), 1)) &&
3270 !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3271 pd->lookup.uid))
3272 r = TAILQ_NEXT(r, entries);
3273 /* tcp/udp only. gid.op always 0 in other cases */
3274 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3275 pf_socket_lookup(direction, pd, m), 1)) &&
3276 !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3277 pd->lookup.gid))
3278 r = TAILQ_NEXT(r, entries);
3279 else if (r->prob &&
3280 r->prob <= arc4random())
3281 r = TAILQ_NEXT(r, entries);
3282 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3283 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3284 r = TAILQ_NEXT(r, entries);
3285 else if (r->os_fingerprint != PF_OSFP_ANY &&
3286 (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3287 pf_osfp_fingerprint(pd, m, off, th),
3288 r->os_fingerprint)))
3289 r = TAILQ_NEXT(r, entries);
3290 else {
3291 if (r->tag)
3292 tag = r->tag;
3293 if (r->rtableid >= 0)
3294 rtableid = r->rtableid;
3295 if (r->anchor == NULL) {
3296 match = 1;
3297 *rm = r;
3298 *am = a;
3299 *rsm = ruleset;
3300 if ((*rm)->quick)
3301 break;
3302 r = TAILQ_NEXT(r, entries);
3303 } else
3304 pf_step_into_anchor(anchor_stack, &asd,
3305 &ruleset, PF_RULESET_FILTER, &r, &a,
3306 &match);
3307 }
3308 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3309 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3310 break;
3311 }
3312 r = *rm;
3313 a = *am;
3314 ruleset = *rsm;
3315
3316 REASON_SET(&reason, PFRES_MATCH);
3317
3318 if (r->log || (nr != NULL && nr->log)) {
3319 if (rewrite)
3320 m_copyback(m, off, hdrlen, pd->hdr.any);
3321 PFLOG_PACKET(kif, m, af, direction, reason, r->log ? r : nr, a,
3322 ruleset, pd, 1);
3323 }
3324
3325 if ((r->action == PF_DROP) &&
3326 ((r->rule_flag & PFRULE_RETURNRST) ||
3327 (r->rule_flag & PFRULE_RETURNICMP) ||
3328 (r->rule_flag & PFRULE_RETURN))) {
3329 /* undo NAT changes, if they have taken place */
3330 if (nr != NULL) {
3331 PF_ACPY(saddr, &sk->addr[pd->sidx], af);
3332 PF_ACPY(daddr, &sk->addr[pd->didx], af);
3333 if (pd->sport)
3334 *pd->sport = sk->port[pd->sidx];
3335 if (pd->dport)
3336 *pd->dport = sk->port[pd->didx];
3337 if (pd->proto_sum)
3338 *pd->proto_sum = bproto_sum;
3339 if (pd->ip_sum)
3340 *pd->ip_sum = bip_sum;
3341 m_copyback(m, off, hdrlen, pd->hdr.any);
3342 }
3343 if (pd->proto == IPPROTO_TCP &&
3344 ((r->rule_flag & PFRULE_RETURNRST) ||
3345 (r->rule_flag & PFRULE_RETURN)) &&
3346 !(th->th_flags & TH_RST)) {
3347 u_int32_t ack = ntohl(th->th_seq) + pd->p_len;
3348 int len = 0;
3349#ifdef INET
3350 struct ip *h4;
3351#endif
3352#ifdef INET6
3353 struct ip6_hdr *h6;
3354#endif
3355
3356 switch (af) {
3357#ifdef INET
3358 case AF_INET:
3359 h4 = mtod(m, struct ip *);
3360 len = ntohs(h4->ip_len) - off;
3361 break;
3362#endif
3363#ifdef INET6
3364 case AF_INET6:
3365 h6 = mtod(m, struct ip6_hdr *);
3366 len = ntohs(h6->ip6_plen) - (off - sizeof(*h6));
3367 break;
3368#endif
3369 }
3370
3371 if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
3372 REASON_SET(&reason, PFRES_PROTCKSUM);
3373 else {
3374 if (th->th_flags & TH_SYN)
3375 ack++;
3376 if (th->th_flags & TH_FIN)
3377 ack++;
3378 pf_send_tcp(m, r, af, pd->dst,
3379 pd->src, th->th_dport, th->th_sport,
3380 ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
3381 r->return_ttl, 1, 0, kif->pfik_ifp);
3382 }
3383 } else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
3384 r->return_icmp)
3385 pf_send_icmp(m, r->return_icmp >> 8,
3386 r->return_icmp & 255, af, r);
3387 else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
3388 r->return_icmp6)
3389 pf_send_icmp(m, r->return_icmp6 >> 8,
3390 r->return_icmp6 & 255, af, r);
3391 }
3392
3393 if (r->action == PF_DROP)
3394 goto cleanup;
3395
3396 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3397 REASON_SET(&reason, PFRES_MEMORY);
3398 goto cleanup;
3399 }
3400 if (rtableid >= 0)
3401 M_SETFIB(m, rtableid);
3402
3403 if (!state_icmp && (r->keep_state || nr != NULL ||
3404 (pd->flags & PFDESC_TCP_NORM))) {
3405 int action;
3406 action = pf_create_state(r, nr, a, pd, nsn, nk, sk, m, off,
3407 sport, dport, &rewrite, kif, sm, tag, bproto_sum, bip_sum,
3408 hdrlen);
3409 if (action != PF_PASS)
3410 return (action);
3411 } else {
3412 if (sk != NULL)
3413 uma_zfree(V_pf_state_key_z, sk);
3414 if (nk != NULL)
3415 uma_zfree(V_pf_state_key_z, nk);
3416 }
3417
3418 /* copy back packet headers if we performed NAT operations */
3419 if (rewrite)
3420 m_copyback(m, off, hdrlen, pd->hdr.any);
3421
3422 if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
3423 direction == PF_OUT &&
3424 pfsync_defer_ptr != NULL && pfsync_defer_ptr(*sm, m))
3425 /*
3426 * We want the state created, but we dont
3427 * want to send this in case a partner
3428 * firewall has to know about it to allow
3429 * replies through it.
3430 */
3431 return (PF_DEFER);
3432
3433 return (PF_PASS);
3434
3435cleanup:
3436 if (sk != NULL)
3437 uma_zfree(V_pf_state_key_z, sk);
3438 if (nk != NULL)
3439 uma_zfree(V_pf_state_key_z, nk);
3440 return (PF_DROP);
3441}
3442
3443static int
3444pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3445 struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *nk,
3446 struct pf_state_key *sk, struct mbuf *m, int off, u_int16_t sport,
3447 u_int16_t dport, int *rewrite, struct pfi_kif *kif, struct pf_state **sm,
3448 int tag, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen)
3449{
3450 struct pf_state *s = NULL;
3451 struct pf_src_node *sn = NULL;
3452 struct tcphdr *th = pd->hdr.tcp;
3453 u_int16_t mss = V_tcp_mssdflt;
3454 u_short reason;
3455
3456 /* check maximums */
3457 if (r->max_states &&
3458 (counter_u64_fetch(r->states_cur) >= r->max_states)) {
3459 counter_u64_add(V_pf_status.lcounters[LCNT_STATES], 1);
3460 REASON_SET(&reason, PFRES_MAXSTATES);
3461 return (PF_DROP);
3462 }
3463 /* src node for filter rule */
3464 if ((r->rule_flag & PFRULE_SRCTRACK ||
3465 r->rpool.opts & PF_POOL_STICKYADDR) &&
3466 pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3467 REASON_SET(&reason, PFRES_SRCLIMIT);
3468 goto csfailed;
3469 }
3470 /* src node for translation rule */
3471 if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3472 pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3473 REASON_SET(&reason, PFRES_SRCLIMIT);
3474 goto csfailed;
3475 }
3476 s = uma_zalloc(V_pf_state_z, M_NOWAIT | M_ZERO);
3477 if (s == NULL) {
3478 REASON_SET(&reason, PFRES_MEMORY);
3479 goto csfailed;
3480 }
3481 s->rule.ptr = r;
3482 s->nat_rule.ptr = nr;
3483 s->anchor.ptr = a;
3484 STATE_INC_COUNTERS(s);
3485 if (r->allow_opts)
3486 s->state_flags |= PFSTATE_ALLOWOPTS;
3487 if (r->rule_flag & PFRULE_STATESLOPPY)
3488 s->state_flags |= PFSTATE_SLOPPY;
3489 s->log = r->log & PF_LOG_ALL;
3490 s->sync_state = PFSYNC_S_NONE;
3491 if (nr != NULL)
3492 s->log |= nr->log & PF_LOG_ALL;
3493 switch (pd->proto) {
3494 case IPPROTO_TCP:
3495 s->src.seqlo = ntohl(th->th_seq);
3496 s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3497 if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3498 r->keep_state == PF_STATE_MODULATE) {
3499 /* Generate sequence number modulator */
3500 if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3501 0)
3502 s->src.seqdiff = 1;
3503 pf_change_a(&th->th_seq, &th->th_sum,
3504 htonl(s->src.seqlo + s->src.seqdiff), 0);
3505 *rewrite = 1;
3506 } else
3507 s->src.seqdiff = 0;
3508 if (th->th_flags & TH_SYN) {
3509 s->src.seqhi++;
3510 s->src.wscale = pf_get_wscale(m, off,
3511 th->th_off, pd->af);
3512 }
3513 s->src.max_win = MAX(ntohs(th->th_win), 1);
3514 if (s->src.wscale & PF_WSCALE_MASK) {
3515 /* Remove scale factor from initial window */
3516 int win = s->src.max_win;
3517 win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3518 s->src.max_win = (win - 1) >>
3519 (s->src.wscale & PF_WSCALE_MASK);
3520 }
3521 if (th->th_flags & TH_FIN)
3522 s->src.seqhi++;
3523 s->dst.seqhi = 1;
3524 s->dst.max_win = 1;
3525 s->src.state = TCPS_SYN_SENT;
3526 s->dst.state = TCPS_CLOSED;
3527 s->timeout = PFTM_TCP_FIRST_PACKET;
3528 break;
3529 case IPPROTO_UDP:
3530 s->src.state = PFUDPS_SINGLE;
3531 s->dst.state = PFUDPS_NO_TRAFFIC;
3532 s->timeout = PFTM_UDP_FIRST_PACKET;
3533 break;
3534 case IPPROTO_ICMP:
3535#ifdef INET6
3536 case IPPROTO_ICMPV6:
3537#endif
3538 s->timeout = PFTM_ICMP_FIRST_PACKET;
3539 break;
3540 default:
3541 s->src.state = PFOTHERS_SINGLE;
3542 s->dst.state = PFOTHERS_NO_TRAFFIC;
3543 s->timeout = PFTM_OTHER_FIRST_PACKET;
3544 }
3545
3546 if (r->rt && r->rt != PF_FASTROUTE) {
3547 if (pf_map_addr(pd->af, r, pd->src, &s->rt_addr, NULL, &sn)) {
3548 REASON_SET(&reason, PFRES_BADSTATE);
3549 pf_src_tree_remove_state(s);
3550 STATE_DEC_COUNTERS(s);
3551 uma_zfree(V_pf_state_z, s);
3552 goto csfailed;
3553 }
3554 s->rt_kif = r->rpool.cur->kif;
3555 }
3556
3557 s->creation = time_uptime;
3558 s->expire = time_uptime;
3559
3574 if (sn != NULL) {
3560 if (sn != NULL)
3575 s->src_node = sn;
3561 s->src_node = sn;
3576 s->src_node->states++;
3577 }
3578 if (nsn != NULL) {
3579 /* XXX We only modify one side for now. */
3580 PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3581 s->nat_src_node = nsn;
3562 if (nsn != NULL) {
3563 /* XXX We only modify one side for now. */
3564 PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3565 s->nat_src_node = nsn;
3582 s->nat_src_node->states++;
3583 }
3584 if (pd->proto == IPPROTO_TCP) {
3585 if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3586 off, pd, th, &s->src, &s->dst)) {
3587 REASON_SET(&reason, PFRES_MEMORY);
3588 pf_src_tree_remove_state(s);
3589 STATE_DEC_COUNTERS(s);
3590 uma_zfree(V_pf_state_z, s);
3591 return (PF_DROP);
3592 }
3593 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3594 pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3595 &s->src, &s->dst, rewrite)) {
3596 /* This really shouldn't happen!!! */
3597 DPFPRINTF(PF_DEBUG_URGENT,
3598 ("pf_normalize_tcp_stateful failed on first pkt"));
3599 pf_normalize_tcp_cleanup(s);
3600 pf_src_tree_remove_state(s);
3601 STATE_DEC_COUNTERS(s);
3602 uma_zfree(V_pf_state_z, s);
3603 return (PF_DROP);
3604 }
3605 }
3606 s->direction = pd->dir;
3607
3608 /*
3609 * sk/nk could already been setup by pf_get_translation().
3610 */
3611 if (nr == NULL) {
3612 KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
3613 __func__, nr, sk, nk));
3614 sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
3615 if (sk == NULL)
3616 goto csfailed;
3617 nk = sk;
3618 } else
3619 KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
3620 __func__, nr, sk, nk));
3621
3622 /* Swap sk/nk for PF_OUT. */
3623 if (pf_state_insert(BOUND_IFACE(r, kif),
3624 (pd->dir == PF_IN) ? sk : nk,
3625 (pd->dir == PF_IN) ? nk : sk, s)) {
3626 if (pd->proto == IPPROTO_TCP)
3627 pf_normalize_tcp_cleanup(s);
3628 REASON_SET(&reason, PFRES_STATEINS);
3629 pf_src_tree_remove_state(s);
3630 STATE_DEC_COUNTERS(s);
3631 uma_zfree(V_pf_state_z, s);
3632 return (PF_DROP);
3633 } else
3634 *sm = s;
3635
3636 if (tag > 0)
3637 s->tag = tag;
3638 if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
3639 TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
3640 s->src.state = PF_TCPS_PROXY_SRC;
3641 /* undo NAT changes, if they have taken place */
3642 if (nr != NULL) {
3643 struct pf_state_key *skt = s->key[PF_SK_WIRE];
3644 if (pd->dir == PF_OUT)
3645 skt = s->key[PF_SK_STACK];
3646 PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
3647 PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
3648 if (pd->sport)
3649 *pd->sport = skt->port[pd->sidx];
3650 if (pd->dport)
3651 *pd->dport = skt->port[pd->didx];
3652 if (pd->proto_sum)
3653 *pd->proto_sum = bproto_sum;
3654 if (pd->ip_sum)
3655 *pd->ip_sum = bip_sum;
3656 m_copyback(m, off, hdrlen, pd->hdr.any);
3657 }
3658 s->src.seqhi = htonl(arc4random());
3659 /* Find mss option */
3660 int rtid = M_GETFIB(m);
3661 mss = pf_get_mss(m, off, th->th_off, pd->af);
3662 mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
3663 mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
3664 s->src.mss = mss;
3665 pf_send_tcp(NULL, r, pd->af, pd->dst, pd->src, th->th_dport,
3666 th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3667 TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL);
3668 REASON_SET(&reason, PFRES_SYNPROXY);
3669 return (PF_SYNPROXY_DROP);
3670 }
3671
3672 return (PF_PASS);
3673
3674csfailed:
3675 if (sk != NULL)
3676 uma_zfree(V_pf_state_key_z, sk);
3677 if (nk != NULL)
3678 uma_zfree(V_pf_state_key_z, nk);
3679
3566 }
3567 if (pd->proto == IPPROTO_TCP) {
3568 if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3569 off, pd, th, &s->src, &s->dst)) {
3570 REASON_SET(&reason, PFRES_MEMORY);
3571 pf_src_tree_remove_state(s);
3572 STATE_DEC_COUNTERS(s);
3573 uma_zfree(V_pf_state_z, s);
3574 return (PF_DROP);
3575 }
3576 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3577 pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3578 &s->src, &s->dst, rewrite)) {
3579 /* This really shouldn't happen!!! */
3580 DPFPRINTF(PF_DEBUG_URGENT,
3581 ("pf_normalize_tcp_stateful failed on first pkt"));
3582 pf_normalize_tcp_cleanup(s);
3583 pf_src_tree_remove_state(s);
3584 STATE_DEC_COUNTERS(s);
3585 uma_zfree(V_pf_state_z, s);
3586 return (PF_DROP);
3587 }
3588 }
3589 s->direction = pd->dir;
3590
3591 /*
3592 * sk/nk could already been setup by pf_get_translation().
3593 */
3594 if (nr == NULL) {
3595 KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
3596 __func__, nr, sk, nk));
3597 sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
3598 if (sk == NULL)
3599 goto csfailed;
3600 nk = sk;
3601 } else
3602 KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
3603 __func__, nr, sk, nk));
3604
3605 /* Swap sk/nk for PF_OUT. */
3606 if (pf_state_insert(BOUND_IFACE(r, kif),
3607 (pd->dir == PF_IN) ? sk : nk,
3608 (pd->dir == PF_IN) ? nk : sk, s)) {
3609 if (pd->proto == IPPROTO_TCP)
3610 pf_normalize_tcp_cleanup(s);
3611 REASON_SET(&reason, PFRES_STATEINS);
3612 pf_src_tree_remove_state(s);
3613 STATE_DEC_COUNTERS(s);
3614 uma_zfree(V_pf_state_z, s);
3615 return (PF_DROP);
3616 } else
3617 *sm = s;
3618
3619 if (tag > 0)
3620 s->tag = tag;
3621 if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
3622 TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
3623 s->src.state = PF_TCPS_PROXY_SRC;
3624 /* undo NAT changes, if they have taken place */
3625 if (nr != NULL) {
3626 struct pf_state_key *skt = s->key[PF_SK_WIRE];
3627 if (pd->dir == PF_OUT)
3628 skt = s->key[PF_SK_STACK];
3629 PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
3630 PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
3631 if (pd->sport)
3632 *pd->sport = skt->port[pd->sidx];
3633 if (pd->dport)
3634 *pd->dport = skt->port[pd->didx];
3635 if (pd->proto_sum)
3636 *pd->proto_sum = bproto_sum;
3637 if (pd->ip_sum)
3638 *pd->ip_sum = bip_sum;
3639 m_copyback(m, off, hdrlen, pd->hdr.any);
3640 }
3641 s->src.seqhi = htonl(arc4random());
3642 /* Find mss option */
3643 int rtid = M_GETFIB(m);
3644 mss = pf_get_mss(m, off, th->th_off, pd->af);
3645 mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
3646 mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
3647 s->src.mss = mss;
3648 pf_send_tcp(NULL, r, pd->af, pd->dst, pd->src, th->th_dport,
3649 th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3650 TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL);
3651 REASON_SET(&reason, PFRES_SYNPROXY);
3652 return (PF_SYNPROXY_DROP);
3653 }
3654
3655 return (PF_PASS);
3656
3657csfailed:
3658 if (sk != NULL)
3659 uma_zfree(V_pf_state_key_z, sk);
3660 if (nk != NULL)
3661 uma_zfree(V_pf_state_key_z, nk);
3662
3680 if (sn != NULL && sn->states == 0 && sn->expire == 0) {
3681 pf_unlink_src_node(sn);
3682 pf_free_src_node(sn);
3663 if (sn != NULL) {
3664 struct pf_srchash *sh;
3665
3666 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
3667 PF_HASHROW_LOCK(sh);
3668 if (--sn->states == 0 && sn->expire == 0) {
3669 pf_unlink_src_node(sn);
3670 uma_zfree(V_pf_sources_z, sn);
3671 counter_u64_add(
3672 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3673 }
3674 PF_HASHROW_UNLOCK(sh);
3683 }
3684
3675 }
3676
3685 if (nsn != sn && nsn != NULL && nsn->states == 0 && nsn->expire == 0) {
3686 pf_unlink_src_node(nsn);
3687 pf_free_src_node(nsn);
3677 if (nsn != sn && nsn != NULL) {
3678 struct pf_srchash *sh;
3679
3680 sh = &V_pf_srchash[pf_hashsrc(&nsn->addr, nsn->af)];
3681 PF_HASHROW_LOCK(sh);
3682 if (--nsn->states == 1 && nsn->expire == 0) {
3683 pf_unlink_src_node(nsn);
3684 uma_zfree(V_pf_sources_z, nsn);
3685 counter_u64_add(
3686 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3687 }
3688 PF_HASHROW_UNLOCK(sh);
3688 }
3689
3690 return (PF_DROP);
3691}
3692
3693static int
3694pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3695 struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3696 struct pf_ruleset **rsm)
3697{
3698 struct pf_rule *r, *a = NULL;
3699 struct pf_ruleset *ruleset = NULL;
3700 sa_family_t af = pd->af;
3701 u_short reason;
3702 int tag = -1;
3703 int asd = 0;
3704 int match = 0;
3705 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3706
3707 PF_RULES_RASSERT();
3708
3709 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3710 while (r != NULL) {
3711 r->evaluations++;
3712 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3713 r = r->skip[PF_SKIP_IFP].ptr;
3714 else if (r->direction && r->direction != direction)
3715 r = r->skip[PF_SKIP_DIR].ptr;
3716 else if (r->af && r->af != af)
3717 r = r->skip[PF_SKIP_AF].ptr;
3718 else if (r->proto && r->proto != pd->proto)
3719 r = r->skip[PF_SKIP_PROTO].ptr;
3720 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3721 r->src.neg, kif, M_GETFIB(m)))
3722 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3723 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3724 r->dst.neg, NULL, M_GETFIB(m)))
3725 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3726 else if (r->tos && !(r->tos == pd->tos))
3727 r = TAILQ_NEXT(r, entries);
3728 else if (r->os_fingerprint != PF_OSFP_ANY)
3729 r = TAILQ_NEXT(r, entries);
3730 else if (pd->proto == IPPROTO_UDP &&
3731 (r->src.port_op || r->dst.port_op))
3732 r = TAILQ_NEXT(r, entries);
3733 else if (pd->proto == IPPROTO_TCP &&
3734 (r->src.port_op || r->dst.port_op || r->flagset))
3735 r = TAILQ_NEXT(r, entries);
3736 else if ((pd->proto == IPPROTO_ICMP ||
3737 pd->proto == IPPROTO_ICMPV6) &&
3738 (r->type || r->code))
3739 r = TAILQ_NEXT(r, entries);
3740 else if (r->prob && r->prob <=
3741 (arc4random() % (UINT_MAX - 1) + 1))
3742 r = TAILQ_NEXT(r, entries);
3743 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3744 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3745 r = TAILQ_NEXT(r, entries);
3746 else {
3747 if (r->anchor == NULL) {
3748 match = 1;
3749 *rm = r;
3750 *am = a;
3751 *rsm = ruleset;
3752 if ((*rm)->quick)
3753 break;
3754 r = TAILQ_NEXT(r, entries);
3755 } else
3756 pf_step_into_anchor(anchor_stack, &asd,
3757 &ruleset, PF_RULESET_FILTER, &r, &a,
3758 &match);
3759 }
3760 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3761 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3762 break;
3763 }
3764 r = *rm;
3765 a = *am;
3766 ruleset = *rsm;
3767
3768 REASON_SET(&reason, PFRES_MATCH);
3769
3770 if (r->log)
3771 PFLOG_PACKET(kif, m, af, direction, reason, r, a, ruleset, pd,
3772 1);
3773
3774 if (r->action != PF_PASS)
3775 return (PF_DROP);
3776
3777 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3778 REASON_SET(&reason, PFRES_MEMORY);
3779 return (PF_DROP);
3780 }
3781
3782 return (PF_PASS);
3783}
3784
3785static int
3786pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
3787 struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
3788 struct pf_pdesc *pd, u_short *reason, int *copyback)
3789{
3790 struct tcphdr *th = pd->hdr.tcp;
3791 u_int16_t win = ntohs(th->th_win);
3792 u_int32_t ack, end, seq, orig_seq;
3793 u_int8_t sws, dws;
3794 int ackskew;
3795
3796 if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3797 sws = src->wscale & PF_WSCALE_MASK;
3798 dws = dst->wscale & PF_WSCALE_MASK;
3799 } else
3800 sws = dws = 0;
3801
3802 /*
3803 * Sequence tracking algorithm from Guido van Rooij's paper:
3804 * http://www.madison-gurkha.com/publications/tcp_filtering/
3805 * tcp_filtering.ps
3806 */
3807
3808 orig_seq = seq = ntohl(th->th_seq);
3809 if (src->seqlo == 0) {
3810 /* First packet from this end. Set its state */
3811
3812 if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
3813 src->scrub == NULL) {
3814 if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
3815 REASON_SET(reason, PFRES_MEMORY);
3816 return (PF_DROP);
3817 }
3818 }
3819
3820 /* Deferred generation of sequence number modulator */
3821 if (dst->seqdiff && !src->seqdiff) {
3822 /* use random iss for the TCP server */
3823 while ((src->seqdiff = arc4random() - seq) == 0)
3824 ;
3825 ack = ntohl(th->th_ack) - dst->seqdiff;
3826 pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
3827 src->seqdiff), 0);
3828 pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
3829 *copyback = 1;
3830 } else {
3831 ack = ntohl(th->th_ack);
3832 }
3833
3834 end = seq + pd->p_len;
3835 if (th->th_flags & TH_SYN) {
3836 end++;
3837 if (dst->wscale & PF_WSCALE_FLAG) {
3838 src->wscale = pf_get_wscale(m, off, th->th_off,
3839 pd->af);
3840 if (src->wscale & PF_WSCALE_FLAG) {
3841 /* Remove scale factor from initial
3842 * window */
3843 sws = src->wscale & PF_WSCALE_MASK;
3844 win = ((u_int32_t)win + (1 << sws) - 1)
3845 >> sws;
3846 dws = dst->wscale & PF_WSCALE_MASK;
3847 } else {
3848 /* fixup other window */
3849 dst->max_win <<= dst->wscale &
3850 PF_WSCALE_MASK;
3851 /* in case of a retrans SYN|ACK */
3852 dst->wscale = 0;
3853 }
3854 }
3855 }
3856 if (th->th_flags & TH_FIN)
3857 end++;
3858
3859 src->seqlo = seq;
3860 if (src->state < TCPS_SYN_SENT)
3861 src->state = TCPS_SYN_SENT;
3862
3863 /*
3864 * May need to slide the window (seqhi may have been set by
3865 * the crappy stack check or if we picked up the connection
3866 * after establishment)
3867 */
3868 if (src->seqhi == 1 ||
3869 SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
3870 src->seqhi = end + MAX(1, dst->max_win << dws);
3871 if (win > src->max_win)
3872 src->max_win = win;
3873
3874 } else {
3875 ack = ntohl(th->th_ack) - dst->seqdiff;
3876 if (src->seqdiff) {
3877 /* Modulate sequence numbers */
3878 pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
3879 src->seqdiff), 0);
3880 pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
3881 *copyback = 1;
3882 }
3883 end = seq + pd->p_len;
3884 if (th->th_flags & TH_SYN)
3885 end++;
3886 if (th->th_flags & TH_FIN)
3887 end++;
3888 }
3889
3890 if ((th->th_flags & TH_ACK) == 0) {
3891 /* Let it pass through the ack skew check */
3892 ack = dst->seqlo;
3893 } else if ((ack == 0 &&
3894 (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
3895 /* broken tcp stacks do not set ack */
3896 (dst->state < TCPS_SYN_SENT)) {
3897 /*
3898 * Many stacks (ours included) will set the ACK number in an
3899 * FIN|ACK if the SYN times out -- no sequence to ACK.
3900 */
3901 ack = dst->seqlo;
3902 }
3903
3904 if (seq == end) {
3905 /* Ease sequencing restrictions on no data packets */
3906 seq = src->seqlo;
3907 end = seq;
3908 }
3909
3910 ackskew = dst->seqlo - ack;
3911
3912
3913 /*
3914 * Need to demodulate the sequence numbers in any TCP SACK options
3915 * (Selective ACK). We could optionally validate the SACK values
3916 * against the current ACK window, either forwards or backwards, but
3917 * I'm not confident that SACK has been implemented properly
3918 * everywhere. It wouldn't surprise me if several stacks accidently
3919 * SACK too far backwards of previously ACKed data. There really aren't
3920 * any security implications of bad SACKing unless the target stack
3921 * doesn't validate the option length correctly. Someone trying to
3922 * spoof into a TCP connection won't bother blindly sending SACK
3923 * options anyway.
3924 */
3925 if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
3926 if (pf_modulate_sack(m, off, pd, th, dst))
3927 *copyback = 1;
3928 }
3929
3930
3931#define MAXACKWINDOW (0xffff + 1500) /* 1500 is an arbitrary fudge factor */
3932 if (SEQ_GEQ(src->seqhi, end) &&
3933 /* Last octet inside other's window space */
3934 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
3935 /* Retrans: not more than one window back */
3936 (ackskew >= -MAXACKWINDOW) &&
3937 /* Acking not more than one reassembled fragment backwards */
3938 (ackskew <= (MAXACKWINDOW << sws)) &&
3939 /* Acking not more than one window forward */
3940 ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
3941 (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
3942 (pd->flags & PFDESC_IP_REAS) == 0)) {
3943 /* Require an exact/+1 sequence match on resets when possible */
3944
3945 if (dst->scrub || src->scrub) {
3946 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
3947 *state, src, dst, copyback))
3948 return (PF_DROP);
3949 }
3950
3951 /* update max window */
3952 if (src->max_win < win)
3953 src->max_win = win;
3954 /* synchronize sequencing */
3955 if (SEQ_GT(end, src->seqlo))
3956 src->seqlo = end;
3957 /* slide the window of what the other end can send */
3958 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
3959 dst->seqhi = ack + MAX((win << sws), 1);
3960
3961
3962 /* update states */
3963 if (th->th_flags & TH_SYN)
3964 if (src->state < TCPS_SYN_SENT)
3965 src->state = TCPS_SYN_SENT;
3966 if (th->th_flags & TH_FIN)
3967 if (src->state < TCPS_CLOSING)
3968 src->state = TCPS_CLOSING;
3969 if (th->th_flags & TH_ACK) {
3970 if (dst->state == TCPS_SYN_SENT) {
3971 dst->state = TCPS_ESTABLISHED;
3972 if (src->state == TCPS_ESTABLISHED &&
3973 (*state)->src_node != NULL &&
3974 pf_src_connlimit(state)) {
3975 REASON_SET(reason, PFRES_SRCLIMIT);
3976 return (PF_DROP);
3977 }
3978 } else if (dst->state == TCPS_CLOSING)
3979 dst->state = TCPS_FIN_WAIT_2;
3980 }
3981 if (th->th_flags & TH_RST)
3982 src->state = dst->state = TCPS_TIME_WAIT;
3983
3984 /* update expire time */
3985 (*state)->expire = time_uptime;
3986 if (src->state >= TCPS_FIN_WAIT_2 &&
3987 dst->state >= TCPS_FIN_WAIT_2)
3988 (*state)->timeout = PFTM_TCP_CLOSED;
3989 else if (src->state >= TCPS_CLOSING &&
3990 dst->state >= TCPS_CLOSING)
3991 (*state)->timeout = PFTM_TCP_FIN_WAIT;
3992 else if (src->state < TCPS_ESTABLISHED ||
3993 dst->state < TCPS_ESTABLISHED)
3994 (*state)->timeout = PFTM_TCP_OPENING;
3995 else if (src->state >= TCPS_CLOSING ||
3996 dst->state >= TCPS_CLOSING)
3997 (*state)->timeout = PFTM_TCP_CLOSING;
3998 else
3999 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4000
4001 /* Fall through to PASS packet */
4002
4003 } else if ((dst->state < TCPS_SYN_SENT ||
4004 dst->state >= TCPS_FIN_WAIT_2 ||
4005 src->state >= TCPS_FIN_WAIT_2) &&
4006 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
4007 /* Within a window forward of the originating packet */
4008 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
4009 /* Within a window backward of the originating packet */
4010
4011 /*
4012 * This currently handles three situations:
4013 * 1) Stupid stacks will shotgun SYNs before their peer
4014 * replies.
4015 * 2) When PF catches an already established stream (the
4016 * firewall rebooted, the state table was flushed, routes
4017 * changed...)
4018 * 3) Packets get funky immediately after the connection
4019 * closes (this should catch Solaris spurious ACK|FINs
4020 * that web servers like to spew after a close)
4021 *
4022 * This must be a little more careful than the above code
4023 * since packet floods will also be caught here. We don't
4024 * update the TTL here to mitigate the damage of a packet
4025 * flood and so the same code can handle awkward establishment
4026 * and a loosened connection close.
4027 * In the establishment case, a correct peer response will
4028 * validate the connection, go through the normal state code
4029 * and keep updating the state TTL.
4030 */
4031
4032 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4033 printf("pf: loose state match: ");
4034 pf_print_state(*state);
4035 pf_print_flags(th->th_flags);
4036 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4037 "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
4038 pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
4039 (unsigned long long)(*state)->packets[1],
4040 pd->dir == PF_IN ? "in" : "out",
4041 pd->dir == (*state)->direction ? "fwd" : "rev");
4042 }
4043
4044 if (dst->scrub || src->scrub) {
4045 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4046 *state, src, dst, copyback))
4047 return (PF_DROP);
4048 }
4049
4050 /* update max window */
4051 if (src->max_win < win)
4052 src->max_win = win;
4053 /* synchronize sequencing */
4054 if (SEQ_GT(end, src->seqlo))
4055 src->seqlo = end;
4056 /* slide the window of what the other end can send */
4057 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4058 dst->seqhi = ack + MAX((win << sws), 1);
4059
4060 /*
4061 * Cannot set dst->seqhi here since this could be a shotgunned
4062 * SYN and not an already established connection.
4063 */
4064
4065 if (th->th_flags & TH_FIN)
4066 if (src->state < TCPS_CLOSING)
4067 src->state = TCPS_CLOSING;
4068 if (th->th_flags & TH_RST)
4069 src->state = dst->state = TCPS_TIME_WAIT;
4070
4071 /* Fall through to PASS packet */
4072
4073 } else {
4074 if ((*state)->dst.state == TCPS_SYN_SENT &&
4075 (*state)->src.state == TCPS_SYN_SENT) {
4076 /* Send RST for state mismatches during handshake */
4077 if (!(th->th_flags & TH_RST))
4078 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4079 pd->dst, pd->src, th->th_dport,
4080 th->th_sport, ntohl(th->th_ack), 0,
4081 TH_RST, 0, 0,
4082 (*state)->rule.ptr->return_ttl, 1, 0,
4083 kif->pfik_ifp);
4084 src->seqlo = 0;
4085 src->seqhi = 1;
4086 src->max_win = 1;
4087 } else if (V_pf_status.debug >= PF_DEBUG_MISC) {
4088 printf("pf: BAD state: ");
4089 pf_print_state(*state);
4090 pf_print_flags(th->th_flags);
4091 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4092 "pkts=%llu:%llu dir=%s,%s\n",
4093 seq, orig_seq, ack, pd->p_len, ackskew,
4094 (unsigned long long)(*state)->packets[0],
4095 (unsigned long long)(*state)->packets[1],
4096 pd->dir == PF_IN ? "in" : "out",
4097 pd->dir == (*state)->direction ? "fwd" : "rev");
4098 printf("pf: State failure on: %c %c %c %c | %c %c\n",
4099 SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4100 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4101 ' ': '2',
4102 (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4103 (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4104 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4105 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4106 }
4107 REASON_SET(reason, PFRES_BADSTATE);
4108 return (PF_DROP);
4109 }
4110
4111 return (PF_PASS);
4112}
4113
4114static int
4115pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4116 struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4117{
4118 struct tcphdr *th = pd->hdr.tcp;
4119
4120 if (th->th_flags & TH_SYN)
4121 if (src->state < TCPS_SYN_SENT)
4122 src->state = TCPS_SYN_SENT;
4123 if (th->th_flags & TH_FIN)
4124 if (src->state < TCPS_CLOSING)
4125 src->state = TCPS_CLOSING;
4126 if (th->th_flags & TH_ACK) {
4127 if (dst->state == TCPS_SYN_SENT) {
4128 dst->state = TCPS_ESTABLISHED;
4129 if (src->state == TCPS_ESTABLISHED &&
4130 (*state)->src_node != NULL &&
4131 pf_src_connlimit(state)) {
4132 REASON_SET(reason, PFRES_SRCLIMIT);
4133 return (PF_DROP);
4134 }
4135 } else if (dst->state == TCPS_CLOSING) {
4136 dst->state = TCPS_FIN_WAIT_2;
4137 } else if (src->state == TCPS_SYN_SENT &&
4138 dst->state < TCPS_SYN_SENT) {
4139 /*
4140 * Handle a special sloppy case where we only see one
4141 * half of the connection. If there is a ACK after
4142 * the initial SYN without ever seeing a packet from
4143 * the destination, set the connection to established.
4144 */
4145 dst->state = src->state = TCPS_ESTABLISHED;
4146 if ((*state)->src_node != NULL &&
4147 pf_src_connlimit(state)) {
4148 REASON_SET(reason, PFRES_SRCLIMIT);
4149 return (PF_DROP);
4150 }
4151 } else if (src->state == TCPS_CLOSING &&
4152 dst->state == TCPS_ESTABLISHED &&
4153 dst->seqlo == 0) {
4154 /*
4155 * Handle the closing of half connections where we
4156 * don't see the full bidirectional FIN/ACK+ACK
4157 * handshake.
4158 */
4159 dst->state = TCPS_CLOSING;
4160 }
4161 }
4162 if (th->th_flags & TH_RST)
4163 src->state = dst->state = TCPS_TIME_WAIT;
4164
4165 /* update expire time */
4166 (*state)->expire = time_uptime;
4167 if (src->state >= TCPS_FIN_WAIT_2 &&
4168 dst->state >= TCPS_FIN_WAIT_2)
4169 (*state)->timeout = PFTM_TCP_CLOSED;
4170 else if (src->state >= TCPS_CLOSING &&
4171 dst->state >= TCPS_CLOSING)
4172 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4173 else if (src->state < TCPS_ESTABLISHED ||
4174 dst->state < TCPS_ESTABLISHED)
4175 (*state)->timeout = PFTM_TCP_OPENING;
4176 else if (src->state >= TCPS_CLOSING ||
4177 dst->state >= TCPS_CLOSING)
4178 (*state)->timeout = PFTM_TCP_CLOSING;
4179 else
4180 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4181
4182 return (PF_PASS);
4183}
4184
4185static int
4186pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4187 struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4188 u_short *reason)
4189{
4190 struct pf_state_key_cmp key;
4191 struct tcphdr *th = pd->hdr.tcp;
4192 int copyback = 0;
4193 struct pf_state_peer *src, *dst;
4194 struct pf_state_key *sk;
4195
4196 bzero(&key, sizeof(key));
4197 key.af = pd->af;
4198 key.proto = IPPROTO_TCP;
4199 if (direction == PF_IN) { /* wire side, straight */
4200 PF_ACPY(&key.addr[0], pd->src, key.af);
4201 PF_ACPY(&key.addr[1], pd->dst, key.af);
4202 key.port[0] = th->th_sport;
4203 key.port[1] = th->th_dport;
4204 } else { /* stack side, reverse */
4205 PF_ACPY(&key.addr[1], pd->src, key.af);
4206 PF_ACPY(&key.addr[0], pd->dst, key.af);
4207 key.port[1] = th->th_sport;
4208 key.port[0] = th->th_dport;
4209 }
4210
4211 STATE_LOOKUP(kif, &key, direction, *state, pd);
4212
4213 if (direction == (*state)->direction) {
4214 src = &(*state)->src;
4215 dst = &(*state)->dst;
4216 } else {
4217 src = &(*state)->dst;
4218 dst = &(*state)->src;
4219 }
4220
4221 sk = (*state)->key[pd->didx];
4222
4223 if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4224 if (direction != (*state)->direction) {
4225 REASON_SET(reason, PFRES_SYNPROXY);
4226 return (PF_SYNPROXY_DROP);
4227 }
4228 if (th->th_flags & TH_SYN) {
4229 if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4230 REASON_SET(reason, PFRES_SYNPROXY);
4231 return (PF_DROP);
4232 }
4233 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4234 pd->src, th->th_dport, th->th_sport,
4235 (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4236 TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1, 0, NULL);
4237 REASON_SET(reason, PFRES_SYNPROXY);
4238 return (PF_SYNPROXY_DROP);
4239 } else if (!(th->th_flags & TH_ACK) ||
4240 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4241 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4242 REASON_SET(reason, PFRES_SYNPROXY);
4243 return (PF_DROP);
4244 } else if ((*state)->src_node != NULL &&
4245 pf_src_connlimit(state)) {
4246 REASON_SET(reason, PFRES_SRCLIMIT);
4247 return (PF_DROP);
4248 } else
4249 (*state)->src.state = PF_TCPS_PROXY_DST;
4250 }
4251 if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4252 if (direction == (*state)->direction) {
4253 if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4254 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4255 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4256 REASON_SET(reason, PFRES_SYNPROXY);
4257 return (PF_DROP);
4258 }
4259 (*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4260 if ((*state)->dst.seqhi == 1)
4261 (*state)->dst.seqhi = htonl(arc4random());
4262 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4263 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4264 sk->port[pd->sidx], sk->port[pd->didx],
4265 (*state)->dst.seqhi, 0, TH_SYN, 0,
4266 (*state)->src.mss, 0, 0, (*state)->tag, NULL);
4267 REASON_SET(reason, PFRES_SYNPROXY);
4268 return (PF_SYNPROXY_DROP);
4269 } else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4270 (TH_SYN|TH_ACK)) ||
4271 (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4272 REASON_SET(reason, PFRES_SYNPROXY);
4273 return (PF_DROP);
4274 } else {
4275 (*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4276 (*state)->dst.seqlo = ntohl(th->th_seq);
4277 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4278 pd->src, th->th_dport, th->th_sport,
4279 ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4280 TH_ACK, (*state)->src.max_win, 0, 0, 0,
4281 (*state)->tag, NULL);
4282 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4283 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4284 sk->port[pd->sidx], sk->port[pd->didx],
4285 (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4286 TH_ACK, (*state)->dst.max_win, 0, 0, 1, 0, NULL);
4287 (*state)->src.seqdiff = (*state)->dst.seqhi -
4288 (*state)->src.seqlo;
4289 (*state)->dst.seqdiff = (*state)->src.seqhi -
4290 (*state)->dst.seqlo;
4291 (*state)->src.seqhi = (*state)->src.seqlo +
4292 (*state)->dst.max_win;
4293 (*state)->dst.seqhi = (*state)->dst.seqlo +
4294 (*state)->src.max_win;
4295 (*state)->src.wscale = (*state)->dst.wscale = 0;
4296 (*state)->src.state = (*state)->dst.state =
4297 TCPS_ESTABLISHED;
4298 REASON_SET(reason, PFRES_SYNPROXY);
4299 return (PF_SYNPROXY_DROP);
4300 }
4301 }
4302
4303 if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4304 dst->state >= TCPS_FIN_WAIT_2 &&
4305 src->state >= TCPS_FIN_WAIT_2) {
4306 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4307 printf("pf: state reuse ");
4308 pf_print_state(*state);
4309 pf_print_flags(th->th_flags);
4310 printf("\n");
4311 }
4312 /* XXX make sure it's the same direction ?? */
4313 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4314 pf_unlink_state(*state, PF_ENTER_LOCKED);
4315 *state = NULL;
4316 return (PF_DROP);
4317 }
4318
4319 if ((*state)->state_flags & PFSTATE_SLOPPY) {
4320 if (pf_tcp_track_sloppy(src, dst, state, pd, reason) == PF_DROP)
4321 return (PF_DROP);
4322 } else {
4323 if (pf_tcp_track_full(src, dst, state, kif, m, off, pd, reason,
4324 &copyback) == PF_DROP)
4325 return (PF_DROP);
4326 }
4327
4328 /* translate source/destination address, if necessary */
4329 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4330 struct pf_state_key *nk = (*state)->key[pd->didx];
4331
4332 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4333 nk->port[pd->sidx] != th->th_sport)
4334 pf_change_ap(pd->src, &th->th_sport, pd->ip_sum,
4335 &th->th_sum, &nk->addr[pd->sidx],
4336 nk->port[pd->sidx], 0, pd->af);
4337
4338 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4339 nk->port[pd->didx] != th->th_dport)
4340 pf_change_ap(pd->dst, &th->th_dport, pd->ip_sum,
4341 &th->th_sum, &nk->addr[pd->didx],
4342 nk->port[pd->didx], 0, pd->af);
4343 copyback = 1;
4344 }
4345
4346 /* Copyback sequence modulation or stateful scrub changes if needed */
4347 if (copyback)
4348 m_copyback(m, off, sizeof(*th), (caddr_t)th);
4349
4350 return (PF_PASS);
4351}
4352
4353static int
4354pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4355 struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4356{
4357 struct pf_state_peer *src, *dst;
4358 struct pf_state_key_cmp key;
4359 struct udphdr *uh = pd->hdr.udp;
4360
4361 bzero(&key, sizeof(key));
4362 key.af = pd->af;
4363 key.proto = IPPROTO_UDP;
4364 if (direction == PF_IN) { /* wire side, straight */
4365 PF_ACPY(&key.addr[0], pd->src, key.af);
4366 PF_ACPY(&key.addr[1], pd->dst, key.af);
4367 key.port[0] = uh->uh_sport;
4368 key.port[1] = uh->uh_dport;
4369 } else { /* stack side, reverse */
4370 PF_ACPY(&key.addr[1], pd->src, key.af);
4371 PF_ACPY(&key.addr[0], pd->dst, key.af);
4372 key.port[1] = uh->uh_sport;
4373 key.port[0] = uh->uh_dport;
4374 }
4375
4376 STATE_LOOKUP(kif, &key, direction, *state, pd);
4377
4378 if (direction == (*state)->direction) {
4379 src = &(*state)->src;
4380 dst = &(*state)->dst;
4381 } else {
4382 src = &(*state)->dst;
4383 dst = &(*state)->src;
4384 }
4385
4386 /* update states */
4387 if (src->state < PFUDPS_SINGLE)
4388 src->state = PFUDPS_SINGLE;
4389 if (dst->state == PFUDPS_SINGLE)
4390 dst->state = PFUDPS_MULTIPLE;
4391
4392 /* update expire time */
4393 (*state)->expire = time_uptime;
4394 if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4395 (*state)->timeout = PFTM_UDP_MULTIPLE;
4396 else
4397 (*state)->timeout = PFTM_UDP_SINGLE;
4398
4399 /* translate source/destination address, if necessary */
4400 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4401 struct pf_state_key *nk = (*state)->key[pd->didx];
4402
4403 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4404 nk->port[pd->sidx] != uh->uh_sport)
4405 pf_change_ap(pd->src, &uh->uh_sport, pd->ip_sum,
4406 &uh->uh_sum, &nk->addr[pd->sidx],
4407 nk->port[pd->sidx], 1, pd->af);
4408
4409 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4410 nk->port[pd->didx] != uh->uh_dport)
4411 pf_change_ap(pd->dst, &uh->uh_dport, pd->ip_sum,
4412 &uh->uh_sum, &nk->addr[pd->didx],
4413 nk->port[pd->didx], 1, pd->af);
4414 m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4415 }
4416
4417 return (PF_PASS);
4418}
4419
4420static int
4421pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4422 struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
4423{
4424 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
4425 u_int16_t icmpid = 0, *icmpsum;
4426 u_int8_t icmptype;
4427 int state_icmp = 0;
4428 struct pf_state_key_cmp key;
4429
4430 bzero(&key, sizeof(key));
4431 switch (pd->proto) {
4432#ifdef INET
4433 case IPPROTO_ICMP:
4434 icmptype = pd->hdr.icmp->icmp_type;
4435 icmpid = pd->hdr.icmp->icmp_id;
4436 icmpsum = &pd->hdr.icmp->icmp_cksum;
4437
4438 if (icmptype == ICMP_UNREACH ||
4439 icmptype == ICMP_SOURCEQUENCH ||
4440 icmptype == ICMP_REDIRECT ||
4441 icmptype == ICMP_TIMXCEED ||
4442 icmptype == ICMP_PARAMPROB)
4443 state_icmp++;
4444 break;
4445#endif /* INET */
4446#ifdef INET6
4447 case IPPROTO_ICMPV6:
4448 icmptype = pd->hdr.icmp6->icmp6_type;
4449 icmpid = pd->hdr.icmp6->icmp6_id;
4450 icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4451
4452 if (icmptype == ICMP6_DST_UNREACH ||
4453 icmptype == ICMP6_PACKET_TOO_BIG ||
4454 icmptype == ICMP6_TIME_EXCEEDED ||
4455 icmptype == ICMP6_PARAM_PROB)
4456 state_icmp++;
4457 break;
4458#endif /* INET6 */
4459 }
4460
4461 if (!state_icmp) {
4462
4463 /*
4464 * ICMP query/reply message not related to a TCP/UDP packet.
4465 * Search for an ICMP state.
4466 */
4467 key.af = pd->af;
4468 key.proto = pd->proto;
4469 key.port[0] = key.port[1] = icmpid;
4470 if (direction == PF_IN) { /* wire side, straight */
4471 PF_ACPY(&key.addr[0], pd->src, key.af);
4472 PF_ACPY(&key.addr[1], pd->dst, key.af);
4473 } else { /* stack side, reverse */
4474 PF_ACPY(&key.addr[1], pd->src, key.af);
4475 PF_ACPY(&key.addr[0], pd->dst, key.af);
4476 }
4477
4478 STATE_LOOKUP(kif, &key, direction, *state, pd);
4479
4480 (*state)->expire = time_uptime;
4481 (*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4482
4483 /* translate source/destination address, if necessary */
4484 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4485 struct pf_state_key *nk = (*state)->key[pd->didx];
4486
4487 switch (pd->af) {
4488#ifdef INET
4489 case AF_INET:
4490 if (PF_ANEQ(pd->src,
4491 &nk->addr[pd->sidx], AF_INET))
4492 pf_change_a(&saddr->v4.s_addr,
4493 pd->ip_sum,
4494 nk->addr[pd->sidx].v4.s_addr, 0);
4495
4496 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
4497 AF_INET))
4498 pf_change_a(&daddr->v4.s_addr,
4499 pd->ip_sum,
4500 nk->addr[pd->didx].v4.s_addr, 0);
4501
4502 if (nk->port[0] !=
4503 pd->hdr.icmp->icmp_id) {
4504 pd->hdr.icmp->icmp_cksum =
4505 pf_cksum_fixup(
4506 pd->hdr.icmp->icmp_cksum, icmpid,
4507 nk->port[pd->sidx], 0);
4508 pd->hdr.icmp->icmp_id =
4509 nk->port[pd->sidx];
4510 }
4511
4512 m_copyback(m, off, ICMP_MINLEN,
4513 (caddr_t )pd->hdr.icmp);
4514 break;
4515#endif /* INET */
4516#ifdef INET6
4517 case AF_INET6:
4518 if (PF_ANEQ(pd->src,
4519 &nk->addr[pd->sidx], AF_INET6))
4520 pf_change_a6(saddr,
4521 &pd->hdr.icmp6->icmp6_cksum,
4522 &nk->addr[pd->sidx], 0);
4523
4524 if (PF_ANEQ(pd->dst,
4525 &nk->addr[pd->didx], AF_INET6))
4526 pf_change_a6(daddr,
4527 &pd->hdr.icmp6->icmp6_cksum,
4528 &nk->addr[pd->didx], 0);
4529
4530 m_copyback(m, off, sizeof(struct icmp6_hdr),
4531 (caddr_t )pd->hdr.icmp6);
4532 break;
4533#endif /* INET6 */
4534 }
4535 }
4536 return (PF_PASS);
4537
4538 } else {
4539 /*
4540 * ICMP error message in response to a TCP/UDP packet.
4541 * Extract the inner TCP/UDP header and search for that state.
4542 */
4543
4544 struct pf_pdesc pd2;
4545 bzero(&pd2, sizeof pd2);
4546#ifdef INET
4547 struct ip h2;
4548#endif /* INET */
4549#ifdef INET6
4550 struct ip6_hdr h2_6;
4551 int terminal = 0;
4552#endif /* INET6 */
4553 int ipoff2 = 0;
4554 int off2 = 0;
4555
4556 pd2.af = pd->af;
4557 /* Payload packet is from the opposite direction. */
4558 pd2.sidx = (direction == PF_IN) ? 1 : 0;
4559 pd2.didx = (direction == PF_IN) ? 0 : 1;
4560 switch (pd->af) {
4561#ifdef INET
4562 case AF_INET:
4563 /* offset of h2 in mbuf chain */
4564 ipoff2 = off + ICMP_MINLEN;
4565
4566 if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
4567 NULL, reason, pd2.af)) {
4568 DPFPRINTF(PF_DEBUG_MISC,
4569 ("pf: ICMP error message too short "
4570 "(ip)\n"));
4571 return (PF_DROP);
4572 }
4573 /*
4574 * ICMP error messages don't refer to non-first
4575 * fragments
4576 */
4577 if (h2.ip_off & htons(IP_OFFMASK)) {
4578 REASON_SET(reason, PFRES_FRAG);
4579 return (PF_DROP);
4580 }
4581
4582 /* offset of protocol header that follows h2 */
4583 off2 = ipoff2 + (h2.ip_hl << 2);
4584
4585 pd2.proto = h2.ip_p;
4586 pd2.src = (struct pf_addr *)&h2.ip_src;
4587 pd2.dst = (struct pf_addr *)&h2.ip_dst;
4588 pd2.ip_sum = &h2.ip_sum;
4589 break;
4590#endif /* INET */
4591#ifdef INET6
4592 case AF_INET6:
4593 ipoff2 = off + sizeof(struct icmp6_hdr);
4594
4595 if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
4596 NULL, reason, pd2.af)) {
4597 DPFPRINTF(PF_DEBUG_MISC,
4598 ("pf: ICMP error message too short "
4599 "(ip6)\n"));
4600 return (PF_DROP);
4601 }
4602 pd2.proto = h2_6.ip6_nxt;
4603 pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4604 pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4605 pd2.ip_sum = NULL;
4606 off2 = ipoff2 + sizeof(h2_6);
4607 do {
4608 switch (pd2.proto) {
4609 case IPPROTO_FRAGMENT:
4610 /*
4611 * ICMPv6 error messages for
4612 * non-first fragments
4613 */
4614 REASON_SET(reason, PFRES_FRAG);
4615 return (PF_DROP);
4616 case IPPROTO_AH:
4617 case IPPROTO_HOPOPTS:
4618 case IPPROTO_ROUTING:
4619 case IPPROTO_DSTOPTS: {
4620 /* get next header and header length */
4621 struct ip6_ext opt6;
4622
4623 if (!pf_pull_hdr(m, off2, &opt6,
4624 sizeof(opt6), NULL, reason,
4625 pd2.af)) {
4626 DPFPRINTF(PF_DEBUG_MISC,
4627 ("pf: ICMPv6 short opt\n"));
4628 return (PF_DROP);
4629 }
4630 if (pd2.proto == IPPROTO_AH)
4631 off2 += (opt6.ip6e_len + 2) * 4;
4632 else
4633 off2 += (opt6.ip6e_len + 1) * 8;
4634 pd2.proto = opt6.ip6e_nxt;
4635 /* goto the next header */
4636 break;
4637 }
4638 default:
4639 terminal++;
4640 break;
4641 }
4642 } while (!terminal);
4643 break;
4644#endif /* INET6 */
4645 }
4646
4647 switch (pd2.proto) {
4648 case IPPROTO_TCP: {
4649 struct tcphdr th;
4650 u_int32_t seq;
4651 struct pf_state_peer *src, *dst;
4652 u_int8_t dws;
4653 int copyback = 0;
4654
4655 /*
4656 * Only the first 8 bytes of the TCP header can be
4657 * expected. Don't access any TCP header fields after
4658 * th_seq, an ackskew test is not possible.
4659 */
4660 if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
4661 pd2.af)) {
4662 DPFPRINTF(PF_DEBUG_MISC,
4663 ("pf: ICMP error message too short "
4664 "(tcp)\n"));
4665 return (PF_DROP);
4666 }
4667
4668 key.af = pd2.af;
4669 key.proto = IPPROTO_TCP;
4670 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4671 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4672 key.port[pd2.sidx] = th.th_sport;
4673 key.port[pd2.didx] = th.th_dport;
4674
4675 STATE_LOOKUP(kif, &key, direction, *state, pd);
4676
4677 if (direction == (*state)->direction) {
4678 src = &(*state)->dst;
4679 dst = &(*state)->src;
4680 } else {
4681 src = &(*state)->src;
4682 dst = &(*state)->dst;
4683 }
4684
4685 if (src->wscale && dst->wscale)
4686 dws = dst->wscale & PF_WSCALE_MASK;
4687 else
4688 dws = 0;
4689
4690 /* Demodulate sequence number */
4691 seq = ntohl(th.th_seq) - src->seqdiff;
4692 if (src->seqdiff) {
4693 pf_change_a(&th.th_seq, icmpsum,
4694 htonl(seq), 0);
4695 copyback = 1;
4696 }
4697
4698 if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
4699 (!SEQ_GEQ(src->seqhi, seq) ||
4700 !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
4701 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4702 printf("pf: BAD ICMP %d:%d ",
4703 icmptype, pd->hdr.icmp->icmp_code);
4704 pf_print_host(pd->src, 0, pd->af);
4705 printf(" -> ");
4706 pf_print_host(pd->dst, 0, pd->af);
4707 printf(" state: ");
4708 pf_print_state(*state);
4709 printf(" seq=%u\n", seq);
4710 }
4711 REASON_SET(reason, PFRES_BADSTATE);
4712 return (PF_DROP);
4713 } else {
4714 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4715 printf("pf: OK ICMP %d:%d ",
4716 icmptype, pd->hdr.icmp->icmp_code);
4717 pf_print_host(pd->src, 0, pd->af);
4718 printf(" -> ");
4719 pf_print_host(pd->dst, 0, pd->af);
4720 printf(" state: ");
4721 pf_print_state(*state);
4722 printf(" seq=%u\n", seq);
4723 }
4724 }
4725
4726 /* translate source/destination address, if necessary */
4727 if ((*state)->key[PF_SK_WIRE] !=
4728 (*state)->key[PF_SK_STACK]) {
4729 struct pf_state_key *nk =
4730 (*state)->key[pd->didx];
4731
4732 if (PF_ANEQ(pd2.src,
4733 &nk->addr[pd2.sidx], pd2.af) ||
4734 nk->port[pd2.sidx] != th.th_sport)
4735 pf_change_icmp(pd2.src, &th.th_sport,
4736 daddr, &nk->addr[pd2.sidx],
4737 nk->port[pd2.sidx], NULL,
4738 pd2.ip_sum, icmpsum,
4739 pd->ip_sum, 0, pd2.af);
4740
4741 if (PF_ANEQ(pd2.dst,
4742 &nk->addr[pd2.didx], pd2.af) ||
4743 nk->port[pd2.didx] != th.th_dport)
4744 pf_change_icmp(pd2.dst, &th.th_dport,
4745 NULL, /* XXX Inbound NAT? */
4746 &nk->addr[pd2.didx],
4747 nk->port[pd2.didx], NULL,
4748 pd2.ip_sum, icmpsum,
4749 pd->ip_sum, 0, pd2.af);
4750 copyback = 1;
4751 }
4752
4753 if (copyback) {
4754 switch (pd2.af) {
4755#ifdef INET
4756 case AF_INET:
4757 m_copyback(m, off, ICMP_MINLEN,
4758 (caddr_t )pd->hdr.icmp);
4759 m_copyback(m, ipoff2, sizeof(h2),
4760 (caddr_t )&h2);
4761 break;
4762#endif /* INET */
4763#ifdef INET6
4764 case AF_INET6:
4765 m_copyback(m, off,
4766 sizeof(struct icmp6_hdr),
4767 (caddr_t )pd->hdr.icmp6);
4768 m_copyback(m, ipoff2, sizeof(h2_6),
4769 (caddr_t )&h2_6);
4770 break;
4771#endif /* INET6 */
4772 }
4773 m_copyback(m, off2, 8, (caddr_t)&th);
4774 }
4775
4776 return (PF_PASS);
4777 break;
4778 }
4779 case IPPROTO_UDP: {
4780 struct udphdr uh;
4781
4782 if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
4783 NULL, reason, pd2.af)) {
4784 DPFPRINTF(PF_DEBUG_MISC,
4785 ("pf: ICMP error message too short "
4786 "(udp)\n"));
4787 return (PF_DROP);
4788 }
4789
4790 key.af = pd2.af;
4791 key.proto = IPPROTO_UDP;
4792 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4793 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4794 key.port[pd2.sidx] = uh.uh_sport;
4795 key.port[pd2.didx] = uh.uh_dport;
4796
4797 STATE_LOOKUP(kif, &key, direction, *state, pd);
4798
4799 /* translate source/destination address, if necessary */
4800 if ((*state)->key[PF_SK_WIRE] !=
4801 (*state)->key[PF_SK_STACK]) {
4802 struct pf_state_key *nk =
4803 (*state)->key[pd->didx];
4804
4805 if (PF_ANEQ(pd2.src,
4806 &nk->addr[pd2.sidx], pd2.af) ||
4807 nk->port[pd2.sidx] != uh.uh_sport)
4808 pf_change_icmp(pd2.src, &uh.uh_sport,
4809 daddr, &nk->addr[pd2.sidx],
4810 nk->port[pd2.sidx], &uh.uh_sum,
4811 pd2.ip_sum, icmpsum,
4812 pd->ip_sum, 1, pd2.af);
4813
4814 if (PF_ANEQ(pd2.dst,
4815 &nk->addr[pd2.didx], pd2.af) ||
4816 nk->port[pd2.didx] != uh.uh_dport)
4817 pf_change_icmp(pd2.dst, &uh.uh_dport,
4818 NULL, /* XXX Inbound NAT? */
4819 &nk->addr[pd2.didx],
4820 nk->port[pd2.didx], &uh.uh_sum,
4821 pd2.ip_sum, icmpsum,
4822 pd->ip_sum, 1, pd2.af);
4823
4824 switch (pd2.af) {
4825#ifdef INET
4826 case AF_INET:
4827 m_copyback(m, off, ICMP_MINLEN,
4828 (caddr_t )pd->hdr.icmp);
4829 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4830 break;
4831#endif /* INET */
4832#ifdef INET6
4833 case AF_INET6:
4834 m_copyback(m, off,
4835 sizeof(struct icmp6_hdr),
4836 (caddr_t )pd->hdr.icmp6);
4837 m_copyback(m, ipoff2, sizeof(h2_6),
4838 (caddr_t )&h2_6);
4839 break;
4840#endif /* INET6 */
4841 }
4842 m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
4843 }
4844 return (PF_PASS);
4845 break;
4846 }
4847#ifdef INET
4848 case IPPROTO_ICMP: {
4849 struct icmp iih;
4850
4851 if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
4852 NULL, reason, pd2.af)) {
4853 DPFPRINTF(PF_DEBUG_MISC,
4854 ("pf: ICMP error message too short i"
4855 "(icmp)\n"));
4856 return (PF_DROP);
4857 }
4858
4859 key.af = pd2.af;
4860 key.proto = IPPROTO_ICMP;
4861 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4862 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4863 key.port[0] = key.port[1] = iih.icmp_id;
4864
4865 STATE_LOOKUP(kif, &key, direction, *state, pd);
4866
4867 /* translate source/destination address, if necessary */
4868 if ((*state)->key[PF_SK_WIRE] !=
4869 (*state)->key[PF_SK_STACK]) {
4870 struct pf_state_key *nk =
4871 (*state)->key[pd->didx];
4872
4873 if (PF_ANEQ(pd2.src,
4874 &nk->addr[pd2.sidx], pd2.af) ||
4875 nk->port[pd2.sidx] != iih.icmp_id)
4876 pf_change_icmp(pd2.src, &iih.icmp_id,
4877 daddr, &nk->addr[pd2.sidx],
4878 nk->port[pd2.sidx], NULL,
4879 pd2.ip_sum, icmpsum,
4880 pd->ip_sum, 0, AF_INET);
4881
4882 if (PF_ANEQ(pd2.dst,
4883 &nk->addr[pd2.didx], pd2.af) ||
4884 nk->port[pd2.didx] != iih.icmp_id)
4885 pf_change_icmp(pd2.dst, &iih.icmp_id,
4886 NULL, /* XXX Inbound NAT? */
4887 &nk->addr[pd2.didx],
4888 nk->port[pd2.didx], NULL,
4889 pd2.ip_sum, icmpsum,
4890 pd->ip_sum, 0, AF_INET);
4891
4892 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
4893 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4894 m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
4895 }
4896 return (PF_PASS);
4897 break;
4898 }
4899#endif /* INET */
4900#ifdef INET6
4901 case IPPROTO_ICMPV6: {
4902 struct icmp6_hdr iih;
4903
4904 if (!pf_pull_hdr(m, off2, &iih,
4905 sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
4906 DPFPRINTF(PF_DEBUG_MISC,
4907 ("pf: ICMP error message too short "
4908 "(icmp6)\n"));
4909 return (PF_DROP);
4910 }
4911
4912 key.af = pd2.af;
4913 key.proto = IPPROTO_ICMPV6;
4914 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4915 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4916 key.port[0] = key.port[1] = iih.icmp6_id;
4917
4918 STATE_LOOKUP(kif, &key, direction, *state, pd);
4919
4920 /* translate source/destination address, if necessary */
4921 if ((*state)->key[PF_SK_WIRE] !=
4922 (*state)->key[PF_SK_STACK]) {
4923 struct pf_state_key *nk =
4924 (*state)->key[pd->didx];
4925
4926 if (PF_ANEQ(pd2.src,
4927 &nk->addr[pd2.sidx], pd2.af) ||
4928 nk->port[pd2.sidx] != iih.icmp6_id)
4929 pf_change_icmp(pd2.src, &iih.icmp6_id,
4930 daddr, &nk->addr[pd2.sidx],
4931 nk->port[pd2.sidx], NULL,
4932 pd2.ip_sum, icmpsum,
4933 pd->ip_sum, 0, AF_INET6);
4934
4935 if (PF_ANEQ(pd2.dst,
4936 &nk->addr[pd2.didx], pd2.af) ||
4937 nk->port[pd2.didx] != iih.icmp6_id)
4938 pf_change_icmp(pd2.dst, &iih.icmp6_id,
4939 NULL, /* XXX Inbound NAT? */
4940 &nk->addr[pd2.didx],
4941 nk->port[pd2.didx], NULL,
4942 pd2.ip_sum, icmpsum,
4943 pd->ip_sum, 0, AF_INET6);
4944
4945 m_copyback(m, off, sizeof(struct icmp6_hdr),
4946 (caddr_t)pd->hdr.icmp6);
4947 m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
4948 m_copyback(m, off2, sizeof(struct icmp6_hdr),
4949 (caddr_t)&iih);
4950 }
4951 return (PF_PASS);
4952 break;
4953 }
4954#endif /* INET6 */
4955 default: {
4956 key.af = pd2.af;
4957 key.proto = pd2.proto;
4958 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4959 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4960 key.port[0] = key.port[1] = 0;
4961
4962 STATE_LOOKUP(kif, &key, direction, *state, pd);
4963
4964 /* translate source/destination address, if necessary */
4965 if ((*state)->key[PF_SK_WIRE] !=
4966 (*state)->key[PF_SK_STACK]) {
4967 struct pf_state_key *nk =
4968 (*state)->key[pd->didx];
4969
4970 if (PF_ANEQ(pd2.src,
4971 &nk->addr[pd2.sidx], pd2.af))
4972 pf_change_icmp(pd2.src, NULL, daddr,
4973 &nk->addr[pd2.sidx], 0, NULL,
4974 pd2.ip_sum, icmpsum,
4975 pd->ip_sum, 0, pd2.af);
4976
4977 if (PF_ANEQ(pd2.dst,
4978 &nk->addr[pd2.didx], pd2.af))
4979 pf_change_icmp(pd2.src, NULL,
4980 NULL, /* XXX Inbound NAT? */
4981 &nk->addr[pd2.didx], 0, NULL,
4982 pd2.ip_sum, icmpsum,
4983 pd->ip_sum, 0, pd2.af);
4984
4985 switch (pd2.af) {
4986#ifdef INET
4987 case AF_INET:
4988 m_copyback(m, off, ICMP_MINLEN,
4989 (caddr_t)pd->hdr.icmp);
4990 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4991 break;
4992#endif /* INET */
4993#ifdef INET6
4994 case AF_INET6:
4995 m_copyback(m, off,
4996 sizeof(struct icmp6_hdr),
4997 (caddr_t )pd->hdr.icmp6);
4998 m_copyback(m, ipoff2, sizeof(h2_6),
4999 (caddr_t )&h2_6);
5000 break;
5001#endif /* INET6 */
5002 }
5003 }
5004 return (PF_PASS);
5005 break;
5006 }
5007 }
5008 }
5009}
5010
5011static int
5012pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
5013 struct mbuf *m, struct pf_pdesc *pd)
5014{
5015 struct pf_state_peer *src, *dst;
5016 struct pf_state_key_cmp key;
5017
5018 bzero(&key, sizeof(key));
5019 key.af = pd->af;
5020 key.proto = pd->proto;
5021 if (direction == PF_IN) {
5022 PF_ACPY(&key.addr[0], pd->src, key.af);
5023 PF_ACPY(&key.addr[1], pd->dst, key.af);
5024 key.port[0] = key.port[1] = 0;
5025 } else {
5026 PF_ACPY(&key.addr[1], pd->src, key.af);
5027 PF_ACPY(&key.addr[0], pd->dst, key.af);
5028 key.port[1] = key.port[0] = 0;
5029 }
5030
5031 STATE_LOOKUP(kif, &key, direction, *state, pd);
5032
5033 if (direction == (*state)->direction) {
5034 src = &(*state)->src;
5035 dst = &(*state)->dst;
5036 } else {
5037 src = &(*state)->dst;
5038 dst = &(*state)->src;
5039 }
5040
5041 /* update states */
5042 if (src->state < PFOTHERS_SINGLE)
5043 src->state = PFOTHERS_SINGLE;
5044 if (dst->state == PFOTHERS_SINGLE)
5045 dst->state = PFOTHERS_MULTIPLE;
5046
5047 /* update expire time */
5048 (*state)->expire = time_uptime;
5049 if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5050 (*state)->timeout = PFTM_OTHER_MULTIPLE;
5051 else
5052 (*state)->timeout = PFTM_OTHER_SINGLE;
5053
5054 /* translate source/destination address, if necessary */
5055 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5056 struct pf_state_key *nk = (*state)->key[pd->didx];
5057
5058 KASSERT(nk, ("%s: nk is null", __func__));
5059 KASSERT(pd, ("%s: pd is null", __func__));
5060 KASSERT(pd->src, ("%s: pd->src is null", __func__));
5061 KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
5062 switch (pd->af) {
5063#ifdef INET
5064 case AF_INET:
5065 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5066 pf_change_a(&pd->src->v4.s_addr,
5067 pd->ip_sum,
5068 nk->addr[pd->sidx].v4.s_addr,
5069 0);
5070
5071
5072 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5073 pf_change_a(&pd->dst->v4.s_addr,
5074 pd->ip_sum,
5075 nk->addr[pd->didx].v4.s_addr,
5076 0);
5077
5078 break;
5079#endif /* INET */
5080#ifdef INET6
5081 case AF_INET6:
5082 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5083 PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5084
5085 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5086 PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5087#endif /* INET6 */
5088 }
5089 }
5090 return (PF_PASS);
5091}
5092
5093/*
5094 * ipoff and off are measured from the start of the mbuf chain.
5095 * h must be at "ipoff" on the mbuf chain.
5096 */
5097void *
5098pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5099 u_short *actionp, u_short *reasonp, sa_family_t af)
5100{
5101 switch (af) {
5102#ifdef INET
5103 case AF_INET: {
5104 struct ip *h = mtod(m, struct ip *);
5105 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
5106
5107 if (fragoff) {
5108 if (fragoff >= len)
5109 ACTION_SET(actionp, PF_PASS);
5110 else {
5111 ACTION_SET(actionp, PF_DROP);
5112 REASON_SET(reasonp, PFRES_FRAG);
5113 }
5114 return (NULL);
5115 }
5116 if (m->m_pkthdr.len < off + len ||
5117 ntohs(h->ip_len) < off + len) {
5118 ACTION_SET(actionp, PF_DROP);
5119 REASON_SET(reasonp, PFRES_SHORT);
5120 return (NULL);
5121 }
5122 break;
5123 }
5124#endif /* INET */
5125#ifdef INET6
5126 case AF_INET6: {
5127 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
5128
5129 if (m->m_pkthdr.len < off + len ||
5130 (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5131 (unsigned)(off + len)) {
5132 ACTION_SET(actionp, PF_DROP);
5133 REASON_SET(reasonp, PFRES_SHORT);
5134 return (NULL);
5135 }
5136 break;
5137 }
5138#endif /* INET6 */
5139 }
5140 m_copydata(m, off, len, p);
5141 return (p);
5142}
5143
5144int
5145pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5146 int rtableid)
5147{
5148#ifdef RADIX_MPATH
5149 struct radix_node_head *rnh;
5150#endif
5151 struct sockaddr_in *dst;
5152 int ret = 1;
5153 int check_mpath;
5154#ifdef INET6
5155 struct sockaddr_in6 *dst6;
5156 struct route_in6 ro;
5157#else
5158 struct route ro;
5159#endif
5160 struct radix_node *rn;
5161 struct rtentry *rt;
5162 struct ifnet *ifp;
5163
5164 check_mpath = 0;
5165#ifdef RADIX_MPATH
5166 /* XXX: stick to table 0 for now */
5167 rnh = rt_tables_get_rnh(0, af);
5168 if (rnh != NULL && rn_mpath_capable(rnh))
5169 check_mpath = 1;
5170#endif
5171 bzero(&ro, sizeof(ro));
5172 switch (af) {
5173 case AF_INET:
5174 dst = satosin(&ro.ro_dst);
5175 dst->sin_family = AF_INET;
5176 dst->sin_len = sizeof(*dst);
5177 dst->sin_addr = addr->v4;
5178 break;
5179#ifdef INET6
5180 case AF_INET6:
5181 /*
5182 * Skip check for addresses with embedded interface scope,
5183 * as they would always match anyway.
5184 */
5185 if (IN6_IS_SCOPE_EMBED(&addr->v6))
5186 goto out;
5187 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5188 dst6->sin6_family = AF_INET6;
5189 dst6->sin6_len = sizeof(*dst6);
5190 dst6->sin6_addr = addr->v6;
5191 break;
5192#endif /* INET6 */
5193 default:
5194 return (0);
5195 }
5196
5197 /* Skip checks for ipsec interfaces */
5198 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5199 goto out;
5200
5201 switch (af) {
5202#ifdef INET6
5203 case AF_INET6:
5204 in6_rtalloc_ign(&ro, 0, rtableid);
5205 break;
5206#endif
5207#ifdef INET
5208 case AF_INET:
5209 in_rtalloc_ign((struct route *)&ro, 0, rtableid);
5210 break;
5211#endif
5212 default:
5213 rtalloc_ign((struct route *)&ro, 0); /* No/default FIB. */
5214 break;
5215 }
5216
5217 if (ro.ro_rt != NULL) {
5218 /* No interface given, this is a no-route check */
5219 if (kif == NULL)
5220 goto out;
5221
5222 if (kif->pfik_ifp == NULL) {
5223 ret = 0;
5224 goto out;
5225 }
5226
5227 /* Perform uRPF check if passed input interface */
5228 ret = 0;
5229 rn = (struct radix_node *)ro.ro_rt;
5230 do {
5231 rt = (struct rtentry *)rn;
5232 ifp = rt->rt_ifp;
5233
5234 if (kif->pfik_ifp == ifp)
5235 ret = 1;
5236#ifdef RADIX_MPATH
5237 rn = rn_mpath_next(rn);
5238#endif
5239 } while (check_mpath == 1 && rn != NULL && ret == 0);
5240 } else
5241 ret = 0;
5242out:
5243 if (ro.ro_rt != NULL)
5244 RTFREE(ro.ro_rt);
5245 return (ret);
5246}
5247
5248#ifdef INET
5249static void
5250pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5251 struct pf_state *s, struct pf_pdesc *pd)
5252{
5253 struct mbuf *m0, *m1;
5254 struct sockaddr_in dst;
5255 struct ip *ip;
5256 struct ifnet *ifp = NULL;
5257 struct pf_addr naddr;
5258 struct pf_src_node *sn = NULL;
5259 int error = 0;
5260 uint16_t ip_len, ip_off;
5261
5262 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5263 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5264 __func__));
5265
5266 if ((pd->pf_mtag == NULL &&
5267 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5268 pd->pf_mtag->routed++ > 3) {
5269 m0 = *m;
5270 *m = NULL;
5271 goto bad_locked;
5272 }
5273
5274 if (r->rt == PF_DUPTO) {
5275 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5276 if (s)
5277 PF_STATE_UNLOCK(s);
5278 return;
5279 }
5280 } else {
5281 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5282 if (s)
5283 PF_STATE_UNLOCK(s);
5284 return;
5285 }
5286 m0 = *m;
5287 }
5288
5289 ip = mtod(m0, struct ip *);
5290
5291 bzero(&dst, sizeof(dst));
5292 dst.sin_family = AF_INET;
5293 dst.sin_len = sizeof(dst);
5294 dst.sin_addr = ip->ip_dst;
5295
5296 if (r->rt == PF_FASTROUTE) {
5297 struct rtentry *rt;
5298
5299 if (s)
5300 PF_STATE_UNLOCK(s);
5301 rt = rtalloc1_fib(sintosa(&dst), 0, 0, M_GETFIB(m0));
5302 if (rt == NULL) {
5303 KMOD_IPSTAT_INC(ips_noroute);
5304 error = EHOSTUNREACH;
5305 goto bad;
5306 }
5307
5308 ifp = rt->rt_ifp;
5309 counter_u64_add(rt->rt_pksent, 1);
5310
5311 if (rt->rt_flags & RTF_GATEWAY)
5312 bcopy(satosin(rt->rt_gateway), &dst, sizeof(dst));
5313 RTFREE_LOCKED(rt);
5314 } else {
5315 if (TAILQ_EMPTY(&r->rpool.list)) {
5316 DPFPRINTF(PF_DEBUG_URGENT,
5317 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5318 goto bad_locked;
5319 }
5320 if (s == NULL) {
5321 pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5322 &naddr, NULL, &sn);
5323 if (!PF_AZERO(&naddr, AF_INET))
5324 dst.sin_addr.s_addr = naddr.v4.s_addr;
5325 ifp = r->rpool.cur->kif ?
5326 r->rpool.cur->kif->pfik_ifp : NULL;
5327 } else {
5328 if (!PF_AZERO(&s->rt_addr, AF_INET))
5329 dst.sin_addr.s_addr =
5330 s->rt_addr.v4.s_addr;
5331 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5332 PF_STATE_UNLOCK(s);
5333 }
5334 }
5335 if (ifp == NULL)
5336 goto bad;
5337
5338 if (oifp != ifp) {
5339 if (pf_test(PF_OUT, ifp, &m0, NULL) != PF_PASS)
5340 goto bad;
5341 else if (m0 == NULL)
5342 goto done;
5343 if (m0->m_len < sizeof(struct ip)) {
5344 DPFPRINTF(PF_DEBUG_URGENT,
5345 ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
5346 goto bad;
5347 }
5348 ip = mtod(m0, struct ip *);
5349 }
5350
5351 if (ifp->if_flags & IFF_LOOPBACK)
5352 m0->m_flags |= M_SKIP_FIREWALL;
5353
5354 ip_len = ntohs(ip->ip_len);
5355 ip_off = ntohs(ip->ip_off);
5356
5357 /* Copied from FreeBSD 10.0-CURRENT ip_output. */
5358 m0->m_pkthdr.csum_flags |= CSUM_IP;
5359 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
5360 in_delayed_cksum(m0);
5361 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
5362 }
5363#ifdef SCTP
5364 if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
5365 sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
5366 m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
5367 }
5368#endif
5369
5370 /*
5371 * If small enough for interface, or the interface will take
5372 * care of the fragmentation for us, we can just send directly.
5373 */
5374 if (ip_len <= ifp->if_mtu ||
5375 (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0 ||
5376 ((ip_off & IP_DF) == 0 && (ifp->if_hwassist & CSUM_FRAGMENT))) {
5377 ip->ip_sum = 0;
5378 if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
5379 ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5380 m0->m_pkthdr.csum_flags &= ~CSUM_IP;
5381 }
5382 m_clrprotoflags(m0); /* Avoid confusing lower layers. */
5383 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5384 goto done;
5385 }
5386
5387 /* Balk when DF bit is set or the interface didn't support TSO. */
5388 if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5389 error = EMSGSIZE;
5390 KMOD_IPSTAT_INC(ips_cantfrag);
5391 if (r->rt != PF_DUPTO) {
5392 icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5393 ifp->if_mtu);
5394 goto done;
5395 } else
5396 goto bad;
5397 }
5398
5399 error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
5400 if (error)
5401 goto bad;
5402
5403 for (; m0; m0 = m1) {
5404 m1 = m0->m_nextpkt;
5405 m0->m_nextpkt = NULL;
5406 if (error == 0) {
5407 m_clrprotoflags(m0);
5408 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5409 } else
5410 m_freem(m0);
5411 }
5412
5413 if (error == 0)
5414 KMOD_IPSTAT_INC(ips_fragmented);
5415
5416done:
5417 if (r->rt != PF_DUPTO)
5418 *m = NULL;
5419 return;
5420
5421bad_locked:
5422 if (s)
5423 PF_STATE_UNLOCK(s);
5424bad:
5425 m_freem(m0);
5426 goto done;
5427}
5428#endif /* INET */
5429
5430#ifdef INET6
5431static void
5432pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5433 struct pf_state *s, struct pf_pdesc *pd)
5434{
5435 struct mbuf *m0;
5436 struct sockaddr_in6 dst;
5437 struct ip6_hdr *ip6;
5438 struct ifnet *ifp = NULL;
5439 struct pf_addr naddr;
5440 struct pf_src_node *sn = NULL;
5441
5442 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5443 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5444 __func__));
5445
5446 if ((pd->pf_mtag == NULL &&
5447 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5448 pd->pf_mtag->routed++ > 3) {
5449 m0 = *m;
5450 *m = NULL;
5451 goto bad_locked;
5452 }
5453
5454 if (r->rt == PF_DUPTO) {
5455 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5456 if (s)
5457 PF_STATE_UNLOCK(s);
5458 return;
5459 }
5460 } else {
5461 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5462 if (s)
5463 PF_STATE_UNLOCK(s);
5464 return;
5465 }
5466 m0 = *m;
5467 }
5468
5469 ip6 = mtod(m0, struct ip6_hdr *);
5470
5471 bzero(&dst, sizeof(dst));
5472 dst.sin6_family = AF_INET6;
5473 dst.sin6_len = sizeof(dst);
5474 dst.sin6_addr = ip6->ip6_dst;
5475
5476 /* Cheat. XXX why only in the v6 case??? */
5477 if (r->rt == PF_FASTROUTE) {
5478 if (s)
5479 PF_STATE_UNLOCK(s);
5480 m0->m_flags |= M_SKIP_FIREWALL;
5481 ip6_output(m0, NULL, NULL, 0, NULL, NULL, NULL);
5482 *m = NULL;
5483 return;
5484 }
5485
5486 if (TAILQ_EMPTY(&r->rpool.list)) {
5487 DPFPRINTF(PF_DEBUG_URGENT,
5488 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5489 goto bad_locked;
5490 }
5491 if (s == NULL) {
5492 pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5493 &naddr, NULL, &sn);
5494 if (!PF_AZERO(&naddr, AF_INET6))
5495 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5496 &naddr, AF_INET6);
5497 ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
5498 } else {
5499 if (!PF_AZERO(&s->rt_addr, AF_INET6))
5500 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5501 &s->rt_addr, AF_INET6);
5502 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5503 }
5504
5505 if (s)
5506 PF_STATE_UNLOCK(s);
5507
5508 if (ifp == NULL)
5509 goto bad;
5510
5511 if (oifp != ifp) {
5512 if (pf_test6(PF_FWD, ifp, &m0, NULL) != PF_PASS)
5513 goto bad;
5514 else if (m0 == NULL)
5515 goto done;
5516 if (m0->m_len < sizeof(struct ip6_hdr)) {
5517 DPFPRINTF(PF_DEBUG_URGENT,
5518 ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
5519 __func__));
5520 goto bad;
5521 }
5522 ip6 = mtod(m0, struct ip6_hdr *);
5523 }
5524
5525 if (ifp->if_flags & IFF_LOOPBACK)
5526 m0->m_flags |= M_SKIP_FIREWALL;
5527
5528 /*
5529 * If the packet is too large for the outgoing interface,
5530 * send back an icmp6 error.
5531 */
5532 if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
5533 dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5534 if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu)
5535 nd6_output(ifp, ifp, m0, &dst, NULL);
5536 else {
5537 in6_ifstat_inc(ifp, ifs6_in_toobig);
5538 if (r->rt != PF_DUPTO)
5539 icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5540 else
5541 goto bad;
5542 }
5543
5544done:
5545 if (r->rt != PF_DUPTO)
5546 *m = NULL;
5547 return;
5548
5549bad_locked:
5550 if (s)
5551 PF_STATE_UNLOCK(s);
5552bad:
5553 m_freem(m0);
5554 goto done;
5555}
5556#endif /* INET6 */
5557
5558/*
5559 * FreeBSD supports cksum offloads for the following drivers.
5560 * em(4), fxp(4), ixgb(4), lge(4), ndis(4), nge(4), re(4),
5561 * ti(4), txp(4), xl(4)
5562 *
5563 * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
5564 * network driver performed cksum including pseudo header, need to verify
5565 * csum_data
5566 * CSUM_DATA_VALID :
5567 * network driver performed cksum, needs to additional pseudo header
5568 * cksum computation with partial csum_data(i.e. lack of H/W support for
5569 * pseudo header, for instance hme(4), sk(4) and possibly gem(4))
5570 *
5571 * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
5572 * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
5573 * TCP/UDP layer.
5574 * Also, set csum_data to 0xffff to force cksum validation.
5575 */
5576static int
5577pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
5578{
5579 u_int16_t sum = 0;
5580 int hw_assist = 0;
5581 struct ip *ip;
5582
5583 if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
5584 return (1);
5585 if (m->m_pkthdr.len < off + len)
5586 return (1);
5587
5588 switch (p) {
5589 case IPPROTO_TCP:
5590 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5591 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5592 sum = m->m_pkthdr.csum_data;
5593 } else {
5594 ip = mtod(m, struct ip *);
5595 sum = in_pseudo(ip->ip_src.s_addr,
5596 ip->ip_dst.s_addr, htonl((u_short)len +
5597 m->m_pkthdr.csum_data + IPPROTO_TCP));
5598 }
5599 sum ^= 0xffff;
5600 ++hw_assist;
5601 }
5602 break;
5603 case IPPROTO_UDP:
5604 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5605 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5606 sum = m->m_pkthdr.csum_data;
5607 } else {
5608 ip = mtod(m, struct ip *);
5609 sum = in_pseudo(ip->ip_src.s_addr,
5610 ip->ip_dst.s_addr, htonl((u_short)len +
5611 m->m_pkthdr.csum_data + IPPROTO_UDP));
5612 }
5613 sum ^= 0xffff;
5614 ++hw_assist;
5615 }
5616 break;
5617 case IPPROTO_ICMP:
5618#ifdef INET6
5619 case IPPROTO_ICMPV6:
5620#endif /* INET6 */
5621 break;
5622 default:
5623 return (1);
5624 }
5625
5626 if (!hw_assist) {
5627 switch (af) {
5628 case AF_INET:
5629 if (p == IPPROTO_ICMP) {
5630 if (m->m_len < off)
5631 return (1);
5632 m->m_data += off;
5633 m->m_len -= off;
5634 sum = in_cksum(m, len);
5635 m->m_data -= off;
5636 m->m_len += off;
5637 } else {
5638 if (m->m_len < sizeof(struct ip))
5639 return (1);
5640 sum = in4_cksum(m, p, off, len);
5641 }
5642 break;
5643#ifdef INET6
5644 case AF_INET6:
5645 if (m->m_len < sizeof(struct ip6_hdr))
5646 return (1);
5647 sum = in6_cksum(m, p, off, len);
5648 break;
5649#endif /* INET6 */
5650 default:
5651 return (1);
5652 }
5653 }
5654 if (sum) {
5655 switch (p) {
5656 case IPPROTO_TCP:
5657 {
5658 KMOD_TCPSTAT_INC(tcps_rcvbadsum);
5659 break;
5660 }
5661 case IPPROTO_UDP:
5662 {
5663 KMOD_UDPSTAT_INC(udps_badsum);
5664 break;
5665 }
5666#ifdef INET
5667 case IPPROTO_ICMP:
5668 {
5669 KMOD_ICMPSTAT_INC(icps_checksum);
5670 break;
5671 }
5672#endif
5673#ifdef INET6
5674 case IPPROTO_ICMPV6:
5675 {
5676 KMOD_ICMP6STAT_INC(icp6s_checksum);
5677 break;
5678 }
5679#endif /* INET6 */
5680 }
5681 return (1);
5682 } else {
5683 if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
5684 m->m_pkthdr.csum_flags |=
5685 (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
5686 m->m_pkthdr.csum_data = 0xffff;
5687 }
5688 }
5689 return (0);
5690}
5691
5692
5693#ifdef INET
5694int
5695pf_test(int dir, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
5696{
5697 struct pfi_kif *kif;
5698 u_short action, reason = 0, log = 0;
5699 struct mbuf *m = *m0;
5700 struct ip *h = NULL;
5701 struct m_tag *ipfwtag;
5702 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
5703 struct pf_state *s = NULL;
5704 struct pf_ruleset *ruleset = NULL;
5705 struct pf_pdesc pd;
5706 int off, dirndx, pqid = 0;
5707
5708 M_ASSERTPKTHDR(m);
5709
5710 if (!V_pf_status.running)
5711 return (PF_PASS);
5712
5713 memset(&pd, 0, sizeof(pd));
5714
5715 kif = (struct pfi_kif *)ifp->if_pf_kif;
5716
5717 if (kif == NULL) {
5718 DPFPRINTF(PF_DEBUG_URGENT,
5719 ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
5720 return (PF_DROP);
5721 }
5722 if (kif->pfik_flags & PFI_IFLAG_SKIP)
5723 return (PF_PASS);
5724
5725 if (m->m_flags & M_SKIP_FIREWALL)
5726 return (PF_PASS);
5727
5728 pd.pf_mtag = pf_find_mtag(m);
5729
5730 PF_RULES_RLOCK();
5731
5732 if (ip_divert_ptr != NULL &&
5733 ((ipfwtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL)) != NULL)) {
5734 struct ipfw_rule_ref *rr = (struct ipfw_rule_ref *)(ipfwtag+1);
5735 if (rr->info & IPFW_IS_DIVERT && rr->rulenum == 0) {
5736 if (pd.pf_mtag == NULL &&
5737 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5738 action = PF_DROP;
5739 goto done;
5740 }
5741 pd.pf_mtag->flags |= PF_PACKET_LOOPED;
5742 m_tag_delete(m, ipfwtag);
5743 }
5744 if (pd.pf_mtag && pd.pf_mtag->flags & PF_FASTFWD_OURS_PRESENT) {
5745 m->m_flags |= M_FASTFWD_OURS;
5746 pd.pf_mtag->flags &= ~PF_FASTFWD_OURS_PRESENT;
5747 }
5748 } else if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
5749 /* We do IP header normalization and packet reassembly here */
5750 action = PF_DROP;
5751 goto done;
5752 }
5753 m = *m0; /* pf_normalize messes with m0 */
5754 h = mtod(m, struct ip *);
5755
5756 off = h->ip_hl << 2;
5757 if (off < (int)sizeof(struct ip)) {
5758 action = PF_DROP;
5759 REASON_SET(&reason, PFRES_SHORT);
5760 log = 1;
5761 goto done;
5762 }
5763
5764 pd.src = (struct pf_addr *)&h->ip_src;
5765 pd.dst = (struct pf_addr *)&h->ip_dst;
5766 pd.sport = pd.dport = NULL;
5767 pd.ip_sum = &h->ip_sum;
5768 pd.proto_sum = NULL;
5769 pd.proto = h->ip_p;
5770 pd.dir = dir;
5771 pd.sidx = (dir == PF_IN) ? 0 : 1;
5772 pd.didx = (dir == PF_IN) ? 1 : 0;
5773 pd.af = AF_INET;
5774 pd.tos = h->ip_tos;
5775 pd.tot_len = ntohs(h->ip_len);
5776
5777 /* handle fragments that didn't get reassembled by normalization */
5778 if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
5779 action = pf_test_fragment(&r, dir, kif, m, h,
5780 &pd, &a, &ruleset);
5781 goto done;
5782 }
5783
5784 switch (h->ip_p) {
5785
5786 case IPPROTO_TCP: {
5787 struct tcphdr th;
5788
5789 pd.hdr.tcp = &th;
5790 if (!pf_pull_hdr(m, off, &th, sizeof(th),
5791 &action, &reason, AF_INET)) {
5792 log = action != PF_PASS;
5793 goto done;
5794 }
5795 pd.p_len = pd.tot_len - off - (th.th_off << 2);
5796 if ((th.th_flags & TH_ACK) && pd.p_len == 0)
5797 pqid = 1;
5798 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
5799 if (action == PF_DROP)
5800 goto done;
5801 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
5802 &reason);
5803 if (action == PF_PASS) {
5804 if (pfsync_update_state_ptr != NULL)
5805 pfsync_update_state_ptr(s);
5806 r = s->rule.ptr;
5807 a = s->anchor.ptr;
5808 log = s->log;
5809 } else if (s == NULL)
5810 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5811 &a, &ruleset, inp);
5812 break;
5813 }
5814
5815 case IPPROTO_UDP: {
5816 struct udphdr uh;
5817
5818 pd.hdr.udp = &uh;
5819 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
5820 &action, &reason, AF_INET)) {
5821 log = action != PF_PASS;
5822 goto done;
5823 }
5824 if (uh.uh_dport == 0 ||
5825 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
5826 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
5827 action = PF_DROP;
5828 REASON_SET(&reason, PFRES_SHORT);
5829 goto done;
5830 }
5831 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
5832 if (action == PF_PASS) {
5833 if (pfsync_update_state_ptr != NULL)
5834 pfsync_update_state_ptr(s);
5835 r = s->rule.ptr;
5836 a = s->anchor.ptr;
5837 log = s->log;
5838 } else if (s == NULL)
5839 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5840 &a, &ruleset, inp);
5841 break;
5842 }
5843
5844 case IPPROTO_ICMP: {
5845 struct icmp ih;
5846
5847 pd.hdr.icmp = &ih;
5848 if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
5849 &action, &reason, AF_INET)) {
5850 log = action != PF_PASS;
5851 goto done;
5852 }
5853 action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
5854 &reason);
5855 if (action == PF_PASS) {
5856 if (pfsync_update_state_ptr != NULL)
5857 pfsync_update_state_ptr(s);
5858 r = s->rule.ptr;
5859 a = s->anchor.ptr;
5860 log = s->log;
5861 } else if (s == NULL)
5862 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5863 &a, &ruleset, inp);
5864 break;
5865 }
5866
5867#ifdef INET6
5868 case IPPROTO_ICMPV6: {
5869 action = PF_DROP;
5870 DPFPRINTF(PF_DEBUG_MISC,
5871 ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
5872 goto done;
5873 }
5874#endif
5875
5876 default:
5877 action = pf_test_state_other(&s, dir, kif, m, &pd);
5878 if (action == PF_PASS) {
5879 if (pfsync_update_state_ptr != NULL)
5880 pfsync_update_state_ptr(s);
5881 r = s->rule.ptr;
5882 a = s->anchor.ptr;
5883 log = s->log;
5884 } else if (s == NULL)
5885 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5886 &a, &ruleset, inp);
5887 break;
5888 }
5889
5890done:
5891 PF_RULES_RUNLOCK();
5892 if (action == PF_PASS && h->ip_hl > 5 &&
5893 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
5894 action = PF_DROP;
5895 REASON_SET(&reason, PFRES_IPOPTIONS);
5896 log = 1;
5897 DPFPRINTF(PF_DEBUG_MISC,
5898 ("pf: dropping packet with ip options\n"));
5899 }
5900
5901 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
5902 action = PF_DROP;
5903 REASON_SET(&reason, PFRES_MEMORY);
5904 }
5905 if (r->rtableid >= 0)
5906 M_SETFIB(m, r->rtableid);
5907
5908#ifdef ALTQ
5909 if (action == PF_PASS && r->qid) {
5910 if (pd.pf_mtag == NULL &&
5911 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5912 action = PF_DROP;
5913 REASON_SET(&reason, PFRES_MEMORY);
5914 }
5915 if (pqid || (pd.tos & IPTOS_LOWDELAY))
5916 pd.pf_mtag->qid = r->pqid;
5917 else
5918 pd.pf_mtag->qid = r->qid;
5919 /* add hints for ecn */
5920 pd.pf_mtag->hdr = h;
5921
5922 }
5923#endif /* ALTQ */
5924
5925 /*
5926 * connections redirected to loopback should not match sockets
5927 * bound specifically to loopback due to security implications,
5928 * see tcp_input() and in_pcblookup_listen().
5929 */
5930 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
5931 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
5932 (s->nat_rule.ptr->action == PF_RDR ||
5933 s->nat_rule.ptr->action == PF_BINAT) &&
5934 (ntohl(pd.dst->v4.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
5935 m->m_flags |= M_SKIP_FIREWALL;
5936
5937 if (action == PF_PASS && r->divert.port && ip_divert_ptr != NULL &&
5938 !PACKET_LOOPED(&pd)) {
5939
5940 ipfwtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
5941 sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
5942 if (ipfwtag != NULL) {
5943 ((struct ipfw_rule_ref *)(ipfwtag+1))->info =
5944 ntohs(r->divert.port);
5945 ((struct ipfw_rule_ref *)(ipfwtag+1))->rulenum = dir;
5946
5947 if (s)
5948 PF_STATE_UNLOCK(s);
5949
5950 m_tag_prepend(m, ipfwtag);
5951 if (m->m_flags & M_FASTFWD_OURS) {
5952 if (pd.pf_mtag == NULL &&
5953 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5954 action = PF_DROP;
5955 REASON_SET(&reason, PFRES_MEMORY);
5956 log = 1;
5957 DPFPRINTF(PF_DEBUG_MISC,
5958 ("pf: failed to allocate tag\n"));
5959 }
5960 pd.pf_mtag->flags |= PF_FASTFWD_OURS_PRESENT;
5961 m->m_flags &= ~M_FASTFWD_OURS;
5962 }
5963 ip_divert_ptr(*m0, dir == PF_IN ? DIR_IN : DIR_OUT);
5964 *m0 = NULL;
5965
5966 return (action);
5967 } else {
5968 /* XXX: ipfw has the same behaviour! */
5969 action = PF_DROP;
5970 REASON_SET(&reason, PFRES_MEMORY);
5971 log = 1;
5972 DPFPRINTF(PF_DEBUG_MISC,
5973 ("pf: failed to allocate divert tag\n"));
5974 }
5975 }
5976
5977 if (log) {
5978 struct pf_rule *lr;
5979
5980 if (s != NULL && s->nat_rule.ptr != NULL &&
5981 s->nat_rule.ptr->log & PF_LOG_ALL)
5982 lr = s->nat_rule.ptr;
5983 else
5984 lr = r;
5985 PFLOG_PACKET(kif, m, AF_INET, dir, reason, lr, a, ruleset, &pd,
5986 (s == NULL));
5987 }
5988
5989 kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
5990 kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
5991
5992 if (action == PF_PASS || r->action == PF_DROP) {
5993 dirndx = (dir == PF_OUT);
5994 r->packets[dirndx]++;
5995 r->bytes[dirndx] += pd.tot_len;
5996 if (a != NULL) {
5997 a->packets[dirndx]++;
5998 a->bytes[dirndx] += pd.tot_len;
5999 }
6000 if (s != NULL) {
6001 if (s->nat_rule.ptr != NULL) {
6002 s->nat_rule.ptr->packets[dirndx]++;
6003 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6004 }
6005 if (s->src_node != NULL) {
6006 s->src_node->packets[dirndx]++;
6007 s->src_node->bytes[dirndx] += pd.tot_len;
6008 }
6009 if (s->nat_src_node != NULL) {
6010 s->nat_src_node->packets[dirndx]++;
6011 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6012 }
6013 dirndx = (dir == s->direction) ? 0 : 1;
6014 s->packets[dirndx]++;
6015 s->bytes[dirndx] += pd.tot_len;
6016 }
6017 tr = r;
6018 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6019 if (nr != NULL && r == &V_pf_default_rule)
6020 tr = nr;
6021 if (tr->src.addr.type == PF_ADDR_TABLE)
6022 pfr_update_stats(tr->src.addr.p.tbl,
6023 (s == NULL) ? pd.src :
6024 &s->key[(s->direction == PF_IN)]->
6025 addr[(s->direction == PF_OUT)],
6026 pd.af, pd.tot_len, dir == PF_OUT,
6027 r->action == PF_PASS, tr->src.neg);
6028 if (tr->dst.addr.type == PF_ADDR_TABLE)
6029 pfr_update_stats(tr->dst.addr.p.tbl,
6030 (s == NULL) ? pd.dst :
6031 &s->key[(s->direction == PF_IN)]->
6032 addr[(s->direction == PF_IN)],
6033 pd.af, pd.tot_len, dir == PF_OUT,
6034 r->action == PF_PASS, tr->dst.neg);
6035 }
6036
6037 switch (action) {
6038 case PF_SYNPROXY_DROP:
6039 m_freem(*m0);
6040 case PF_DEFER:
6041 *m0 = NULL;
6042 action = PF_PASS;
6043 break;
6044 case PF_DROP:
6045 m_freem(*m0);
6046 *m0 = NULL;
6047 break;
6048 default:
6049 /* pf_route() returns unlocked. */
6050 if (r->rt) {
6051 pf_route(m0, r, dir, kif->pfik_ifp, s, &pd);
6052 return (action);
6053 }
6054 break;
6055 }
6056 if (s)
6057 PF_STATE_UNLOCK(s);
6058
6059 return (action);
6060}
6061#endif /* INET */
6062
6063#ifdef INET6
6064int
6065pf_test6(int dir, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
6066{
6067 struct pfi_kif *kif;
6068 u_short action, reason = 0, log = 0;
6069 struct mbuf *m = *m0, *n = NULL;
6070 struct m_tag *mtag;
6071 struct ip6_hdr *h = NULL;
6072 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
6073 struct pf_state *s = NULL;
6074 struct pf_ruleset *ruleset = NULL;
6075 struct pf_pdesc pd;
6076 int off, terminal = 0, dirndx, rh_cnt = 0;
6077 int fwdir = dir;
6078
6079 M_ASSERTPKTHDR(m);
6080
6081 if (dir == PF_OUT && m->m_pkthdr.rcvif && ifp != m->m_pkthdr.rcvif)
6082 fwdir = PF_FWD;
6083
6084 if (!V_pf_status.running)
6085 return (PF_PASS);
6086
6087 memset(&pd, 0, sizeof(pd));
6088 pd.pf_mtag = pf_find_mtag(m);
6089
6090 if (pd.pf_mtag && pd.pf_mtag->flags & PF_TAG_GENERATED)
6091 return (PF_PASS);
6092
6093 kif = (struct pfi_kif *)ifp->if_pf_kif;
6094 if (kif == NULL) {
6095 DPFPRINTF(PF_DEBUG_URGENT,
6096 ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6097 return (PF_DROP);
6098 }
6099 if (kif->pfik_flags & PFI_IFLAG_SKIP)
6100 return (PF_PASS);
6101
6102 if (m->m_flags & M_SKIP_FIREWALL)
6103 return (PF_PASS);
6104
6105 PF_RULES_RLOCK();
6106
6107 /* We do IP header normalization and packet reassembly here */
6108 if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6109 action = PF_DROP;
6110 goto done;
6111 }
6112 m = *m0; /* pf_normalize messes with m0 */
6113 h = mtod(m, struct ip6_hdr *);
6114
6115#if 1
6116 /*
6117 * we do not support jumbogram yet. if we keep going, zero ip6_plen
6118 * will do something bad, so drop the packet for now.
6119 */
6120 if (htons(h->ip6_plen) == 0) {
6121 action = PF_DROP;
6122 REASON_SET(&reason, PFRES_NORM); /*XXX*/
6123 goto done;
6124 }
6125#endif
6126
6127 pd.src = (struct pf_addr *)&h->ip6_src;
6128 pd.dst = (struct pf_addr *)&h->ip6_dst;
6129 pd.sport = pd.dport = NULL;
6130 pd.ip_sum = NULL;
6131 pd.proto_sum = NULL;
6132 pd.dir = dir;
6133 pd.sidx = (dir == PF_IN) ? 0 : 1;
6134 pd.didx = (dir == PF_IN) ? 1 : 0;
6135 pd.af = AF_INET6;
6136 pd.tos = 0;
6137 pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6138
6139 off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6140 pd.proto = h->ip6_nxt;
6141 do {
6142 switch (pd.proto) {
6143 case IPPROTO_FRAGMENT:
6144 action = pf_test_fragment(&r, dir, kif, m, h,
6145 &pd, &a, &ruleset);
6146 if (action == PF_DROP)
6147 REASON_SET(&reason, PFRES_FRAG);
6148 goto done;
6149 case IPPROTO_ROUTING: {
6150 struct ip6_rthdr rthdr;
6151
6152 if (rh_cnt++) {
6153 DPFPRINTF(PF_DEBUG_MISC,
6154 ("pf: IPv6 more than one rthdr\n"));
6155 action = PF_DROP;
6156 REASON_SET(&reason, PFRES_IPOPTIONS);
6157 log = 1;
6158 goto done;
6159 }
6160 if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6161 &reason, pd.af)) {
6162 DPFPRINTF(PF_DEBUG_MISC,
6163 ("pf: IPv6 short rthdr\n"));
6164 action = PF_DROP;
6165 REASON_SET(&reason, PFRES_SHORT);
6166 log = 1;
6167 goto done;
6168 }
6169 if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6170 DPFPRINTF(PF_DEBUG_MISC,
6171 ("pf: IPv6 rthdr0\n"));
6172 action = PF_DROP;
6173 REASON_SET(&reason, PFRES_IPOPTIONS);
6174 log = 1;
6175 goto done;
6176 }
6177 /* FALLTHROUGH */
6178 }
6179 case IPPROTO_AH:
6180 case IPPROTO_HOPOPTS:
6181 case IPPROTO_DSTOPTS: {
6182 /* get next header and header length */
6183 struct ip6_ext opt6;
6184
6185 if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6186 NULL, &reason, pd.af)) {
6187 DPFPRINTF(PF_DEBUG_MISC,
6188 ("pf: IPv6 short opt\n"));
6189 action = PF_DROP;
6190 log = 1;
6191 goto done;
6192 }
6193 if (pd.proto == IPPROTO_AH)
6194 off += (opt6.ip6e_len + 2) * 4;
6195 else
6196 off += (opt6.ip6e_len + 1) * 8;
6197 pd.proto = opt6.ip6e_nxt;
6198 /* goto the next header */
6199 break;
6200 }
6201 default:
6202 terminal++;
6203 break;
6204 }
6205 } while (!terminal);
6206
6207 /* if there's no routing header, use unmodified mbuf for checksumming */
6208 if (!n)
6209 n = m;
6210
6211 switch (pd.proto) {
6212
6213 case IPPROTO_TCP: {
6214 struct tcphdr th;
6215
6216 pd.hdr.tcp = &th;
6217 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6218 &action, &reason, AF_INET6)) {
6219 log = action != PF_PASS;
6220 goto done;
6221 }
6222 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6223 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6224 if (action == PF_DROP)
6225 goto done;
6226 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6227 &reason);
6228 if (action == PF_PASS) {
6229 if (pfsync_update_state_ptr != NULL)
6230 pfsync_update_state_ptr(s);
6231 r = s->rule.ptr;
6232 a = s->anchor.ptr;
6233 log = s->log;
6234 } else if (s == NULL)
6235 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6236 &a, &ruleset, inp);
6237 break;
6238 }
6239
6240 case IPPROTO_UDP: {
6241 struct udphdr uh;
6242
6243 pd.hdr.udp = &uh;
6244 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6245 &action, &reason, AF_INET6)) {
6246 log = action != PF_PASS;
6247 goto done;
6248 }
6249 if (uh.uh_dport == 0 ||
6250 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6251 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6252 action = PF_DROP;
6253 REASON_SET(&reason, PFRES_SHORT);
6254 goto done;
6255 }
6256 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6257 if (action == PF_PASS) {
6258 if (pfsync_update_state_ptr != NULL)
6259 pfsync_update_state_ptr(s);
6260 r = s->rule.ptr;
6261 a = s->anchor.ptr;
6262 log = s->log;
6263 } else if (s == NULL)
6264 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6265 &a, &ruleset, inp);
6266 break;
6267 }
6268
6269 case IPPROTO_ICMP: {
6270 action = PF_DROP;
6271 DPFPRINTF(PF_DEBUG_MISC,
6272 ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
6273 goto done;
6274 }
6275
6276 case IPPROTO_ICMPV6: {
6277 struct icmp6_hdr ih;
6278
6279 pd.hdr.icmp6 = &ih;
6280 if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6281 &action, &reason, AF_INET6)) {
6282 log = action != PF_PASS;
6283 goto done;
6284 }
6285 action = pf_test_state_icmp(&s, dir, kif,
6286 m, off, h, &pd, &reason);
6287 if (action == PF_PASS) {
6288 if (pfsync_update_state_ptr != NULL)
6289 pfsync_update_state_ptr(s);
6290 r = s->rule.ptr;
6291 a = s->anchor.ptr;
6292 log = s->log;
6293 } else if (s == NULL)
6294 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6295 &a, &ruleset, inp);
6296 break;
6297 }
6298
6299 default:
6300 action = pf_test_state_other(&s, dir, kif, m, &pd);
6301 if (action == PF_PASS) {
6302 if (pfsync_update_state_ptr != NULL)
6303 pfsync_update_state_ptr(s);
6304 r = s->rule.ptr;
6305 a = s->anchor.ptr;
6306 log = s->log;
6307 } else if (s == NULL)
6308 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6309 &a, &ruleset, inp);
6310 break;
6311 }
6312
6313done:
6314 PF_RULES_RUNLOCK();
6315 if (n != m) {
6316 m_freem(n);
6317 n = NULL;
6318 }
6319
6320 /* handle dangerous IPv6 extension headers. */
6321 if (action == PF_PASS && rh_cnt &&
6322 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6323 action = PF_DROP;
6324 REASON_SET(&reason, PFRES_IPOPTIONS);
6325 log = 1;
6326 DPFPRINTF(PF_DEBUG_MISC,
6327 ("pf: dropping packet with dangerous v6 headers\n"));
6328 }
6329
6330 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6331 action = PF_DROP;
6332 REASON_SET(&reason, PFRES_MEMORY);
6333 }
6334 if (r->rtableid >= 0)
6335 M_SETFIB(m, r->rtableid);
6336
6337#ifdef ALTQ
6338 if (action == PF_PASS && r->qid) {
6339 if (pd.pf_mtag == NULL &&
6340 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6341 action = PF_DROP;
6342 REASON_SET(&reason, PFRES_MEMORY);
6343 }
6344 if (pd.tos & IPTOS_LOWDELAY)
6345 pd.pf_mtag->qid = r->pqid;
6346 else
6347 pd.pf_mtag->qid = r->qid;
6348 /* add hints for ecn */
6349 pd.pf_mtag->hdr = h;
6350 }
6351#endif /* ALTQ */
6352
6353 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6354 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6355 (s->nat_rule.ptr->action == PF_RDR ||
6356 s->nat_rule.ptr->action == PF_BINAT) &&
6357 IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6358 m->m_flags |= M_SKIP_FIREWALL;
6359
6360 /* XXX: Anybody working on it?! */
6361 if (r->divert.port)
6362 printf("pf: divert(9) is not supported for IPv6\n");
6363
6364 if (log) {
6365 struct pf_rule *lr;
6366
6367 if (s != NULL && s->nat_rule.ptr != NULL &&
6368 s->nat_rule.ptr->log & PF_LOG_ALL)
6369 lr = s->nat_rule.ptr;
6370 else
6371 lr = r;
6372 PFLOG_PACKET(kif, m, AF_INET6, dir, reason, lr, a, ruleset,
6373 &pd, (s == NULL));
6374 }
6375
6376 kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6377 kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6378
6379 if (action == PF_PASS || r->action == PF_DROP) {
6380 dirndx = (dir == PF_OUT);
6381 r->packets[dirndx]++;
6382 r->bytes[dirndx] += pd.tot_len;
6383 if (a != NULL) {
6384 a->packets[dirndx]++;
6385 a->bytes[dirndx] += pd.tot_len;
6386 }
6387 if (s != NULL) {
6388 if (s->nat_rule.ptr != NULL) {
6389 s->nat_rule.ptr->packets[dirndx]++;
6390 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6391 }
6392 if (s->src_node != NULL) {
6393 s->src_node->packets[dirndx]++;
6394 s->src_node->bytes[dirndx] += pd.tot_len;
6395 }
6396 if (s->nat_src_node != NULL) {
6397 s->nat_src_node->packets[dirndx]++;
6398 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6399 }
6400 dirndx = (dir == s->direction) ? 0 : 1;
6401 s->packets[dirndx]++;
6402 s->bytes[dirndx] += pd.tot_len;
6403 }
6404 tr = r;
6405 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6406 if (nr != NULL && r == &V_pf_default_rule)
6407 tr = nr;
6408 if (tr->src.addr.type == PF_ADDR_TABLE)
6409 pfr_update_stats(tr->src.addr.p.tbl,
6410 (s == NULL) ? pd.src :
6411 &s->key[(s->direction == PF_IN)]->addr[0],
6412 pd.af, pd.tot_len, dir == PF_OUT,
6413 r->action == PF_PASS, tr->src.neg);
6414 if (tr->dst.addr.type == PF_ADDR_TABLE)
6415 pfr_update_stats(tr->dst.addr.p.tbl,
6416 (s == NULL) ? pd.dst :
6417 &s->key[(s->direction == PF_IN)]->addr[1],
6418 pd.af, pd.tot_len, dir == PF_OUT,
6419 r->action == PF_PASS, tr->dst.neg);
6420 }
6421
6422 switch (action) {
6423 case PF_SYNPROXY_DROP:
6424 m_freem(*m0);
6425 case PF_DEFER:
6426 *m0 = NULL;
6427 action = PF_PASS;
6428 break;
6429 case PF_DROP:
6430 m_freem(*m0);
6431 *m0 = NULL;
6432 break;
6433 default:
6434 /* pf_route6() returns unlocked. */
6435 if (r->rt) {
6436 pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd);
6437 return (action);
6438 }
6439 break;
6440 }
6441
6442 if (s)
6443 PF_STATE_UNLOCK(s);
6444
6445 /* If reassembled packet passed, create new fragments. */
6446 if (action == PF_PASS && *m0 && fwdir == PF_FWD &&
6447 (mtag = m_tag_find(m, PF_REASSEMBLED, NULL)) != NULL)
6448 action = pf_refragment6(ifp, m0, mtag);
6449
6450 return (action);
6451}
6452#endif /* INET6 */
3689 }
3690
3691 return (PF_DROP);
3692}
3693
3694static int
3695pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3696 struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3697 struct pf_ruleset **rsm)
3698{
3699 struct pf_rule *r, *a = NULL;
3700 struct pf_ruleset *ruleset = NULL;
3701 sa_family_t af = pd->af;
3702 u_short reason;
3703 int tag = -1;
3704 int asd = 0;
3705 int match = 0;
3706 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3707
3708 PF_RULES_RASSERT();
3709
3710 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3711 while (r != NULL) {
3712 r->evaluations++;
3713 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3714 r = r->skip[PF_SKIP_IFP].ptr;
3715 else if (r->direction && r->direction != direction)
3716 r = r->skip[PF_SKIP_DIR].ptr;
3717 else if (r->af && r->af != af)
3718 r = r->skip[PF_SKIP_AF].ptr;
3719 else if (r->proto && r->proto != pd->proto)
3720 r = r->skip[PF_SKIP_PROTO].ptr;
3721 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3722 r->src.neg, kif, M_GETFIB(m)))
3723 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3724 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3725 r->dst.neg, NULL, M_GETFIB(m)))
3726 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3727 else if (r->tos && !(r->tos == pd->tos))
3728 r = TAILQ_NEXT(r, entries);
3729 else if (r->os_fingerprint != PF_OSFP_ANY)
3730 r = TAILQ_NEXT(r, entries);
3731 else if (pd->proto == IPPROTO_UDP &&
3732 (r->src.port_op || r->dst.port_op))
3733 r = TAILQ_NEXT(r, entries);
3734 else if (pd->proto == IPPROTO_TCP &&
3735 (r->src.port_op || r->dst.port_op || r->flagset))
3736 r = TAILQ_NEXT(r, entries);
3737 else if ((pd->proto == IPPROTO_ICMP ||
3738 pd->proto == IPPROTO_ICMPV6) &&
3739 (r->type || r->code))
3740 r = TAILQ_NEXT(r, entries);
3741 else if (r->prob && r->prob <=
3742 (arc4random() % (UINT_MAX - 1) + 1))
3743 r = TAILQ_NEXT(r, entries);
3744 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3745 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3746 r = TAILQ_NEXT(r, entries);
3747 else {
3748 if (r->anchor == NULL) {
3749 match = 1;
3750 *rm = r;
3751 *am = a;
3752 *rsm = ruleset;
3753 if ((*rm)->quick)
3754 break;
3755 r = TAILQ_NEXT(r, entries);
3756 } else
3757 pf_step_into_anchor(anchor_stack, &asd,
3758 &ruleset, PF_RULESET_FILTER, &r, &a,
3759 &match);
3760 }
3761 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3762 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3763 break;
3764 }
3765 r = *rm;
3766 a = *am;
3767 ruleset = *rsm;
3768
3769 REASON_SET(&reason, PFRES_MATCH);
3770
3771 if (r->log)
3772 PFLOG_PACKET(kif, m, af, direction, reason, r, a, ruleset, pd,
3773 1);
3774
3775 if (r->action != PF_PASS)
3776 return (PF_DROP);
3777
3778 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3779 REASON_SET(&reason, PFRES_MEMORY);
3780 return (PF_DROP);
3781 }
3782
3783 return (PF_PASS);
3784}
3785
3786static int
3787pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
3788 struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
3789 struct pf_pdesc *pd, u_short *reason, int *copyback)
3790{
3791 struct tcphdr *th = pd->hdr.tcp;
3792 u_int16_t win = ntohs(th->th_win);
3793 u_int32_t ack, end, seq, orig_seq;
3794 u_int8_t sws, dws;
3795 int ackskew;
3796
3797 if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3798 sws = src->wscale & PF_WSCALE_MASK;
3799 dws = dst->wscale & PF_WSCALE_MASK;
3800 } else
3801 sws = dws = 0;
3802
3803 /*
3804 * Sequence tracking algorithm from Guido van Rooij's paper:
3805 * http://www.madison-gurkha.com/publications/tcp_filtering/
3806 * tcp_filtering.ps
3807 */
3808
3809 orig_seq = seq = ntohl(th->th_seq);
3810 if (src->seqlo == 0) {
3811 /* First packet from this end. Set its state */
3812
3813 if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
3814 src->scrub == NULL) {
3815 if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
3816 REASON_SET(reason, PFRES_MEMORY);
3817 return (PF_DROP);
3818 }
3819 }
3820
3821 /* Deferred generation of sequence number modulator */
3822 if (dst->seqdiff && !src->seqdiff) {
3823 /* use random iss for the TCP server */
3824 while ((src->seqdiff = arc4random() - seq) == 0)
3825 ;
3826 ack = ntohl(th->th_ack) - dst->seqdiff;
3827 pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
3828 src->seqdiff), 0);
3829 pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
3830 *copyback = 1;
3831 } else {
3832 ack = ntohl(th->th_ack);
3833 }
3834
3835 end = seq + pd->p_len;
3836 if (th->th_flags & TH_SYN) {
3837 end++;
3838 if (dst->wscale & PF_WSCALE_FLAG) {
3839 src->wscale = pf_get_wscale(m, off, th->th_off,
3840 pd->af);
3841 if (src->wscale & PF_WSCALE_FLAG) {
3842 /* Remove scale factor from initial
3843 * window */
3844 sws = src->wscale & PF_WSCALE_MASK;
3845 win = ((u_int32_t)win + (1 << sws) - 1)
3846 >> sws;
3847 dws = dst->wscale & PF_WSCALE_MASK;
3848 } else {
3849 /* fixup other window */
3850 dst->max_win <<= dst->wscale &
3851 PF_WSCALE_MASK;
3852 /* in case of a retrans SYN|ACK */
3853 dst->wscale = 0;
3854 }
3855 }
3856 }
3857 if (th->th_flags & TH_FIN)
3858 end++;
3859
3860 src->seqlo = seq;
3861 if (src->state < TCPS_SYN_SENT)
3862 src->state = TCPS_SYN_SENT;
3863
3864 /*
3865 * May need to slide the window (seqhi may have been set by
3866 * the crappy stack check or if we picked up the connection
3867 * after establishment)
3868 */
3869 if (src->seqhi == 1 ||
3870 SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
3871 src->seqhi = end + MAX(1, dst->max_win << dws);
3872 if (win > src->max_win)
3873 src->max_win = win;
3874
3875 } else {
3876 ack = ntohl(th->th_ack) - dst->seqdiff;
3877 if (src->seqdiff) {
3878 /* Modulate sequence numbers */
3879 pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
3880 src->seqdiff), 0);
3881 pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
3882 *copyback = 1;
3883 }
3884 end = seq + pd->p_len;
3885 if (th->th_flags & TH_SYN)
3886 end++;
3887 if (th->th_flags & TH_FIN)
3888 end++;
3889 }
3890
3891 if ((th->th_flags & TH_ACK) == 0) {
3892 /* Let it pass through the ack skew check */
3893 ack = dst->seqlo;
3894 } else if ((ack == 0 &&
3895 (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
3896 /* broken tcp stacks do not set ack */
3897 (dst->state < TCPS_SYN_SENT)) {
3898 /*
3899 * Many stacks (ours included) will set the ACK number in an
3900 * FIN|ACK if the SYN times out -- no sequence to ACK.
3901 */
3902 ack = dst->seqlo;
3903 }
3904
3905 if (seq == end) {
3906 /* Ease sequencing restrictions on no data packets */
3907 seq = src->seqlo;
3908 end = seq;
3909 }
3910
3911 ackskew = dst->seqlo - ack;
3912
3913
3914 /*
3915 * Need to demodulate the sequence numbers in any TCP SACK options
3916 * (Selective ACK). We could optionally validate the SACK values
3917 * against the current ACK window, either forwards or backwards, but
3918 * I'm not confident that SACK has been implemented properly
3919 * everywhere. It wouldn't surprise me if several stacks accidently
3920 * SACK too far backwards of previously ACKed data. There really aren't
3921 * any security implications of bad SACKing unless the target stack
3922 * doesn't validate the option length correctly. Someone trying to
3923 * spoof into a TCP connection won't bother blindly sending SACK
3924 * options anyway.
3925 */
3926 if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
3927 if (pf_modulate_sack(m, off, pd, th, dst))
3928 *copyback = 1;
3929 }
3930
3931
3932#define MAXACKWINDOW (0xffff + 1500) /* 1500 is an arbitrary fudge factor */
3933 if (SEQ_GEQ(src->seqhi, end) &&
3934 /* Last octet inside other's window space */
3935 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
3936 /* Retrans: not more than one window back */
3937 (ackskew >= -MAXACKWINDOW) &&
3938 /* Acking not more than one reassembled fragment backwards */
3939 (ackskew <= (MAXACKWINDOW << sws)) &&
3940 /* Acking not more than one window forward */
3941 ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
3942 (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
3943 (pd->flags & PFDESC_IP_REAS) == 0)) {
3944 /* Require an exact/+1 sequence match on resets when possible */
3945
3946 if (dst->scrub || src->scrub) {
3947 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
3948 *state, src, dst, copyback))
3949 return (PF_DROP);
3950 }
3951
3952 /* update max window */
3953 if (src->max_win < win)
3954 src->max_win = win;
3955 /* synchronize sequencing */
3956 if (SEQ_GT(end, src->seqlo))
3957 src->seqlo = end;
3958 /* slide the window of what the other end can send */
3959 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
3960 dst->seqhi = ack + MAX((win << sws), 1);
3961
3962
3963 /* update states */
3964 if (th->th_flags & TH_SYN)
3965 if (src->state < TCPS_SYN_SENT)
3966 src->state = TCPS_SYN_SENT;
3967 if (th->th_flags & TH_FIN)
3968 if (src->state < TCPS_CLOSING)
3969 src->state = TCPS_CLOSING;
3970 if (th->th_flags & TH_ACK) {
3971 if (dst->state == TCPS_SYN_SENT) {
3972 dst->state = TCPS_ESTABLISHED;
3973 if (src->state == TCPS_ESTABLISHED &&
3974 (*state)->src_node != NULL &&
3975 pf_src_connlimit(state)) {
3976 REASON_SET(reason, PFRES_SRCLIMIT);
3977 return (PF_DROP);
3978 }
3979 } else if (dst->state == TCPS_CLOSING)
3980 dst->state = TCPS_FIN_WAIT_2;
3981 }
3982 if (th->th_flags & TH_RST)
3983 src->state = dst->state = TCPS_TIME_WAIT;
3984
3985 /* update expire time */
3986 (*state)->expire = time_uptime;
3987 if (src->state >= TCPS_FIN_WAIT_2 &&
3988 dst->state >= TCPS_FIN_WAIT_2)
3989 (*state)->timeout = PFTM_TCP_CLOSED;
3990 else if (src->state >= TCPS_CLOSING &&
3991 dst->state >= TCPS_CLOSING)
3992 (*state)->timeout = PFTM_TCP_FIN_WAIT;
3993 else if (src->state < TCPS_ESTABLISHED ||
3994 dst->state < TCPS_ESTABLISHED)
3995 (*state)->timeout = PFTM_TCP_OPENING;
3996 else if (src->state >= TCPS_CLOSING ||
3997 dst->state >= TCPS_CLOSING)
3998 (*state)->timeout = PFTM_TCP_CLOSING;
3999 else
4000 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4001
4002 /* Fall through to PASS packet */
4003
4004 } else if ((dst->state < TCPS_SYN_SENT ||
4005 dst->state >= TCPS_FIN_WAIT_2 ||
4006 src->state >= TCPS_FIN_WAIT_2) &&
4007 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
4008 /* Within a window forward of the originating packet */
4009 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
4010 /* Within a window backward of the originating packet */
4011
4012 /*
4013 * This currently handles three situations:
4014 * 1) Stupid stacks will shotgun SYNs before their peer
4015 * replies.
4016 * 2) When PF catches an already established stream (the
4017 * firewall rebooted, the state table was flushed, routes
4018 * changed...)
4019 * 3) Packets get funky immediately after the connection
4020 * closes (this should catch Solaris spurious ACK|FINs
4021 * that web servers like to spew after a close)
4022 *
4023 * This must be a little more careful than the above code
4024 * since packet floods will also be caught here. We don't
4025 * update the TTL here to mitigate the damage of a packet
4026 * flood and so the same code can handle awkward establishment
4027 * and a loosened connection close.
4028 * In the establishment case, a correct peer response will
4029 * validate the connection, go through the normal state code
4030 * and keep updating the state TTL.
4031 */
4032
4033 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4034 printf("pf: loose state match: ");
4035 pf_print_state(*state);
4036 pf_print_flags(th->th_flags);
4037 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4038 "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
4039 pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
4040 (unsigned long long)(*state)->packets[1],
4041 pd->dir == PF_IN ? "in" : "out",
4042 pd->dir == (*state)->direction ? "fwd" : "rev");
4043 }
4044
4045 if (dst->scrub || src->scrub) {
4046 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4047 *state, src, dst, copyback))
4048 return (PF_DROP);
4049 }
4050
4051 /* update max window */
4052 if (src->max_win < win)
4053 src->max_win = win;
4054 /* synchronize sequencing */
4055 if (SEQ_GT(end, src->seqlo))
4056 src->seqlo = end;
4057 /* slide the window of what the other end can send */
4058 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4059 dst->seqhi = ack + MAX((win << sws), 1);
4060
4061 /*
4062 * Cannot set dst->seqhi here since this could be a shotgunned
4063 * SYN and not an already established connection.
4064 */
4065
4066 if (th->th_flags & TH_FIN)
4067 if (src->state < TCPS_CLOSING)
4068 src->state = TCPS_CLOSING;
4069 if (th->th_flags & TH_RST)
4070 src->state = dst->state = TCPS_TIME_WAIT;
4071
4072 /* Fall through to PASS packet */
4073
4074 } else {
4075 if ((*state)->dst.state == TCPS_SYN_SENT &&
4076 (*state)->src.state == TCPS_SYN_SENT) {
4077 /* Send RST for state mismatches during handshake */
4078 if (!(th->th_flags & TH_RST))
4079 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4080 pd->dst, pd->src, th->th_dport,
4081 th->th_sport, ntohl(th->th_ack), 0,
4082 TH_RST, 0, 0,
4083 (*state)->rule.ptr->return_ttl, 1, 0,
4084 kif->pfik_ifp);
4085 src->seqlo = 0;
4086 src->seqhi = 1;
4087 src->max_win = 1;
4088 } else if (V_pf_status.debug >= PF_DEBUG_MISC) {
4089 printf("pf: BAD state: ");
4090 pf_print_state(*state);
4091 pf_print_flags(th->th_flags);
4092 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4093 "pkts=%llu:%llu dir=%s,%s\n",
4094 seq, orig_seq, ack, pd->p_len, ackskew,
4095 (unsigned long long)(*state)->packets[0],
4096 (unsigned long long)(*state)->packets[1],
4097 pd->dir == PF_IN ? "in" : "out",
4098 pd->dir == (*state)->direction ? "fwd" : "rev");
4099 printf("pf: State failure on: %c %c %c %c | %c %c\n",
4100 SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4101 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4102 ' ': '2',
4103 (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4104 (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4105 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4106 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4107 }
4108 REASON_SET(reason, PFRES_BADSTATE);
4109 return (PF_DROP);
4110 }
4111
4112 return (PF_PASS);
4113}
4114
4115static int
4116pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4117 struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4118{
4119 struct tcphdr *th = pd->hdr.tcp;
4120
4121 if (th->th_flags & TH_SYN)
4122 if (src->state < TCPS_SYN_SENT)
4123 src->state = TCPS_SYN_SENT;
4124 if (th->th_flags & TH_FIN)
4125 if (src->state < TCPS_CLOSING)
4126 src->state = TCPS_CLOSING;
4127 if (th->th_flags & TH_ACK) {
4128 if (dst->state == TCPS_SYN_SENT) {
4129 dst->state = TCPS_ESTABLISHED;
4130 if (src->state == TCPS_ESTABLISHED &&
4131 (*state)->src_node != NULL &&
4132 pf_src_connlimit(state)) {
4133 REASON_SET(reason, PFRES_SRCLIMIT);
4134 return (PF_DROP);
4135 }
4136 } else if (dst->state == TCPS_CLOSING) {
4137 dst->state = TCPS_FIN_WAIT_2;
4138 } else if (src->state == TCPS_SYN_SENT &&
4139 dst->state < TCPS_SYN_SENT) {
4140 /*
4141 * Handle a special sloppy case where we only see one
4142 * half of the connection. If there is a ACK after
4143 * the initial SYN without ever seeing a packet from
4144 * the destination, set the connection to established.
4145 */
4146 dst->state = src->state = TCPS_ESTABLISHED;
4147 if ((*state)->src_node != NULL &&
4148 pf_src_connlimit(state)) {
4149 REASON_SET(reason, PFRES_SRCLIMIT);
4150 return (PF_DROP);
4151 }
4152 } else if (src->state == TCPS_CLOSING &&
4153 dst->state == TCPS_ESTABLISHED &&
4154 dst->seqlo == 0) {
4155 /*
4156 * Handle the closing of half connections where we
4157 * don't see the full bidirectional FIN/ACK+ACK
4158 * handshake.
4159 */
4160 dst->state = TCPS_CLOSING;
4161 }
4162 }
4163 if (th->th_flags & TH_RST)
4164 src->state = dst->state = TCPS_TIME_WAIT;
4165
4166 /* update expire time */
4167 (*state)->expire = time_uptime;
4168 if (src->state >= TCPS_FIN_WAIT_2 &&
4169 dst->state >= TCPS_FIN_WAIT_2)
4170 (*state)->timeout = PFTM_TCP_CLOSED;
4171 else if (src->state >= TCPS_CLOSING &&
4172 dst->state >= TCPS_CLOSING)
4173 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4174 else if (src->state < TCPS_ESTABLISHED ||
4175 dst->state < TCPS_ESTABLISHED)
4176 (*state)->timeout = PFTM_TCP_OPENING;
4177 else if (src->state >= TCPS_CLOSING ||
4178 dst->state >= TCPS_CLOSING)
4179 (*state)->timeout = PFTM_TCP_CLOSING;
4180 else
4181 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4182
4183 return (PF_PASS);
4184}
4185
4186static int
4187pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4188 struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4189 u_short *reason)
4190{
4191 struct pf_state_key_cmp key;
4192 struct tcphdr *th = pd->hdr.tcp;
4193 int copyback = 0;
4194 struct pf_state_peer *src, *dst;
4195 struct pf_state_key *sk;
4196
4197 bzero(&key, sizeof(key));
4198 key.af = pd->af;
4199 key.proto = IPPROTO_TCP;
4200 if (direction == PF_IN) { /* wire side, straight */
4201 PF_ACPY(&key.addr[0], pd->src, key.af);
4202 PF_ACPY(&key.addr[1], pd->dst, key.af);
4203 key.port[0] = th->th_sport;
4204 key.port[1] = th->th_dport;
4205 } else { /* stack side, reverse */
4206 PF_ACPY(&key.addr[1], pd->src, key.af);
4207 PF_ACPY(&key.addr[0], pd->dst, key.af);
4208 key.port[1] = th->th_sport;
4209 key.port[0] = th->th_dport;
4210 }
4211
4212 STATE_LOOKUP(kif, &key, direction, *state, pd);
4213
4214 if (direction == (*state)->direction) {
4215 src = &(*state)->src;
4216 dst = &(*state)->dst;
4217 } else {
4218 src = &(*state)->dst;
4219 dst = &(*state)->src;
4220 }
4221
4222 sk = (*state)->key[pd->didx];
4223
4224 if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4225 if (direction != (*state)->direction) {
4226 REASON_SET(reason, PFRES_SYNPROXY);
4227 return (PF_SYNPROXY_DROP);
4228 }
4229 if (th->th_flags & TH_SYN) {
4230 if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4231 REASON_SET(reason, PFRES_SYNPROXY);
4232 return (PF_DROP);
4233 }
4234 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4235 pd->src, th->th_dport, th->th_sport,
4236 (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4237 TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1, 0, NULL);
4238 REASON_SET(reason, PFRES_SYNPROXY);
4239 return (PF_SYNPROXY_DROP);
4240 } else if (!(th->th_flags & TH_ACK) ||
4241 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4242 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4243 REASON_SET(reason, PFRES_SYNPROXY);
4244 return (PF_DROP);
4245 } else if ((*state)->src_node != NULL &&
4246 pf_src_connlimit(state)) {
4247 REASON_SET(reason, PFRES_SRCLIMIT);
4248 return (PF_DROP);
4249 } else
4250 (*state)->src.state = PF_TCPS_PROXY_DST;
4251 }
4252 if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4253 if (direction == (*state)->direction) {
4254 if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4255 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4256 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4257 REASON_SET(reason, PFRES_SYNPROXY);
4258 return (PF_DROP);
4259 }
4260 (*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4261 if ((*state)->dst.seqhi == 1)
4262 (*state)->dst.seqhi = htonl(arc4random());
4263 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4264 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4265 sk->port[pd->sidx], sk->port[pd->didx],
4266 (*state)->dst.seqhi, 0, TH_SYN, 0,
4267 (*state)->src.mss, 0, 0, (*state)->tag, NULL);
4268 REASON_SET(reason, PFRES_SYNPROXY);
4269 return (PF_SYNPROXY_DROP);
4270 } else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4271 (TH_SYN|TH_ACK)) ||
4272 (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4273 REASON_SET(reason, PFRES_SYNPROXY);
4274 return (PF_DROP);
4275 } else {
4276 (*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4277 (*state)->dst.seqlo = ntohl(th->th_seq);
4278 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4279 pd->src, th->th_dport, th->th_sport,
4280 ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4281 TH_ACK, (*state)->src.max_win, 0, 0, 0,
4282 (*state)->tag, NULL);
4283 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4284 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4285 sk->port[pd->sidx], sk->port[pd->didx],
4286 (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4287 TH_ACK, (*state)->dst.max_win, 0, 0, 1, 0, NULL);
4288 (*state)->src.seqdiff = (*state)->dst.seqhi -
4289 (*state)->src.seqlo;
4290 (*state)->dst.seqdiff = (*state)->src.seqhi -
4291 (*state)->dst.seqlo;
4292 (*state)->src.seqhi = (*state)->src.seqlo +
4293 (*state)->dst.max_win;
4294 (*state)->dst.seqhi = (*state)->dst.seqlo +
4295 (*state)->src.max_win;
4296 (*state)->src.wscale = (*state)->dst.wscale = 0;
4297 (*state)->src.state = (*state)->dst.state =
4298 TCPS_ESTABLISHED;
4299 REASON_SET(reason, PFRES_SYNPROXY);
4300 return (PF_SYNPROXY_DROP);
4301 }
4302 }
4303
4304 if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4305 dst->state >= TCPS_FIN_WAIT_2 &&
4306 src->state >= TCPS_FIN_WAIT_2) {
4307 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4308 printf("pf: state reuse ");
4309 pf_print_state(*state);
4310 pf_print_flags(th->th_flags);
4311 printf("\n");
4312 }
4313 /* XXX make sure it's the same direction ?? */
4314 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4315 pf_unlink_state(*state, PF_ENTER_LOCKED);
4316 *state = NULL;
4317 return (PF_DROP);
4318 }
4319
4320 if ((*state)->state_flags & PFSTATE_SLOPPY) {
4321 if (pf_tcp_track_sloppy(src, dst, state, pd, reason) == PF_DROP)
4322 return (PF_DROP);
4323 } else {
4324 if (pf_tcp_track_full(src, dst, state, kif, m, off, pd, reason,
4325 &copyback) == PF_DROP)
4326 return (PF_DROP);
4327 }
4328
4329 /* translate source/destination address, if necessary */
4330 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4331 struct pf_state_key *nk = (*state)->key[pd->didx];
4332
4333 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4334 nk->port[pd->sidx] != th->th_sport)
4335 pf_change_ap(pd->src, &th->th_sport, pd->ip_sum,
4336 &th->th_sum, &nk->addr[pd->sidx],
4337 nk->port[pd->sidx], 0, pd->af);
4338
4339 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4340 nk->port[pd->didx] != th->th_dport)
4341 pf_change_ap(pd->dst, &th->th_dport, pd->ip_sum,
4342 &th->th_sum, &nk->addr[pd->didx],
4343 nk->port[pd->didx], 0, pd->af);
4344 copyback = 1;
4345 }
4346
4347 /* Copyback sequence modulation or stateful scrub changes if needed */
4348 if (copyback)
4349 m_copyback(m, off, sizeof(*th), (caddr_t)th);
4350
4351 return (PF_PASS);
4352}
4353
4354static int
4355pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4356 struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4357{
4358 struct pf_state_peer *src, *dst;
4359 struct pf_state_key_cmp key;
4360 struct udphdr *uh = pd->hdr.udp;
4361
4362 bzero(&key, sizeof(key));
4363 key.af = pd->af;
4364 key.proto = IPPROTO_UDP;
4365 if (direction == PF_IN) { /* wire side, straight */
4366 PF_ACPY(&key.addr[0], pd->src, key.af);
4367 PF_ACPY(&key.addr[1], pd->dst, key.af);
4368 key.port[0] = uh->uh_sport;
4369 key.port[1] = uh->uh_dport;
4370 } else { /* stack side, reverse */
4371 PF_ACPY(&key.addr[1], pd->src, key.af);
4372 PF_ACPY(&key.addr[0], pd->dst, key.af);
4373 key.port[1] = uh->uh_sport;
4374 key.port[0] = uh->uh_dport;
4375 }
4376
4377 STATE_LOOKUP(kif, &key, direction, *state, pd);
4378
4379 if (direction == (*state)->direction) {
4380 src = &(*state)->src;
4381 dst = &(*state)->dst;
4382 } else {
4383 src = &(*state)->dst;
4384 dst = &(*state)->src;
4385 }
4386
4387 /* update states */
4388 if (src->state < PFUDPS_SINGLE)
4389 src->state = PFUDPS_SINGLE;
4390 if (dst->state == PFUDPS_SINGLE)
4391 dst->state = PFUDPS_MULTIPLE;
4392
4393 /* update expire time */
4394 (*state)->expire = time_uptime;
4395 if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4396 (*state)->timeout = PFTM_UDP_MULTIPLE;
4397 else
4398 (*state)->timeout = PFTM_UDP_SINGLE;
4399
4400 /* translate source/destination address, if necessary */
4401 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4402 struct pf_state_key *nk = (*state)->key[pd->didx];
4403
4404 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4405 nk->port[pd->sidx] != uh->uh_sport)
4406 pf_change_ap(pd->src, &uh->uh_sport, pd->ip_sum,
4407 &uh->uh_sum, &nk->addr[pd->sidx],
4408 nk->port[pd->sidx], 1, pd->af);
4409
4410 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4411 nk->port[pd->didx] != uh->uh_dport)
4412 pf_change_ap(pd->dst, &uh->uh_dport, pd->ip_sum,
4413 &uh->uh_sum, &nk->addr[pd->didx],
4414 nk->port[pd->didx], 1, pd->af);
4415 m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4416 }
4417
4418 return (PF_PASS);
4419}
4420
4421static int
4422pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4423 struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
4424{
4425 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
4426 u_int16_t icmpid = 0, *icmpsum;
4427 u_int8_t icmptype;
4428 int state_icmp = 0;
4429 struct pf_state_key_cmp key;
4430
4431 bzero(&key, sizeof(key));
4432 switch (pd->proto) {
4433#ifdef INET
4434 case IPPROTO_ICMP:
4435 icmptype = pd->hdr.icmp->icmp_type;
4436 icmpid = pd->hdr.icmp->icmp_id;
4437 icmpsum = &pd->hdr.icmp->icmp_cksum;
4438
4439 if (icmptype == ICMP_UNREACH ||
4440 icmptype == ICMP_SOURCEQUENCH ||
4441 icmptype == ICMP_REDIRECT ||
4442 icmptype == ICMP_TIMXCEED ||
4443 icmptype == ICMP_PARAMPROB)
4444 state_icmp++;
4445 break;
4446#endif /* INET */
4447#ifdef INET6
4448 case IPPROTO_ICMPV6:
4449 icmptype = pd->hdr.icmp6->icmp6_type;
4450 icmpid = pd->hdr.icmp6->icmp6_id;
4451 icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4452
4453 if (icmptype == ICMP6_DST_UNREACH ||
4454 icmptype == ICMP6_PACKET_TOO_BIG ||
4455 icmptype == ICMP6_TIME_EXCEEDED ||
4456 icmptype == ICMP6_PARAM_PROB)
4457 state_icmp++;
4458 break;
4459#endif /* INET6 */
4460 }
4461
4462 if (!state_icmp) {
4463
4464 /*
4465 * ICMP query/reply message not related to a TCP/UDP packet.
4466 * Search for an ICMP state.
4467 */
4468 key.af = pd->af;
4469 key.proto = pd->proto;
4470 key.port[0] = key.port[1] = icmpid;
4471 if (direction == PF_IN) { /* wire side, straight */
4472 PF_ACPY(&key.addr[0], pd->src, key.af);
4473 PF_ACPY(&key.addr[1], pd->dst, key.af);
4474 } else { /* stack side, reverse */
4475 PF_ACPY(&key.addr[1], pd->src, key.af);
4476 PF_ACPY(&key.addr[0], pd->dst, key.af);
4477 }
4478
4479 STATE_LOOKUP(kif, &key, direction, *state, pd);
4480
4481 (*state)->expire = time_uptime;
4482 (*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4483
4484 /* translate source/destination address, if necessary */
4485 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4486 struct pf_state_key *nk = (*state)->key[pd->didx];
4487
4488 switch (pd->af) {
4489#ifdef INET
4490 case AF_INET:
4491 if (PF_ANEQ(pd->src,
4492 &nk->addr[pd->sidx], AF_INET))
4493 pf_change_a(&saddr->v4.s_addr,
4494 pd->ip_sum,
4495 nk->addr[pd->sidx].v4.s_addr, 0);
4496
4497 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
4498 AF_INET))
4499 pf_change_a(&daddr->v4.s_addr,
4500 pd->ip_sum,
4501 nk->addr[pd->didx].v4.s_addr, 0);
4502
4503 if (nk->port[0] !=
4504 pd->hdr.icmp->icmp_id) {
4505 pd->hdr.icmp->icmp_cksum =
4506 pf_cksum_fixup(
4507 pd->hdr.icmp->icmp_cksum, icmpid,
4508 nk->port[pd->sidx], 0);
4509 pd->hdr.icmp->icmp_id =
4510 nk->port[pd->sidx];
4511 }
4512
4513 m_copyback(m, off, ICMP_MINLEN,
4514 (caddr_t )pd->hdr.icmp);
4515 break;
4516#endif /* INET */
4517#ifdef INET6
4518 case AF_INET6:
4519 if (PF_ANEQ(pd->src,
4520 &nk->addr[pd->sidx], AF_INET6))
4521 pf_change_a6(saddr,
4522 &pd->hdr.icmp6->icmp6_cksum,
4523 &nk->addr[pd->sidx], 0);
4524
4525 if (PF_ANEQ(pd->dst,
4526 &nk->addr[pd->didx], AF_INET6))
4527 pf_change_a6(daddr,
4528 &pd->hdr.icmp6->icmp6_cksum,
4529 &nk->addr[pd->didx], 0);
4530
4531 m_copyback(m, off, sizeof(struct icmp6_hdr),
4532 (caddr_t )pd->hdr.icmp6);
4533 break;
4534#endif /* INET6 */
4535 }
4536 }
4537 return (PF_PASS);
4538
4539 } else {
4540 /*
4541 * ICMP error message in response to a TCP/UDP packet.
4542 * Extract the inner TCP/UDP header and search for that state.
4543 */
4544
4545 struct pf_pdesc pd2;
4546 bzero(&pd2, sizeof pd2);
4547#ifdef INET
4548 struct ip h2;
4549#endif /* INET */
4550#ifdef INET6
4551 struct ip6_hdr h2_6;
4552 int terminal = 0;
4553#endif /* INET6 */
4554 int ipoff2 = 0;
4555 int off2 = 0;
4556
4557 pd2.af = pd->af;
4558 /* Payload packet is from the opposite direction. */
4559 pd2.sidx = (direction == PF_IN) ? 1 : 0;
4560 pd2.didx = (direction == PF_IN) ? 0 : 1;
4561 switch (pd->af) {
4562#ifdef INET
4563 case AF_INET:
4564 /* offset of h2 in mbuf chain */
4565 ipoff2 = off + ICMP_MINLEN;
4566
4567 if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
4568 NULL, reason, pd2.af)) {
4569 DPFPRINTF(PF_DEBUG_MISC,
4570 ("pf: ICMP error message too short "
4571 "(ip)\n"));
4572 return (PF_DROP);
4573 }
4574 /*
4575 * ICMP error messages don't refer to non-first
4576 * fragments
4577 */
4578 if (h2.ip_off & htons(IP_OFFMASK)) {
4579 REASON_SET(reason, PFRES_FRAG);
4580 return (PF_DROP);
4581 }
4582
4583 /* offset of protocol header that follows h2 */
4584 off2 = ipoff2 + (h2.ip_hl << 2);
4585
4586 pd2.proto = h2.ip_p;
4587 pd2.src = (struct pf_addr *)&h2.ip_src;
4588 pd2.dst = (struct pf_addr *)&h2.ip_dst;
4589 pd2.ip_sum = &h2.ip_sum;
4590 break;
4591#endif /* INET */
4592#ifdef INET6
4593 case AF_INET6:
4594 ipoff2 = off + sizeof(struct icmp6_hdr);
4595
4596 if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
4597 NULL, reason, pd2.af)) {
4598 DPFPRINTF(PF_DEBUG_MISC,
4599 ("pf: ICMP error message too short "
4600 "(ip6)\n"));
4601 return (PF_DROP);
4602 }
4603 pd2.proto = h2_6.ip6_nxt;
4604 pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4605 pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4606 pd2.ip_sum = NULL;
4607 off2 = ipoff2 + sizeof(h2_6);
4608 do {
4609 switch (pd2.proto) {
4610 case IPPROTO_FRAGMENT:
4611 /*
4612 * ICMPv6 error messages for
4613 * non-first fragments
4614 */
4615 REASON_SET(reason, PFRES_FRAG);
4616 return (PF_DROP);
4617 case IPPROTO_AH:
4618 case IPPROTO_HOPOPTS:
4619 case IPPROTO_ROUTING:
4620 case IPPROTO_DSTOPTS: {
4621 /* get next header and header length */
4622 struct ip6_ext opt6;
4623
4624 if (!pf_pull_hdr(m, off2, &opt6,
4625 sizeof(opt6), NULL, reason,
4626 pd2.af)) {
4627 DPFPRINTF(PF_DEBUG_MISC,
4628 ("pf: ICMPv6 short opt\n"));
4629 return (PF_DROP);
4630 }
4631 if (pd2.proto == IPPROTO_AH)
4632 off2 += (opt6.ip6e_len + 2) * 4;
4633 else
4634 off2 += (opt6.ip6e_len + 1) * 8;
4635 pd2.proto = opt6.ip6e_nxt;
4636 /* goto the next header */
4637 break;
4638 }
4639 default:
4640 terminal++;
4641 break;
4642 }
4643 } while (!terminal);
4644 break;
4645#endif /* INET6 */
4646 }
4647
4648 switch (pd2.proto) {
4649 case IPPROTO_TCP: {
4650 struct tcphdr th;
4651 u_int32_t seq;
4652 struct pf_state_peer *src, *dst;
4653 u_int8_t dws;
4654 int copyback = 0;
4655
4656 /*
4657 * Only the first 8 bytes of the TCP header can be
4658 * expected. Don't access any TCP header fields after
4659 * th_seq, an ackskew test is not possible.
4660 */
4661 if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
4662 pd2.af)) {
4663 DPFPRINTF(PF_DEBUG_MISC,
4664 ("pf: ICMP error message too short "
4665 "(tcp)\n"));
4666 return (PF_DROP);
4667 }
4668
4669 key.af = pd2.af;
4670 key.proto = IPPROTO_TCP;
4671 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4672 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4673 key.port[pd2.sidx] = th.th_sport;
4674 key.port[pd2.didx] = th.th_dport;
4675
4676 STATE_LOOKUP(kif, &key, direction, *state, pd);
4677
4678 if (direction == (*state)->direction) {
4679 src = &(*state)->dst;
4680 dst = &(*state)->src;
4681 } else {
4682 src = &(*state)->src;
4683 dst = &(*state)->dst;
4684 }
4685
4686 if (src->wscale && dst->wscale)
4687 dws = dst->wscale & PF_WSCALE_MASK;
4688 else
4689 dws = 0;
4690
4691 /* Demodulate sequence number */
4692 seq = ntohl(th.th_seq) - src->seqdiff;
4693 if (src->seqdiff) {
4694 pf_change_a(&th.th_seq, icmpsum,
4695 htonl(seq), 0);
4696 copyback = 1;
4697 }
4698
4699 if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
4700 (!SEQ_GEQ(src->seqhi, seq) ||
4701 !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
4702 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4703 printf("pf: BAD ICMP %d:%d ",
4704 icmptype, pd->hdr.icmp->icmp_code);
4705 pf_print_host(pd->src, 0, pd->af);
4706 printf(" -> ");
4707 pf_print_host(pd->dst, 0, pd->af);
4708 printf(" state: ");
4709 pf_print_state(*state);
4710 printf(" seq=%u\n", seq);
4711 }
4712 REASON_SET(reason, PFRES_BADSTATE);
4713 return (PF_DROP);
4714 } else {
4715 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4716 printf("pf: OK ICMP %d:%d ",
4717 icmptype, pd->hdr.icmp->icmp_code);
4718 pf_print_host(pd->src, 0, pd->af);
4719 printf(" -> ");
4720 pf_print_host(pd->dst, 0, pd->af);
4721 printf(" state: ");
4722 pf_print_state(*state);
4723 printf(" seq=%u\n", seq);
4724 }
4725 }
4726
4727 /* translate source/destination address, if necessary */
4728 if ((*state)->key[PF_SK_WIRE] !=
4729 (*state)->key[PF_SK_STACK]) {
4730 struct pf_state_key *nk =
4731 (*state)->key[pd->didx];
4732
4733 if (PF_ANEQ(pd2.src,
4734 &nk->addr[pd2.sidx], pd2.af) ||
4735 nk->port[pd2.sidx] != th.th_sport)
4736 pf_change_icmp(pd2.src, &th.th_sport,
4737 daddr, &nk->addr[pd2.sidx],
4738 nk->port[pd2.sidx], NULL,
4739 pd2.ip_sum, icmpsum,
4740 pd->ip_sum, 0, pd2.af);
4741
4742 if (PF_ANEQ(pd2.dst,
4743 &nk->addr[pd2.didx], pd2.af) ||
4744 nk->port[pd2.didx] != th.th_dport)
4745 pf_change_icmp(pd2.dst, &th.th_dport,
4746 NULL, /* XXX Inbound NAT? */
4747 &nk->addr[pd2.didx],
4748 nk->port[pd2.didx], NULL,
4749 pd2.ip_sum, icmpsum,
4750 pd->ip_sum, 0, pd2.af);
4751 copyback = 1;
4752 }
4753
4754 if (copyback) {
4755 switch (pd2.af) {
4756#ifdef INET
4757 case AF_INET:
4758 m_copyback(m, off, ICMP_MINLEN,
4759 (caddr_t )pd->hdr.icmp);
4760 m_copyback(m, ipoff2, sizeof(h2),
4761 (caddr_t )&h2);
4762 break;
4763#endif /* INET */
4764#ifdef INET6
4765 case AF_INET6:
4766 m_copyback(m, off,
4767 sizeof(struct icmp6_hdr),
4768 (caddr_t )pd->hdr.icmp6);
4769 m_copyback(m, ipoff2, sizeof(h2_6),
4770 (caddr_t )&h2_6);
4771 break;
4772#endif /* INET6 */
4773 }
4774 m_copyback(m, off2, 8, (caddr_t)&th);
4775 }
4776
4777 return (PF_PASS);
4778 break;
4779 }
4780 case IPPROTO_UDP: {
4781 struct udphdr uh;
4782
4783 if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
4784 NULL, reason, pd2.af)) {
4785 DPFPRINTF(PF_DEBUG_MISC,
4786 ("pf: ICMP error message too short "
4787 "(udp)\n"));
4788 return (PF_DROP);
4789 }
4790
4791 key.af = pd2.af;
4792 key.proto = IPPROTO_UDP;
4793 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4794 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4795 key.port[pd2.sidx] = uh.uh_sport;
4796 key.port[pd2.didx] = uh.uh_dport;
4797
4798 STATE_LOOKUP(kif, &key, direction, *state, pd);
4799
4800 /* translate source/destination address, if necessary */
4801 if ((*state)->key[PF_SK_WIRE] !=
4802 (*state)->key[PF_SK_STACK]) {
4803 struct pf_state_key *nk =
4804 (*state)->key[pd->didx];
4805
4806 if (PF_ANEQ(pd2.src,
4807 &nk->addr[pd2.sidx], pd2.af) ||
4808 nk->port[pd2.sidx] != uh.uh_sport)
4809 pf_change_icmp(pd2.src, &uh.uh_sport,
4810 daddr, &nk->addr[pd2.sidx],
4811 nk->port[pd2.sidx], &uh.uh_sum,
4812 pd2.ip_sum, icmpsum,
4813 pd->ip_sum, 1, pd2.af);
4814
4815 if (PF_ANEQ(pd2.dst,
4816 &nk->addr[pd2.didx], pd2.af) ||
4817 nk->port[pd2.didx] != uh.uh_dport)
4818 pf_change_icmp(pd2.dst, &uh.uh_dport,
4819 NULL, /* XXX Inbound NAT? */
4820 &nk->addr[pd2.didx],
4821 nk->port[pd2.didx], &uh.uh_sum,
4822 pd2.ip_sum, icmpsum,
4823 pd->ip_sum, 1, pd2.af);
4824
4825 switch (pd2.af) {
4826#ifdef INET
4827 case AF_INET:
4828 m_copyback(m, off, ICMP_MINLEN,
4829 (caddr_t )pd->hdr.icmp);
4830 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4831 break;
4832#endif /* INET */
4833#ifdef INET6
4834 case AF_INET6:
4835 m_copyback(m, off,
4836 sizeof(struct icmp6_hdr),
4837 (caddr_t )pd->hdr.icmp6);
4838 m_copyback(m, ipoff2, sizeof(h2_6),
4839 (caddr_t )&h2_6);
4840 break;
4841#endif /* INET6 */
4842 }
4843 m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
4844 }
4845 return (PF_PASS);
4846 break;
4847 }
4848#ifdef INET
4849 case IPPROTO_ICMP: {
4850 struct icmp iih;
4851
4852 if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
4853 NULL, reason, pd2.af)) {
4854 DPFPRINTF(PF_DEBUG_MISC,
4855 ("pf: ICMP error message too short i"
4856 "(icmp)\n"));
4857 return (PF_DROP);
4858 }
4859
4860 key.af = pd2.af;
4861 key.proto = IPPROTO_ICMP;
4862 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4863 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4864 key.port[0] = key.port[1] = iih.icmp_id;
4865
4866 STATE_LOOKUP(kif, &key, direction, *state, pd);
4867
4868 /* translate source/destination address, if necessary */
4869 if ((*state)->key[PF_SK_WIRE] !=
4870 (*state)->key[PF_SK_STACK]) {
4871 struct pf_state_key *nk =
4872 (*state)->key[pd->didx];
4873
4874 if (PF_ANEQ(pd2.src,
4875 &nk->addr[pd2.sidx], pd2.af) ||
4876 nk->port[pd2.sidx] != iih.icmp_id)
4877 pf_change_icmp(pd2.src, &iih.icmp_id,
4878 daddr, &nk->addr[pd2.sidx],
4879 nk->port[pd2.sidx], NULL,
4880 pd2.ip_sum, icmpsum,
4881 pd->ip_sum, 0, AF_INET);
4882
4883 if (PF_ANEQ(pd2.dst,
4884 &nk->addr[pd2.didx], pd2.af) ||
4885 nk->port[pd2.didx] != iih.icmp_id)
4886 pf_change_icmp(pd2.dst, &iih.icmp_id,
4887 NULL, /* XXX Inbound NAT? */
4888 &nk->addr[pd2.didx],
4889 nk->port[pd2.didx], NULL,
4890 pd2.ip_sum, icmpsum,
4891 pd->ip_sum, 0, AF_INET);
4892
4893 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
4894 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4895 m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
4896 }
4897 return (PF_PASS);
4898 break;
4899 }
4900#endif /* INET */
4901#ifdef INET6
4902 case IPPROTO_ICMPV6: {
4903 struct icmp6_hdr iih;
4904
4905 if (!pf_pull_hdr(m, off2, &iih,
4906 sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
4907 DPFPRINTF(PF_DEBUG_MISC,
4908 ("pf: ICMP error message too short "
4909 "(icmp6)\n"));
4910 return (PF_DROP);
4911 }
4912
4913 key.af = pd2.af;
4914 key.proto = IPPROTO_ICMPV6;
4915 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4916 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4917 key.port[0] = key.port[1] = iih.icmp6_id;
4918
4919 STATE_LOOKUP(kif, &key, direction, *state, pd);
4920
4921 /* translate source/destination address, if necessary */
4922 if ((*state)->key[PF_SK_WIRE] !=
4923 (*state)->key[PF_SK_STACK]) {
4924 struct pf_state_key *nk =
4925 (*state)->key[pd->didx];
4926
4927 if (PF_ANEQ(pd2.src,
4928 &nk->addr[pd2.sidx], pd2.af) ||
4929 nk->port[pd2.sidx] != iih.icmp6_id)
4930 pf_change_icmp(pd2.src, &iih.icmp6_id,
4931 daddr, &nk->addr[pd2.sidx],
4932 nk->port[pd2.sidx], NULL,
4933 pd2.ip_sum, icmpsum,
4934 pd->ip_sum, 0, AF_INET6);
4935
4936 if (PF_ANEQ(pd2.dst,
4937 &nk->addr[pd2.didx], pd2.af) ||
4938 nk->port[pd2.didx] != iih.icmp6_id)
4939 pf_change_icmp(pd2.dst, &iih.icmp6_id,
4940 NULL, /* XXX Inbound NAT? */
4941 &nk->addr[pd2.didx],
4942 nk->port[pd2.didx], NULL,
4943 pd2.ip_sum, icmpsum,
4944 pd->ip_sum, 0, AF_INET6);
4945
4946 m_copyback(m, off, sizeof(struct icmp6_hdr),
4947 (caddr_t)pd->hdr.icmp6);
4948 m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
4949 m_copyback(m, off2, sizeof(struct icmp6_hdr),
4950 (caddr_t)&iih);
4951 }
4952 return (PF_PASS);
4953 break;
4954 }
4955#endif /* INET6 */
4956 default: {
4957 key.af = pd2.af;
4958 key.proto = pd2.proto;
4959 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4960 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4961 key.port[0] = key.port[1] = 0;
4962
4963 STATE_LOOKUP(kif, &key, direction, *state, pd);
4964
4965 /* translate source/destination address, if necessary */
4966 if ((*state)->key[PF_SK_WIRE] !=
4967 (*state)->key[PF_SK_STACK]) {
4968 struct pf_state_key *nk =
4969 (*state)->key[pd->didx];
4970
4971 if (PF_ANEQ(pd2.src,
4972 &nk->addr[pd2.sidx], pd2.af))
4973 pf_change_icmp(pd2.src, NULL, daddr,
4974 &nk->addr[pd2.sidx], 0, NULL,
4975 pd2.ip_sum, icmpsum,
4976 pd->ip_sum, 0, pd2.af);
4977
4978 if (PF_ANEQ(pd2.dst,
4979 &nk->addr[pd2.didx], pd2.af))
4980 pf_change_icmp(pd2.src, NULL,
4981 NULL, /* XXX Inbound NAT? */
4982 &nk->addr[pd2.didx], 0, NULL,
4983 pd2.ip_sum, icmpsum,
4984 pd->ip_sum, 0, pd2.af);
4985
4986 switch (pd2.af) {
4987#ifdef INET
4988 case AF_INET:
4989 m_copyback(m, off, ICMP_MINLEN,
4990 (caddr_t)pd->hdr.icmp);
4991 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4992 break;
4993#endif /* INET */
4994#ifdef INET6
4995 case AF_INET6:
4996 m_copyback(m, off,
4997 sizeof(struct icmp6_hdr),
4998 (caddr_t )pd->hdr.icmp6);
4999 m_copyback(m, ipoff2, sizeof(h2_6),
5000 (caddr_t )&h2_6);
5001 break;
5002#endif /* INET6 */
5003 }
5004 }
5005 return (PF_PASS);
5006 break;
5007 }
5008 }
5009 }
5010}
5011
5012static int
5013pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
5014 struct mbuf *m, struct pf_pdesc *pd)
5015{
5016 struct pf_state_peer *src, *dst;
5017 struct pf_state_key_cmp key;
5018
5019 bzero(&key, sizeof(key));
5020 key.af = pd->af;
5021 key.proto = pd->proto;
5022 if (direction == PF_IN) {
5023 PF_ACPY(&key.addr[0], pd->src, key.af);
5024 PF_ACPY(&key.addr[1], pd->dst, key.af);
5025 key.port[0] = key.port[1] = 0;
5026 } else {
5027 PF_ACPY(&key.addr[1], pd->src, key.af);
5028 PF_ACPY(&key.addr[0], pd->dst, key.af);
5029 key.port[1] = key.port[0] = 0;
5030 }
5031
5032 STATE_LOOKUP(kif, &key, direction, *state, pd);
5033
5034 if (direction == (*state)->direction) {
5035 src = &(*state)->src;
5036 dst = &(*state)->dst;
5037 } else {
5038 src = &(*state)->dst;
5039 dst = &(*state)->src;
5040 }
5041
5042 /* update states */
5043 if (src->state < PFOTHERS_SINGLE)
5044 src->state = PFOTHERS_SINGLE;
5045 if (dst->state == PFOTHERS_SINGLE)
5046 dst->state = PFOTHERS_MULTIPLE;
5047
5048 /* update expire time */
5049 (*state)->expire = time_uptime;
5050 if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5051 (*state)->timeout = PFTM_OTHER_MULTIPLE;
5052 else
5053 (*state)->timeout = PFTM_OTHER_SINGLE;
5054
5055 /* translate source/destination address, if necessary */
5056 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5057 struct pf_state_key *nk = (*state)->key[pd->didx];
5058
5059 KASSERT(nk, ("%s: nk is null", __func__));
5060 KASSERT(pd, ("%s: pd is null", __func__));
5061 KASSERT(pd->src, ("%s: pd->src is null", __func__));
5062 KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
5063 switch (pd->af) {
5064#ifdef INET
5065 case AF_INET:
5066 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5067 pf_change_a(&pd->src->v4.s_addr,
5068 pd->ip_sum,
5069 nk->addr[pd->sidx].v4.s_addr,
5070 0);
5071
5072
5073 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5074 pf_change_a(&pd->dst->v4.s_addr,
5075 pd->ip_sum,
5076 nk->addr[pd->didx].v4.s_addr,
5077 0);
5078
5079 break;
5080#endif /* INET */
5081#ifdef INET6
5082 case AF_INET6:
5083 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5084 PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5085
5086 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5087 PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5088#endif /* INET6 */
5089 }
5090 }
5091 return (PF_PASS);
5092}
5093
5094/*
5095 * ipoff and off are measured from the start of the mbuf chain.
5096 * h must be at "ipoff" on the mbuf chain.
5097 */
5098void *
5099pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5100 u_short *actionp, u_short *reasonp, sa_family_t af)
5101{
5102 switch (af) {
5103#ifdef INET
5104 case AF_INET: {
5105 struct ip *h = mtod(m, struct ip *);
5106 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
5107
5108 if (fragoff) {
5109 if (fragoff >= len)
5110 ACTION_SET(actionp, PF_PASS);
5111 else {
5112 ACTION_SET(actionp, PF_DROP);
5113 REASON_SET(reasonp, PFRES_FRAG);
5114 }
5115 return (NULL);
5116 }
5117 if (m->m_pkthdr.len < off + len ||
5118 ntohs(h->ip_len) < off + len) {
5119 ACTION_SET(actionp, PF_DROP);
5120 REASON_SET(reasonp, PFRES_SHORT);
5121 return (NULL);
5122 }
5123 break;
5124 }
5125#endif /* INET */
5126#ifdef INET6
5127 case AF_INET6: {
5128 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
5129
5130 if (m->m_pkthdr.len < off + len ||
5131 (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5132 (unsigned)(off + len)) {
5133 ACTION_SET(actionp, PF_DROP);
5134 REASON_SET(reasonp, PFRES_SHORT);
5135 return (NULL);
5136 }
5137 break;
5138 }
5139#endif /* INET6 */
5140 }
5141 m_copydata(m, off, len, p);
5142 return (p);
5143}
5144
5145int
5146pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5147 int rtableid)
5148{
5149#ifdef RADIX_MPATH
5150 struct radix_node_head *rnh;
5151#endif
5152 struct sockaddr_in *dst;
5153 int ret = 1;
5154 int check_mpath;
5155#ifdef INET6
5156 struct sockaddr_in6 *dst6;
5157 struct route_in6 ro;
5158#else
5159 struct route ro;
5160#endif
5161 struct radix_node *rn;
5162 struct rtentry *rt;
5163 struct ifnet *ifp;
5164
5165 check_mpath = 0;
5166#ifdef RADIX_MPATH
5167 /* XXX: stick to table 0 for now */
5168 rnh = rt_tables_get_rnh(0, af);
5169 if (rnh != NULL && rn_mpath_capable(rnh))
5170 check_mpath = 1;
5171#endif
5172 bzero(&ro, sizeof(ro));
5173 switch (af) {
5174 case AF_INET:
5175 dst = satosin(&ro.ro_dst);
5176 dst->sin_family = AF_INET;
5177 dst->sin_len = sizeof(*dst);
5178 dst->sin_addr = addr->v4;
5179 break;
5180#ifdef INET6
5181 case AF_INET6:
5182 /*
5183 * Skip check for addresses with embedded interface scope,
5184 * as they would always match anyway.
5185 */
5186 if (IN6_IS_SCOPE_EMBED(&addr->v6))
5187 goto out;
5188 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5189 dst6->sin6_family = AF_INET6;
5190 dst6->sin6_len = sizeof(*dst6);
5191 dst6->sin6_addr = addr->v6;
5192 break;
5193#endif /* INET6 */
5194 default:
5195 return (0);
5196 }
5197
5198 /* Skip checks for ipsec interfaces */
5199 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5200 goto out;
5201
5202 switch (af) {
5203#ifdef INET6
5204 case AF_INET6:
5205 in6_rtalloc_ign(&ro, 0, rtableid);
5206 break;
5207#endif
5208#ifdef INET
5209 case AF_INET:
5210 in_rtalloc_ign((struct route *)&ro, 0, rtableid);
5211 break;
5212#endif
5213 default:
5214 rtalloc_ign((struct route *)&ro, 0); /* No/default FIB. */
5215 break;
5216 }
5217
5218 if (ro.ro_rt != NULL) {
5219 /* No interface given, this is a no-route check */
5220 if (kif == NULL)
5221 goto out;
5222
5223 if (kif->pfik_ifp == NULL) {
5224 ret = 0;
5225 goto out;
5226 }
5227
5228 /* Perform uRPF check if passed input interface */
5229 ret = 0;
5230 rn = (struct radix_node *)ro.ro_rt;
5231 do {
5232 rt = (struct rtentry *)rn;
5233 ifp = rt->rt_ifp;
5234
5235 if (kif->pfik_ifp == ifp)
5236 ret = 1;
5237#ifdef RADIX_MPATH
5238 rn = rn_mpath_next(rn);
5239#endif
5240 } while (check_mpath == 1 && rn != NULL && ret == 0);
5241 } else
5242 ret = 0;
5243out:
5244 if (ro.ro_rt != NULL)
5245 RTFREE(ro.ro_rt);
5246 return (ret);
5247}
5248
5249#ifdef INET
5250static void
5251pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5252 struct pf_state *s, struct pf_pdesc *pd)
5253{
5254 struct mbuf *m0, *m1;
5255 struct sockaddr_in dst;
5256 struct ip *ip;
5257 struct ifnet *ifp = NULL;
5258 struct pf_addr naddr;
5259 struct pf_src_node *sn = NULL;
5260 int error = 0;
5261 uint16_t ip_len, ip_off;
5262
5263 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5264 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5265 __func__));
5266
5267 if ((pd->pf_mtag == NULL &&
5268 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5269 pd->pf_mtag->routed++ > 3) {
5270 m0 = *m;
5271 *m = NULL;
5272 goto bad_locked;
5273 }
5274
5275 if (r->rt == PF_DUPTO) {
5276 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5277 if (s)
5278 PF_STATE_UNLOCK(s);
5279 return;
5280 }
5281 } else {
5282 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5283 if (s)
5284 PF_STATE_UNLOCK(s);
5285 return;
5286 }
5287 m0 = *m;
5288 }
5289
5290 ip = mtod(m0, struct ip *);
5291
5292 bzero(&dst, sizeof(dst));
5293 dst.sin_family = AF_INET;
5294 dst.sin_len = sizeof(dst);
5295 dst.sin_addr = ip->ip_dst;
5296
5297 if (r->rt == PF_FASTROUTE) {
5298 struct rtentry *rt;
5299
5300 if (s)
5301 PF_STATE_UNLOCK(s);
5302 rt = rtalloc1_fib(sintosa(&dst), 0, 0, M_GETFIB(m0));
5303 if (rt == NULL) {
5304 KMOD_IPSTAT_INC(ips_noroute);
5305 error = EHOSTUNREACH;
5306 goto bad;
5307 }
5308
5309 ifp = rt->rt_ifp;
5310 counter_u64_add(rt->rt_pksent, 1);
5311
5312 if (rt->rt_flags & RTF_GATEWAY)
5313 bcopy(satosin(rt->rt_gateway), &dst, sizeof(dst));
5314 RTFREE_LOCKED(rt);
5315 } else {
5316 if (TAILQ_EMPTY(&r->rpool.list)) {
5317 DPFPRINTF(PF_DEBUG_URGENT,
5318 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5319 goto bad_locked;
5320 }
5321 if (s == NULL) {
5322 pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5323 &naddr, NULL, &sn);
5324 if (!PF_AZERO(&naddr, AF_INET))
5325 dst.sin_addr.s_addr = naddr.v4.s_addr;
5326 ifp = r->rpool.cur->kif ?
5327 r->rpool.cur->kif->pfik_ifp : NULL;
5328 } else {
5329 if (!PF_AZERO(&s->rt_addr, AF_INET))
5330 dst.sin_addr.s_addr =
5331 s->rt_addr.v4.s_addr;
5332 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5333 PF_STATE_UNLOCK(s);
5334 }
5335 }
5336 if (ifp == NULL)
5337 goto bad;
5338
5339 if (oifp != ifp) {
5340 if (pf_test(PF_OUT, ifp, &m0, NULL) != PF_PASS)
5341 goto bad;
5342 else if (m0 == NULL)
5343 goto done;
5344 if (m0->m_len < sizeof(struct ip)) {
5345 DPFPRINTF(PF_DEBUG_URGENT,
5346 ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
5347 goto bad;
5348 }
5349 ip = mtod(m0, struct ip *);
5350 }
5351
5352 if (ifp->if_flags & IFF_LOOPBACK)
5353 m0->m_flags |= M_SKIP_FIREWALL;
5354
5355 ip_len = ntohs(ip->ip_len);
5356 ip_off = ntohs(ip->ip_off);
5357
5358 /* Copied from FreeBSD 10.0-CURRENT ip_output. */
5359 m0->m_pkthdr.csum_flags |= CSUM_IP;
5360 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
5361 in_delayed_cksum(m0);
5362 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
5363 }
5364#ifdef SCTP
5365 if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
5366 sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
5367 m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
5368 }
5369#endif
5370
5371 /*
5372 * If small enough for interface, or the interface will take
5373 * care of the fragmentation for us, we can just send directly.
5374 */
5375 if (ip_len <= ifp->if_mtu ||
5376 (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0 ||
5377 ((ip_off & IP_DF) == 0 && (ifp->if_hwassist & CSUM_FRAGMENT))) {
5378 ip->ip_sum = 0;
5379 if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
5380 ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5381 m0->m_pkthdr.csum_flags &= ~CSUM_IP;
5382 }
5383 m_clrprotoflags(m0); /* Avoid confusing lower layers. */
5384 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5385 goto done;
5386 }
5387
5388 /* Balk when DF bit is set or the interface didn't support TSO. */
5389 if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5390 error = EMSGSIZE;
5391 KMOD_IPSTAT_INC(ips_cantfrag);
5392 if (r->rt != PF_DUPTO) {
5393 icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5394 ifp->if_mtu);
5395 goto done;
5396 } else
5397 goto bad;
5398 }
5399
5400 error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
5401 if (error)
5402 goto bad;
5403
5404 for (; m0; m0 = m1) {
5405 m1 = m0->m_nextpkt;
5406 m0->m_nextpkt = NULL;
5407 if (error == 0) {
5408 m_clrprotoflags(m0);
5409 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5410 } else
5411 m_freem(m0);
5412 }
5413
5414 if (error == 0)
5415 KMOD_IPSTAT_INC(ips_fragmented);
5416
5417done:
5418 if (r->rt != PF_DUPTO)
5419 *m = NULL;
5420 return;
5421
5422bad_locked:
5423 if (s)
5424 PF_STATE_UNLOCK(s);
5425bad:
5426 m_freem(m0);
5427 goto done;
5428}
5429#endif /* INET */
5430
5431#ifdef INET6
5432static void
5433pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5434 struct pf_state *s, struct pf_pdesc *pd)
5435{
5436 struct mbuf *m0;
5437 struct sockaddr_in6 dst;
5438 struct ip6_hdr *ip6;
5439 struct ifnet *ifp = NULL;
5440 struct pf_addr naddr;
5441 struct pf_src_node *sn = NULL;
5442
5443 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5444 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5445 __func__));
5446
5447 if ((pd->pf_mtag == NULL &&
5448 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5449 pd->pf_mtag->routed++ > 3) {
5450 m0 = *m;
5451 *m = NULL;
5452 goto bad_locked;
5453 }
5454
5455 if (r->rt == PF_DUPTO) {
5456 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5457 if (s)
5458 PF_STATE_UNLOCK(s);
5459 return;
5460 }
5461 } else {
5462 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5463 if (s)
5464 PF_STATE_UNLOCK(s);
5465 return;
5466 }
5467 m0 = *m;
5468 }
5469
5470 ip6 = mtod(m0, struct ip6_hdr *);
5471
5472 bzero(&dst, sizeof(dst));
5473 dst.sin6_family = AF_INET6;
5474 dst.sin6_len = sizeof(dst);
5475 dst.sin6_addr = ip6->ip6_dst;
5476
5477 /* Cheat. XXX why only in the v6 case??? */
5478 if (r->rt == PF_FASTROUTE) {
5479 if (s)
5480 PF_STATE_UNLOCK(s);
5481 m0->m_flags |= M_SKIP_FIREWALL;
5482 ip6_output(m0, NULL, NULL, 0, NULL, NULL, NULL);
5483 *m = NULL;
5484 return;
5485 }
5486
5487 if (TAILQ_EMPTY(&r->rpool.list)) {
5488 DPFPRINTF(PF_DEBUG_URGENT,
5489 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5490 goto bad_locked;
5491 }
5492 if (s == NULL) {
5493 pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5494 &naddr, NULL, &sn);
5495 if (!PF_AZERO(&naddr, AF_INET6))
5496 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5497 &naddr, AF_INET6);
5498 ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
5499 } else {
5500 if (!PF_AZERO(&s->rt_addr, AF_INET6))
5501 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5502 &s->rt_addr, AF_INET6);
5503 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5504 }
5505
5506 if (s)
5507 PF_STATE_UNLOCK(s);
5508
5509 if (ifp == NULL)
5510 goto bad;
5511
5512 if (oifp != ifp) {
5513 if (pf_test6(PF_FWD, ifp, &m0, NULL) != PF_PASS)
5514 goto bad;
5515 else if (m0 == NULL)
5516 goto done;
5517 if (m0->m_len < sizeof(struct ip6_hdr)) {
5518 DPFPRINTF(PF_DEBUG_URGENT,
5519 ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
5520 __func__));
5521 goto bad;
5522 }
5523 ip6 = mtod(m0, struct ip6_hdr *);
5524 }
5525
5526 if (ifp->if_flags & IFF_LOOPBACK)
5527 m0->m_flags |= M_SKIP_FIREWALL;
5528
5529 /*
5530 * If the packet is too large for the outgoing interface,
5531 * send back an icmp6 error.
5532 */
5533 if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
5534 dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5535 if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu)
5536 nd6_output(ifp, ifp, m0, &dst, NULL);
5537 else {
5538 in6_ifstat_inc(ifp, ifs6_in_toobig);
5539 if (r->rt != PF_DUPTO)
5540 icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5541 else
5542 goto bad;
5543 }
5544
5545done:
5546 if (r->rt != PF_DUPTO)
5547 *m = NULL;
5548 return;
5549
5550bad_locked:
5551 if (s)
5552 PF_STATE_UNLOCK(s);
5553bad:
5554 m_freem(m0);
5555 goto done;
5556}
5557#endif /* INET6 */
5558
5559/*
5560 * FreeBSD supports cksum offloads for the following drivers.
5561 * em(4), fxp(4), ixgb(4), lge(4), ndis(4), nge(4), re(4),
5562 * ti(4), txp(4), xl(4)
5563 *
5564 * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
5565 * network driver performed cksum including pseudo header, need to verify
5566 * csum_data
5567 * CSUM_DATA_VALID :
5568 * network driver performed cksum, needs to additional pseudo header
5569 * cksum computation with partial csum_data(i.e. lack of H/W support for
5570 * pseudo header, for instance hme(4), sk(4) and possibly gem(4))
5571 *
5572 * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
5573 * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
5574 * TCP/UDP layer.
5575 * Also, set csum_data to 0xffff to force cksum validation.
5576 */
5577static int
5578pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
5579{
5580 u_int16_t sum = 0;
5581 int hw_assist = 0;
5582 struct ip *ip;
5583
5584 if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
5585 return (1);
5586 if (m->m_pkthdr.len < off + len)
5587 return (1);
5588
5589 switch (p) {
5590 case IPPROTO_TCP:
5591 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5592 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5593 sum = m->m_pkthdr.csum_data;
5594 } else {
5595 ip = mtod(m, struct ip *);
5596 sum = in_pseudo(ip->ip_src.s_addr,
5597 ip->ip_dst.s_addr, htonl((u_short)len +
5598 m->m_pkthdr.csum_data + IPPROTO_TCP));
5599 }
5600 sum ^= 0xffff;
5601 ++hw_assist;
5602 }
5603 break;
5604 case IPPROTO_UDP:
5605 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5606 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5607 sum = m->m_pkthdr.csum_data;
5608 } else {
5609 ip = mtod(m, struct ip *);
5610 sum = in_pseudo(ip->ip_src.s_addr,
5611 ip->ip_dst.s_addr, htonl((u_short)len +
5612 m->m_pkthdr.csum_data + IPPROTO_UDP));
5613 }
5614 sum ^= 0xffff;
5615 ++hw_assist;
5616 }
5617 break;
5618 case IPPROTO_ICMP:
5619#ifdef INET6
5620 case IPPROTO_ICMPV6:
5621#endif /* INET6 */
5622 break;
5623 default:
5624 return (1);
5625 }
5626
5627 if (!hw_assist) {
5628 switch (af) {
5629 case AF_INET:
5630 if (p == IPPROTO_ICMP) {
5631 if (m->m_len < off)
5632 return (1);
5633 m->m_data += off;
5634 m->m_len -= off;
5635 sum = in_cksum(m, len);
5636 m->m_data -= off;
5637 m->m_len += off;
5638 } else {
5639 if (m->m_len < sizeof(struct ip))
5640 return (1);
5641 sum = in4_cksum(m, p, off, len);
5642 }
5643 break;
5644#ifdef INET6
5645 case AF_INET6:
5646 if (m->m_len < sizeof(struct ip6_hdr))
5647 return (1);
5648 sum = in6_cksum(m, p, off, len);
5649 break;
5650#endif /* INET6 */
5651 default:
5652 return (1);
5653 }
5654 }
5655 if (sum) {
5656 switch (p) {
5657 case IPPROTO_TCP:
5658 {
5659 KMOD_TCPSTAT_INC(tcps_rcvbadsum);
5660 break;
5661 }
5662 case IPPROTO_UDP:
5663 {
5664 KMOD_UDPSTAT_INC(udps_badsum);
5665 break;
5666 }
5667#ifdef INET
5668 case IPPROTO_ICMP:
5669 {
5670 KMOD_ICMPSTAT_INC(icps_checksum);
5671 break;
5672 }
5673#endif
5674#ifdef INET6
5675 case IPPROTO_ICMPV6:
5676 {
5677 KMOD_ICMP6STAT_INC(icp6s_checksum);
5678 break;
5679 }
5680#endif /* INET6 */
5681 }
5682 return (1);
5683 } else {
5684 if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
5685 m->m_pkthdr.csum_flags |=
5686 (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
5687 m->m_pkthdr.csum_data = 0xffff;
5688 }
5689 }
5690 return (0);
5691}
5692
5693
5694#ifdef INET
5695int
5696pf_test(int dir, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
5697{
5698 struct pfi_kif *kif;
5699 u_short action, reason = 0, log = 0;
5700 struct mbuf *m = *m0;
5701 struct ip *h = NULL;
5702 struct m_tag *ipfwtag;
5703 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
5704 struct pf_state *s = NULL;
5705 struct pf_ruleset *ruleset = NULL;
5706 struct pf_pdesc pd;
5707 int off, dirndx, pqid = 0;
5708
5709 M_ASSERTPKTHDR(m);
5710
5711 if (!V_pf_status.running)
5712 return (PF_PASS);
5713
5714 memset(&pd, 0, sizeof(pd));
5715
5716 kif = (struct pfi_kif *)ifp->if_pf_kif;
5717
5718 if (kif == NULL) {
5719 DPFPRINTF(PF_DEBUG_URGENT,
5720 ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
5721 return (PF_DROP);
5722 }
5723 if (kif->pfik_flags & PFI_IFLAG_SKIP)
5724 return (PF_PASS);
5725
5726 if (m->m_flags & M_SKIP_FIREWALL)
5727 return (PF_PASS);
5728
5729 pd.pf_mtag = pf_find_mtag(m);
5730
5731 PF_RULES_RLOCK();
5732
5733 if (ip_divert_ptr != NULL &&
5734 ((ipfwtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL)) != NULL)) {
5735 struct ipfw_rule_ref *rr = (struct ipfw_rule_ref *)(ipfwtag+1);
5736 if (rr->info & IPFW_IS_DIVERT && rr->rulenum == 0) {
5737 if (pd.pf_mtag == NULL &&
5738 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5739 action = PF_DROP;
5740 goto done;
5741 }
5742 pd.pf_mtag->flags |= PF_PACKET_LOOPED;
5743 m_tag_delete(m, ipfwtag);
5744 }
5745 if (pd.pf_mtag && pd.pf_mtag->flags & PF_FASTFWD_OURS_PRESENT) {
5746 m->m_flags |= M_FASTFWD_OURS;
5747 pd.pf_mtag->flags &= ~PF_FASTFWD_OURS_PRESENT;
5748 }
5749 } else if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
5750 /* We do IP header normalization and packet reassembly here */
5751 action = PF_DROP;
5752 goto done;
5753 }
5754 m = *m0; /* pf_normalize messes with m0 */
5755 h = mtod(m, struct ip *);
5756
5757 off = h->ip_hl << 2;
5758 if (off < (int)sizeof(struct ip)) {
5759 action = PF_DROP;
5760 REASON_SET(&reason, PFRES_SHORT);
5761 log = 1;
5762 goto done;
5763 }
5764
5765 pd.src = (struct pf_addr *)&h->ip_src;
5766 pd.dst = (struct pf_addr *)&h->ip_dst;
5767 pd.sport = pd.dport = NULL;
5768 pd.ip_sum = &h->ip_sum;
5769 pd.proto_sum = NULL;
5770 pd.proto = h->ip_p;
5771 pd.dir = dir;
5772 pd.sidx = (dir == PF_IN) ? 0 : 1;
5773 pd.didx = (dir == PF_IN) ? 1 : 0;
5774 pd.af = AF_INET;
5775 pd.tos = h->ip_tos;
5776 pd.tot_len = ntohs(h->ip_len);
5777
5778 /* handle fragments that didn't get reassembled by normalization */
5779 if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
5780 action = pf_test_fragment(&r, dir, kif, m, h,
5781 &pd, &a, &ruleset);
5782 goto done;
5783 }
5784
5785 switch (h->ip_p) {
5786
5787 case IPPROTO_TCP: {
5788 struct tcphdr th;
5789
5790 pd.hdr.tcp = &th;
5791 if (!pf_pull_hdr(m, off, &th, sizeof(th),
5792 &action, &reason, AF_INET)) {
5793 log = action != PF_PASS;
5794 goto done;
5795 }
5796 pd.p_len = pd.tot_len - off - (th.th_off << 2);
5797 if ((th.th_flags & TH_ACK) && pd.p_len == 0)
5798 pqid = 1;
5799 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
5800 if (action == PF_DROP)
5801 goto done;
5802 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
5803 &reason);
5804 if (action == PF_PASS) {
5805 if (pfsync_update_state_ptr != NULL)
5806 pfsync_update_state_ptr(s);
5807 r = s->rule.ptr;
5808 a = s->anchor.ptr;
5809 log = s->log;
5810 } else if (s == NULL)
5811 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5812 &a, &ruleset, inp);
5813 break;
5814 }
5815
5816 case IPPROTO_UDP: {
5817 struct udphdr uh;
5818
5819 pd.hdr.udp = &uh;
5820 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
5821 &action, &reason, AF_INET)) {
5822 log = action != PF_PASS;
5823 goto done;
5824 }
5825 if (uh.uh_dport == 0 ||
5826 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
5827 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
5828 action = PF_DROP;
5829 REASON_SET(&reason, PFRES_SHORT);
5830 goto done;
5831 }
5832 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
5833 if (action == PF_PASS) {
5834 if (pfsync_update_state_ptr != NULL)
5835 pfsync_update_state_ptr(s);
5836 r = s->rule.ptr;
5837 a = s->anchor.ptr;
5838 log = s->log;
5839 } else if (s == NULL)
5840 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5841 &a, &ruleset, inp);
5842 break;
5843 }
5844
5845 case IPPROTO_ICMP: {
5846 struct icmp ih;
5847
5848 pd.hdr.icmp = &ih;
5849 if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
5850 &action, &reason, AF_INET)) {
5851 log = action != PF_PASS;
5852 goto done;
5853 }
5854 action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
5855 &reason);
5856 if (action == PF_PASS) {
5857 if (pfsync_update_state_ptr != NULL)
5858 pfsync_update_state_ptr(s);
5859 r = s->rule.ptr;
5860 a = s->anchor.ptr;
5861 log = s->log;
5862 } else if (s == NULL)
5863 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5864 &a, &ruleset, inp);
5865 break;
5866 }
5867
5868#ifdef INET6
5869 case IPPROTO_ICMPV6: {
5870 action = PF_DROP;
5871 DPFPRINTF(PF_DEBUG_MISC,
5872 ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
5873 goto done;
5874 }
5875#endif
5876
5877 default:
5878 action = pf_test_state_other(&s, dir, kif, m, &pd);
5879 if (action == PF_PASS) {
5880 if (pfsync_update_state_ptr != NULL)
5881 pfsync_update_state_ptr(s);
5882 r = s->rule.ptr;
5883 a = s->anchor.ptr;
5884 log = s->log;
5885 } else if (s == NULL)
5886 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5887 &a, &ruleset, inp);
5888 break;
5889 }
5890
5891done:
5892 PF_RULES_RUNLOCK();
5893 if (action == PF_PASS && h->ip_hl > 5 &&
5894 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
5895 action = PF_DROP;
5896 REASON_SET(&reason, PFRES_IPOPTIONS);
5897 log = 1;
5898 DPFPRINTF(PF_DEBUG_MISC,
5899 ("pf: dropping packet with ip options\n"));
5900 }
5901
5902 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
5903 action = PF_DROP;
5904 REASON_SET(&reason, PFRES_MEMORY);
5905 }
5906 if (r->rtableid >= 0)
5907 M_SETFIB(m, r->rtableid);
5908
5909#ifdef ALTQ
5910 if (action == PF_PASS && r->qid) {
5911 if (pd.pf_mtag == NULL &&
5912 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5913 action = PF_DROP;
5914 REASON_SET(&reason, PFRES_MEMORY);
5915 }
5916 if (pqid || (pd.tos & IPTOS_LOWDELAY))
5917 pd.pf_mtag->qid = r->pqid;
5918 else
5919 pd.pf_mtag->qid = r->qid;
5920 /* add hints for ecn */
5921 pd.pf_mtag->hdr = h;
5922
5923 }
5924#endif /* ALTQ */
5925
5926 /*
5927 * connections redirected to loopback should not match sockets
5928 * bound specifically to loopback due to security implications,
5929 * see tcp_input() and in_pcblookup_listen().
5930 */
5931 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
5932 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
5933 (s->nat_rule.ptr->action == PF_RDR ||
5934 s->nat_rule.ptr->action == PF_BINAT) &&
5935 (ntohl(pd.dst->v4.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
5936 m->m_flags |= M_SKIP_FIREWALL;
5937
5938 if (action == PF_PASS && r->divert.port && ip_divert_ptr != NULL &&
5939 !PACKET_LOOPED(&pd)) {
5940
5941 ipfwtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
5942 sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
5943 if (ipfwtag != NULL) {
5944 ((struct ipfw_rule_ref *)(ipfwtag+1))->info =
5945 ntohs(r->divert.port);
5946 ((struct ipfw_rule_ref *)(ipfwtag+1))->rulenum = dir;
5947
5948 if (s)
5949 PF_STATE_UNLOCK(s);
5950
5951 m_tag_prepend(m, ipfwtag);
5952 if (m->m_flags & M_FASTFWD_OURS) {
5953 if (pd.pf_mtag == NULL &&
5954 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5955 action = PF_DROP;
5956 REASON_SET(&reason, PFRES_MEMORY);
5957 log = 1;
5958 DPFPRINTF(PF_DEBUG_MISC,
5959 ("pf: failed to allocate tag\n"));
5960 }
5961 pd.pf_mtag->flags |= PF_FASTFWD_OURS_PRESENT;
5962 m->m_flags &= ~M_FASTFWD_OURS;
5963 }
5964 ip_divert_ptr(*m0, dir == PF_IN ? DIR_IN : DIR_OUT);
5965 *m0 = NULL;
5966
5967 return (action);
5968 } else {
5969 /* XXX: ipfw has the same behaviour! */
5970 action = PF_DROP;
5971 REASON_SET(&reason, PFRES_MEMORY);
5972 log = 1;
5973 DPFPRINTF(PF_DEBUG_MISC,
5974 ("pf: failed to allocate divert tag\n"));
5975 }
5976 }
5977
5978 if (log) {
5979 struct pf_rule *lr;
5980
5981 if (s != NULL && s->nat_rule.ptr != NULL &&
5982 s->nat_rule.ptr->log & PF_LOG_ALL)
5983 lr = s->nat_rule.ptr;
5984 else
5985 lr = r;
5986 PFLOG_PACKET(kif, m, AF_INET, dir, reason, lr, a, ruleset, &pd,
5987 (s == NULL));
5988 }
5989
5990 kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
5991 kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
5992
5993 if (action == PF_PASS || r->action == PF_DROP) {
5994 dirndx = (dir == PF_OUT);
5995 r->packets[dirndx]++;
5996 r->bytes[dirndx] += pd.tot_len;
5997 if (a != NULL) {
5998 a->packets[dirndx]++;
5999 a->bytes[dirndx] += pd.tot_len;
6000 }
6001 if (s != NULL) {
6002 if (s->nat_rule.ptr != NULL) {
6003 s->nat_rule.ptr->packets[dirndx]++;
6004 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6005 }
6006 if (s->src_node != NULL) {
6007 s->src_node->packets[dirndx]++;
6008 s->src_node->bytes[dirndx] += pd.tot_len;
6009 }
6010 if (s->nat_src_node != NULL) {
6011 s->nat_src_node->packets[dirndx]++;
6012 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6013 }
6014 dirndx = (dir == s->direction) ? 0 : 1;
6015 s->packets[dirndx]++;
6016 s->bytes[dirndx] += pd.tot_len;
6017 }
6018 tr = r;
6019 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6020 if (nr != NULL && r == &V_pf_default_rule)
6021 tr = nr;
6022 if (tr->src.addr.type == PF_ADDR_TABLE)
6023 pfr_update_stats(tr->src.addr.p.tbl,
6024 (s == NULL) ? pd.src :
6025 &s->key[(s->direction == PF_IN)]->
6026 addr[(s->direction == PF_OUT)],
6027 pd.af, pd.tot_len, dir == PF_OUT,
6028 r->action == PF_PASS, tr->src.neg);
6029 if (tr->dst.addr.type == PF_ADDR_TABLE)
6030 pfr_update_stats(tr->dst.addr.p.tbl,
6031 (s == NULL) ? pd.dst :
6032 &s->key[(s->direction == PF_IN)]->
6033 addr[(s->direction == PF_IN)],
6034 pd.af, pd.tot_len, dir == PF_OUT,
6035 r->action == PF_PASS, tr->dst.neg);
6036 }
6037
6038 switch (action) {
6039 case PF_SYNPROXY_DROP:
6040 m_freem(*m0);
6041 case PF_DEFER:
6042 *m0 = NULL;
6043 action = PF_PASS;
6044 break;
6045 case PF_DROP:
6046 m_freem(*m0);
6047 *m0 = NULL;
6048 break;
6049 default:
6050 /* pf_route() returns unlocked. */
6051 if (r->rt) {
6052 pf_route(m0, r, dir, kif->pfik_ifp, s, &pd);
6053 return (action);
6054 }
6055 break;
6056 }
6057 if (s)
6058 PF_STATE_UNLOCK(s);
6059
6060 return (action);
6061}
6062#endif /* INET */
6063
6064#ifdef INET6
6065int
6066pf_test6(int dir, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
6067{
6068 struct pfi_kif *kif;
6069 u_short action, reason = 0, log = 0;
6070 struct mbuf *m = *m0, *n = NULL;
6071 struct m_tag *mtag;
6072 struct ip6_hdr *h = NULL;
6073 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
6074 struct pf_state *s = NULL;
6075 struct pf_ruleset *ruleset = NULL;
6076 struct pf_pdesc pd;
6077 int off, terminal = 0, dirndx, rh_cnt = 0;
6078 int fwdir = dir;
6079
6080 M_ASSERTPKTHDR(m);
6081
6082 if (dir == PF_OUT && m->m_pkthdr.rcvif && ifp != m->m_pkthdr.rcvif)
6083 fwdir = PF_FWD;
6084
6085 if (!V_pf_status.running)
6086 return (PF_PASS);
6087
6088 memset(&pd, 0, sizeof(pd));
6089 pd.pf_mtag = pf_find_mtag(m);
6090
6091 if (pd.pf_mtag && pd.pf_mtag->flags & PF_TAG_GENERATED)
6092 return (PF_PASS);
6093
6094 kif = (struct pfi_kif *)ifp->if_pf_kif;
6095 if (kif == NULL) {
6096 DPFPRINTF(PF_DEBUG_URGENT,
6097 ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6098 return (PF_DROP);
6099 }
6100 if (kif->pfik_flags & PFI_IFLAG_SKIP)
6101 return (PF_PASS);
6102
6103 if (m->m_flags & M_SKIP_FIREWALL)
6104 return (PF_PASS);
6105
6106 PF_RULES_RLOCK();
6107
6108 /* We do IP header normalization and packet reassembly here */
6109 if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6110 action = PF_DROP;
6111 goto done;
6112 }
6113 m = *m0; /* pf_normalize messes with m0 */
6114 h = mtod(m, struct ip6_hdr *);
6115
6116#if 1
6117 /*
6118 * we do not support jumbogram yet. if we keep going, zero ip6_plen
6119 * will do something bad, so drop the packet for now.
6120 */
6121 if (htons(h->ip6_plen) == 0) {
6122 action = PF_DROP;
6123 REASON_SET(&reason, PFRES_NORM); /*XXX*/
6124 goto done;
6125 }
6126#endif
6127
6128 pd.src = (struct pf_addr *)&h->ip6_src;
6129 pd.dst = (struct pf_addr *)&h->ip6_dst;
6130 pd.sport = pd.dport = NULL;
6131 pd.ip_sum = NULL;
6132 pd.proto_sum = NULL;
6133 pd.dir = dir;
6134 pd.sidx = (dir == PF_IN) ? 0 : 1;
6135 pd.didx = (dir == PF_IN) ? 1 : 0;
6136 pd.af = AF_INET6;
6137 pd.tos = 0;
6138 pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6139
6140 off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6141 pd.proto = h->ip6_nxt;
6142 do {
6143 switch (pd.proto) {
6144 case IPPROTO_FRAGMENT:
6145 action = pf_test_fragment(&r, dir, kif, m, h,
6146 &pd, &a, &ruleset);
6147 if (action == PF_DROP)
6148 REASON_SET(&reason, PFRES_FRAG);
6149 goto done;
6150 case IPPROTO_ROUTING: {
6151 struct ip6_rthdr rthdr;
6152
6153 if (rh_cnt++) {
6154 DPFPRINTF(PF_DEBUG_MISC,
6155 ("pf: IPv6 more than one rthdr\n"));
6156 action = PF_DROP;
6157 REASON_SET(&reason, PFRES_IPOPTIONS);
6158 log = 1;
6159 goto done;
6160 }
6161 if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6162 &reason, pd.af)) {
6163 DPFPRINTF(PF_DEBUG_MISC,
6164 ("pf: IPv6 short rthdr\n"));
6165 action = PF_DROP;
6166 REASON_SET(&reason, PFRES_SHORT);
6167 log = 1;
6168 goto done;
6169 }
6170 if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6171 DPFPRINTF(PF_DEBUG_MISC,
6172 ("pf: IPv6 rthdr0\n"));
6173 action = PF_DROP;
6174 REASON_SET(&reason, PFRES_IPOPTIONS);
6175 log = 1;
6176 goto done;
6177 }
6178 /* FALLTHROUGH */
6179 }
6180 case IPPROTO_AH:
6181 case IPPROTO_HOPOPTS:
6182 case IPPROTO_DSTOPTS: {
6183 /* get next header and header length */
6184 struct ip6_ext opt6;
6185
6186 if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6187 NULL, &reason, pd.af)) {
6188 DPFPRINTF(PF_DEBUG_MISC,
6189 ("pf: IPv6 short opt\n"));
6190 action = PF_DROP;
6191 log = 1;
6192 goto done;
6193 }
6194 if (pd.proto == IPPROTO_AH)
6195 off += (opt6.ip6e_len + 2) * 4;
6196 else
6197 off += (opt6.ip6e_len + 1) * 8;
6198 pd.proto = opt6.ip6e_nxt;
6199 /* goto the next header */
6200 break;
6201 }
6202 default:
6203 terminal++;
6204 break;
6205 }
6206 } while (!terminal);
6207
6208 /* if there's no routing header, use unmodified mbuf for checksumming */
6209 if (!n)
6210 n = m;
6211
6212 switch (pd.proto) {
6213
6214 case IPPROTO_TCP: {
6215 struct tcphdr th;
6216
6217 pd.hdr.tcp = &th;
6218 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6219 &action, &reason, AF_INET6)) {
6220 log = action != PF_PASS;
6221 goto done;
6222 }
6223 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6224 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6225 if (action == PF_DROP)
6226 goto done;
6227 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6228 &reason);
6229 if (action == PF_PASS) {
6230 if (pfsync_update_state_ptr != NULL)
6231 pfsync_update_state_ptr(s);
6232 r = s->rule.ptr;
6233 a = s->anchor.ptr;
6234 log = s->log;
6235 } else if (s == NULL)
6236 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6237 &a, &ruleset, inp);
6238 break;
6239 }
6240
6241 case IPPROTO_UDP: {
6242 struct udphdr uh;
6243
6244 pd.hdr.udp = &uh;
6245 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6246 &action, &reason, AF_INET6)) {
6247 log = action != PF_PASS;
6248 goto done;
6249 }
6250 if (uh.uh_dport == 0 ||
6251 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6252 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6253 action = PF_DROP;
6254 REASON_SET(&reason, PFRES_SHORT);
6255 goto done;
6256 }
6257 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6258 if (action == PF_PASS) {
6259 if (pfsync_update_state_ptr != NULL)
6260 pfsync_update_state_ptr(s);
6261 r = s->rule.ptr;
6262 a = s->anchor.ptr;
6263 log = s->log;
6264 } else if (s == NULL)
6265 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6266 &a, &ruleset, inp);
6267 break;
6268 }
6269
6270 case IPPROTO_ICMP: {
6271 action = PF_DROP;
6272 DPFPRINTF(PF_DEBUG_MISC,
6273 ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
6274 goto done;
6275 }
6276
6277 case IPPROTO_ICMPV6: {
6278 struct icmp6_hdr ih;
6279
6280 pd.hdr.icmp6 = &ih;
6281 if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6282 &action, &reason, AF_INET6)) {
6283 log = action != PF_PASS;
6284 goto done;
6285 }
6286 action = pf_test_state_icmp(&s, dir, kif,
6287 m, off, h, &pd, &reason);
6288 if (action == PF_PASS) {
6289 if (pfsync_update_state_ptr != NULL)
6290 pfsync_update_state_ptr(s);
6291 r = s->rule.ptr;
6292 a = s->anchor.ptr;
6293 log = s->log;
6294 } else if (s == NULL)
6295 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6296 &a, &ruleset, inp);
6297 break;
6298 }
6299
6300 default:
6301 action = pf_test_state_other(&s, dir, kif, m, &pd);
6302 if (action == PF_PASS) {
6303 if (pfsync_update_state_ptr != NULL)
6304 pfsync_update_state_ptr(s);
6305 r = s->rule.ptr;
6306 a = s->anchor.ptr;
6307 log = s->log;
6308 } else if (s == NULL)
6309 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6310 &a, &ruleset, inp);
6311 break;
6312 }
6313
6314done:
6315 PF_RULES_RUNLOCK();
6316 if (n != m) {
6317 m_freem(n);
6318 n = NULL;
6319 }
6320
6321 /* handle dangerous IPv6 extension headers. */
6322 if (action == PF_PASS && rh_cnt &&
6323 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6324 action = PF_DROP;
6325 REASON_SET(&reason, PFRES_IPOPTIONS);
6326 log = 1;
6327 DPFPRINTF(PF_DEBUG_MISC,
6328 ("pf: dropping packet with dangerous v6 headers\n"));
6329 }
6330
6331 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6332 action = PF_DROP;
6333 REASON_SET(&reason, PFRES_MEMORY);
6334 }
6335 if (r->rtableid >= 0)
6336 M_SETFIB(m, r->rtableid);
6337
6338#ifdef ALTQ
6339 if (action == PF_PASS && r->qid) {
6340 if (pd.pf_mtag == NULL &&
6341 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6342 action = PF_DROP;
6343 REASON_SET(&reason, PFRES_MEMORY);
6344 }
6345 if (pd.tos & IPTOS_LOWDELAY)
6346 pd.pf_mtag->qid = r->pqid;
6347 else
6348 pd.pf_mtag->qid = r->qid;
6349 /* add hints for ecn */
6350 pd.pf_mtag->hdr = h;
6351 }
6352#endif /* ALTQ */
6353
6354 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6355 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6356 (s->nat_rule.ptr->action == PF_RDR ||
6357 s->nat_rule.ptr->action == PF_BINAT) &&
6358 IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6359 m->m_flags |= M_SKIP_FIREWALL;
6360
6361 /* XXX: Anybody working on it?! */
6362 if (r->divert.port)
6363 printf("pf: divert(9) is not supported for IPv6\n");
6364
6365 if (log) {
6366 struct pf_rule *lr;
6367
6368 if (s != NULL && s->nat_rule.ptr != NULL &&
6369 s->nat_rule.ptr->log & PF_LOG_ALL)
6370 lr = s->nat_rule.ptr;
6371 else
6372 lr = r;
6373 PFLOG_PACKET(kif, m, AF_INET6, dir, reason, lr, a, ruleset,
6374 &pd, (s == NULL));
6375 }
6376
6377 kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6378 kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6379
6380 if (action == PF_PASS || r->action == PF_DROP) {
6381 dirndx = (dir == PF_OUT);
6382 r->packets[dirndx]++;
6383 r->bytes[dirndx] += pd.tot_len;
6384 if (a != NULL) {
6385 a->packets[dirndx]++;
6386 a->bytes[dirndx] += pd.tot_len;
6387 }
6388 if (s != NULL) {
6389 if (s->nat_rule.ptr != NULL) {
6390 s->nat_rule.ptr->packets[dirndx]++;
6391 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6392 }
6393 if (s->src_node != NULL) {
6394 s->src_node->packets[dirndx]++;
6395 s->src_node->bytes[dirndx] += pd.tot_len;
6396 }
6397 if (s->nat_src_node != NULL) {
6398 s->nat_src_node->packets[dirndx]++;
6399 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6400 }
6401 dirndx = (dir == s->direction) ? 0 : 1;
6402 s->packets[dirndx]++;
6403 s->bytes[dirndx] += pd.tot_len;
6404 }
6405 tr = r;
6406 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6407 if (nr != NULL && r == &V_pf_default_rule)
6408 tr = nr;
6409 if (tr->src.addr.type == PF_ADDR_TABLE)
6410 pfr_update_stats(tr->src.addr.p.tbl,
6411 (s == NULL) ? pd.src :
6412 &s->key[(s->direction == PF_IN)]->addr[0],
6413 pd.af, pd.tot_len, dir == PF_OUT,
6414 r->action == PF_PASS, tr->src.neg);
6415 if (tr->dst.addr.type == PF_ADDR_TABLE)
6416 pfr_update_stats(tr->dst.addr.p.tbl,
6417 (s == NULL) ? pd.dst :
6418 &s->key[(s->direction == PF_IN)]->addr[1],
6419 pd.af, pd.tot_len, dir == PF_OUT,
6420 r->action == PF_PASS, tr->dst.neg);
6421 }
6422
6423 switch (action) {
6424 case PF_SYNPROXY_DROP:
6425 m_freem(*m0);
6426 case PF_DEFER:
6427 *m0 = NULL;
6428 action = PF_PASS;
6429 break;
6430 case PF_DROP:
6431 m_freem(*m0);
6432 *m0 = NULL;
6433 break;
6434 default:
6435 /* pf_route6() returns unlocked. */
6436 if (r->rt) {
6437 pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd);
6438 return (action);
6439 }
6440 break;
6441 }
6442
6443 if (s)
6444 PF_STATE_UNLOCK(s);
6445
6446 /* If reassembled packet passed, create new fragments. */
6447 if (action == PF_PASS && *m0 && fwdir == PF_FWD &&
6448 (mtag = m_tag_find(m, PF_REASSEMBLED, NULL)) != NULL)
6449 action = pf_refragment6(ifp, m0, mtag);
6450
6451 return (action);
6452}
6453#endif /* INET6 */