1 /*- 2 * SPDX-License-Identifier: BSD-2-Clause 3 * 4 * Copyright 2001 Niels Provos <provos@citi.umich.edu> 5 * Copyright 2011-2018 Alexander Bluhm <bluhm@openbsd.org> 6 * All rights reserved. 7 * 8 * Redistribution and use in source and binary forms, with or without 9 * modification, are permitted provided that the following conditions 10 * are met: 11 * 1. Redistributions of source code must retain the above copyright 12 * notice, this list of conditions and the following disclaimer. 13 * 2. Redistributions in binary form must reproduce the above copyright 14 * notice, this list of conditions and the following disclaimer in the 15 * documentation and/or other materials provided with the distribution. 16 * 17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 * 28 * $OpenBSD: pf_norm.c,v 1.114 2009/01/29 14:11:45 henning Exp $ 29 */ 30 31 #include <sys/cdefs.h> 32 #include "opt_inet.h" 33 #include "opt_inet6.h" 34 #include "opt_pf.h" 35 36 #include <sys/param.h> 37 #include <sys/kernel.h> 38 #include <sys/lock.h> 39 #include <sys/mbuf.h> 40 #include <sys/mutex.h> 41 #include <sys/refcount.h> 42 #include <sys/socket.h> 43 44 #include <net/if.h> 45 #include <net/if_var.h> 46 #include <net/vnet.h> 47 #include <net/pfvar.h> 48 #include <net/if_pflog.h> 49 50 #include <netinet/in.h> 51 #include <netinet/ip.h> 52 #include <netinet/ip_var.h> 53 #include <netinet6/in6_var.h> 54 #include <netinet6/nd6.h> 55 #include <netinet6/ip6_var.h> 56 #include <netinet6/scope6_var.h> 57 #include <netinet/tcp.h> 58 #include <netinet/tcp_fsm.h> 59 #include <netinet/tcp_seq.h> 60 #include <netinet/sctp_constants.h> 61 #include <netinet/sctp_header.h> 62 63 #ifdef INET6 64 #include <netinet/ip6.h> 65 #endif /* INET6 */ 66 67 struct pf_frent { 68 TAILQ_ENTRY(pf_frent) fr_next; 69 struct mbuf *fe_m; 70 uint16_t fe_hdrlen; /* ipv4 header length with ip options 71 ipv6, extension, fragment header */ 72 uint16_t fe_extoff; /* last extension header offset or 0 */ 73 uint16_t fe_len; /* fragment length */ 74 uint16_t fe_off; /* fragment offset */ 75 uint16_t fe_mff; /* more fragment flag */ 76 }; 77 78 struct pf_fragment_cmp { 79 struct pf_addr frc_src; 80 struct pf_addr frc_dst; 81 uint32_t frc_id; 82 sa_family_t frc_af; 83 uint8_t frc_proto; 84 }; 85 86 struct pf_fragment { 87 struct pf_fragment_cmp fr_key; 88 #define fr_src fr_key.frc_src 89 #define fr_dst fr_key.frc_dst 90 #define fr_id fr_key.frc_id 91 #define fr_af fr_key.frc_af 92 #define fr_proto fr_key.frc_proto 93 94 /* pointers to queue element */ 95 struct pf_frent *fr_firstoff[PF_FRAG_ENTRY_POINTS]; 96 /* count entries between pointers */ 97 uint8_t fr_entries[PF_FRAG_ENTRY_POINTS]; 98 RB_ENTRY(pf_fragment) fr_entry; 99 TAILQ_ENTRY(pf_fragment) frag_next; 100 uint32_t fr_timeout; 101 TAILQ_HEAD(pf_fragq, pf_frent) fr_queue; 102 uint16_t fr_maxlen; /* maximum length of single fragment */ 103 u_int16_t fr_holes; /* number of holes in the queue */ 104 }; 105 106 VNET_DEFINE_STATIC(struct mtx, pf_frag_mtx); 107 #define V_pf_frag_mtx VNET(pf_frag_mtx) 108 #define PF_FRAG_LOCK() mtx_lock(&V_pf_frag_mtx) 109 #define PF_FRAG_UNLOCK() mtx_unlock(&V_pf_frag_mtx) 110 #define PF_FRAG_ASSERT() mtx_assert(&V_pf_frag_mtx, MA_OWNED) 111 112 VNET_DEFINE(uma_zone_t, pf_state_scrub_z); /* XXX: shared with pfsync */ 113 114 VNET_DEFINE_STATIC(uma_zone_t, pf_frent_z); 115 #define V_pf_frent_z VNET(pf_frent_z) 116 VNET_DEFINE_STATIC(uma_zone_t, pf_frag_z); 117 #define V_pf_frag_z VNET(pf_frag_z) 118 119 TAILQ_HEAD(pf_fragqueue, pf_fragment); 120 TAILQ_HEAD(pf_cachequeue, pf_fragment); 121 VNET_DEFINE_STATIC(struct pf_fragqueue, pf_fragqueue); 122 #define V_pf_fragqueue VNET(pf_fragqueue) 123 RB_HEAD(pf_frag_tree, pf_fragment); 124 VNET_DEFINE_STATIC(struct pf_frag_tree, pf_frag_tree); 125 #define V_pf_frag_tree VNET(pf_frag_tree) 126 static int pf_frag_compare(struct pf_fragment *, 127 struct pf_fragment *); 128 static RB_PROTOTYPE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare); 129 static RB_GENERATE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare); 130 131 static void pf_flush_fragments(void); 132 static void pf_free_fragment(struct pf_fragment *); 133 134 static struct pf_frent *pf_create_fragment(u_short *); 135 static int pf_frent_holes(struct pf_frent *frent); 136 static struct pf_fragment *pf_find_fragment(struct pf_fragment_cmp *key, 137 struct pf_frag_tree *tree); 138 static inline int pf_frent_index(struct pf_frent *); 139 static int pf_frent_insert(struct pf_fragment *, 140 struct pf_frent *, struct pf_frent *); 141 void pf_frent_remove(struct pf_fragment *, 142 struct pf_frent *); 143 struct pf_frent *pf_frent_previous(struct pf_fragment *, 144 struct pf_frent *); 145 static struct pf_fragment *pf_fillup_fragment(struct pf_fragment_cmp *, 146 struct pf_frent *, u_short *); 147 static struct mbuf *pf_join_fragment(struct pf_fragment *); 148 #ifdef INET 149 static int pf_reassemble(struct mbuf **, int, u_short *); 150 #endif /* INET */ 151 #ifdef INET6 152 static int pf_reassemble6(struct mbuf **, 153 struct ip6_frag *, uint16_t, uint16_t, u_short *); 154 #endif /* INET6 */ 155 156 #define DPFPRINTF(x) do { \ 157 if (V_pf_status.debug >= PF_DEBUG_MISC) { \ 158 printf("%s: ", __func__); \ 159 printf x ; \ 160 } \ 161 } while(0) 162 163 #ifdef INET 164 static void 165 pf_ip2key(struct ip *ip, int dir, struct pf_fragment_cmp *key) 166 { 167 168 key->frc_src.v4 = ip->ip_src; 169 key->frc_dst.v4 = ip->ip_dst; 170 key->frc_af = AF_INET; 171 key->frc_proto = ip->ip_p; 172 key->frc_id = ip->ip_id; 173 } 174 #endif /* INET */ 175 176 void 177 pf_normalize_init(void) 178 { 179 180 V_pf_frag_z = uma_zcreate("pf frags", sizeof(struct pf_fragment), 181 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0); 182 V_pf_frent_z = uma_zcreate("pf frag entries", sizeof(struct pf_frent), 183 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0); 184 V_pf_state_scrub_z = uma_zcreate("pf state scrubs", 185 sizeof(struct pf_state_scrub), NULL, NULL, NULL, NULL, 186 UMA_ALIGN_PTR, 0); 187 188 mtx_init(&V_pf_frag_mtx, "pf fragments", NULL, MTX_DEF); 189 190 V_pf_limits[PF_LIMIT_FRAGS].zone = V_pf_frent_z; 191 V_pf_limits[PF_LIMIT_FRAGS].limit = PFFRAG_FRENT_HIWAT; 192 uma_zone_set_max(V_pf_frent_z, PFFRAG_FRENT_HIWAT); 193 uma_zone_set_warning(V_pf_frent_z, "PF frag entries limit reached"); 194 195 TAILQ_INIT(&V_pf_fragqueue); 196 } 197 198 void 199 pf_normalize_cleanup(void) 200 { 201 202 uma_zdestroy(V_pf_state_scrub_z); 203 uma_zdestroy(V_pf_frent_z); 204 uma_zdestroy(V_pf_frag_z); 205 206 mtx_destroy(&V_pf_frag_mtx); 207 } 208 209 static int 210 pf_frag_compare(struct pf_fragment *a, struct pf_fragment *b) 211 { 212 int diff; 213 214 if ((diff = a->fr_id - b->fr_id) != 0) 215 return (diff); 216 if ((diff = a->fr_proto - b->fr_proto) != 0) 217 return (diff); 218 if ((diff = a->fr_af - b->fr_af) != 0) 219 return (diff); 220 if ((diff = pf_addr_cmp(&a->fr_src, &b->fr_src, a->fr_af)) != 0) 221 return (diff); 222 if ((diff = pf_addr_cmp(&a->fr_dst, &b->fr_dst, a->fr_af)) != 0) 223 return (diff); 224 return (0); 225 } 226 227 void 228 pf_purge_expired_fragments(void) 229 { 230 u_int32_t expire = time_uptime - 231 V_pf_default_rule.timeout[PFTM_FRAG]; 232 233 pf_purge_fragments(expire); 234 } 235 236 void 237 pf_purge_fragments(uint32_t expire) 238 { 239 struct pf_fragment *frag; 240 241 PF_FRAG_LOCK(); 242 while ((frag = TAILQ_LAST(&V_pf_fragqueue, pf_fragqueue)) != NULL) { 243 if (frag->fr_timeout > expire) 244 break; 245 246 DPFPRINTF(("expiring %d(%p)\n", frag->fr_id, frag)); 247 pf_free_fragment(frag); 248 } 249 250 PF_FRAG_UNLOCK(); 251 } 252 253 /* 254 * Try to flush old fragments to make space for new ones 255 */ 256 static void 257 pf_flush_fragments(void) 258 { 259 struct pf_fragment *frag; 260 int goal; 261 262 PF_FRAG_ASSERT(); 263 264 goal = uma_zone_get_cur(V_pf_frent_z) * 9 / 10; 265 DPFPRINTF(("trying to free %d frag entriess\n", goal)); 266 while (goal < uma_zone_get_cur(V_pf_frent_z)) { 267 frag = TAILQ_LAST(&V_pf_fragqueue, pf_fragqueue); 268 if (frag) 269 pf_free_fragment(frag); 270 else 271 break; 272 } 273 } 274 275 /* 276 * Remove a fragment from the fragment queue, free its fragment entries, 277 * and free the fragment itself. 278 */ 279 static void 280 pf_free_fragment(struct pf_fragment *frag) 281 { 282 struct pf_frent *frent; 283 284 PF_FRAG_ASSERT(); 285 286 RB_REMOVE(pf_frag_tree, &V_pf_frag_tree, frag); 287 TAILQ_REMOVE(&V_pf_fragqueue, frag, frag_next); 288 289 /* Free all fragment entries */ 290 while ((frent = TAILQ_FIRST(&frag->fr_queue)) != NULL) { 291 TAILQ_REMOVE(&frag->fr_queue, frent, fr_next); 292 293 m_freem(frent->fe_m); 294 uma_zfree(V_pf_frent_z, frent); 295 } 296 297 uma_zfree(V_pf_frag_z, frag); 298 } 299 300 static struct pf_fragment * 301 pf_find_fragment(struct pf_fragment_cmp *key, struct pf_frag_tree *tree) 302 { 303 struct pf_fragment *frag; 304 305 PF_FRAG_ASSERT(); 306 307 frag = RB_FIND(pf_frag_tree, tree, (struct pf_fragment *)key); 308 if (frag != NULL) { 309 /* XXX Are we sure we want to update the timeout? */ 310 frag->fr_timeout = time_uptime; 311 TAILQ_REMOVE(&V_pf_fragqueue, frag, frag_next); 312 TAILQ_INSERT_HEAD(&V_pf_fragqueue, frag, frag_next); 313 } 314 315 return (frag); 316 } 317 318 /* Removes a fragment from the fragment queue and frees the fragment */ 319 static void 320 pf_remove_fragment(struct pf_fragment *frag) 321 { 322 323 PF_FRAG_ASSERT(); 324 KASSERT(frag, ("frag != NULL")); 325 326 RB_REMOVE(pf_frag_tree, &V_pf_frag_tree, frag); 327 TAILQ_REMOVE(&V_pf_fragqueue, frag, frag_next); 328 uma_zfree(V_pf_frag_z, frag); 329 } 330 331 static struct pf_frent * 332 pf_create_fragment(u_short *reason) 333 { 334 struct pf_frent *frent; 335 336 PF_FRAG_ASSERT(); 337 338 frent = uma_zalloc(V_pf_frent_z, M_NOWAIT); 339 if (frent == NULL) { 340 pf_flush_fragments(); 341 frent = uma_zalloc(V_pf_frent_z, M_NOWAIT); 342 if (frent == NULL) { 343 REASON_SET(reason, PFRES_MEMORY); 344 return (NULL); 345 } 346 } 347 348 return (frent); 349 } 350 351 /* 352 * Calculate the additional holes that were created in the fragment 353 * queue by inserting this fragment. A fragment in the middle 354 * creates one more hole by splitting. For each connected side, 355 * it loses one hole. 356 * Fragment entry must be in the queue when calling this function. 357 */ 358 static int 359 pf_frent_holes(struct pf_frent *frent) 360 { 361 struct pf_frent *prev = TAILQ_PREV(frent, pf_fragq, fr_next); 362 struct pf_frent *next = TAILQ_NEXT(frent, fr_next); 363 int holes = 1; 364 365 if (prev == NULL) { 366 if (frent->fe_off == 0) 367 holes--; 368 } else { 369 KASSERT(frent->fe_off != 0, ("frent->fe_off != 0")); 370 if (frent->fe_off == prev->fe_off + prev->fe_len) 371 holes--; 372 } 373 if (next == NULL) { 374 if (!frent->fe_mff) 375 holes--; 376 } else { 377 KASSERT(frent->fe_mff, ("frent->fe_mff")); 378 if (next->fe_off == frent->fe_off + frent->fe_len) 379 holes--; 380 } 381 return holes; 382 } 383 384 static inline int 385 pf_frent_index(struct pf_frent *frent) 386 { 387 /* 388 * We have an array of 16 entry points to the queue. A full size 389 * 65535 octet IP packet can have 8192 fragments. So the queue 390 * traversal length is at most 512 and at most 16 entry points are 391 * checked. We need 128 additional bytes on a 64 bit architecture. 392 */ 393 CTASSERT(((u_int16_t)0xffff &~ 7) / (0x10000 / PF_FRAG_ENTRY_POINTS) == 394 16 - 1); 395 CTASSERT(((u_int16_t)0xffff >> 3) / PF_FRAG_ENTRY_POINTS == 512 - 1); 396 397 return frent->fe_off / (0x10000 / PF_FRAG_ENTRY_POINTS); 398 } 399 400 static int 401 pf_frent_insert(struct pf_fragment *frag, struct pf_frent *frent, 402 struct pf_frent *prev) 403 { 404 int index; 405 406 CTASSERT(PF_FRAG_ENTRY_LIMIT <= 0xff); 407 408 /* 409 * A packet has at most 65536 octets. With 16 entry points, each one 410 * spawns 4096 octets. We limit these to 64 fragments each, which 411 * means on average every fragment must have at least 64 octets. 412 */ 413 index = pf_frent_index(frent); 414 if (frag->fr_entries[index] >= PF_FRAG_ENTRY_LIMIT) 415 return ENOBUFS; 416 frag->fr_entries[index]++; 417 418 if (prev == NULL) { 419 TAILQ_INSERT_HEAD(&frag->fr_queue, frent, fr_next); 420 } else { 421 KASSERT(prev->fe_off + prev->fe_len <= frent->fe_off, 422 ("overlapping fragment")); 423 TAILQ_INSERT_AFTER(&frag->fr_queue, prev, frent, fr_next); 424 } 425 426 if (frag->fr_firstoff[index] == NULL) { 427 KASSERT(prev == NULL || pf_frent_index(prev) < index, 428 ("prev == NULL || pf_frent_index(pref) < index")); 429 frag->fr_firstoff[index] = frent; 430 } else { 431 if (frent->fe_off < frag->fr_firstoff[index]->fe_off) { 432 KASSERT(prev == NULL || pf_frent_index(prev) < index, 433 ("prev == NULL || pf_frent_index(pref) < index")); 434 frag->fr_firstoff[index] = frent; 435 } else { 436 KASSERT(prev != NULL, ("prev != NULL")); 437 KASSERT(pf_frent_index(prev) == index, 438 ("pf_frent_index(prev) == index")); 439 } 440 } 441 442 frag->fr_holes += pf_frent_holes(frent); 443 444 return 0; 445 } 446 447 void 448 pf_frent_remove(struct pf_fragment *frag, struct pf_frent *frent) 449 { 450 #ifdef INVARIANTS 451 struct pf_frent *prev = TAILQ_PREV(frent, pf_fragq, fr_next); 452 #endif 453 struct pf_frent *next = TAILQ_NEXT(frent, fr_next); 454 int index; 455 456 frag->fr_holes -= pf_frent_holes(frent); 457 458 index = pf_frent_index(frent); 459 KASSERT(frag->fr_firstoff[index] != NULL, ("frent not found")); 460 if (frag->fr_firstoff[index]->fe_off == frent->fe_off) { 461 if (next == NULL) { 462 frag->fr_firstoff[index] = NULL; 463 } else { 464 KASSERT(frent->fe_off + frent->fe_len <= next->fe_off, 465 ("overlapping fragment")); 466 if (pf_frent_index(next) == index) { 467 frag->fr_firstoff[index] = next; 468 } else { 469 frag->fr_firstoff[index] = NULL; 470 } 471 } 472 } else { 473 KASSERT(frag->fr_firstoff[index]->fe_off < frent->fe_off, 474 ("frag->fr_firstoff[index]->fe_off < frent->fe_off")); 475 KASSERT(prev != NULL, ("prev != NULL")); 476 KASSERT(prev->fe_off + prev->fe_len <= frent->fe_off, 477 ("overlapping fragment")); 478 KASSERT(pf_frent_index(prev) == index, 479 ("pf_frent_index(prev) == index")); 480 } 481 482 TAILQ_REMOVE(&frag->fr_queue, frent, fr_next); 483 484 KASSERT(frag->fr_entries[index] > 0, ("No fragments remaining")); 485 frag->fr_entries[index]--; 486 } 487 488 struct pf_frent * 489 pf_frent_previous(struct pf_fragment *frag, struct pf_frent *frent) 490 { 491 struct pf_frent *prev, *next; 492 int index; 493 494 /* 495 * If there are no fragments after frag, take the final one. Assume 496 * that the global queue is not empty. 497 */ 498 prev = TAILQ_LAST(&frag->fr_queue, pf_fragq); 499 KASSERT(prev != NULL, ("prev != NULL")); 500 if (prev->fe_off <= frent->fe_off) 501 return prev; 502 /* 503 * We want to find a fragment entry that is before frag, but still 504 * close to it. Find the first fragment entry that is in the same 505 * entry point or in the first entry point after that. As we have 506 * already checked that there are entries behind frag, this will 507 * succeed. 508 */ 509 for (index = pf_frent_index(frent); index < PF_FRAG_ENTRY_POINTS; 510 index++) { 511 prev = frag->fr_firstoff[index]; 512 if (prev != NULL) 513 break; 514 } 515 KASSERT(prev != NULL, ("prev != NULL")); 516 /* 517 * In prev we may have a fragment from the same entry point that is 518 * before frent, or one that is just one position behind frent. 519 * In the latter case, we go back one step and have the predecessor. 520 * There may be none if the new fragment will be the first one. 521 */ 522 if (prev->fe_off > frent->fe_off) { 523 prev = TAILQ_PREV(prev, pf_fragq, fr_next); 524 if (prev == NULL) 525 return NULL; 526 KASSERT(prev->fe_off <= frent->fe_off, 527 ("prev->fe_off <= frent->fe_off")); 528 return prev; 529 } 530 /* 531 * In prev is the first fragment of the entry point. The offset 532 * of frag is behind it. Find the closest previous fragment. 533 */ 534 for (next = TAILQ_NEXT(prev, fr_next); next != NULL; 535 next = TAILQ_NEXT(next, fr_next)) { 536 if (next->fe_off > frent->fe_off) 537 break; 538 prev = next; 539 } 540 return prev; 541 } 542 543 static struct pf_fragment * 544 pf_fillup_fragment(struct pf_fragment_cmp *key, struct pf_frent *frent, 545 u_short *reason) 546 { 547 struct pf_frent *after, *next, *prev; 548 struct pf_fragment *frag; 549 uint16_t total; 550 int old_index, new_index; 551 552 PF_FRAG_ASSERT(); 553 554 /* No empty fragments. */ 555 if (frent->fe_len == 0) { 556 DPFPRINTF(("bad fragment: len 0\n")); 557 goto bad_fragment; 558 } 559 560 /* All fragments are 8 byte aligned. */ 561 if (frent->fe_mff && (frent->fe_len & 0x7)) { 562 DPFPRINTF(("bad fragment: mff and len %d\n", frent->fe_len)); 563 goto bad_fragment; 564 } 565 566 /* Respect maximum length, IP_MAXPACKET == IPV6_MAXPACKET. */ 567 if (frent->fe_off + frent->fe_len > IP_MAXPACKET) { 568 DPFPRINTF(("bad fragment: max packet %d\n", 569 frent->fe_off + frent->fe_len)); 570 goto bad_fragment; 571 } 572 573 DPFPRINTF((key->frc_af == AF_INET ? 574 "reass frag %d @ %d-%d\n" : "reass frag %#08x @ %d-%d\n", 575 key->frc_id, frent->fe_off, frent->fe_off + frent->fe_len)); 576 577 /* Fully buffer all of the fragments in this fragment queue. */ 578 frag = pf_find_fragment(key, &V_pf_frag_tree); 579 580 /* Create a new reassembly queue for this packet. */ 581 if (frag == NULL) { 582 frag = uma_zalloc(V_pf_frag_z, M_NOWAIT); 583 if (frag == NULL) { 584 pf_flush_fragments(); 585 frag = uma_zalloc(V_pf_frag_z, M_NOWAIT); 586 if (frag == NULL) { 587 REASON_SET(reason, PFRES_MEMORY); 588 goto drop_fragment; 589 } 590 } 591 592 *(struct pf_fragment_cmp *)frag = *key; 593 memset(frag->fr_firstoff, 0, sizeof(frag->fr_firstoff)); 594 memset(frag->fr_entries, 0, sizeof(frag->fr_entries)); 595 frag->fr_timeout = time_uptime; 596 TAILQ_INIT(&frag->fr_queue); 597 frag->fr_maxlen = frent->fe_len; 598 frag->fr_holes = 1; 599 600 RB_INSERT(pf_frag_tree, &V_pf_frag_tree, frag); 601 TAILQ_INSERT_HEAD(&V_pf_fragqueue, frag, frag_next); 602 603 /* We do not have a previous fragment, cannot fail. */ 604 pf_frent_insert(frag, frent, NULL); 605 606 return (frag); 607 } 608 609 KASSERT(!TAILQ_EMPTY(&frag->fr_queue), ("!TAILQ_EMPTY()->fr_queue")); 610 611 /* Remember maximum fragment len for refragmentation. */ 612 if (frent->fe_len > frag->fr_maxlen) 613 frag->fr_maxlen = frent->fe_len; 614 615 /* Maximum data we have seen already. */ 616 total = TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_off + 617 TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_len; 618 619 /* Non terminal fragments must have more fragments flag. */ 620 if (frent->fe_off + frent->fe_len < total && !frent->fe_mff) 621 goto bad_fragment; 622 623 /* Check if we saw the last fragment already. */ 624 if (!TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_mff) { 625 if (frent->fe_off + frent->fe_len > total || 626 (frent->fe_off + frent->fe_len == total && frent->fe_mff)) 627 goto bad_fragment; 628 } else { 629 if (frent->fe_off + frent->fe_len == total && !frent->fe_mff) 630 goto bad_fragment; 631 } 632 633 /* Find neighbors for newly inserted fragment */ 634 prev = pf_frent_previous(frag, frent); 635 if (prev == NULL) { 636 after = TAILQ_FIRST(&frag->fr_queue); 637 KASSERT(after != NULL, ("after != NULL")); 638 } else { 639 after = TAILQ_NEXT(prev, fr_next); 640 } 641 642 if (prev != NULL && prev->fe_off + prev->fe_len > frent->fe_off) { 643 uint16_t precut; 644 645 if (frag->fr_af == AF_INET6) 646 goto free_fragment; 647 648 precut = prev->fe_off + prev->fe_len - frent->fe_off; 649 if (precut >= frent->fe_len) { 650 DPFPRINTF(("new frag overlapped\n")); 651 goto drop_fragment; 652 } 653 DPFPRINTF(("frag head overlap %d\n", precut)); 654 m_adj(frent->fe_m, precut); 655 frent->fe_off += precut; 656 frent->fe_len -= precut; 657 } 658 659 for (; after != NULL && frent->fe_off + frent->fe_len > after->fe_off; 660 after = next) { 661 uint16_t aftercut; 662 663 aftercut = frent->fe_off + frent->fe_len - after->fe_off; 664 DPFPRINTF(("adjust overlap %d\n", aftercut)); 665 if (aftercut < after->fe_len) { 666 m_adj(after->fe_m, aftercut); 667 old_index = pf_frent_index(after); 668 after->fe_off += aftercut; 669 after->fe_len -= aftercut; 670 new_index = pf_frent_index(after); 671 if (old_index != new_index) { 672 DPFPRINTF(("frag index %d, new %d\n", 673 old_index, new_index)); 674 /* Fragment switched queue as fe_off changed */ 675 after->fe_off -= aftercut; 676 after->fe_len += aftercut; 677 /* Remove restored fragment from old queue */ 678 pf_frent_remove(frag, after); 679 after->fe_off += aftercut; 680 after->fe_len -= aftercut; 681 /* Insert into correct queue */ 682 if (pf_frent_insert(frag, after, prev)) { 683 DPFPRINTF( 684 ("fragment requeue limit exceeded\n")); 685 m_freem(after->fe_m); 686 uma_zfree(V_pf_frent_z, after); 687 /* There is not way to recover */ 688 goto bad_fragment; 689 } 690 } 691 break; 692 } 693 694 /* This fragment is completely overlapped, lose it. */ 695 DPFPRINTF(("old frag overlapped\n")); 696 next = TAILQ_NEXT(after, fr_next); 697 pf_frent_remove(frag, after); 698 m_freem(after->fe_m); 699 uma_zfree(V_pf_frent_z, after); 700 } 701 702 /* If part of the queue gets too long, there is not way to recover. */ 703 if (pf_frent_insert(frag, frent, prev)) { 704 DPFPRINTF(("fragment queue limit exceeded\n")); 705 goto bad_fragment; 706 } 707 708 return (frag); 709 710 free_fragment: 711 /* 712 * RFC 5722, Errata 3089: When reassembling an IPv6 datagram, if one 713 * or more its constituent fragments is determined to be an overlapping 714 * fragment, the entire datagram (and any constituent fragments) MUST 715 * be silently discarded. 716 */ 717 DPFPRINTF(("flush overlapping fragments\n")); 718 pf_free_fragment(frag); 719 720 bad_fragment: 721 REASON_SET(reason, PFRES_FRAG); 722 drop_fragment: 723 uma_zfree(V_pf_frent_z, frent); 724 return (NULL); 725 } 726 727 static struct mbuf * 728 pf_join_fragment(struct pf_fragment *frag) 729 { 730 struct mbuf *m, *m2; 731 struct pf_frent *frent; 732 733 frent = TAILQ_FIRST(&frag->fr_queue); 734 TAILQ_REMOVE(&frag->fr_queue, frent, fr_next); 735 736 m = frent->fe_m; 737 m_adj(m, (frent->fe_hdrlen + frent->fe_len) - m->m_pkthdr.len); 738 uma_zfree(V_pf_frent_z, frent); 739 while ((frent = TAILQ_FIRST(&frag->fr_queue)) != NULL) { 740 TAILQ_REMOVE(&frag->fr_queue, frent, fr_next); 741 742 m2 = frent->fe_m; 743 /* Strip off ip header. */ 744 m_adj(m2, frent->fe_hdrlen); 745 /* Strip off any trailing bytes. */ 746 m_adj(m2, frent->fe_len - m2->m_pkthdr.len); 747 748 uma_zfree(V_pf_frent_z, frent); 749 m_cat(m, m2); 750 } 751 752 /* Remove from fragment queue. */ 753 pf_free_fragment(frag); 754 755 return (m); 756 } 757 758 #ifdef INET 759 static int 760 pf_reassemble(struct mbuf **m0, int dir, u_short *reason) 761 { 762 struct mbuf *m = *m0; 763 struct ip *ip = mtod(m, struct ip *); 764 struct pf_frent *frent; 765 struct pf_fragment *frag; 766 struct m_tag *mtag; 767 struct pf_fragment_tag *ftag; 768 struct pf_fragment_cmp key; 769 uint16_t total, hdrlen; 770 uint32_t frag_id; 771 uint16_t maxlen; 772 773 /* Get an entry for the fragment queue */ 774 if ((frent = pf_create_fragment(reason)) == NULL) 775 return (PF_DROP); 776 777 frent->fe_m = m; 778 frent->fe_hdrlen = ip->ip_hl << 2; 779 frent->fe_extoff = 0; 780 frent->fe_len = ntohs(ip->ip_len) - (ip->ip_hl << 2); 781 frent->fe_off = (ntohs(ip->ip_off) & IP_OFFMASK) << 3; 782 frent->fe_mff = ntohs(ip->ip_off) & IP_MF; 783 784 pf_ip2key(ip, dir, &key); 785 786 if ((frag = pf_fillup_fragment(&key, frent, reason)) == NULL) 787 return (PF_DROP); 788 789 /* The mbuf is part of the fragment entry, no direct free or access */ 790 m = *m0 = NULL; 791 792 if (frag->fr_holes) { 793 DPFPRINTF(("frag %d, holes %d\n", frag->fr_id, frag->fr_holes)); 794 return (PF_PASS); /* drop because *m0 is NULL, no error */ 795 } 796 797 /* We have all the data */ 798 frent = TAILQ_FIRST(&frag->fr_queue); 799 KASSERT(frent != NULL, ("frent != NULL")); 800 total = TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_off + 801 TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_len; 802 hdrlen = frent->fe_hdrlen; 803 804 maxlen = frag->fr_maxlen; 805 frag_id = frag->fr_id; 806 m = *m0 = pf_join_fragment(frag); 807 frag = NULL; 808 809 if (m->m_flags & M_PKTHDR) { 810 int plen = 0; 811 for (m = *m0; m; m = m->m_next) 812 plen += m->m_len; 813 m = *m0; 814 m->m_pkthdr.len = plen; 815 } 816 817 if ((mtag = m_tag_get(PACKET_TAG_PF_REASSEMBLED, 818 sizeof(struct pf_fragment_tag), M_NOWAIT)) == NULL) { 819 REASON_SET(reason, PFRES_SHORT); 820 /* PF_DROP requires a valid mbuf *m0 in pf_test() */ 821 return (PF_DROP); 822 } 823 ftag = (struct pf_fragment_tag *)(mtag + 1); 824 ftag->ft_hdrlen = hdrlen; 825 ftag->ft_extoff = 0; 826 ftag->ft_maxlen = maxlen; 827 ftag->ft_id = frag_id; 828 m_tag_prepend(m, mtag); 829 830 ip = mtod(m, struct ip *); 831 ip->ip_sum = pf_cksum_fixup(ip->ip_sum, ip->ip_len, 832 htons(hdrlen + total), 0); 833 ip->ip_len = htons(hdrlen + total); 834 ip->ip_sum = pf_cksum_fixup(ip->ip_sum, ip->ip_off, 835 ip->ip_off & ~(IP_MF|IP_OFFMASK), 0); 836 ip->ip_off &= ~(IP_MF|IP_OFFMASK); 837 838 if (hdrlen + total > IP_MAXPACKET) { 839 DPFPRINTF(("drop: too big: %d\n", total)); 840 ip->ip_len = 0; 841 REASON_SET(reason, PFRES_SHORT); 842 /* PF_DROP requires a valid mbuf *m0 in pf_test() */ 843 return (PF_DROP); 844 } 845 846 DPFPRINTF(("complete: %p(%d)\n", m, ntohs(ip->ip_len))); 847 return (PF_PASS); 848 } 849 #endif /* INET */ 850 851 #ifdef INET6 852 static int 853 pf_reassemble6(struct mbuf **m0, struct ip6_frag *fraghdr, 854 uint16_t hdrlen, uint16_t extoff, u_short *reason) 855 { 856 struct mbuf *m = *m0; 857 struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *); 858 struct pf_frent *frent; 859 struct pf_fragment *frag; 860 struct pf_fragment_cmp key; 861 struct m_tag *mtag; 862 struct pf_fragment_tag *ftag; 863 int off; 864 uint32_t frag_id; 865 uint16_t total, maxlen; 866 uint8_t proto; 867 868 PF_FRAG_LOCK(); 869 870 /* Get an entry for the fragment queue. */ 871 if ((frent = pf_create_fragment(reason)) == NULL) { 872 PF_FRAG_UNLOCK(); 873 return (PF_DROP); 874 } 875 876 frent->fe_m = m; 877 frent->fe_hdrlen = hdrlen; 878 frent->fe_extoff = extoff; 879 frent->fe_len = sizeof(struct ip6_hdr) + ntohs(ip6->ip6_plen) - hdrlen; 880 frent->fe_off = ntohs(fraghdr->ip6f_offlg & IP6F_OFF_MASK); 881 frent->fe_mff = fraghdr->ip6f_offlg & IP6F_MORE_FRAG; 882 883 key.frc_src.v6 = ip6->ip6_src; 884 key.frc_dst.v6 = ip6->ip6_dst; 885 key.frc_af = AF_INET6; 886 /* Only the first fragment's protocol is relevant. */ 887 key.frc_proto = 0; 888 key.frc_id = fraghdr->ip6f_ident; 889 890 if ((frag = pf_fillup_fragment(&key, frent, reason)) == NULL) { 891 PF_FRAG_UNLOCK(); 892 return (PF_DROP); 893 } 894 895 /* The mbuf is part of the fragment entry, no direct free or access. */ 896 m = *m0 = NULL; 897 898 if (frag->fr_holes) { 899 DPFPRINTF(("frag %d, holes %d\n", frag->fr_id, 900 frag->fr_holes)); 901 PF_FRAG_UNLOCK(); 902 return (PF_PASS); /* Drop because *m0 is NULL, no error. */ 903 } 904 905 /* We have all the data. */ 906 frent = TAILQ_FIRST(&frag->fr_queue); 907 KASSERT(frent != NULL, ("frent != NULL")); 908 extoff = frent->fe_extoff; 909 maxlen = frag->fr_maxlen; 910 frag_id = frag->fr_id; 911 total = TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_off + 912 TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_len; 913 hdrlen = frent->fe_hdrlen - sizeof(struct ip6_frag); 914 915 m = *m0 = pf_join_fragment(frag); 916 frag = NULL; 917 918 PF_FRAG_UNLOCK(); 919 920 /* Take protocol from first fragment header. */ 921 m = m_getptr(m, hdrlen + offsetof(struct ip6_frag, ip6f_nxt), &off); 922 KASSERT(m, ("%s: short mbuf chain", __func__)); 923 proto = *(mtod(m, uint8_t *) + off); 924 m = *m0; 925 926 /* Delete frag6 header */ 927 if (ip6_deletefraghdr(m, hdrlen, M_NOWAIT) != 0) 928 goto fail; 929 930 if (m->m_flags & M_PKTHDR) { 931 int plen = 0; 932 for (m = *m0; m; m = m->m_next) 933 plen += m->m_len; 934 m = *m0; 935 m->m_pkthdr.len = plen; 936 } 937 938 if ((mtag = m_tag_get(PACKET_TAG_PF_REASSEMBLED, 939 sizeof(struct pf_fragment_tag), M_NOWAIT)) == NULL) 940 goto fail; 941 ftag = (struct pf_fragment_tag *)(mtag + 1); 942 ftag->ft_hdrlen = hdrlen; 943 ftag->ft_extoff = extoff; 944 ftag->ft_maxlen = maxlen; 945 ftag->ft_id = frag_id; 946 m_tag_prepend(m, mtag); 947 948 ip6 = mtod(m, struct ip6_hdr *); 949 ip6->ip6_plen = htons(hdrlen - sizeof(struct ip6_hdr) + total); 950 if (extoff) { 951 /* Write protocol into next field of last extension header. */ 952 m = m_getptr(m, extoff + offsetof(struct ip6_ext, ip6e_nxt), 953 &off); 954 KASSERT(m, ("%s: short mbuf chain", __func__)); 955 *(mtod(m, char *) + off) = proto; 956 m = *m0; 957 } else 958 ip6->ip6_nxt = proto; 959 960 if (hdrlen - sizeof(struct ip6_hdr) + total > IPV6_MAXPACKET) { 961 DPFPRINTF(("drop: too big: %d\n", total)); 962 ip6->ip6_plen = 0; 963 REASON_SET(reason, PFRES_SHORT); 964 /* PF_DROP requires a valid mbuf *m0 in pf_test6(). */ 965 return (PF_DROP); 966 } 967 968 DPFPRINTF(("complete: %p(%d)\n", m, ntohs(ip6->ip6_plen))); 969 return (PF_PASS); 970 971 fail: 972 REASON_SET(reason, PFRES_MEMORY); 973 /* PF_DROP requires a valid mbuf *m0 in pf_test6(), will free later. */ 974 return (PF_DROP); 975 } 976 #endif /* INET6 */ 977 978 #ifdef INET6 979 int 980 pf_max_frag_size(struct mbuf *m) 981 { 982 struct m_tag *tag; 983 struct pf_fragment_tag *ftag; 984 985 tag = m_tag_find(m, PACKET_TAG_PF_REASSEMBLED, NULL); 986 if (tag == NULL) 987 return (m->m_pkthdr.len); 988 989 ftag = (struct pf_fragment_tag *)(tag + 1); 990 991 return (ftag->ft_maxlen); 992 } 993 994 int 995 pf_refragment6(struct ifnet *ifp, struct mbuf **m0, struct m_tag *mtag, 996 struct ifnet *rt, bool forward) 997 { 998 struct mbuf *m = *m0, *t; 999 struct ip6_hdr *hdr; 1000 struct pf_fragment_tag *ftag = (struct pf_fragment_tag *)(mtag + 1); 1001 struct pf_pdesc pd; 1002 uint32_t frag_id; 1003 uint16_t hdrlen, extoff, maxlen; 1004 uint8_t proto; 1005 int error, action; 1006 1007 hdrlen = ftag->ft_hdrlen; 1008 extoff = ftag->ft_extoff; 1009 maxlen = ftag->ft_maxlen; 1010 frag_id = ftag->ft_id; 1011 m_tag_delete(m, mtag); 1012 mtag = NULL; 1013 ftag = NULL; 1014 1015 if (extoff) { 1016 int off; 1017 1018 /* Use protocol from next field of last extension header */ 1019 m = m_getptr(m, extoff + offsetof(struct ip6_ext, ip6e_nxt), 1020 &off); 1021 KASSERT((m != NULL), ("pf_refragment6: short mbuf chain")); 1022 proto = *(mtod(m, uint8_t *) + off); 1023 *(mtod(m, char *) + off) = IPPROTO_FRAGMENT; 1024 m = *m0; 1025 } else { 1026 hdr = mtod(m, struct ip6_hdr *); 1027 proto = hdr->ip6_nxt; 1028 hdr->ip6_nxt = IPPROTO_FRAGMENT; 1029 } 1030 1031 /* In case of link-local traffic we'll need a scope set. */ 1032 hdr = mtod(m, struct ip6_hdr *); 1033 1034 in6_setscope(&hdr->ip6_src, ifp, NULL); 1035 in6_setscope(&hdr->ip6_dst, ifp, NULL); 1036 1037 /* The MTU must be a multiple of 8 bytes, or we risk doing the 1038 * fragmentation wrong. */ 1039 maxlen = maxlen & ~7; 1040 1041 /* 1042 * Maxlen may be less than 8 if there was only a single 1043 * fragment. As it was fragmented before, add a fragment 1044 * header also for a single fragment. If total or maxlen 1045 * is less than 8, ip6_fragment() will return EMSGSIZE and 1046 * we drop the packet. 1047 */ 1048 error = ip6_fragment(ifp, m, hdrlen, proto, maxlen, frag_id); 1049 m = (*m0)->m_nextpkt; 1050 (*m0)->m_nextpkt = NULL; 1051 if (error == 0) { 1052 /* The first mbuf contains the unfragmented packet. */ 1053 m_freem(*m0); 1054 *m0 = NULL; 1055 action = PF_PASS; 1056 } else { 1057 /* Drop expects an mbuf to free. */ 1058 DPFPRINTF(("refragment error %d\n", error)); 1059 action = PF_DROP; 1060 } 1061 for (; m; m = t) { 1062 t = m->m_nextpkt; 1063 m->m_nextpkt = NULL; 1064 m->m_flags |= M_SKIP_FIREWALL; 1065 memset(&pd, 0, sizeof(pd)); 1066 pd.pf_mtag = pf_find_mtag(m); 1067 if (error != 0) { 1068 m_freem(m); 1069 continue; 1070 } 1071 if (rt != NULL) { 1072 struct sockaddr_in6 dst; 1073 hdr = mtod(m, struct ip6_hdr *); 1074 1075 bzero(&dst, sizeof(dst)); 1076 dst.sin6_family = AF_INET6; 1077 dst.sin6_len = sizeof(dst); 1078 dst.sin6_addr = hdr->ip6_dst; 1079 1080 nd6_output_ifp(rt, rt, m, &dst, NULL); 1081 } else if (forward) { 1082 MPASS(m->m_pkthdr.rcvif != NULL); 1083 ip6_forward(m, 0); 1084 } else { 1085 (void)ip6_output(m, NULL, NULL, 0, NULL, NULL, 1086 NULL); 1087 } 1088 } 1089 1090 return (action); 1091 } 1092 #endif /* INET6 */ 1093 1094 #ifdef INET 1095 int 1096 pf_normalize_ip(u_short *reason, struct pf_pdesc *pd) 1097 { 1098 struct pf_krule *r; 1099 struct ip *h = mtod(pd->m, struct ip *); 1100 int mff = (ntohs(h->ip_off) & IP_MF); 1101 int hlen = h->ip_hl << 2; 1102 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3; 1103 u_int16_t max; 1104 int ip_len; 1105 int tag = -1; 1106 int verdict; 1107 bool scrub_compat; 1108 1109 PF_RULES_RASSERT(); 1110 1111 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr); 1112 /* 1113 * Check if there are any scrub rules, matching or not. 1114 * Lack of scrub rules means: 1115 * - enforced packet normalization operation just like in OpenBSD 1116 * - fragment reassembly depends on V_pf_status.reass 1117 * With scrub rules: 1118 * - packet normalization is performed if there is a matching scrub rule 1119 * - fragment reassembly is performed if the matching rule has no 1120 * PFRULE_FRAGMENT_NOREASS flag 1121 */ 1122 scrub_compat = (r != NULL); 1123 while (r != NULL) { 1124 pf_counter_u64_add(&r->evaluations, 1); 1125 if (pfi_kkif_match(r->kif, pd->kif) == r->ifnot) 1126 r = r->skip[PF_SKIP_IFP]; 1127 else if (r->direction && r->direction != pd->dir) 1128 r = r->skip[PF_SKIP_DIR]; 1129 else if (r->af && r->af != AF_INET) 1130 r = r->skip[PF_SKIP_AF]; 1131 else if (r->proto && r->proto != h->ip_p) 1132 r = r->skip[PF_SKIP_PROTO]; 1133 else if (PF_MISMATCHAW(&r->src.addr, 1134 (struct pf_addr *)&h->ip_src.s_addr, AF_INET, 1135 r->src.neg, pd->kif, M_GETFIB(pd->m))) 1136 r = r->skip[PF_SKIP_SRC_ADDR]; 1137 else if (PF_MISMATCHAW(&r->dst.addr, 1138 (struct pf_addr *)&h->ip_dst.s_addr, AF_INET, 1139 r->dst.neg, NULL, M_GETFIB(pd->m))) 1140 r = r->skip[PF_SKIP_DST_ADDR]; 1141 else if (r->match_tag && !pf_match_tag(pd->m, r, &tag, 1142 pd->pf_mtag ? pd->pf_mtag->tag : 0)) 1143 r = TAILQ_NEXT(r, entries); 1144 else 1145 break; 1146 } 1147 1148 if (scrub_compat) { 1149 /* With scrub rules present IPv4 normalization happens only 1150 * if one of rules has matched and it's not a "no scrub" rule */ 1151 if (r == NULL || r->action == PF_NOSCRUB) 1152 return (PF_PASS); 1153 1154 pf_counter_u64_critical_enter(); 1155 pf_counter_u64_add_protected(&r->packets[pd->dir == PF_OUT], 1); 1156 pf_counter_u64_add_protected(&r->bytes[pd->dir == PF_OUT], pd->tot_len); 1157 pf_counter_u64_critical_exit(); 1158 pf_rule_to_actions(r, &pd->act); 1159 } 1160 1161 /* Check for illegal packets */ 1162 if (hlen < (int)sizeof(struct ip)) { 1163 REASON_SET(reason, PFRES_NORM); 1164 goto drop; 1165 } 1166 1167 if (hlen > ntohs(h->ip_len)) { 1168 REASON_SET(reason, PFRES_NORM); 1169 goto drop; 1170 } 1171 1172 /* Clear IP_DF if the rule uses the no-df option or we're in no-df mode */ 1173 if (((!scrub_compat && V_pf_status.reass & PF_REASS_NODF) || 1174 (r != NULL && r->rule_flag & PFRULE_NODF)) && 1175 (h->ip_off & htons(IP_DF)) 1176 ) { 1177 u_int16_t ip_off = h->ip_off; 1178 1179 h->ip_off &= htons(~IP_DF); 1180 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0); 1181 } 1182 1183 /* We will need other tests here */ 1184 if (!fragoff && !mff) 1185 goto no_fragment; 1186 1187 /* We're dealing with a fragment now. Don't allow fragments 1188 * with IP_DF to enter the cache. If the flag was cleared by 1189 * no-df above, fine. Otherwise drop it. 1190 */ 1191 if (h->ip_off & htons(IP_DF)) { 1192 DPFPRINTF(("IP_DF\n")); 1193 goto bad; 1194 } 1195 1196 ip_len = ntohs(h->ip_len) - hlen; 1197 1198 /* All fragments are 8 byte aligned */ 1199 if (mff && (ip_len & 0x7)) { 1200 DPFPRINTF(("mff and %d\n", ip_len)); 1201 goto bad; 1202 } 1203 1204 /* Respect maximum length */ 1205 if (fragoff + ip_len > IP_MAXPACKET) { 1206 DPFPRINTF(("max packet %d\n", fragoff + ip_len)); 1207 goto bad; 1208 } 1209 1210 if ((!scrub_compat && V_pf_status.reass) || 1211 (r != NULL && !(r->rule_flag & PFRULE_FRAGMENT_NOREASS)) 1212 ) { 1213 max = fragoff + ip_len; 1214 1215 /* Fully buffer all of the fragments 1216 * Might return a completely reassembled mbuf, or NULL */ 1217 PF_FRAG_LOCK(); 1218 DPFPRINTF(("reass frag %d @ %d-%d\n", h->ip_id, fragoff, max)); 1219 verdict = pf_reassemble(&pd->m, pd->dir, reason); 1220 PF_FRAG_UNLOCK(); 1221 1222 if (verdict != PF_PASS) 1223 return (PF_DROP); 1224 1225 if (pd->m == NULL) 1226 return (PF_DROP); 1227 1228 h = mtod(pd->m, struct ip *); 1229 pd->tot_len = htons(h->ip_len); 1230 1231 no_fragment: 1232 /* At this point, only IP_DF is allowed in ip_off */ 1233 if (h->ip_off & ~htons(IP_DF)) { 1234 u_int16_t ip_off = h->ip_off; 1235 1236 h->ip_off &= htons(IP_DF); 1237 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0); 1238 } 1239 } 1240 1241 return (PF_PASS); 1242 1243 bad: 1244 DPFPRINTF(("dropping bad fragment\n")); 1245 REASON_SET(reason, PFRES_FRAG); 1246 drop: 1247 if (r != NULL && r->log) 1248 PFLOG_PACKET(PF_DROP, *reason, r, NULL, NULL, pd, 1); 1249 1250 return (PF_DROP); 1251 } 1252 #endif 1253 1254 #ifdef INET6 1255 int 1256 pf_normalize_ip6(int off, u_short *reason, 1257 struct pf_pdesc *pd) 1258 { 1259 struct pf_krule *r; 1260 struct ip6_hdr *h; 1261 struct ip6_frag frag; 1262 bool scrub_compat; 1263 1264 PF_RULES_RASSERT(); 1265 1266 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr); 1267 /* 1268 * Check if there are any scrub rules, matching or not. 1269 * Lack of scrub rules means: 1270 * - enforced packet normalization operation just like in OpenBSD 1271 * With scrub rules: 1272 * - packet normalization is performed if there is a matching scrub rule 1273 * XXX: Fragment reassembly always performed for IPv6! 1274 */ 1275 scrub_compat = (r != NULL); 1276 while (r != NULL) { 1277 pf_counter_u64_add(&r->evaluations, 1); 1278 if (pfi_kkif_match(r->kif, pd->kif) == r->ifnot) 1279 r = r->skip[PF_SKIP_IFP]; 1280 else if (r->direction && r->direction != pd->dir) 1281 r = r->skip[PF_SKIP_DIR]; 1282 else if (r->af && r->af != AF_INET6) 1283 r = r->skip[PF_SKIP_AF]; 1284 else if (r->proto && r->proto != pd->proto) 1285 r = r->skip[PF_SKIP_PROTO]; 1286 else if (PF_MISMATCHAW(&r->src.addr, 1287 (struct pf_addr *)&pd->src, AF_INET6, 1288 r->src.neg, pd->kif, M_GETFIB(pd->m))) 1289 r = r->skip[PF_SKIP_SRC_ADDR]; 1290 else if (PF_MISMATCHAW(&r->dst.addr, 1291 (struct pf_addr *)&pd->dst, AF_INET6, 1292 r->dst.neg, NULL, M_GETFIB(pd->m))) 1293 r = r->skip[PF_SKIP_DST_ADDR]; 1294 else 1295 break; 1296 } 1297 1298 if (scrub_compat) { 1299 /* With scrub rules present IPv6 normalization happens only 1300 * if one of rules has matched and it's not a "no scrub" rule */ 1301 if (r == NULL || r->action == PF_NOSCRUB) 1302 return (PF_PASS); 1303 1304 pf_counter_u64_critical_enter(); 1305 pf_counter_u64_add_protected(&r->packets[pd->dir == PF_OUT], 1); 1306 pf_counter_u64_add_protected(&r->bytes[pd->dir == PF_OUT], pd->tot_len); 1307 pf_counter_u64_critical_exit(); 1308 pf_rule_to_actions(r, &pd->act); 1309 } 1310 1311 if (!pf_pull_hdr(pd->m, off, &frag, sizeof(frag), NULL, reason, AF_INET6)) 1312 return (PF_DROP); 1313 1314 /* Offset now points to data portion. */ 1315 off += sizeof(frag); 1316 1317 if (pd->virtual_proto == PF_VPROTO_FRAGMENT) { 1318 /* Returns PF_DROP or *m0 is NULL or completely reassembled 1319 * mbuf. */ 1320 if (pf_reassemble6(&pd->m, &frag, off, pd->extoff, reason) != PF_PASS) 1321 return (PF_DROP); 1322 if (pd->m == NULL) 1323 return (PF_DROP); 1324 h = mtod(pd->m, struct ip6_hdr *); 1325 pd->tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr); 1326 } 1327 1328 return (PF_PASS); 1329 } 1330 #endif /* INET6 */ 1331 1332 int 1333 pf_normalize_tcp(struct pf_pdesc *pd) 1334 { 1335 struct pf_krule *r, *rm = NULL; 1336 struct tcphdr *th = &pd->hdr.tcp; 1337 int rewrite = 0; 1338 u_short reason; 1339 u_int16_t flags; 1340 sa_family_t af = pd->af; 1341 int srs; 1342 1343 PF_RULES_RASSERT(); 1344 1345 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr); 1346 /* Check if there any scrub rules. Lack of scrub rules means enforced 1347 * packet normalization operation just like in OpenBSD. */ 1348 srs = (r != NULL); 1349 while (r != NULL) { 1350 pf_counter_u64_add(&r->evaluations, 1); 1351 if (pfi_kkif_match(r->kif, pd->kif) == r->ifnot) 1352 r = r->skip[PF_SKIP_IFP]; 1353 else if (r->direction && r->direction != pd->dir) 1354 r = r->skip[PF_SKIP_DIR]; 1355 else if (r->af && r->af != af) 1356 r = r->skip[PF_SKIP_AF]; 1357 else if (r->proto && r->proto != pd->proto) 1358 r = r->skip[PF_SKIP_PROTO]; 1359 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af, 1360 r->src.neg, pd->kif, M_GETFIB(pd->m))) 1361 r = r->skip[PF_SKIP_SRC_ADDR]; 1362 else if (r->src.port_op && !pf_match_port(r->src.port_op, 1363 r->src.port[0], r->src.port[1], th->th_sport)) 1364 r = r->skip[PF_SKIP_SRC_PORT]; 1365 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af, 1366 r->dst.neg, NULL, M_GETFIB(pd->m))) 1367 r = r->skip[PF_SKIP_DST_ADDR]; 1368 else if (r->dst.port_op && !pf_match_port(r->dst.port_op, 1369 r->dst.port[0], r->dst.port[1], th->th_dport)) 1370 r = r->skip[PF_SKIP_DST_PORT]; 1371 else if (r->os_fingerprint != PF_OSFP_ANY && !pf_osfp_match( 1372 pf_osfp_fingerprint(pd, th), 1373 r->os_fingerprint)) 1374 r = TAILQ_NEXT(r, entries); 1375 else { 1376 rm = r; 1377 break; 1378 } 1379 } 1380 1381 if (srs) { 1382 /* With scrub rules present TCP normalization happens only 1383 * if one of rules has matched and it's not a "no scrub" rule */ 1384 if (rm == NULL || rm->action == PF_NOSCRUB) 1385 return (PF_PASS); 1386 1387 pf_counter_u64_critical_enter(); 1388 pf_counter_u64_add_protected(&r->packets[pd->dir == PF_OUT], 1); 1389 pf_counter_u64_add_protected(&r->bytes[pd->dir == PF_OUT], pd->tot_len); 1390 pf_counter_u64_critical_exit(); 1391 pf_rule_to_actions(rm, &pd->act); 1392 } 1393 1394 if (rm && rm->rule_flag & PFRULE_REASSEMBLE_TCP) 1395 pd->flags |= PFDESC_TCP_NORM; 1396 1397 flags = tcp_get_flags(th); 1398 if (flags & TH_SYN) { 1399 /* Illegal packet */ 1400 if (flags & TH_RST) 1401 goto tcp_drop; 1402 1403 if (flags & TH_FIN) 1404 goto tcp_drop; 1405 } else { 1406 /* Illegal packet */ 1407 if (!(flags & (TH_ACK|TH_RST))) 1408 goto tcp_drop; 1409 } 1410 1411 if (!(flags & TH_ACK)) { 1412 /* These flags are only valid if ACK is set */ 1413 if ((flags & TH_FIN) || (flags & TH_PUSH) || (flags & TH_URG)) 1414 goto tcp_drop; 1415 } 1416 1417 /* Check for illegal header length */ 1418 if (th->th_off < (sizeof(struct tcphdr) >> 2)) 1419 goto tcp_drop; 1420 1421 /* If flags changed, or reserved data set, then adjust */ 1422 if (flags != tcp_get_flags(th) || 1423 (tcp_get_flags(th) & (TH_RES1|TH_RES2|TH_RES2)) != 0) { 1424 u_int16_t ov, nv; 1425 1426 ov = *(u_int16_t *)(&th->th_ack + 1); 1427 flags &= ~(TH_RES1 | TH_RES2 | TH_RES3); 1428 tcp_set_flags(th, flags); 1429 nv = *(u_int16_t *)(&th->th_ack + 1); 1430 1431 th->th_sum = pf_proto_cksum_fixup(pd->m, th->th_sum, ov, nv, 0); 1432 rewrite = 1; 1433 } 1434 1435 /* Remove urgent pointer, if TH_URG is not set */ 1436 if (!(flags & TH_URG) && th->th_urp) { 1437 th->th_sum = pf_proto_cksum_fixup(pd->m, th->th_sum, th->th_urp, 1438 0, 0); 1439 th->th_urp = 0; 1440 rewrite = 1; 1441 } 1442 1443 /* copy back packet headers if we sanitized */ 1444 if (rewrite) 1445 m_copyback(pd->m, pd->off, sizeof(*th), (caddr_t)th); 1446 1447 return (PF_PASS); 1448 1449 tcp_drop: 1450 REASON_SET(&reason, PFRES_NORM); 1451 if (rm != NULL && r->log) 1452 PFLOG_PACKET(PF_DROP, reason, r, NULL, NULL, pd, 1); 1453 return (PF_DROP); 1454 } 1455 1456 int 1457 pf_normalize_tcp_init(struct pf_pdesc *pd, struct tcphdr *th, 1458 struct pf_state_peer *src, struct pf_state_peer *dst) 1459 { 1460 u_int32_t tsval, tsecr; 1461 u_int8_t hdr[60]; 1462 u_int8_t *opt; 1463 1464 KASSERT((src->scrub == NULL), 1465 ("pf_normalize_tcp_init: src->scrub != NULL")); 1466 1467 src->scrub = uma_zalloc(V_pf_state_scrub_z, M_ZERO | M_NOWAIT); 1468 if (src->scrub == NULL) 1469 return (1); 1470 1471 switch (pd->af) { 1472 #ifdef INET 1473 case AF_INET: { 1474 struct ip *h = mtod(pd->m, struct ip *); 1475 src->scrub->pfss_ttl = h->ip_ttl; 1476 break; 1477 } 1478 #endif /* INET */ 1479 #ifdef INET6 1480 case AF_INET6: { 1481 struct ip6_hdr *h = mtod(pd->m, struct ip6_hdr *); 1482 src->scrub->pfss_ttl = h->ip6_hlim; 1483 break; 1484 } 1485 #endif /* INET6 */ 1486 } 1487 1488 /* 1489 * All normalizations below are only begun if we see the start of 1490 * the connections. They must all set an enabled bit in pfss_flags 1491 */ 1492 if ((tcp_get_flags(th) & TH_SYN) == 0) 1493 return (0); 1494 1495 if (th->th_off > (sizeof(struct tcphdr) >> 2) && src->scrub && 1496 pf_pull_hdr(pd->m, pd->off, hdr, th->th_off << 2, NULL, NULL, pd->af)) { 1497 /* Diddle with TCP options */ 1498 int hlen; 1499 opt = hdr + sizeof(struct tcphdr); 1500 hlen = (th->th_off << 2) - sizeof(struct tcphdr); 1501 while (hlen >= TCPOLEN_TIMESTAMP) { 1502 switch (*opt) { 1503 case TCPOPT_EOL: /* FALLTHROUGH */ 1504 case TCPOPT_NOP: 1505 opt++; 1506 hlen--; 1507 break; 1508 case TCPOPT_TIMESTAMP: 1509 if (opt[1] >= TCPOLEN_TIMESTAMP) { 1510 src->scrub->pfss_flags |= 1511 PFSS_TIMESTAMP; 1512 src->scrub->pfss_ts_mod = 1513 htonl(arc4random()); 1514 1515 /* note PFSS_PAWS not set yet */ 1516 memcpy(&tsval, &opt[2], 1517 sizeof(u_int32_t)); 1518 memcpy(&tsecr, &opt[6], 1519 sizeof(u_int32_t)); 1520 src->scrub->pfss_tsval0 = ntohl(tsval); 1521 src->scrub->pfss_tsval = ntohl(tsval); 1522 src->scrub->pfss_tsecr = ntohl(tsecr); 1523 getmicrouptime(&src->scrub->pfss_last); 1524 } 1525 /* FALLTHROUGH */ 1526 default: 1527 hlen -= MAX(opt[1], 2); 1528 opt += MAX(opt[1], 2); 1529 break; 1530 } 1531 } 1532 } 1533 1534 return (0); 1535 } 1536 1537 void 1538 pf_normalize_tcp_cleanup(struct pf_kstate *state) 1539 { 1540 /* XXX Note: this also cleans up SCTP. */ 1541 uma_zfree(V_pf_state_scrub_z, state->src.scrub); 1542 uma_zfree(V_pf_state_scrub_z, state->dst.scrub); 1543 1544 /* Someday... flush the TCP segment reassembly descriptors. */ 1545 } 1546 int 1547 pf_normalize_sctp_init(struct pf_pdesc *pd, struct pf_state_peer *src, 1548 struct pf_state_peer *dst) 1549 { 1550 src->scrub = uma_zalloc(V_pf_state_scrub_z, M_ZERO | M_NOWAIT); 1551 if (src->scrub == NULL) 1552 return (1); 1553 1554 dst->scrub = uma_zalloc(V_pf_state_scrub_z, M_ZERO | M_NOWAIT); 1555 if (dst->scrub == NULL) { 1556 uma_zfree(V_pf_state_scrub_z, src); 1557 return (1); 1558 } 1559 1560 dst->scrub->pfss_v_tag = pd->sctp_initiate_tag; 1561 1562 return (0); 1563 } 1564 1565 int 1566 pf_normalize_tcp_stateful(struct pf_pdesc *pd, 1567 u_short *reason, struct tcphdr *th, struct pf_kstate *state, 1568 struct pf_state_peer *src, struct pf_state_peer *dst, int *writeback) 1569 { 1570 struct timeval uptime; 1571 u_int32_t tsval, tsecr; 1572 u_int tsval_from_last; 1573 u_int8_t hdr[60]; 1574 u_int8_t *opt; 1575 int copyback = 0; 1576 int got_ts = 0; 1577 size_t startoff; 1578 1579 KASSERT((src->scrub || dst->scrub), 1580 ("%s: src->scrub && dst->scrub!", __func__)); 1581 1582 /* 1583 * Enforce the minimum TTL seen for this connection. Negate a common 1584 * technique to evade an intrusion detection system and confuse 1585 * firewall state code. 1586 */ 1587 switch (pd->af) { 1588 #ifdef INET 1589 case AF_INET: { 1590 if (src->scrub) { 1591 struct ip *h = mtod(pd->m, struct ip *); 1592 if (h->ip_ttl > src->scrub->pfss_ttl) 1593 src->scrub->pfss_ttl = h->ip_ttl; 1594 h->ip_ttl = src->scrub->pfss_ttl; 1595 } 1596 break; 1597 } 1598 #endif /* INET */ 1599 #ifdef INET6 1600 case AF_INET6: { 1601 if (src->scrub) { 1602 struct ip6_hdr *h = mtod(pd->m, struct ip6_hdr *); 1603 if (h->ip6_hlim > src->scrub->pfss_ttl) 1604 src->scrub->pfss_ttl = h->ip6_hlim; 1605 h->ip6_hlim = src->scrub->pfss_ttl; 1606 } 1607 break; 1608 } 1609 #endif /* INET6 */ 1610 } 1611 1612 if (th->th_off > (sizeof(struct tcphdr) >> 2) && 1613 ((src->scrub && (src->scrub->pfss_flags & PFSS_TIMESTAMP)) || 1614 (dst->scrub && (dst->scrub->pfss_flags & PFSS_TIMESTAMP))) && 1615 pf_pull_hdr(pd->m, pd->off, hdr, th->th_off << 2, NULL, NULL, pd->af)) { 1616 /* Diddle with TCP options */ 1617 int hlen; 1618 opt = hdr + sizeof(struct tcphdr); 1619 hlen = (th->th_off << 2) - sizeof(struct tcphdr); 1620 while (hlen >= TCPOLEN_TIMESTAMP) { 1621 startoff = opt - (hdr + sizeof(struct tcphdr)); 1622 switch (*opt) { 1623 case TCPOPT_EOL: /* FALLTHROUGH */ 1624 case TCPOPT_NOP: 1625 opt++; 1626 hlen--; 1627 break; 1628 case TCPOPT_TIMESTAMP: 1629 /* Modulate the timestamps. Can be used for 1630 * NAT detection, OS uptime determination or 1631 * reboot detection. 1632 */ 1633 1634 if (got_ts) { 1635 /* Huh? Multiple timestamps!? */ 1636 if (V_pf_status.debug >= PF_DEBUG_MISC) { 1637 DPFPRINTF(("multiple TS??\n")); 1638 pf_print_state(state); 1639 printf("\n"); 1640 } 1641 REASON_SET(reason, PFRES_TS); 1642 return (PF_DROP); 1643 } 1644 if (opt[1] >= TCPOLEN_TIMESTAMP) { 1645 memcpy(&tsval, &opt[2], 1646 sizeof(u_int32_t)); 1647 if (tsval && src->scrub && 1648 (src->scrub->pfss_flags & 1649 PFSS_TIMESTAMP)) { 1650 tsval = ntohl(tsval); 1651 pf_patch_32_unaligned(pd->m, 1652 &th->th_sum, 1653 &opt[2], 1654 htonl(tsval + 1655 src->scrub->pfss_ts_mod), 1656 PF_ALGNMNT(startoff), 1657 0); 1658 copyback = 1; 1659 } 1660 1661 /* Modulate TS reply iff valid (!0) */ 1662 memcpy(&tsecr, &opt[6], 1663 sizeof(u_int32_t)); 1664 if (tsecr && dst->scrub && 1665 (dst->scrub->pfss_flags & 1666 PFSS_TIMESTAMP)) { 1667 tsecr = ntohl(tsecr) 1668 - dst->scrub->pfss_ts_mod; 1669 pf_patch_32_unaligned(pd->m, 1670 &th->th_sum, 1671 &opt[6], 1672 htonl(tsecr), 1673 PF_ALGNMNT(startoff), 1674 0); 1675 copyback = 1; 1676 } 1677 got_ts = 1; 1678 } 1679 /* FALLTHROUGH */ 1680 default: 1681 hlen -= MAX(opt[1], 2); 1682 opt += MAX(opt[1], 2); 1683 break; 1684 } 1685 } 1686 if (copyback) { 1687 /* Copyback the options, caller copys back header */ 1688 *writeback = 1; 1689 m_copyback(pd->m, pd->off + sizeof(struct tcphdr), 1690 (th->th_off << 2) - sizeof(struct tcphdr), hdr + 1691 sizeof(struct tcphdr)); 1692 } 1693 } 1694 1695 /* 1696 * Must invalidate PAWS checks on connections idle for too long. 1697 * The fastest allowed timestamp clock is 1ms. That turns out to 1698 * be about 24 days before it wraps. XXX Right now our lowerbound 1699 * TS echo check only works for the first 12 days of a connection 1700 * when the TS has exhausted half its 32bit space 1701 */ 1702 #define TS_MAX_IDLE (24*24*60*60) 1703 #define TS_MAX_CONN (12*24*60*60) /* XXX remove when better tsecr check */ 1704 1705 getmicrouptime(&uptime); 1706 if (src->scrub && (src->scrub->pfss_flags & PFSS_PAWS) && 1707 (uptime.tv_sec - src->scrub->pfss_last.tv_sec > TS_MAX_IDLE || 1708 time_uptime - (state->creation / 1000) > TS_MAX_CONN)) { 1709 if (V_pf_status.debug >= PF_DEBUG_MISC) { 1710 DPFPRINTF(("src idled out of PAWS\n")); 1711 pf_print_state(state); 1712 printf("\n"); 1713 } 1714 src->scrub->pfss_flags = (src->scrub->pfss_flags & ~PFSS_PAWS) 1715 | PFSS_PAWS_IDLED; 1716 } 1717 if (dst->scrub && (dst->scrub->pfss_flags & PFSS_PAWS) && 1718 uptime.tv_sec - dst->scrub->pfss_last.tv_sec > TS_MAX_IDLE) { 1719 if (V_pf_status.debug >= PF_DEBUG_MISC) { 1720 DPFPRINTF(("dst idled out of PAWS\n")); 1721 pf_print_state(state); 1722 printf("\n"); 1723 } 1724 dst->scrub->pfss_flags = (dst->scrub->pfss_flags & ~PFSS_PAWS) 1725 | PFSS_PAWS_IDLED; 1726 } 1727 1728 if (got_ts && src->scrub && dst->scrub && 1729 (src->scrub->pfss_flags & PFSS_PAWS) && 1730 (dst->scrub->pfss_flags & PFSS_PAWS)) { 1731 /* Validate that the timestamps are "in-window". 1732 * RFC1323 describes TCP Timestamp options that allow 1733 * measurement of RTT (round trip time) and PAWS 1734 * (protection against wrapped sequence numbers). PAWS 1735 * gives us a set of rules for rejecting packets on 1736 * long fat pipes (packets that were somehow delayed 1737 * in transit longer than the time it took to send the 1738 * full TCP sequence space of 4Gb). We can use these 1739 * rules and infer a few others that will let us treat 1740 * the 32bit timestamp and the 32bit echoed timestamp 1741 * as sequence numbers to prevent a blind attacker from 1742 * inserting packets into a connection. 1743 * 1744 * RFC1323 tells us: 1745 * - The timestamp on this packet must be greater than 1746 * or equal to the last value echoed by the other 1747 * endpoint. The RFC says those will be discarded 1748 * since it is a dup that has already been acked. 1749 * This gives us a lowerbound on the timestamp. 1750 * timestamp >= other last echoed timestamp 1751 * - The timestamp will be less than or equal to 1752 * the last timestamp plus the time between the 1753 * last packet and now. The RFC defines the max 1754 * clock rate as 1ms. We will allow clocks to be 1755 * up to 10% fast and will allow a total difference 1756 * or 30 seconds due to a route change. And this 1757 * gives us an upperbound on the timestamp. 1758 * timestamp <= last timestamp + max ticks 1759 * We have to be careful here. Windows will send an 1760 * initial timestamp of zero and then initialize it 1761 * to a random value after the 3whs; presumably to 1762 * avoid a DoS by having to call an expensive RNG 1763 * during a SYN flood. Proof MS has at least one 1764 * good security geek. 1765 * 1766 * - The TCP timestamp option must also echo the other 1767 * endpoints timestamp. The timestamp echoed is the 1768 * one carried on the earliest unacknowledged segment 1769 * on the left edge of the sequence window. The RFC 1770 * states that the host will reject any echoed 1771 * timestamps that were larger than any ever sent. 1772 * This gives us an upperbound on the TS echo. 1773 * tescr <= largest_tsval 1774 * - The lowerbound on the TS echo is a little more 1775 * tricky to determine. The other endpoint's echoed 1776 * values will not decrease. But there may be 1777 * network conditions that re-order packets and 1778 * cause our view of them to decrease. For now the 1779 * only lowerbound we can safely determine is that 1780 * the TS echo will never be less than the original 1781 * TS. XXX There is probably a better lowerbound. 1782 * Remove TS_MAX_CONN with better lowerbound check. 1783 * tescr >= other original TS 1784 * 1785 * It is also important to note that the fastest 1786 * timestamp clock of 1ms will wrap its 32bit space in 1787 * 24 days. So we just disable TS checking after 24 1788 * days of idle time. We actually must use a 12d 1789 * connection limit until we can come up with a better 1790 * lowerbound to the TS echo check. 1791 */ 1792 struct timeval delta_ts; 1793 int ts_fudge; 1794 1795 /* 1796 * PFTM_TS_DIFF is how many seconds of leeway to allow 1797 * a host's timestamp. This can happen if the previous 1798 * packet got delayed in transit for much longer than 1799 * this packet. 1800 */ 1801 if ((ts_fudge = state->rule->timeout[PFTM_TS_DIFF]) == 0) 1802 ts_fudge = V_pf_default_rule.timeout[PFTM_TS_DIFF]; 1803 1804 /* Calculate max ticks since the last timestamp */ 1805 #define TS_MAXFREQ 1100 /* RFC max TS freq of 1Khz + 10% skew */ 1806 #define TS_MICROSECS 1000000 /* microseconds per second */ 1807 delta_ts = uptime; 1808 timevalsub(&delta_ts, &src->scrub->pfss_last); 1809 tsval_from_last = (delta_ts.tv_sec + ts_fudge) * TS_MAXFREQ; 1810 tsval_from_last += delta_ts.tv_usec / (TS_MICROSECS/TS_MAXFREQ); 1811 1812 if ((src->state >= TCPS_ESTABLISHED && 1813 dst->state >= TCPS_ESTABLISHED) && 1814 (SEQ_LT(tsval, dst->scrub->pfss_tsecr) || 1815 SEQ_GT(tsval, src->scrub->pfss_tsval + tsval_from_last) || 1816 (tsecr && (SEQ_GT(tsecr, dst->scrub->pfss_tsval) || 1817 SEQ_LT(tsecr, dst->scrub->pfss_tsval0))))) { 1818 /* Bad RFC1323 implementation or an insertion attack. 1819 * 1820 * - Solaris 2.6 and 2.7 are known to send another ACK 1821 * after the FIN,FIN|ACK,ACK closing that carries 1822 * an old timestamp. 1823 */ 1824 1825 DPFPRINTF(("Timestamp failed %c%c%c%c\n", 1826 SEQ_LT(tsval, dst->scrub->pfss_tsecr) ? '0' : ' ', 1827 SEQ_GT(tsval, src->scrub->pfss_tsval + 1828 tsval_from_last) ? '1' : ' ', 1829 SEQ_GT(tsecr, dst->scrub->pfss_tsval) ? '2' : ' ', 1830 SEQ_LT(tsecr, dst->scrub->pfss_tsval0)? '3' : ' ')); 1831 DPFPRINTF((" tsval: %u tsecr: %u +ticks: %u " 1832 "idle: %jus %lums\n", 1833 tsval, tsecr, tsval_from_last, 1834 (uintmax_t)delta_ts.tv_sec, 1835 delta_ts.tv_usec / 1000)); 1836 DPFPRINTF((" src->tsval: %u tsecr: %u\n", 1837 src->scrub->pfss_tsval, src->scrub->pfss_tsecr)); 1838 DPFPRINTF((" dst->tsval: %u tsecr: %u tsval0: %u" 1839 "\n", dst->scrub->pfss_tsval, 1840 dst->scrub->pfss_tsecr, dst->scrub->pfss_tsval0)); 1841 if (V_pf_status.debug >= PF_DEBUG_MISC) { 1842 pf_print_state(state); 1843 pf_print_flags(tcp_get_flags(th)); 1844 printf("\n"); 1845 } 1846 REASON_SET(reason, PFRES_TS); 1847 return (PF_DROP); 1848 } 1849 1850 /* XXX I'd really like to require tsecr but it's optional */ 1851 1852 } else if (!got_ts && (tcp_get_flags(th) & TH_RST) == 0 && 1853 ((src->state == TCPS_ESTABLISHED && dst->state == TCPS_ESTABLISHED) 1854 || pd->p_len > 0 || (tcp_get_flags(th) & TH_SYN)) && 1855 src->scrub && dst->scrub && 1856 (src->scrub->pfss_flags & PFSS_PAWS) && 1857 (dst->scrub->pfss_flags & PFSS_PAWS)) { 1858 /* Didn't send a timestamp. Timestamps aren't really useful 1859 * when: 1860 * - connection opening or closing (often not even sent). 1861 * but we must not let an attacker to put a FIN on a 1862 * data packet to sneak it through our ESTABLISHED check. 1863 * - on a TCP reset. RFC suggests not even looking at TS. 1864 * - on an empty ACK. The TS will not be echoed so it will 1865 * probably not help keep the RTT calculation in sync and 1866 * there isn't as much danger when the sequence numbers 1867 * got wrapped. So some stacks don't include TS on empty 1868 * ACKs :-( 1869 * 1870 * To minimize the disruption to mostly RFC1323 conformant 1871 * stacks, we will only require timestamps on data packets. 1872 * 1873 * And what do ya know, we cannot require timestamps on data 1874 * packets. There appear to be devices that do legitimate 1875 * TCP connection hijacking. There are HTTP devices that allow 1876 * a 3whs (with timestamps) and then buffer the HTTP request. 1877 * If the intermediate device has the HTTP response cache, it 1878 * will spoof the response but not bother timestamping its 1879 * packets. So we can look for the presence of a timestamp in 1880 * the first data packet and if there, require it in all future 1881 * packets. 1882 */ 1883 1884 if (pd->p_len > 0 && (src->scrub->pfss_flags & PFSS_DATA_TS)) { 1885 /* 1886 * Hey! Someone tried to sneak a packet in. Or the 1887 * stack changed its RFC1323 behavior?!?! 1888 */ 1889 if (V_pf_status.debug >= PF_DEBUG_MISC) { 1890 DPFPRINTF(("Did not receive expected RFC1323 " 1891 "timestamp\n")); 1892 pf_print_state(state); 1893 pf_print_flags(tcp_get_flags(th)); 1894 printf("\n"); 1895 } 1896 REASON_SET(reason, PFRES_TS); 1897 return (PF_DROP); 1898 } 1899 } 1900 1901 /* 1902 * We will note if a host sends his data packets with or without 1903 * timestamps. And require all data packets to contain a timestamp 1904 * if the first does. PAWS implicitly requires that all data packets be 1905 * timestamped. But I think there are middle-man devices that hijack 1906 * TCP streams immediately after the 3whs and don't timestamp their 1907 * packets (seen in a WWW accelerator or cache). 1908 */ 1909 if (pd->p_len > 0 && src->scrub && (src->scrub->pfss_flags & 1910 (PFSS_TIMESTAMP|PFSS_DATA_TS|PFSS_DATA_NOTS)) == PFSS_TIMESTAMP) { 1911 if (got_ts) 1912 src->scrub->pfss_flags |= PFSS_DATA_TS; 1913 else { 1914 src->scrub->pfss_flags |= PFSS_DATA_NOTS; 1915 if (V_pf_status.debug >= PF_DEBUG_MISC && dst->scrub && 1916 (dst->scrub->pfss_flags & PFSS_TIMESTAMP)) { 1917 /* Don't warn if other host rejected RFC1323 */ 1918 DPFPRINTF(("Broken RFC1323 stack did not " 1919 "timestamp data packet. Disabled PAWS " 1920 "security.\n")); 1921 pf_print_state(state); 1922 pf_print_flags(tcp_get_flags(th)); 1923 printf("\n"); 1924 } 1925 } 1926 } 1927 1928 /* 1929 * Update PAWS values 1930 */ 1931 if (got_ts && src->scrub && PFSS_TIMESTAMP == (src->scrub->pfss_flags & 1932 (PFSS_PAWS_IDLED|PFSS_TIMESTAMP))) { 1933 getmicrouptime(&src->scrub->pfss_last); 1934 if (SEQ_GEQ(tsval, src->scrub->pfss_tsval) || 1935 (src->scrub->pfss_flags & PFSS_PAWS) == 0) 1936 src->scrub->pfss_tsval = tsval; 1937 1938 if (tsecr) { 1939 if (SEQ_GEQ(tsecr, src->scrub->pfss_tsecr) || 1940 (src->scrub->pfss_flags & PFSS_PAWS) == 0) 1941 src->scrub->pfss_tsecr = tsecr; 1942 1943 if ((src->scrub->pfss_flags & PFSS_PAWS) == 0 && 1944 (SEQ_LT(tsval, src->scrub->pfss_tsval0) || 1945 src->scrub->pfss_tsval0 == 0)) { 1946 /* tsval0 MUST be the lowest timestamp */ 1947 src->scrub->pfss_tsval0 = tsval; 1948 } 1949 1950 /* Only fully initialized after a TS gets echoed */ 1951 if ((src->scrub->pfss_flags & PFSS_PAWS) == 0) 1952 src->scrub->pfss_flags |= PFSS_PAWS; 1953 } 1954 } 1955 1956 /* I have a dream.... TCP segment reassembly.... */ 1957 return (0); 1958 } 1959 1960 int 1961 pf_normalize_mss(struct pf_pdesc *pd) 1962 { 1963 struct tcphdr *th = &pd->hdr.tcp; 1964 u_int16_t *mss; 1965 int thoff; 1966 int opt, cnt, optlen = 0; 1967 u_char opts[TCP_MAXOLEN]; 1968 u_char *optp = opts; 1969 size_t startoff; 1970 1971 thoff = th->th_off << 2; 1972 cnt = thoff - sizeof(struct tcphdr); 1973 1974 if (cnt > 0 && !pf_pull_hdr(pd->m, pd->off + sizeof(*th), opts, cnt, 1975 NULL, NULL, pd->af)) 1976 return (0); 1977 1978 for (; cnt > 0; cnt -= optlen, optp += optlen) { 1979 startoff = optp - opts; 1980 opt = optp[0]; 1981 if (opt == TCPOPT_EOL) 1982 break; 1983 if (opt == TCPOPT_NOP) 1984 optlen = 1; 1985 else { 1986 if (cnt < 2) 1987 break; 1988 optlen = optp[1]; 1989 if (optlen < 2 || optlen > cnt) 1990 break; 1991 } 1992 switch (opt) { 1993 case TCPOPT_MAXSEG: 1994 mss = (u_int16_t *)(optp + 2); 1995 if ((ntohs(*mss)) > pd->act.max_mss) { 1996 pf_patch_16_unaligned(pd->m, 1997 &th->th_sum, 1998 mss, htons(pd->act.max_mss), 1999 PF_ALGNMNT(startoff), 2000 0); 2001 m_copyback(pd->m, pd->off + sizeof(*th), 2002 thoff - sizeof(*th), opts); 2003 m_copyback(pd->m, pd->off, sizeof(*th), (caddr_t)th); 2004 } 2005 break; 2006 default: 2007 break; 2008 } 2009 } 2010 2011 return (0); 2012 } 2013 2014 int 2015 pf_scan_sctp(struct pf_pdesc *pd) 2016 { 2017 struct sctp_chunkhdr ch = { }; 2018 int chunk_off = sizeof(struct sctphdr); 2019 int chunk_start; 2020 int ret; 2021 2022 while (pd->off + chunk_off < pd->tot_len) { 2023 if (!pf_pull_hdr(pd->m, pd->off + chunk_off, &ch, sizeof(ch), NULL, 2024 NULL, pd->af)) 2025 return (PF_DROP); 2026 2027 /* Length includes the header, this must be at least 4. */ 2028 if (ntohs(ch.chunk_length) < 4) 2029 return (PF_DROP); 2030 2031 chunk_start = chunk_off; 2032 chunk_off += roundup(ntohs(ch.chunk_length), 4); 2033 2034 switch (ch.chunk_type) { 2035 case SCTP_INITIATION: 2036 case SCTP_INITIATION_ACK: { 2037 struct sctp_init_chunk init; 2038 2039 if (!pf_pull_hdr(pd->m, pd->off + chunk_start, &init, 2040 sizeof(init), NULL, NULL, pd->af)) 2041 return (PF_DROP); 2042 2043 /* 2044 * RFC 9620, Section 3.3.2, "The Initiate Tag is allowed to have 2045 * any value except 0." 2046 */ 2047 if (init.init.initiate_tag == 0) 2048 return (PF_DROP); 2049 if (init.init.num_inbound_streams == 0) 2050 return (PF_DROP); 2051 if (init.init.num_outbound_streams == 0) 2052 return (PF_DROP); 2053 if (ntohl(init.init.a_rwnd) < SCTP_MIN_RWND) 2054 return (PF_DROP); 2055 2056 /* 2057 * RFC 9260, Section 3.1, INIT chunks MUST have zero 2058 * verification tag. 2059 */ 2060 if (ch.chunk_type == SCTP_INITIATION && 2061 pd->hdr.sctp.v_tag != 0) 2062 return (PF_DROP); 2063 2064 pd->sctp_initiate_tag = init.init.initiate_tag; 2065 2066 if (ch.chunk_type == SCTP_INITIATION) 2067 pd->sctp_flags |= PFDESC_SCTP_INIT; 2068 else 2069 pd->sctp_flags |= PFDESC_SCTP_INIT_ACK; 2070 2071 ret = pf_multihome_scan_init(pd->off + chunk_start, 2072 ntohs(init.ch.chunk_length), pd); 2073 if (ret != PF_PASS) 2074 return (ret); 2075 2076 break; 2077 } 2078 case SCTP_ABORT_ASSOCIATION: 2079 pd->sctp_flags |= PFDESC_SCTP_ABORT; 2080 break; 2081 case SCTP_SHUTDOWN: 2082 case SCTP_SHUTDOWN_ACK: 2083 pd->sctp_flags |= PFDESC_SCTP_SHUTDOWN; 2084 break; 2085 case SCTP_SHUTDOWN_COMPLETE: 2086 pd->sctp_flags |= PFDESC_SCTP_SHUTDOWN_COMPLETE; 2087 break; 2088 case SCTP_COOKIE_ECHO: 2089 pd->sctp_flags |= PFDESC_SCTP_COOKIE; 2090 break; 2091 case SCTP_COOKIE_ACK: 2092 pd->sctp_flags |= PFDESC_SCTP_COOKIE_ACK; 2093 break; 2094 case SCTP_DATA: 2095 pd->sctp_flags |= PFDESC_SCTP_DATA; 2096 break; 2097 case SCTP_HEARTBEAT_REQUEST: 2098 pd->sctp_flags |= PFDESC_SCTP_HEARTBEAT; 2099 break; 2100 case SCTP_HEARTBEAT_ACK: 2101 pd->sctp_flags |= PFDESC_SCTP_HEARTBEAT_ACK; 2102 break; 2103 case SCTP_ASCONF: 2104 pd->sctp_flags |= PFDESC_SCTP_ASCONF; 2105 2106 ret = pf_multihome_scan_asconf(pd->off + chunk_start, 2107 ntohs(ch.chunk_length), pd); 2108 if (ret != PF_PASS) 2109 return (ret); 2110 break; 2111 default: 2112 pd->sctp_flags |= PFDESC_SCTP_OTHER; 2113 break; 2114 } 2115 } 2116 2117 /* Validate chunk lengths vs. packet length. */ 2118 if (pd->off + chunk_off != pd->tot_len) 2119 return (PF_DROP); 2120 2121 /* 2122 * INIT, INIT_ACK or SHUTDOWN_COMPLETE chunks must always be the only 2123 * one in a packet. 2124 */ 2125 if ((pd->sctp_flags & PFDESC_SCTP_INIT) && 2126 (pd->sctp_flags & ~PFDESC_SCTP_INIT)) 2127 return (PF_DROP); 2128 if ((pd->sctp_flags & PFDESC_SCTP_INIT_ACK) && 2129 (pd->sctp_flags & ~PFDESC_SCTP_INIT_ACK)) 2130 return (PF_DROP); 2131 if ((pd->sctp_flags & PFDESC_SCTP_SHUTDOWN_COMPLETE) && 2132 (pd->sctp_flags & ~PFDESC_SCTP_SHUTDOWN_COMPLETE)) 2133 return (PF_DROP); 2134 if ((pd->sctp_flags & PFDESC_SCTP_ABORT) && 2135 (pd->sctp_flags & PFDESC_SCTP_DATA)) { 2136 /* 2137 * RFC4960 3.3.7: DATA chunks MUST NOT be 2138 * bundled with ABORT. 2139 */ 2140 return (PF_DROP); 2141 } 2142 2143 return (PF_PASS); 2144 } 2145 2146 int 2147 pf_normalize_sctp(struct pf_pdesc *pd) 2148 { 2149 struct pf_krule *r, *rm = NULL; 2150 struct sctphdr *sh = &pd->hdr.sctp; 2151 u_short reason; 2152 sa_family_t af = pd->af; 2153 int srs; 2154 2155 PF_RULES_RASSERT(); 2156 2157 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr); 2158 /* Check if there any scrub rules. Lack of scrub rules means enforced 2159 * packet normalization operation just like in OpenBSD. */ 2160 srs = (r != NULL); 2161 while (r != NULL) { 2162 pf_counter_u64_add(&r->evaluations, 1); 2163 if (pfi_kkif_match(r->kif, pd->kif) == r->ifnot) 2164 r = r->skip[PF_SKIP_IFP]; 2165 else if (r->direction && r->direction != pd->dir) 2166 r = r->skip[PF_SKIP_DIR]; 2167 else if (r->af && r->af != af) 2168 r = r->skip[PF_SKIP_AF]; 2169 else if (r->proto && r->proto != pd->proto) 2170 r = r->skip[PF_SKIP_PROTO]; 2171 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af, 2172 r->src.neg, pd->kif, M_GETFIB(pd->m))) 2173 r = r->skip[PF_SKIP_SRC_ADDR]; 2174 else if (r->src.port_op && !pf_match_port(r->src.port_op, 2175 r->src.port[0], r->src.port[1], sh->src_port)) 2176 r = r->skip[PF_SKIP_SRC_PORT]; 2177 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af, 2178 r->dst.neg, NULL, M_GETFIB(pd->m))) 2179 r = r->skip[PF_SKIP_DST_ADDR]; 2180 else if (r->dst.port_op && !pf_match_port(r->dst.port_op, 2181 r->dst.port[0], r->dst.port[1], sh->dest_port)) 2182 r = r->skip[PF_SKIP_DST_PORT]; 2183 else { 2184 rm = r; 2185 break; 2186 } 2187 } 2188 2189 if (srs) { 2190 /* With scrub rules present SCTP normalization happens only 2191 * if one of rules has matched and it's not a "no scrub" rule */ 2192 if (rm == NULL || rm->action == PF_NOSCRUB) 2193 return (PF_PASS); 2194 2195 pf_counter_u64_critical_enter(); 2196 pf_counter_u64_add_protected(&r->packets[pd->dir == PF_OUT], 1); 2197 pf_counter_u64_add_protected(&r->bytes[pd->dir == PF_OUT], pd->tot_len); 2198 pf_counter_u64_critical_exit(); 2199 } 2200 2201 /* Verify we're a multiple of 4 bytes long */ 2202 if ((pd->tot_len - pd->off - sizeof(struct sctphdr)) % 4) 2203 goto sctp_drop; 2204 2205 /* INIT chunk needs to be the only chunk */ 2206 if (pd->sctp_flags & PFDESC_SCTP_INIT) 2207 if (pd->sctp_flags & ~PFDESC_SCTP_INIT) 2208 goto sctp_drop; 2209 2210 return (PF_PASS); 2211 2212 sctp_drop: 2213 REASON_SET(&reason, PFRES_NORM); 2214 if (rm != NULL && r->log) 2215 PFLOG_PACKET(PF_DROP, reason, r, NULL, NULL, pd, 2216 1); 2217 2218 return (PF_DROP); 2219 } 2220 2221 #if defined(INET) || defined(INET6) 2222 void 2223 pf_scrub(struct pf_pdesc *pd) 2224 { 2225 2226 struct ip *h = mtod(pd->m, struct ip *); 2227 #ifdef INET6 2228 struct ip6_hdr *h6 = mtod(pd->m, struct ip6_hdr *); 2229 #endif 2230 2231 /* Clear IP_DF if no-df was requested */ 2232 if (pd->af == AF_INET && pd->act.flags & PFSTATE_NODF && 2233 h->ip_off & htons(IP_DF)) 2234 { 2235 u_int16_t ip_off = h->ip_off; 2236 2237 h->ip_off &= htons(~IP_DF); 2238 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0); 2239 } 2240 2241 /* Enforce a minimum ttl, may cause endless packet loops */ 2242 if (pd->af == AF_INET && pd->act.min_ttl && 2243 h->ip_ttl < pd->act.min_ttl) { 2244 u_int16_t ip_ttl = h->ip_ttl; 2245 2246 h->ip_ttl = pd->act.min_ttl; 2247 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_ttl, h->ip_ttl, 0); 2248 } 2249 #ifdef INET6 2250 /* Enforce a minimum ttl, may cause endless packet loops */ 2251 if (pd->af == AF_INET6 && pd->act.min_ttl && 2252 h6->ip6_hlim < pd->act.min_ttl) 2253 h6->ip6_hlim = pd->act.min_ttl; 2254 #endif 2255 /* Enforce tos */ 2256 if (pd->act.flags & PFSTATE_SETTOS) { 2257 switch (pd->af) { 2258 case AF_INET: { 2259 u_int16_t ov, nv; 2260 2261 ov = *(u_int16_t *)h; 2262 h->ip_tos = pd->act.set_tos | (h->ip_tos & IPTOS_ECN_MASK); 2263 nv = *(u_int16_t *)h; 2264 2265 h->ip_sum = pf_cksum_fixup(h->ip_sum, ov, nv, 0); 2266 break; 2267 } 2268 #ifdef INET6 2269 case AF_INET6: 2270 h6->ip6_flow &= IPV6_FLOWLABEL_MASK | IPV6_VERSION_MASK; 2271 h6->ip6_flow |= htonl((pd->act.set_tos | IPV6_ECN(h6)) << 20); 2272 break; 2273 #endif 2274 } 2275 } 2276 2277 /* random-id, but not for fragments */ 2278 #ifdef INET 2279 if (pd->af == AF_INET && 2280 pd->act.flags & PFSTATE_RANDOMID && !(h->ip_off & ~htons(IP_DF))) { 2281 uint16_t ip_id = h->ip_id; 2282 2283 ip_fillid(h); 2284 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_id, h->ip_id, 0); 2285 } 2286 #endif 2287 } 2288 #endif 2289