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