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