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