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