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