1 /* $OpenBSD: pf_norm.c,v 1.233 2024/07/14 18:53:39 bluhm Exp $ */ 2 3 /* 4 * Copyright 2001 Niels Provos <provos@citi.umich.edu> 5 * Copyright 2009 Henning Brauer <henning@openbsd.org> 6 * Copyright 2011-2018 Alexander Bluhm <bluhm@openbsd.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 * 1. Redistributions of source code must retain the above copyright 13 * notice, this list of conditions and the following disclaimer. 14 * 2. Redistributions in binary form must reproduce the above copyright 15 * notice, this list of conditions and the following disclaimer in the 16 * documentation and/or other materials provided with the distribution. 17 * 18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 */ 29 30 #include "pflog.h" 31 32 #include <sys/param.h> 33 #include <sys/systm.h> 34 #include <sys/mbuf.h> 35 #include <sys/filio.h> 36 #include <sys/fcntl.h> 37 #include <sys/socket.h> 38 #include <sys/kernel.h> 39 #include <sys/time.h> 40 #include <sys/pool.h> 41 #include <sys/syslog.h> 42 #include <sys/mutex.h> 43 44 #include <net/if.h> 45 #include <net/if_var.h> 46 #include <net/if_pflog.h> 47 48 #include <netinet/in.h> 49 #include <netinet/ip.h> 50 #include <netinet/ip_var.h> 51 #include <netinet/ip_icmp.h> 52 #include <netinet/tcp.h> 53 #include <netinet/tcp_seq.h> 54 #include <netinet/tcp_fsm.h> 55 #include <netinet/udp.h> 56 57 #ifdef INET6 58 #include <netinet6/in6_var.h> 59 #include <netinet/ip6.h> 60 #include <netinet6/ip6_var.h> 61 #include <netinet/icmp6.h> 62 #include <netinet6/nd6.h> 63 #endif /* INET6 */ 64 65 #include <net/pfvar.h> 66 #include <net/pfvar_priv.h> 67 68 struct pf_frent { 69 TAILQ_ENTRY(pf_frent) fr_next; 70 struct mbuf *fe_m; 71 u_int16_t fe_hdrlen; /* ipv4 header length with ip options 72 ipv6, extension, fragment header */ 73 u_int16_t fe_extoff; /* last extension header offset or 0 */ 74 u_int16_t fe_len; /* fragment length */ 75 u_int16_t fe_off; /* fragment offset */ 76 u_int16_t fe_mff; /* more fragment flag */ 77 }; 78 79 RB_HEAD(pf_frag_tree, pf_fragment); 80 struct pf_frnode { 81 struct pf_addr fn_src; /* ip source address */ 82 struct pf_addr fn_dst; /* ip destination address */ 83 sa_family_t fn_af; /* address family */ 84 u_int8_t fn_proto; /* protocol for fragments in fn_tree */ 85 u_int8_t fn_direction; /* pf packet direction */ 86 u_int32_t fn_fragments; /* number of entries in fn_tree */ 87 u_int32_t fn_gen; /* fr_gen of newest entry in fn_tree */ 88 89 RB_ENTRY(pf_frnode) fn_entry; 90 struct pf_frag_tree fn_tree; /* matching fragments, lookup by id */ 91 }; 92 93 struct pf_fragment { 94 struct pf_frent *fr_firstoff[PF_FRAG_ENTRY_POINTS]; 95 /* pointers to queue element */ 96 u_int8_t fr_entries[PF_FRAG_ENTRY_POINTS]; 97 /* count entries between pointers */ 98 RB_ENTRY(pf_fragment) fr_entry; 99 TAILQ_ENTRY(pf_fragment) frag_next; 100 TAILQ_HEAD(pf_fragq, pf_frent) fr_queue; 101 u_int32_t fr_id; /* fragment id for reassemble */ 102 int32_t fr_timeout; 103 u_int32_t fr_gen; /* generation number (per pf_frnode) */ 104 u_int16_t fr_maxlen; /* maximum length of single fragment */ 105 u_int16_t fr_holes; /* number of holes in the queue */ 106 struct pf_frnode *fr_node; /* ip src/dst/proto/af for fragments */ 107 }; 108 109 struct pf_fragment_tag { 110 u_int16_t ft_hdrlen; /* header length of reassembled pkt */ 111 u_int16_t ft_extoff; /* last extension header offset or 0 */ 112 u_int16_t ft_maxlen; /* maximum fragment payload length */ 113 }; 114 115 TAILQ_HEAD(pf_fragqueue, pf_fragment) pf_fragqueue; 116 117 static __inline int pf_frnode_compare(struct pf_frnode *, 118 struct pf_frnode *); 119 RB_HEAD(pf_frnode_tree, pf_frnode) pf_frnode_tree; 120 RB_PROTOTYPE(pf_frnode_tree, pf_frnode, fn_entry, pf_frnode_compare); 121 RB_GENERATE(pf_frnode_tree, pf_frnode, fn_entry, pf_frnode_compare); 122 123 static __inline int pf_frag_compare(struct pf_fragment *, 124 struct pf_fragment *); 125 RB_PROTOTYPE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare); 126 RB_GENERATE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare); 127 128 /* Private prototypes */ 129 void pf_flush_fragments(void); 130 void pf_free_fragment(struct pf_fragment *); 131 struct pf_fragment *pf_find_fragment(struct pf_frnode *, u_int32_t); 132 struct pf_frent *pf_create_fragment(u_short *); 133 int pf_frent_holes(struct pf_frent *); 134 static inline int pf_frent_index(struct pf_frent *); 135 int pf_frent_insert(struct pf_fragment *, 136 struct pf_frent *, struct pf_frent *); 137 void pf_frent_remove(struct pf_fragment *, 138 struct pf_frent *); 139 struct pf_frent *pf_frent_previous(struct pf_fragment *, 140 struct pf_frent *); 141 struct pf_fragment *pf_fillup_fragment(struct pf_frnode *, u_int32_t, 142 struct pf_frent *, u_short *); 143 struct mbuf *pf_join_fragment(struct pf_fragment *); 144 int pf_reassemble(struct mbuf **, int, u_short *); 145 #ifdef INET6 146 int pf_reassemble6(struct mbuf **, struct ip6_frag *, 147 u_int16_t, u_int16_t, int, u_short *); 148 #endif /* INET6 */ 149 150 /* Globals */ 151 struct pool pf_frent_pl, pf_frag_pl, pf_frnode_pl; 152 struct pool pf_state_scrub_pl; 153 154 struct mutex pf_frag_mtx; 155 156 #define PF_FRAG_LOCK_INIT() mtx_init(&pf_frag_mtx, IPL_SOFTNET) 157 158 void 159 pf_normalize_init(void) 160 { 161 pool_init(&pf_frent_pl, sizeof(struct pf_frent), 0, 162 IPL_SOFTNET, 0, "pffrent", NULL); 163 pool_init(&pf_frnode_pl, sizeof(struct pf_frnode), 0, 164 IPL_SOFTNET, 0, "pffrnode", NULL); 165 pool_init(&pf_frag_pl, sizeof(struct pf_fragment), 0, 166 IPL_SOFTNET, 0, "pffrag", NULL); 167 pool_init(&pf_state_scrub_pl, sizeof(struct pf_state_scrub), 0, 168 IPL_SOFTNET, 0, "pfstscr", NULL); 169 170 pool_sethiwat(&pf_frag_pl, PFFRAG_FRAG_HIWAT); 171 pool_sethardlimit(&pf_frent_pl, PFFRAG_FRENT_HIWAT, NULL, 0); 172 173 TAILQ_INIT(&pf_fragqueue); 174 175 PF_FRAG_LOCK_INIT(); 176 } 177 178 static __inline int 179 pf_frnode_compare(struct pf_frnode *a, struct pf_frnode *b) 180 { 181 int diff; 182 183 if ((diff = a->fn_proto - b->fn_proto) != 0) 184 return (diff); 185 if ((diff = a->fn_af - b->fn_af) != 0) 186 return (diff); 187 if ((diff = pf_addr_compare(&a->fn_src, &b->fn_src, a->fn_af)) != 0) 188 return (diff); 189 if ((diff = pf_addr_compare(&a->fn_dst, &b->fn_dst, a->fn_af)) != 0) 190 return (diff); 191 192 return (0); 193 } 194 195 static __inline int 196 pf_frag_compare(struct pf_fragment *a, struct pf_fragment *b) 197 { 198 int diff; 199 200 if ((diff = a->fr_id - b->fr_id) != 0) 201 return (diff); 202 203 return (0); 204 } 205 206 void 207 pf_purge_expired_fragments(void) 208 { 209 struct pf_fragment *frag; 210 int32_t expire; 211 212 PF_ASSERT_UNLOCKED(); 213 214 expire = getuptime() - pf_default_rule.timeout[PFTM_FRAG]; 215 216 PF_FRAG_LOCK(); 217 while ((frag = TAILQ_LAST(&pf_fragqueue, pf_fragqueue)) != NULL) { 218 if (frag->fr_timeout > expire) 219 break; 220 DPFPRINTF(LOG_NOTICE, "expiring %d(%p)", frag->fr_id, frag); 221 pf_free_fragment(frag); 222 } 223 PF_FRAG_UNLOCK(); 224 } 225 226 /* 227 * Try to flush old fragments to make space for new ones 228 */ 229 void 230 pf_flush_fragments(void) 231 { 232 struct pf_fragment *frag; 233 u_int goal; 234 235 goal = pf_status.fragments * 9 / 10; 236 DPFPRINTF(LOG_NOTICE, "trying to free > %u frents", 237 pf_status.fragments - goal); 238 while (goal < pf_status.fragments) { 239 if ((frag = TAILQ_LAST(&pf_fragqueue, pf_fragqueue)) == NULL) 240 break; 241 pf_free_fragment(frag); 242 } 243 } 244 245 /* 246 * Remove a fragment from the fragment queue, free its fragment entries, 247 * and free the fragment itself. 248 */ 249 void 250 pf_free_fragment(struct pf_fragment *frag) 251 { 252 struct pf_frent *frent; 253 struct pf_frnode *frnode; 254 255 frnode = frag->fr_node; 256 RB_REMOVE(pf_frag_tree, &frnode->fn_tree, frag); 257 KASSERT(frnode->fn_fragments >= 1); 258 frnode->fn_fragments--; 259 if (frnode->fn_fragments == 0) { 260 KASSERT(RB_EMPTY(&frnode->fn_tree)); 261 RB_REMOVE(pf_frnode_tree, &pf_frnode_tree, frnode); 262 pool_put(&pf_frnode_pl, frnode); 263 } 264 TAILQ_REMOVE(&pf_fragqueue, frag, frag_next); 265 266 /* Free all fragment entries */ 267 while ((frent = TAILQ_FIRST(&frag->fr_queue)) != NULL) { 268 TAILQ_REMOVE(&frag->fr_queue, frent, fr_next); 269 pf_status.ncounters[NCNT_FRAG_REMOVALS]++; 270 m_freem(frent->fe_m); 271 pool_put(&pf_frent_pl, frent); 272 pf_status.fragments--; 273 } 274 pool_put(&pf_frag_pl, frag); 275 } 276 277 struct pf_fragment * 278 pf_find_fragment(struct pf_frnode *key, u_int32_t id) 279 { 280 struct pf_fragment *frag, idkey; 281 struct pf_frnode *frnode; 282 u_int32_t stale; 283 284 frnode = RB_FIND(pf_frnode_tree, &pf_frnode_tree, key); 285 pf_status.ncounters[NCNT_FRAG_SEARCH]++; 286 if (frnode == NULL) 287 return (NULL); 288 KASSERT(frnode->fn_fragments >= 1); 289 idkey.fr_id = id; 290 frag = RB_FIND(pf_frag_tree, &frnode->fn_tree, &idkey); 291 if (frag == NULL) 292 return (NULL); 293 /* 294 * Limit the number of fragments we accept for each (proto,src,dst,af) 295 * combination (aka pf_frnode), so we can deal better with a high rate 296 * of fragments. Problem analysis is in RFC 4963. 297 * Store the current generation for each pf_frnode in fn_gen and on 298 * lookup discard 'stale' fragments (pf_fragment, based on the fr_gen 299 * member). Instead of adding another button interpret the pf fragment 300 * timeout in multiples of 200 fragments. This way the default of 60s 301 * means: pf_fragment objects older than 60*200 = 12,000 generations 302 * are considered stale. 303 */ 304 stale = pf_default_rule.timeout[PFTM_FRAG] * PF_FRAG_STALE; 305 if ((frnode->fn_gen - frag->fr_gen) >= stale) { 306 DPFPRINTF(LOG_NOTICE, "stale fragment %d(%p), gen %u, num %u", 307 frag->fr_id, frag, frag->fr_gen, frnode->fn_fragments); 308 pf_free_fragment(frag); 309 return (NULL); 310 } 311 TAILQ_REMOVE(&pf_fragqueue, frag, frag_next); 312 TAILQ_INSERT_HEAD(&pf_fragqueue, frag, frag_next); 313 314 return (frag); 315 } 316 317 struct pf_frent * 318 pf_create_fragment(u_short *reason) 319 { 320 struct pf_frent *frent; 321 322 frent = pool_get(&pf_frent_pl, PR_NOWAIT); 323 if (frent == NULL) { 324 pf_flush_fragments(); 325 frent = pool_get(&pf_frent_pl, PR_NOWAIT); 326 if (frent == NULL) { 327 REASON_SET(reason, PFRES_MEMORY); 328 return (NULL); 329 } 330 } 331 pf_status.fragments++; 332 333 return (frent); 334 } 335 336 /* 337 * Calculate the additional holes that were created in the fragment 338 * queue by inserting this fragment. A fragment in the middle 339 * creates one more hole by splitting. For each connected side, 340 * it loses one hole. 341 * Fragment entry must be in the queue when calling this function. 342 */ 343 int 344 pf_frent_holes(struct pf_frent *frent) 345 { 346 struct pf_frent *prev = TAILQ_PREV(frent, pf_fragq, fr_next); 347 struct pf_frent *next = TAILQ_NEXT(frent, fr_next); 348 int holes = 1; 349 350 if (prev == NULL) { 351 if (frent->fe_off == 0) 352 holes--; 353 } else { 354 KASSERT(frent->fe_off != 0); 355 if (frent->fe_off == prev->fe_off + prev->fe_len) 356 holes--; 357 } 358 if (next == NULL) { 359 if (!frent->fe_mff) 360 holes--; 361 } else { 362 KASSERT(frent->fe_mff); 363 if (next->fe_off == frent->fe_off + frent->fe_len) 364 holes--; 365 } 366 return holes; 367 } 368 369 static inline int 370 pf_frent_index(struct pf_frent *frent) 371 { 372 /* 373 * We have an array of 16 entry points to the queue. A full size 374 * 65535 octet IP packet can have 8192 fragments. So the queue 375 * traversal length is at most 512 and at most 16 entry points are 376 * checked. We need 128 additional bytes on a 64 bit architecture. 377 */ 378 CTASSERT(((u_int16_t)0xffff &~ 7) / (0x10000 / PF_FRAG_ENTRY_POINTS) == 379 16 - 1); 380 CTASSERT(((u_int16_t)0xffff >> 3) / PF_FRAG_ENTRY_POINTS == 512 - 1); 381 382 return frent->fe_off / (0x10000 / PF_FRAG_ENTRY_POINTS); 383 } 384 385 int 386 pf_frent_insert(struct pf_fragment *frag, struct pf_frent *frent, 387 struct pf_frent *prev) 388 { 389 CTASSERT(PF_FRAG_ENTRY_LIMIT <= 0xff); 390 int index; 391 392 /* 393 * A packet has at most 65536 octets. With 16 entry points, each one 394 * spawns 4096 octets. We limit these to 64 fragments each, which 395 * means on average every fragment must have at least 64 octets. 396 */ 397 index = pf_frent_index(frent); 398 if (frag->fr_entries[index] >= PF_FRAG_ENTRY_LIMIT) 399 return ENOBUFS; 400 frag->fr_entries[index]++; 401 402 if (prev == NULL) { 403 TAILQ_INSERT_HEAD(&frag->fr_queue, frent, fr_next); 404 } else { 405 KASSERT(prev->fe_off + prev->fe_len <= frent->fe_off); 406 TAILQ_INSERT_AFTER(&frag->fr_queue, prev, frent, fr_next); 407 } 408 pf_status.ncounters[NCNT_FRAG_INSERT]++; 409 410 if (frag->fr_firstoff[index] == NULL) { 411 KASSERT(prev == NULL || pf_frent_index(prev) < index); 412 frag->fr_firstoff[index] = frent; 413 } else { 414 if (frent->fe_off < frag->fr_firstoff[index]->fe_off) { 415 KASSERT(prev == NULL || pf_frent_index(prev) < index); 416 frag->fr_firstoff[index] = frent; 417 } else { 418 KASSERT(prev != NULL); 419 KASSERT(pf_frent_index(prev) == index); 420 } 421 } 422 423 frag->fr_holes += pf_frent_holes(frent); 424 425 return 0; 426 } 427 428 void 429 pf_frent_remove(struct pf_fragment *frag, struct pf_frent *frent) 430 { 431 #ifdef DIAGNOSTIC 432 struct pf_frent *prev = TAILQ_PREV(frent, pf_fragq, fr_next); 433 #endif 434 struct pf_frent *next = TAILQ_NEXT(frent, fr_next); 435 int index; 436 437 frag->fr_holes -= pf_frent_holes(frent); 438 439 index = pf_frent_index(frent); 440 KASSERT(frag->fr_firstoff[index] != NULL); 441 if (frag->fr_firstoff[index]->fe_off == frent->fe_off) { 442 if (next == NULL) { 443 frag->fr_firstoff[index] = NULL; 444 } else { 445 KASSERT(frent->fe_off + frent->fe_len <= next->fe_off); 446 if (pf_frent_index(next) == index) { 447 frag->fr_firstoff[index] = next; 448 } else { 449 frag->fr_firstoff[index] = NULL; 450 } 451 } 452 } else { 453 KASSERT(frag->fr_firstoff[index]->fe_off < frent->fe_off); 454 KASSERT(prev != NULL); 455 KASSERT(prev->fe_off + prev->fe_len <= frent->fe_off); 456 KASSERT(pf_frent_index(prev) == index); 457 } 458 459 TAILQ_REMOVE(&frag->fr_queue, frent, fr_next); 460 pf_status.ncounters[NCNT_FRAG_REMOVALS]++; 461 462 KASSERT(frag->fr_entries[index] > 0); 463 frag->fr_entries[index]--; 464 } 465 466 struct pf_frent * 467 pf_frent_previous(struct pf_fragment *frag, struct pf_frent *frent) 468 { 469 struct pf_frent *prev, *next; 470 int index; 471 472 /* 473 * If there are no fragments after frag, take the final one. Assume 474 * that the global queue is not empty. 475 */ 476 prev = TAILQ_LAST(&frag->fr_queue, pf_fragq); 477 KASSERT(prev != NULL); 478 if (prev->fe_off <= frent->fe_off) 479 return prev; 480 /* 481 * We want to find a fragment entry that is before frag, but still 482 * close to it. Find the first fragment entry that is in the same 483 * entry point or in the first entry point after that. As we have 484 * already checked that there are entries behind frag, this will 485 * succeed. 486 */ 487 for (index = pf_frent_index(frent); index < PF_FRAG_ENTRY_POINTS; 488 index++) { 489 prev = frag->fr_firstoff[index]; 490 if (prev != NULL) 491 break; 492 } 493 KASSERT(prev != NULL); 494 /* 495 * In prev we may have a fragment from the same entry point that is 496 * before frent, or one that is just one position behind frent. 497 * In the latter case, we go back one step and have the predecessor. 498 * There may be none if the new fragment will be the first one. 499 */ 500 if (prev->fe_off > frent->fe_off) { 501 prev = TAILQ_PREV(prev, pf_fragq, fr_next); 502 if (prev == NULL) 503 return NULL; 504 KASSERT(prev->fe_off <= frent->fe_off); 505 return prev; 506 } 507 /* 508 * In prev is the first fragment of the entry point. The offset 509 * of frag is behind it. Find the closest previous fragment. 510 */ 511 for (next = TAILQ_NEXT(prev, fr_next); next != NULL; 512 next = TAILQ_NEXT(next, fr_next)) { 513 if (next->fe_off > frent->fe_off) 514 break; 515 prev = next; 516 } 517 return prev; 518 } 519 520 struct pf_fragment * 521 pf_fillup_fragment(struct pf_frnode *key, u_int32_t id, 522 struct pf_frent *frent, u_short *reason) 523 { 524 struct pf_frent *after, *next, *prev; 525 struct pf_fragment *frag; 526 struct pf_frnode *frnode; 527 u_int16_t total; 528 529 /* No empty fragments */ 530 if (frent->fe_len == 0) { 531 DPFPRINTF(LOG_NOTICE, "bad fragment: len 0"); 532 goto bad_fragment; 533 } 534 535 /* All fragments are 8 byte aligned */ 536 if (frent->fe_mff && (frent->fe_len & 0x7)) { 537 DPFPRINTF(LOG_NOTICE, "bad fragment: mff and len %d", 538 frent->fe_len); 539 goto bad_fragment; 540 } 541 542 /* Respect maximum length, IP_MAXPACKET == IPV6_MAXPACKET */ 543 if (frent->fe_off + frent->fe_len > IP_MAXPACKET) { 544 DPFPRINTF(LOG_NOTICE, "bad fragment: max packet %d", 545 frent->fe_off + frent->fe_len); 546 goto bad_fragment; 547 } 548 549 DPFPRINTF(LOG_INFO, key->fn_af == AF_INET ? 550 "reass frag %d @ %d-%d" : "reass frag %#08x @ %d-%d", 551 id, frent->fe_off, frent->fe_off + frent->fe_len); 552 553 /* Fully buffer all of the fragments in this fragment queue */ 554 frag = pf_find_fragment(key, id); 555 556 /* Create a new reassembly queue for this packet */ 557 if (frag == NULL) { 558 frag = pool_get(&pf_frag_pl, PR_NOWAIT); 559 if (frag == NULL) { 560 pf_flush_fragments(); 561 frag = pool_get(&pf_frag_pl, PR_NOWAIT); 562 if (frag == NULL) { 563 REASON_SET(reason, PFRES_MEMORY); 564 goto drop_fragment; 565 } 566 } 567 frnode = RB_FIND(pf_frnode_tree, &pf_frnode_tree, key); 568 if (frnode == NULL) { 569 frnode = pool_get(&pf_frnode_pl, PR_NOWAIT); 570 if (frnode == NULL) { 571 pf_flush_fragments(); 572 frnode = pool_get(&pf_frnode_pl, PR_NOWAIT); 573 if (frnode == NULL) { 574 REASON_SET(reason, PFRES_MEMORY); 575 pool_put(&pf_frag_pl, frag); 576 goto drop_fragment; 577 } 578 } 579 *frnode = *key; 580 RB_INIT(&frnode->fn_tree); 581 frnode->fn_fragments = 0; 582 frnode->fn_gen = 0; 583 } 584 memset(frag->fr_firstoff, 0, sizeof(frag->fr_firstoff)); 585 memset(frag->fr_entries, 0, sizeof(frag->fr_entries)); 586 TAILQ_INIT(&frag->fr_queue); 587 frag->fr_id = id; 588 frag->fr_timeout = getuptime(); 589 frag->fr_gen = frnode->fn_gen++; 590 frag->fr_maxlen = frent->fe_len; 591 frag->fr_holes = 1; 592 frag->fr_node = frnode; 593 /* RB_INSERT cannot fail as pf_find_fragment() found nothing */ 594 RB_INSERT(pf_frag_tree, &frnode->fn_tree, frag); 595 frnode->fn_fragments++; 596 if (frnode->fn_fragments == 1) 597 RB_INSERT(pf_frnode_tree, &pf_frnode_tree, frnode); 598 TAILQ_INSERT_HEAD(&pf_fragqueue, frag, frag_next); 599 600 /* We do not have a previous fragment, cannot fail. */ 601 pf_frent_insert(frag, frent, NULL); 602 603 return (frag); 604 } 605 606 KASSERT(!TAILQ_EMPTY(&frag->fr_queue)); 607 KASSERT(frag->fr_node); 608 609 /* Remember maximum fragment len for refragmentation */ 610 if (frent->fe_len > frag->fr_maxlen) 611 frag->fr_maxlen = frent->fe_len; 612 613 /* Maximum data we have seen already */ 614 total = TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_off + 615 TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_len; 616 617 /* Non terminal fragments must have more fragments flag */ 618 if (frent->fe_off + frent->fe_len < total && !frent->fe_mff) 619 goto free_ipv6_fragment; 620 621 /* Check if we saw the last fragment already */ 622 if (!TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_mff) { 623 if (frent->fe_off + frent->fe_len > total || 624 (frent->fe_off + frent->fe_len == total && frent->fe_mff)) 625 goto free_ipv6_fragment; 626 } else { 627 if (frent->fe_off + frent->fe_len == total && !frent->fe_mff) 628 goto free_ipv6_fragment; 629 } 630 631 /* Find neighbors for newly inserted fragment */ 632 prev = pf_frent_previous(frag, frent); 633 if (prev == NULL) { 634 after = TAILQ_FIRST(&frag->fr_queue); 635 KASSERT(after != NULL); 636 } else { 637 after = TAILQ_NEXT(prev, fr_next); 638 } 639 640 if (prev != NULL && prev->fe_off + prev->fe_len > frent->fe_off) { 641 u_int16_t precut; 642 643 #ifdef INET6 644 if (frag->fr_node->fn_af == AF_INET6) 645 goto free_ipv6_fragment; 646 #endif /* INET6 */ 647 648 precut = prev->fe_off + prev->fe_len - frent->fe_off; 649 if (precut >= frent->fe_len) { 650 DPFPRINTF(LOG_NOTICE, "new frag overlapped"); 651 goto drop_fragment; 652 } 653 DPFPRINTF(LOG_NOTICE, "frag head overlap %d", 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 u_int16_t aftercut; 662 663 #ifdef INET6 664 if (frag->fr_node->fn_af == AF_INET6) 665 goto free_ipv6_fragment; 666 #endif /* INET6 */ 667 668 aftercut = frent->fe_off + frent->fe_len - after->fe_off; 669 if (aftercut < after->fe_len) { 670 int old_index, new_index; 671 672 DPFPRINTF(LOG_NOTICE, "frag tail overlap %d", aftercut); 673 m_adj(after->fe_m, aftercut); 674 old_index = pf_frent_index(after); 675 after->fe_off += aftercut; 676 after->fe_len -= aftercut; 677 new_index = pf_frent_index(after); 678 if (old_index != new_index) { 679 DPFPRINTF(LOG_DEBUG, "frag index %d, new %d", 680 old_index, new_index); 681 /* Fragment switched queue as fe_off changed */ 682 after->fe_off -= aftercut; 683 after->fe_len += aftercut; 684 /* Remove restored fragment from old queue */ 685 pf_frent_remove(frag, after); 686 after->fe_off += aftercut; 687 after->fe_len -= aftercut; 688 /* Insert into correct queue */ 689 if (pf_frent_insert(frag, after, prev)) { 690 DPFPRINTF(LOG_WARNING, 691 "fragment requeue limit exceeded"); 692 m_freem(after->fe_m); 693 pool_put(&pf_frent_pl, after); 694 pf_status.fragments--; 695 /* There is not way to recover */ 696 goto free_fragment; 697 } 698 } 699 break; 700 } 701 702 /* This fragment is completely overlapped, lose it */ 703 DPFPRINTF(LOG_NOTICE, "old frag overlapped"); 704 next = TAILQ_NEXT(after, fr_next); 705 pf_frent_remove(frag, after); 706 m_freem(after->fe_m); 707 pool_put(&pf_frent_pl, after); 708 pf_status.fragments--; 709 } 710 711 /* If part of the queue gets too long, there is not way to recover. */ 712 if (pf_frent_insert(frag, frent, prev)) { 713 DPFPRINTF(LOG_WARNING, "fragment queue limit exceeded"); 714 goto free_fragment; 715 } 716 717 return (frag); 718 719 free_ipv6_fragment: 720 if (frag->fr_node->fn_af == AF_INET) 721 goto bad_fragment; 722 /* 723 * RFC 5722, Errata 3089: When reassembling an IPv6 datagram, if one 724 * or more its constituent fragments is determined to be an overlapping 725 * fragment, the entire datagram (and any constituent fragments) MUST 726 * be silently discarded. 727 */ 728 DPFPRINTF(LOG_NOTICE, "flush overlapping fragments"); 729 free_fragment: 730 pf_free_fragment(frag); 731 bad_fragment: 732 REASON_SET(reason, PFRES_FRAG); 733 drop_fragment: 734 pool_put(&pf_frent_pl, frent); 735 pf_status.fragments--; 736 return (NULL); 737 } 738 739 struct mbuf * 740 pf_join_fragment(struct pf_fragment *frag) 741 { 742 struct mbuf *m, *m2; 743 struct pf_frent *frent; 744 745 frent = TAILQ_FIRST(&frag->fr_queue); 746 TAILQ_REMOVE(&frag->fr_queue, frent, fr_next); 747 pf_status.ncounters[NCNT_FRAG_REMOVALS]++; 748 749 m = frent->fe_m; 750 /* Strip off any trailing bytes */ 751 if ((frent->fe_hdrlen + frent->fe_len) < m->m_pkthdr.len) 752 m_adj(m, (frent->fe_hdrlen + frent->fe_len) - m->m_pkthdr.len); 753 /* Magic from ip_input */ 754 m2 = m->m_next; 755 m->m_next = NULL; 756 m_cat(m, m2); 757 pool_put(&pf_frent_pl, frent); 758 pf_status.fragments--; 759 760 while ((frent = TAILQ_FIRST(&frag->fr_queue)) != NULL) { 761 TAILQ_REMOVE(&frag->fr_queue, frent, fr_next); 762 pf_status.ncounters[NCNT_FRAG_REMOVALS]++; 763 m2 = frent->fe_m; 764 /* Strip off ip header */ 765 m_adj(m2, frent->fe_hdrlen); 766 /* Strip off any trailing bytes */ 767 if (frent->fe_len < m2->m_pkthdr.len) 768 m_adj(m2, frent->fe_len - m2->m_pkthdr.len); 769 pool_put(&pf_frent_pl, frent); 770 pf_status.fragments--; 771 m_removehdr(m2); 772 m_cat(m, m2); 773 } 774 775 /* Remove from fragment queue */ 776 pf_free_fragment(frag); 777 778 return (m); 779 } 780 781 int 782 pf_reassemble(struct mbuf **m0, int dir, u_short *reason) 783 { 784 struct mbuf *m = *m0; 785 struct ip *ip = mtod(m, struct ip *); 786 struct pf_frent *frent; 787 struct pf_fragment *frag; 788 struct pf_frnode key; 789 u_int16_t total, hdrlen; 790 791 /* Get an entry for the fragment queue */ 792 if ((frent = pf_create_fragment(reason)) == NULL) 793 return (PF_DROP); 794 795 frent->fe_m = m; 796 frent->fe_hdrlen = ip->ip_hl << 2; 797 frent->fe_extoff = 0; 798 frent->fe_len = ntohs(ip->ip_len) - (ip->ip_hl << 2); 799 frent->fe_off = (ntohs(ip->ip_off) & IP_OFFMASK) << 3; 800 frent->fe_mff = ntohs(ip->ip_off) & IP_MF; 801 802 key.fn_src.v4 = ip->ip_src; 803 key.fn_dst.v4 = ip->ip_dst; 804 key.fn_af = AF_INET; 805 key.fn_proto = ip->ip_p; 806 key.fn_direction = dir; 807 808 if ((frag = pf_fillup_fragment(&key, ip->ip_id, frent, reason)) 809 == NULL) 810 return (PF_DROP); 811 812 /* The mbuf is part of the fragment entry, no direct free or access */ 813 m = *m0 = NULL; 814 815 if (frag->fr_holes) { 816 DPFPRINTF(LOG_DEBUG, "frag %d, holes %d", 817 frag->fr_id, frag->fr_holes); 818 return (PF_PASS); /* drop because *m0 is NULL, no error */ 819 } 820 821 /* We have all the data */ 822 frent = TAILQ_FIRST(&frag->fr_queue); 823 KASSERT(frent != NULL); 824 total = TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_off + 825 TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_len; 826 hdrlen = frent->fe_hdrlen; 827 m = *m0 = pf_join_fragment(frag); 828 frag = NULL; 829 m_calchdrlen(m); 830 831 ip = mtod(m, struct ip *); 832 ip->ip_len = htons(hdrlen + total); 833 ip->ip_off &= ~(IP_MF|IP_OFFMASK); 834 835 if (hdrlen + total > IP_MAXPACKET) { 836 DPFPRINTF(LOG_NOTICE, "drop: too big: %d", total); 837 ip->ip_len = 0; 838 REASON_SET(reason, PFRES_SHORT); 839 /* PF_DROP requires a valid mbuf *m0 in pf_test() */ 840 return (PF_DROP); 841 } 842 843 DPFPRINTF(LOG_INFO, "complete: %p(%d)", m, ntohs(ip->ip_len)); 844 return (PF_PASS); 845 } 846 847 #ifdef INET6 848 int 849 pf_reassemble6(struct mbuf **m0, struct ip6_frag *fraghdr, 850 u_int16_t hdrlen, u_int16_t extoff, int dir, u_short *reason) 851 { 852 struct mbuf *m = *m0; 853 struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *); 854 struct m_tag *mtag; 855 struct pf_fragment_tag *ftag; 856 struct pf_frent *frent; 857 struct pf_fragment *frag; 858 struct pf_frnode key; 859 int off; 860 u_int16_t total, maxlen; 861 u_int8_t proto; 862 863 /* Get an entry for the fragment queue */ 864 if ((frent = pf_create_fragment(reason)) == NULL) 865 return (PF_DROP); 866 867 frent->fe_m = m; 868 frent->fe_hdrlen = hdrlen; 869 frent->fe_extoff = extoff; 870 frent->fe_len = sizeof(struct ip6_hdr) + ntohs(ip6->ip6_plen) - hdrlen; 871 frent->fe_off = ntohs(fraghdr->ip6f_offlg & IP6F_OFF_MASK); 872 frent->fe_mff = fraghdr->ip6f_offlg & IP6F_MORE_FRAG; 873 874 key.fn_src.v6 = ip6->ip6_src; 875 key.fn_dst.v6 = ip6->ip6_dst; 876 key.fn_af = AF_INET6; 877 /* Only the first fragment's protocol is relevant */ 878 key.fn_proto = 0; 879 key.fn_direction = dir; 880 881 if ((frag = pf_fillup_fragment(&key, fraghdr->ip6f_ident, frent, 882 reason)) == NULL) 883 return (PF_DROP); 884 885 /* The mbuf is part of the fragment entry, no direct free or access */ 886 m = *m0 = NULL; 887 888 if (frag->fr_holes) { 889 DPFPRINTF(LOG_DEBUG, "frag %#08x, holes %d", 890 frag->fr_id, frag->fr_holes); 891 return (PF_PASS); /* drop because *m0 is NULL, no error */ 892 } 893 894 /* We have all the data */ 895 frent = TAILQ_FIRST(&frag->fr_queue); 896 KASSERT(frent != NULL); 897 extoff = frent->fe_extoff; 898 maxlen = frag->fr_maxlen; 899 total = TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_off + 900 TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_len; 901 hdrlen = frent->fe_hdrlen - sizeof(struct ip6_frag); 902 m = *m0 = pf_join_fragment(frag); 903 frag = NULL; 904 905 /* Take protocol from first fragment header */ 906 if ((m = m_getptr(m, hdrlen + offsetof(struct ip6_frag, ip6f_nxt), 907 &off)) == NULL) 908 panic("%s: short frag mbuf chain", __func__); 909 proto = *(mtod(m, caddr_t) + off); 910 m = *m0; 911 912 /* Delete frag6 header */ 913 if (frag6_deletefraghdr(m, hdrlen) != 0) 914 goto fail; 915 916 m_calchdrlen(m); 917 918 if ((mtag = m_tag_get(PACKET_TAG_PF_REASSEMBLED, sizeof(struct 919 pf_fragment_tag), M_NOWAIT)) == NULL) 920 goto fail; 921 ftag = (struct pf_fragment_tag *)(mtag + 1); 922 ftag->ft_hdrlen = hdrlen; 923 ftag->ft_extoff = extoff; 924 ftag->ft_maxlen = maxlen; 925 m_tag_prepend(m, mtag); 926 927 ip6 = mtod(m, struct ip6_hdr *); 928 ip6->ip6_plen = htons(hdrlen - sizeof(struct ip6_hdr) + total); 929 if (extoff) { 930 /* Write protocol into next field of last extension header */ 931 if ((m = m_getptr(m, extoff + offsetof(struct ip6_ext, 932 ip6e_nxt), &off)) == NULL) 933 panic("%s: short ext mbuf chain", __func__); 934 *(mtod(m, caddr_t) + off) = proto; 935 m = *m0; 936 } else 937 ip6->ip6_nxt = proto; 938 939 if (hdrlen - sizeof(struct ip6_hdr) + total > IPV6_MAXPACKET) { 940 DPFPRINTF(LOG_NOTICE, "drop: too big: %d", total); 941 ip6->ip6_plen = 0; 942 REASON_SET(reason, PFRES_SHORT); 943 /* PF_DROP requires a valid mbuf *m0 in pf_test6() */ 944 return (PF_DROP); 945 } 946 947 DPFPRINTF(LOG_INFO, "complete: %p(%d)", m, ntohs(ip6->ip6_plen)); 948 return (PF_PASS); 949 950 fail: 951 REASON_SET(reason, PFRES_MEMORY); 952 /* PF_DROP requires a valid mbuf *m0 in pf_test6(), will free later */ 953 return (PF_DROP); 954 } 955 956 int 957 pf_refragment6(struct mbuf **m0, struct m_tag *mtag, struct sockaddr_in6 *dst, 958 struct ifnet *ifp, struct rtentry *rt) 959 { 960 struct mbuf *m = *m0; 961 struct mbuf_list ml; 962 struct pf_fragment_tag *ftag = (struct pf_fragment_tag *)(mtag + 1); 963 u_int32_t mtu; 964 u_int16_t hdrlen, extoff, maxlen; 965 u_int8_t proto; 966 int error; 967 968 hdrlen = ftag->ft_hdrlen; 969 extoff = ftag->ft_extoff; 970 maxlen = ftag->ft_maxlen; 971 m_tag_delete(m, mtag); 972 mtag = NULL; 973 ftag = NULL; 974 975 /* Checksum must be calculated for the whole packet */ 976 in6_proto_cksum_out(m, NULL); 977 978 if (extoff) { 979 int off; 980 981 /* Use protocol from next field of last extension header */ 982 if ((m = m_getptr(m, extoff + offsetof(struct ip6_ext, 983 ip6e_nxt), &off)) == NULL) 984 panic("%s: short ext mbuf chain", __func__); 985 proto = *(mtod(m, caddr_t) + off); 986 *(mtod(m, caddr_t) + off) = IPPROTO_FRAGMENT; 987 m = *m0; 988 } else { 989 struct ip6_hdr *hdr; 990 991 hdr = mtod(m, struct ip6_hdr *); 992 proto = hdr->ip6_nxt; 993 hdr->ip6_nxt = IPPROTO_FRAGMENT; 994 } 995 996 /* 997 * Maxlen may be less than 8 iff there was only a single 998 * fragment. As it was fragmented before, add a fragment 999 * header also for a single fragment. If total or maxlen 1000 * is less than 8, ip6_fragment() will return EMSGSIZE and 1001 * we drop the packet. 1002 */ 1003 mtu = hdrlen + sizeof(struct ip6_frag) + maxlen; 1004 error = ip6_fragment(m, &ml, hdrlen, proto, mtu); 1005 *m0 = NULL; /* ip6_fragment() has consumed original packet. */ 1006 if (error) { 1007 DPFPRINTF(LOG_NOTICE, "refragment error %d", error); 1008 return (PF_DROP); 1009 } 1010 1011 while ((m = ml_dequeue(&ml)) != NULL) { 1012 m->m_pkthdr.pf.flags |= PF_TAG_REFRAGMENTED; 1013 if (ifp == NULL) { 1014 int flags = 0; 1015 1016 switch (atomic_load_int(&ip6_forwarding)) { 1017 case 2: 1018 SET(flags, IPV6_FORWARDING_IPSEC); 1019 /* FALLTHROUGH */ 1020 case 1: 1021 SET(flags, IPV6_FORWARDING); 1022 break; 1023 default: 1024 ip6stat_inc(ip6s_cantforward); 1025 return (PF_DROP); 1026 } 1027 ip6_forward(m, NULL, flags); 1028 } else if ((u_long)m->m_pkthdr.len <= ifp->if_mtu) { 1029 ifp->if_output(ifp, m, sin6tosa(dst), rt); 1030 } else { 1031 icmp6_error(m, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu); 1032 } 1033 } 1034 1035 return (PF_PASS); 1036 } 1037 #endif /* INET6 */ 1038 1039 int 1040 pf_normalize_ip(struct pf_pdesc *pd, u_short *reason) 1041 { 1042 struct ip *h = mtod(pd->m, struct ip *); 1043 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3; 1044 u_int16_t mff = (ntohs(h->ip_off) & IP_MF); 1045 1046 if (!fragoff && !mff) 1047 goto no_fragment; 1048 1049 /* Clear IP_DF if we're in no-df mode */ 1050 if (pf_status.reass & PF_REASS_NODF && h->ip_off & htons(IP_DF)) 1051 h->ip_off &= htons(~IP_DF); 1052 1053 /* We're dealing with a fragment now. Don't allow fragments 1054 * with IP_DF to enter the cache. If the flag was cleared by 1055 * no-df above, fine. Otherwise drop it. 1056 */ 1057 if (h->ip_off & htons(IP_DF)) { 1058 DPFPRINTF(LOG_NOTICE, "bad fragment: IP_DF"); 1059 REASON_SET(reason, PFRES_FRAG); 1060 return (PF_DROP); 1061 } 1062 1063 if (!pf_status.reass) 1064 return (PF_PASS); /* no reassembly */ 1065 1066 /* Returns PF_DROP or m is NULL or completely reassembled mbuf */ 1067 PF_FRAG_LOCK(); 1068 if (pf_reassemble(&pd->m, pd->dir, reason) != PF_PASS) { 1069 PF_FRAG_UNLOCK(); 1070 return (PF_DROP); 1071 } 1072 PF_FRAG_UNLOCK(); 1073 if (pd->m == NULL) 1074 return (PF_PASS); /* packet has been reassembled, no error */ 1075 1076 h = mtod(pd->m, struct ip *); 1077 1078 no_fragment: 1079 /* At this point, only IP_DF is allowed in ip_off */ 1080 if (h->ip_off & ~htons(IP_DF)) 1081 h->ip_off &= htons(IP_DF); 1082 1083 return (PF_PASS); 1084 } 1085 1086 #ifdef INET6 1087 int 1088 pf_normalize_ip6(struct pf_pdesc *pd, u_short *reason) 1089 { 1090 struct ip6_frag frag; 1091 1092 if (pd->fragoff == 0) 1093 goto no_fragment; 1094 1095 if (!pf_pull_hdr(pd->m, pd->fragoff, &frag, sizeof(frag), reason, 1096 AF_INET6)) 1097 return (PF_DROP); 1098 1099 if (!pf_status.reass) 1100 return (PF_PASS); /* no reassembly */ 1101 1102 /* Returns PF_DROP or m is NULL or completely reassembled mbuf */ 1103 PF_FRAG_LOCK(); 1104 if (pf_reassemble6(&pd->m, &frag, pd->fragoff + sizeof(frag), 1105 pd->extoff, pd->dir, reason) != PF_PASS) { 1106 PF_FRAG_UNLOCK(); 1107 return (PF_DROP); 1108 } 1109 PF_FRAG_UNLOCK(); 1110 if (pd->m == NULL) 1111 return (PF_PASS); /* packet has been reassembled, no error */ 1112 1113 no_fragment: 1114 return (PF_PASS); 1115 } 1116 #endif /* INET6 */ 1117 1118 struct pf_state_scrub * 1119 pf_state_scrub_get(void) 1120 { 1121 return (pool_get(&pf_state_scrub_pl, PR_NOWAIT | PR_ZERO)); 1122 } 1123 1124 void 1125 pf_state_scrub_put(struct pf_state_scrub *scrub) 1126 { 1127 pool_put(&pf_state_scrub_pl, scrub); 1128 } 1129 1130 int 1131 pf_normalize_tcp_alloc(struct pf_state_peer *src) 1132 { 1133 src->scrub = pf_state_scrub_get(); 1134 if (src->scrub == NULL) 1135 return (ENOMEM); 1136 1137 return (0); 1138 } 1139 1140 int 1141 pf_normalize_tcp(struct pf_pdesc *pd) 1142 { 1143 struct tcphdr *th = &pd->hdr.tcp; 1144 u_short reason; 1145 u_int8_t flags; 1146 u_int rewrite = 0; 1147 1148 flags = th->th_flags; 1149 if (flags & TH_SYN) { 1150 /* Illegal packet */ 1151 if (flags & TH_RST) 1152 goto tcp_drop; 1153 1154 if (flags & TH_FIN) /* XXX why clear instead of drop? */ 1155 flags &= ~TH_FIN; 1156 } else { 1157 /* Illegal packet */ 1158 if (!(flags & (TH_ACK|TH_RST))) 1159 goto tcp_drop; 1160 } 1161 1162 if (!(flags & TH_ACK)) { 1163 /* These flags are only valid if ACK is set */ 1164 if (flags & (TH_FIN|TH_PUSH|TH_URG)) 1165 goto tcp_drop; 1166 } 1167 1168 /* If flags changed, or reserved data set, then adjust */ 1169 if (flags != th->th_flags || th->th_x2 != 0) { 1170 /* hack: set 4-bit th_x2 = 0 */ 1171 u_int8_t *th_off = (u_int8_t*)(&th->th_ack+1); 1172 pf_patch_8(pd, th_off, th->th_off << 4, PF_HI); 1173 1174 pf_patch_8(pd, &th->th_flags, flags, PF_LO); 1175 rewrite = 1; 1176 } 1177 1178 /* Remove urgent pointer, if TH_URG is not set */ 1179 if (!(flags & TH_URG) && th->th_urp) { 1180 pf_patch_16(pd, &th->th_urp, 0); 1181 rewrite = 1; 1182 } 1183 1184 /* copy back packet headers if we sanitized */ 1185 if (rewrite) { 1186 m_copyback(pd->m, pd->off, sizeof(*th), th, M_NOWAIT); 1187 } 1188 1189 return (PF_PASS); 1190 1191 tcp_drop: 1192 REASON_SET(&reason, PFRES_NORM); 1193 return (PF_DROP); 1194 } 1195 1196 int 1197 pf_normalize_tcp_init(struct pf_pdesc *pd, struct pf_state_peer *src) 1198 { 1199 struct tcphdr *th = &pd->hdr.tcp; 1200 u_int32_t tsval, tsecr; 1201 int olen; 1202 u_int8_t opts[MAX_TCPOPTLEN], *opt; 1203 1204 1205 KASSERT(src->scrub == NULL); 1206 1207 if (pf_normalize_tcp_alloc(src) != 0) 1208 return (1); 1209 1210 switch (pd->af) { 1211 case AF_INET: { 1212 struct ip *h = mtod(pd->m, struct ip *); 1213 src->scrub->pfss_ttl = h->ip_ttl; 1214 break; 1215 } 1216 #ifdef INET6 1217 case AF_INET6: { 1218 struct ip6_hdr *h = mtod(pd->m, struct ip6_hdr *); 1219 src->scrub->pfss_ttl = h->ip6_hlim; 1220 break; 1221 } 1222 #endif /* INET6 */ 1223 default: 1224 unhandled_af(pd->af); 1225 } 1226 1227 /* 1228 * All normalizations below are only begun if we see the start of 1229 * the connections. They must all set an enabled bit in pfss_flags 1230 */ 1231 if ((th->th_flags & TH_SYN) == 0) 1232 return (0); 1233 1234 olen = (th->th_off << 2) - sizeof(*th); 1235 if (olen < TCPOLEN_TIMESTAMP || !pf_pull_hdr(pd->m, 1236 pd->off + sizeof(*th), opts, olen, NULL, pd->af)) 1237 return (0); 1238 1239 opt = opts; 1240 while ((opt = pf_find_tcpopt(opt, opts, olen, 1241 TCPOPT_TIMESTAMP, TCPOLEN_TIMESTAMP)) != NULL) { 1242 1243 src->scrub->pfss_flags |= PFSS_TIMESTAMP; 1244 src->scrub->pfss_ts_mod = arc4random(); 1245 /* note PFSS_PAWS not set yet */ 1246 memcpy(&tsval, &opt[2], sizeof(u_int32_t)); 1247 memcpy(&tsecr, &opt[6], sizeof(u_int32_t)); 1248 src->scrub->pfss_tsval0 = ntohl(tsval); 1249 src->scrub->pfss_tsval = ntohl(tsval); 1250 src->scrub->pfss_tsecr = ntohl(tsecr); 1251 getmicrouptime(&src->scrub->pfss_last); 1252 1253 opt += opt[1]; 1254 } 1255 1256 return (0); 1257 } 1258 1259 void 1260 pf_normalize_tcp_cleanup(struct pf_state *state) 1261 { 1262 if (state->src.scrub) 1263 pool_put(&pf_state_scrub_pl, state->src.scrub); 1264 if (state->dst.scrub) 1265 pool_put(&pf_state_scrub_pl, state->dst.scrub); 1266 1267 /* Someday... flush the TCP segment reassembly descriptors. */ 1268 } 1269 1270 int 1271 pf_normalize_tcp_stateful(struct pf_pdesc *pd, u_short *reason, 1272 struct pf_state *state, struct pf_state_peer *src, 1273 struct pf_state_peer *dst, int *writeback) 1274 { 1275 struct tcphdr *th = &pd->hdr.tcp; 1276 struct timeval uptime; 1277 u_int tsval_from_last; 1278 u_int32_t tsval, tsecr; 1279 int copyback = 0; 1280 int got_ts = 0; 1281 int olen; 1282 u_int8_t opts[MAX_TCPOPTLEN], *opt; 1283 1284 KASSERT(src->scrub || dst->scrub); 1285 1286 /* 1287 * Enforce the minimum TTL seen for this connection. Negate a common 1288 * technique to evade an intrusion detection system and confuse 1289 * firewall state code. 1290 */ 1291 switch (pd->af) { 1292 case AF_INET: 1293 if (src->scrub) { 1294 struct ip *h = mtod(pd->m, struct ip *); 1295 if (h->ip_ttl > src->scrub->pfss_ttl) 1296 src->scrub->pfss_ttl = h->ip_ttl; 1297 h->ip_ttl = src->scrub->pfss_ttl; 1298 } 1299 break; 1300 #ifdef INET6 1301 case AF_INET6: 1302 if (src->scrub) { 1303 struct ip6_hdr *h = mtod(pd->m, struct ip6_hdr *); 1304 if (h->ip6_hlim > src->scrub->pfss_ttl) 1305 src->scrub->pfss_ttl = h->ip6_hlim; 1306 h->ip6_hlim = src->scrub->pfss_ttl; 1307 } 1308 break; 1309 #endif /* INET6 */ 1310 default: 1311 unhandled_af(pd->af); 1312 } 1313 1314 olen = (th->th_off << 2) - sizeof(*th); 1315 1316 if (olen >= TCPOLEN_TIMESTAMP && 1317 ((src->scrub && (src->scrub->pfss_flags & PFSS_TIMESTAMP)) || 1318 (dst->scrub && (dst->scrub->pfss_flags & PFSS_TIMESTAMP))) && 1319 pf_pull_hdr(pd->m, pd->off + sizeof(*th), opts, olen, NULL, 1320 pd->af)) { 1321 1322 /* Modulate the timestamps. Can be used for NAT detection, OS 1323 * uptime determination or reboot detection. 1324 */ 1325 opt = opts; 1326 while ((opt = pf_find_tcpopt(opt, opts, olen, 1327 TCPOPT_TIMESTAMP, TCPOLEN_TIMESTAMP)) != NULL) { 1328 1329 u_int8_t *ts = opt + 2; 1330 u_int8_t *tsr = opt + 6; 1331 1332 if (got_ts) { 1333 /* Huh? Multiple timestamps!? */ 1334 if (pf_status.debug >= LOG_NOTICE) { 1335 log(LOG_NOTICE, 1336 "pf: %s: multiple TS??", __func__); 1337 pf_print_state(state); 1338 addlog("\n"); 1339 } 1340 REASON_SET(reason, PFRES_TS); 1341 return (PF_DROP); 1342 } 1343 1344 memcpy(&tsval, ts, sizeof(u_int32_t)); 1345 memcpy(&tsecr, tsr, sizeof(u_int32_t)); 1346 1347 /* modulate TS */ 1348 if (tsval && src->scrub && 1349 (src->scrub->pfss_flags & PFSS_TIMESTAMP)) { 1350 /* tsval used further on */ 1351 tsval = ntohl(tsval); 1352 pf_patch_32_unaligned(pd, 1353 ts, htonl(tsval + src->scrub->pfss_ts_mod), 1354 PF_ALGNMNT(ts - opts)); 1355 copyback = 1; 1356 } 1357 1358 /* modulate TS reply if any (!0) */ 1359 if (tsecr && dst->scrub && 1360 (dst->scrub->pfss_flags & PFSS_TIMESTAMP)) { 1361 /* tsecr used further on */ 1362 tsecr = ntohl(tsecr) - dst->scrub->pfss_ts_mod; 1363 pf_patch_32_unaligned(pd, 1364 tsr, htonl(tsecr), PF_ALGNMNT(tsr - opts)); 1365 copyback = 1; 1366 } 1367 1368 got_ts = 1; 1369 opt += opt[1]; 1370 } 1371 1372 if (copyback) { 1373 /* Copyback the options, caller copies back header */ 1374 *writeback = 1; 1375 m_copyback(pd->m, pd->off + sizeof(*th), olen, opts, M_NOWAIT); 1376 } 1377 } 1378 1379 1380 /* 1381 * Must invalidate PAWS checks on connections idle for too long. 1382 * The fastest allowed timestamp clock is 1ms. That turns out to 1383 * be about 24 days before it wraps. XXX Right now our lowerbound 1384 * TS echo check only works for the first 12 days of a connection 1385 * when the TS has exhausted half its 32bit space 1386 */ 1387 #define TS_MAX_IDLE (24*24*60*60) 1388 #define TS_MAX_CONN (12*24*60*60) /* XXX remove when better tsecr check */ 1389 1390 getmicrouptime(&uptime); 1391 if (src->scrub && (src->scrub->pfss_flags & PFSS_PAWS) && 1392 (uptime.tv_sec - src->scrub->pfss_last.tv_sec > TS_MAX_IDLE || 1393 getuptime() - state->creation > TS_MAX_CONN)) { 1394 if (pf_status.debug >= LOG_NOTICE) { 1395 log(LOG_NOTICE, "pf: src idled out of PAWS "); 1396 pf_print_state(state); 1397 addlog("\n"); 1398 } 1399 src->scrub->pfss_flags = 1400 (src->scrub->pfss_flags & ~PFSS_PAWS) | PFSS_PAWS_IDLED; 1401 } 1402 if (dst->scrub && (dst->scrub->pfss_flags & PFSS_PAWS) && 1403 uptime.tv_sec - dst->scrub->pfss_last.tv_sec > TS_MAX_IDLE) { 1404 if (pf_status.debug >= LOG_NOTICE) { 1405 log(LOG_NOTICE, "pf: dst idled out of PAWS "); 1406 pf_print_state(state); 1407 addlog("\n"); 1408 } 1409 dst->scrub->pfss_flags = 1410 (dst->scrub->pfss_flags & ~PFSS_PAWS) | PFSS_PAWS_IDLED; 1411 } 1412 1413 if (got_ts && src->scrub && dst->scrub && 1414 (src->scrub->pfss_flags & PFSS_PAWS) && 1415 (dst->scrub->pfss_flags & PFSS_PAWS)) { 1416 /* Validate that the timestamps are "in-window". 1417 * RFC1323 describes TCP Timestamp options that allow 1418 * measurement of RTT (round trip time) and PAWS 1419 * (protection against wrapped sequence numbers). PAWS 1420 * gives us a set of rules for rejecting packets on 1421 * long fat pipes (packets that were somehow delayed 1422 * in transit longer than the time it took to send the 1423 * full TCP sequence space of 4Gb). We can use these 1424 * rules and infer a few others that will let us treat 1425 * the 32bit timestamp and the 32bit echoed timestamp 1426 * as sequence numbers to prevent a blind attacker from 1427 * inserting packets into a connection. 1428 * 1429 * RFC1323 tells us: 1430 * - The timestamp on this packet must be greater than 1431 * or equal to the last value echoed by the other 1432 * endpoint. The RFC says those will be discarded 1433 * since it is a dup that has already been acked. 1434 * This gives us a lowerbound on the timestamp. 1435 * timestamp >= other last echoed timestamp 1436 * - The timestamp will be less than or equal to 1437 * the last timestamp plus the time between the 1438 * last packet and now. The RFC defines the max 1439 * clock rate as 1ms. We will allow clocks to be 1440 * up to 10% fast and will allow a total difference 1441 * or 30 seconds due to a route change. And this 1442 * gives us an upperbound on the timestamp. 1443 * timestamp <= last timestamp + max ticks 1444 * We have to be careful here. Windows will send an 1445 * initial timestamp of zero and then initialize it 1446 * to a random value after the 3whs; presumably to 1447 * avoid a DoS by having to call an expensive RNG 1448 * during a SYN flood. Proof MS has at least one 1449 * good security geek. 1450 * 1451 * - The TCP timestamp option must also echo the other 1452 * endpoints timestamp. The timestamp echoed is the 1453 * one carried on the earliest unacknowledged segment 1454 * on the left edge of the sequence window. The RFC 1455 * states that the host will reject any echoed 1456 * timestamps that were larger than any ever sent. 1457 * This gives us an upperbound on the TS echo. 1458 * tescr <= largest_tsval 1459 * - The lowerbound on the TS echo is a little more 1460 * tricky to determine. The other endpoint's echoed 1461 * values will not decrease. But there may be 1462 * network conditions that re-order packets and 1463 * cause our view of them to decrease. For now the 1464 * only lowerbound we can safely determine is that 1465 * the TS echo will never be less than the original 1466 * TS. XXX There is probably a better lowerbound. 1467 * Remove TS_MAX_CONN with better lowerbound check. 1468 * tescr >= other original TS 1469 * 1470 * It is also important to note that the fastest 1471 * timestamp clock of 1ms will wrap its 32bit space in 1472 * 24 days. So we just disable TS checking after 24 1473 * days of idle time. We actually must use a 12d 1474 * connection limit until we can come up with a better 1475 * lowerbound to the TS echo check. 1476 */ 1477 struct timeval delta_ts; 1478 int ts_fudge; 1479 1480 /* 1481 * PFTM_TS_DIFF is how many seconds of leeway to allow 1482 * a host's timestamp. This can happen if the previous 1483 * packet got delayed in transit for much longer than 1484 * this packet. 1485 */ 1486 if ((ts_fudge = state->rule.ptr->timeout[PFTM_TS_DIFF]) == 0) 1487 ts_fudge = pf_default_rule.timeout[PFTM_TS_DIFF]; 1488 1489 /* Calculate max ticks since the last timestamp */ 1490 #define TS_MAXFREQ 1100 /* RFC max TS freq of 1Khz + 10% skew */ 1491 #define TS_MICROSECS 1000000 /* microseconds per second */ 1492 timersub(&uptime, &src->scrub->pfss_last, &delta_ts); 1493 tsval_from_last = (delta_ts.tv_sec + ts_fudge) * TS_MAXFREQ; 1494 tsval_from_last += delta_ts.tv_usec / (TS_MICROSECS/TS_MAXFREQ); 1495 1496 if ((src->state >= TCPS_ESTABLISHED && 1497 dst->state >= TCPS_ESTABLISHED) && 1498 (SEQ_LT(tsval, dst->scrub->pfss_tsecr) || 1499 SEQ_GT(tsval, src->scrub->pfss_tsval + tsval_from_last) || 1500 (tsecr && (SEQ_GT(tsecr, dst->scrub->pfss_tsval) || 1501 SEQ_LT(tsecr, dst->scrub->pfss_tsval0))))) { 1502 /* Bad RFC1323 implementation or an insertion attack. 1503 * 1504 * - Solaris 2.6 and 2.7 are known to send another ACK 1505 * after the FIN,FIN|ACK,ACK closing that carries 1506 * an old timestamp. 1507 */ 1508 1509 DPFPRINTF(LOG_NOTICE, "Timestamp failed %c%c%c%c", 1510 SEQ_LT(tsval, dst->scrub->pfss_tsecr) ? '0' : ' ', 1511 SEQ_GT(tsval, src->scrub->pfss_tsval + 1512 tsval_from_last) ? '1' : ' ', 1513 SEQ_GT(tsecr, dst->scrub->pfss_tsval) ? '2' : ' ', 1514 SEQ_LT(tsecr, dst->scrub->pfss_tsval0)? '3' : ' '); 1515 DPFPRINTF(LOG_NOTICE, " tsval: %u tsecr: %u " 1516 "+ticks: %u idle: %llu.%06lus", tsval, tsecr, 1517 tsval_from_last, (long long)delta_ts.tv_sec, 1518 delta_ts.tv_usec); 1519 DPFPRINTF(LOG_NOTICE, " src->tsval: %u tsecr: %u", 1520 src->scrub->pfss_tsval, src->scrub->pfss_tsecr); 1521 DPFPRINTF(LOG_NOTICE, " dst->tsval: %u tsecr: %u " 1522 "tsval0: %u", dst->scrub->pfss_tsval, 1523 dst->scrub->pfss_tsecr, dst->scrub->pfss_tsval0); 1524 if (pf_status.debug >= LOG_NOTICE) { 1525 log(LOG_NOTICE, "pf: "); 1526 pf_print_state(state); 1527 pf_print_flags(th->th_flags); 1528 addlog("\n"); 1529 } 1530 REASON_SET(reason, PFRES_TS); 1531 return (PF_DROP); 1532 } 1533 /* XXX I'd really like to require tsecr but it's optional */ 1534 } else if (!got_ts && (th->th_flags & TH_RST) == 0 && 1535 ((src->state == TCPS_ESTABLISHED && dst->state == TCPS_ESTABLISHED) 1536 || pd->p_len > 0 || (th->th_flags & TH_SYN)) && 1537 src->scrub && dst->scrub && 1538 (src->scrub->pfss_flags & PFSS_PAWS) && 1539 (dst->scrub->pfss_flags & PFSS_PAWS)) { 1540 /* Didn't send a timestamp. Timestamps aren't really useful 1541 * when: 1542 * - connection opening or closing (often not even sent). 1543 * but we must not let an attacker to put a FIN on a 1544 * data packet to sneak it through our ESTABLISHED check. 1545 * - on a TCP reset. RFC suggests not even looking at TS. 1546 * - on an empty ACK. The TS will not be echoed so it will 1547 * probably not help keep the RTT calculation in sync and 1548 * there isn't as much danger when the sequence numbers 1549 * got wrapped. So some stacks don't include TS on empty 1550 * ACKs :-( 1551 * 1552 * To minimize the disruption to mostly RFC1323 conformant 1553 * stacks, we will only require timestamps on data packets. 1554 * 1555 * And what do ya know, we cannot require timestamps on data 1556 * packets. There appear to be devices that do legitimate 1557 * TCP connection hijacking. There are HTTP devices that allow 1558 * a 3whs (with timestamps) and then buffer the HTTP request. 1559 * If the intermediate device has the HTTP response cache, it 1560 * will spoof the response but not bother timestamping its 1561 * packets. So we can look for the presence of a timestamp in 1562 * the first data packet and if there, require it in all future 1563 * packets. 1564 */ 1565 1566 if (pd->p_len > 0 && (src->scrub->pfss_flags & PFSS_DATA_TS)) { 1567 /* 1568 * Hey! Someone tried to sneak a packet in. Or the 1569 * stack changed its RFC1323 behavior?!?! 1570 */ 1571 if (pf_status.debug >= LOG_NOTICE) { 1572 log(LOG_NOTICE, 1573 "pf: did not receive expected RFC1323 " 1574 "timestamp"); 1575 pf_print_state(state); 1576 pf_print_flags(th->th_flags); 1577 addlog("\n"); 1578 } 1579 REASON_SET(reason, PFRES_TS); 1580 return (PF_DROP); 1581 } 1582 } 1583 1584 /* 1585 * We will note if a host sends his data packets with or without 1586 * timestamps. And require all data packets to contain a timestamp 1587 * if the first does. PAWS implicitly requires that all data packets be 1588 * timestamped. But I think there are middle-man devices that hijack 1589 * TCP streams immediately after the 3whs and don't timestamp their 1590 * packets (seen in a WWW accelerator or cache). 1591 */ 1592 if (pd->p_len > 0 && src->scrub && (src->scrub->pfss_flags & 1593 (PFSS_TIMESTAMP|PFSS_DATA_TS|PFSS_DATA_NOTS)) == PFSS_TIMESTAMP) { 1594 if (got_ts) 1595 src->scrub->pfss_flags |= PFSS_DATA_TS; 1596 else { 1597 src->scrub->pfss_flags |= PFSS_DATA_NOTS; 1598 if (pf_status.debug >= LOG_NOTICE && dst->scrub && 1599 (dst->scrub->pfss_flags & PFSS_TIMESTAMP)) { 1600 /* Don't warn if other host rejected RFC1323 */ 1601 log(LOG_NOTICE, 1602 "pf: broken RFC1323 stack did not " 1603 "timestamp data packet. Disabled PAWS " 1604 "security."); 1605 pf_print_state(state); 1606 pf_print_flags(th->th_flags); 1607 addlog("\n"); 1608 } 1609 } 1610 } 1611 1612 /* 1613 * Update PAWS values 1614 */ 1615 if (got_ts && src->scrub && PFSS_TIMESTAMP == (src->scrub->pfss_flags & 1616 (PFSS_PAWS_IDLED|PFSS_TIMESTAMP))) { 1617 getmicrouptime(&src->scrub->pfss_last); 1618 if (SEQ_GEQ(tsval, src->scrub->pfss_tsval) || 1619 (src->scrub->pfss_flags & PFSS_PAWS) == 0) 1620 src->scrub->pfss_tsval = tsval; 1621 1622 if (tsecr) { 1623 if (SEQ_GEQ(tsecr, src->scrub->pfss_tsecr) || 1624 (src->scrub->pfss_flags & PFSS_PAWS) == 0) 1625 src->scrub->pfss_tsecr = tsecr; 1626 1627 if ((src->scrub->pfss_flags & PFSS_PAWS) == 0 && 1628 (SEQ_LT(tsval, src->scrub->pfss_tsval0) || 1629 src->scrub->pfss_tsval0 == 0)) { 1630 /* tsval0 MUST be the lowest timestamp */ 1631 src->scrub->pfss_tsval0 = tsval; 1632 } 1633 1634 /* Only fully initialized after a TS gets echoed */ 1635 if ((src->scrub->pfss_flags & PFSS_PAWS) == 0) 1636 src->scrub->pfss_flags |= PFSS_PAWS; 1637 } 1638 } 1639 1640 /* I have a dream.... TCP segment reassembly.... */ 1641 return (0); 1642 } 1643 1644 int 1645 pf_normalize_mss(struct pf_pdesc *pd, u_int16_t maxmss) 1646 { 1647 int olen, optsoff; 1648 u_int8_t opts[MAX_TCPOPTLEN], *opt; 1649 1650 olen = (pd->hdr.tcp.th_off << 2) - sizeof(struct tcphdr); 1651 optsoff = pd->off + sizeof(struct tcphdr); 1652 if (olen < TCPOLEN_MAXSEG || 1653 !pf_pull_hdr(pd->m, optsoff, opts, olen, NULL, pd->af)) 1654 return (0); 1655 1656 opt = opts; 1657 while ((opt = pf_find_tcpopt(opt, opts, olen, 1658 TCPOPT_MAXSEG, TCPOLEN_MAXSEG)) != NULL) { 1659 u_int16_t mss; 1660 u_int8_t *mssp = opt + 2; 1661 memcpy(&mss, mssp, sizeof(mss)); 1662 if (ntohs(mss) > maxmss) { 1663 size_t mssoffopts = mssp - opts; 1664 pf_patch_16_unaligned(pd, &mss, 1665 htons(maxmss), PF_ALGNMNT(mssoffopts)); 1666 m_copyback(pd->m, optsoff + mssoffopts, 1667 sizeof(mss), &mss, M_NOWAIT); 1668 m_copyback(pd->m, pd->off, 1669 sizeof(struct tcphdr), &pd->hdr.tcp, M_NOWAIT); 1670 } 1671 1672 opt += opt[1]; 1673 } 1674 1675 return (0); 1676 } 1677 1678 void 1679 pf_scrub(struct mbuf *m, u_int16_t flags, sa_family_t af, u_int8_t min_ttl, 1680 u_int8_t tos) 1681 { 1682 struct ip *h = mtod(m, struct ip *); 1683 #ifdef INET6 1684 struct ip6_hdr *h6 = mtod(m, struct ip6_hdr *); 1685 #endif /* INET6 */ 1686 u_int16_t old; 1687 1688 /* Clear IP_DF if no-df was requested */ 1689 if (flags & PFSTATE_NODF && af == AF_INET && h->ip_off & htons(IP_DF)) { 1690 old = h->ip_off; 1691 h->ip_off &= htons(~IP_DF); 1692 pf_cksum_fixup(&h->ip_sum, old, h->ip_off, 0); 1693 } 1694 1695 /* Enforce a minimum ttl, may cause endless packet loops */ 1696 if (min_ttl && af == AF_INET && h->ip_ttl < min_ttl) { 1697 old = h->ip_ttl; 1698 h->ip_ttl = min_ttl; 1699 pf_cksum_fixup(&h->ip_sum, old, h->ip_ttl, 0); 1700 } 1701 #ifdef INET6 1702 if (min_ttl && af == AF_INET6 && h6->ip6_hlim < min_ttl) 1703 h6->ip6_hlim = min_ttl; 1704 #endif /* INET6 */ 1705 1706 /* Enforce tos */ 1707 if (flags & PFSTATE_SETTOS) { 1708 if (af == AF_INET) { 1709 /* 1710 * ip_tos is 8 bit field at offset 1. Use 16 bit value 1711 * at offset 0. 1712 */ 1713 old = *(u_int16_t *)h; 1714 h->ip_tos = tos | (h->ip_tos & IPTOS_ECN_MASK); 1715 pf_cksum_fixup(&h->ip_sum, old, *(u_int16_t *)h, 0); 1716 } 1717 #ifdef INET6 1718 if (af == AF_INET6) { 1719 /* drugs are unable to explain such idiocy */ 1720 h6->ip6_flow &= ~htonl(0x0fc00000); 1721 h6->ip6_flow |= htonl(((u_int32_t)tos) << 20); 1722 } 1723 #endif /* INET6 */ 1724 } 1725 1726 /* random-id, but not for fragments */ 1727 if (flags & PFSTATE_RANDOMID && af == AF_INET && 1728 !(h->ip_off & ~htons(IP_DF))) { 1729 old = h->ip_id; 1730 h->ip_id = htons(ip_randomid()); 1731 pf_cksum_fixup(&h->ip_sum, old, h->ip_id, 0); 1732 } 1733 } 1734