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