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