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