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