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