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