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_int16_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_int16_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 static int
pf_translate_af(struct pf_pdesc * pd,struct pf_krule * r)3609 pf_translate_af(struct pf_pdesc *pd, struct pf_krule *r)
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 if (pd->ttl == 1) {
3621 /* We'd generate an ICMP error. Do so now rather than after af translation. */
3622 if (pd->af == AF_INET) {
3623 pf_send_icmp(pd->m, ICMP_TIMXCEED,
3624 ICMP_TIMXCEED_INTRANS, 0, pd->af, r,
3625 pd->act.rtableid);
3626 } else {
3627 pf_send_icmp(pd->m, ICMP6_TIME_EXCEEDED,
3628 ICMP6_TIME_EXCEED_TRANSIT, 0, pd->af, r,
3629 pd->act.rtableid);
3630 }
3631
3632 return (-1);
3633 }
3634
3635 hlen = pd->naf == AF_INET ? sizeof(*ip4) : sizeof(*ip6);
3636
3637 /* trim the old header */
3638 m_adj(pd->m, pd->off);
3639
3640 /* prepend a new one */
3641 M_PREPEND(pd->m, hlen, M_NOWAIT);
3642 if (pd->m == NULL)
3643 return (-1);
3644
3645 switch (pd->naf) {
3646 case AF_INET:
3647 ip4 = mtod(pd->m, struct ip *);
3648 bzero(ip4, hlen);
3649 ip4->ip_v = IPVERSION;
3650 ip4->ip_hl = hlen >> 2;
3651 ip4->ip_tos = pd->tos;
3652 ip4->ip_len = htons(hlen + (pd->tot_len - pd->off));
3653 ip_fillid(ip4, V_ip_random_id);
3654 ip4->ip_ttl = pd->ttl;
3655 ip4->ip_p = pd->proto;
3656 ip4->ip_src = pd->nsaddr.v4;
3657 ip4->ip_dst = pd->ndaddr.v4;
3658 pd->src = (struct pf_addr *)&ip4->ip_src;
3659 pd->dst = (struct pf_addr *)&ip4->ip_dst;
3660 pd->off = sizeof(struct ip);
3661 if (pd->m->m_pkthdr.csum_flags & CSUM_TCP_IPV6) {
3662 pd->m->m_pkthdr.csum_flags &= ~CSUM_TCP_IPV6;
3663 pd->m->m_pkthdr.csum_flags |= CSUM_TCP;
3664 }
3665 if (pd->m->m_pkthdr.csum_flags & CSUM_UDP_IPV6) {
3666 pd->m->m_pkthdr.csum_flags &= ~CSUM_UDP_IPV6;
3667 pd->m->m_pkthdr.csum_flags |= CSUM_UDP;
3668 }
3669 if (pd->m->m_pkthdr.csum_flags & CSUM_SCTP_IPV6) {
3670 pd->m->m_pkthdr.csum_flags &= ~CSUM_SCTP_IPV6;
3671 pd->m->m_pkthdr.csum_flags |= CSUM_SCTP;
3672 }
3673 break;
3674 case AF_INET6:
3675 ip6 = mtod(pd->m, struct ip6_hdr *);
3676 bzero(ip6, hlen);
3677 ip6->ip6_vfc = IPV6_VERSION;
3678 ip6->ip6_flow |= htonl((u_int32_t)pd->tos << 20);
3679 ip6->ip6_plen = htons(pd->tot_len - pd->off);
3680 ip6->ip6_nxt = pd->proto;
3681 if (!pd->ttl || pd->ttl > IPV6_DEFHLIM)
3682 ip6->ip6_hlim = IPV6_DEFHLIM;
3683 else
3684 ip6->ip6_hlim = pd->ttl;
3685 ip6->ip6_src = pd->nsaddr.v6;
3686 ip6->ip6_dst = pd->ndaddr.v6;
3687 pd->src = (struct pf_addr *)&ip6->ip6_src;
3688 pd->dst = (struct pf_addr *)&ip6->ip6_dst;
3689 pd->off = sizeof(struct ip6_hdr);
3690 if (pd->m->m_pkthdr.csum_flags & CSUM_TCP) {
3691 pd->m->m_pkthdr.csum_flags &= ~CSUM_TCP;
3692 pd->m->m_pkthdr.csum_flags |= CSUM_TCP_IPV6;
3693 }
3694 if (pd->m->m_pkthdr.csum_flags & CSUM_UDP) {
3695 pd->m->m_pkthdr.csum_flags &= ~CSUM_UDP;
3696 pd->m->m_pkthdr.csum_flags |= CSUM_UDP_IPV6;
3697 }
3698 if (pd->m->m_pkthdr.csum_flags & CSUM_SCTP) {
3699 pd->m->m_pkthdr.csum_flags &= ~CSUM_SCTP;
3700 pd->m->m_pkthdr.csum_flags |= CSUM_SCTP_IPV6;
3701 }
3702
3703 /*
3704 * If we're dealing with a reassembled packet we need to adjust
3705 * the header length from the IPv4 header size to IPv6 header
3706 * size.
3707 */
3708 mtag = m_tag_find(pd->m, PACKET_TAG_PF_REASSEMBLED, NULL);
3709 if (mtag) {
3710 ftag = (struct pf_fragment_tag *)(mtag + 1);
3711 ftag->ft_hdrlen = sizeof(*ip6);
3712 ftag->ft_maxlen -= sizeof(struct ip6_hdr) -
3713 sizeof(struct ip) + sizeof(struct ip6_frag);
3714 }
3715 break;
3716 default:
3717 return (-1);
3718 }
3719
3720 /* recalculate icmp/icmp6 checksums */
3721 if (pd->proto == IPPROTO_ICMP || pd->proto == IPPROTO_ICMPV6) {
3722 int off;
3723 if ((mp = m_pulldown(pd->m, hlen, sizeof(*icmp), &off)) ==
3724 NULL) {
3725 pd->m = NULL;
3726 return (-1);
3727 }
3728 icmp = (struct icmp6_hdr *)(mp->m_data + off);
3729 icmp->icmp6_cksum = 0;
3730 icmp->icmp6_cksum = pd->naf == AF_INET ?
3731 in4_cksum(pd->m, 0, hlen, ntohs(ip4->ip_len) - hlen) :
3732 in6_cksum(pd->m, IPPROTO_ICMPV6, hlen,
3733 ntohs(ip6->ip6_plen));
3734 }
3735 #endif /* INET && INET6 */
3736
3737 return (0);
3738 }
3739
3740 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)3741 pf_change_icmp_af(struct mbuf *m, int off, struct pf_pdesc *pd,
3742 struct pf_pdesc *pd2, struct pf_addr *src, struct pf_addr *dst,
3743 sa_family_t af, sa_family_t naf)
3744 {
3745 #if defined(INET) && defined(INET6)
3746 struct mbuf *n = NULL;
3747 struct ip *ip4;
3748 struct ip6_hdr *ip6;
3749 int hlen, olen, mlen;
3750
3751 if (af == naf || (af != AF_INET && af != AF_INET6) ||
3752 (naf != AF_INET && naf != AF_INET6))
3753 return (-1);
3754
3755 /* split the mbuf chain on the inner ip/ip6 header boundary */
3756 if ((n = m_split(m, off, M_NOWAIT)) == NULL)
3757 return (-1);
3758
3759 /* old header */
3760 olen = pd2->off - off;
3761 /* new header */
3762 hlen = naf == AF_INET ? sizeof(*ip4) : sizeof(*ip6);
3763
3764 /* trim old header */
3765 m_adj(n, olen);
3766
3767 /* prepend a new one */
3768 M_PREPEND(n, hlen, M_NOWAIT);
3769 if (n == NULL)
3770 return (-1);
3771
3772 /* translate inner ip/ip6 header */
3773 switch (naf) {
3774 case AF_INET:
3775 ip4 = mtod(n, struct ip *);
3776 bzero(ip4, sizeof(*ip4));
3777 ip4->ip_v = IPVERSION;
3778 ip4->ip_hl = sizeof(*ip4) >> 2;
3779 ip4->ip_len = htons(sizeof(*ip4) + pd2->tot_len - olen);
3780 ip_fillid(ip4, V_ip_random_id);
3781 ip4->ip_off = htons(IP_DF);
3782 ip4->ip_ttl = pd2->ttl;
3783 if (pd2->proto == IPPROTO_ICMPV6)
3784 ip4->ip_p = IPPROTO_ICMP;
3785 else
3786 ip4->ip_p = pd2->proto;
3787 ip4->ip_src = src->v4;
3788 ip4->ip_dst = dst->v4;
3789 ip4->ip_sum = in_cksum(n, ip4->ip_hl << 2);
3790 break;
3791 case AF_INET6:
3792 ip6 = mtod(n, struct ip6_hdr *);
3793 bzero(ip6, sizeof(*ip6));
3794 ip6->ip6_vfc = IPV6_VERSION;
3795 ip6->ip6_plen = htons(pd2->tot_len - olen);
3796 if (pd2->proto == IPPROTO_ICMP)
3797 ip6->ip6_nxt = IPPROTO_ICMPV6;
3798 else
3799 ip6->ip6_nxt = pd2->proto;
3800 if (!pd2->ttl || pd2->ttl > IPV6_DEFHLIM)
3801 ip6->ip6_hlim = IPV6_DEFHLIM;
3802 else
3803 ip6->ip6_hlim = pd2->ttl;
3804 ip6->ip6_src = src->v6;
3805 ip6->ip6_dst = dst->v6;
3806 break;
3807 default:
3808 unhandled_af(naf);
3809 }
3810
3811 /* adjust payload offset and total packet length */
3812 pd2->off += hlen - olen;
3813 pd->tot_len += hlen - olen;
3814
3815 /* merge modified inner packet with the original header */
3816 mlen = n->m_pkthdr.len;
3817 m_cat(m, n);
3818 m->m_pkthdr.len += mlen;
3819 #endif /* INET && INET6 */
3820
3821 return (0);
3822 }
3823
3824 #define PTR_IP(field) (offsetof(struct ip, field))
3825 #define PTR_IP6(field) (offsetof(struct ip6_hdr, field))
3826
3827 int
pf_translate_icmp_af(int af,void * arg)3828 pf_translate_icmp_af(int af, void *arg)
3829 {
3830 #if defined(INET) && defined(INET6)
3831 struct icmp *icmp4;
3832 struct icmp6_hdr *icmp6;
3833 u_int32_t mtu;
3834 int32_t ptr = -1;
3835 u_int8_t type;
3836 u_int8_t code;
3837
3838 switch (af) {
3839 case AF_INET:
3840 icmp6 = arg;
3841 type = icmp6->icmp6_type;
3842 code = icmp6->icmp6_code;
3843 mtu = ntohl(icmp6->icmp6_mtu);
3844
3845 switch (type) {
3846 case ICMP6_ECHO_REQUEST:
3847 type = ICMP_ECHO;
3848 break;
3849 case ICMP6_ECHO_REPLY:
3850 type = ICMP_ECHOREPLY;
3851 break;
3852 case ICMP6_DST_UNREACH:
3853 type = ICMP_UNREACH;
3854 switch (code) {
3855 case ICMP6_DST_UNREACH_NOROUTE:
3856 case ICMP6_DST_UNREACH_BEYONDSCOPE:
3857 case ICMP6_DST_UNREACH_ADDR:
3858 code = ICMP_UNREACH_HOST;
3859 break;
3860 case ICMP6_DST_UNREACH_ADMIN:
3861 code = ICMP_UNREACH_HOST_PROHIB;
3862 break;
3863 case ICMP6_DST_UNREACH_NOPORT:
3864 code = ICMP_UNREACH_PORT;
3865 break;
3866 default:
3867 return (-1);
3868 }
3869 break;
3870 case ICMP6_PACKET_TOO_BIG:
3871 type = ICMP_UNREACH;
3872 code = ICMP_UNREACH_NEEDFRAG;
3873 mtu -= 20;
3874 break;
3875 case ICMP6_TIME_EXCEEDED:
3876 type = ICMP_TIMXCEED;
3877 break;
3878 case ICMP6_PARAM_PROB:
3879 switch (code) {
3880 case ICMP6_PARAMPROB_HEADER:
3881 type = ICMP_PARAMPROB;
3882 code = ICMP_PARAMPROB_ERRATPTR;
3883 ptr = ntohl(icmp6->icmp6_pptr);
3884
3885 if (ptr == PTR_IP6(ip6_vfc))
3886 ; /* preserve */
3887 else if (ptr == PTR_IP6(ip6_vfc) + 1)
3888 ptr = PTR_IP(ip_tos);
3889 else if (ptr == PTR_IP6(ip6_plen) ||
3890 ptr == PTR_IP6(ip6_plen) + 1)
3891 ptr = PTR_IP(ip_len);
3892 else if (ptr == PTR_IP6(ip6_nxt))
3893 ptr = PTR_IP(ip_p);
3894 else if (ptr == PTR_IP6(ip6_hlim))
3895 ptr = PTR_IP(ip_ttl);
3896 else if (ptr >= PTR_IP6(ip6_src) &&
3897 ptr < PTR_IP6(ip6_dst))
3898 ptr = PTR_IP(ip_src);
3899 else if (ptr >= PTR_IP6(ip6_dst) &&
3900 ptr < sizeof(struct ip6_hdr))
3901 ptr = PTR_IP(ip_dst);
3902 else {
3903 return (-1);
3904 }
3905 break;
3906 case ICMP6_PARAMPROB_NEXTHEADER:
3907 type = ICMP_UNREACH;
3908 code = ICMP_UNREACH_PROTOCOL;
3909 break;
3910 default:
3911 return (-1);
3912 }
3913 break;
3914 default:
3915 return (-1);
3916 }
3917 if (icmp6->icmp6_type != type) {
3918 icmp6->icmp6_cksum = pf_cksum_fixup(icmp6->icmp6_cksum,
3919 icmp6->icmp6_type, type, 0);
3920 icmp6->icmp6_type = type;
3921 }
3922 if (icmp6->icmp6_code != code) {
3923 icmp6->icmp6_cksum = pf_cksum_fixup(icmp6->icmp6_cksum,
3924 icmp6->icmp6_code, code, 0);
3925 icmp6->icmp6_code = code;
3926 }
3927 if (icmp6->icmp6_mtu != htonl(mtu)) {
3928 icmp6->icmp6_cksum = pf_cksum_fixup(icmp6->icmp6_cksum,
3929 htons(ntohl(icmp6->icmp6_mtu)), htons(mtu), 0);
3930 /* aligns well with a icmpv4 nextmtu */
3931 icmp6->icmp6_mtu = htonl(mtu);
3932 }
3933 if (ptr >= 0 && icmp6->icmp6_pptr != htonl(ptr)) {
3934 icmp6->icmp6_cksum = pf_cksum_fixup(icmp6->icmp6_cksum,
3935 htons(ntohl(icmp6->icmp6_pptr)), htons(ptr), 0);
3936 /* icmpv4 pptr is a one most significant byte */
3937 icmp6->icmp6_pptr = htonl(ptr << 24);
3938 }
3939 break;
3940 case AF_INET6:
3941 icmp4 = arg;
3942 type = icmp4->icmp_type;
3943 code = icmp4->icmp_code;
3944 mtu = ntohs(icmp4->icmp_nextmtu);
3945
3946 switch (type) {
3947 case ICMP_ECHO:
3948 type = ICMP6_ECHO_REQUEST;
3949 break;
3950 case ICMP_ECHOREPLY:
3951 type = ICMP6_ECHO_REPLY;
3952 break;
3953 case ICMP_UNREACH:
3954 type = ICMP6_DST_UNREACH;
3955 switch (code) {
3956 case ICMP_UNREACH_NET:
3957 case ICMP_UNREACH_HOST:
3958 case ICMP_UNREACH_NET_UNKNOWN:
3959 case ICMP_UNREACH_HOST_UNKNOWN:
3960 case ICMP_UNREACH_ISOLATED:
3961 case ICMP_UNREACH_TOSNET:
3962 case ICMP_UNREACH_TOSHOST:
3963 code = ICMP6_DST_UNREACH_NOROUTE;
3964 break;
3965 case ICMP_UNREACH_PORT:
3966 code = ICMP6_DST_UNREACH_NOPORT;
3967 break;
3968 case ICMP_UNREACH_NET_PROHIB:
3969 case ICMP_UNREACH_HOST_PROHIB:
3970 case ICMP_UNREACH_FILTER_PROHIB:
3971 case ICMP_UNREACH_PRECEDENCE_CUTOFF:
3972 code = ICMP6_DST_UNREACH_ADMIN;
3973 break;
3974 case ICMP_UNREACH_PROTOCOL:
3975 type = ICMP6_PARAM_PROB;
3976 code = ICMP6_PARAMPROB_NEXTHEADER;
3977 ptr = offsetof(struct ip6_hdr, ip6_nxt);
3978 break;
3979 case ICMP_UNREACH_NEEDFRAG:
3980 type = ICMP6_PACKET_TOO_BIG;
3981 code = 0;
3982 mtu += 20;
3983 break;
3984 default:
3985 return (-1);
3986 }
3987 break;
3988 case ICMP_TIMXCEED:
3989 type = ICMP6_TIME_EXCEEDED;
3990 break;
3991 case ICMP_PARAMPROB:
3992 type = ICMP6_PARAM_PROB;
3993 switch (code) {
3994 case ICMP_PARAMPROB_ERRATPTR:
3995 code = ICMP6_PARAMPROB_HEADER;
3996 break;
3997 case ICMP_PARAMPROB_LENGTH:
3998 code = ICMP6_PARAMPROB_HEADER;
3999 break;
4000 default:
4001 return (-1);
4002 }
4003
4004 ptr = icmp4->icmp_pptr;
4005 if (ptr == 0 || ptr == PTR_IP(ip_tos))
4006 ; /* preserve */
4007 else if (ptr == PTR_IP(ip_len) ||
4008 ptr == PTR_IP(ip_len) + 1)
4009 ptr = PTR_IP6(ip6_plen);
4010 else if (ptr == PTR_IP(ip_ttl))
4011 ptr = PTR_IP6(ip6_hlim);
4012 else if (ptr == PTR_IP(ip_p))
4013 ptr = PTR_IP6(ip6_nxt);
4014 else if (ptr >= PTR_IP(ip_src) && ptr < PTR_IP(ip_dst))
4015 ptr = PTR_IP6(ip6_src);
4016 else if (ptr >= PTR_IP(ip_dst) &&
4017 ptr < sizeof(struct ip))
4018 ptr = PTR_IP6(ip6_dst);
4019 else {
4020 return (-1);
4021 }
4022 break;
4023 default:
4024 return (-1);
4025 }
4026 if (icmp4->icmp_type != type) {
4027 icmp4->icmp_cksum = pf_cksum_fixup(icmp4->icmp_cksum,
4028 icmp4->icmp_type, type, 0);
4029 icmp4->icmp_type = type;
4030 }
4031 if (icmp4->icmp_code != code) {
4032 icmp4->icmp_cksum = pf_cksum_fixup(icmp4->icmp_cksum,
4033 icmp4->icmp_code, code, 0);
4034 icmp4->icmp_code = code;
4035 }
4036 if (icmp4->icmp_nextmtu != htons(mtu)) {
4037 icmp4->icmp_cksum = pf_cksum_fixup(icmp4->icmp_cksum,
4038 icmp4->icmp_nextmtu, htons(mtu), 0);
4039 icmp4->icmp_nextmtu = htons(mtu);
4040 }
4041 if (ptr >= 0 && icmp4->icmp_void != ptr) {
4042 icmp4->icmp_cksum = pf_cksum_fixup(icmp4->icmp_cksum,
4043 htons(icmp4->icmp_pptr), htons(ptr), 0);
4044 icmp4->icmp_void = htonl(ptr);
4045 }
4046 break;
4047 default:
4048 unhandled_af(af);
4049 }
4050 #endif /* INET && INET6 */
4051
4052 return (0);
4053 }
4054
4055 /*
4056 * Need to modulate the sequence numbers in the TCP SACK option
4057 * (credits to Krzysztof Pfaff for report and patch)
4058 */
4059 static int
pf_modulate_sack(struct pf_pdesc * pd,struct tcphdr * th,struct pf_state_peer * dst)4060 pf_modulate_sack(struct pf_pdesc *pd, struct tcphdr *th,
4061 struct pf_state_peer *dst)
4062 {
4063 struct sackblk sack;
4064 int copyback = 0, i;
4065 int olen, optsoff;
4066 uint8_t opts[MAX_TCPOPTLEN], *opt, *eoh;
4067
4068 olen = (pd->hdr.tcp.th_off << 2) - sizeof(struct tcphdr);
4069 optsoff = pd->off + sizeof(struct tcphdr);
4070 #define TCPOLEN_MINSACK (TCPOLEN_SACK + 2)
4071 if (olen < TCPOLEN_MINSACK ||
4072 !pf_pull_hdr(pd->m, optsoff, opts, olen, NULL, pd->af))
4073 return (0);
4074
4075 eoh = opts + olen;
4076 opt = opts;
4077 while ((opt = pf_find_tcpopt(opt, opts, olen,
4078 TCPOPT_SACK, TCPOLEN_MINSACK)) != NULL)
4079 {
4080 size_t safelen = MIN(opt[1], (eoh - opt));
4081 for (i = 2; i + TCPOLEN_SACK <= safelen; i += TCPOLEN_SACK) {
4082 size_t startoff = (opt + i) - opts;
4083 memcpy(&sack, &opt[i], sizeof(sack));
4084 pf_patch_32(pd, &sack.start,
4085 htonl(ntohl(sack.start) - dst->seqdiff),
4086 PF_ALGNMNT(startoff));
4087 pf_patch_32(pd, &sack.end,
4088 htonl(ntohl(sack.end) - dst->seqdiff),
4089 PF_ALGNMNT(startoff + sizeof(sack.start)));
4090 memcpy(&opt[i], &sack, sizeof(sack));
4091 }
4092 copyback = 1;
4093 opt += opt[1];
4094 }
4095
4096 if (copyback)
4097 m_copyback(pd->m, optsoff, olen, (caddr_t)opts);
4098
4099 return (copyback);
4100 }
4101
4102 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)4103 pf_build_tcp(const struct pf_krule *r, sa_family_t af,
4104 const struct pf_addr *saddr, const struct pf_addr *daddr,
4105 u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
4106 u_int8_t tcp_flags, u_int16_t win, u_int16_t mss, u_int8_t ttl,
4107 int mbuf_flags, u_int16_t mtag_tag, u_int16_t mtag_flags, u_int sack,
4108 int rtableid, u_short *reason)
4109 {
4110 struct mbuf *m;
4111 int len, tlen;
4112 #ifdef INET
4113 struct ip *h = NULL;
4114 #endif /* INET */
4115 #ifdef INET6
4116 struct ip6_hdr *h6 = NULL;
4117 #endif /* INET6 */
4118 struct tcphdr *th;
4119 char *opt;
4120 struct pf_mtag *pf_mtag;
4121
4122 len = 0;
4123 th = NULL;
4124
4125 /* maximum segment size tcp option */
4126 tlen = sizeof(struct tcphdr);
4127 if (mss)
4128 tlen += 4;
4129 if (sack)
4130 tlen += 2;
4131
4132 switch (af) {
4133 #ifdef INET
4134 case AF_INET:
4135 len = sizeof(struct ip) + tlen;
4136 break;
4137 #endif /* INET */
4138 #ifdef INET6
4139 case AF_INET6:
4140 len = sizeof(struct ip6_hdr) + tlen;
4141 break;
4142 #endif /* INET6 */
4143 default:
4144 unhandled_af(af);
4145 }
4146
4147 m = m_gethdr(M_NOWAIT, MT_DATA);
4148 if (m == NULL) {
4149 REASON_SET(reason, PFRES_MEMORY);
4150 return (NULL);
4151 }
4152
4153 #ifdef MAC
4154 mac_netinet_firewall_send(m);
4155 #endif
4156 if ((pf_mtag = pf_get_mtag(m)) == NULL) {
4157 REASON_SET(reason, PFRES_MEMORY);
4158 m_freem(m);
4159 return (NULL);
4160 }
4161 m->m_flags |= mbuf_flags;
4162 pf_mtag->tag = mtag_tag;
4163 pf_mtag->flags = mtag_flags;
4164
4165 if (rtableid >= 0)
4166 M_SETFIB(m, rtableid);
4167
4168 #ifdef ALTQ
4169 if (r != NULL && r->qid) {
4170 pf_mtag->qid = r->qid;
4171
4172 /* add hints for ecn */
4173 pf_mtag->hdr = mtod(m, struct ip *);
4174 }
4175 #endif /* ALTQ */
4176 m->m_data += max_linkhdr;
4177 m->m_pkthdr.len = m->m_len = len;
4178 /* The rest of the stack assumes a rcvif, so provide one.
4179 * This is a locally generated packet, so .. close enough. */
4180 m->m_pkthdr.rcvif = V_loif;
4181 bzero(m->m_data, len);
4182 switch (af) {
4183 #ifdef INET
4184 case AF_INET:
4185 m->m_pkthdr.csum_flags |= CSUM_TCP;
4186 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
4187
4188 h = mtod(m, struct ip *);
4189
4190 h->ip_p = IPPROTO_TCP;
4191 h->ip_len = htons(tlen);
4192 h->ip_v = 4;
4193 h->ip_hl = sizeof(*h) >> 2;
4194 h->ip_tos = IPTOS_LOWDELAY;
4195 h->ip_len = htons(len);
4196 h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
4197 h->ip_ttl = ttl ? ttl : V_ip_defttl;
4198 h->ip_sum = 0;
4199 h->ip_src.s_addr = saddr->v4.s_addr;
4200 h->ip_dst.s_addr = daddr->v4.s_addr;
4201
4202 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
4203 th->th_sum = in_pseudo(h->ip_src.s_addr, h->ip_dst.s_addr,
4204 htons(len - sizeof(struct ip) + IPPROTO_TCP));
4205 break;
4206 #endif /* INET */
4207 #ifdef INET6
4208 case AF_INET6:
4209 m->m_pkthdr.csum_flags |= CSUM_TCP_IPV6;
4210 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
4211
4212 h6 = mtod(m, struct ip6_hdr *);
4213
4214 /* IP header fields included in the TCP checksum */
4215 h6->ip6_nxt = IPPROTO_TCP;
4216 h6->ip6_plen = htons(tlen);
4217 h6->ip6_vfc |= IPV6_VERSION;
4218 h6->ip6_hlim = V_ip6_defhlim;
4219 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
4220 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
4221
4222 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
4223 th->th_sum = in6_cksum_pseudo(h6, len - sizeof(struct ip6_hdr),
4224 IPPROTO_TCP, 0);
4225 break;
4226 #endif /* INET6 */
4227 }
4228
4229 /* TCP header */
4230 th->th_sport = sport;
4231 th->th_dport = dport;
4232 th->th_seq = htonl(seq);
4233 th->th_ack = htonl(ack);
4234 th->th_off = tlen >> 2;
4235 tcp_set_flags(th, tcp_flags);
4236 th->th_win = htons(win);
4237
4238 opt = (char *)(th + 1);
4239 if (mss) {
4240 opt = (char *)(th + 1);
4241 opt[0] = TCPOPT_MAXSEG;
4242 opt[1] = 4;
4243 mss = htons(mss);
4244 memcpy((opt + 2), &mss, 2);
4245 opt += 4;
4246 }
4247 if (sack) {
4248 opt[0] = TCPOPT_SACK_PERMITTED;
4249 opt[1] = 2;
4250 opt += 2;
4251 }
4252
4253 return (m);
4254 }
4255
4256 static void
pf_send_sctp_abort(sa_family_t af,struct pf_pdesc * pd,uint8_t ttl,int rtableid)4257 pf_send_sctp_abort(sa_family_t af, struct pf_pdesc *pd,
4258 uint8_t ttl, int rtableid)
4259 {
4260 struct mbuf *m;
4261 #ifdef INET
4262 struct ip *h = NULL;
4263 #endif /* INET */
4264 #ifdef INET6
4265 struct ip6_hdr *h6 = NULL;
4266 #endif /* INET6 */
4267 struct sctphdr *hdr;
4268 struct sctp_chunkhdr *chunk;
4269 struct pf_send_entry *pfse;
4270 int off = 0;
4271
4272 MPASS(af == pd->af);
4273
4274 m = m_gethdr(M_NOWAIT, MT_DATA);
4275 if (m == NULL)
4276 return;
4277
4278 m->m_data += max_linkhdr;
4279 m->m_flags |= M_SKIP_FIREWALL;
4280 /* The rest of the stack assumes a rcvif, so provide one.
4281 * This is a locally generated packet, so .. close enough. */
4282 m->m_pkthdr.rcvif = V_loif;
4283
4284 /* IPv4|6 header */
4285 switch (af) {
4286 #ifdef INET
4287 case AF_INET:
4288 bzero(m->m_data, sizeof(struct ip) + sizeof(*hdr) + sizeof(*chunk));
4289
4290 h = mtod(m, struct ip *);
4291
4292 /* IP header fields included in the TCP checksum */
4293
4294 h->ip_p = IPPROTO_SCTP;
4295 h->ip_len = htons(sizeof(*h) + sizeof(*hdr) + sizeof(*chunk));
4296 h->ip_ttl = ttl ? ttl : V_ip_defttl;
4297 h->ip_src = pd->dst->v4;
4298 h->ip_dst = pd->src->v4;
4299
4300 off += sizeof(struct ip);
4301 break;
4302 #endif /* INET */
4303 #ifdef INET6
4304 case AF_INET6:
4305 bzero(m->m_data, sizeof(struct ip6_hdr) + sizeof(*hdr) + sizeof(*chunk));
4306
4307 h6 = mtod(m, struct ip6_hdr *);
4308
4309 /* IP header fields included in the TCP checksum */
4310 h6->ip6_vfc |= IPV6_VERSION;
4311 h6->ip6_nxt = IPPROTO_SCTP;
4312 h6->ip6_plen = htons(sizeof(*h6) + sizeof(*hdr) + sizeof(*chunk));
4313 h6->ip6_hlim = ttl ? ttl : V_ip6_defhlim;
4314 memcpy(&h6->ip6_src, &pd->dst->v6, sizeof(struct in6_addr));
4315 memcpy(&h6->ip6_dst, &pd->src->v6, sizeof(struct in6_addr));
4316
4317 off += sizeof(struct ip6_hdr);
4318 break;
4319 #endif /* INET6 */
4320 default:
4321 unhandled_af(af);
4322 }
4323
4324 /* SCTP header */
4325 hdr = mtodo(m, off);
4326
4327 hdr->src_port = pd->hdr.sctp.dest_port;
4328 hdr->dest_port = pd->hdr.sctp.src_port;
4329 hdr->v_tag = pd->sctp_initiate_tag;
4330 hdr->checksum = 0;
4331
4332 /* Abort chunk. */
4333 off += sizeof(struct sctphdr);
4334 chunk = mtodo(m, off);
4335
4336 chunk->chunk_type = SCTP_ABORT_ASSOCIATION;
4337 chunk->chunk_length = htons(sizeof(*chunk));
4338
4339 /* SCTP checksum */
4340 off += sizeof(*chunk);
4341 m->m_pkthdr.len = m->m_len = off;
4342
4343 pf_sctp_checksum(m, off - sizeof(*hdr) - sizeof(*chunk));
4344
4345 if (rtableid >= 0)
4346 M_SETFIB(m, rtableid);
4347
4348 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
4349 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
4350 if (pfse == NULL) {
4351 m_freem(m);
4352 return;
4353 }
4354
4355 switch (af) {
4356 #ifdef INET
4357 case AF_INET:
4358 pfse->pfse_type = PFSE_IP;
4359 break;
4360 #endif /* INET */
4361 #ifdef INET6
4362 case AF_INET6:
4363 pfse->pfse_type = PFSE_IP6;
4364 break;
4365 #endif /* INET6 */
4366 }
4367
4368 pfse->pfse_m = m;
4369 pf_send(pfse);
4370 }
4371
4372 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)4373 pf_send_tcp(const struct pf_krule *r, sa_family_t af,
4374 const struct pf_addr *saddr, const struct pf_addr *daddr,
4375 u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
4376 u_int8_t tcp_flags, u_int16_t win, u_int16_t mss, u_int8_t ttl,
4377 int mbuf_flags, u_int16_t mtag_tag, u_int16_t mtag_flags, int rtableid,
4378 u_short *reason)
4379 {
4380 struct pf_send_entry *pfse;
4381 struct mbuf *m;
4382
4383 m = pf_build_tcp(r, af, saddr, daddr, sport, dport, seq, ack, tcp_flags,
4384 win, mss, ttl, mbuf_flags, mtag_tag, mtag_flags, 0, rtableid, reason);
4385 if (m == NULL)
4386 return;
4387
4388 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
4389 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
4390 if (pfse == NULL) {
4391 m_freem(m);
4392 REASON_SET(reason, PFRES_MEMORY);
4393 return;
4394 }
4395
4396 switch (af) {
4397 #ifdef INET
4398 case AF_INET:
4399 pfse->pfse_type = PFSE_IP;
4400 break;
4401 #endif /* INET */
4402 #ifdef INET6
4403 case AF_INET6:
4404 pfse->pfse_type = PFSE_IP6;
4405 break;
4406 #endif /* INET6 */
4407 default:
4408 unhandled_af(af);
4409 }
4410
4411 pfse->pfse_m = m;
4412 pf_send(pfse);
4413 }
4414
4415 static void
pf_undo_nat(struct pf_krule * nr,struct pf_pdesc * pd,uint16_t bip_sum)4416 pf_undo_nat(struct pf_krule *nr, struct pf_pdesc *pd, uint16_t bip_sum)
4417 {
4418 /* undo NAT changes, if they have taken place */
4419 if (nr != NULL) {
4420 pf_addrcpy(pd->src, &pd->osrc, pd->af);
4421 pf_addrcpy(pd->dst, &pd->odst, pd->af);
4422 if (pd->sport)
4423 *pd->sport = pd->osport;
4424 if (pd->dport)
4425 *pd->dport = pd->odport;
4426 if (pd->ip_sum)
4427 *pd->ip_sum = bip_sum;
4428 m_copyback(pd->m, pd->off, pd->hdrlen, pd->hdr.any);
4429 }
4430 }
4431
4432 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)4433 pf_return(struct pf_krule *r, struct pf_krule *nr, struct pf_pdesc *pd,
4434 struct tcphdr *th, u_int16_t bproto_sum, u_int16_t bip_sum,
4435 u_short *reason, int rtableid)
4436 {
4437 pf_undo_nat(nr, pd, bip_sum);
4438
4439 if (pd->proto == IPPROTO_TCP &&
4440 ((r->rule_flag & PFRULE_RETURNRST) ||
4441 (r->rule_flag & PFRULE_RETURN)) &&
4442 !(tcp_get_flags(th) & TH_RST)) {
4443 u_int32_t ack = ntohl(th->th_seq) + pd->p_len;
4444
4445 if (pf_check_proto_cksum(pd->m, pd->off, pd->tot_len - pd->off,
4446 IPPROTO_TCP, pd->af))
4447 REASON_SET(reason, PFRES_PROTCKSUM);
4448 else {
4449 if (tcp_get_flags(th) & TH_SYN)
4450 ack++;
4451 if (tcp_get_flags(th) & TH_FIN)
4452 ack++;
4453 pf_send_tcp(r, pd->af, pd->dst,
4454 pd->src, th->th_dport, th->th_sport,
4455 ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
4456 r->return_ttl, M_SKIP_FIREWALL, 0, 0, rtableid,
4457 reason);
4458 }
4459 } else if (pd->proto == IPPROTO_SCTP &&
4460 (r->rule_flag & PFRULE_RETURN)) {
4461 pf_send_sctp_abort(pd->af, pd, r->return_ttl, rtableid);
4462 } else if (pd->proto != IPPROTO_ICMP && pd->af == AF_INET &&
4463 r->return_icmp)
4464 pf_send_icmp(pd->m, r->return_icmp >> 8,
4465 r->return_icmp & 255, 0, pd->af, r, rtableid);
4466 else if (pd->proto != IPPROTO_ICMPV6 && pd->af == AF_INET6 &&
4467 r->return_icmp6)
4468 pf_send_icmp(pd->m, r->return_icmp6 >> 8,
4469 r->return_icmp6 & 255, 0, pd->af, r, rtableid);
4470 }
4471
4472 static int
pf_match_ieee8021q_pcp(u_int8_t prio,struct mbuf * m)4473 pf_match_ieee8021q_pcp(u_int8_t prio, struct mbuf *m)
4474 {
4475 struct m_tag *mtag;
4476 u_int8_t mpcp;
4477
4478 mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_IN, NULL);
4479 if (mtag == NULL)
4480 return (0);
4481
4482 if (prio == PF_PRIO_ZERO)
4483 prio = 0;
4484
4485 mpcp = *(uint8_t *)(mtag + 1);
4486
4487 return (mpcp == prio);
4488 }
4489
4490 static int
pf_icmp_to_bandlim(uint8_t type)4491 pf_icmp_to_bandlim(uint8_t type)
4492 {
4493 switch (type) {
4494 case ICMP_ECHO:
4495 case ICMP_ECHOREPLY:
4496 return (BANDLIM_ICMP_ECHO);
4497 case ICMP_TSTAMP:
4498 case ICMP_TSTAMPREPLY:
4499 return (BANDLIM_ICMP_TSTAMP);
4500 case ICMP_UNREACH:
4501 default:
4502 return (BANDLIM_ICMP_UNREACH);
4503 }
4504 }
4505
4506 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)4507 pf_send_challenge_ack(struct pf_pdesc *pd, struct pf_kstate *s,
4508 struct pf_state_peer *src, struct pf_state_peer *dst,
4509 u_short *reason)
4510 {
4511 /*
4512 * We are sending challenge ACK as a response to SYN packet, which
4513 * matches existing state (modulo TCP window check). Therefore packet
4514 * must be sent on behalf of destination.
4515 *
4516 * We expect sender to remain either silent, or send RST packet
4517 * so both, firewall and remote peer, can purge dead state from
4518 * memory.
4519 */
4520 pf_send_tcp(s->rule, pd->af, pd->dst, pd->src,
4521 pd->hdr.tcp.th_dport, pd->hdr.tcp.th_sport, dst->seqlo,
4522 src->seqlo, TH_ACK, 0, 0, s->rule->return_ttl, 0, 0, 0,
4523 s->rule->rtableid, reason);
4524 }
4525
4526 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)4527 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, int mtu,
4528 sa_family_t af, struct pf_krule *r, int rtableid)
4529 {
4530 struct pf_send_entry *pfse;
4531 struct mbuf *m0;
4532 struct pf_mtag *pf_mtag;
4533
4534 /* ICMP packet rate limitation. */
4535 switch (af) {
4536 #ifdef INET6
4537 case AF_INET6:
4538 if (icmp6_ratelimit(NULL, type, code))
4539 return;
4540 break;
4541 #endif /* INET6 */
4542 #ifdef INET
4543 case AF_INET:
4544 if (badport_bandlim(pf_icmp_to_bandlim(type)) != 0)
4545 return;
4546 break;
4547 #endif /* INET */
4548 }
4549
4550 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
4551 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
4552 if (pfse == NULL)
4553 return;
4554
4555 if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
4556 free(pfse, M_PFTEMP);
4557 return;
4558 }
4559
4560 if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
4561 free(pfse, M_PFTEMP);
4562 return;
4563 }
4564 /* XXX: revisit */
4565 m0->m_flags |= M_SKIP_FIREWALL;
4566
4567 if (rtableid >= 0)
4568 M_SETFIB(m0, rtableid);
4569
4570 #ifdef ALTQ
4571 if (r->qid) {
4572 pf_mtag->qid = r->qid;
4573 /* add hints for ecn */
4574 pf_mtag->hdr = mtod(m0, struct ip *);
4575 }
4576 #endif /* ALTQ */
4577
4578 switch (af) {
4579 #ifdef INET
4580 case AF_INET:
4581 pfse->pfse_type = PFSE_ICMP;
4582 break;
4583 #endif /* INET */
4584 #ifdef INET6
4585 case AF_INET6:
4586 pfse->pfse_type = PFSE_ICMP6;
4587 break;
4588 #endif /* INET6 */
4589 }
4590 pfse->pfse_m = m0;
4591 pfse->icmpopts.type = type;
4592 pfse->icmpopts.code = code;
4593 pfse->icmpopts.mtu = mtu;
4594 pf_send(pfse);
4595 }
4596
4597 /*
4598 * Return ((n = 0) == (a = b [with mask m]))
4599 * Note: n != 0 => returns (a != b [with mask m])
4600 */
4601 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)4602 pf_match_addr(u_int8_t n, const struct pf_addr *a, const struct pf_addr *m,
4603 const struct pf_addr *b, sa_family_t af)
4604 {
4605 switch (af) {
4606 #ifdef INET
4607 case AF_INET:
4608 if (IN_ARE_MASKED_ADDR_EQUAL(a->v4, b->v4, m->v4))
4609 return (n == 0);
4610 break;
4611 #endif /* INET */
4612 #ifdef INET6
4613 case AF_INET6:
4614 if (IN6_ARE_MASKED_ADDR_EQUAL(&a->v6, &b->v6, &m->v6))
4615 return (n == 0);
4616 break;
4617 #endif /* INET6 */
4618 }
4619
4620 return (n != 0);
4621 }
4622
4623 /*
4624 * Return 1 if b <= a <= e, otherwise return 0.
4625 */
4626 int
pf_match_addr_range(const struct pf_addr * b,const struct pf_addr * e,const struct pf_addr * a,sa_family_t af)4627 pf_match_addr_range(const struct pf_addr *b, const struct pf_addr *e,
4628 const struct pf_addr *a, sa_family_t af)
4629 {
4630 switch (af) {
4631 #ifdef INET
4632 case AF_INET:
4633 if ((ntohl(a->addr32[0]) < ntohl(b->addr32[0])) ||
4634 (ntohl(a->addr32[0]) > ntohl(e->addr32[0])))
4635 return (0);
4636 break;
4637 #endif /* INET */
4638 #ifdef INET6
4639 case AF_INET6: {
4640 int i;
4641
4642 /* check a >= b */
4643 for (i = 0; i < 4; ++i)
4644 if (ntohl(a->addr32[i]) > ntohl(b->addr32[i]))
4645 break;
4646 else if (ntohl(a->addr32[i]) < ntohl(b->addr32[i]))
4647 return (0);
4648 /* check a <= e */
4649 for (i = 0; i < 4; ++i)
4650 if (ntohl(a->addr32[i]) < ntohl(e->addr32[i]))
4651 break;
4652 else if (ntohl(a->addr32[i]) > ntohl(e->addr32[i]))
4653 return (0);
4654 break;
4655 }
4656 #endif /* INET6 */
4657 }
4658 return (1);
4659 }
4660
4661 static int
pf_match(u_int8_t op,u_int32_t a1,u_int32_t a2,u_int32_t p)4662 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
4663 {
4664 switch (op) {
4665 case PF_OP_IRG:
4666 return ((p > a1) && (p < a2));
4667 case PF_OP_XRG:
4668 return ((p < a1) || (p > a2));
4669 case PF_OP_RRG:
4670 return ((p >= a1) && (p <= a2));
4671 case PF_OP_EQ:
4672 return (p == a1);
4673 case PF_OP_NE:
4674 return (p != a1);
4675 case PF_OP_LT:
4676 return (p < a1);
4677 case PF_OP_LE:
4678 return (p <= a1);
4679 case PF_OP_GT:
4680 return (p > a1);
4681 case PF_OP_GE:
4682 return (p >= a1);
4683 }
4684 return (0); /* never reached */
4685 }
4686
4687 int
pf_match_port(u_int8_t op,u_int16_t a1,u_int16_t a2,u_int16_t p)4688 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
4689 {
4690 return (pf_match(op, ntohs(a1), ntohs(a2), ntohs(p)));
4691 }
4692
4693 static int
pf_match_uid(u_int8_t op,uid_t a1,uid_t a2,uid_t u)4694 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
4695 {
4696 if (u == -1 && op != PF_OP_EQ && op != PF_OP_NE)
4697 return (0);
4698 return (pf_match(op, a1, a2, u));
4699 }
4700
4701 static int
pf_match_gid(u_int8_t op,gid_t a1,gid_t a2,gid_t g)4702 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
4703 {
4704 if (g == -1 && op != PF_OP_EQ && op != PF_OP_NE)
4705 return (0);
4706 return (pf_match(op, a1, a2, g));
4707 }
4708
4709 int
pf_match_tag(struct mbuf * m,struct pf_krule * r,int * tag,int mtag)4710 pf_match_tag(struct mbuf *m, struct pf_krule *r, int *tag, int mtag)
4711 {
4712 if (*tag == -1)
4713 *tag = mtag;
4714
4715 return ((!r->match_tag_not && r->match_tag == *tag) ||
4716 (r->match_tag_not && r->match_tag != *tag));
4717 }
4718
4719 static int
pf_match_rcvif(struct mbuf * m,struct pf_krule * r)4720 pf_match_rcvif(struct mbuf *m, struct pf_krule *r)
4721 {
4722 struct ifnet *ifp = m->m_pkthdr.rcvif;
4723 struct pfi_kkif *kif;
4724
4725 if (ifp == NULL)
4726 return (0);
4727
4728 kif = (struct pfi_kkif *)ifp->if_pf_kif;
4729
4730 if (kif == NULL) {
4731 DPFPRINTF(PF_DEBUG_URGENT,
4732 "%s: kif == NULL, @%d via %s", __func__, r->nr,
4733 r->rcv_ifname);
4734 return (0);
4735 }
4736
4737 return (pfi_kkif_match(r->rcv_kif, kif));
4738 }
4739
4740 int
pf_tag_packet(struct pf_pdesc * pd,int tag)4741 pf_tag_packet(struct pf_pdesc *pd, int tag)
4742 {
4743
4744 KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
4745
4746 if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(pd->m)) == NULL))
4747 return (ENOMEM);
4748
4749 pd->pf_mtag->tag = tag;
4750
4751 return (0);
4752 }
4753
4754 /*
4755 * XXX: We rely on malloc(9) returning pointer aligned addresses.
4756 */
4757 #define PF_ANCHORSTACK_MATCH 0x00000001
4758 #define PF_ANCHORSTACK_MASK (PF_ANCHORSTACK_MATCH)
4759
4760 #define PF_ANCHOR_MATCH(f) ((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
4761 #define PF_ANCHOR_RULE(f) (struct pf_krule *) \
4762 ((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
4763 #define PF_ANCHOR_SET_MATCH(f) do { (f)->r = (void *) \
4764 ((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH); \
4765 } while (0)
4766
4767 enum pf_test_status
pf_step_into_anchor(struct pf_test_ctx * ctx,struct pf_krule * r,struct pf_krule_slist * match_rules)4768 pf_step_into_anchor(struct pf_test_ctx *ctx, struct pf_krule *r,
4769 struct pf_krule_slist *match_rules)
4770 {
4771 enum pf_test_status rv;
4772
4773 PF_RULES_RASSERT();
4774
4775 if (ctx->depth >= PF_ANCHOR_STACK_MAX) {
4776 printf("%s: anchor stack overflow on %s\n",
4777 __func__, r->anchor->name);
4778 return (PF_TEST_FAIL);
4779 }
4780
4781 ctx->depth++;
4782
4783 if (r->anchor_wildcard) {
4784 struct pf_kanchor *child;
4785 rv = PF_TEST_OK;
4786 RB_FOREACH(child, pf_kanchor_node, &r->anchor->children) {
4787 rv = pf_match_rule(ctx, &child->ruleset, match_rules);
4788 if ((rv == PF_TEST_QUICK) || (rv == PF_TEST_FAIL)) {
4789 /*
4790 * we either hit a rule with quick action
4791 * (more likely), or hit some runtime
4792 * error (e.g. pool_get() failure).
4793 */
4794 break;
4795 }
4796 }
4797 } else {
4798 rv = pf_match_rule(ctx, &r->anchor->ruleset, match_rules);
4799 /*
4800 * Unless errors occured, stop iff any rule matched
4801 * within quick anchors.
4802 */
4803 if (rv != PF_TEST_FAIL && r->quick == PF_TEST_QUICK &&
4804 *ctx->am == r)
4805 rv = PF_TEST_QUICK;
4806 }
4807
4808 ctx->depth--;
4809
4810 return (rv);
4811 }
4812
4813 struct pf_keth_anchor_stackframe {
4814 struct pf_keth_ruleset *rs;
4815 struct pf_keth_rule *r; /* XXX: + match bit */
4816 struct pf_keth_anchor *child;
4817 };
4818
4819 #define PF_ETH_ANCHOR_MATCH(f) ((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
4820 #define PF_ETH_ANCHOR_RULE(f) (struct pf_keth_rule *) \
4821 ((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
4822 #define PF_ETH_ANCHOR_SET_MATCH(f) do { (f)->r = (void *) \
4823 ((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH); \
4824 } while (0)
4825
4826 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)4827 pf_step_into_keth_anchor(struct pf_keth_anchor_stackframe *stack, int *depth,
4828 struct pf_keth_ruleset **rs, struct pf_keth_rule **r,
4829 struct pf_keth_rule **a, int *match)
4830 {
4831 struct pf_keth_anchor_stackframe *f;
4832
4833 NET_EPOCH_ASSERT();
4834
4835 if (match)
4836 *match = 0;
4837 if (*depth >= PF_ANCHOR_STACK_MAX) {
4838 printf("%s: anchor stack overflow on %s\n",
4839 __func__, (*r)->anchor->name);
4840 *r = TAILQ_NEXT(*r, entries);
4841 return;
4842 } else if (*depth == 0 && a != NULL)
4843 *a = *r;
4844 f = stack + (*depth)++;
4845 f->rs = *rs;
4846 f->r = *r;
4847 if ((*r)->anchor_wildcard) {
4848 struct pf_keth_anchor_node *parent = &(*r)->anchor->children;
4849
4850 if ((f->child = RB_MIN(pf_keth_anchor_node, parent)) == NULL) {
4851 *r = NULL;
4852 return;
4853 }
4854 *rs = &f->child->ruleset;
4855 } else {
4856 f->child = NULL;
4857 *rs = &(*r)->anchor->ruleset;
4858 }
4859 *r = TAILQ_FIRST((*rs)->active.rules);
4860 }
4861
4862 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)4863 pf_step_out_of_keth_anchor(struct pf_keth_anchor_stackframe *stack, int *depth,
4864 struct pf_keth_ruleset **rs, struct pf_keth_rule **r,
4865 struct pf_keth_rule **a, int *match)
4866 {
4867 struct pf_keth_anchor_stackframe *f;
4868 struct pf_keth_rule *fr;
4869 int quick = 0;
4870
4871 NET_EPOCH_ASSERT();
4872
4873 do {
4874 if (*depth <= 0)
4875 break;
4876 f = stack + *depth - 1;
4877 fr = PF_ETH_ANCHOR_RULE(f);
4878 if (f->child != NULL) {
4879 /*
4880 * This block traverses through
4881 * a wildcard anchor.
4882 */
4883 if (match != NULL && *match) {
4884 /*
4885 * If any of "*" matched, then
4886 * "foo/ *" matched, mark frame
4887 * appropriately.
4888 */
4889 PF_ETH_ANCHOR_SET_MATCH(f);
4890 *match = 0;
4891 }
4892 f->child = RB_NEXT(pf_keth_anchor_node,
4893 &fr->anchor->children, f->child);
4894 if (f->child != NULL) {
4895 *rs = &f->child->ruleset;
4896 *r = TAILQ_FIRST((*rs)->active.rules);
4897 if (*r == NULL)
4898 continue;
4899 else
4900 break;
4901 }
4902 }
4903 (*depth)--;
4904 if (*depth == 0 && a != NULL)
4905 *a = NULL;
4906 *rs = f->rs;
4907 if (PF_ETH_ANCHOR_MATCH(f) || (match != NULL && *match))
4908 quick = fr->quick;
4909 *r = TAILQ_NEXT(fr, entries);
4910 } while (*r == NULL);
4911
4912 return (quick);
4913 }
4914
4915 void
pf_poolmask(struct pf_addr * naddr,struct pf_addr * raddr,struct pf_addr * rmask,struct pf_addr * saddr,sa_family_t af)4916 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
4917 struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
4918 {
4919 switch (af) {
4920 #ifdef INET
4921 case AF_INET:
4922 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
4923 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
4924 break;
4925 #endif /* INET */
4926 #ifdef INET6
4927 case AF_INET6:
4928 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
4929 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
4930 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
4931 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
4932 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
4933 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
4934 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
4935 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
4936 break;
4937 #endif /* INET6 */
4938 }
4939 }
4940
4941 void
pf_addr_inc(struct pf_addr * addr,sa_family_t af)4942 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
4943 {
4944 switch (af) {
4945 #ifdef INET
4946 case AF_INET:
4947 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
4948 break;
4949 #endif /* INET */
4950 #ifdef INET6
4951 case AF_INET6:
4952 if (addr->addr32[3] == 0xffffffff) {
4953 addr->addr32[3] = 0;
4954 if (addr->addr32[2] == 0xffffffff) {
4955 addr->addr32[2] = 0;
4956 if (addr->addr32[1] == 0xffffffff) {
4957 addr->addr32[1] = 0;
4958 addr->addr32[0] =
4959 htonl(ntohl(addr->addr32[0]) + 1);
4960 } else
4961 addr->addr32[1] =
4962 htonl(ntohl(addr->addr32[1]) + 1);
4963 } else
4964 addr->addr32[2] =
4965 htonl(ntohl(addr->addr32[2]) + 1);
4966 } else
4967 addr->addr32[3] =
4968 htonl(ntohl(addr->addr32[3]) + 1);
4969 break;
4970 #endif /* INET6 */
4971 }
4972 }
4973
4974 void
pf_rule_to_actions(struct pf_krule * r,struct pf_rule_actions * a)4975 pf_rule_to_actions(struct pf_krule *r, struct pf_rule_actions *a)
4976 {
4977 /*
4978 * Modern rules use the same flags in rules as they do in states.
4979 */
4980 a->flags |= (r->scrub_flags & (PFSTATE_NODF|PFSTATE_RANDOMID|
4981 PFSTATE_SCRUB_TCP|PFSTATE_SETPRIO));
4982
4983 /*
4984 * Old-style scrub rules have different flags which need to be translated.
4985 */
4986 if (r->rule_flag & PFRULE_RANDOMID)
4987 a->flags |= PFSTATE_RANDOMID;
4988 if (r->scrub_flags & PFSTATE_SETTOS || r->rule_flag & PFRULE_SET_TOS ) {
4989 a->flags |= PFSTATE_SETTOS;
4990 a->set_tos = r->set_tos;
4991 }
4992
4993 if (r->qid)
4994 a->qid = r->qid;
4995 if (r->pqid)
4996 a->pqid = r->pqid;
4997 if (r->rtableid >= 0)
4998 a->rtableid = r->rtableid;
4999 a->log |= r->log;
5000 if (r->min_ttl)
5001 a->min_ttl = r->min_ttl;
5002 if (r->max_mss)
5003 a->max_mss = r->max_mss;
5004 if (r->dnpipe)
5005 a->dnpipe = r->dnpipe;
5006 if (r->dnrpipe)
5007 a->dnrpipe = r->dnrpipe;
5008 if (r->dnpipe || r->dnrpipe) {
5009 if (r->free_flags & PFRULE_DN_IS_PIPE)
5010 a->flags |= PFSTATE_DN_IS_PIPE;
5011 else
5012 a->flags &= ~PFSTATE_DN_IS_PIPE;
5013 }
5014 if (r->scrub_flags & PFSTATE_SETPRIO) {
5015 a->set_prio[0] = r->set_prio[0];
5016 a->set_prio[1] = r->set_prio[1];
5017 }
5018 if (r->allow_opts)
5019 a->allow_opts = r->allow_opts;
5020 if (r->max_pkt_size)
5021 a->max_pkt_size = r->max_pkt_size;
5022 }
5023
5024 int
pf_socket_lookup(struct pf_pdesc * pd)5025 pf_socket_lookup(struct pf_pdesc *pd)
5026 {
5027 struct pf_addr *saddr, *daddr;
5028 u_int16_t sport, dport;
5029 struct inpcbinfo *pi;
5030 struct inpcb *inp;
5031
5032 pd->lookup.uid = -1;
5033 pd->lookup.gid = -1;
5034
5035 switch (pd->proto) {
5036 case IPPROTO_TCP:
5037 sport = pd->hdr.tcp.th_sport;
5038 dport = pd->hdr.tcp.th_dport;
5039 pi = &V_tcbinfo;
5040 break;
5041 case IPPROTO_UDP:
5042 sport = pd->hdr.udp.uh_sport;
5043 dport = pd->hdr.udp.uh_dport;
5044 pi = &V_udbinfo;
5045 break;
5046 default:
5047 return (-1);
5048 }
5049 if (pd->dir == PF_IN) {
5050 saddr = pd->src;
5051 daddr = pd->dst;
5052 } else {
5053 u_int16_t p;
5054
5055 p = sport;
5056 sport = dport;
5057 dport = p;
5058 saddr = pd->dst;
5059 daddr = pd->src;
5060 }
5061 switch (pd->af) {
5062 #ifdef INET
5063 case AF_INET:
5064 inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
5065 dport, INPLOOKUP_RLOCKPCB, NULL, pd->m);
5066 if (inp == NULL) {
5067 inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
5068 daddr->v4, dport, INPLOOKUP_WILDCARD |
5069 INPLOOKUP_RLOCKPCB, NULL, pd->m);
5070 if (inp == NULL)
5071 return (-1);
5072 }
5073 break;
5074 #endif /* INET */
5075 #ifdef INET6
5076 case AF_INET6:
5077 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
5078 dport, INPLOOKUP_RLOCKPCB, NULL, pd->m);
5079 if (inp == NULL) {
5080 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
5081 &daddr->v6, dport, INPLOOKUP_WILDCARD |
5082 INPLOOKUP_RLOCKPCB, NULL, pd->m);
5083 if (inp == NULL)
5084 return (-1);
5085 }
5086 break;
5087 #endif /* INET6 */
5088 default:
5089 unhandled_af(pd->af);
5090 }
5091 INP_RLOCK_ASSERT(inp);
5092 pd->lookup.uid = inp->inp_cred->cr_uid;
5093 pd->lookup.gid = inp->inp_cred->cr_gid;
5094 INP_RUNLOCK(inp);
5095
5096 return (1);
5097 }
5098
5099 /* post: r => (r[0] == type /\ r[1] >= min_typelen >= 2 "validity"
5100 * /\ (eoh - r) >= min_typelen >= 2 "safety" )
5101 *
5102 * warning: r + r[1] may exceed opts bounds for r[1] > min_typelen
5103 */
5104 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)5105 pf_find_tcpopt(u_int8_t *opt, u_int8_t *opts, size_t hlen, u_int8_t type,
5106 u_int8_t min_typelen)
5107 {
5108 uint8_t *eoh = opts + hlen;
5109
5110 if (min_typelen < 2)
5111 return (NULL);
5112
5113 while ((eoh - opt) >= min_typelen) {
5114 switch (*opt) {
5115 case TCPOPT_EOL:
5116 /* FALLTHROUGH - Workaround the failure of some
5117 systems to NOP-pad their bzero'd option buffers,
5118 producing spurious EOLs */
5119 case TCPOPT_NOP:
5120 opt++;
5121 continue;
5122 default:
5123 if (opt[0] == type &&
5124 opt[1] >= min_typelen)
5125 return (opt);
5126 }
5127
5128 opt += MAX(opt[1], 2); /* evade infinite loops */
5129 }
5130
5131 return (NULL);
5132 }
5133
5134 u_int8_t
pf_get_wscale(struct pf_pdesc * pd)5135 pf_get_wscale(struct pf_pdesc *pd)
5136 {
5137 int olen;
5138 uint8_t opts[MAX_TCPOPTLEN], *opt;
5139 uint8_t wscale = 0;
5140
5141 olen = (pd->hdr.tcp.th_off << 2) - sizeof(struct tcphdr);
5142 if (olen < TCPOLEN_WINDOW || !pf_pull_hdr(pd->m,
5143 pd->off + sizeof(struct tcphdr), opts, olen, NULL, pd->af))
5144 return (0);
5145
5146 opt = opts;
5147 while ((opt = pf_find_tcpopt(opt, opts, olen,
5148 TCPOPT_WINDOW, TCPOLEN_WINDOW)) != NULL) {
5149 wscale = opt[2];
5150 wscale = MIN(wscale, TCP_MAX_WINSHIFT);
5151 wscale |= PF_WSCALE_FLAG;
5152
5153 opt += opt[1];
5154 }
5155
5156 return (wscale);
5157 }
5158
5159 u_int16_t
pf_get_mss(struct pf_pdesc * pd)5160 pf_get_mss(struct pf_pdesc *pd)
5161 {
5162 int olen;
5163 uint8_t opts[MAX_TCPOPTLEN], *opt;
5164 u_int16_t mss = V_tcp_mssdflt;
5165
5166 olen = (pd->hdr.tcp.th_off << 2) - sizeof(struct tcphdr);
5167 if (olen < TCPOLEN_MAXSEG || !pf_pull_hdr(pd->m,
5168 pd->off + sizeof(struct tcphdr), opts, olen, NULL, pd->af))
5169 return (0);
5170
5171 opt = opts;
5172 while ((opt = pf_find_tcpopt(opt, opts, olen,
5173 TCPOPT_MAXSEG, TCPOLEN_MAXSEG)) != NULL) {
5174 memcpy(&mss, (opt + 2), 2);
5175 mss = ntohs(mss);
5176 opt += opt[1];
5177 }
5178
5179 return (mss);
5180 }
5181
5182 static u_int16_t
pf_calc_mss(struct pf_addr * addr,sa_family_t af,int rtableid,u_int16_t offer)5183 pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
5184 {
5185 struct nhop_object *nh;
5186 #ifdef INET6
5187 struct in6_addr dst6;
5188 uint32_t scopeid;
5189 #endif /* INET6 */
5190 int hlen = 0;
5191 uint16_t mss = 0;
5192
5193 NET_EPOCH_ASSERT();
5194
5195 switch (af) {
5196 #ifdef INET
5197 case AF_INET:
5198 hlen = sizeof(struct ip);
5199 nh = fib4_lookup(rtableid, addr->v4, 0, 0, 0);
5200 if (nh != NULL)
5201 mss = nh->nh_mtu - hlen - sizeof(struct tcphdr);
5202 break;
5203 #endif /* INET */
5204 #ifdef INET6
5205 case AF_INET6:
5206 hlen = sizeof(struct ip6_hdr);
5207 in6_splitscope(&addr->v6, &dst6, &scopeid);
5208 nh = fib6_lookup(rtableid, &dst6, scopeid, 0, 0);
5209 if (nh != NULL)
5210 mss = nh->nh_mtu - hlen - sizeof(struct tcphdr);
5211 break;
5212 #endif /* INET6 */
5213 }
5214
5215 mss = max(V_tcp_mssdflt, mss);
5216 mss = min(mss, offer);
5217 mss = max(mss, 64); /* sanity - at least max opt space */
5218 return (mss);
5219 }
5220
5221 static u_int32_t
pf_tcp_iss(struct pf_pdesc * pd)5222 pf_tcp_iss(struct pf_pdesc *pd)
5223 {
5224 SHA512_CTX ctx;
5225 union {
5226 uint8_t bytes[SHA512_DIGEST_LENGTH];
5227 uint32_t words[1];
5228 } digest;
5229
5230 if (V_pf_tcp_secret_init == 0) {
5231 arc4random_buf(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
5232 SHA512_Init(&V_pf_tcp_secret_ctx);
5233 SHA512_Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
5234 sizeof(V_pf_tcp_secret));
5235 V_pf_tcp_secret_init = 1;
5236 }
5237
5238 ctx = V_pf_tcp_secret_ctx;
5239
5240 SHA512_Update(&ctx, &pd->hdr.tcp.th_sport, sizeof(u_short));
5241 SHA512_Update(&ctx, &pd->hdr.tcp.th_dport, sizeof(u_short));
5242 switch (pd->af) {
5243 case AF_INET6:
5244 SHA512_Update(&ctx, &pd->src->v6, sizeof(struct in6_addr));
5245 SHA512_Update(&ctx, &pd->dst->v6, sizeof(struct in6_addr));
5246 break;
5247 case AF_INET:
5248 SHA512_Update(&ctx, &pd->src->v4, sizeof(struct in_addr));
5249 SHA512_Update(&ctx, &pd->dst->v4, sizeof(struct in_addr));
5250 break;
5251 }
5252 SHA512_Final(digest.bytes, &ctx);
5253 V_pf_tcp_iss_off += 4096;
5254 #define ISN_RANDOM_INCREMENT (4096 - 1)
5255 return (digest.words[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
5256 V_pf_tcp_iss_off);
5257 #undef ISN_RANDOM_INCREMENT
5258 }
5259
5260 static bool
pf_match_eth_addr(const uint8_t * a,const struct pf_keth_rule_addr * r)5261 pf_match_eth_addr(const uint8_t *a, const struct pf_keth_rule_addr *r)
5262 {
5263 bool match = true;
5264
5265 /* Always matches if not set */
5266 if (! r->isset)
5267 return (!r->neg);
5268
5269 for (int i = 0; i < ETHER_ADDR_LEN; i++) {
5270 if ((a[i] & r->mask[i]) != (r->addr[i] & r->mask[i])) {
5271 match = false;
5272 break;
5273 }
5274 }
5275
5276 return (match ^ r->neg);
5277 }
5278
5279 static int
pf_match_eth_tag(struct mbuf * m,struct pf_keth_rule * r,int * tag,int mtag)5280 pf_match_eth_tag(struct mbuf *m, struct pf_keth_rule *r, int *tag, int mtag)
5281 {
5282 if (*tag == -1)
5283 *tag = mtag;
5284
5285 return ((!r->match_tag_not && r->match_tag == *tag) ||
5286 (r->match_tag_not && r->match_tag != *tag));
5287 }
5288
5289 static void
pf_bridge_to(struct ifnet * ifp,struct mbuf * m)5290 pf_bridge_to(struct ifnet *ifp, struct mbuf *m)
5291 {
5292 /* If we don't have the interface drop the packet. */
5293 if (ifp == NULL) {
5294 m_freem(m);
5295 return;
5296 }
5297
5298 switch (ifp->if_type) {
5299 case IFT_ETHER:
5300 case IFT_XETHER:
5301 case IFT_L2VLAN:
5302 case IFT_BRIDGE:
5303 case IFT_IEEE8023ADLAG:
5304 break;
5305 default:
5306 m_freem(m);
5307 return;
5308 }
5309
5310 ifp->if_transmit(ifp, m);
5311 }
5312
5313 static int
pf_test_eth_rule(int dir,struct pfi_kkif * kif,struct mbuf ** m0)5314 pf_test_eth_rule(int dir, struct pfi_kkif *kif, struct mbuf **m0)
5315 {
5316 #ifdef INET
5317 struct ip ip;
5318 #endif /* INET */
5319 #ifdef INET6
5320 struct ip6_hdr ip6;
5321 #endif /* INET6 */
5322 struct mbuf *m = *m0;
5323 struct ether_header *e;
5324 struct pf_keth_rule *r, *rm, *a = NULL;
5325 struct pf_keth_ruleset *ruleset = NULL;
5326 struct pf_mtag *mtag;
5327 struct pf_keth_ruleq *rules;
5328 struct pf_addr *src = NULL, *dst = NULL;
5329 struct pfi_kkif *bridge_to;
5330 sa_family_t af = 0;
5331 uint16_t proto;
5332 int asd = 0, match = 0;
5333 int tag = -1;
5334 uint8_t action;
5335 struct pf_keth_anchor_stackframe anchor_stack[PF_ANCHOR_STACK_MAX];
5336
5337 MPASS(kif->pfik_ifp->if_vnet == curvnet);
5338 NET_EPOCH_ASSERT();
5339
5340 PF_RULES_RLOCK_TRACKER;
5341
5342 SDT_PROBE3(pf, eth, test_rule, entry, dir, kif->pfik_ifp, m);
5343
5344 mtag = pf_find_mtag(m);
5345 if (mtag != NULL && mtag->flags & PF_MTAG_FLAG_DUMMYNET) {
5346 /* Dummynet re-injects packets after they've
5347 * completed their delay. We've already
5348 * processed them, so pass unconditionally. */
5349
5350 /* But only once. We may see the packet multiple times (e.g.
5351 * PFIL_IN/PFIL_OUT). */
5352 pf_dummynet_flag_remove(m, mtag);
5353
5354 return (PF_PASS);
5355 }
5356
5357 if (__predict_false(m->m_len < sizeof(struct ether_header)) &&
5358 (m = *m0 = m_pullup(*m0, sizeof(struct ether_header))) == NULL) {
5359 DPFPRINTF(PF_DEBUG_URGENT,
5360 "%s: m_len < sizeof(struct ether_header)"
5361 ", pullup failed", __func__);
5362 return (PF_DROP);
5363 }
5364 e = mtod(m, struct ether_header *);
5365 proto = ntohs(e->ether_type);
5366
5367 switch (proto) {
5368 #ifdef INET
5369 case ETHERTYPE_IP: {
5370 if (m_length(m, NULL) < (sizeof(struct ether_header) +
5371 sizeof(ip)))
5372 return (PF_DROP);
5373
5374 af = AF_INET;
5375 m_copydata(m, sizeof(struct ether_header), sizeof(ip),
5376 (caddr_t)&ip);
5377 src = (struct pf_addr *)&ip.ip_src;
5378 dst = (struct pf_addr *)&ip.ip_dst;
5379 break;
5380 }
5381 #endif /* INET */
5382 #ifdef INET6
5383 case ETHERTYPE_IPV6: {
5384 if (m_length(m, NULL) < (sizeof(struct ether_header) +
5385 sizeof(ip6)))
5386 return (PF_DROP);
5387
5388 af = AF_INET6;
5389 m_copydata(m, sizeof(struct ether_header), sizeof(ip6),
5390 (caddr_t)&ip6);
5391 src = (struct pf_addr *)&ip6.ip6_src;
5392 dst = (struct pf_addr *)&ip6.ip6_dst;
5393 break;
5394 }
5395 #endif /* INET6 */
5396 }
5397
5398 PF_RULES_RLOCK();
5399
5400 ruleset = V_pf_keth;
5401 rules = atomic_load_ptr(&ruleset->active.rules);
5402 for (r = TAILQ_FIRST(rules), rm = NULL; r != NULL;) {
5403 counter_u64_add(r->evaluations, 1);
5404 SDT_PROBE2(pf, eth, test_rule, test, r->nr, r);
5405
5406 if (pfi_kkif_match(r->kif, kif) == r->ifnot) {
5407 SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
5408 "kif");
5409 r = r->skip[PFE_SKIP_IFP].ptr;
5410 }
5411 else if (r->direction && r->direction != dir) {
5412 SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
5413 "dir");
5414 r = r->skip[PFE_SKIP_DIR].ptr;
5415 }
5416 else if (r->proto && r->proto != proto) {
5417 SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
5418 "proto");
5419 r = r->skip[PFE_SKIP_PROTO].ptr;
5420 }
5421 else if (! pf_match_eth_addr(e->ether_shost, &r->src)) {
5422 SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
5423 "src");
5424 r = r->skip[PFE_SKIP_SRC_ADDR].ptr;
5425 }
5426 else if (! pf_match_eth_addr(e->ether_dhost, &r->dst)) {
5427 SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
5428 "dst");
5429 r = r->skip[PFE_SKIP_DST_ADDR].ptr;
5430 }
5431 else if (src != NULL && PF_MISMATCHAW(&r->ipsrc.addr, src, af,
5432 r->ipsrc.neg, kif, M_GETFIB(m))) {
5433 SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
5434 "ip_src");
5435 r = r->skip[PFE_SKIP_SRC_IP_ADDR].ptr;
5436 }
5437 else if (dst != NULL && PF_MISMATCHAW(&r->ipdst.addr, dst, af,
5438 r->ipdst.neg, kif, M_GETFIB(m))) {
5439 SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
5440 "ip_dst");
5441 r = r->skip[PFE_SKIP_DST_IP_ADDR].ptr;
5442 }
5443 else if (r->match_tag && !pf_match_eth_tag(m, r, &tag,
5444 mtag ? mtag->tag : 0)) {
5445 SDT_PROBE3(pf, eth, test_rule, mismatch, r->nr, r,
5446 "match_tag");
5447 r = TAILQ_NEXT(r, entries);
5448 }
5449 else {
5450 if (r->tag)
5451 tag = r->tag;
5452 if (r->anchor == NULL) {
5453 /* Rule matches */
5454 rm = r;
5455
5456 SDT_PROBE2(pf, eth, test_rule, match, r->nr, r);
5457
5458 if (r->quick)
5459 break;
5460
5461 r = TAILQ_NEXT(r, entries);
5462 } else {
5463 pf_step_into_keth_anchor(anchor_stack, &asd,
5464 &ruleset, &r, &a, &match);
5465 }
5466 }
5467 if (r == NULL && pf_step_out_of_keth_anchor(anchor_stack, &asd,
5468 &ruleset, &r, &a, &match))
5469 break;
5470 }
5471
5472 r = rm;
5473
5474 SDT_PROBE2(pf, eth, test_rule, final_match, (r != NULL ? r->nr : -1), r);
5475
5476 /* Default to pass. */
5477 if (r == NULL) {
5478 PF_RULES_RUNLOCK();
5479 return (PF_PASS);
5480 }
5481
5482 /* Execute action. */
5483 counter_u64_add(r->packets[dir == PF_OUT], 1);
5484 counter_u64_add(r->bytes[dir == PF_OUT], m_length(m, NULL));
5485 pf_update_timestamp(r);
5486
5487 /* Shortcut. Don't tag if we're just going to drop anyway. */
5488 if (r->action == PF_DROP) {
5489 PF_RULES_RUNLOCK();
5490 return (PF_DROP);
5491 }
5492
5493 if (tag > 0) {
5494 if (mtag == NULL)
5495 mtag = pf_get_mtag(m);
5496 if (mtag == NULL) {
5497 PF_RULES_RUNLOCK();
5498 counter_u64_add(V_pf_status.counters[PFRES_MEMORY], 1);
5499 return (PF_DROP);
5500 }
5501 mtag->tag = tag;
5502 }
5503
5504 if (r->qid != 0) {
5505 if (mtag == NULL)
5506 mtag = pf_get_mtag(m);
5507 if (mtag == NULL) {
5508 PF_RULES_RUNLOCK();
5509 counter_u64_add(V_pf_status.counters[PFRES_MEMORY], 1);
5510 return (PF_DROP);
5511 }
5512 mtag->qid = r->qid;
5513 }
5514
5515 action = r->action;
5516 bridge_to = r->bridge_to;
5517
5518 /* Dummynet */
5519 if (r->dnpipe) {
5520 struct ip_fw_args dnflow;
5521
5522 /* Drop packet if dummynet is not loaded. */
5523 if (ip_dn_io_ptr == NULL) {
5524 PF_RULES_RUNLOCK();
5525 m_freem(m);
5526 counter_u64_add(V_pf_status.counters[PFRES_MEMORY], 1);
5527 return (PF_DROP);
5528 }
5529 if (mtag == NULL)
5530 mtag = pf_get_mtag(m);
5531 if (mtag == NULL) {
5532 PF_RULES_RUNLOCK();
5533 counter_u64_add(V_pf_status.counters[PFRES_MEMORY], 1);
5534 return (PF_DROP);
5535 }
5536
5537 bzero(&dnflow, sizeof(dnflow));
5538
5539 /* We don't have port numbers here, so we set 0. That means
5540 * that we'll be somewhat limited in distinguishing flows (i.e.
5541 * only based on IP addresses, not based on port numbers), but
5542 * it's better than nothing. */
5543 dnflow.f_id.dst_port = 0;
5544 dnflow.f_id.src_port = 0;
5545 dnflow.f_id.proto = 0;
5546
5547 dnflow.rule.info = r->dnpipe;
5548 dnflow.rule.info |= IPFW_IS_DUMMYNET;
5549 if (r->dnflags & PFRULE_DN_IS_PIPE)
5550 dnflow.rule.info |= IPFW_IS_PIPE;
5551
5552 dnflow.f_id.extra = dnflow.rule.info;
5553
5554 dnflow.flags = dir == PF_IN ? IPFW_ARGS_IN : IPFW_ARGS_OUT;
5555 dnflow.flags |= IPFW_ARGS_ETHER;
5556 dnflow.ifp = kif->pfik_ifp;
5557
5558 switch (af) {
5559 case AF_INET:
5560 dnflow.f_id.addr_type = 4;
5561 dnflow.f_id.src_ip = src->v4.s_addr;
5562 dnflow.f_id.dst_ip = dst->v4.s_addr;
5563 break;
5564 case AF_INET6:
5565 dnflow.flags |= IPFW_ARGS_IP6;
5566 dnflow.f_id.addr_type = 6;
5567 dnflow.f_id.src_ip6 = src->v6;
5568 dnflow.f_id.dst_ip6 = dst->v6;
5569 break;
5570 }
5571
5572 PF_RULES_RUNLOCK();
5573
5574 mtag->flags |= PF_MTAG_FLAG_DUMMYNET;
5575 ip_dn_io_ptr(m0, &dnflow);
5576 if (*m0 != NULL)
5577 pf_dummynet_flag_remove(m, mtag);
5578 } else {
5579 PF_RULES_RUNLOCK();
5580 }
5581
5582 if (action == PF_PASS && bridge_to) {
5583 pf_bridge_to(bridge_to->pfik_ifp, *m0);
5584 *m0 = NULL; /* We've eaten the packet. */
5585 }
5586
5587 return (action);
5588 }
5589
5590 #define PF_TEST_ATTRIB(t, a) \
5591 if (t) { \
5592 r = a; \
5593 continue; \
5594 } else do { \
5595 } while (0)
5596
5597 static __inline u_short
pf_rule_apply_nat(struct pf_test_ctx * ctx,struct pf_krule * r)5598 pf_rule_apply_nat(struct pf_test_ctx *ctx, struct pf_krule *r)
5599 {
5600 struct pf_pdesc *pd = ctx->pd;
5601 u_short transerror;
5602 u_int8_t nat_action;
5603
5604 if (r->rule_flag & PFRULE_AFTO) {
5605 /* Don't translate if there was an old style NAT rule */
5606 if (ctx->nr != NULL)
5607 return (PFRES_TRANSLATE);
5608
5609 /* pass af-to rules, unsupported on match rules */
5610 KASSERT(r->action != PF_MATCH, ("%s: af-to on match rule", __func__));
5611 /* XXX I can imagine scenarios where we have both NAT and RDR source tracking */
5612 ctx->nat_pool = &(r->nat);
5613 ctx->nr = r;
5614 pd->naf = r->naf;
5615 if (pf_get_transaddr_af(ctx->nr, pd) == -1) {
5616 return (PFRES_TRANSLATE);
5617 }
5618 return (PFRES_MATCH);
5619 } else if (r->rdr.cur || r->nat.cur) {
5620 /* Don't translate if there was an old style NAT rule */
5621 if (ctx->nr != NULL)
5622 return (PFRES_TRANSLATE);
5623
5624 /* match/pass nat-to/rdr-to rules */
5625 ctx->nr = r;
5626 if (r->nat.cur) {
5627 nat_action = PF_NAT;
5628 ctx->nat_pool = &(r->nat);
5629 } else {
5630 nat_action = PF_RDR;
5631 ctx->nat_pool = &(r->rdr);
5632 }
5633
5634 transerror = pf_get_transaddr(ctx, ctx->nr,
5635 nat_action, ctx->nat_pool);
5636 if (transerror == PFRES_MATCH) {
5637 ctx->rewrite += pf_translate_compat(ctx);
5638 return(PFRES_MATCH);
5639 }
5640 return (transerror);
5641 }
5642
5643 return (PFRES_MAX);
5644 }
5645
5646 enum pf_test_status
pf_match_rule(struct pf_test_ctx * ctx,struct pf_kruleset * ruleset,struct pf_krule_slist * match_rules)5647 pf_match_rule(struct pf_test_ctx *ctx, struct pf_kruleset *ruleset,
5648 struct pf_krule_slist *match_rules)
5649 {
5650 struct pf_krule_item *ri, *rt;
5651 struct pf_krule *r;
5652 struct pf_krule *save_a;
5653 struct pf_kruleset *save_aruleset;
5654 struct pf_pdesc *pd = ctx->pd;
5655 u_short transerror;
5656
5657 r = TAILQ_FIRST(ruleset->rules[PF_RULESET_FILTER].active.ptr);
5658 while (r != NULL) {
5659 if (ctx->pd->related_rule) {
5660 *ctx->rm = ctx->pd->related_rule;
5661 break;
5662 }
5663 PF_TEST_ATTRIB(r->rule_flag & PFRULE_EXPIRED,
5664 TAILQ_NEXT(r, entries));
5665 /* Don't count expired rule evaluations. */
5666 pf_counter_u64_add(&r->evaluations, 1);
5667 PF_TEST_ATTRIB(pfi_kkif_match(r->kif, pd->kif) == r->ifnot,
5668 r->skip[PF_SKIP_IFP]);
5669 PF_TEST_ATTRIB(r->direction && r->direction != pd->dir,
5670 r->skip[PF_SKIP_DIR]);
5671 PF_TEST_ATTRIB(r->af && r->af != pd->af,
5672 r->skip[PF_SKIP_AF]);
5673 PF_TEST_ATTRIB(r->proto && r->proto != pd->proto,
5674 r->skip[PF_SKIP_PROTO]);
5675 PF_TEST_ATTRIB(PF_MISMATCHAW(&r->src.addr, &pd->nsaddr, pd->naf,
5676 r->src.neg, pd->kif, M_GETFIB(pd->m)),
5677 r->skip[PF_SKIP_SRC_ADDR]);
5678 PF_TEST_ATTRIB(PF_MISMATCHAW(&r->dst.addr, &pd->ndaddr, pd->af,
5679 r->dst.neg, NULL, M_GETFIB(pd->m)),
5680 r->skip[PF_SKIP_DST_ADDR]);
5681 switch (pd->virtual_proto) {
5682 case PF_VPROTO_FRAGMENT:
5683 /* tcp/udp only. port_op always 0 in other cases */
5684 PF_TEST_ATTRIB((r->src.port_op || r->dst.port_op),
5685 TAILQ_NEXT(r, entries));
5686 PF_TEST_ATTRIB((pd->proto == IPPROTO_TCP && r->flagset),
5687 TAILQ_NEXT(r, entries));
5688 /* icmp only. type/code always 0 in other cases */
5689 PF_TEST_ATTRIB((r->type || r->code),
5690 TAILQ_NEXT(r, entries));
5691 /* tcp/udp only. {uid|gid}.op always 0 in other cases */
5692 PF_TEST_ATTRIB((r->gid.op || r->uid.op),
5693 TAILQ_NEXT(r, entries));
5694 break;
5695
5696 case IPPROTO_TCP:
5697 PF_TEST_ATTRIB((r->flagset & tcp_get_flags(ctx->th))
5698 != r->flags,
5699 TAILQ_NEXT(r, entries));
5700 /* FALLTHROUGH */
5701 case IPPROTO_SCTP:
5702 case IPPROTO_UDP:
5703 /* tcp/udp only. port_op always 0 in other cases */
5704 PF_TEST_ATTRIB(r->src.port_op && !pf_match_port(r->src.port_op,
5705 r->src.port[0], r->src.port[1], pd->nsport),
5706 r->skip[PF_SKIP_SRC_PORT]);
5707 /* tcp/udp only. port_op always 0 in other cases */
5708 PF_TEST_ATTRIB(r->dst.port_op && !pf_match_port(r->dst.port_op,
5709 r->dst.port[0], r->dst.port[1], pd->ndport),
5710 r->skip[PF_SKIP_DST_PORT]);
5711 /* tcp/udp only. uid.op always 0 in other cases */
5712 PF_TEST_ATTRIB(r->uid.op && (pd->lookup.done || (pd->lookup.done =
5713 pf_socket_lookup(pd), 1)) &&
5714 !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
5715 pd->lookup.uid),
5716 TAILQ_NEXT(r, entries));
5717 /* tcp/udp only. gid.op always 0 in other cases */
5718 PF_TEST_ATTRIB(r->gid.op && (pd->lookup.done || (pd->lookup.done =
5719 pf_socket_lookup(pd), 1)) &&
5720 !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
5721 pd->lookup.gid),
5722 TAILQ_NEXT(r, entries));
5723 break;
5724
5725 case IPPROTO_ICMP:
5726 case IPPROTO_ICMPV6:
5727 /* icmp only. type always 0 in other cases */
5728 PF_TEST_ATTRIB(r->type && r->type != ctx->icmptype + 1,
5729 TAILQ_NEXT(r, entries));
5730 /* icmp only. type always 0 in other cases */
5731 PF_TEST_ATTRIB(r->code && r->code != ctx->icmpcode + 1,
5732 TAILQ_NEXT(r, entries));
5733 break;
5734
5735 default:
5736 break;
5737 }
5738 PF_TEST_ATTRIB(r->tos && !(r->tos == pd->tos),
5739 TAILQ_NEXT(r, entries));
5740 PF_TEST_ATTRIB(r->prio &&
5741 !pf_match_ieee8021q_pcp(r->prio, pd->m),
5742 TAILQ_NEXT(r, entries));
5743 PF_TEST_ATTRIB(r->prob &&
5744 r->prob <= arc4random(),
5745 TAILQ_NEXT(r, entries));
5746 PF_TEST_ATTRIB(r->match_tag && !pf_match_tag(pd->m, r,
5747 &ctx->tag, pd->pf_mtag ? pd->pf_mtag->tag : 0),
5748 TAILQ_NEXT(r, entries));
5749 PF_TEST_ATTRIB((r->rcv_kif && pf_match_rcvif(pd->m, r) ==
5750 r->rcvifnot),
5751 TAILQ_NEXT(r, entries));
5752 PF_TEST_ATTRIB((r->rule_flag & PFRULE_FRAGMENT &&
5753 pd->virtual_proto != PF_VPROTO_FRAGMENT),
5754 TAILQ_NEXT(r, entries));
5755 PF_TEST_ATTRIB(r->os_fingerprint != PF_OSFP_ANY &&
5756 (pd->virtual_proto != IPPROTO_TCP || !pf_osfp_match(
5757 pf_osfp_fingerprint(pd, ctx->th),
5758 r->os_fingerprint)),
5759 TAILQ_NEXT(r, entries));
5760 /* must be last! */
5761 if (r->pktrate.limit) {
5762 PF_TEST_ATTRIB((pf_check_threshold(&r->pktrate)),
5763 TAILQ_NEXT(r, entries));
5764 }
5765 /* FALLTHROUGH */
5766 if (r->tag)
5767 ctx->tag = r->tag;
5768 if (r->anchor == NULL) {
5769
5770 if (r->rule_flag & PFRULE_ONCE) {
5771 uint32_t rule_flag;
5772
5773 rule_flag = r->rule_flag;
5774 if ((rule_flag & PFRULE_EXPIRED) == 0 &&
5775 atomic_cmpset_int(&r->rule_flag, rule_flag,
5776 rule_flag | PFRULE_EXPIRED)) {
5777 r->exptime = time_uptime;
5778 } else {
5779 r = TAILQ_NEXT(r, entries);
5780 continue;
5781 }
5782 }
5783
5784 if (r->action == PF_MATCH) {
5785 /*
5786 * Apply translations before increasing counters,
5787 * in case it fails.
5788 */
5789 transerror = pf_rule_apply_nat(ctx, r);
5790 switch (transerror) {
5791 case PFRES_MATCH:
5792 /* Translation action found in rule and applied successfully */
5793 case PFRES_MAX:
5794 /* No translation action found in rule */
5795 break;
5796 default:
5797 /* Translation action found in rule but failed to apply */
5798 REASON_SET(&ctx->reason, transerror);
5799 return (PF_TEST_FAIL);
5800 }
5801 ri = malloc(sizeof(struct pf_krule_item), M_PF_RULE_ITEM, M_NOWAIT | M_ZERO);
5802 if (ri == NULL) {
5803 REASON_SET(&ctx->reason, PFRES_MEMORY);
5804 return (PF_TEST_FAIL);
5805 }
5806 ri->r = r;
5807
5808 if (SLIST_EMPTY(match_rules)) {
5809 SLIST_INSERT_HEAD(match_rules, ri, entry);
5810 } else {
5811 SLIST_INSERT_AFTER(rt, ri, entry);
5812 }
5813 rt = ri;
5814
5815 pf_rule_to_actions(r, &pd->act);
5816 if (r->log)
5817 PFLOG_PACKET(r->action, PFRES_MATCH, r,
5818 ctx->a, ruleset, pd, 1, NULL);
5819 } else {
5820 /*
5821 * found matching r
5822 */
5823 *ctx->rm = r;
5824 /*
5825 * anchor, with ruleset, where r belongs to
5826 */
5827 *ctx->am = ctx->a;
5828 /*
5829 * ruleset where r belongs to
5830 */
5831 *ctx->rsm = ruleset;
5832 /*
5833 * ruleset, where anchor belongs to.
5834 */
5835 ctx->arsm = ctx->aruleset;
5836 }
5837 if (pd->act.log & PF_LOG_MATCHES)
5838 pf_log_matches(pd, r, ctx->a, ruleset, match_rules);
5839 if (r->quick) {
5840 ctx->test_status = PF_TEST_QUICK;
5841 break;
5842 }
5843 } else {
5844 save_a = ctx->a;
5845 save_aruleset = ctx->aruleset;
5846
5847 ctx->a = r; /* remember anchor */
5848 ctx->aruleset = ruleset; /* and its ruleset */
5849 if (ctx->a->quick)
5850 ctx->test_status = PF_TEST_QUICK;
5851 /*
5852 * Note: we don't need to restore if we are not going
5853 * to continue with ruleset evaluation.
5854 */
5855 if (pf_step_into_anchor(ctx, r, match_rules) != PF_TEST_OK) {
5856 break;
5857 }
5858 ctx->a = save_a;
5859 ctx->aruleset = save_aruleset;
5860 }
5861 r = TAILQ_NEXT(r, entries);
5862 }
5863
5864
5865 return (ctx->test_status);
5866 }
5867
5868 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)5869 pf_test_rule(struct pf_krule **rm, struct pf_kstate **sm,
5870 struct pf_pdesc *pd, struct pf_krule **am,
5871 struct pf_kruleset **rsm, u_short *reason, struct inpcb *inp,
5872 struct pf_krule_slist *match_rules)
5873 {
5874 struct pf_krule *r = NULL;
5875 struct pf_kruleset *ruleset = NULL;
5876 struct pf_test_ctx ctx;
5877 u_short transerror;
5878 int action = PF_PASS;
5879 u_int16_t bproto_sum = 0, bip_sum = 0;
5880 enum pf_test_status rv;
5881
5882 PF_RULES_RASSERT();
5883
5884 bzero(&ctx, sizeof(ctx));
5885 ctx.tag = -1;
5886 ctx.pd = pd;
5887 ctx.rm = rm;
5888 ctx.am = am;
5889 ctx.rsm = rsm;
5890 ctx.th = &pd->hdr.tcp;
5891 ctx.reason = *reason;
5892
5893 pf_addrcpy(&pd->nsaddr, pd->src, pd->af);
5894 pf_addrcpy(&pd->ndaddr, pd->dst, pd->af);
5895
5896 if (inp != NULL) {
5897 INP_LOCK_ASSERT(inp);
5898 pd->lookup.uid = inp->inp_cred->cr_uid;
5899 pd->lookup.gid = inp->inp_cred->cr_gid;
5900 pd->lookup.done = 1;
5901 }
5902
5903 if (pd->ip_sum)
5904 bip_sum = *pd->ip_sum;
5905
5906 switch (pd->virtual_proto) {
5907 case IPPROTO_TCP:
5908 bproto_sum = ctx.th->th_sum;
5909 pd->nsport = ctx.th->th_sport;
5910 pd->ndport = ctx.th->th_dport;
5911 break;
5912 case IPPROTO_UDP:
5913 bproto_sum = pd->hdr.udp.uh_sum;
5914 pd->nsport = pd->hdr.udp.uh_sport;
5915 pd->ndport = pd->hdr.udp.uh_dport;
5916 break;
5917 case IPPROTO_SCTP:
5918 pd->nsport = pd->hdr.sctp.src_port;
5919 pd->ndport = pd->hdr.sctp.dest_port;
5920 break;
5921 #ifdef INET
5922 case IPPROTO_ICMP:
5923 MPASS(pd->af == AF_INET);
5924 ctx.icmptype = pd->hdr.icmp.icmp_type;
5925 ctx.icmpcode = pd->hdr.icmp.icmp_code;
5926 ctx.state_icmp = pf_icmp_mapping(pd, ctx.icmptype,
5927 &ctx.icmp_dir, &ctx.virtual_id, &ctx.virtual_type);
5928 if (ctx.icmp_dir == PF_IN) {
5929 pd->nsport = ctx.virtual_id;
5930 pd->ndport = ctx.virtual_type;
5931 } else {
5932 pd->nsport = ctx.virtual_type;
5933 pd->ndport = ctx.virtual_id;
5934 }
5935 break;
5936 #endif /* INET */
5937 #ifdef INET6
5938 case IPPROTO_ICMPV6:
5939 MPASS(pd->af == AF_INET6);
5940 ctx.icmptype = pd->hdr.icmp6.icmp6_type;
5941 ctx.icmpcode = pd->hdr.icmp6.icmp6_code;
5942 ctx.state_icmp = pf_icmp_mapping(pd, ctx.icmptype,
5943 &ctx.icmp_dir, &ctx.virtual_id, &ctx.virtual_type);
5944 if (ctx.icmp_dir == PF_IN) {
5945 pd->nsport = ctx.virtual_id;
5946 pd->ndport = ctx.virtual_type;
5947 } else {
5948 pd->nsport = ctx.virtual_type;
5949 pd->ndport = ctx.virtual_id;
5950 }
5951
5952 break;
5953 #endif /* INET6 */
5954 default:
5955 pd->nsport = pd->ndport = 0;
5956 break;
5957 }
5958 pd->osport = pd->nsport;
5959 pd->odport = pd->ndport;
5960
5961 /* check packet for BINAT/NAT/RDR */
5962 transerror = pf_get_translation(&ctx);
5963 switch (transerror) {
5964 default:
5965 /* A translation error occurred. */
5966 REASON_SET(&ctx.reason, transerror);
5967 goto cleanup;
5968 case PFRES_MAX:
5969 /* No match. */
5970 break;
5971 case PFRES_MATCH:
5972 KASSERT(ctx.sk != NULL, ("%s: null sk", __func__));
5973 KASSERT(ctx.nk != NULL, ("%s: null nk", __func__));
5974 if (ctx.nr->log) {
5975 PFLOG_PACKET(ctx.nr->action, PFRES_MATCH, ctx.nr, ctx.a,
5976 ruleset, pd, 1, NULL);
5977 }
5978
5979 ctx.rewrite += pf_translate_compat(&ctx);
5980 ctx.nat_pool = &(ctx.nr->rdr);
5981 }
5982
5983 *ctx.rm = &V_pf_default_rule;
5984 if (ctx.nr && ctx.nr->natpass) {
5985 r = ctx.nr;
5986 ruleset = *ctx.rsm;
5987 } else {
5988 ruleset = &pf_main_ruleset;
5989 rv = pf_match_rule(&ctx, ruleset, match_rules);
5990 if (rv == PF_TEST_FAIL) {
5991 /*
5992 * Reason has been set in pf_match_rule() already.
5993 */
5994 goto cleanup;
5995 }
5996
5997 r = *ctx.rm; /* matching rule */
5998 ctx.a = *ctx.am; /* rule that defines an anchor containing 'r' */
5999 ruleset = *ctx.rsm; /* ruleset of the anchor defined by the rule 'a' */
6000 ctx.aruleset = ctx.arsm; /* ruleset of the 'a' rule itself */
6001
6002 /* apply actions for last matching pass/block rule */
6003 pf_rule_to_actions(r, &pd->act);
6004 transerror = pf_rule_apply_nat(&ctx, r);
6005 switch (transerror) {
6006 case PFRES_MATCH:
6007 /* Translation action found in rule and applied successfully */
6008 case PFRES_MAX:
6009 /* No translation action found in rule */
6010 break;
6011 default:
6012 /* Translation action found in rule but failed to apply */
6013 REASON_SET(&ctx.reason, transerror);
6014 goto cleanup;
6015 }
6016 }
6017
6018 REASON_SET(&ctx.reason, PFRES_MATCH);
6019
6020 if (r->log) {
6021 if (ctx.rewrite)
6022 m_copyback(pd->m, pd->off, pd->hdrlen, pd->hdr.any);
6023 PFLOG_PACKET(r->action, ctx.reason, r, ctx.a, ruleset, pd, 1, NULL);
6024 }
6025 if (pd->act.log & PF_LOG_MATCHES)
6026 pf_log_matches(pd, r, ctx.a, ruleset, match_rules);
6027 if (pd->virtual_proto != PF_VPROTO_FRAGMENT &&
6028 (r->action == PF_DROP) &&
6029 ((r->rule_flag & PFRULE_RETURNRST) ||
6030 (r->rule_flag & PFRULE_RETURNICMP) ||
6031 (r->rule_flag & PFRULE_RETURN))) {
6032 pf_return(r, ctx.nr, pd, ctx.th, bproto_sum,
6033 bip_sum, &ctx.reason, r->rtableid);
6034 }
6035
6036 if (r->action == PF_DROP)
6037 goto cleanup;
6038
6039 if (ctx.tag > 0 && pf_tag_packet(pd, ctx.tag)) {
6040 REASON_SET(&ctx.reason, PFRES_MEMORY);
6041 goto cleanup;
6042 }
6043 if (pd->act.rtableid >= 0)
6044 M_SETFIB(pd->m, pd->act.rtableid);
6045
6046 if (r->rt) {
6047 /*
6048 * Set act.rt here instead of in pf_rule_to_actions() because
6049 * it is applied only from the last pass rule. For rules
6050 * with the prefer-ipv6-nexthop option act.rt_af is a hint
6051 * about AF of the forwarded packet and might be changed.
6052 */
6053 pd->act.rt = r->rt;
6054 if (r->rt == PF_REPLYTO)
6055 pd->act.rt_af = pd->af;
6056 else
6057 pd->act.rt_af = pd->naf;
6058 if ((transerror = pf_map_addr_sn(pd->af, r, pd->src,
6059 &pd->act.rt_addr, &pd->act.rt_af, &pd->act.rt_kif, NULL,
6060 &(r->route), PF_SN_ROUTE)) != PFRES_MATCH) {
6061 REASON_SET(&ctx.reason, transerror);
6062 goto cleanup;
6063 }
6064 }
6065
6066 if (pd->virtual_proto != PF_VPROTO_FRAGMENT &&
6067 (!ctx.state_icmp && (r->keep_state || ctx.nr != NULL ||
6068 (pd->flags & PFDESC_TCP_NORM)))) {
6069 bool nat64;
6070
6071 action = pf_create_state(r, &ctx, sm, bproto_sum, bip_sum,
6072 match_rules);
6073 ctx.sk = ctx.nk = NULL;
6074 if (action != PF_PASS) {
6075 pf_udp_mapping_release(ctx.udp_mapping);
6076 if (r->log || (ctx.nr != NULL && ctx.nr->log) ||
6077 ctx.reason == PFRES_MEMORY)
6078 pd->act.log |= PF_LOG_FORCE;
6079 if (action == PF_DROP &&
6080 (r->rule_flag & PFRULE_RETURN))
6081 pf_return(r, ctx.nr, pd, ctx.th,
6082 bproto_sum, bip_sum, &ctx.reason,
6083 pd->act.rtableid);
6084 *reason = ctx.reason;
6085 return (action);
6086 }
6087
6088 nat64 = pd->af != pd->naf;
6089 if (nat64) {
6090 int ret;
6091
6092 if (ctx.sk == NULL)
6093 ctx.sk = (*sm)->key[pd->dir == PF_IN ? PF_SK_STACK : PF_SK_WIRE];
6094 if (ctx.nk == NULL)
6095 ctx.nk = (*sm)->key[pd->dir == PF_IN ? PF_SK_WIRE : PF_SK_STACK];
6096
6097 if (pd->dir == PF_IN) {
6098 ret = pf_translate(pd, &ctx.sk->addr[pd->didx],
6099 ctx.sk->port[pd->didx], &ctx.sk->addr[pd->sidx],
6100 ctx.sk->port[pd->sidx], ctx.virtual_type,
6101 ctx.icmp_dir);
6102 } else {
6103 ret = pf_translate(pd, &ctx.sk->addr[pd->sidx],
6104 ctx.sk->port[pd->sidx], &ctx.sk->addr[pd->didx],
6105 ctx.sk->port[pd->didx], ctx.virtual_type,
6106 ctx.icmp_dir);
6107 }
6108
6109 if (ret < 0)
6110 goto cleanup;
6111
6112 ctx.rewrite += ret;
6113
6114 if (ctx.rewrite && ctx.sk->af != ctx.nk->af)
6115 action = PF_AFRT;
6116 }
6117 } else {
6118 uma_zfree(V_pf_state_key_z, ctx.sk);
6119 uma_zfree(V_pf_state_key_z, ctx.nk);
6120 ctx.sk = ctx.nk = NULL;
6121 pf_udp_mapping_release(ctx.udp_mapping);
6122 }
6123
6124 /* copy back packet headers if we performed NAT operations */
6125 if (ctx.rewrite)
6126 m_copyback(pd->m, pd->off, pd->hdrlen, pd->hdr.any);
6127
6128 if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
6129 pd->dir == PF_OUT &&
6130 V_pfsync_defer_ptr != NULL && V_pfsync_defer_ptr(*sm, pd->m)) {
6131 /*
6132 * We want the state created, but we dont
6133 * want to send this in case a partner
6134 * firewall has to know about it to allow
6135 * replies through it.
6136 */
6137 *reason = ctx.reason;
6138 return (PF_DEFER);
6139 }
6140
6141 *reason = ctx.reason;
6142 return (action);
6143
6144 cleanup:
6145 uma_zfree(V_pf_state_key_z, ctx.sk);
6146 uma_zfree(V_pf_state_key_z, ctx.nk);
6147 pf_udp_mapping_release(ctx.udp_mapping);
6148 *reason = ctx.reason;
6149
6150 return (PF_DROP);
6151 }
6152
6153 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)6154 pf_create_state(struct pf_krule *r, struct pf_test_ctx *ctx,
6155 struct pf_kstate **sm, u_int16_t bproto_sum, u_int16_t bip_sum,
6156 struct pf_krule_slist *match_rules)
6157 {
6158 struct pf_pdesc *pd = ctx->pd;
6159 struct pf_kstate *s = NULL;
6160 struct pf_ksrc_node *sns[PF_SN_MAX] = { NULL };
6161 /*
6162 * XXXKS: The hash for PF_SN_LIMIT and PF_SN_ROUTE should be the same
6163 * but for PF_SN_NAT it is different. Don't try optimizing it,
6164 * just store all 3 hashes.
6165 */
6166 struct pf_srchash *snhs[PF_SN_MAX] = { NULL };
6167 struct tcphdr *th = &pd->hdr.tcp;
6168 u_int16_t mss = V_tcp_mssdflt;
6169 u_short sn_reason;
6170
6171 /* check maximums */
6172 if (r->max_states &&
6173 (counter_u64_fetch(r->states_cur) >= r->max_states)) {
6174 counter_u64_add(V_pf_status.lcounters[LCNT_STATES], 1);
6175 REASON_SET(&ctx->reason, PFRES_MAXSTATES);
6176 goto csfailed;
6177 }
6178 /* src node for limits */
6179 if ((r->rule_flag & PFRULE_SRCTRACK) &&
6180 (sn_reason = pf_insert_src_node(sns, snhs, r, pd->src, pd->af,
6181 NULL, NULL, pd->af, PF_SN_LIMIT)) != 0) {
6182 REASON_SET(&ctx->reason, sn_reason);
6183 goto csfailed;
6184 }
6185 /* src node for route-to rule */
6186 if (r->rt) {
6187 if ((r->route.opts & PF_POOL_STICKYADDR) &&
6188 (sn_reason = pf_insert_src_node(sns, snhs, r, pd->src,
6189 pd->af, &pd->act.rt_addr, pd->act.rt_kif, pd->act.rt_af,
6190 PF_SN_ROUTE)) != 0) {
6191 REASON_SET(&ctx->reason, sn_reason);
6192 goto csfailed;
6193 }
6194 }
6195 /* src node for translation rule */
6196 if (ctx->nr != NULL) {
6197 KASSERT(ctx->nat_pool != NULL, ("%s: nat_pool is NULL", __func__));
6198 /*
6199 * The NAT addresses are chosen during ruleset parsing.
6200 * The new afto code stores post-nat addresses in nsaddr.
6201 * The old nat code (also used for new nat-to rules) creates
6202 * state keys and stores addresses in them.
6203 */
6204 if ((ctx->nat_pool->opts & PF_POOL_STICKYADDR) &&
6205 (sn_reason = pf_insert_src_node(sns, snhs, ctx->nr,
6206 ctx->sk ? &(ctx->sk->addr[pd->sidx]) : pd->src, pd->af,
6207 ctx->nk ? &(ctx->nk->addr[1]) : &(pd->nsaddr), NULL,
6208 pd->naf, PF_SN_NAT)) != 0 ) {
6209 REASON_SET(&ctx->reason, sn_reason);
6210 goto csfailed;
6211 }
6212 }
6213 s = pf_alloc_state(M_NOWAIT);
6214 if (s == NULL) {
6215 REASON_SET(&ctx->reason, PFRES_MEMORY);
6216 goto csfailed;
6217 }
6218 s->rule = r;
6219 s->nat_rule = ctx->nr;
6220 s->anchor = ctx->a;
6221 s->match_rules = *match_rules;
6222 memcpy(&s->act, &pd->act, sizeof(struct pf_rule_actions));
6223
6224 if (pd->act.allow_opts)
6225 s->state_flags |= PFSTATE_ALLOWOPTS;
6226 if (r->rule_flag & PFRULE_STATESLOPPY)
6227 s->state_flags |= PFSTATE_SLOPPY;
6228 if (pd->flags & PFDESC_TCP_NORM) /* Set by old-style scrub rules */
6229 s->state_flags |= PFSTATE_SCRUB_TCP;
6230 if ((r->rule_flag & PFRULE_PFLOW) ||
6231 (ctx->nr != NULL && ctx->nr->rule_flag & PFRULE_PFLOW))
6232 s->state_flags |= PFSTATE_PFLOW;
6233
6234 s->act.log = pd->act.log & PF_LOG_ALL;
6235 s->sync_state = PFSYNC_S_NONE;
6236 s->state_flags |= pd->act.flags; /* Only needed for pfsync and state export */
6237
6238 if (ctx->nr != NULL)
6239 s->act.log |= ctx->nr->log & PF_LOG_ALL;
6240 switch (pd->proto) {
6241 case IPPROTO_TCP:
6242 s->src.seqlo = ntohl(th->th_seq);
6243 s->src.seqhi = s->src.seqlo + pd->p_len + 1;
6244 if ((tcp_get_flags(th) & (TH_SYN|TH_ACK)) == TH_SYN &&
6245 r->keep_state == PF_STATE_MODULATE) {
6246 /* Generate sequence number modulator */
6247 if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
6248 0)
6249 s->src.seqdiff = 1;
6250 pf_change_proto_a(pd->m, &th->th_seq, &th->th_sum,
6251 htonl(s->src.seqlo + s->src.seqdiff), 0);
6252 ctx->rewrite = 1;
6253 } else
6254 s->src.seqdiff = 0;
6255 if (tcp_get_flags(th) & TH_SYN) {
6256 s->src.seqhi++;
6257 s->src.wscale = pf_get_wscale(pd);
6258 }
6259 s->src.max_win = MAX(ntohs(th->th_win), 1);
6260 if (s->src.wscale & PF_WSCALE_MASK) {
6261 /* Remove scale factor from initial window */
6262 int win = s->src.max_win;
6263 win += 1 << (s->src.wscale & PF_WSCALE_MASK);
6264 s->src.max_win = (win - 1) >>
6265 (s->src.wscale & PF_WSCALE_MASK);
6266 }
6267 if (tcp_get_flags(th) & TH_FIN)
6268 s->src.seqhi++;
6269 s->dst.seqhi = 1;
6270 s->dst.max_win = 1;
6271 pf_set_protostate(s, PF_PEER_SRC, TCPS_SYN_SENT);
6272 pf_set_protostate(s, PF_PEER_DST, TCPS_CLOSED);
6273 s->timeout = PFTM_TCP_FIRST_PACKET;
6274 atomic_add_32(&V_pf_status.states_halfopen, 1);
6275 break;
6276 case IPPROTO_UDP:
6277 pf_set_protostate(s, PF_PEER_SRC, PFUDPS_SINGLE);
6278 pf_set_protostate(s, PF_PEER_DST, PFUDPS_NO_TRAFFIC);
6279 s->timeout = PFTM_UDP_FIRST_PACKET;
6280 break;
6281 case IPPROTO_SCTP:
6282 pf_set_protostate(s, PF_PEER_SRC, SCTP_COOKIE_WAIT);
6283 pf_set_protostate(s, PF_PEER_DST, SCTP_CLOSED);
6284 s->timeout = PFTM_SCTP_FIRST_PACKET;
6285 break;
6286 case IPPROTO_ICMP:
6287 #ifdef INET6
6288 case IPPROTO_ICMPV6:
6289 #endif /* INET6 */
6290 s->timeout = PFTM_ICMP_FIRST_PACKET;
6291 break;
6292 default:
6293 pf_set_protostate(s, PF_PEER_SRC, PFOTHERS_SINGLE);
6294 pf_set_protostate(s, PF_PEER_DST, PFOTHERS_NO_TRAFFIC);
6295 s->timeout = PFTM_OTHER_FIRST_PACKET;
6296 }
6297
6298 s->creation = s->expire = pf_get_uptime();
6299
6300 if (pd->proto == IPPROTO_TCP) {
6301 if (s->state_flags & PFSTATE_SCRUB_TCP &&
6302 pf_normalize_tcp_init(pd, th, &s->src)) {
6303 REASON_SET(&ctx->reason, PFRES_MEMORY);
6304 goto csfailed;
6305 }
6306 if (s->state_flags & PFSTATE_SCRUB_TCP && s->src.scrub &&
6307 pf_normalize_tcp_stateful(pd, &ctx->reason, th, s,
6308 &s->src, &s->dst, &ctx->rewrite)) {
6309 /* This really shouldn't happen!!! */
6310 DPFPRINTF(PF_DEBUG_URGENT,
6311 "%s: tcp normalize failed on first "
6312 "pkt", __func__);
6313 goto csfailed;
6314 }
6315 } else if (pd->proto == IPPROTO_SCTP) {
6316 if (pf_normalize_sctp_init(pd, &s->src, &s->dst))
6317 goto csfailed;
6318 if (! (pd->sctp_flags & (PFDESC_SCTP_INIT | PFDESC_SCTP_ADD_IP)))
6319 goto csfailed;
6320 }
6321 s->direction = pd->dir;
6322
6323 /*
6324 * sk/nk could already been setup by pf_get_translation().
6325 */
6326 if (ctx->sk == NULL && ctx->nk == NULL) {
6327 MPASS(pd->sport == NULL || (pd->osport == *pd->sport));
6328 MPASS(pd->dport == NULL || (pd->odport == *pd->dport));
6329 if (pf_state_key_setup(pd, pd->nsport, pd->ndport,
6330 &ctx->sk, &ctx->nk)) {
6331 goto csfailed;
6332 }
6333 } else
6334 KASSERT((ctx->sk != NULL && ctx->nk != NULL), ("%s: nr %p sk %p, nk %p",
6335 __func__, ctx->nr, ctx->sk, ctx->nk));
6336
6337 /* Swap sk/nk for PF_OUT. */
6338 if (pf_state_insert(BOUND_IFACE(s, pd), pd->kif,
6339 (pd->dir == PF_IN) ? ctx->sk : ctx->nk,
6340 (pd->dir == PF_IN) ? ctx->nk : ctx->sk, s)) {
6341 REASON_SET(&ctx->reason, PFRES_STATEINS);
6342 goto drop;
6343 } else
6344 *sm = s;
6345 ctx->sk = ctx->nk = NULL;
6346
6347 STATE_INC_COUNTERS(s);
6348
6349 /*
6350 * Lock order is important: first state, then source node.
6351 */
6352 for (pf_sn_types_t sn_type=0; sn_type<PF_SN_MAX; sn_type++) {
6353 if (pf_src_node_exists(&sns[sn_type], snhs[sn_type])) {
6354 s->sns[sn_type] = sns[sn_type];
6355 PF_HASHROW_UNLOCK(snhs[sn_type]);
6356 }
6357 }
6358
6359 if (ctx->tag > 0)
6360 s->tag = ctx->tag;
6361 if (pd->proto == IPPROTO_TCP && (tcp_get_flags(th) & (TH_SYN|TH_ACK)) ==
6362 TH_SYN && r->keep_state == PF_STATE_SYNPROXY && pd->dir == PF_IN) {
6363 pf_set_protostate(s, PF_PEER_SRC, PF_TCPS_PROXY_SRC);
6364 pf_undo_nat(ctx->nr, pd, bip_sum);
6365 s->src.seqhi = arc4random();
6366 /* Find mss option */
6367 int rtid = M_GETFIB(pd->m);
6368 mss = pf_get_mss(pd);
6369 mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
6370 mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
6371 s->src.mss = mss;
6372 pf_send_tcp(r, pd->af, pd->dst, pd->src, th->th_dport,
6373 th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
6374 TH_SYN|TH_ACK, 0, s->src.mss, 0, M_SKIP_FIREWALL, 0, 0,
6375 pd->act.rtableid, &ctx->reason);
6376 REASON_SET(&ctx->reason, PFRES_SYNPROXY);
6377 return (PF_SYNPROXY_DROP);
6378 }
6379
6380 s->udp_mapping = ctx->udp_mapping;
6381
6382 return (PF_PASS);
6383
6384 csfailed:
6385 uma_zfree(V_pf_state_key_z, ctx->sk);
6386 uma_zfree(V_pf_state_key_z, ctx->nk);
6387
6388 for (pf_sn_types_t sn_type=0; sn_type<PF_SN_MAX; sn_type++) {
6389 if (pf_src_node_exists(&sns[sn_type], snhs[sn_type])) {
6390 if (--sns[sn_type]->states == 0 &&
6391 sns[sn_type]->expire == 0) {
6392 pf_unlink_src_node(sns[sn_type]);
6393 pf_free_src_node(sns[sn_type]);
6394 counter_u64_add(
6395 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
6396 }
6397 PF_HASHROW_UNLOCK(snhs[sn_type]);
6398 }
6399 }
6400
6401 drop:
6402 if (s != NULL) {
6403 pf_src_tree_remove_state(s);
6404 s->timeout = PFTM_UNLINKED;
6405 pf_free_state(s);
6406 }
6407
6408 return (PF_DROP);
6409 }
6410
6411 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)6412 pf_translate(struct pf_pdesc *pd, struct pf_addr *saddr, u_int16_t sport,
6413 struct pf_addr *daddr, u_int16_t dport, u_int16_t virtual_type,
6414 int icmp_dir)
6415 {
6416 /*
6417 * pf_translate() implements OpenBSD's "new" NAT approach.
6418 * We don't follow it, because it involves a breaking syntax change
6419 * (removing nat/rdr rules, moving it into regular pf rules.)
6420 * It also moves NAT processing to be done after normal rules evaluation
6421 * whereas in FreeBSD that's done before rules processing.
6422 *
6423 * We adopt the function only for nat64, and keep other NAT processing
6424 * before rules processing.
6425 */
6426 int rewrite = 0;
6427 int afto = pd->af != pd->naf;
6428
6429 MPASS(afto);
6430
6431 switch (pd->proto) {
6432 case IPPROTO_TCP:
6433 case IPPROTO_UDP:
6434 case IPPROTO_SCTP:
6435 if (afto || *pd->sport != sport) {
6436 pf_change_ap(pd, pd->src, pd->sport,
6437 saddr, sport);
6438 rewrite = 1;
6439 }
6440 if (afto || *pd->dport != dport) {
6441 pf_change_ap(pd, pd->dst, pd->dport,
6442 daddr, dport);
6443 rewrite = 1;
6444 }
6445 break;
6446
6447 #ifdef INET
6448 case IPPROTO_ICMP:
6449 /* pf_translate() is also used when logging invalid packets */
6450 if (pd->af != AF_INET)
6451 return (0);
6452
6453 if (afto) {
6454 if (pf_translate_icmp_af(AF_INET6, &pd->hdr.icmp))
6455 return (-1);
6456 pd->proto = IPPROTO_ICMPV6;
6457 rewrite = 1;
6458 }
6459 if (virtual_type == htons(ICMP_ECHO)) {
6460 u_int16_t icmpid = (icmp_dir == PF_IN) ? sport : dport;
6461
6462 if (icmpid != pd->hdr.icmp.icmp_id) {
6463 pd->hdr.icmp.icmp_cksum = pf_cksum_fixup(
6464 pd->hdr.icmp.icmp_cksum,
6465 pd->hdr.icmp.icmp_id, icmpid, 0);
6466 pd->hdr.icmp.icmp_id = icmpid;
6467 /* XXX TODO copyback. */
6468 rewrite = 1;
6469 }
6470 }
6471 break;
6472 #endif /* INET */
6473
6474 #ifdef INET6
6475 case IPPROTO_ICMPV6:
6476 /* pf_translate() is also used when logging invalid packets */
6477 if (pd->af != AF_INET6)
6478 return (0);
6479
6480 if (afto) {
6481 /* ip_sum will be recalculated in pf_translate_af */
6482 if (pf_translate_icmp_af(AF_INET, &pd->hdr.icmp6))
6483 return (0);
6484 pd->proto = IPPROTO_ICMP;
6485 rewrite = 1;
6486 }
6487 break;
6488 #endif /* INET6 */
6489
6490 default:
6491 break;
6492 }
6493
6494 return (rewrite);
6495 }
6496
6497 int
pf_translate_compat(struct pf_test_ctx * ctx)6498 pf_translate_compat(struct pf_test_ctx *ctx)
6499 {
6500 struct pf_pdesc *pd = ctx->pd;
6501 struct pf_state_key *nk = ctx->nk;
6502 struct tcphdr *th = &pd->hdr.tcp;
6503 int rewrite = 0;
6504
6505 KASSERT(ctx->sk != NULL, ("%s: null sk", __func__));
6506 KASSERT(ctx->nk != NULL, ("%s: null nk", __func__));
6507
6508 switch (pd->virtual_proto) {
6509 case IPPROTO_TCP:
6510 if (PF_ANEQ(&pd->nsaddr, &nk->addr[pd->sidx], pd->af) ||
6511 nk->port[pd->sidx] != pd->nsport) {
6512 pf_change_ap(pd, pd->src, &th->th_sport,
6513 &nk->addr[pd->sidx], nk->port[pd->sidx]);
6514 pd->sport = &th->th_sport;
6515 pd->nsport = th->th_sport;
6516 pf_addrcpy(&pd->nsaddr, pd->src, pd->af);
6517 }
6518
6519 if (PF_ANEQ(&pd->ndaddr, &nk->addr[pd->didx], pd->af) ||
6520 nk->port[pd->didx] != pd->ndport) {
6521 pf_change_ap(pd, pd->dst, &th->th_dport,
6522 &nk->addr[pd->didx], nk->port[pd->didx]);
6523 pd->dport = &th->th_dport;
6524 pd->ndport = th->th_dport;
6525 pf_addrcpy(&pd->ndaddr, pd->dst, pd->af);
6526 }
6527 rewrite++;
6528 break;
6529 case IPPROTO_UDP:
6530 if (PF_ANEQ(&pd->nsaddr, &nk->addr[pd->sidx], pd->af) ||
6531 nk->port[pd->sidx] != pd->nsport) {
6532 pf_change_ap(pd, pd->src,
6533 &pd->hdr.udp.uh_sport,
6534 &nk->addr[pd->sidx],
6535 nk->port[pd->sidx]);
6536 pd->sport = &pd->hdr.udp.uh_sport;
6537 pd->nsport = pd->hdr.udp.uh_sport;
6538 pf_addrcpy(&pd->nsaddr, pd->src, pd->af);
6539 }
6540
6541 if (PF_ANEQ(&pd->ndaddr, &nk->addr[pd->didx], pd->af) ||
6542 nk->port[pd->didx] != pd->ndport) {
6543 pf_change_ap(pd, pd->dst,
6544 &pd->hdr.udp.uh_dport,
6545 &nk->addr[pd->didx],
6546 nk->port[pd->didx]);
6547 pd->dport = &pd->hdr.udp.uh_dport;
6548 pd->ndport = pd->hdr.udp.uh_dport;
6549 pf_addrcpy(&pd->ndaddr, pd->dst, pd->af);
6550 }
6551 rewrite++;
6552 break;
6553 case IPPROTO_SCTP: {
6554 if (PF_ANEQ(&pd->nsaddr, &nk->addr[pd->sidx], pd->af) ||
6555 nk->port[pd->sidx] != pd->nsport) {
6556 pf_change_ap(pd, pd->src,
6557 &pd->hdr.sctp.src_port,
6558 &nk->addr[pd->sidx],
6559 nk->port[pd->sidx]);
6560 pd->sport = &pd->hdr.sctp.src_port;
6561 pd->nsport = pd->hdr.sctp.src_port;
6562 pf_addrcpy(&pd->nsaddr, pd->src, pd->af);
6563 }
6564 if (PF_ANEQ(&pd->ndaddr, &nk->addr[pd->didx], pd->af) ||
6565 nk->port[pd->didx] != pd->ndport) {
6566 pf_change_ap(pd, pd->dst,
6567 &pd->hdr.sctp.dest_port,
6568 &nk->addr[pd->didx],
6569 nk->port[pd->didx]);
6570 pd->dport = &pd->hdr.sctp.dest_port;
6571 pd->ndport = pd->hdr.sctp.dest_port;
6572 pf_addrcpy(&pd->ndaddr, pd->dst, pd->af);
6573 }
6574 break;
6575 }
6576 #ifdef INET
6577 case IPPROTO_ICMP:
6578 if (PF_ANEQ(&pd->nsaddr, &nk->addr[pd->sidx], AF_INET)) {
6579 pf_change_a(&pd->src->v4.s_addr, pd->ip_sum,
6580 nk->addr[pd->sidx].v4.s_addr, 0);
6581 pf_addrcpy(&pd->nsaddr, pd->src, pd->af);
6582 }
6583
6584 if (PF_ANEQ(&pd->ndaddr, &nk->addr[pd->didx], AF_INET)) {
6585 pf_change_a(&pd->dst->v4.s_addr, pd->ip_sum,
6586 nk->addr[pd->didx].v4.s_addr, 0);
6587 pf_addrcpy(&pd->ndaddr, pd->dst, pd->af);
6588 }
6589
6590 if (ctx->virtual_type == htons(ICMP_ECHO) &&
6591 nk->port[pd->sidx] != pd->hdr.icmp.icmp_id) {
6592 pd->hdr.icmp.icmp_cksum = pf_cksum_fixup(
6593 pd->hdr.icmp.icmp_cksum, pd->nsport,
6594 nk->port[pd->sidx], 0);
6595 pd->hdr.icmp.icmp_id = nk->port[pd->sidx];
6596 pd->sport = &pd->hdr.icmp.icmp_id;
6597 }
6598 m_copyback(pd->m, pd->off, ICMP_MINLEN, (caddr_t)&pd->hdr.icmp);
6599 break;
6600 #endif /* INET */
6601 #ifdef INET6
6602 case IPPROTO_ICMPV6:
6603 if (PF_ANEQ(&pd->nsaddr, &nk->addr[pd->sidx], AF_INET6)) {
6604 pf_change_a6(pd->src, &pd->hdr.icmp6.icmp6_cksum,
6605 &nk->addr[pd->sidx], 0);
6606 pf_addrcpy(&pd->nsaddr, pd->src, pd->af);
6607 }
6608
6609 if (PF_ANEQ(&pd->ndaddr, &nk->addr[pd->didx], AF_INET6)) {
6610 pf_change_a6(pd->dst, &pd->hdr.icmp6.icmp6_cksum,
6611 &nk->addr[pd->didx], 0);
6612 pf_addrcpy(&pd->ndaddr, pd->dst, pd->af);
6613 }
6614 rewrite++;
6615 break;
6616 #endif /* INET */
6617 default:
6618 switch (pd->af) {
6619 #ifdef INET
6620 case AF_INET:
6621 if (PF_ANEQ(&pd->nsaddr,
6622 &nk->addr[pd->sidx], AF_INET)) {
6623 pf_change_a(&pd->src->v4.s_addr,
6624 pd->ip_sum,
6625 nk->addr[pd->sidx].v4.s_addr, 0);
6626 pf_addrcpy(&pd->nsaddr, pd->src, pd->af);
6627 }
6628
6629 if (PF_ANEQ(&pd->ndaddr,
6630 &nk->addr[pd->didx], AF_INET)) {
6631 pf_change_a(&pd->dst->v4.s_addr,
6632 pd->ip_sum,
6633 nk->addr[pd->didx].v4.s_addr, 0);
6634 pf_addrcpy(&pd->ndaddr, pd->dst, pd->af);
6635 }
6636 break;
6637 #endif /* INET */
6638 #ifdef INET6
6639 case AF_INET6:
6640 if (PF_ANEQ(&pd->nsaddr,
6641 &nk->addr[pd->sidx], AF_INET6)) {
6642 pf_addrcpy(&pd->nsaddr, &nk->addr[pd->sidx],
6643 pd->af);
6644 pf_addrcpy(pd->src, &nk->addr[pd->sidx], pd->af);
6645 }
6646
6647 if (PF_ANEQ(&pd->ndaddr,
6648 &nk->addr[pd->didx], AF_INET6)) {
6649 pf_addrcpy(&pd->ndaddr, &nk->addr[pd->didx],
6650 pd->af);
6651 pf_addrcpy(pd->dst, &nk->addr[pd->didx],
6652 pd->af);
6653 }
6654 break;
6655 #endif /* INET6 */
6656 }
6657 break;
6658 }
6659 return (rewrite);
6660 }
6661
6662 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)6663 pf_tcp_track_full(struct pf_kstate *state, struct pf_pdesc *pd,
6664 u_short *reason, int *copyback, struct pf_state_peer *src,
6665 struct pf_state_peer *dst, u_int8_t psrc, u_int8_t pdst)
6666 {
6667 struct tcphdr *th = &pd->hdr.tcp;
6668 u_int16_t win = ntohs(th->th_win);
6669 u_int32_t ack, end, data_end, seq, orig_seq;
6670 u_int8_t sws, dws;
6671 int ackskew;
6672
6673 if (src->wscale && dst->wscale && !(tcp_get_flags(th) & TH_SYN)) {
6674 sws = src->wscale & PF_WSCALE_MASK;
6675 dws = dst->wscale & PF_WSCALE_MASK;
6676 } else
6677 sws = dws = 0;
6678
6679 /*
6680 * Sequence tracking algorithm from Guido van Rooij's paper:
6681 * http://www.madison-gurkha.com/publications/tcp_filtering/
6682 * tcp_filtering.ps
6683 */
6684
6685 orig_seq = seq = ntohl(th->th_seq);
6686 if (src->seqlo == 0) {
6687 /* First packet from this end. Set its state */
6688
6689 if ((state->state_flags & PFSTATE_SCRUB_TCP || dst->scrub) &&
6690 src->scrub == NULL) {
6691 if (pf_normalize_tcp_init(pd, th, src)) {
6692 REASON_SET(reason, PFRES_MEMORY);
6693 return (PF_DROP);
6694 }
6695 }
6696
6697 /* Deferred generation of sequence number modulator */
6698 if (dst->seqdiff && !src->seqdiff) {
6699 /* use random iss for the TCP server */
6700 while ((src->seqdiff = arc4random() - seq) == 0)
6701 ;
6702 ack = ntohl(th->th_ack) - dst->seqdiff;
6703 pf_change_proto_a(pd->m, &th->th_seq, &th->th_sum, htonl(seq +
6704 src->seqdiff), 0);
6705 pf_change_proto_a(pd->m, &th->th_ack, &th->th_sum, htonl(ack), 0);
6706 *copyback = 1;
6707 } else {
6708 ack = ntohl(th->th_ack);
6709 }
6710
6711 end = seq + pd->p_len;
6712 if (tcp_get_flags(th) & TH_SYN) {
6713 end++;
6714 if (dst->wscale & PF_WSCALE_FLAG) {
6715 src->wscale = pf_get_wscale(pd);
6716 if (src->wscale & PF_WSCALE_FLAG) {
6717 /* Remove scale factor from initial
6718 * window */
6719 sws = src->wscale & PF_WSCALE_MASK;
6720 win = ((u_int32_t)win + (1 << sws) - 1)
6721 >> sws;
6722 dws = dst->wscale & PF_WSCALE_MASK;
6723 } else {
6724 /* fixup other window */
6725 dst->max_win = MIN(TCP_MAXWIN,
6726 (u_int32_t)dst->max_win <<
6727 (dst->wscale & PF_WSCALE_MASK));
6728 /* in case of a retrans SYN|ACK */
6729 dst->wscale = 0;
6730 }
6731 }
6732 }
6733 data_end = end;
6734 if (tcp_get_flags(th) & TH_FIN)
6735 end++;
6736
6737 src->seqlo = seq;
6738 if (src->state < TCPS_SYN_SENT)
6739 pf_set_protostate(state, psrc, TCPS_SYN_SENT);
6740
6741 /*
6742 * May need to slide the window (seqhi may have been set by
6743 * the crappy stack check or if we picked up the connection
6744 * after establishment)
6745 */
6746 if (src->seqhi == 1 ||
6747 SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
6748 src->seqhi = end + MAX(1, dst->max_win << dws);
6749 if (win > src->max_win)
6750 src->max_win = win;
6751
6752 } else {
6753 ack = ntohl(th->th_ack) - dst->seqdiff;
6754 if (src->seqdiff) {
6755 /* Modulate sequence numbers */
6756 pf_change_proto_a(pd->m, &th->th_seq, &th->th_sum, htonl(seq +
6757 src->seqdiff), 0);
6758 pf_change_proto_a(pd->m, &th->th_ack, &th->th_sum, htonl(ack), 0);
6759 *copyback = 1;
6760 }
6761 end = seq + pd->p_len;
6762 if (tcp_get_flags(th) & TH_SYN)
6763 end++;
6764 data_end = end;
6765 if (tcp_get_flags(th) & TH_FIN)
6766 end++;
6767 }
6768
6769 if ((tcp_get_flags(th) & TH_ACK) == 0) {
6770 /* Let it pass through the ack skew check */
6771 ack = dst->seqlo;
6772 } else if ((ack == 0 &&
6773 (tcp_get_flags(th) & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
6774 /* broken tcp stacks do not set ack */
6775 (dst->state < TCPS_SYN_SENT)) {
6776 /*
6777 * Many stacks (ours included) will set the ACK number in an
6778 * FIN|ACK if the SYN times out -- no sequence to ACK.
6779 */
6780 ack = dst->seqlo;
6781 }
6782
6783 if (seq == end) {
6784 /* Ease sequencing restrictions on no data packets */
6785 seq = src->seqlo;
6786 data_end = end = seq;
6787 }
6788
6789 ackskew = dst->seqlo - ack;
6790
6791 /*
6792 * Need to demodulate the sequence numbers in any TCP SACK options
6793 * (Selective ACK). We could optionally validate the SACK values
6794 * against the current ACK window, either forwards or backwards, but
6795 * I'm not confident that SACK has been implemented properly
6796 * everywhere. It wouldn't surprise me if several stacks accidentally
6797 * SACK too far backwards of previously ACKed data. There really aren't
6798 * any security implications of bad SACKing unless the target stack
6799 * doesn't validate the option length correctly. Someone trying to
6800 * spoof into a TCP connection won't bother blindly sending SACK
6801 * options anyway.
6802 */
6803 if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
6804 if (pf_modulate_sack(pd, th, dst))
6805 *copyback = 1;
6806 }
6807
6808 #define MAXACKWINDOW (0xffff + 1500) /* 1500 is an arbitrary fudge factor */
6809 if (SEQ_GEQ(src->seqhi, data_end) &&
6810 /* Last octet inside other's window space */
6811 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
6812 /* Retrans: not more than one window back */
6813 (ackskew >= -MAXACKWINDOW) &&
6814 /* Acking not more than one reassembled fragment backwards */
6815 (ackskew <= (MAXACKWINDOW << sws)) &&
6816 /* Acking not more than one window forward */
6817 ((tcp_get_flags(th) & TH_RST) == 0 || orig_seq == src->seqlo ||
6818 (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
6819 /* Require an exact/+1 sequence match on resets when possible */
6820 (SEQ_GEQ(orig_seq, src->seqlo - (dst->max_win << dws)) &&
6821 SEQ_LEQ(orig_seq, src->seqlo + 1) && ackskew == 0 &&
6822 (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)))) {
6823 /* Allow resets to match sequence window if ack is perfect match */
6824
6825 if (dst->scrub || src->scrub) {
6826 if (pf_normalize_tcp_stateful(pd, reason, th,
6827 state, src, dst, copyback))
6828 return (PF_DROP);
6829 }
6830
6831 /* update max window */
6832 if (src->max_win < win)
6833 src->max_win = win;
6834 /* synchronize sequencing */
6835 if (SEQ_GT(end, src->seqlo))
6836 src->seqlo = end;
6837 /* slide the window of what the other end can send */
6838 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
6839 dst->seqhi = ack + MAX((win << sws), 1);
6840
6841 /* update states */
6842 if (tcp_get_flags(th) & TH_SYN)
6843 if (src->state < TCPS_SYN_SENT)
6844 pf_set_protostate(state, psrc, TCPS_SYN_SENT);
6845 if (tcp_get_flags(th) & TH_FIN)
6846 if (src->state < TCPS_CLOSING)
6847 pf_set_protostate(state, psrc, TCPS_CLOSING);
6848 if (tcp_get_flags(th) & TH_ACK) {
6849 if (dst->state == TCPS_SYN_SENT) {
6850 pf_set_protostate(state, pdst,
6851 TCPS_ESTABLISHED);
6852 if (src->state == TCPS_ESTABLISHED &&
6853 state->sns[PF_SN_LIMIT] != NULL &&
6854 pf_src_connlimit(state)) {
6855 REASON_SET(reason, PFRES_SRCLIMIT);
6856 return (PF_DROP);
6857 }
6858 } else if (dst->state == TCPS_CLOSING)
6859 pf_set_protostate(state, pdst,
6860 TCPS_FIN_WAIT_2);
6861 }
6862 if (tcp_get_flags(th) & TH_RST)
6863 pf_set_protostate(state, PF_PEER_BOTH, TCPS_TIME_WAIT);
6864
6865 /* update expire time */
6866 state->expire = pf_get_uptime();
6867 if (src->state >= TCPS_FIN_WAIT_2 &&
6868 dst->state >= TCPS_FIN_WAIT_2)
6869 state->timeout = PFTM_TCP_CLOSED;
6870 else if (src->state >= TCPS_CLOSING &&
6871 dst->state >= TCPS_CLOSING)
6872 state->timeout = PFTM_TCP_FIN_WAIT;
6873 else if (src->state < TCPS_ESTABLISHED ||
6874 dst->state < TCPS_ESTABLISHED)
6875 state->timeout = PFTM_TCP_OPENING;
6876 else if (src->state >= TCPS_CLOSING ||
6877 dst->state >= TCPS_CLOSING)
6878 state->timeout = PFTM_TCP_CLOSING;
6879 else
6880 state->timeout = PFTM_TCP_ESTABLISHED;
6881
6882 /* Fall through to PASS packet */
6883
6884 } else if ((dst->state < TCPS_SYN_SENT ||
6885 dst->state >= TCPS_FIN_WAIT_2 ||
6886 src->state >= TCPS_FIN_WAIT_2) &&
6887 SEQ_GEQ(src->seqhi + MAXACKWINDOW, data_end) &&
6888 /* Within a window forward of the originating packet */
6889 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
6890 /* Within a window backward of the originating packet */
6891
6892 /*
6893 * This currently handles three situations:
6894 * 1) Stupid stacks will shotgun SYNs before their peer
6895 * replies.
6896 * 2) When PF catches an already established stream (the
6897 * firewall rebooted, the state table was flushed, routes
6898 * changed...)
6899 * 3) Packets get funky immediately after the connection
6900 * closes (this should catch Solaris spurious ACK|FINs
6901 * that web servers like to spew after a close)
6902 *
6903 * This must be a little more careful than the above code
6904 * since packet floods will also be caught here. We don't
6905 * update the TTL here to mitigate the damage of a packet
6906 * flood and so the same code can handle awkward establishment
6907 * and a loosened connection close.
6908 * In the establishment case, a correct peer response will
6909 * validate the connection, go through the normal state code
6910 * and keep updating the state TTL.
6911 */
6912
6913 if (V_pf_status.debug >= PF_DEBUG_MISC) {
6914 printf("pf: loose state match: ");
6915 pf_print_state(state);
6916 pf_print_flags(tcp_get_flags(th));
6917 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
6918 "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
6919 pd->p_len, ackskew, (unsigned long long)state->packets[0],
6920 (unsigned long long)state->packets[1],
6921 pd->dir == PF_IN ? "in" : "out",
6922 pd->dir == state->direction ? "fwd" : "rev");
6923 }
6924
6925 if (dst->scrub || src->scrub) {
6926 if (pf_normalize_tcp_stateful(pd, reason, th,
6927 state, src, dst, copyback))
6928 return (PF_DROP);
6929 }
6930
6931 /* update max window */
6932 if (src->max_win < win)
6933 src->max_win = win;
6934 /* synchronize sequencing */
6935 if (SEQ_GT(end, src->seqlo))
6936 src->seqlo = end;
6937 /* slide the window of what the other end can send */
6938 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
6939 dst->seqhi = ack + MAX((win << sws), 1);
6940
6941 /*
6942 * Cannot set dst->seqhi here since this could be a shotgunned
6943 * SYN and not an already established connection.
6944 */
6945
6946 if (tcp_get_flags(th) & TH_FIN)
6947 if (src->state < TCPS_CLOSING)
6948 pf_set_protostate(state, psrc, TCPS_CLOSING);
6949 if (tcp_get_flags(th) & TH_RST)
6950 pf_set_protostate(state, PF_PEER_BOTH, TCPS_TIME_WAIT);
6951
6952 /* Fall through to PASS packet */
6953
6954 } else {
6955 if (state->dst.state == TCPS_SYN_SENT &&
6956 state->src.state == TCPS_SYN_SENT) {
6957 /* Send RST for state mismatches during handshake */
6958 if (!(tcp_get_flags(th) & TH_RST))
6959 pf_send_tcp(state->rule, pd->af,
6960 pd->dst, pd->src, th->th_dport,
6961 th->th_sport, ntohl(th->th_ack), 0,
6962 TH_RST, 0, 0,
6963 state->rule->return_ttl, M_SKIP_FIREWALL,
6964 0, 0, state->act.rtableid, reason);
6965 src->seqlo = 0;
6966 src->seqhi = 1;
6967 src->max_win = 1;
6968 } else if (V_pf_status.debug >= PF_DEBUG_MISC) {
6969 printf("pf: BAD state: ");
6970 pf_print_state(state);
6971 pf_print_flags(tcp_get_flags(th));
6972 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
6973 "pkts=%llu:%llu dir=%s,%s\n",
6974 seq, orig_seq, ack, pd->p_len, ackskew,
6975 (unsigned long long)state->packets[0],
6976 (unsigned long long)state->packets[1],
6977 pd->dir == PF_IN ? "in" : "out",
6978 pd->dir == state->direction ? "fwd" : "rev");
6979 printf("pf: State failure on: %c %c %c %c | %c %c\n",
6980 SEQ_GEQ(src->seqhi, data_end) ? ' ' : '1',
6981 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
6982 ' ': '2',
6983 (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
6984 (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
6985 SEQ_GEQ(src->seqhi + MAXACKWINDOW, data_end) ?' ' :'5',
6986 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
6987 }
6988 REASON_SET(reason, PFRES_BADSTATE);
6989 return (PF_DROP);
6990 }
6991
6992 return (PF_PASS);
6993 }
6994
6995 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)6996 pf_tcp_track_sloppy(struct pf_kstate *state, struct pf_pdesc *pd,
6997 u_short *reason, struct pf_state_peer *src, struct pf_state_peer *dst,
6998 u_int8_t psrc, u_int8_t pdst)
6999 {
7000 struct tcphdr *th = &pd->hdr.tcp;
7001
7002 if (tcp_get_flags(th) & TH_SYN)
7003 if (src->state < TCPS_SYN_SENT)
7004 pf_set_protostate(state, psrc, TCPS_SYN_SENT);
7005 if (tcp_get_flags(th) & TH_FIN)
7006 if (src->state < TCPS_CLOSING)
7007 pf_set_protostate(state, psrc, TCPS_CLOSING);
7008 if (tcp_get_flags(th) & TH_ACK) {
7009 if (dst->state == TCPS_SYN_SENT) {
7010 pf_set_protostate(state, pdst, TCPS_ESTABLISHED);
7011 if (src->state == TCPS_ESTABLISHED &&
7012 state->sns[PF_SN_LIMIT] != NULL &&
7013 pf_src_connlimit(state)) {
7014 REASON_SET(reason, PFRES_SRCLIMIT);
7015 return (PF_DROP);
7016 }
7017 } else if (dst->state == TCPS_CLOSING) {
7018 pf_set_protostate(state, pdst, TCPS_FIN_WAIT_2);
7019 } else if (src->state == TCPS_SYN_SENT &&
7020 dst->state < TCPS_SYN_SENT) {
7021 /*
7022 * Handle a special sloppy case where we only see one
7023 * half of the connection. If there is a ACK after
7024 * the initial SYN without ever seeing a packet from
7025 * the destination, set the connection to established.
7026 */
7027 pf_set_protostate(state, PF_PEER_BOTH,
7028 TCPS_ESTABLISHED);
7029 dst->state = src->state = TCPS_ESTABLISHED;
7030 if (state->sns[PF_SN_LIMIT] != NULL &&
7031 pf_src_connlimit(state)) {
7032 REASON_SET(reason, PFRES_SRCLIMIT);
7033 return (PF_DROP);
7034 }
7035 } else if (src->state == TCPS_CLOSING &&
7036 dst->state == TCPS_ESTABLISHED &&
7037 dst->seqlo == 0) {
7038 /*
7039 * Handle the closing of half connections where we
7040 * don't see the full bidirectional FIN/ACK+ACK
7041 * handshake.
7042 */
7043 pf_set_protostate(state, pdst, TCPS_CLOSING);
7044 }
7045 }
7046 if (tcp_get_flags(th) & TH_RST)
7047 pf_set_protostate(state, PF_PEER_BOTH, TCPS_TIME_WAIT);
7048
7049 /* update expire time */
7050 state->expire = pf_get_uptime();
7051 if (src->state >= TCPS_FIN_WAIT_2 &&
7052 dst->state >= TCPS_FIN_WAIT_2)
7053 state->timeout = PFTM_TCP_CLOSED;
7054 else if (src->state >= TCPS_CLOSING &&
7055 dst->state >= TCPS_CLOSING)
7056 state->timeout = PFTM_TCP_FIN_WAIT;
7057 else if (src->state < TCPS_ESTABLISHED ||
7058 dst->state < TCPS_ESTABLISHED)
7059 state->timeout = PFTM_TCP_OPENING;
7060 else if (src->state >= TCPS_CLOSING ||
7061 dst->state >= TCPS_CLOSING)
7062 state->timeout = PFTM_TCP_CLOSING;
7063 else
7064 state->timeout = PFTM_TCP_ESTABLISHED;
7065
7066 return (PF_PASS);
7067 }
7068
7069 static int
pf_synproxy(struct pf_pdesc * pd,struct pf_kstate * state,u_short * reason)7070 pf_synproxy(struct pf_pdesc *pd, struct pf_kstate *state, u_short *reason)
7071 {
7072 struct pf_state_key *sk = state->key[pd->didx];
7073 struct tcphdr *th = &pd->hdr.tcp;
7074
7075 if (state->src.state == PF_TCPS_PROXY_SRC) {
7076 if (pd->dir != state->direction) {
7077 REASON_SET(reason, PFRES_SYNPROXY);
7078 return (PF_SYNPROXY_DROP);
7079 }
7080 if (tcp_get_flags(th) & TH_SYN) {
7081 if (ntohl(th->th_seq) != state->src.seqlo) {
7082 REASON_SET(reason, PFRES_SYNPROXY);
7083 return (PF_DROP);
7084 }
7085 pf_send_tcp(state->rule, pd->af, pd->dst,
7086 pd->src, th->th_dport, th->th_sport,
7087 state->src.seqhi, ntohl(th->th_seq) + 1,
7088 TH_SYN|TH_ACK, 0, state->src.mss, 0,
7089 M_SKIP_FIREWALL, 0, 0, state->act.rtableid,
7090 reason);
7091 REASON_SET(reason, PFRES_SYNPROXY);
7092 return (PF_SYNPROXY_DROP);
7093 } else if ((tcp_get_flags(th) & (TH_ACK|TH_RST|TH_FIN)) != 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 } else if (state->sns[PF_SN_LIMIT] != NULL &&
7099 pf_src_connlimit(state)) {
7100 REASON_SET(reason, PFRES_SRCLIMIT);
7101 return (PF_DROP);
7102 } else
7103 pf_set_protostate(state, PF_PEER_SRC,
7104 PF_TCPS_PROXY_DST);
7105 }
7106 if (state->src.state == PF_TCPS_PROXY_DST) {
7107 if (pd->dir == state->direction) {
7108 if (((tcp_get_flags(th) & (TH_SYN|TH_ACK)) != TH_ACK) ||
7109 (ntohl(th->th_ack) != state->src.seqhi + 1) ||
7110 (ntohl(th->th_seq) != state->src.seqlo + 1)) {
7111 REASON_SET(reason, PFRES_SYNPROXY);
7112 return (PF_DROP);
7113 }
7114 state->src.max_win = MAX(ntohs(th->th_win), 1);
7115 if (state->dst.seqhi == 1)
7116 state->dst.seqhi = arc4random();
7117 pf_send_tcp(state->rule, pd->af,
7118 &sk->addr[pd->sidx], &sk->addr[pd->didx],
7119 sk->port[pd->sidx], sk->port[pd->didx],
7120 state->dst.seqhi, 0, TH_SYN, 0,
7121 state->src.mss, 0,
7122 state->orig_kif->pfik_ifp == V_loif ? M_LOOP : 0,
7123 state->tag, 0, state->act.rtableid,
7124 reason);
7125 REASON_SET(reason, PFRES_SYNPROXY);
7126 return (PF_SYNPROXY_DROP);
7127 } else if (((tcp_get_flags(th) & (TH_SYN|TH_ACK)) !=
7128 (TH_SYN|TH_ACK)) ||
7129 (ntohl(th->th_ack) != state->dst.seqhi + 1)) {
7130 REASON_SET(reason, PFRES_SYNPROXY);
7131 return (PF_DROP);
7132 } else {
7133 state->dst.max_win = MAX(ntohs(th->th_win), 1);
7134 state->dst.seqlo = ntohl(th->th_seq);
7135 pf_send_tcp(state->rule, pd->af, pd->dst,
7136 pd->src, th->th_dport, th->th_sport,
7137 ntohl(th->th_ack), ntohl(th->th_seq) + 1,
7138 TH_ACK, state->src.max_win, 0, 0, 0,
7139 state->tag, 0, state->act.rtableid,
7140 reason);
7141 pf_send_tcp(state->rule, pd->af,
7142 &sk->addr[pd->sidx], &sk->addr[pd->didx],
7143 sk->port[pd->sidx], sk->port[pd->didx],
7144 state->src.seqhi + 1, state->src.seqlo + 1,
7145 TH_ACK, state->dst.max_win, 0, 0,
7146 M_SKIP_FIREWALL, 0, 0, state->act.rtableid,
7147 reason);
7148 state->src.seqdiff = state->dst.seqhi -
7149 state->src.seqlo;
7150 state->dst.seqdiff = state->src.seqhi -
7151 state->dst.seqlo;
7152 state->src.seqhi = state->src.seqlo +
7153 state->dst.max_win;
7154 state->dst.seqhi = state->dst.seqlo +
7155 state->src.max_win;
7156 state->src.wscale = state->dst.wscale = 0;
7157 pf_set_protostate(state, PF_PEER_BOTH,
7158 TCPS_ESTABLISHED);
7159 REASON_SET(reason, PFRES_SYNPROXY);
7160 return (PF_SYNPROXY_DROP);
7161 }
7162 }
7163
7164 return (PF_PASS);
7165 }
7166
7167 static int
pf_test_state(struct pf_kstate ** state,struct pf_pdesc * pd,u_short * reason)7168 pf_test_state(struct pf_kstate **state, struct pf_pdesc *pd, u_short *reason)
7169 {
7170 struct pf_state_key_cmp key;
7171 int copyback = 0;
7172 struct pf_state_peer *src, *dst;
7173 uint8_t psrc, pdst;
7174 int action;
7175
7176 bzero(&key, sizeof(key));
7177 key.af = pd->af;
7178 key.proto = pd->virtual_proto;
7179 pf_addrcpy(&key.addr[pd->sidx], pd->src, key.af);
7180 pf_addrcpy(&key.addr[pd->didx], pd->dst, key.af);
7181 key.port[pd->sidx] = pd->osport;
7182 key.port[pd->didx] = pd->odport;
7183
7184 action = pf_find_state(pd, &key, state);
7185 if (action != PF_MATCH)
7186 return (action);
7187
7188 action = PF_PASS;
7189 if (pd->dir == (*state)->direction) {
7190 if (PF_REVERSED_KEY(*state, pd->af)) {
7191 src = &(*state)->dst;
7192 dst = &(*state)->src;
7193 psrc = PF_PEER_DST;
7194 pdst = PF_PEER_SRC;
7195 } else {
7196 src = &(*state)->src;
7197 dst = &(*state)->dst;
7198 psrc = PF_PEER_SRC;
7199 pdst = PF_PEER_DST;
7200 }
7201 } else {
7202 if (PF_REVERSED_KEY(*state, pd->af)) {
7203 src = &(*state)->src;
7204 dst = &(*state)->dst;
7205 psrc = PF_PEER_SRC;
7206 pdst = PF_PEER_DST;
7207 } else {
7208 src = &(*state)->dst;
7209 dst = &(*state)->src;
7210 psrc = PF_PEER_DST;
7211 pdst = PF_PEER_SRC;
7212 }
7213 }
7214
7215 switch (pd->virtual_proto) {
7216 case IPPROTO_TCP: {
7217 struct tcphdr *th = &pd->hdr.tcp;
7218
7219 if ((action = pf_synproxy(pd, *state, reason)) != PF_PASS)
7220 return (action);
7221 if (((tcp_get_flags(th) & (TH_SYN | TH_ACK)) == TH_SYN) ||
7222 ((th->th_flags & (TH_SYN | TH_ACK | TH_RST)) == TH_ACK &&
7223 pf_syncookie_check(pd) && pd->dir == PF_IN)) {
7224 if ((*state)->src.state >= TCPS_FIN_WAIT_2 &&
7225 (*state)->dst.state >= TCPS_FIN_WAIT_2) {
7226 if (V_pf_status.debug >= PF_DEBUG_MISC) {
7227 printf("pf: state reuse ");
7228 pf_print_state(*state);
7229 pf_print_flags(tcp_get_flags(th));
7230 printf("\n");
7231 }
7232 /* XXX make sure it's the same direction ?? */
7233 pf_set_protostate(*state, PF_PEER_BOTH, TCPS_CLOSED);
7234 pf_remove_state(*state);
7235 *state = NULL;
7236 return (PF_DROP);
7237 } else if ((*state)->src.state >= TCPS_ESTABLISHED &&
7238 (*state)->dst.state >= TCPS_ESTABLISHED) {
7239 /*
7240 * SYN matches existing state???
7241 * Typically happens when sender boots up after
7242 * sudden panic. Certain protocols (NFSv3) are
7243 * always using same port numbers. Challenge
7244 * ACK enables all parties (firewall and peers)
7245 * to get in sync again.
7246 */
7247 pf_send_challenge_ack(pd, *state, src, dst, reason);
7248 return (PF_DROP);
7249 }
7250 }
7251 if ((*state)->state_flags & PFSTATE_SLOPPY) {
7252 if (pf_tcp_track_sloppy(*state, pd, reason, src, dst,
7253 psrc, pdst) == PF_DROP)
7254 return (PF_DROP);
7255 } else {
7256 int ret;
7257
7258 ret = pf_tcp_track_full(*state, pd, reason,
7259 ©back, src, dst, psrc, pdst);
7260 if (ret == PF_DROP)
7261 return (PF_DROP);
7262 }
7263 break;
7264 }
7265 case IPPROTO_UDP:
7266 /* update states */
7267 if (src->state < PFUDPS_SINGLE)
7268 pf_set_protostate(*state, psrc, PFUDPS_SINGLE);
7269 if (dst->state == PFUDPS_SINGLE)
7270 pf_set_protostate(*state, pdst, PFUDPS_MULTIPLE);
7271
7272 /* update expire time */
7273 (*state)->expire = pf_get_uptime();
7274 if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
7275 (*state)->timeout = PFTM_UDP_MULTIPLE;
7276 else
7277 (*state)->timeout = PFTM_UDP_SINGLE;
7278 break;
7279 case IPPROTO_SCTP:
7280 if ((src->state >= SCTP_SHUTDOWN_SENT || src->state == SCTP_CLOSED) &&
7281 (dst->state >= SCTP_SHUTDOWN_SENT || dst->state == SCTP_CLOSED) &&
7282 pd->sctp_flags & PFDESC_SCTP_INIT) {
7283 pf_set_protostate(*state, PF_PEER_BOTH, SCTP_CLOSED);
7284 pf_remove_state(*state);
7285 *state = NULL;
7286 return (PF_DROP);
7287 }
7288
7289 if (pf_sctp_track(*state, pd, reason) != PF_PASS)
7290 return (PF_DROP);
7291
7292 /* Track state. */
7293 if (pd->sctp_flags & PFDESC_SCTP_INIT) {
7294 if (src->state < SCTP_COOKIE_WAIT) {
7295 pf_set_protostate(*state, psrc, SCTP_COOKIE_WAIT);
7296 (*state)->timeout = PFTM_SCTP_OPENING;
7297 }
7298 }
7299 if (pd->sctp_flags & PFDESC_SCTP_INIT_ACK) {
7300 MPASS(dst->scrub != NULL);
7301 if (dst->scrub->pfss_v_tag == 0)
7302 dst->scrub->pfss_v_tag = pd->sctp_initiate_tag;
7303 }
7304
7305 /*
7306 * Bind to the correct interface if we're if-bound. For multihomed
7307 * extra associations we don't know which interface that will be until
7308 * here, so we've inserted the state on V_pf_all. Fix that now.
7309 */
7310 if ((*state)->kif == V_pfi_all &&
7311 (*state)->rule->rule_flag & PFRULE_IFBOUND)
7312 (*state)->kif = pd->kif;
7313
7314 if (pd->sctp_flags & (PFDESC_SCTP_COOKIE | PFDESC_SCTP_HEARTBEAT_ACK)) {
7315 if (src->state < SCTP_ESTABLISHED) {
7316 pf_set_protostate(*state, psrc, SCTP_ESTABLISHED);
7317 (*state)->timeout = PFTM_SCTP_ESTABLISHED;
7318 }
7319 }
7320 if (pd->sctp_flags & (PFDESC_SCTP_SHUTDOWN |
7321 PFDESC_SCTP_SHUTDOWN_COMPLETE)) {
7322 if (src->state < SCTP_SHUTDOWN_PENDING) {
7323 pf_set_protostate(*state, psrc, SCTP_SHUTDOWN_PENDING);
7324 (*state)->timeout = PFTM_SCTP_CLOSING;
7325 }
7326 }
7327 if (pd->sctp_flags & (PFDESC_SCTP_SHUTDOWN_COMPLETE | PFDESC_SCTP_ABORT)) {
7328 pf_set_protostate(*state, psrc, SCTP_CLOSED);
7329 (*state)->timeout = PFTM_SCTP_CLOSED;
7330 }
7331
7332 (*state)->expire = pf_get_uptime();
7333 break;
7334 default:
7335 /* update states */
7336 if (src->state < PFOTHERS_SINGLE)
7337 pf_set_protostate(*state, psrc, PFOTHERS_SINGLE);
7338 if (dst->state == PFOTHERS_SINGLE)
7339 pf_set_protostate(*state, pdst, PFOTHERS_MULTIPLE);
7340
7341 /* update expire time */
7342 (*state)->expire = pf_get_uptime();
7343 if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
7344 (*state)->timeout = PFTM_OTHER_MULTIPLE;
7345 else
7346 (*state)->timeout = PFTM_OTHER_SINGLE;
7347 break;
7348 }
7349
7350 /* translate source/destination address, if necessary */
7351 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
7352 struct pf_state_key *nk;
7353 int afto, sidx, didx;
7354
7355 if (PF_REVERSED_KEY(*state, pd->af))
7356 nk = (*state)->key[pd->sidx];
7357 else
7358 nk = (*state)->key[pd->didx];
7359
7360 afto = pd->af != nk->af;
7361
7362 if (afto && (*state)->direction == PF_IN) {
7363 sidx = pd->didx;
7364 didx = pd->sidx;
7365 } else {
7366 sidx = pd->sidx;
7367 didx = pd->didx;
7368 }
7369
7370 if (afto) {
7371 pf_addrcpy(&pd->nsaddr, &nk->addr[sidx], nk->af);
7372 pf_addrcpy(&pd->ndaddr, &nk->addr[didx], nk->af);
7373 pd->naf = nk->af;
7374 action = PF_AFRT;
7375 }
7376
7377 if (afto || PF_ANEQ(pd->src, &nk->addr[sidx], pd->af) ||
7378 nk->port[sidx] != pd->osport)
7379 pf_change_ap(pd, pd->src, pd->sport,
7380 &nk->addr[sidx], nk->port[sidx]);
7381
7382 if (afto || PF_ANEQ(pd->dst, &nk->addr[didx], pd->af) ||
7383 nk->port[didx] != pd->odport)
7384 pf_change_ap(pd, pd->dst, pd->dport,
7385 &nk->addr[didx], nk->port[didx]);
7386
7387 copyback = 1;
7388 }
7389
7390 if (copyback && pd->hdrlen > 0)
7391 m_copyback(pd->m, pd->off, pd->hdrlen, pd->hdr.any);
7392
7393 return (action);
7394 }
7395
7396 static int
pf_sctp_track(struct pf_kstate * state,struct pf_pdesc * pd,u_short * reason)7397 pf_sctp_track(struct pf_kstate *state, struct pf_pdesc *pd,
7398 u_short *reason)
7399 {
7400 struct pf_state_peer *src;
7401 if (pd->dir == state->direction) {
7402 if (PF_REVERSED_KEY(state, pd->af))
7403 src = &state->dst;
7404 else
7405 src = &state->src;
7406 } else {
7407 if (PF_REVERSED_KEY(state, pd->af))
7408 src = &state->src;
7409 else
7410 src = &state->dst;
7411 }
7412
7413 if (src->scrub != NULL) {
7414 /*
7415 * Allow tags to be updated, in case of retransmission of
7416 * INIT/INIT_ACK chunks.
7417 **/
7418 if (src->state <= SCTP_COOKIE_WAIT)
7419 src->scrub->pfss_v_tag = pd->hdr.sctp.v_tag;
7420 else if (src->scrub->pfss_v_tag != pd->hdr.sctp.v_tag)
7421 return (PF_DROP);
7422 }
7423
7424 return (PF_PASS);
7425 }
7426
7427 static void
pf_sctp_multihome_detach_addr(const struct pf_kstate * s)7428 pf_sctp_multihome_detach_addr(const struct pf_kstate *s)
7429 {
7430 struct pf_sctp_endpoint key;
7431 struct pf_sctp_endpoint *ep;
7432 struct pf_state_key *sks = s->key[PF_SK_STACK];
7433 struct pf_sctp_source *i, *tmp;
7434
7435 if (sks == NULL || sks->proto != IPPROTO_SCTP || s->dst.scrub == NULL)
7436 return;
7437
7438 PF_SCTP_ENDPOINTS_LOCK();
7439
7440 key.v_tag = s->dst.scrub->pfss_v_tag;
7441 ep = RB_FIND(pf_sctp_endpoints, &V_pf_sctp_endpoints, &key);
7442 if (ep != NULL) {
7443 TAILQ_FOREACH_SAFE(i, &ep->sources, entry, tmp) {
7444 if (pf_addr_cmp(&i->addr,
7445 &s->key[PF_SK_WIRE]->addr[s->direction == PF_OUT],
7446 s->key[PF_SK_WIRE]->af) == 0) {
7447 SDT_PROBE3(pf, sctp, multihome, remove,
7448 key.v_tag, s, i);
7449 TAILQ_REMOVE(&ep->sources, i, entry);
7450 free(i, M_PFTEMP);
7451 break;
7452 }
7453 }
7454
7455 if (TAILQ_EMPTY(&ep->sources)) {
7456 RB_REMOVE(pf_sctp_endpoints, &V_pf_sctp_endpoints, ep);
7457 free(ep, M_PFTEMP);
7458 }
7459 }
7460
7461 /* Other direction. */
7462 key.v_tag = s->src.scrub->pfss_v_tag;
7463 ep = RB_FIND(pf_sctp_endpoints, &V_pf_sctp_endpoints, &key);
7464 if (ep != NULL) {
7465 TAILQ_FOREACH_SAFE(i, &ep->sources, entry, tmp) {
7466 if (pf_addr_cmp(&i->addr,
7467 &s->key[PF_SK_WIRE]->addr[s->direction == PF_IN],
7468 s->key[PF_SK_WIRE]->af) == 0) {
7469 SDT_PROBE3(pf, sctp, multihome, remove,
7470 key.v_tag, s, i);
7471 TAILQ_REMOVE(&ep->sources, i, entry);
7472 free(i, M_PFTEMP);
7473 break;
7474 }
7475 }
7476
7477 if (TAILQ_EMPTY(&ep->sources)) {
7478 RB_REMOVE(pf_sctp_endpoints, &V_pf_sctp_endpoints, ep);
7479 free(ep, M_PFTEMP);
7480 }
7481 }
7482
7483 PF_SCTP_ENDPOINTS_UNLOCK();
7484 }
7485
7486 static void
pf_sctp_multihome_add_addr(struct pf_pdesc * pd,struct pf_addr * a,uint32_t v_tag)7487 pf_sctp_multihome_add_addr(struct pf_pdesc *pd, struct pf_addr *a, uint32_t v_tag)
7488 {
7489 struct pf_sctp_endpoint key = {
7490 .v_tag = v_tag,
7491 };
7492 struct pf_sctp_source *i;
7493 struct pf_sctp_endpoint *ep;
7494 int count;
7495
7496 PF_SCTP_ENDPOINTS_LOCK();
7497
7498 ep = RB_FIND(pf_sctp_endpoints, &V_pf_sctp_endpoints, &key);
7499 if (ep == NULL) {
7500 ep = malloc(sizeof(struct pf_sctp_endpoint),
7501 M_PFTEMP, M_NOWAIT);
7502 if (ep == NULL) {
7503 PF_SCTP_ENDPOINTS_UNLOCK();
7504 return;
7505 }
7506
7507 ep->v_tag = v_tag;
7508 TAILQ_INIT(&ep->sources);
7509 RB_INSERT(pf_sctp_endpoints, &V_pf_sctp_endpoints, ep);
7510 }
7511
7512 /* Avoid inserting duplicates. */
7513 count = 0;
7514 TAILQ_FOREACH(i, &ep->sources, entry) {
7515 count++;
7516 if (pf_addr_cmp(&i->addr, a, pd->af) == 0) {
7517 PF_SCTP_ENDPOINTS_UNLOCK();
7518 return;
7519 }
7520 }
7521
7522 /* Limit the number of addresses per endpoint. */
7523 if (count >= PF_SCTP_MAX_ENDPOINTS) {
7524 PF_SCTP_ENDPOINTS_UNLOCK();
7525 return;
7526 }
7527
7528 i = malloc(sizeof(*i), M_PFTEMP, M_NOWAIT);
7529 if (i == NULL) {
7530 PF_SCTP_ENDPOINTS_UNLOCK();
7531 return;
7532 }
7533
7534 i->af = pd->af;
7535 memcpy(&i->addr, a, sizeof(*a));
7536 TAILQ_INSERT_TAIL(&ep->sources, i, entry);
7537 SDT_PROBE2(pf, sctp, multihome, add, v_tag, i);
7538
7539 PF_SCTP_ENDPOINTS_UNLOCK();
7540 }
7541
7542 static void
pf_sctp_multihome_delayed(struct pf_pdesc * pd,struct pfi_kkif * kif,struct pf_kstate * s,int action)7543 pf_sctp_multihome_delayed(struct pf_pdesc *pd, struct pfi_kkif *kif,
7544 struct pf_kstate *s, int action)
7545 {
7546 struct pf_krule_slist match_rules;
7547 struct pf_sctp_multihome_job *j, *tmp;
7548 struct pf_sctp_source *i;
7549 int ret;
7550 struct pf_kstate *sm = NULL;
7551 struct pf_krule *ra = NULL;
7552 struct pf_krule *r = &V_pf_default_rule;
7553 struct pf_kruleset *rs = NULL;
7554 u_short reason;
7555 bool do_extra = true;
7556
7557 PF_RULES_RLOCK_TRACKER;
7558
7559 again:
7560 TAILQ_FOREACH_SAFE(j, &pd->sctp_multihome_jobs, next, tmp) {
7561 if (s == NULL || action != PF_PASS)
7562 goto free;
7563
7564 /* Confirm we don't recurse here. */
7565 MPASS(! (pd->sctp_flags & PFDESC_SCTP_ADD_IP));
7566
7567 switch (j->op) {
7568 case SCTP_ADD_IP_ADDRESS: {
7569 uint32_t v_tag = pd->sctp_initiate_tag;
7570
7571 if (v_tag == 0) {
7572 if (s->direction == pd->dir)
7573 v_tag = s->src.scrub->pfss_v_tag;
7574 else
7575 v_tag = s->dst.scrub->pfss_v_tag;
7576 }
7577
7578 /*
7579 * Avoid duplicating states. We'll already have
7580 * created a state based on the source address of
7581 * the packet, but SCTP endpoints may also list this
7582 * address again in the INIT(_ACK) parameters.
7583 */
7584 if (pf_addr_cmp(&j->src, pd->src, pd->af) == 0) {
7585 break;
7586 }
7587
7588 j->pd.sctp_flags |= PFDESC_SCTP_ADD_IP;
7589 PF_RULES_RLOCK();
7590 sm = NULL;
7591 if (s->rule->rule_flag & PFRULE_ALLOW_RELATED) {
7592 j->pd.related_rule = s->rule;
7593 }
7594 SLIST_INIT(&match_rules);
7595 ret = pf_test_rule(&r, &sm,
7596 &j->pd, &ra, &rs, &reason, NULL, &match_rules);
7597 /*
7598 * Nothing to do about match rules, the processed
7599 * packet has already increased the counters.
7600 */
7601 pf_free_match_rules(&match_rules);
7602 PF_RULES_RUNLOCK();
7603 SDT_PROBE4(pf, sctp, multihome, test, kif, r, j->pd.m, ret);
7604 if (ret != PF_DROP && sm != NULL) {
7605 /* Inherit v_tag values. */
7606 if (sm->direction == s->direction) {
7607 sm->src.scrub->pfss_v_tag = s->src.scrub->pfss_v_tag;
7608 sm->dst.scrub->pfss_v_tag = s->dst.scrub->pfss_v_tag;
7609 } else {
7610 sm->src.scrub->pfss_v_tag = s->dst.scrub->pfss_v_tag;
7611 sm->dst.scrub->pfss_v_tag = s->src.scrub->pfss_v_tag;
7612 }
7613 PF_STATE_UNLOCK(sm);
7614 } else {
7615 /* If we try duplicate inserts? */
7616 break;
7617 }
7618
7619 /* Only add the address if we've actually allowed the state. */
7620 pf_sctp_multihome_add_addr(pd, &j->src, v_tag);
7621
7622 if (! do_extra) {
7623 break;
7624 }
7625 /*
7626 * We need to do this for each of our source addresses.
7627 * Find those based on the verification tag.
7628 */
7629 struct pf_sctp_endpoint key = {
7630 .v_tag = pd->hdr.sctp.v_tag,
7631 };
7632 struct pf_sctp_endpoint *ep;
7633
7634 PF_SCTP_ENDPOINTS_LOCK();
7635 ep = RB_FIND(pf_sctp_endpoints, &V_pf_sctp_endpoints, &key);
7636 if (ep == NULL) {
7637 PF_SCTP_ENDPOINTS_UNLOCK();
7638 break;
7639 }
7640 MPASS(ep != NULL);
7641
7642 TAILQ_FOREACH(i, &ep->sources, entry) {
7643 struct pf_sctp_multihome_job *nj;
7644
7645 /* SCTP can intermingle IPv4 and IPv6. */
7646 if (i->af != pd->af)
7647 continue;
7648
7649 nj = malloc(sizeof(*nj), M_PFTEMP, M_NOWAIT | M_ZERO);
7650 if (! nj) {
7651 continue;
7652 }
7653 memcpy(&nj->pd, &j->pd, sizeof(j->pd));
7654 memcpy(&nj->src, &j->src, sizeof(nj->src));
7655 nj->pd.src = &nj->src;
7656 // New destination address!
7657 memcpy(&nj->dst, &i->addr, sizeof(nj->dst));
7658 nj->pd.dst = &nj->dst;
7659 nj->pd.m = j->pd.m;
7660 nj->op = j->op;
7661
7662 MPASS(nj->pd.pcksum);
7663 TAILQ_INSERT_TAIL(&pd->sctp_multihome_jobs, nj, next);
7664 }
7665 PF_SCTP_ENDPOINTS_UNLOCK();
7666
7667 break;
7668 }
7669 case SCTP_DEL_IP_ADDRESS: {
7670 struct pf_state_key_cmp key;
7671 uint8_t psrc;
7672 int action;
7673
7674 bzero(&key, sizeof(key));
7675 key.af = j->pd.af;
7676 key.proto = IPPROTO_SCTP;
7677 if (j->pd.dir == PF_IN) { /* wire side, straight */
7678 pf_addrcpy(&key.addr[0], j->pd.src, key.af);
7679 pf_addrcpy(&key.addr[1], j->pd.dst, key.af);
7680 key.port[0] = j->pd.hdr.sctp.src_port;
7681 key.port[1] = j->pd.hdr.sctp.dest_port;
7682 } else { /* stack side, reverse */
7683 pf_addrcpy(&key.addr[1], j->pd.src, key.af);
7684 pf_addrcpy(&key.addr[0], j->pd.dst, key.af);
7685 key.port[1] = j->pd.hdr.sctp.src_port;
7686 key.port[0] = j->pd.hdr.sctp.dest_port;
7687 }
7688
7689 action = pf_find_state(&j->pd, &key, &sm);
7690 if (action == PF_MATCH) {
7691 PF_STATE_LOCK_ASSERT(sm);
7692 if (j->pd.dir == sm->direction) {
7693 psrc = PF_PEER_SRC;
7694 } else {
7695 psrc = PF_PEER_DST;
7696 }
7697 pf_set_protostate(sm, psrc, SCTP_SHUTDOWN_PENDING);
7698 sm->timeout = PFTM_SCTP_CLOSING;
7699 PF_STATE_UNLOCK(sm);
7700 }
7701 break;
7702 default:
7703 panic("Unknown op %#x", j->op);
7704 }
7705 }
7706
7707 free:
7708 TAILQ_REMOVE(&pd->sctp_multihome_jobs, j, next);
7709 free(j, M_PFTEMP);
7710 }
7711
7712 /* We may have inserted extra work while processing the list. */
7713 if (! TAILQ_EMPTY(&pd->sctp_multihome_jobs)) {
7714 do_extra = false;
7715 goto again;
7716 }
7717 }
7718
7719 static int
pf_multihome_scan(int start,int len,struct pf_pdesc * pd,int op)7720 pf_multihome_scan(int start, int len, struct pf_pdesc *pd, int op)
7721 {
7722 int off = 0;
7723 struct pf_sctp_multihome_job *job;
7724
7725 SDT_PROBE4(pf, sctp, multihome_scan, entry, start, len, pd, op);
7726
7727 while (off < len) {
7728 struct sctp_paramhdr h;
7729
7730 if (!pf_pull_hdr(pd->m, start + off, &h, sizeof(h), NULL,
7731 pd->af))
7732 return (PF_DROP);
7733
7734 /* Parameters are at least 4 bytes. */
7735 if (ntohs(h.param_length) < 4)
7736 return (PF_DROP);
7737
7738 SDT_PROBE2(pf, sctp, multihome_scan, param, ntohs(h.param_type),
7739 ntohs(h.param_length));
7740
7741 switch (ntohs(h.param_type)) {
7742 case SCTP_IPV4_ADDRESS: {
7743 struct in_addr t;
7744
7745 if (ntohs(h.param_length) !=
7746 (sizeof(struct sctp_paramhdr) + sizeof(t)))
7747 return (PF_DROP);
7748
7749 if (!pf_pull_hdr(pd->m, start + off + sizeof(h), &t, sizeof(t),
7750 NULL, pd->af))
7751 return (PF_DROP);
7752
7753 if (in_nullhost(t))
7754 t.s_addr = pd->src->v4.s_addr;
7755
7756 /*
7757 * We hold the state lock (idhash) here, which means
7758 * that we can't acquire the keyhash, or we'll get a
7759 * LOR (and potentially double-lock things too). We also
7760 * can't release the state lock here, so instead we'll
7761 * enqueue this for async handling.
7762 * There's a relatively small race here, in that a
7763 * packet using the new addresses could arrive already,
7764 * but that's just though luck for it.
7765 */
7766 job = malloc(sizeof(*job), M_PFTEMP, M_NOWAIT | M_ZERO);
7767 if (! job)
7768 return (PF_DROP);
7769
7770 SDT_PROBE2(pf, sctp, multihome_scan, ipv4, &t, op);
7771
7772 memcpy(&job->pd, pd, sizeof(*pd));
7773
7774 // New source address!
7775 memcpy(&job->src, &t, sizeof(t));
7776 job->pd.src = &job->src;
7777 memcpy(&job->dst, pd->dst, sizeof(job->dst));
7778 job->pd.dst = &job->dst;
7779 job->pd.m = pd->m;
7780 job->op = op;
7781
7782 MPASS(job->pd.pcksum);
7783 TAILQ_INSERT_TAIL(&pd->sctp_multihome_jobs, job, next);
7784 break;
7785 }
7786 #ifdef INET6
7787 case SCTP_IPV6_ADDRESS: {
7788 struct in6_addr t;
7789
7790 if (ntohs(h.param_length) !=
7791 (sizeof(struct sctp_paramhdr) + sizeof(t)))
7792 return (PF_DROP);
7793
7794 if (!pf_pull_hdr(pd->m, start + off + sizeof(h), &t, sizeof(t),
7795 NULL, pd->af))
7796 return (PF_DROP);
7797 if (memcmp(&t, &pd->src->v6, sizeof(t)) == 0)
7798 break;
7799 if (memcmp(&t, &in6addr_any, sizeof(t)) == 0)
7800 memcpy(&t, &pd->src->v6, sizeof(t));
7801
7802 job = malloc(sizeof(*job), M_PFTEMP, M_NOWAIT | M_ZERO);
7803 if (! job)
7804 return (PF_DROP);
7805
7806 SDT_PROBE2(pf, sctp, multihome_scan, ipv6, &t, op);
7807
7808 memcpy(&job->pd, pd, sizeof(*pd));
7809 memcpy(&job->src, &t, sizeof(t));
7810 job->pd.src = &job->src;
7811 memcpy(&job->dst, pd->dst, sizeof(job->dst));
7812 job->pd.dst = &job->dst;
7813 job->pd.m = pd->m;
7814 job->op = op;
7815
7816 MPASS(job->pd.pcksum);
7817 TAILQ_INSERT_TAIL(&pd->sctp_multihome_jobs, job, next);
7818 break;
7819 }
7820 #endif /* INET6 */
7821 case SCTP_ADD_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
7829 ret = pf_multihome_scan(start + off + sizeof(ah),
7830 ntohs(ah.ph.param_length) - sizeof(ah), pd,
7831 SCTP_ADD_IP_ADDRESS);
7832 if (ret != PF_PASS)
7833 return (ret);
7834 break;
7835 }
7836 case SCTP_DEL_IP_ADDRESS: {
7837 int ret;
7838 struct sctp_asconf_paramhdr ah;
7839
7840 if (!pf_pull_hdr(pd->m, start + off, &ah, sizeof(ah),
7841 NULL, pd->af))
7842 return (PF_DROP);
7843 ret = pf_multihome_scan(start + off + sizeof(ah),
7844 ntohs(ah.ph.param_length) - sizeof(ah), pd,
7845 SCTP_DEL_IP_ADDRESS);
7846 if (ret != PF_PASS)
7847 return (ret);
7848 break;
7849 }
7850 default:
7851 break;
7852 }
7853
7854 off += roundup(ntohs(h.param_length), 4);
7855 }
7856
7857 return (PF_PASS);
7858 }
7859
7860 int
pf_multihome_scan_init(int start,int len,struct pf_pdesc * pd)7861 pf_multihome_scan_init(int start, int len, struct pf_pdesc *pd)
7862 {
7863 start += sizeof(struct sctp_init_chunk);
7864 len -= sizeof(struct sctp_init_chunk);
7865
7866 return (pf_multihome_scan(start, len, pd, SCTP_ADD_IP_ADDRESS));
7867 }
7868
7869 int
pf_multihome_scan_asconf(int start,int len,struct pf_pdesc * pd)7870 pf_multihome_scan_asconf(int start, int len, struct pf_pdesc *pd)
7871 {
7872 start += sizeof(struct sctp_asconf_chunk);
7873 len -= sizeof(struct sctp_asconf_chunk);
7874
7875 return (pf_multihome_scan(start, len, pd, SCTP_ADD_IP_ADDRESS));
7876 }
7877
7878 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)7879 pf_icmp_state_lookup(struct pf_state_key_cmp *key, struct pf_pdesc *pd,
7880 struct pf_kstate **state, u_int16_t icmpid, u_int16_t type, int icmp_dir,
7881 int *iidx, int multi, int inner)
7882 {
7883 int action, direction = pd->dir;
7884
7885 key->af = pd->af;
7886 key->proto = pd->proto;
7887 if (icmp_dir == PF_IN) {
7888 *iidx = pd->sidx;
7889 key->port[pd->sidx] = icmpid;
7890 key->port[pd->didx] = type;
7891 } else {
7892 *iidx = pd->didx;
7893 key->port[pd->sidx] = type;
7894 key->port[pd->didx] = icmpid;
7895 }
7896 if (pf_state_key_addr_setup(pd, key, multi))
7897 return (PF_DROP);
7898
7899 action = pf_find_state(pd, key, state);
7900 if (action != PF_MATCH)
7901 return (action);
7902
7903 if ((*state)->state_flags & PFSTATE_SLOPPY)
7904 return (-1);
7905
7906 /* Is this ICMP message flowing in right direction? */
7907 if ((*state)->key[PF_SK_WIRE]->af != (*state)->key[PF_SK_STACK]->af)
7908 direction = (pd->af == (*state)->key[PF_SK_WIRE]->af) ?
7909 PF_IN : PF_OUT;
7910 else
7911 direction = (*state)->direction;
7912 if ((*state)->rule->type &&
7913 (((!inner && direction == pd->dir) ||
7914 (inner && direction != pd->dir)) ?
7915 PF_IN : PF_OUT) != icmp_dir) {
7916 if (V_pf_status.debug >= PF_DEBUG_MISC) {
7917 printf("pf: icmp type %d in wrong direction (%d): ",
7918 ntohs(type), icmp_dir);
7919 pf_print_state(*state);
7920 printf("\n");
7921 }
7922 PF_STATE_UNLOCK(*state);
7923 *state = NULL;
7924 return (PF_DROP);
7925 }
7926 return (-1);
7927 }
7928
7929 static int
pf_test_state_icmp(struct pf_kstate ** state,struct pf_pdesc * pd,u_short * reason)7930 pf_test_state_icmp(struct pf_kstate **state, struct pf_pdesc *pd,
7931 u_short *reason)
7932 {
7933 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
7934 u_int16_t *icmpsum, virtual_id, virtual_type;
7935 u_int8_t icmptype, icmpcode;
7936 int icmp_dir, iidx, ret;
7937 struct pf_state_key_cmp key;
7938 #ifdef INET
7939 u_int16_t icmpid;
7940 #endif /* INET*/
7941
7942 MPASS(*state == NULL);
7943
7944 bzero(&key, sizeof(key));
7945 switch (pd->proto) {
7946 #ifdef INET
7947 case IPPROTO_ICMP:
7948 icmptype = pd->hdr.icmp.icmp_type;
7949 icmpcode = pd->hdr.icmp.icmp_code;
7950 icmpid = pd->hdr.icmp.icmp_id;
7951 icmpsum = &pd->hdr.icmp.icmp_cksum;
7952 break;
7953 #endif /* INET */
7954 #ifdef INET6
7955 case IPPROTO_ICMPV6:
7956 icmptype = pd->hdr.icmp6.icmp6_type;
7957 icmpcode = pd->hdr.icmp6.icmp6_code;
7958 #ifdef INET
7959 icmpid = pd->hdr.icmp6.icmp6_id;
7960 #endif /* INET */
7961 icmpsum = &pd->hdr.icmp6.icmp6_cksum;
7962 break;
7963 #endif /* INET6 */
7964 default:
7965 panic("unhandled proto %d", pd->proto);
7966 }
7967
7968 if (pf_icmp_mapping(pd, icmptype, &icmp_dir, &virtual_id,
7969 &virtual_type) == 0) {
7970 /*
7971 * ICMP query/reply message not related to a TCP/UDP/SCTP
7972 * packet. Search for an ICMP state.
7973 */
7974 ret = pf_icmp_state_lookup(&key, pd, state, virtual_id,
7975 virtual_type, icmp_dir, &iidx, 0, 0);
7976 /* IPv6? try matching a multicast address */
7977 if (ret == PF_DROP && pd->af == AF_INET6 && icmp_dir == PF_OUT) {
7978 MPASS(*state == NULL);
7979 ret = pf_icmp_state_lookup(&key, pd, state,
7980 virtual_id, virtual_type,
7981 icmp_dir, &iidx, 1, 0);
7982 }
7983 if (ret >= 0) {
7984 MPASS(*state == NULL);
7985 return (ret);
7986 }
7987
7988 (*state)->expire = pf_get_uptime();
7989 (*state)->timeout = PFTM_ICMP_ERROR_REPLY;
7990
7991 /* translate source/destination address, if necessary */
7992 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
7993 struct pf_state_key *nk;
7994 int afto, sidx, didx;
7995
7996 if (PF_REVERSED_KEY(*state, pd->af))
7997 nk = (*state)->key[pd->sidx];
7998 else
7999 nk = (*state)->key[pd->didx];
8000
8001 afto = pd->af != nk->af;
8002
8003 if (afto && (*state)->direction == PF_IN) {
8004 sidx = pd->didx;
8005 didx = pd->sidx;
8006 iidx = !iidx;
8007 } else {
8008 sidx = pd->sidx;
8009 didx = pd->didx;
8010 }
8011
8012 switch (pd->af) {
8013 #ifdef INET
8014 case AF_INET:
8015 #ifdef INET6
8016 if (afto) {
8017 if (pf_translate_icmp_af(AF_INET6,
8018 &pd->hdr.icmp))
8019 return (PF_DROP);
8020 pd->proto = IPPROTO_ICMPV6;
8021 }
8022 #endif /* INET6 */
8023 if (!afto &&
8024 PF_ANEQ(pd->src, &nk->addr[sidx], AF_INET))
8025 pf_change_a(&saddr->v4.s_addr,
8026 pd->ip_sum,
8027 nk->addr[sidx].v4.s_addr,
8028 0);
8029
8030 if (!afto && PF_ANEQ(pd->dst,
8031 &nk->addr[didx], AF_INET))
8032 pf_change_a(&daddr->v4.s_addr,
8033 pd->ip_sum,
8034 nk->addr[didx].v4.s_addr, 0);
8035
8036 if (nk->port[iidx] !=
8037 pd->hdr.icmp.icmp_id) {
8038 pd->hdr.icmp.icmp_cksum =
8039 pf_cksum_fixup(
8040 pd->hdr.icmp.icmp_cksum, icmpid,
8041 nk->port[iidx], 0);
8042 pd->hdr.icmp.icmp_id =
8043 nk->port[iidx];
8044 }
8045
8046 m_copyback(pd->m, pd->off, ICMP_MINLEN,
8047 (caddr_t )&pd->hdr.icmp);
8048 break;
8049 #endif /* INET */
8050 #ifdef INET6
8051 case AF_INET6:
8052 #ifdef INET
8053 if (afto) {
8054 if (pf_translate_icmp_af(AF_INET,
8055 &pd->hdr.icmp6))
8056 return (PF_DROP);
8057 pd->proto = IPPROTO_ICMP;
8058 }
8059 #endif /* INET */
8060 if (!afto &&
8061 PF_ANEQ(pd->src, &nk->addr[sidx], AF_INET6))
8062 pf_change_a6(saddr,
8063 &pd->hdr.icmp6.icmp6_cksum,
8064 &nk->addr[sidx], 0);
8065
8066 if (!afto && PF_ANEQ(pd->dst,
8067 &nk->addr[didx], AF_INET6))
8068 pf_change_a6(daddr,
8069 &pd->hdr.icmp6.icmp6_cksum,
8070 &nk->addr[didx], 0);
8071
8072 if (nk->port[iidx] != pd->hdr.icmp6.icmp6_id)
8073 pd->hdr.icmp6.icmp6_id =
8074 nk->port[iidx];
8075
8076 m_copyback(pd->m, pd->off, sizeof(struct icmp6_hdr),
8077 (caddr_t )&pd->hdr.icmp6);
8078 break;
8079 #endif /* INET6 */
8080 }
8081 if (afto) {
8082 pf_addrcpy(&pd->nsaddr, &nk->addr[sidx],
8083 nk->af);
8084 pf_addrcpy(&pd->ndaddr, &nk->addr[didx],
8085 nk->af);
8086 pd->naf = nk->af;
8087 return (PF_AFRT);
8088 }
8089 }
8090 return (PF_PASS);
8091
8092 } else {
8093 /*
8094 * ICMP error message in response to a TCP/UDP packet.
8095 * Extract the inner TCP/UDP header and search for that state.
8096 */
8097
8098 struct pf_pdesc pd2;
8099 bzero(&pd2, sizeof pd2);
8100 #ifdef INET
8101 struct ip h2;
8102 #endif /* INET */
8103 #ifdef INET6
8104 struct ip6_hdr h2_6;
8105 #endif /* INET6 */
8106 int ipoff2 = 0;
8107
8108 pd2.af = pd->af;
8109 pd2.dir = pd->dir;
8110 /* Payload packet is from the opposite direction. */
8111 pd2.sidx = (pd->dir == PF_IN) ? 1 : 0;
8112 pd2.didx = (pd->dir == PF_IN) ? 0 : 1;
8113 pd2.m = pd->m;
8114 pd2.pf_mtag = pd->pf_mtag;
8115 pd2.kif = pd->kif;
8116 switch (pd->af) {
8117 #ifdef INET
8118 case AF_INET:
8119 /* offset of h2 in mbuf chain */
8120 ipoff2 = pd->off + ICMP_MINLEN;
8121
8122 if (!pf_pull_hdr(pd->m, ipoff2, &h2, sizeof(h2),
8123 reason, pd2.af)) {
8124 DPFPRINTF(PF_DEBUG_MISC,
8125 "pf: ICMP error message too short "
8126 "(ip)");
8127 return (PF_DROP);
8128 }
8129 /*
8130 * ICMP error messages don't refer to non-first
8131 * fragments
8132 */
8133 if (h2.ip_off & htons(IP_OFFMASK)) {
8134 REASON_SET(reason, PFRES_FRAG);
8135 return (PF_DROP);
8136 }
8137
8138 /* offset of protocol header that follows h2 */
8139 pd2.off = ipoff2;
8140 if (pf_walk_header(&pd2, &h2, reason) != PF_PASS)
8141 return (PF_DROP);
8142
8143 pd2.tot_len = ntohs(h2.ip_len);
8144 pd2.ttl = h2.ip_ttl;
8145 pd2.src = (struct pf_addr *)&h2.ip_src;
8146 pd2.dst = (struct pf_addr *)&h2.ip_dst;
8147 pd2.ip_sum = &h2.ip_sum;
8148 break;
8149 #endif /* INET */
8150 #ifdef INET6
8151 case AF_INET6:
8152 ipoff2 = pd->off + sizeof(struct icmp6_hdr);
8153
8154 if (!pf_pull_hdr(pd->m, ipoff2, &h2_6, sizeof(h2_6),
8155 reason, pd2.af)) {
8156 DPFPRINTF(PF_DEBUG_MISC,
8157 "pf: ICMP error message too short "
8158 "(ip6)");
8159 return (PF_DROP);
8160 }
8161 pd2.off = ipoff2;
8162 if (pf_walk_header6(&pd2, &h2_6, reason) != PF_PASS)
8163 return (PF_DROP);
8164
8165 pd2.tot_len = ntohs(h2_6.ip6_plen) +
8166 sizeof(struct ip6_hdr);
8167 pd2.ttl = h2_6.ip6_hlim;
8168 pd2.src = (struct pf_addr *)&h2_6.ip6_src;
8169 pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
8170 pd2.ip_sum = NULL;
8171 break;
8172 #endif /* INET6 */
8173 default:
8174 unhandled_af(pd->af);
8175 }
8176
8177 if (PF_ANEQ(pd->dst, pd2.src, pd->af)) {
8178 if (V_pf_status.debug >= PF_DEBUG_MISC) {
8179 printf("pf: BAD ICMP %d:%d outer dst: ",
8180 icmptype, icmpcode);
8181 pf_print_host(pd->src, 0, pd->af);
8182 printf(" -> ");
8183 pf_print_host(pd->dst, 0, pd->af);
8184 printf(" inner src: ");
8185 pf_print_host(pd2.src, 0, pd2.af);
8186 printf(" -> ");
8187 pf_print_host(pd2.dst, 0, pd2.af);
8188 printf("\n");
8189 }
8190 REASON_SET(reason, PFRES_BADSTATE);
8191 return (PF_DROP);
8192 }
8193
8194 switch (pd2.proto) {
8195 case IPPROTO_TCP: {
8196 struct tcphdr *th = &pd2.hdr.tcp;
8197 u_int32_t seq;
8198 struct pf_state_peer *src, *dst;
8199 u_int8_t dws;
8200 int copyback = 0;
8201 int action;
8202
8203 /*
8204 * Only the first 8 bytes of the TCP header can be
8205 * expected. Don't access any TCP header fields after
8206 * th_seq, an ackskew test is not possible.
8207 */
8208 if (!pf_pull_hdr(pd->m, pd2.off, th, 8, reason,
8209 pd2.af)) {
8210 DPFPRINTF(PF_DEBUG_MISC,
8211 "pf: ICMP error message too short "
8212 "(tcp)");
8213 return (PF_DROP);
8214 }
8215 pd2.pcksum = &pd2.hdr.tcp.th_sum;
8216
8217 key.af = pd2.af;
8218 key.proto = IPPROTO_TCP;
8219 pf_addrcpy(&key.addr[pd2.sidx], pd2.src, key.af);
8220 pf_addrcpy(&key.addr[pd2.didx], pd2.dst, key.af);
8221 key.port[pd2.sidx] = th->th_sport;
8222 key.port[pd2.didx] = th->th_dport;
8223
8224 action = pf_find_state(&pd2, &key, state);
8225 if (action != PF_MATCH)
8226 return (action);
8227
8228 if (pd->dir == (*state)->direction) {
8229 if (PF_REVERSED_KEY(*state, pd->af)) {
8230 src = &(*state)->src;
8231 dst = &(*state)->dst;
8232 } else {
8233 src = &(*state)->dst;
8234 dst = &(*state)->src;
8235 }
8236 } else {
8237 if (PF_REVERSED_KEY(*state, pd->af)) {
8238 src = &(*state)->dst;
8239 dst = &(*state)->src;
8240 } else {
8241 src = &(*state)->src;
8242 dst = &(*state)->dst;
8243 }
8244 }
8245
8246 if (src->wscale && dst->wscale)
8247 dws = dst->wscale & PF_WSCALE_MASK;
8248 else
8249 dws = 0;
8250
8251 /* Demodulate sequence number */
8252 seq = ntohl(th->th_seq) - src->seqdiff;
8253 if (src->seqdiff) {
8254 pf_change_a(&th->th_seq, icmpsum,
8255 htonl(seq), 0);
8256 copyback = 1;
8257 }
8258
8259 if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
8260 (!SEQ_GEQ(src->seqhi, seq) ||
8261 !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
8262 if (V_pf_status.debug >= PF_DEBUG_MISC) {
8263 printf("pf: BAD ICMP %d:%d ",
8264 icmptype, icmpcode);
8265 pf_print_host(pd->src, 0, pd->af);
8266 printf(" -> ");
8267 pf_print_host(pd->dst, 0, pd->af);
8268 printf(" state: ");
8269 pf_print_state(*state);
8270 printf(" seq=%u\n", seq);
8271 }
8272 REASON_SET(reason, PFRES_BADSTATE);
8273 return (PF_DROP);
8274 } else {
8275 if (V_pf_status.debug >= PF_DEBUG_MISC) {
8276 printf("pf: OK ICMP %d:%d ",
8277 icmptype, icmpcode);
8278 pf_print_host(pd->src, 0, pd->af);
8279 printf(" -> ");
8280 pf_print_host(pd->dst, 0, pd->af);
8281 printf(" state: ");
8282 pf_print_state(*state);
8283 printf(" seq=%u\n", seq);
8284 }
8285 }
8286
8287 /* translate source/destination address, if necessary */
8288 if ((*state)->key[PF_SK_WIRE] !=
8289 (*state)->key[PF_SK_STACK]) {
8290
8291 struct pf_state_key *nk;
8292
8293 if (PF_REVERSED_KEY(*state, pd->af))
8294 nk = (*state)->key[pd->sidx];
8295 else
8296 nk = (*state)->key[pd->didx];
8297
8298 #if defined(INET) && defined(INET6)
8299 int afto, sidx, didx;
8300
8301 afto = pd->af != nk->af;
8302
8303 if (afto && (*state)->direction == PF_IN) {
8304 sidx = pd2.didx;
8305 didx = pd2.sidx;
8306 } else {
8307 sidx = pd2.sidx;
8308 didx = pd2.didx;
8309 }
8310
8311 if (afto) {
8312 if (pf_translate_icmp_af(nk->af,
8313 &pd->hdr.icmp))
8314 return (PF_DROP);
8315 m_copyback(pd->m, pd->off,
8316 sizeof(struct icmp6_hdr),
8317 (c_caddr_t)&pd->hdr.icmp6);
8318 if (pf_change_icmp_af(pd->m, ipoff2, pd,
8319 &pd2, &nk->addr[sidx],
8320 &nk->addr[didx], pd->af,
8321 nk->af))
8322 return (PF_DROP);
8323 pf_addrcpy(&pd->nsaddr,
8324 &nk->addr[pd2.sidx], nk->af);
8325 pf_addrcpy(&pd->ndaddr,
8326 &nk->addr[pd2.didx], nk->af);
8327 if (nk->af == AF_INET) {
8328 pd->proto = IPPROTO_ICMP;
8329 } else {
8330 pd->proto = IPPROTO_ICMPV6;
8331 /*
8332 * IPv4 becomes IPv6 so we must
8333 * copy IPv4 src addr to least
8334 * 32bits in IPv6 address to
8335 * keep traceroute/icmp
8336 * working.
8337 */
8338 pd->nsaddr.addr32[3] =
8339 pd->src->addr32[0];
8340 }
8341 pd->naf = pd2.naf = nk->af;
8342 pf_change_ap(&pd2, pd2.src, &th->th_sport,
8343 &nk->addr[pd2.sidx], nk->port[sidx]);
8344 pf_change_ap(&pd2, pd2.dst, &th->th_dport,
8345 &nk->addr[pd2.didx], nk->port[didx]);
8346 m_copyback(pd2.m, pd2.off, 8, (c_caddr_t)th);
8347 return (PF_AFRT);
8348 }
8349 #endif /* INET && INET6 */
8350
8351 if (PF_ANEQ(pd2.src,
8352 &nk->addr[pd2.sidx], pd2.af) ||
8353 nk->port[pd2.sidx] != th->th_sport)
8354 pf_change_icmp(pd2.src, &th->th_sport,
8355 daddr, &nk->addr[pd2.sidx],
8356 nk->port[pd2.sidx], NULL,
8357 pd2.ip_sum, icmpsum,
8358 pd->ip_sum, 0, pd2.af);
8359
8360 if (PF_ANEQ(pd2.dst,
8361 &nk->addr[pd2.didx], pd2.af) ||
8362 nk->port[pd2.didx] != th->th_dport)
8363 pf_change_icmp(pd2.dst, &th->th_dport,
8364 saddr, &nk->addr[pd2.didx],
8365 nk->port[pd2.didx], NULL,
8366 pd2.ip_sum, icmpsum,
8367 pd->ip_sum, 0, pd2.af);
8368 copyback = 1;
8369 }
8370
8371 if (copyback) {
8372 switch (pd2.af) {
8373 #ifdef INET
8374 case AF_INET:
8375 m_copyback(pd->m, pd->off, ICMP_MINLEN,
8376 (caddr_t )&pd->hdr.icmp);
8377 m_copyback(pd->m, ipoff2, sizeof(h2),
8378 (caddr_t )&h2);
8379 break;
8380 #endif /* INET */
8381 #ifdef INET6
8382 case AF_INET6:
8383 m_copyback(pd->m, pd->off,
8384 sizeof(struct icmp6_hdr),
8385 (caddr_t )&pd->hdr.icmp6);
8386 m_copyback(pd->m, ipoff2, sizeof(h2_6),
8387 (caddr_t )&h2_6);
8388 break;
8389 #endif /* INET6 */
8390 default:
8391 unhandled_af(pd->af);
8392 }
8393 m_copyback(pd->m, pd2.off, 8, (caddr_t)th);
8394 }
8395
8396 return (PF_PASS);
8397 break;
8398 }
8399 case IPPROTO_UDP: {
8400 struct udphdr *uh = &pd2.hdr.udp;
8401 int action;
8402
8403 if (!pf_pull_hdr(pd->m, pd2.off, uh, sizeof(*uh),
8404 reason, pd2.af)) {
8405 DPFPRINTF(PF_DEBUG_MISC,
8406 "pf: ICMP error message too short "
8407 "(udp)");
8408 return (PF_DROP);
8409 }
8410 pd2.pcksum = &pd2.hdr.udp.uh_sum;
8411
8412 key.af = pd2.af;
8413 key.proto = IPPROTO_UDP;
8414 pf_addrcpy(&key.addr[pd2.sidx], pd2.src, key.af);
8415 pf_addrcpy(&key.addr[pd2.didx], pd2.dst, key.af);
8416 key.port[pd2.sidx] = uh->uh_sport;
8417 key.port[pd2.didx] = uh->uh_dport;
8418
8419 action = pf_find_state(&pd2, &key, state);
8420 if (action != PF_MATCH)
8421 return (action);
8422
8423 /* translate source/destination address, if necessary */
8424 if ((*state)->key[PF_SK_WIRE] !=
8425 (*state)->key[PF_SK_STACK]) {
8426 struct pf_state_key *nk;
8427
8428 if (PF_REVERSED_KEY(*state, pd->af))
8429 nk = (*state)->key[pd->sidx];
8430 else
8431 nk = (*state)->key[pd->didx];
8432
8433 #if defined(INET) && defined(INET6)
8434 int afto, sidx, didx;
8435
8436 afto = pd->af != nk->af;
8437
8438 if (afto && (*state)->direction == PF_IN) {
8439 sidx = pd2.didx;
8440 didx = pd2.sidx;
8441 } else {
8442 sidx = pd2.sidx;
8443 didx = pd2.didx;
8444 }
8445
8446 if (afto) {
8447 if (pf_translate_icmp_af(nk->af,
8448 &pd->hdr.icmp))
8449 return (PF_DROP);
8450 m_copyback(pd->m, pd->off,
8451 sizeof(struct icmp6_hdr),
8452 (c_caddr_t)&pd->hdr.icmp6);
8453 if (pf_change_icmp_af(pd->m, ipoff2, pd,
8454 &pd2, &nk->addr[sidx],
8455 &nk->addr[didx], pd->af,
8456 nk->af))
8457 return (PF_DROP);
8458 pf_addrcpy(&pd->nsaddr,
8459 &nk->addr[pd2.sidx], nk->af);
8460 pf_addrcpy(&pd->ndaddr,
8461 &nk->addr[pd2.didx], nk->af);
8462 if (nk->af == AF_INET) {
8463 pd->proto = IPPROTO_ICMP;
8464 } else {
8465 pd->proto = IPPROTO_ICMPV6;
8466 /*
8467 * IPv4 becomes IPv6 so we must
8468 * copy IPv4 src addr to least
8469 * 32bits in IPv6 address to
8470 * keep traceroute/icmp
8471 * working.
8472 */
8473 pd->nsaddr.addr32[3] =
8474 pd->src->addr32[0];
8475 }
8476 pd->naf = pd2.naf = nk->af;
8477 pf_change_ap(&pd2, pd2.src, &uh->uh_sport,
8478 &nk->addr[pd2.sidx], nk->port[sidx]);
8479 pf_change_ap(&pd2, pd2.dst, &uh->uh_dport,
8480 &nk->addr[pd2.didx], nk->port[didx]);
8481 m_copyback(pd2.m, pd2.off, sizeof(*uh),
8482 (c_caddr_t)uh);
8483 return (PF_AFRT);
8484 }
8485 #endif /* INET && INET6 */
8486
8487 if (PF_ANEQ(pd2.src,
8488 &nk->addr[pd2.sidx], pd2.af) ||
8489 nk->port[pd2.sidx] != uh->uh_sport)
8490 pf_change_icmp(pd2.src, &uh->uh_sport,
8491 daddr, &nk->addr[pd2.sidx],
8492 nk->port[pd2.sidx], &uh->uh_sum,
8493 pd2.ip_sum, icmpsum,
8494 pd->ip_sum, 1, pd2.af);
8495
8496 if (PF_ANEQ(pd2.dst,
8497 &nk->addr[pd2.didx], pd2.af) ||
8498 nk->port[pd2.didx] != uh->uh_dport)
8499 pf_change_icmp(pd2.dst, &uh->uh_dport,
8500 saddr, &nk->addr[pd2.didx],
8501 nk->port[pd2.didx], &uh->uh_sum,
8502 pd2.ip_sum, icmpsum,
8503 pd->ip_sum, 1, pd2.af);
8504
8505 switch (pd2.af) {
8506 #ifdef INET
8507 case AF_INET:
8508 m_copyback(pd->m, pd->off, ICMP_MINLEN,
8509 (caddr_t )&pd->hdr.icmp);
8510 m_copyback(pd->m, ipoff2, sizeof(h2), (caddr_t)&h2);
8511 break;
8512 #endif /* INET */
8513 #ifdef INET6
8514 case AF_INET6:
8515 m_copyback(pd->m, pd->off,
8516 sizeof(struct icmp6_hdr),
8517 (caddr_t )&pd->hdr.icmp6);
8518 m_copyback(pd->m, ipoff2, sizeof(h2_6),
8519 (caddr_t )&h2_6);
8520 break;
8521 #endif /* INET6 */
8522 }
8523 m_copyback(pd->m, pd2.off, sizeof(*uh), (caddr_t)uh);
8524 }
8525 return (PF_PASS);
8526 break;
8527 }
8528 #ifdef INET
8529 case IPPROTO_SCTP: {
8530 struct sctphdr *sh = &pd2.hdr.sctp;
8531 struct pf_state_peer *src;
8532 int copyback = 0;
8533 int action;
8534
8535 if (! pf_pull_hdr(pd->m, pd2.off, sh, sizeof(*sh), reason,
8536 pd2.af)) {
8537 DPFPRINTF(PF_DEBUG_MISC,
8538 "pf: ICMP error message too short "
8539 "(sctp)");
8540 return (PF_DROP);
8541 }
8542 pd2.pcksum = &pd2.sctp_dummy_sum;
8543
8544 key.af = pd2.af;
8545 key.proto = IPPROTO_SCTP;
8546 pf_addrcpy(&key.addr[pd2.sidx], pd2.src, key.af);
8547 pf_addrcpy(&key.addr[pd2.didx], pd2.dst, key.af);
8548 key.port[pd2.sidx] = sh->src_port;
8549 key.port[pd2.didx] = sh->dest_port;
8550
8551 action = pf_find_state(&pd2, &key, state);
8552 if (action != PF_MATCH)
8553 return (action);
8554
8555 if (pd->dir == (*state)->direction) {
8556 if (PF_REVERSED_KEY(*state, pd->af))
8557 src = &(*state)->src;
8558 else
8559 src = &(*state)->dst;
8560 } else {
8561 if (PF_REVERSED_KEY(*state, pd->af))
8562 src = &(*state)->dst;
8563 else
8564 src = &(*state)->src;
8565 }
8566
8567 if (src->scrub->pfss_v_tag != sh->v_tag) {
8568 DPFPRINTF(PF_DEBUG_MISC,
8569 "pf: ICMP error message has incorrect "
8570 "SCTP v_tag");
8571 return (PF_DROP);
8572 }
8573
8574 /* translate source/destination address, if necessary */
8575 if ((*state)->key[PF_SK_WIRE] !=
8576 (*state)->key[PF_SK_STACK]) {
8577
8578 struct pf_state_key *nk;
8579
8580 if (PF_REVERSED_KEY(*state, pd->af))
8581 nk = (*state)->key[pd->sidx];
8582 else
8583 nk = (*state)->key[pd->didx];
8584
8585 #if defined(INET) && defined(INET6)
8586 int afto, sidx, didx;
8587
8588 afto = pd->af != nk->af;
8589
8590 if (afto && (*state)->direction == PF_IN) {
8591 sidx = pd2.didx;
8592 didx = pd2.sidx;
8593 } else {
8594 sidx = pd2.sidx;
8595 didx = pd2.didx;
8596 }
8597
8598 if (afto) {
8599 if (pf_translate_icmp_af(nk->af,
8600 &pd->hdr.icmp))
8601 return (PF_DROP);
8602 m_copyback(pd->m, pd->off,
8603 sizeof(struct icmp6_hdr),
8604 (c_caddr_t)&pd->hdr.icmp6);
8605 if (pf_change_icmp_af(pd->m, ipoff2, pd,
8606 &pd2, &nk->addr[sidx],
8607 &nk->addr[didx], pd->af,
8608 nk->af))
8609 return (PF_DROP);
8610 sh->src_port = nk->port[sidx];
8611 sh->dest_port = nk->port[didx];
8612 m_copyback(pd2.m, pd2.off, sizeof(*sh), (c_caddr_t)sh);
8613 pf_addrcpy(&pd->nsaddr,
8614 &nk->addr[pd2.sidx], nk->af);
8615 pf_addrcpy(&pd->ndaddr,
8616 &nk->addr[pd2.didx], nk->af);
8617 if (nk->af == AF_INET) {
8618 pd->proto = IPPROTO_ICMP;
8619 } else {
8620 pd->proto = IPPROTO_ICMPV6;
8621 /*
8622 * IPv4 becomes IPv6 so we must
8623 * copy IPv4 src addr to least
8624 * 32bits in IPv6 address to
8625 * keep traceroute/icmp
8626 * working.
8627 */
8628 pd->nsaddr.addr32[3] =
8629 pd->src->addr32[0];
8630 }
8631 pd->naf = nk->af;
8632 return (PF_AFRT);
8633 }
8634 #endif /* INET && INET6 */
8635
8636 if (PF_ANEQ(pd2.src,
8637 &nk->addr[pd2.sidx], pd2.af) ||
8638 nk->port[pd2.sidx] != sh->src_port)
8639 pf_change_icmp(pd2.src, &sh->src_port,
8640 daddr, &nk->addr[pd2.sidx],
8641 nk->port[pd2.sidx], NULL,
8642 pd2.ip_sum, icmpsum,
8643 pd->ip_sum, 0, pd2.af);
8644
8645 if (PF_ANEQ(pd2.dst,
8646 &nk->addr[pd2.didx], pd2.af) ||
8647 nk->port[pd2.didx] != sh->dest_port)
8648 pf_change_icmp(pd2.dst, &sh->dest_port,
8649 saddr, &nk->addr[pd2.didx],
8650 nk->port[pd2.didx], NULL,
8651 pd2.ip_sum, icmpsum,
8652 pd->ip_sum, 0, pd2.af);
8653 copyback = 1;
8654 }
8655
8656 if (copyback) {
8657 switch (pd2.af) {
8658 #ifdef INET
8659 case AF_INET:
8660 m_copyback(pd->m, pd->off, ICMP_MINLEN,
8661 (caddr_t )&pd->hdr.icmp);
8662 m_copyback(pd->m, ipoff2, sizeof(h2),
8663 (caddr_t )&h2);
8664 break;
8665 #endif /* INET */
8666 #ifdef INET6
8667 case AF_INET6:
8668 m_copyback(pd->m, pd->off,
8669 sizeof(struct icmp6_hdr),
8670 (caddr_t )&pd->hdr.icmp6);
8671 m_copyback(pd->m, ipoff2, sizeof(h2_6),
8672 (caddr_t )&h2_6);
8673 break;
8674 #endif /* INET6 */
8675 }
8676 m_copyback(pd->m, pd2.off, sizeof(*sh), (caddr_t)sh);
8677 }
8678
8679 return (PF_PASS);
8680 break;
8681 }
8682 case IPPROTO_ICMP: {
8683 struct icmp *iih = &pd2.hdr.icmp;
8684
8685 if (pd2.af != AF_INET) {
8686 REASON_SET(reason, PFRES_NORM);
8687 return (PF_DROP);
8688 }
8689
8690 if (!pf_pull_hdr(pd->m, pd2.off, iih, ICMP_MINLEN,
8691 reason, pd2.af)) {
8692 DPFPRINTF(PF_DEBUG_MISC,
8693 "pf: ICMP error message too short i"
8694 "(icmp)");
8695 return (PF_DROP);
8696 }
8697 pd2.pcksum = &pd2.hdr.icmp.icmp_cksum;
8698
8699 icmpid = iih->icmp_id;
8700 pf_icmp_mapping(&pd2, iih->icmp_type,
8701 &icmp_dir, &virtual_id, &virtual_type);
8702
8703 ret = pf_icmp_state_lookup(&key, &pd2, state,
8704 virtual_id, virtual_type, icmp_dir, &iidx, 0, 1);
8705 if (ret >= 0) {
8706 MPASS(*state == NULL);
8707 return (ret);
8708 }
8709
8710 /* translate source/destination address, if necessary */
8711 if ((*state)->key[PF_SK_WIRE] !=
8712 (*state)->key[PF_SK_STACK]) {
8713 struct pf_state_key *nk;
8714
8715 if (PF_REVERSED_KEY(*state, pd->af))
8716 nk = (*state)->key[pd->sidx];
8717 else
8718 nk = (*state)->key[pd->didx];
8719
8720 #if defined(INET) && defined(INET6)
8721 int afto, sidx, didx;
8722
8723 afto = pd->af != nk->af;
8724
8725 if (afto && (*state)->direction == PF_IN) {
8726 sidx = pd2.didx;
8727 didx = pd2.sidx;
8728 iidx = !iidx;
8729 } else {
8730 sidx = pd2.sidx;
8731 didx = pd2.didx;
8732 }
8733
8734 if (afto) {
8735 if (nk->af != AF_INET6)
8736 return (PF_DROP);
8737 if (pf_translate_icmp_af(nk->af,
8738 &pd->hdr.icmp))
8739 return (PF_DROP);
8740 m_copyback(pd->m, pd->off,
8741 sizeof(struct icmp6_hdr),
8742 (c_caddr_t)&pd->hdr.icmp6);
8743 if (pf_change_icmp_af(pd->m, ipoff2, pd,
8744 &pd2, &nk->addr[sidx],
8745 &nk->addr[didx], pd->af,
8746 nk->af))
8747 return (PF_DROP);
8748 pd->proto = IPPROTO_ICMPV6;
8749 if (pf_translate_icmp_af(nk->af, iih))
8750 return (PF_DROP);
8751 if (virtual_type == htons(ICMP_ECHO) &&
8752 nk->port[iidx] != iih->icmp_id)
8753 iih->icmp_id = nk->port[iidx];
8754 m_copyback(pd2.m, pd2.off, ICMP_MINLEN,
8755 (c_caddr_t)iih);
8756 pf_addrcpy(&pd->nsaddr,
8757 &nk->addr[pd2.sidx], nk->af);
8758 pf_addrcpy(&pd->ndaddr,
8759 &nk->addr[pd2.didx], nk->af);
8760 /*
8761 * IPv4 becomes IPv6 so we must copy
8762 * IPv4 src addr to least 32bits in
8763 * IPv6 address to keep traceroute
8764 * working.
8765 */
8766 pd->nsaddr.addr32[3] =
8767 pd->src->addr32[0];
8768 pd->naf = nk->af;
8769 return (PF_AFRT);
8770 }
8771 #endif /* INET && INET6 */
8772
8773 if (PF_ANEQ(pd2.src,
8774 &nk->addr[pd2.sidx], pd2.af) ||
8775 (virtual_type == htons(ICMP_ECHO) &&
8776 nk->port[iidx] != iih->icmp_id))
8777 pf_change_icmp(pd2.src,
8778 (virtual_type == htons(ICMP_ECHO)) ?
8779 &iih->icmp_id : NULL,
8780 daddr, &nk->addr[pd2.sidx],
8781 (virtual_type == htons(ICMP_ECHO)) ?
8782 nk->port[iidx] : 0, NULL,
8783 pd2.ip_sum, icmpsum,
8784 pd->ip_sum, 0, AF_INET);
8785
8786 if (PF_ANEQ(pd2.dst,
8787 &nk->addr[pd2.didx], pd2.af))
8788 pf_change_icmp(pd2.dst, NULL, NULL,
8789 &nk->addr[pd2.didx], 0, NULL,
8790 pd2.ip_sum, icmpsum, pd->ip_sum, 0,
8791 AF_INET);
8792
8793 m_copyback(pd->m, pd->off, ICMP_MINLEN, (caddr_t)&pd->hdr.icmp);
8794 m_copyback(pd->m, ipoff2, sizeof(h2), (caddr_t)&h2);
8795 m_copyback(pd->m, pd2.off, ICMP_MINLEN, (caddr_t)iih);
8796 }
8797 return (PF_PASS);
8798 break;
8799 }
8800 #endif /* INET */
8801 #ifdef INET6
8802 case IPPROTO_ICMPV6: {
8803 struct icmp6_hdr *iih = &pd2.hdr.icmp6;
8804
8805 if (pd2.af != AF_INET6) {
8806 REASON_SET(reason, PFRES_NORM);
8807 return (PF_DROP);
8808 }
8809
8810 if (!pf_pull_hdr(pd->m, pd2.off, iih,
8811 sizeof(struct icmp6_hdr), reason, pd2.af)) {
8812 DPFPRINTF(PF_DEBUG_MISC,
8813 "pf: ICMP error message too short "
8814 "(icmp6)");
8815 return (PF_DROP);
8816 }
8817 pd2.pcksum = &pd2.hdr.icmp6.icmp6_cksum;
8818
8819 pf_icmp_mapping(&pd2, iih->icmp6_type,
8820 &icmp_dir, &virtual_id, &virtual_type);
8821
8822 ret = pf_icmp_state_lookup(&key, &pd2, state,
8823 virtual_id, virtual_type, icmp_dir, &iidx, 0, 1);
8824 /* IPv6? try matching a multicast address */
8825 if (ret == PF_DROP && pd2.af == AF_INET6 &&
8826 icmp_dir == PF_OUT) {
8827 MPASS(*state == NULL);
8828 ret = pf_icmp_state_lookup(&key, &pd2,
8829 state, virtual_id, virtual_type,
8830 icmp_dir, &iidx, 1, 1);
8831 }
8832 if (ret >= 0) {
8833 MPASS(*state == NULL);
8834 return (ret);
8835 }
8836
8837 /* translate source/destination address, if necessary */
8838 if ((*state)->key[PF_SK_WIRE] !=
8839 (*state)->key[PF_SK_STACK]) {
8840 struct pf_state_key *nk;
8841
8842 if (PF_REVERSED_KEY(*state, pd->af))
8843 nk = (*state)->key[pd->sidx];
8844 else
8845 nk = (*state)->key[pd->didx];
8846
8847 #if defined(INET) && defined(INET6)
8848 int afto, sidx, didx;
8849
8850 afto = pd->af != nk->af;
8851
8852 if (afto && (*state)->direction == PF_IN) {
8853 sidx = pd2.didx;
8854 didx = pd2.sidx;
8855 iidx = !iidx;
8856 } else {
8857 sidx = pd2.sidx;
8858 didx = pd2.didx;
8859 }
8860
8861 if (afto) {
8862 if (nk->af != AF_INET)
8863 return (PF_DROP);
8864 if (pf_translate_icmp_af(nk->af,
8865 &pd->hdr.icmp))
8866 return (PF_DROP);
8867 m_copyback(pd->m, pd->off,
8868 sizeof(struct icmp6_hdr),
8869 (c_caddr_t)&pd->hdr.icmp6);
8870 if (pf_change_icmp_af(pd->m, ipoff2, pd,
8871 &pd2, &nk->addr[sidx],
8872 &nk->addr[didx], pd->af,
8873 nk->af))
8874 return (PF_DROP);
8875 pd->proto = IPPROTO_ICMP;
8876 if (pf_translate_icmp_af(nk->af, iih))
8877 return (PF_DROP);
8878 if (virtual_type ==
8879 htons(ICMP6_ECHO_REQUEST) &&
8880 nk->port[iidx] != iih->icmp6_id)
8881 iih->icmp6_id = nk->port[iidx];
8882 m_copyback(pd2.m, pd2.off,
8883 sizeof(struct icmp6_hdr), (c_caddr_t)iih);
8884 pf_addrcpy(&pd->nsaddr,
8885 &nk->addr[pd2.sidx], nk->af);
8886 pf_addrcpy(&pd->ndaddr,
8887 &nk->addr[pd2.didx], nk->af);
8888 pd->naf = nk->af;
8889 return (PF_AFRT);
8890 }
8891 #endif /* INET && INET6 */
8892
8893 if (PF_ANEQ(pd2.src,
8894 &nk->addr[pd2.sidx], pd2.af) ||
8895 ((virtual_type == htons(ICMP6_ECHO_REQUEST)) &&
8896 nk->port[pd2.sidx] != iih->icmp6_id))
8897 pf_change_icmp(pd2.src,
8898 (virtual_type == htons(ICMP6_ECHO_REQUEST))
8899 ? &iih->icmp6_id : NULL,
8900 daddr, &nk->addr[pd2.sidx],
8901 (virtual_type == htons(ICMP6_ECHO_REQUEST))
8902 ? nk->port[iidx] : 0, NULL,
8903 pd2.ip_sum, icmpsum,
8904 pd->ip_sum, 0, AF_INET6);
8905
8906 if (PF_ANEQ(pd2.dst,
8907 &nk->addr[pd2.didx], pd2.af))
8908 pf_change_icmp(pd2.dst, NULL, NULL,
8909 &nk->addr[pd2.didx], 0, NULL,
8910 pd2.ip_sum, icmpsum,
8911 pd->ip_sum, 0, AF_INET6);
8912
8913 m_copyback(pd->m, pd->off, sizeof(struct icmp6_hdr),
8914 (caddr_t)&pd->hdr.icmp6);
8915 m_copyback(pd->m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
8916 m_copyback(pd->m, pd2.off, sizeof(struct icmp6_hdr),
8917 (caddr_t)iih);
8918 }
8919 return (PF_PASS);
8920 break;
8921 }
8922 #endif /* INET6 */
8923 default: {
8924 int action;
8925
8926 /*
8927 * Placeholder value, so future calls to pf_change_ap()
8928 * don't try to update a NULL checksum pointer.
8929 */
8930 pd->pcksum = &pd->sctp_dummy_sum;
8931 key.af = pd2.af;
8932 key.proto = pd2.proto;
8933 pf_addrcpy(&key.addr[pd2.sidx], pd2.src, key.af);
8934 pf_addrcpy(&key.addr[pd2.didx], pd2.dst, key.af);
8935 key.port[0] = key.port[1] = 0;
8936
8937 action = pf_find_state(&pd2, &key, state);
8938 if (action != PF_MATCH)
8939 return (action);
8940
8941 /* translate source/destination address, if necessary */
8942 if ((*state)->key[PF_SK_WIRE] !=
8943 (*state)->key[PF_SK_STACK]) {
8944 struct pf_state_key *nk =
8945 (*state)->key[pd->didx];
8946
8947 if (PF_ANEQ(pd2.src,
8948 &nk->addr[pd2.sidx], pd2.af))
8949 pf_change_icmp(pd2.src, NULL, daddr,
8950 &nk->addr[pd2.sidx], 0, NULL,
8951 pd2.ip_sum, icmpsum,
8952 pd->ip_sum, 0, pd2.af);
8953
8954 if (PF_ANEQ(pd2.dst,
8955 &nk->addr[pd2.didx], pd2.af))
8956 pf_change_icmp(pd2.dst, NULL, saddr,
8957 &nk->addr[pd2.didx], 0, NULL,
8958 pd2.ip_sum, icmpsum,
8959 pd->ip_sum, 0, pd2.af);
8960
8961 switch (pd2.af) {
8962 #ifdef INET
8963 case AF_INET:
8964 m_copyback(pd->m, pd->off, ICMP_MINLEN,
8965 (caddr_t)&pd->hdr.icmp);
8966 m_copyback(pd->m, ipoff2, sizeof(h2), (caddr_t)&h2);
8967 break;
8968 #endif /* INET */
8969 #ifdef INET6
8970 case AF_INET6:
8971 m_copyback(pd->m, pd->off,
8972 sizeof(struct icmp6_hdr),
8973 (caddr_t )&pd->hdr.icmp6);
8974 m_copyback(pd->m, ipoff2, sizeof(h2_6),
8975 (caddr_t )&h2_6);
8976 break;
8977 #endif /* INET6 */
8978 }
8979 }
8980 return (PF_PASS);
8981 break;
8982 }
8983 }
8984 }
8985 }
8986
8987 /*
8988 * ipoff and off are measured from the start of the mbuf chain.
8989 * h must be at "ipoff" on the mbuf chain.
8990 */
8991 void *
pf_pull_hdr(const struct mbuf * m,int off,void * p,int len,u_short * reasonp,sa_family_t af)8992 pf_pull_hdr(const struct mbuf *m, int off, void *p, int len,
8993 u_short *reasonp, sa_family_t af)
8994 {
8995 int iplen = 0;
8996 switch (af) {
8997 #ifdef INET
8998 case AF_INET: {
8999 const struct ip *h = mtod(m, struct ip *);
9000 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
9001
9002 if (fragoff) {
9003 REASON_SET(reasonp, PFRES_FRAG);
9004 return (NULL);
9005 }
9006 iplen = ntohs(h->ip_len);
9007 break;
9008 }
9009 #endif /* INET */
9010 #ifdef INET6
9011 case AF_INET6: {
9012 const struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
9013
9014 iplen = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
9015 break;
9016 }
9017 #endif /* INET6 */
9018 }
9019 if (m->m_pkthdr.len < off + len || iplen < off + len) {
9020 REASON_SET(reasonp, PFRES_SHORT);
9021 return (NULL);
9022 }
9023 m_copydata(m, off, len, p);
9024 return (p);
9025 }
9026
9027 int
pf_routable(struct pf_addr * addr,sa_family_t af,struct pfi_kkif * kif,int rtableid)9028 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kkif *kif,
9029 int rtableid)
9030 {
9031 struct ifnet *ifp;
9032
9033 /*
9034 * Skip check for addresses with embedded interface scope,
9035 * as they would always match anyway.
9036 */
9037 if (af == AF_INET6 && IN6_IS_SCOPE_EMBED(&addr->v6))
9038 return (1);
9039
9040 if (af != AF_INET && af != AF_INET6)
9041 return (0);
9042
9043 if (kif == V_pfi_all)
9044 return (1);
9045
9046 /* Skip checks for ipsec interfaces */
9047 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
9048 return (1);
9049
9050 ifp = (kif != NULL) ? kif->pfik_ifp : NULL;
9051
9052 switch (af) {
9053 #ifdef INET6
9054 case AF_INET6:
9055 return (fib6_check_urpf(rtableid, &addr->v6, 0, NHR_NONE,
9056 ifp));
9057 #endif /* INET6 */
9058 #ifdef INET
9059 case AF_INET:
9060 return (fib4_check_urpf(rtableid, addr->v4, 0, NHR_NONE,
9061 ifp));
9062 #endif /* INET */
9063 }
9064
9065 return (0);
9066 }
9067
9068 #ifdef INET
9069 static int
pf_route(struct pf_krule * r,struct ifnet * oifp,struct pf_kstate * s,struct pf_pdesc * pd,struct inpcb * inp)9070 pf_route(struct pf_krule *r, struct ifnet *oifp,
9071 struct pf_kstate *s, struct pf_pdesc *pd, struct inpcb *inp)
9072 {
9073 struct mbuf *m0, *m1, *md;
9074 struct route_in6 ro;
9075 union sockaddr_union rt_gw;
9076 const union sockaddr_union *gw = (const union sockaddr_union *)&ro.ro_dst;
9077 union sockaddr_union *dst;
9078 struct ip *ip;
9079 struct ifnet *ifp = NULL;
9080 int error = 0;
9081 uint16_t ip_len, ip_off;
9082 uint16_t tmp;
9083 int r_dir;
9084 bool skip_test = false;
9085 int action = PF_PASS;
9086
9087 KASSERT(pd->m && r && oifp, ("%s: invalid parameters", __func__));
9088
9089 SDT_PROBE4(pf, ip, route_to, entry, pd->m, pd, s, oifp);
9090
9091 if (s) {
9092 r_dir = s->direction;
9093 } else {
9094 r_dir = r->direction;
9095 }
9096
9097 KASSERT(pd->dir == PF_IN || pd->dir == PF_OUT ||
9098 r_dir == PF_IN || r_dir == PF_OUT, ("%s: invalid direction",
9099 __func__));
9100
9101 if ((pd->pf_mtag == NULL &&
9102 ((pd->pf_mtag = pf_get_mtag(pd->m)) == NULL)) ||
9103 pd->pf_mtag->routed++ > 3) {
9104 m0 = pd->m;
9105 pd->m = NULL;
9106 SDT_PROBE1(pf, ip, route_to, drop, __LINE__);
9107 action = PF_DROP;
9108 goto bad_locked;
9109 }
9110
9111 if (pd->act.rt_kif != NULL)
9112 ifp = pd->act.rt_kif->pfik_ifp;
9113
9114 if (pd->act.rt == PF_DUPTO) {
9115 if ((pd->pf_mtag->flags & PF_MTAG_FLAG_DUPLICATED)) {
9116 if (s != NULL) {
9117 PF_STATE_UNLOCK(s);
9118 }
9119 if (ifp == oifp) {
9120 /* When the 2nd interface is not skipped */
9121 return (action);
9122 } else {
9123 m0 = pd->m;
9124 pd->m = NULL;
9125 SDT_PROBE1(pf, ip, route_to, drop, __LINE__);
9126 action = PF_DROP;
9127 goto bad;
9128 }
9129 } else {
9130 pd->pf_mtag->flags |= PF_MTAG_FLAG_DUPLICATED;
9131 if (((m0 = m_dup(pd->m, M_NOWAIT)) == NULL)) {
9132 if (s)
9133 PF_STATE_UNLOCK(s);
9134 return (action);
9135 }
9136 }
9137 } else {
9138 if ((pd->act.rt == PF_REPLYTO) == (r_dir == pd->dir)) {
9139 if (pd->af == pd->naf) {
9140 pf_dummynet(pd, s, r, &pd->m);
9141 if (s)
9142 PF_STATE_UNLOCK(s);
9143 return (action);
9144 } else {
9145 if (r_dir == PF_IN) {
9146 skip_test = true;
9147 }
9148 }
9149 }
9150
9151 /*
9152 * If we're actually doing route-to and af-to and are in the
9153 * reply direction.
9154 */
9155 if (pd->act.rt_kif && pd->act.rt_kif->pfik_ifp &&
9156 pd->af != pd->naf) {
9157 if (pd->act.rt == PF_ROUTETO && r->naf != AF_INET) {
9158 /* Un-set ifp so we do a plain route lookup. */
9159 ifp = NULL;
9160 }
9161 if (pd->act.rt == PF_REPLYTO && r->naf != AF_INET6) {
9162 /* Un-set ifp so we do a plain route lookup. */
9163 ifp = NULL;
9164 }
9165 }
9166 m0 = pd->m;
9167 }
9168
9169 ip = mtod(m0, struct ip *);
9170
9171 bzero(&ro, sizeof(ro));
9172 dst = (union sockaddr_union *)&ro.ro_dst;
9173 dst->sin.sin_family = AF_INET;
9174 dst->sin.sin_len = sizeof(struct sockaddr_in);
9175 dst->sin.sin_addr = ip->ip_dst;
9176 if (ifp) { /* Only needed in forward direction and route-to */
9177 bzero(&rt_gw, sizeof(rt_gw));
9178 ro.ro_flags |= RT_HAS_GW;
9179 gw = &rt_gw;
9180 switch (pd->act.rt_af) {
9181 #ifdef INET
9182 case AF_INET:
9183 rt_gw.sin.sin_family = AF_INET;
9184 rt_gw.sin.sin_len = sizeof(struct sockaddr_in);
9185 rt_gw.sin.sin_addr.s_addr = pd->act.rt_addr.v4.s_addr;
9186 break;
9187 #endif /* INET */
9188 #ifdef INET6
9189 case AF_INET6:
9190 rt_gw.sin6.sin6_family = AF_INET6;
9191 rt_gw.sin6.sin6_len = sizeof(struct sockaddr_in6);
9192 pf_addrcpy((struct pf_addr *)&rt_gw.sin6.sin6_addr,
9193 &pd->act.rt_addr, AF_INET6);
9194 break;
9195 #endif /* INET6 */
9196 default:
9197 /* Normal af-to without route-to */
9198 break;
9199 }
9200 }
9201
9202 if (pd->dir == PF_IN) {
9203 if (ip->ip_ttl <= IPTTLDEC) {
9204 if (r->rt != PF_DUPTO && pd->naf == pd->af)
9205 pf_send_icmp(m0, ICMP_TIMXCEED,
9206 ICMP_TIMXCEED_INTRANS, 0, pd->af, r,
9207 pd->act.rtableid);
9208 action = PF_DROP;
9209 goto bad_locked;
9210 }
9211 ip->ip_ttl -= IPTTLDEC;
9212 }
9213
9214 if (s != NULL) {
9215 if (ifp == NULL && (pd->af != pd->naf)) {
9216 /* We're in the AFTO case. Do a route lookup. */
9217 const struct nhop_object *nh;
9218 nh = fib4_lookup(M_GETFIB(m0), ip->ip_dst, 0, NHR_NONE, 0);
9219 if (nh) {
9220 ifp = nh->nh_ifp;
9221
9222 /* Use the gateway if needed. */
9223 if (nh->nh_flags & NHF_GATEWAY) {
9224 gw = (const union sockaddr_union *)&nh->gw_sa;
9225 ro.ro_flags |= RT_HAS_GW;
9226 } else {
9227 dst->sin.sin_addr = ip->ip_dst;
9228 }
9229 }
9230 }
9231 PF_STATE_UNLOCK(s);
9232 }
9233
9234 /* It must have been either set from rt_af or from fib4_lookup */
9235 KASSERT(gw->sin.sin_family != 0, ("%s: gw address family undetermined", __func__));
9236
9237 if (ifp == NULL) {
9238 m0 = pd->m;
9239 pd->m = NULL;
9240 action = PF_DROP;
9241 SDT_PROBE1(pf, ip, route_to, drop, __LINE__);
9242 goto bad;
9243 }
9244
9245 /*
9246 * Bind to the correct interface if we're if-bound. We don't know which
9247 * interface that will be until here, so we've inserted the state
9248 * on V_pf_all. Fix that now.
9249 */
9250 if (s != NULL && s->kif == V_pfi_all && r->rule_flag & PFRULE_IFBOUND) {
9251 /* Verify that we're here because of BOUND_IFACE */
9252 MPASS(r->rt == PF_REPLYTO || (pd->af != pd->naf && s->direction == PF_IN));
9253 s->kif = ifp->if_pf_kif;
9254 if (pd->act.rt == PF_REPLYTO) {
9255 s->orig_kif = oifp->if_pf_kif;
9256 }
9257 }
9258
9259 if (r->rt == PF_DUPTO || (pd->af != pd->naf && s->direction == PF_IN))
9260 skip_test = true;
9261
9262 if (pd->dir == PF_IN) {
9263 if (skip_test) {
9264 struct pfi_kkif *out_kif = (struct pfi_kkif *)ifp->if_pf_kif;
9265 MPASS(s != NULL);
9266 pf_counter_u64_critical_enter();
9267 pf_counter_u64_add_protected(
9268 &out_kif->pfik_bytes[pd->naf == AF_INET6][1]
9269 [action != PF_PASS && action != PF_AFRT], pd->tot_len);
9270 pf_counter_u64_add_protected(
9271 &out_kif->pfik_packets[pd->naf == AF_INET6][1]
9272 [action != PF_PASS && action != PF_AFRT], 1);
9273 pf_counter_u64_critical_exit();
9274 } else {
9275 if (pf_test(AF_INET, PF_OUT, PFIL_FWD, ifp, &m0, inp,
9276 &pd->act) != PF_PASS) {
9277 action = PF_DROP;
9278 SDT_PROBE1(pf, ip, route_to, drop, __LINE__);
9279 goto bad;
9280 } else if (m0 == NULL) {
9281 action = PF_DROP;
9282 SDT_PROBE1(pf, ip, route_to, drop, __LINE__);
9283 goto done;
9284 }
9285 if (m0->m_len < sizeof(struct ip)) {
9286 DPFPRINTF(PF_DEBUG_URGENT,
9287 "%s: m0->m_len < sizeof(struct ip)", __func__);
9288 SDT_PROBE1(pf, ip, route_to, drop, __LINE__);
9289 action = PF_DROP;
9290 goto bad;
9291 }
9292 ip = mtod(m0, struct ip *);
9293 }
9294 }
9295
9296 if (ifp->if_flags & IFF_LOOPBACK)
9297 m0->m_flags |= M_SKIP_FIREWALL;
9298
9299 ip_len = ntohs(ip->ip_len);
9300 ip_off = ntohs(ip->ip_off);
9301
9302 /* Copied from FreeBSD 10.0-CURRENT ip_output. */
9303 m0->m_pkthdr.csum_flags |= CSUM_IP;
9304 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
9305 in_delayed_cksum(m0);
9306 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
9307 }
9308 if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
9309 pf_sctp_checksum(m0, (uint32_t)(ip->ip_hl << 2));
9310 m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
9311 }
9312
9313 if (pd->dir == PF_IN) {
9314 /*
9315 * Make sure dummynet gets the correct direction, in case it needs to
9316 * re-inject later.
9317 */
9318 pd->dir = PF_OUT;
9319
9320 /*
9321 * The following processing is actually the rest of the inbound processing, even
9322 * though we've marked it as outbound (so we don't look through dummynet) and it
9323 * happens after the outbound processing (pf_test(PF_OUT) above).
9324 * Swap the dummynet pipe numbers, because it's going to come to the wrong
9325 * conclusion about what direction it's processing, and we can't fix it or it
9326 * will re-inject incorrectly. Swapping the pipe numbers means that its incorrect
9327 * decision will pick the right pipe, and everything will mostly work as expected.
9328 */
9329 tmp = pd->act.dnrpipe;
9330 pd->act.dnrpipe = pd->act.dnpipe;
9331 pd->act.dnpipe = tmp;
9332 }
9333
9334 /*
9335 * If small enough for interface, or the interface will take
9336 * care of the fragmentation for us, we can just send directly.
9337 */
9338 if (ip_len <= ifp->if_mtu ||
9339 (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0) {
9340 ip->ip_sum = 0;
9341 if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
9342 ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
9343 m0->m_pkthdr.csum_flags &= ~CSUM_IP;
9344 }
9345 m_clrprotoflags(m0); /* Avoid confusing lower layers. */
9346
9347 md = m0;
9348 error = pf_dummynet_route(pd, s, r, ifp,
9349 (const struct sockaddr *)gw, &md);
9350 if (md != NULL) {
9351 error = (*ifp->if_output)(ifp, md,
9352 (const struct sockaddr *)gw, (struct route *)&ro);
9353 SDT_PROBE2(pf, ip, route_to, output, ifp, error);
9354 }
9355 goto done;
9356 }
9357
9358 /* Balk when DF bit is set or the interface didn't support TSO. */
9359 if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
9360 error = EMSGSIZE;
9361 KMOD_IPSTAT_INC(ips_cantfrag);
9362 if (pd->act.rt != PF_DUPTO) {
9363 if (s && s->nat_rule != NULL) {
9364 MPASS(m0 == pd->m);
9365 PACKET_UNDO_NAT(pd,
9366 (ip->ip_hl << 2) + (ip_off & IP_OFFMASK),
9367 s);
9368 }
9369
9370 pf_send_icmp(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG,
9371 ifp->if_mtu, pd->af, r, pd->act.rtableid);
9372 }
9373 SDT_PROBE1(pf, ip, route_to, drop, __LINE__);
9374 action = PF_DROP;
9375 goto bad;
9376 }
9377
9378 error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
9379 if (error) {
9380 SDT_PROBE1(pf, ip, route_to, drop, __LINE__);
9381 action = PF_DROP;
9382 goto bad;
9383 }
9384
9385 for (; m0; m0 = m1) {
9386 m1 = m0->m_nextpkt;
9387 m0->m_nextpkt = NULL;
9388 if (error == 0) {
9389 m_clrprotoflags(m0);
9390 md = m0;
9391 pd->pf_mtag = pf_find_mtag(md);
9392 error = pf_dummynet_route(pd, s, r, ifp,
9393 (const struct sockaddr *)gw, &md);
9394 if (md != NULL) {
9395 error = (*ifp->if_output)(ifp, md,
9396 (const struct sockaddr *)gw,
9397 (struct route *)&ro);
9398 SDT_PROBE2(pf, ip, route_to, output, ifp, error);
9399 }
9400 } else
9401 m_freem(m0);
9402 }
9403
9404 if (error == 0)
9405 KMOD_IPSTAT_INC(ips_fragmented);
9406
9407 done:
9408 if (pd->act.rt != PF_DUPTO)
9409 pd->m = NULL;
9410 else
9411 action = PF_PASS;
9412 return (action);
9413
9414 bad_locked:
9415 if (s)
9416 PF_STATE_UNLOCK(s);
9417 bad:
9418 m_freem(m0);
9419 goto done;
9420 }
9421 #endif /* INET */
9422
9423 #ifdef INET6
9424 static int
pf_route6(struct pf_krule * r,struct ifnet * oifp,struct pf_kstate * s,struct pf_pdesc * pd,struct inpcb * inp)9425 pf_route6(struct pf_krule *r, struct ifnet *oifp,
9426 struct pf_kstate *s, struct pf_pdesc *pd, struct inpcb *inp)
9427 {
9428 struct mbuf *m0, *md;
9429 struct m_tag *mtag;
9430 struct sockaddr_in6 dst;
9431 struct ip6_hdr *ip6;
9432 struct ifnet *ifp = NULL;
9433 int r_dir;
9434 bool skip_test = false;
9435 int action = PF_PASS;
9436
9437 KASSERT(pd->m && r && oifp, ("%s: invalid parameters", __func__));
9438
9439 SDT_PROBE4(pf, ip6, route_to, entry, pd->m, pd, s, oifp);
9440
9441 if (s) {
9442 r_dir = s->direction;
9443 } else {
9444 r_dir = r->direction;
9445 }
9446
9447 KASSERT(pd->dir == PF_IN || pd->dir == PF_OUT ||
9448 r_dir == PF_IN || r_dir == PF_OUT, ("%s: invalid direction",
9449 __func__));
9450
9451 if ((pd->pf_mtag == NULL &&
9452 ((pd->pf_mtag = pf_get_mtag(pd->m)) == NULL)) ||
9453 pd->pf_mtag->routed++ > 3) {
9454 m0 = pd->m;
9455 pd->m = NULL;
9456 action = PF_DROP;
9457 SDT_PROBE1(pf, ip6, route_to, drop, __LINE__);
9458 goto bad_locked;
9459 }
9460
9461 if (pd->act.rt_kif != NULL)
9462 ifp = pd->act.rt_kif->pfik_ifp;
9463
9464 if (pd->act.rt == PF_DUPTO) {
9465 if ((pd->pf_mtag->flags & PF_MTAG_FLAG_DUPLICATED)) {
9466 if (s != NULL) {
9467 PF_STATE_UNLOCK(s);
9468 }
9469 if (ifp == oifp) {
9470 /* When the 2nd interface is not skipped */
9471 return (action);
9472 } else {
9473 m0 = pd->m;
9474 pd->m = NULL;
9475 action = PF_DROP;
9476 SDT_PROBE1(pf, ip6, route_to, drop, __LINE__);
9477 goto bad;
9478 }
9479 } else {
9480 pd->pf_mtag->flags |= PF_MTAG_FLAG_DUPLICATED;
9481 if (((m0 = m_dup(pd->m, M_NOWAIT)) == NULL)) {
9482 if (s)
9483 PF_STATE_UNLOCK(s);
9484 return (action);
9485 }
9486 }
9487 } else {
9488 if ((pd->act.rt == PF_REPLYTO) == (r_dir == pd->dir)) {
9489 if (pd->af == pd->naf) {
9490 pf_dummynet(pd, s, r, &pd->m);
9491 if (s)
9492 PF_STATE_UNLOCK(s);
9493 return (action);
9494 } else {
9495 if (r_dir == PF_IN) {
9496 skip_test = true;
9497 }
9498 }
9499 }
9500
9501 /*
9502 * If we're actually doing route-to and af-to and are in the
9503 * reply direction.
9504 */
9505 if (pd->act.rt_kif && pd->act.rt_kif->pfik_ifp &&
9506 pd->af != pd->naf) {
9507 if (pd->act.rt == PF_ROUTETO && r->naf != AF_INET6) {
9508 /* Un-set ifp so we do a plain route lookup. */
9509 ifp = NULL;
9510 }
9511 if (pd->act.rt == PF_REPLYTO && r->naf != AF_INET) {
9512 /* Un-set ifp so we do a plain route lookup. */
9513 ifp = NULL;
9514 }
9515 }
9516 m0 = pd->m;
9517 }
9518
9519 ip6 = mtod(m0, struct ip6_hdr *);
9520
9521 bzero(&dst, sizeof(dst));
9522 dst.sin6_family = AF_INET6;
9523 dst.sin6_len = sizeof(dst);
9524 pf_addrcpy((struct pf_addr *)&dst.sin6_addr, &pd->act.rt_addr,
9525 AF_INET6);
9526
9527 if (pd->dir == PF_IN) {
9528 if (ip6->ip6_hlim <= IPV6_HLIMDEC) {
9529 if (r->rt != PF_DUPTO && pd->naf == pd->af)
9530 pf_send_icmp(m0, ICMP6_TIME_EXCEEDED,
9531 ICMP6_TIME_EXCEED_TRANSIT, 0, pd->af, r,
9532 pd->act.rtableid);
9533 action = PF_DROP;
9534 goto bad_locked;
9535 }
9536 ip6->ip6_hlim -= IPV6_HLIMDEC;
9537 }
9538
9539 if (s != NULL) {
9540 if (ifp == NULL && (pd->af != pd->naf)) {
9541 const struct nhop_object *nh;
9542 nh = fib6_lookup(M_GETFIB(m0), &ip6->ip6_dst, 0, NHR_NONE, 0);
9543 if (nh) {
9544 ifp = nh->nh_ifp;
9545
9546 /* Use the gateway if needed. */
9547 if (nh->nh_flags & NHF_GATEWAY)
9548 bcopy(&nh->gw6_sa.sin6_addr, &dst.sin6_addr,
9549 sizeof(dst.sin6_addr));
9550 else
9551 dst.sin6_addr = ip6->ip6_dst;
9552 }
9553 }
9554 PF_STATE_UNLOCK(s);
9555 }
9556
9557 if (pd->af != pd->naf) {
9558 struct udphdr *uh = &pd->hdr.udp;
9559
9560 if (pd->proto == IPPROTO_UDP && uh->uh_sum == 0) {
9561 uh->uh_sum = in6_cksum_pseudo(ip6,
9562 ntohs(uh->uh_ulen), IPPROTO_UDP, 0);
9563 m_copyback(m0, pd->off, sizeof(*uh), pd->hdr.any);
9564 }
9565 }
9566
9567 if (ifp == NULL) {
9568 m0 = pd->m;
9569 pd->m = NULL;
9570 action = PF_DROP;
9571 SDT_PROBE1(pf, ip6, route_to, drop, __LINE__);
9572 goto bad;
9573 }
9574
9575 /*
9576 * Bind to the correct interface if we're if-bound. We don't know which
9577 * interface that will be until here, so we've inserted the state
9578 * on V_pf_all. Fix that now.
9579 */
9580 if (s != NULL && s->kif == V_pfi_all && r->rule_flag & PFRULE_IFBOUND) {
9581 /* Verify that we're here because of BOUND_IFACE */
9582 MPASS(r->rt == PF_REPLYTO || (pd->af != pd->naf && s->direction == PF_IN));
9583 s->kif = ifp->if_pf_kif;
9584 if (pd->act.rt == PF_REPLYTO) {
9585 s->orig_kif = oifp->if_pf_kif;
9586 }
9587 }
9588
9589 if (r->rt == PF_DUPTO || (pd->af != pd->naf && s->direction == PF_IN))
9590 skip_test = true;
9591
9592 if (pd->dir == PF_IN) {
9593 if (skip_test) {
9594 struct pfi_kkif *out_kif = (struct pfi_kkif *)ifp->if_pf_kif;
9595 MPASS(s != NULL);
9596 pf_counter_u64_critical_enter();
9597 pf_counter_u64_add_protected(
9598 &out_kif->pfik_bytes[pd->naf == AF_INET6][1]
9599 [action != PF_PASS && action != PF_AFRT], pd->tot_len);
9600 pf_counter_u64_add_protected(
9601 &out_kif->pfik_packets[pd->naf == AF_INET6][1]
9602 [action != PF_PASS && action != PF_AFRT], 1);
9603 pf_counter_u64_critical_exit();
9604 } else {
9605 if (pf_test(AF_INET6, PF_OUT, PFIL_FWD | PF_PFIL_NOREFRAGMENT,
9606 ifp, &m0, inp, &pd->act) != PF_PASS) {
9607 action = PF_DROP;
9608 SDT_PROBE1(pf, ip6, route_to, drop, __LINE__);
9609 goto bad;
9610 } else if (m0 == NULL) {
9611 action = PF_DROP;
9612 SDT_PROBE1(pf, ip6, route_to, drop, __LINE__);
9613 goto done;
9614 }
9615 if (m0->m_len < sizeof(struct ip6_hdr)) {
9616 DPFPRINTF(PF_DEBUG_URGENT,
9617 "%s: m0->m_len < sizeof(struct ip6_hdr)",
9618 __func__);
9619 action = PF_DROP;
9620 SDT_PROBE1(pf, ip6, route_to, drop, __LINE__);
9621 goto bad;
9622 }
9623 ip6 = mtod(m0, struct ip6_hdr *);
9624 }
9625 }
9626
9627 if (ifp->if_flags & IFF_LOOPBACK)
9628 m0->m_flags |= M_SKIP_FIREWALL;
9629
9630 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6 &
9631 ~ifp->if_hwassist) {
9632 uint32_t plen = m0->m_pkthdr.len - sizeof(*ip6);
9633 in6_delayed_cksum(m0, plen, sizeof(struct ip6_hdr));
9634 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
9635 }
9636
9637 if (pd->dir == PF_IN) {
9638 uint16_t tmp;
9639 /*
9640 * Make sure dummynet gets the correct direction, in case it needs to
9641 * re-inject later.
9642 */
9643 pd->dir = PF_OUT;
9644
9645 /*
9646 * The following processing is actually the rest of the inbound processing, even
9647 * though we've marked it as outbound (so we don't look through dummynet) and it
9648 * happens after the outbound processing (pf_test(PF_OUT) above).
9649 * Swap the dummynet pipe numbers, because it's going to come to the wrong
9650 * conclusion about what direction it's processing, and we can't fix it or it
9651 * will re-inject incorrectly. Swapping the pipe numbers means that its incorrect
9652 * decision will pick the right pipe, and everything will mostly work as expected.
9653 */
9654 tmp = pd->act.dnrpipe;
9655 pd->act.dnrpipe = pd->act.dnpipe;
9656 pd->act.dnpipe = tmp;
9657 }
9658
9659 /*
9660 * If the packet is too large for the outgoing interface,
9661 * send back an icmp6 error.
9662 */
9663 if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
9664 dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
9665 mtag = m_tag_find(m0, PACKET_TAG_PF_REASSEMBLED, NULL);
9666 if (mtag != NULL) {
9667 int ret __sdt_used;
9668 ret = pf_refragment6(ifp, &m0, mtag, ifp, true);
9669 SDT_PROBE2(pf, ip6, route_to, output, ifp, ret);
9670 goto done;
9671 }
9672
9673 if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu) {
9674 md = m0;
9675 pf_dummynet_route(pd, s, r, ifp, sintosa(&dst), &md);
9676 if (md != NULL) {
9677 int ret __sdt_used;
9678 ret = nd6_output_ifp(ifp, ifp, md, &dst, NULL);
9679 SDT_PROBE2(pf, ip6, route_to, output, ifp, ret);
9680 }
9681 }
9682 else {
9683 in6_ifstat_inc(ifp, ifs6_in_toobig);
9684 if (pd->act.rt != PF_DUPTO) {
9685 if (s && s->nat_rule != NULL) {
9686 MPASS(m0 == pd->m);
9687 PACKET_UNDO_NAT(pd,
9688 ((caddr_t)ip6 - m0->m_data) +
9689 sizeof(struct ip6_hdr), s);
9690 }
9691
9692 if (r->rt != PF_DUPTO)
9693 pf_send_icmp(m0, ICMP6_PACKET_TOO_BIG, 0,
9694 ifp->if_mtu, pd->af, r, pd->act.rtableid);
9695 }
9696 action = PF_DROP;
9697 SDT_PROBE1(pf, ip6, route_to, drop, __LINE__);
9698 goto bad;
9699 }
9700
9701 done:
9702 if (pd->act.rt != PF_DUPTO)
9703 pd->m = NULL;
9704 else
9705 action = PF_PASS;
9706 return (action);
9707
9708 bad_locked:
9709 if (s)
9710 PF_STATE_UNLOCK(s);
9711 bad:
9712 m_freem(m0);
9713 goto done;
9714 }
9715 #endif /* INET6 */
9716
9717 /*
9718 * FreeBSD supports cksum offloads for the following drivers.
9719 * em(4), fxp(4), lge(4), nge(4), re(4), ti(4), txp(4), xl(4)
9720 *
9721 * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
9722 * network driver performed cksum including pseudo header, need to verify
9723 * csum_data
9724 * CSUM_DATA_VALID :
9725 * network driver performed cksum, needs to additional pseudo header
9726 * cksum computation with partial csum_data(i.e. lack of H/W support for
9727 * pseudo header, for instance sk(4) and possibly gem(4))
9728 *
9729 * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
9730 * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
9731 * TCP/UDP layer.
9732 * Also, set csum_data to 0xffff to force cksum validation.
9733 */
9734 static int
pf_check_proto_cksum(struct mbuf * m,int off,int len,u_int8_t p,sa_family_t af)9735 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
9736 {
9737 u_int16_t sum = 0;
9738 int hw_assist = 0;
9739 struct ip *ip;
9740
9741 if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
9742 return (1);
9743 if (m->m_pkthdr.len < off + len)
9744 return (1);
9745
9746 switch (p) {
9747 case IPPROTO_TCP:
9748 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
9749 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
9750 sum = m->m_pkthdr.csum_data;
9751 } else {
9752 ip = mtod(m, struct ip *);
9753 sum = in_pseudo(ip->ip_src.s_addr,
9754 ip->ip_dst.s_addr, htonl((u_short)len +
9755 m->m_pkthdr.csum_data + IPPROTO_TCP));
9756 }
9757 sum ^= 0xffff;
9758 ++hw_assist;
9759 }
9760 break;
9761 case IPPROTO_UDP:
9762 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
9763 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
9764 sum = m->m_pkthdr.csum_data;
9765 } else {
9766 ip = mtod(m, struct ip *);
9767 sum = in_pseudo(ip->ip_src.s_addr,
9768 ip->ip_dst.s_addr, htonl((u_short)len +
9769 m->m_pkthdr.csum_data + IPPROTO_UDP));
9770 }
9771 sum ^= 0xffff;
9772 ++hw_assist;
9773 }
9774 break;
9775 case IPPROTO_ICMP:
9776 #ifdef INET6
9777 case IPPROTO_ICMPV6:
9778 #endif /* INET6 */
9779 break;
9780 default:
9781 return (1);
9782 }
9783
9784 if (!hw_assist) {
9785 switch (af) {
9786 case AF_INET:
9787 if (m->m_len < sizeof(struct ip))
9788 return (1);
9789 sum = in4_cksum(m, (p == IPPROTO_ICMP ? 0 : p), off, len);
9790 break;
9791 #ifdef INET6
9792 case AF_INET6:
9793 if (m->m_len < sizeof(struct ip6_hdr))
9794 return (1);
9795 sum = in6_cksum(m, p, off, len);
9796 break;
9797 #endif /* INET6 */
9798 }
9799 }
9800 if (sum) {
9801 switch (p) {
9802 case IPPROTO_TCP:
9803 {
9804 KMOD_TCPSTAT_INC(tcps_rcvbadsum);
9805 break;
9806 }
9807 case IPPROTO_UDP:
9808 {
9809 KMOD_UDPSTAT_INC(udps_badsum);
9810 break;
9811 }
9812 #ifdef INET
9813 case IPPROTO_ICMP:
9814 {
9815 KMOD_ICMPSTAT_INC(icps_checksum);
9816 break;
9817 }
9818 #endif
9819 #ifdef INET6
9820 case IPPROTO_ICMPV6:
9821 {
9822 KMOD_ICMP6STAT_INC(icp6s_checksum);
9823 break;
9824 }
9825 #endif /* INET6 */
9826 }
9827 return (1);
9828 } else {
9829 if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
9830 m->m_pkthdr.csum_flags |=
9831 (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
9832 m->m_pkthdr.csum_data = 0xffff;
9833 }
9834 }
9835 return (0);
9836 }
9837
9838 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)9839 pf_pdesc_to_dnflow(const struct pf_pdesc *pd, const struct pf_krule *r,
9840 const struct pf_kstate *s, struct ip_fw_args *dnflow)
9841 {
9842 int dndir = r->direction;
9843 sa_family_t af = pd->naf;
9844
9845 if (s && dndir == PF_INOUT) {
9846 dndir = s->direction;
9847 } else if (dndir == PF_INOUT) {
9848 /* Assume primary direction. Happens when we've set dnpipe in
9849 * the ethernet level code. */
9850 dndir = pd->dir;
9851 }
9852
9853 if (pd->pf_mtag->flags & PF_MTAG_FLAG_DUMMYNETED)
9854 return (false);
9855
9856 memset(dnflow, 0, sizeof(*dnflow));
9857
9858 if (pd->dport != NULL)
9859 dnflow->f_id.dst_port = ntohs(*pd->dport);
9860 if (pd->sport != NULL)
9861 dnflow->f_id.src_port = ntohs(*pd->sport);
9862
9863 if (pd->dir == PF_IN)
9864 dnflow->flags |= IPFW_ARGS_IN;
9865 else
9866 dnflow->flags |= IPFW_ARGS_OUT;
9867
9868 if (pd->dir != dndir && pd->act.dnrpipe) {
9869 dnflow->rule.info = pd->act.dnrpipe;
9870 }
9871 else if (pd->dir == dndir && pd->act.dnpipe) {
9872 dnflow->rule.info = pd->act.dnpipe;
9873 }
9874 else {
9875 return (false);
9876 }
9877
9878 dnflow->rule.info |= IPFW_IS_DUMMYNET;
9879 if (r->free_flags & PFRULE_DN_IS_PIPE || pd->act.flags & PFSTATE_DN_IS_PIPE)
9880 dnflow->rule.info |= IPFW_IS_PIPE;
9881
9882 dnflow->f_id.proto = pd->proto;
9883 dnflow->f_id.extra = dnflow->rule.info;
9884 if (s)
9885 af = s->key[PF_SK_STACK]->af;
9886
9887 switch (af) {
9888 case AF_INET:
9889 dnflow->f_id.addr_type = 4;
9890 if (s) {
9891 dnflow->f_id.src_ip = htonl(
9892 s->key[PF_SK_STACK]->addr[pd->sidx].v4.s_addr);
9893 dnflow->f_id.dst_ip = htonl(
9894 s->key[PF_SK_STACK]->addr[pd->didx].v4.s_addr);
9895 } else {
9896 dnflow->f_id.src_ip = ntohl(pd->src->v4.s_addr);
9897 dnflow->f_id.dst_ip = ntohl(pd->dst->v4.s_addr);
9898 }
9899 break;
9900 case AF_INET6:
9901 dnflow->f_id.addr_type = 6;
9902
9903 if (s) {
9904 dnflow->f_id.src_ip6 =
9905 s->key[PF_SK_STACK]->addr[pd->sidx].v6;
9906 dnflow->f_id.dst_ip6 =
9907 s->key[PF_SK_STACK]->addr[pd->didx].v6;
9908 } else {
9909 dnflow->f_id.src_ip6 = pd->src->v6;
9910 dnflow->f_id.dst_ip6 = pd->dst->v6;
9911 }
9912 break;
9913 }
9914
9915 /*
9916 * Separate this out, because while we pass the pre-NAT addresses to
9917 * dummynet we want the post-nat address family in case of nat64.
9918 * Dummynet may call ip_output/ip6_output itself, and we need it to
9919 * call the correct one.
9920 */
9921 if (pd->naf == AF_INET6)
9922 dnflow->flags |= IPFW_ARGS_IP6;
9923
9924 return (true);
9925 }
9926
9927 int
pf_test_eth(int dir,int pflags,struct ifnet * ifp,struct mbuf ** m0,struct inpcb * inp)9928 pf_test_eth(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0,
9929 struct inpcb *inp)
9930 {
9931 struct pfi_kkif *kif;
9932 struct mbuf *m = *m0;
9933
9934 M_ASSERTPKTHDR(m);
9935 MPASS(ifp->if_vnet == curvnet);
9936 NET_EPOCH_ASSERT();
9937
9938 if (!V_pf_status.running)
9939 return (PF_PASS);
9940
9941 kif = (struct pfi_kkif *)ifp->if_pf_kif;
9942
9943 if (kif == NULL) {
9944 DPFPRINTF(PF_DEBUG_URGENT,
9945 "%s: kif == NULL, if_xname %s", __func__, ifp->if_xname);
9946 return (PF_DROP);
9947 }
9948 if (kif->pfik_flags & PFI_IFLAG_SKIP)
9949 return (PF_PASS);
9950
9951 if (m->m_flags & M_SKIP_FIREWALL)
9952 return (PF_PASS);
9953
9954 if (__predict_false(! M_WRITABLE(*m0))) {
9955 m = *m0 = m_unshare(*m0, M_NOWAIT);
9956 if (*m0 == NULL)
9957 return (PF_DROP);
9958 }
9959
9960 /* Stateless! */
9961 return (pf_test_eth_rule(dir, kif, m0));
9962 }
9963
9964 static __inline void
pf_dummynet_flag_remove(struct mbuf * m,struct pf_mtag * pf_mtag)9965 pf_dummynet_flag_remove(struct mbuf *m, struct pf_mtag *pf_mtag)
9966 {
9967 struct m_tag *mtag;
9968
9969 pf_mtag->flags &= ~PF_MTAG_FLAG_DUMMYNET;
9970
9971 /* dummynet adds this tag, but pf does not need it,
9972 * and keeping it creates unexpected behavior,
9973 * e.g. in case of divert(4) usage right after dummynet. */
9974 mtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL);
9975 if (mtag != NULL)
9976 m_tag_delete(m, mtag);
9977 }
9978
9979 static int
pf_dummynet(struct pf_pdesc * pd,struct pf_kstate * s,struct pf_krule * r,struct mbuf ** m0)9980 pf_dummynet(struct pf_pdesc *pd, struct pf_kstate *s,
9981 struct pf_krule *r, struct mbuf **m0)
9982 {
9983 return (pf_dummynet_route(pd, s, r, NULL, NULL, m0));
9984 }
9985
9986 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)9987 pf_dummynet_route(struct pf_pdesc *pd, struct pf_kstate *s,
9988 struct pf_krule *r, struct ifnet *ifp, const struct sockaddr *sa,
9989 struct mbuf **m0)
9990 {
9991 struct ip_fw_args dnflow;
9992
9993 NET_EPOCH_ASSERT();
9994
9995 if (pd->act.dnpipe == 0 && pd->act.dnrpipe == 0)
9996 return (0);
9997
9998 if (ip_dn_io_ptr == NULL) {
9999 m_freem(*m0);
10000 *m0 = NULL;
10001 return (ENOMEM);
10002 }
10003
10004 if (pd->pf_mtag == NULL &&
10005 ((pd->pf_mtag = pf_get_mtag(*m0)) == NULL)) {
10006 m_freem(*m0);
10007 *m0 = NULL;
10008 return (ENOMEM);
10009 }
10010
10011 if (ifp != NULL) {
10012 pd->pf_mtag->flags |= PF_MTAG_FLAG_ROUTE_TO;
10013
10014 pd->pf_mtag->if_index = ifp->if_index;
10015 pd->pf_mtag->if_idxgen = ifp->if_idxgen;
10016
10017 MPASS(sa != NULL);
10018
10019 switch (sa->sa_family) {
10020 case AF_INET:
10021 memcpy(&pd->pf_mtag->dst, sa,
10022 sizeof(struct sockaddr_in));
10023 break;
10024 case AF_INET6:
10025 memcpy(&pd->pf_mtag->dst, sa,
10026 sizeof(struct sockaddr_in6));
10027 break;
10028 }
10029 }
10030
10031 if (s != NULL && s->nat_rule != NULL &&
10032 s->nat_rule->action == PF_RDR &&
10033 (
10034 #ifdef INET
10035 (pd->af == AF_INET && IN_LOOPBACK(ntohl(pd->dst->v4.s_addr))) ||
10036 #endif /* INET */
10037 (pd->af == AF_INET6 && IN6_IS_ADDR_LOOPBACK(&pd->dst->v6)))) {
10038 /*
10039 * If we're redirecting to loopback mark this packet
10040 * as being local. Otherwise it might get dropped
10041 * if dummynet re-injects.
10042 */
10043 (*m0)->m_pkthdr.rcvif = V_loif;
10044 }
10045
10046 if (pf_pdesc_to_dnflow(pd, r, s, &dnflow)) {
10047 pd->pf_mtag->flags |= PF_MTAG_FLAG_DUMMYNET;
10048 pd->pf_mtag->flags |= PF_MTAG_FLAG_DUMMYNETED;
10049 ip_dn_io_ptr(m0, &dnflow);
10050 if (*m0 != NULL) {
10051 pd->pf_mtag->flags &= ~PF_MTAG_FLAG_ROUTE_TO;
10052 pf_dummynet_flag_remove(*m0, pd->pf_mtag);
10053 }
10054 }
10055
10056 return (0);
10057 }
10058
10059 static int
pf_walk_option(struct pf_pdesc * pd,struct ip * h,int off,int end,u_short * reason)10060 pf_walk_option(struct pf_pdesc *pd, struct ip *h, int off, int end,
10061 u_short *reason)
10062 {
10063 uint8_t type, length, opts[15 * 4 - sizeof(struct ip)];
10064
10065 /* IP header in payload of ICMP packet may be too short */
10066 if (pd->m->m_pkthdr.len < end) {
10067 DPFPRINTF(PF_DEBUG_MISC, "IP option too short");
10068 REASON_SET(reason, PFRES_SHORT);
10069 return (PF_DROP);
10070 }
10071
10072 MPASS(end - off <= sizeof(opts));
10073 m_copydata(pd->m, off, end - off, opts);
10074 end -= off;
10075 off = 0;
10076
10077 while (off < end) {
10078 type = opts[off];
10079 if (type == IPOPT_EOL)
10080 break;
10081 if (type == IPOPT_NOP) {
10082 off++;
10083 continue;
10084 }
10085 if (off + 2 > end) {
10086 DPFPRINTF(PF_DEBUG_MISC, "IP length opt");
10087 REASON_SET(reason, PFRES_IPOPTIONS);
10088 return (PF_DROP);
10089 }
10090 length = opts[off + 1];
10091 if (length < 2) {
10092 DPFPRINTF(PF_DEBUG_MISC, "IP short opt");
10093 REASON_SET(reason, PFRES_IPOPTIONS);
10094 return (PF_DROP);
10095 }
10096 if (off + length > end) {
10097 DPFPRINTF(PF_DEBUG_MISC, "IP long opt");
10098 REASON_SET(reason, PFRES_IPOPTIONS);
10099 return (PF_DROP);
10100 }
10101 switch (type) {
10102 case IPOPT_RA:
10103 pd->badopts |= PF_OPT_ROUTER_ALERT;
10104 break;
10105 default:
10106 pd->badopts |= PF_OPT_OTHER;
10107 break;
10108 }
10109 off += length;
10110 }
10111
10112 return (PF_PASS);
10113 }
10114
10115 static int
pf_walk_header(struct pf_pdesc * pd,struct ip * h,u_short * reason)10116 pf_walk_header(struct pf_pdesc *pd, struct ip *h, u_short *reason)
10117 {
10118 struct ah ext;
10119 u_int32_t hlen, end;
10120 int hdr_cnt;
10121
10122 hlen = h->ip_hl << 2;
10123 if (hlen < sizeof(struct ip) || hlen > ntohs(h->ip_len)) {
10124 REASON_SET(reason, PFRES_SHORT);
10125 return (PF_DROP);
10126 }
10127 if (hlen != sizeof(struct ip)) {
10128 if (pf_walk_option(pd, h, pd->off + sizeof(struct ip),
10129 pd->off + hlen, reason) != PF_PASS)
10130 return (PF_DROP);
10131 /* header options which contain only padding is fishy */
10132 if (pd->badopts == 0)
10133 pd->badopts |= PF_OPT_OTHER;
10134 }
10135 end = pd->off + ntohs(h->ip_len);
10136 pd->off += hlen;
10137 pd->proto = h->ip_p;
10138 /* IGMP packets have router alert options, allow them */
10139 if (pd->proto == IPPROTO_IGMP) {
10140 /*
10141 * According to RFC 1112 ttl must be set to 1 in all IGMP
10142 * packets sent to 224.0.0.1
10143 */
10144 if ((h->ip_ttl != 1) &&
10145 (h->ip_dst.s_addr == INADDR_ALLHOSTS_GROUP)) {
10146 DPFPRINTF(PF_DEBUG_MISC, "Invalid IGMP");
10147 REASON_SET(reason, PFRES_IPOPTIONS);
10148 return (PF_DROP);
10149 }
10150 pd->badopts &= ~PF_OPT_ROUTER_ALERT;
10151 }
10152 /* stop walking over non initial fragments */
10153 if ((h->ip_off & htons(IP_OFFMASK)) != 0)
10154 return (PF_PASS);
10155 for (hdr_cnt = 0; hdr_cnt < PF_HDR_LIMIT; hdr_cnt++) {
10156 switch (pd->proto) {
10157 case IPPROTO_AH:
10158 /* fragments may be short */
10159 if ((h->ip_off & htons(IP_MF | IP_OFFMASK)) != 0 &&
10160 end < pd->off + sizeof(ext))
10161 return (PF_PASS);
10162 if (!pf_pull_hdr(pd->m, pd->off, &ext, sizeof(ext),
10163 reason, AF_INET)) {
10164 DPFPRINTF(PF_DEBUG_MISC, "IP short exthdr");
10165 return (PF_DROP);
10166 }
10167 pd->off += (ext.ah_len + 2) * 4;
10168 pd->proto = ext.ah_nxt;
10169 break;
10170 default:
10171 return (PF_PASS);
10172 }
10173 }
10174 DPFPRINTF(PF_DEBUG_MISC, "IPv4 nested authentication header limit");
10175 REASON_SET(reason, PFRES_IPOPTIONS);
10176 return (PF_DROP);
10177 }
10178
10179 #ifdef INET6
10180 static int
pf_walk_option6(struct pf_pdesc * pd,struct ip6_hdr * h,int off,int end,u_short * reason)10181 pf_walk_option6(struct pf_pdesc *pd, struct ip6_hdr *h, int off, int end,
10182 u_short *reason)
10183 {
10184 struct ip6_opt opt;
10185 struct ip6_opt_jumbo jumbo;
10186
10187 while (off < end) {
10188 if (!pf_pull_hdr(pd->m, off, &opt.ip6o_type,
10189 sizeof(opt.ip6o_type), reason, AF_INET6)) {
10190 DPFPRINTF(PF_DEBUG_MISC, "IPv6 short opt type");
10191 return (PF_DROP);
10192 }
10193 if (opt.ip6o_type == IP6OPT_PAD1) {
10194 off++;
10195 continue;
10196 }
10197 if (!pf_pull_hdr(pd->m, off, &opt, sizeof(opt),
10198 reason, AF_INET6)) {
10199 DPFPRINTF(PF_DEBUG_MISC, "IPv6 short opt");
10200 return (PF_DROP);
10201 }
10202 if (off + sizeof(opt) + opt.ip6o_len > end) {
10203 DPFPRINTF(PF_DEBUG_MISC, "IPv6 long opt");
10204 REASON_SET(reason, PFRES_IPOPTIONS);
10205 return (PF_DROP);
10206 }
10207 switch (opt.ip6o_type) {
10208 case IP6OPT_PADN:
10209 break;
10210 case IP6OPT_JUMBO:
10211 pd->badopts |= PF_OPT_JUMBO;
10212 if (pd->jumbolen != 0) {
10213 DPFPRINTF(PF_DEBUG_MISC, "IPv6 multiple jumbo");
10214 REASON_SET(reason, PFRES_IPOPTIONS);
10215 return (PF_DROP);
10216 }
10217 if (ntohs(h->ip6_plen) != 0) {
10218 DPFPRINTF(PF_DEBUG_MISC, "IPv6 bad jumbo plen");
10219 REASON_SET(reason, PFRES_IPOPTIONS);
10220 return (PF_DROP);
10221 }
10222 if (!pf_pull_hdr(pd->m, off, &jumbo, sizeof(jumbo),
10223 reason, AF_INET6)) {
10224 DPFPRINTF(PF_DEBUG_MISC, "IPv6 short jumbo");
10225 return (PF_DROP);
10226 }
10227 memcpy(&pd->jumbolen, jumbo.ip6oj_jumbo_len,
10228 sizeof(pd->jumbolen));
10229 pd->jumbolen = ntohl(pd->jumbolen);
10230 if (pd->jumbolen < IPV6_MAXPACKET) {
10231 DPFPRINTF(PF_DEBUG_MISC, "IPv6 short jumbolen");
10232 REASON_SET(reason, PFRES_IPOPTIONS);
10233 return (PF_DROP);
10234 }
10235 break;
10236 case IP6OPT_ROUTER_ALERT:
10237 pd->badopts |= PF_OPT_ROUTER_ALERT;
10238 break;
10239 default:
10240 pd->badopts |= PF_OPT_OTHER;
10241 break;
10242 }
10243 off += sizeof(opt) + opt.ip6o_len;
10244 }
10245
10246 return (PF_PASS);
10247 }
10248
10249 int
pf_walk_header6(struct pf_pdesc * pd,struct ip6_hdr * h,u_short * reason)10250 pf_walk_header6(struct pf_pdesc *pd, struct ip6_hdr *h, u_short *reason)
10251 {
10252 struct ip6_frag frag;
10253 struct ip6_ext ext;
10254 struct icmp6_hdr icmp6;
10255 struct ip6_rthdr rthdr;
10256 uint32_t end;
10257 int hdr_cnt, fraghdr_cnt = 0, rthdr_cnt = 0;
10258
10259 pd->off += sizeof(struct ip6_hdr);
10260 end = pd->off + ntohs(h->ip6_plen);
10261 pd->fragoff = pd->extoff = pd->jumbolen = 0;
10262 pd->proto = h->ip6_nxt;
10263 for (hdr_cnt = 0; hdr_cnt < PF_HDR_LIMIT; hdr_cnt++) {
10264 switch (pd->proto) {
10265 case IPPROTO_ROUTING:
10266 case IPPROTO_DSTOPTS:
10267 pd->badopts |= PF_OPT_OTHER;
10268 break;
10269 case IPPROTO_HOPOPTS:
10270 if (!pf_pull_hdr(pd->m, pd->off, &ext, sizeof(ext),
10271 reason, AF_INET6)) {
10272 DPFPRINTF(PF_DEBUG_MISC, "IPv6 short exthdr");
10273 return (PF_DROP);
10274 }
10275 if (pf_walk_option6(pd, h, pd->off + sizeof(ext),
10276 pd->off + (ext.ip6e_len + 1) * 8,
10277 reason) != PF_PASS)
10278 return (PF_DROP);
10279 /* option header which contains only padding is fishy */
10280 if (pd->badopts == 0)
10281 pd->badopts |= PF_OPT_OTHER;
10282 break;
10283 }
10284 switch (pd->proto) {
10285 case IPPROTO_FRAGMENT:
10286 if (fraghdr_cnt++) {
10287 DPFPRINTF(PF_DEBUG_MISC, "IPv6 multiple fragment");
10288 REASON_SET(reason, PFRES_FRAG);
10289 return (PF_DROP);
10290 }
10291 /* jumbo payload packets cannot be fragmented */
10292 if (pd->jumbolen != 0) {
10293 DPFPRINTF(PF_DEBUG_MISC, "IPv6 fragmented jumbo");
10294 REASON_SET(reason, PFRES_FRAG);
10295 return (PF_DROP);
10296 }
10297 if (!pf_pull_hdr(pd->m, pd->off, &frag, sizeof(frag),
10298 reason, AF_INET6)) {
10299 DPFPRINTF(PF_DEBUG_MISC, "IPv6 short fragment");
10300 return (PF_DROP);
10301 }
10302 /* stop walking over non initial fragments */
10303 if (ntohs((frag.ip6f_offlg & IP6F_OFF_MASK)) != 0) {
10304 pd->fragoff = pd->off;
10305 return (PF_PASS);
10306 }
10307 /* RFC6946: reassemble only non atomic fragments */
10308 if (frag.ip6f_offlg & IP6F_MORE_FRAG)
10309 pd->fragoff = pd->off;
10310 pd->off += sizeof(frag);
10311 pd->proto = frag.ip6f_nxt;
10312 break;
10313 case IPPROTO_ROUTING:
10314 if (rthdr_cnt++) {
10315 DPFPRINTF(PF_DEBUG_MISC, "IPv6 multiple rthdr");
10316 REASON_SET(reason, PFRES_IPOPTIONS);
10317 return (PF_DROP);
10318 }
10319 /* fragments may be short */
10320 if (pd->fragoff != 0 && end < pd->off + sizeof(rthdr)) {
10321 pd->off = pd->fragoff;
10322 pd->proto = IPPROTO_FRAGMENT;
10323 return (PF_PASS);
10324 }
10325 if (!pf_pull_hdr(pd->m, pd->off, &rthdr, sizeof(rthdr),
10326 reason, AF_INET6)) {
10327 DPFPRINTF(PF_DEBUG_MISC, "IPv6 short rthdr");
10328 return (PF_DROP);
10329 }
10330 if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
10331 DPFPRINTF(PF_DEBUG_MISC, "IPv6 rthdr0");
10332 REASON_SET(reason, PFRES_IPOPTIONS);
10333 return (PF_DROP);
10334 }
10335 /* FALLTHROUGH */
10336 case IPPROTO_HOPOPTS:
10337 /* RFC2460 4.1: Hop-by-Hop only after IPv6 header */
10338 if (pd->proto == IPPROTO_HOPOPTS && hdr_cnt > 0) {
10339 DPFPRINTF(PF_DEBUG_MISC, "IPv6 hopopts not first");
10340 REASON_SET(reason, PFRES_IPOPTIONS);
10341 return (PF_DROP);
10342 }
10343 /* FALLTHROUGH */
10344 case IPPROTO_AH:
10345 case IPPROTO_DSTOPTS:
10346 if (!pf_pull_hdr(pd->m, pd->off, &ext, sizeof(ext),
10347 reason, AF_INET6)) {
10348 DPFPRINTF(PF_DEBUG_MISC, "IPv6 short exthdr");
10349 return (PF_DROP);
10350 }
10351 /* fragments may be short */
10352 if (pd->fragoff != 0 && end < pd->off + sizeof(ext)) {
10353 pd->off = pd->fragoff;
10354 pd->proto = IPPROTO_FRAGMENT;
10355 return (PF_PASS);
10356 }
10357 /* reassembly needs the ext header before the frag */
10358 if (pd->fragoff == 0)
10359 pd->extoff = pd->off;
10360 if (pd->proto == IPPROTO_HOPOPTS && pd->fragoff == 0 &&
10361 ntohs(h->ip6_plen) == 0 && pd->jumbolen != 0) {
10362 DPFPRINTF(PF_DEBUG_MISC, "IPv6 missing jumbo");
10363 REASON_SET(reason, PFRES_IPOPTIONS);
10364 return (PF_DROP);
10365 }
10366 if (pd->proto == IPPROTO_AH)
10367 pd->off += (ext.ip6e_len + 2) * 4;
10368 else
10369 pd->off += (ext.ip6e_len + 1) * 8;
10370 pd->proto = ext.ip6e_nxt;
10371 break;
10372 case IPPROTO_ICMPV6:
10373 /* fragments may be short, ignore inner header then */
10374 if (pd->fragoff != 0 && end < pd->off + sizeof(icmp6)) {
10375 pd->off = pd->fragoff;
10376 pd->proto = IPPROTO_FRAGMENT;
10377 return (PF_PASS);
10378 }
10379 if (!pf_pull_hdr(pd->m, pd->off, &icmp6, sizeof(icmp6),
10380 reason, AF_INET6)) {
10381 DPFPRINTF(PF_DEBUG_MISC,
10382 "IPv6 short icmp6hdr");
10383 return (PF_DROP);
10384 }
10385 /* ICMP multicast packets have router alert options */
10386 switch (icmp6.icmp6_type) {
10387 case MLD_LISTENER_QUERY:
10388 case MLD_LISTENER_REPORT:
10389 case MLD_LISTENER_DONE:
10390 case MLDV2_LISTENER_REPORT:
10391 /*
10392 * According to RFC 2710 all MLD messages are
10393 * sent with hop-limit (ttl) set to 1, and link
10394 * local source address. If either one is
10395 * missing then MLD message is invalid and
10396 * should be discarded.
10397 */
10398 if ((h->ip6_hlim != 1) ||
10399 !IN6_IS_ADDR_LINKLOCAL(&h->ip6_src)) {
10400 DPFPRINTF(PF_DEBUG_MISC, "Invalid MLD");
10401 REASON_SET(reason, PFRES_IPOPTIONS);
10402 return (PF_DROP);
10403 }
10404 pd->badopts &= ~PF_OPT_ROUTER_ALERT;
10405 break;
10406 }
10407 return (PF_PASS);
10408 case IPPROTO_TCP:
10409 case IPPROTO_UDP:
10410 case IPPROTO_SCTP:
10411 /* fragments may be short, ignore inner header then */
10412 if (pd->fragoff != 0 && end < pd->off +
10413 (pd->proto == IPPROTO_TCP ? sizeof(struct tcphdr) :
10414 pd->proto == IPPROTO_UDP ? sizeof(struct udphdr) :
10415 pd->proto == IPPROTO_SCTP ? sizeof(struct sctphdr) :
10416 sizeof(struct icmp6_hdr))) {
10417 pd->off = pd->fragoff;
10418 pd->proto = IPPROTO_FRAGMENT;
10419 }
10420 /* FALLTHROUGH */
10421 default:
10422 return (PF_PASS);
10423 }
10424 }
10425 DPFPRINTF(PF_DEBUG_MISC, "IPv6 nested extension header limit");
10426 REASON_SET(reason, PFRES_IPOPTIONS);
10427 return (PF_DROP);
10428 }
10429 #endif /* INET6 */
10430
10431 static void
pf_init_pdesc(struct pf_pdesc * pd,struct mbuf * m)10432 pf_init_pdesc(struct pf_pdesc *pd, struct mbuf *m)
10433 {
10434 memset(pd, 0, sizeof(*pd));
10435 pd->pf_mtag = pf_find_mtag(m);
10436 pd->m = m;
10437 }
10438
10439 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)10440 pf_setup_pdesc(sa_family_t af, int dir, struct pf_pdesc *pd, struct mbuf **m0,
10441 u_short *action, u_short *reason, struct pfi_kkif *kif,
10442 struct pf_rule_actions *default_actions)
10443 {
10444 pd->dir = dir;
10445 pd->kif = kif;
10446 pd->m = *m0;
10447 pd->sidx = (dir == PF_IN) ? 0 : 1;
10448 pd->didx = (dir == PF_IN) ? 1 : 0;
10449 pd->af = pd->naf = af;
10450
10451 PF_RULES_ASSERT();
10452
10453 TAILQ_INIT(&pd->sctp_multihome_jobs);
10454 if (default_actions != NULL)
10455 memcpy(&pd->act, default_actions, sizeof(pd->act));
10456
10457 if (pd->pf_mtag && pd->pf_mtag->dnpipe) {
10458 pd->act.dnpipe = pd->pf_mtag->dnpipe;
10459 pd->act.flags = pd->pf_mtag->dnflags;
10460 }
10461
10462 switch (af) {
10463 #ifdef INET
10464 case AF_INET: {
10465 struct ip *h;
10466
10467 if (__predict_false((*m0)->m_len < sizeof(struct ip)) &&
10468 (pd->m = *m0 = m_pullup(*m0, sizeof(struct ip))) == NULL) {
10469 DPFPRINTF(PF_DEBUG_URGENT,
10470 "%s: m_len < sizeof(struct ip), pullup failed",
10471 __func__);
10472 *action = PF_DROP;
10473 REASON_SET(reason, PFRES_SHORT);
10474 return (PF_DROP);
10475 }
10476
10477 h = mtod(pd->m, struct ip *);
10478 if (pd->m->m_pkthdr.len < ntohs(h->ip_len)) {
10479 *action = PF_DROP;
10480 REASON_SET(reason, PFRES_SHORT);
10481 return (PF_DROP);
10482 }
10483
10484 if (pf_normalize_ip(reason, pd) != PF_PASS) {
10485 /* We do IP header normalization and packet reassembly here */
10486 *m0 = pd->m;
10487 *action = PF_DROP;
10488 return (PF_DROP);
10489 }
10490 *m0 = pd->m;
10491 h = mtod(pd->m, struct ip *);
10492
10493 if (pf_walk_header(pd, h, reason) != PF_PASS) {
10494 *action = PF_DROP;
10495 return (PF_DROP);
10496 }
10497
10498 pd->src = (struct pf_addr *)&h->ip_src;
10499 pd->dst = (struct pf_addr *)&h->ip_dst;
10500 pf_addrcpy(&pd->osrc, pd->src, af);
10501 pf_addrcpy(&pd->odst, pd->dst, af);
10502 pd->ip_sum = &h->ip_sum;
10503 pd->tos = h->ip_tos & ~IPTOS_ECN_MASK;
10504 pd->ttl = h->ip_ttl;
10505 pd->tot_len = ntohs(h->ip_len);
10506 pd->act.rtableid = -1;
10507 pd->df = h->ip_off & htons(IP_DF);
10508 pd->virtual_proto = (h->ip_off & htons(IP_MF | IP_OFFMASK)) ?
10509 PF_VPROTO_FRAGMENT : pd->proto;
10510
10511 break;
10512 }
10513 #endif /* INET */
10514 #ifdef INET6
10515 case AF_INET6: {
10516 struct ip6_hdr *h;
10517
10518 if (__predict_false((*m0)->m_len < sizeof(struct ip6_hdr)) &&
10519 (pd->m = *m0 = m_pullup(*m0, sizeof(struct ip6_hdr))) == NULL) {
10520 DPFPRINTF(PF_DEBUG_URGENT,
10521 "%s: m_len < sizeof(struct ip6_hdr)"
10522 ", pullup failed", __func__);
10523 *action = PF_DROP;
10524 REASON_SET(reason, PFRES_SHORT);
10525 return (PF_DROP);
10526 }
10527
10528 h = mtod(pd->m, struct ip6_hdr *);
10529 if (pd->m->m_pkthdr.len <
10530 sizeof(struct ip6_hdr) + ntohs(h->ip6_plen)) {
10531 *action = PF_DROP;
10532 REASON_SET(reason, PFRES_SHORT);
10533 return (PF_DROP);
10534 }
10535
10536 /*
10537 * we do not support jumbogram. if we keep going, zero ip6_plen
10538 * will do something bad, so drop the packet for now.
10539 */
10540 if (htons(h->ip6_plen) == 0) {
10541 *action = PF_DROP;
10542 return (PF_DROP);
10543 }
10544
10545 if (pf_walk_header6(pd, h, reason) != PF_PASS) {
10546 *action = PF_DROP;
10547 return (PF_DROP);
10548 }
10549
10550 h = mtod(pd->m, struct ip6_hdr *);
10551 pd->src = (struct pf_addr *)&h->ip6_src;
10552 pd->dst = (struct pf_addr *)&h->ip6_dst;
10553 pf_addrcpy(&pd->osrc, pd->src, af);
10554 pf_addrcpy(&pd->odst, pd->dst, af);
10555 pd->ip_sum = NULL;
10556 pd->tos = IPV6_DSCP(h);
10557 pd->ttl = h->ip6_hlim;
10558 pd->tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
10559 pd->act.rtableid = -1;
10560
10561 pd->virtual_proto = (pd->fragoff != 0) ?
10562 PF_VPROTO_FRAGMENT : pd->proto;
10563
10564 /* We do IP header normalization and packet reassembly here */
10565 if (pf_normalize_ip6(pd->fragoff, reason, pd) !=
10566 PF_PASS) {
10567 *m0 = pd->m;
10568 *action = PF_DROP;
10569 return (PF_DROP);
10570 }
10571 *m0 = pd->m;
10572 if (pd->m == NULL) {
10573 /* packet sits in reassembly queue, no error */
10574 *action = PF_PASS;
10575 return (PF_DROP);
10576 }
10577
10578 /* Update pointers into the packet. */
10579 h = mtod(pd->m, struct ip6_hdr *);
10580 pd->src = (struct pf_addr *)&h->ip6_src;
10581 pd->dst = (struct pf_addr *)&h->ip6_dst;
10582
10583 pd->off = 0;
10584
10585 if (pf_walk_header6(pd, h, reason) != PF_PASS) {
10586 *action = PF_DROP;
10587 return (PF_DROP);
10588 }
10589
10590 if (m_tag_find(pd->m, PACKET_TAG_PF_REASSEMBLED, NULL) != NULL) {
10591 /*
10592 * Reassembly may have changed the next protocol from
10593 * fragment to something else, so update.
10594 */
10595 pd->virtual_proto = pd->proto;
10596 MPASS(pd->fragoff == 0);
10597 }
10598
10599 if (pd->fragoff != 0)
10600 pd->virtual_proto = PF_VPROTO_FRAGMENT;
10601
10602 break;
10603 }
10604 #endif /* INET6 */
10605 default:
10606 panic("pf_setup_pdesc called with illegal af %u", af);
10607 }
10608
10609 switch (pd->virtual_proto) {
10610 case IPPROTO_TCP: {
10611 struct tcphdr *th = &pd->hdr.tcp;
10612
10613 if (!pf_pull_hdr(pd->m, pd->off, th, sizeof(*th),
10614 reason, af)) {
10615 *action = PF_DROP;
10616 REASON_SET(reason, PFRES_SHORT);
10617 return (PF_DROP);
10618 }
10619 pd->hdrlen = sizeof(*th);
10620 pd->p_len = pd->tot_len - pd->off - (th->th_off << 2);
10621 pd->sport = &th->th_sport;
10622 pd->dport = &th->th_dport;
10623 pd->pcksum = &th->th_sum;
10624 break;
10625 }
10626 case IPPROTO_UDP: {
10627 struct udphdr *uh = &pd->hdr.udp;
10628
10629 if (!pf_pull_hdr(pd->m, pd->off, uh, sizeof(*uh),
10630 reason, af)) {
10631 *action = PF_DROP;
10632 REASON_SET(reason, PFRES_SHORT);
10633 return (PF_DROP);
10634 }
10635 pd->hdrlen = sizeof(*uh);
10636 if (uh->uh_dport == 0 ||
10637 ntohs(uh->uh_ulen) > pd->m->m_pkthdr.len - pd->off ||
10638 ntohs(uh->uh_ulen) < sizeof(struct udphdr)) {
10639 *action = PF_DROP;
10640 REASON_SET(reason, PFRES_SHORT);
10641 return (PF_DROP);
10642 }
10643 pd->sport = &uh->uh_sport;
10644 pd->dport = &uh->uh_dport;
10645 pd->pcksum = &uh->uh_sum;
10646 break;
10647 }
10648 case IPPROTO_SCTP: {
10649 if (!pf_pull_hdr(pd->m, pd->off, &pd->hdr.sctp, sizeof(pd->hdr.sctp),
10650 reason, af)) {
10651 *action = PF_DROP;
10652 REASON_SET(reason, PFRES_SHORT);
10653 return (PF_DROP);
10654 }
10655 pd->hdrlen = sizeof(pd->hdr.sctp);
10656 pd->p_len = pd->tot_len - pd->off;
10657
10658 pd->sport = &pd->hdr.sctp.src_port;
10659 pd->dport = &pd->hdr.sctp.dest_port;
10660 if (pd->hdr.sctp.src_port == 0 || pd->hdr.sctp.dest_port == 0) {
10661 *action = PF_DROP;
10662 REASON_SET(reason, PFRES_SHORT);
10663 return (PF_DROP);
10664 }
10665
10666 /*
10667 * Placeholder. The SCTP checksum is 32-bits, but
10668 * pf_test_state() expects to update a 16-bit checksum.
10669 * Provide a dummy value which we'll subsequently ignore.
10670 * Do this before pf_scan_sctp() so any jobs we enqueue
10671 * have a pcksum set.
10672 */
10673 pd->pcksum = &pd->sctp_dummy_sum;
10674
10675 if (pf_scan_sctp(pd) != PF_PASS) {
10676 *action = PF_DROP;
10677 REASON_SET(reason, PFRES_SHORT);
10678 return (PF_DROP);
10679 }
10680 break;
10681 }
10682 case IPPROTO_ICMP: {
10683 if (!pf_pull_hdr(pd->m, pd->off, &pd->hdr.icmp, ICMP_MINLEN,
10684 reason, af)) {
10685 *action = PF_DROP;
10686 REASON_SET(reason, PFRES_SHORT);
10687 return (PF_DROP);
10688 }
10689 pd->pcksum = &pd->hdr.icmp.icmp_cksum;
10690 pd->hdrlen = ICMP_MINLEN;
10691 break;
10692 }
10693 #ifdef INET6
10694 case IPPROTO_ICMPV6: {
10695 size_t icmp_hlen = sizeof(struct icmp6_hdr);
10696
10697 if (!pf_pull_hdr(pd->m, pd->off, &pd->hdr.icmp6, icmp_hlen,
10698 reason, af)) {
10699 *action = PF_DROP;
10700 REASON_SET(reason, PFRES_SHORT);
10701 return (PF_DROP);
10702 }
10703 /* ICMP headers we look further into to match state */
10704 switch (pd->hdr.icmp6.icmp6_type) {
10705 case MLD_LISTENER_QUERY:
10706 case MLD_LISTENER_REPORT:
10707 icmp_hlen = sizeof(struct mld_hdr);
10708 break;
10709 case ND_NEIGHBOR_SOLICIT:
10710 case ND_NEIGHBOR_ADVERT:
10711 icmp_hlen = sizeof(struct nd_neighbor_solicit);
10712 /* FALLTHROUGH */
10713 case ND_ROUTER_SOLICIT:
10714 case ND_ROUTER_ADVERT:
10715 case ND_REDIRECT:
10716 if (pd->ttl != 255) {
10717 REASON_SET(reason, PFRES_NORM);
10718 return (PF_DROP);
10719 }
10720 break;
10721 }
10722 if (icmp_hlen > sizeof(struct icmp6_hdr) &&
10723 !pf_pull_hdr(pd->m, pd->off, &pd->hdr.icmp6, icmp_hlen,
10724 reason, af)) {
10725 *action = PF_DROP;
10726 REASON_SET(reason, PFRES_SHORT);
10727 return (PF_DROP);
10728 }
10729 pd->hdrlen = icmp_hlen;
10730 pd->pcksum = &pd->hdr.icmp6.icmp6_cksum;
10731 break;
10732 }
10733 #endif /* INET6 */
10734 default:
10735 /*
10736 * Placeholder value, so future calls to pf_change_ap() don't
10737 * try to update a NULL checksum pointer.
10738 */
10739 pd->pcksum = &pd->sctp_dummy_sum;
10740 break;
10741 }
10742
10743 if (pd->sport)
10744 pd->osport = pd->nsport = *pd->sport;
10745 if (pd->dport)
10746 pd->odport = pd->ndport = *pd->dport;
10747
10748 MPASS(pd->pcksum != NULL);
10749
10750 return (PF_PASS);
10751 }
10752
10753 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)10754 pf_rule_counters_inc(struct pf_pdesc *pd, struct pf_krule *r, int dir_out,
10755 int op_pass, sa_family_t af, struct pf_addr *src_host,
10756 struct pf_addr *dst_host)
10757 {
10758 pf_counter_u64_add_protected(&(r->packets[dir_out]), 1);
10759 pf_counter_u64_add_protected(&(r->bytes[dir_out]), pd->tot_len);
10760 pf_update_timestamp(r);
10761
10762 if (r->src.addr.type == PF_ADDR_TABLE)
10763 pfr_update_stats(r->src.addr.p.tbl, src_host, af,
10764 pd->tot_len, dir_out, op_pass, r->src.neg);
10765 if (r->dst.addr.type == PF_ADDR_TABLE)
10766 pfr_update_stats(r->dst.addr.p.tbl, dst_host, af,
10767 pd->tot_len, dir_out, op_pass, r->dst.neg);
10768 }
10769
10770 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)10771 pf_counters_inc(int action, struct pf_pdesc *pd, struct pf_kstate *s,
10772 struct pf_krule *r, struct pf_krule *a, struct pf_krule_slist *match_rules)
10773 {
10774 struct pf_krule_slist *mr = match_rules;
10775 struct pf_krule_item *ri;
10776 struct pf_krule *nr = NULL;
10777 struct pf_addr *src_host = pd->src;
10778 struct pf_addr *dst_host = pd->dst;
10779 struct pf_state_key *key;
10780 int dir_out = (pd->dir == PF_OUT);
10781 int op_r_pass = (r->action == PF_PASS);
10782 int op_pass = (action == PF_PASS || action == PF_AFRT);
10783 int s_dir_in, s_dir_out, s_dir_rev;
10784 sa_family_t af = pd->af;
10785
10786 pf_counter_u64_critical_enter();
10787
10788 /*
10789 * Set AF for interface counters, it will be later overwritten for
10790 * rule and state counters with value from proper state key.
10791 */
10792 if (action == PF_AFRT) {
10793 MPASS(s != NULL);
10794 if (s->direction == PF_OUT && dir_out)
10795 af = pd->naf;
10796 }
10797
10798 pf_counter_u64_add_protected(
10799 &pd->kif->pfik_bytes[af == AF_INET6][dir_out][!op_pass],
10800 pd->tot_len);
10801 pf_counter_u64_add_protected(
10802 &pd->kif->pfik_packets[af == AF_INET6][dir_out][!op_pass],
10803 1);
10804
10805 /* If the rule has failed to apply, don't increase its counters */
10806 if (!(op_pass || r->action == PF_DROP)) {
10807 pf_counter_u64_critical_exit();
10808 return;
10809 }
10810
10811 if (s != NULL) {
10812 PF_STATE_LOCK_ASSERT(s);
10813 mr = &(s->match_rules);
10814
10815 /*
10816 * For af-to on the inbound direction we can determine
10817 * the direction of passing packet only by checking direction
10818 * of AF translation. The af-to in "in" direction covers both
10819 * the inbound and the outbound side of state tracking,
10820 * so pd->dir is always PF_IN. We set dir_out and s_dir_rev
10821 * in a way to count packets as if the state was outbound,
10822 * because pfctl -ss shows the state with "->", as if it was
10823 * oubound.
10824 */
10825 if (action == PF_AFRT && s->direction == PF_IN) {
10826 dir_out = (pd->naf == s->rule->naf);
10827 s_dir_in = 1;
10828 s_dir_out = 0;
10829 s_dir_rev = (pd->naf == s->rule->af);
10830 } else {
10831 dir_out = (pd->dir == PF_OUT);
10832 s_dir_in = (s->direction == PF_IN);
10833 s_dir_out = (s->direction == PF_OUT);
10834 s_dir_rev = (pd->dir != s->direction);
10835 }
10836
10837 /* pd->tot_len is a problematic with af-to rules. Sure, we can
10838 * agree that it's the post-af-to packet length that was
10839 * forwarded through a state, but what about tables which match
10840 * on pre-af-to addresses? We don't have access the the original
10841 * packet length anymore.
10842 */
10843 s->packets[s_dir_rev]++;
10844 s->bytes[s_dir_rev] += pd->tot_len;
10845
10846 /*
10847 * Source nodes are accessed unlocked here. But since we are
10848 * operating with stateful tracking and the state is locked,
10849 * those SNs could not have been freed.
10850 */
10851 for (pf_sn_types_t sn_type=0; sn_type<PF_SN_MAX; sn_type++) {
10852 if (s->sns[sn_type] != NULL) {
10853 counter_u64_add(
10854 s->sns[sn_type]->packets[dir_out],
10855 1);
10856 counter_u64_add(
10857 s->sns[sn_type]->bytes[dir_out],
10858 pd->tot_len);
10859 }
10860 }
10861
10862 /* Start with pre-NAT addresses */
10863 key = s->key[(s->direction == PF_OUT)];
10864 src_host = &(key->addr[s_dir_out]);
10865 dst_host = &(key->addr[s_dir_in]);
10866 af = key->af;
10867 if (s->nat_rule) {
10868 /* Old-style NAT rules */
10869 if (s->nat_rule->action == PF_NAT ||
10870 s->nat_rule->action == PF_RDR ||
10871 s->nat_rule->action == PF_BINAT) {
10872 nr = s->nat_rule;
10873 pf_rule_counters_inc(pd, s->nat_rule, dir_out,
10874 op_r_pass, af, src_host, dst_host);
10875 /* Use post-NAT addresses from now on */
10876 key = s->key[s_dir_in];
10877 src_host = &(key->addr[s_dir_out]);
10878 dst_host = &(key->addr[s_dir_in]);
10879 af = key->af;
10880 }
10881 }
10882 }
10883
10884 SLIST_FOREACH(ri, mr, entry) {
10885 pf_rule_counters_inc(pd, ri->r, dir_out, op_r_pass, af,
10886 src_host, dst_host);
10887 if (s && s->nat_rule == ri->r) {
10888 /* Use post-NAT addresses after a match NAT rule */
10889 key = s->key[s_dir_in];
10890 src_host = &(key->addr[s_dir_out]);
10891 dst_host = &(key->addr[s_dir_in]);
10892 af = key->af;
10893 }
10894 }
10895
10896 if (s == NULL) {
10897 pf_free_match_rules(mr);
10898 }
10899
10900 if (a != NULL) {
10901 pf_rule_counters_inc(pd, a, dir_out, op_r_pass, af,
10902 src_host, dst_host);
10903 }
10904
10905 if (r != nr) {
10906 pf_rule_counters_inc(pd, r, dir_out, op_r_pass, af,
10907 src_host, dst_host);
10908 }
10909
10910 pf_counter_u64_critical_exit();
10911 }
10912
10913 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)10914 pf_log_matches(struct pf_pdesc *pd, struct pf_krule *rm,
10915 struct pf_krule *am, struct pf_kruleset *ruleset,
10916 struct pf_krule_slist *match_rules)
10917 {
10918 struct pf_krule_item *ri;
10919
10920 /* if this is the log(matches) rule, packet has been logged already */
10921 if (rm->log & PF_LOG_MATCHES)
10922 return;
10923
10924 SLIST_FOREACH(ri, match_rules, entry)
10925 if (ri->r->log & PF_LOG_MATCHES)
10926 PFLOG_PACKET(rm->action, PFRES_MATCH, rm, am,
10927 ruleset, pd, 1, ri->r);
10928 }
10929
10930 #if defined(INET) || defined(INET6)
10931 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)10932 pf_test(sa_family_t af, int dir, int pflags, struct ifnet *ifp, struct mbuf **m0,
10933 struct inpcb *inp, struct pf_rule_actions *default_actions)
10934 {
10935 struct pfi_kkif *kif;
10936 u_short action, reason = 0;
10937 struct m_tag *mtag;
10938 struct pf_krule *a = NULL, *r = &V_pf_default_rule;
10939 struct pf_kstate *s = NULL;
10940 struct pf_kruleset *ruleset = NULL;
10941 struct pf_krule_item *ri;
10942 struct pf_krule_slist match_rules;
10943 struct pf_pdesc pd;
10944 int use_2nd_queue = 0;
10945 uint16_t tag;
10946
10947 PF_RULES_RLOCK_TRACKER;
10948 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: bad direction %d\n", __func__, dir));
10949 M_ASSERTPKTHDR(*m0);
10950 NET_EPOCH_ASSERT();
10951
10952 if (!V_pf_status.running)
10953 return (PF_PASS);
10954
10955 kif = (struct pfi_kkif *)ifp->if_pf_kif;
10956
10957 if (__predict_false(kif == NULL)) {
10958 DPFPRINTF(PF_DEBUG_URGENT,
10959 "%s: kif == NULL, if_xname %s",
10960 __func__, ifp->if_xname);
10961 return (PF_DROP);
10962 }
10963 if (kif->pfik_flags & PFI_IFLAG_SKIP) {
10964 return (PF_PASS);
10965 }
10966
10967 if ((*m0)->m_flags & M_SKIP_FIREWALL) {
10968 return (PF_PASS);
10969 }
10970
10971 if (__predict_false(! M_WRITABLE(*m0))) {
10972 *m0 = m_unshare(*m0, M_NOWAIT);
10973 if (*m0 == NULL) {
10974 return (PF_DROP);
10975 }
10976 }
10977
10978 pf_init_pdesc(&pd, *m0);
10979 SLIST_INIT(&match_rules);
10980
10981 if (pd.pf_mtag != NULL && (pd.pf_mtag->flags & PF_MTAG_FLAG_ROUTE_TO)) {
10982 pd.pf_mtag->flags &= ~PF_MTAG_FLAG_ROUTE_TO;
10983
10984 ifp = ifnet_byindexgen(pd.pf_mtag->if_index,
10985 pd.pf_mtag->if_idxgen);
10986 if (ifp == NULL || ifp->if_flags & IFF_DYING) {
10987 m_freem(*m0);
10988 *m0 = NULL;
10989 return (PF_PASS);
10990 }
10991 (ifp->if_output)(ifp, *m0, sintosa(&pd.pf_mtag->dst), NULL);
10992 *m0 = NULL;
10993 return (PF_PASS);
10994 }
10995
10996 if (ip_dn_io_ptr != NULL && pd.pf_mtag != NULL &&
10997 pd.pf_mtag->flags & PF_MTAG_FLAG_DUMMYNET) {
10998 /* Dummynet re-injects packets after they've
10999 * completed their delay. We've already
11000 * processed them, so pass unconditionally. */
11001
11002 /* But only once. We may see the packet multiple times (e.g.
11003 * PFIL_IN/PFIL_OUT). */
11004 pf_dummynet_flag_remove(pd.m, pd.pf_mtag);
11005
11006 return (PF_PASS);
11007 }
11008
11009 PF_RULES_RLOCK();
11010
11011 if (pf_setup_pdesc(af, dir, &pd, m0, &action, &reason,
11012 kif, default_actions) != PF_PASS) {
11013 if (action != PF_PASS)
11014 pd.act.log |= PF_LOG_FORCE;
11015 goto done;
11016 }
11017
11018 #ifdef INET
11019 if (af == AF_INET && dir == PF_OUT && pflags & PFIL_FWD &&
11020 pd.df && (*m0)->m_pkthdr.len > ifp->if_mtu) {
11021 PF_RULES_RUNLOCK();
11022 icmp_error(*m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG,
11023 0, ifp->if_mtu);
11024 *m0 = NULL;
11025 return (PF_DROP);
11026 }
11027 #endif /* INET */
11028 #ifdef INET6
11029 /*
11030 * If we end up changing IP addresses (e.g. binat) the stack may get
11031 * confused and fail to send the icmp6 packet too big error. Just send
11032 * it here, before we do any NAT.
11033 */
11034 if (af == AF_INET6 && dir == PF_OUT && pflags & PFIL_FWD &&
11035 IN6_LINKMTU(ifp) < pf_max_frag_size(*m0)) {
11036 PF_RULES_RUNLOCK();
11037 icmp6_error(*m0, ICMP6_PACKET_TOO_BIG, 0, IN6_LINKMTU(ifp));
11038 *m0 = NULL;
11039 return (PF_DROP);
11040 }
11041 #endif /* INET6 */
11042
11043 if (__predict_false(ip_divert_ptr != NULL) &&
11044 ((mtag = m_tag_locate(pd.m, MTAG_PF_DIVERT, 0, NULL)) != NULL)) {
11045 struct pf_divert_mtag *dt = (struct pf_divert_mtag *)(mtag+1);
11046 if ((dt->idir == PF_DIVERT_MTAG_DIR_IN && dir == PF_IN) ||
11047 (dt->idir == PF_DIVERT_MTAG_DIR_OUT && dir == PF_OUT)) {
11048 if (pd.pf_mtag == NULL &&
11049 ((pd.pf_mtag = pf_get_mtag(pd.m)) == NULL)) {
11050 action = PF_DROP;
11051 goto done;
11052 }
11053 pd.pf_mtag->flags |= PF_MTAG_FLAG_PACKET_LOOPED;
11054 }
11055 if (pd.pf_mtag && pd.pf_mtag->flags & PF_MTAG_FLAG_FASTFWD_OURS_PRESENT) {
11056 pd.m->m_flags |= M_FASTFWD_OURS;
11057 pd.pf_mtag->flags &= ~PF_MTAG_FLAG_FASTFWD_OURS_PRESENT;
11058 }
11059 m_tag_delete(pd.m, mtag);
11060
11061 mtag = m_tag_locate(pd.m, MTAG_IPFW_RULE, 0, NULL);
11062 if (mtag != NULL)
11063 m_tag_delete(pd.m, mtag);
11064 }
11065
11066 switch (pd.virtual_proto) {
11067 case PF_VPROTO_FRAGMENT:
11068 /*
11069 * handle fragments that aren't reassembled by
11070 * normalization
11071 */
11072 if (kif == NULL || r == NULL) /* pflog */
11073 action = PF_DROP;
11074 else
11075 action = pf_test_rule(&r, &s, &pd, &a,
11076 &ruleset, &reason, inp, &match_rules);
11077 if (action != PF_PASS)
11078 REASON_SET(&reason, PFRES_FRAG);
11079 break;
11080
11081 case IPPROTO_TCP: {
11082 /* Respond to SYN with a syncookie. */
11083 if ((tcp_get_flags(&pd.hdr.tcp) & (TH_SYN|TH_ACK|TH_RST)) == TH_SYN &&
11084 pd.dir == PF_IN && pf_synflood_check(&pd)) {
11085 pf_syncookie_send(&pd, &reason);
11086 action = PF_DROP;
11087 break;
11088 }
11089
11090 if ((tcp_get_flags(&pd.hdr.tcp) & TH_ACK) && pd.p_len == 0)
11091 use_2nd_queue = 1;
11092 action = pf_normalize_tcp(&pd);
11093 if (action == PF_DROP)
11094 break;
11095 action = pf_test_state(&s, &pd, &reason);
11096 if (action == PF_PASS || action == PF_AFRT) {
11097 if (s != NULL) {
11098 if (V_pfsync_update_state_ptr != NULL)
11099 V_pfsync_update_state_ptr(s);
11100 r = s->rule;
11101 a = s->anchor;
11102 }
11103 } else if (s == NULL) {
11104 /* Validate remote SYN|ACK, re-create original SYN if
11105 * valid. */
11106 if ((tcp_get_flags(&pd.hdr.tcp) & (TH_SYN|TH_ACK|TH_RST)) ==
11107 TH_ACK && pf_syncookie_validate(&pd) &&
11108 pd.dir == PF_IN) {
11109 struct mbuf *msyn;
11110
11111 msyn = pf_syncookie_recreate_syn(&pd, &reason);
11112 if (msyn == NULL) {
11113 action = PF_DROP;
11114 break;
11115 }
11116
11117 action = pf_test(af, dir, pflags, ifp, &msyn, inp,
11118 &pd.act);
11119 m_freem(msyn);
11120 if (action != PF_PASS)
11121 break;
11122
11123 action = pf_test_state(&s, &pd, &reason);
11124 if (action != PF_PASS || s == NULL) {
11125 action = PF_DROP;
11126 break;
11127 }
11128
11129 s->src.seqhi = ntohl(pd.hdr.tcp.th_ack) - 1;
11130 s->src.seqlo = ntohl(pd.hdr.tcp.th_seq) - 1;
11131 pf_set_protostate(s, PF_PEER_SRC, PF_TCPS_PROXY_DST);
11132 action = pf_synproxy(&pd, s, &reason);
11133 break;
11134 } else {
11135 action = pf_test_rule(&r, &s, &pd,
11136 &a, &ruleset, &reason, inp, &match_rules);
11137 }
11138 }
11139 break;
11140 }
11141
11142 case IPPROTO_SCTP:
11143 action = pf_normalize_sctp(&pd);
11144 if (action == PF_DROP)
11145 break;
11146 /* fallthrough */
11147 case IPPROTO_UDP:
11148 default:
11149 action = pf_test_state(&s, &pd, &reason);
11150 if (action == PF_PASS || action == PF_AFRT) {
11151 if (s != NULL) {
11152 if (V_pfsync_update_state_ptr != NULL)
11153 V_pfsync_update_state_ptr(s);
11154 r = s->rule;
11155 a = s->anchor;
11156 }
11157 } else if (s == NULL) {
11158 action = pf_test_rule(&r, &s,
11159 &pd, &a, &ruleset, &reason, inp, &match_rules);
11160 }
11161 break;
11162
11163 case IPPROTO_ICMP:
11164 case IPPROTO_ICMPV6: {
11165 if (pd.virtual_proto == IPPROTO_ICMP && af != AF_INET) {
11166 action = PF_DROP;
11167 REASON_SET(&reason, PFRES_NORM);
11168 DPFPRINTF(PF_DEBUG_MISC,
11169 "dropping IPv6 packet with ICMPv4 payload");
11170 break;
11171 }
11172 if (pd.virtual_proto == IPPROTO_ICMPV6 && af != AF_INET6) {
11173 action = PF_DROP;
11174 REASON_SET(&reason, PFRES_NORM);
11175 DPFPRINTF(PF_DEBUG_MISC,
11176 "pf: dropping IPv4 packet with ICMPv6 payload");
11177 break;
11178 }
11179 action = pf_test_state_icmp(&s, &pd, &reason);
11180 if (action == PF_PASS || action == PF_AFRT) {
11181 if (V_pfsync_update_state_ptr != NULL)
11182 V_pfsync_update_state_ptr(s);
11183 r = s->rule;
11184 a = s->anchor;
11185 } else if (s == NULL)
11186 action = pf_test_rule(&r, &s, &pd,
11187 &a, &ruleset, &reason, inp, &match_rules);
11188 break;
11189 }
11190
11191 }
11192
11193 done:
11194 PF_RULES_RUNLOCK();
11195
11196 /* if packet sits in reassembly queue, return without error */
11197 if (pd.m == NULL) {
11198 pf_free_match_rules(&match_rules);
11199 goto eat_pkt;
11200 }
11201
11202 if (s)
11203 memcpy(&pd.act, &s->act, sizeof(s->act));
11204
11205 if (action == PF_PASS && pd.badopts != 0 && !pd.act.allow_opts) {
11206 action = PF_DROP;
11207 REASON_SET(&reason, PFRES_IPOPTIONS);
11208 pd.act.log = PF_LOG_FORCE;
11209 DPFPRINTF(PF_DEBUG_MISC,
11210 "pf: dropping packet with dangerous headers");
11211 }
11212
11213 if (pd.act.max_pkt_size && pd.act.max_pkt_size &&
11214 pd.tot_len > pd.act.max_pkt_size) {
11215 action = PF_DROP;
11216 REASON_SET(&reason, PFRES_NORM);
11217 pd.act.log = PF_LOG_FORCE;
11218 DPFPRINTF(PF_DEBUG_MISC,
11219 "pf: dropping overly long packet");
11220 }
11221
11222 if (s) {
11223 uint8_t log = pd.act.log;
11224 memcpy(&pd.act, &s->act, sizeof(struct pf_rule_actions));
11225 pd.act.log |= log;
11226 tag = s->tag;
11227 } else {
11228 tag = r->tag;
11229 }
11230
11231 if (tag > 0 && pf_tag_packet(&pd, tag)) {
11232 action = PF_DROP;
11233 REASON_SET(&reason, PFRES_MEMORY);
11234 }
11235
11236 pf_scrub(&pd);
11237 if (pd.proto == IPPROTO_TCP && pd.act.max_mss)
11238 pf_normalize_mss(&pd);
11239
11240 if (pd.act.rtableid >= 0)
11241 M_SETFIB(pd.m, pd.act.rtableid);
11242
11243 if (pd.act.flags & PFSTATE_SETPRIO) {
11244 if (pd.tos & IPTOS_LOWDELAY)
11245 use_2nd_queue = 1;
11246 if (vlan_set_pcp(pd.m, pd.act.set_prio[use_2nd_queue])) {
11247 action = PF_DROP;
11248 REASON_SET(&reason, PFRES_MEMORY);
11249 pd.act.log = PF_LOG_FORCE;
11250 DPFPRINTF(PF_DEBUG_MISC,
11251 "pf: failed to allocate 802.1q mtag");
11252 }
11253 }
11254
11255 #ifdef ALTQ
11256 if (action == PF_PASS && pd.act.qid) {
11257 if (pd.pf_mtag == NULL &&
11258 ((pd.pf_mtag = pf_get_mtag(pd.m)) == NULL)) {
11259 action = PF_DROP;
11260 REASON_SET(&reason, PFRES_MEMORY);
11261 } else {
11262 if (s != NULL)
11263 pd.pf_mtag->qid_hash = pf_state_hash(s);
11264 if (use_2nd_queue || (pd.tos & IPTOS_LOWDELAY))
11265 pd.pf_mtag->qid = pd.act.pqid;
11266 else
11267 pd.pf_mtag->qid = pd.act.qid;
11268 /* Add hints for ecn. */
11269 pd.pf_mtag->hdr = mtod(pd.m, void *);
11270 }
11271 }
11272 #endif /* ALTQ */
11273
11274 /*
11275 * connections redirected to loopback should not match sockets
11276 * bound specifically to loopback due to security implications,
11277 * see tcp_input() and in_pcblookup_listen().
11278 */
11279 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
11280 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule != NULL &&
11281 (s->nat_rule->action == PF_RDR ||
11282 s->nat_rule->action == PF_BINAT) &&
11283 pf_is_loopback(af, pd.dst))
11284 pd.m->m_flags |= M_SKIP_FIREWALL;
11285
11286 if (af == AF_INET && __predict_false(ip_divert_ptr != NULL) &&
11287 action == PF_PASS && r->divert.port && !PACKET_LOOPED(&pd)) {
11288 mtag = m_tag_alloc(MTAG_PF_DIVERT, 0,
11289 sizeof(struct pf_divert_mtag), M_NOWAIT | M_ZERO);
11290 if (mtag != NULL) {
11291 ((struct pf_divert_mtag *)(mtag+1))->port =
11292 ntohs(r->divert.port);
11293 ((struct pf_divert_mtag *)(mtag+1))->idir =
11294 (dir == PF_IN) ? PF_DIVERT_MTAG_DIR_IN :
11295 PF_DIVERT_MTAG_DIR_OUT;
11296
11297 pf_counters_inc(action, &pd, s, r, a, &match_rules);
11298
11299 if (s)
11300 PF_STATE_UNLOCK(s);
11301
11302 m_tag_prepend(pd.m, mtag);
11303 if (pd.m->m_flags & M_FASTFWD_OURS) {
11304 if (pd.pf_mtag == NULL &&
11305 ((pd.pf_mtag = pf_get_mtag(pd.m)) == NULL)) {
11306 action = PF_DROP;
11307 REASON_SET(&reason, PFRES_MEMORY);
11308 pd.act.log = PF_LOG_FORCE;
11309 DPFPRINTF(PF_DEBUG_MISC,
11310 "pf: failed to allocate tag");
11311 } else {
11312 pd.pf_mtag->flags |=
11313 PF_MTAG_FLAG_FASTFWD_OURS_PRESENT;
11314 pd.m->m_flags &= ~M_FASTFWD_OURS;
11315 }
11316 }
11317 ip_divert_ptr(*m0, dir == PF_IN);
11318 *m0 = NULL;
11319
11320 return (action);
11321 } else {
11322 /* XXX: ipfw has the same behaviour! */
11323 action = PF_DROP;
11324 REASON_SET(&reason, PFRES_MEMORY);
11325 pd.act.log = PF_LOG_FORCE;
11326 DPFPRINTF(PF_DEBUG_MISC,
11327 "pf: failed to allocate divert tag");
11328 }
11329 }
11330 /* XXX: Anybody working on it?! */
11331 if (af == AF_INET6 && r->divert.port)
11332 printf("pf: divert(9) is not supported for IPv6\n");
11333
11334 /* this flag will need revising if the pkt is forwarded */
11335 if (pd.pf_mtag)
11336 pd.pf_mtag->flags &= ~PF_MTAG_FLAG_PACKET_LOOPED;
11337
11338 if (pd.act.log) {
11339 struct pf_krule *lr;
11340
11341 if (s != NULL && s->nat_rule != NULL &&
11342 s->nat_rule->log & PF_LOG_ALL)
11343 lr = s->nat_rule;
11344 else
11345 lr = r;
11346
11347 if (pd.act.log & PF_LOG_FORCE || lr->log & PF_LOG_ALL)
11348 PFLOG_PACKET(action, reason, lr, a,
11349 ruleset, &pd, (s == NULL), NULL);
11350 if (s) {
11351 SLIST_FOREACH(ri, &s->match_rules, entry)
11352 if (ri->r->log & PF_LOG_ALL)
11353 PFLOG_PACKET(action,
11354 reason, ri->r, a, ruleset, &pd, 0, NULL);
11355 }
11356 }
11357
11358 pf_counters_inc(action, &pd, s, r, a, &match_rules);
11359
11360 switch (action) {
11361 case PF_SYNPROXY_DROP:
11362 m_freem(*m0);
11363 case PF_DEFER:
11364 *m0 = NULL;
11365 action = PF_PASS;
11366 break;
11367 case PF_DROP:
11368 m_freem(*m0);
11369 *m0 = NULL;
11370 break;
11371 case PF_AFRT:
11372 if (pf_translate_af(&pd, r)) {
11373 *m0 = pd.m;
11374 action = PF_DROP;
11375 break;
11376 }
11377 #ifdef INET
11378 if (pd.naf == AF_INET) {
11379 action = pf_route(r, kif->pfik_ifp, s, &pd,
11380 inp);
11381 }
11382 #endif /* INET */
11383 #ifdef INET6
11384 if (pd.naf == AF_INET6) {
11385 action = pf_route6(r, kif->pfik_ifp, s, &pd,
11386 inp);
11387 }
11388 #endif /* INET6 */
11389 *m0 = pd.m;
11390 goto out;
11391 break;
11392 default:
11393 if (pd.act.rt) {
11394 switch (af) {
11395 #ifdef INET
11396 case AF_INET:
11397 /* pf_route() returns unlocked. */
11398 action = pf_route(r, kif->pfik_ifp, s, &pd,
11399 inp);
11400 break;
11401 #endif /* INET */
11402 #ifdef INET6
11403 case AF_INET6:
11404 /* pf_route6() returns unlocked. */
11405 action = pf_route6(r, kif->pfik_ifp, s, &pd,
11406 inp);
11407 break;
11408 #endif /* INET6 */
11409 }
11410 *m0 = pd.m;
11411 goto out;
11412 }
11413 if (pf_dummynet(&pd, s, r, m0) != 0) {
11414 action = PF_DROP;
11415 REASON_SET(&reason, PFRES_MEMORY);
11416 }
11417 break;
11418 }
11419
11420 eat_pkt:
11421 SDT_PROBE4(pf, ip, test, done, action, reason, r, s);
11422
11423 if (s && action != PF_DROP) {
11424 if (!s->if_index_in && dir == PF_IN)
11425 s->if_index_in = ifp->if_index;
11426 else if (!s->if_index_out && dir == PF_OUT)
11427 s->if_index_out = ifp->if_index;
11428 }
11429
11430 if (s)
11431 PF_STATE_UNLOCK(s);
11432
11433 out:
11434 #ifdef INET6
11435 /* If reassembled packet passed, create new fragments. */
11436 if (af == AF_INET6 && action == PF_PASS && *m0 && dir == PF_OUT &&
11437 (! (pflags & PF_PFIL_NOREFRAGMENT)) &&
11438 (mtag = m_tag_find(pd.m, PACKET_TAG_PF_REASSEMBLED, NULL)) != NULL)
11439 action = pf_refragment6(ifp, m0, mtag, NULL, pflags & PFIL_FWD);
11440 #endif /* INET6 */
11441
11442 pf_sctp_multihome_delayed(&pd, kif, s, action);
11443
11444 return (action);
11445 }
11446 #endif /* INET || INET6 */
11447