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