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