1 /*- 2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD 3 * 4 * Copyright (c) 2001 McAfee, Inc. 5 * Copyright (c) 2006,2013 Andre Oppermann, Internet Business Solutions AG 6 * All rights reserved. 7 * 8 * This software was developed for the FreeBSD Project by Jonathan Lemon 9 * and McAfee Research, the Security Research Division of McAfee, Inc. under 10 * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the 11 * DARPA CHATS research program. [2001 McAfee, Inc.] 12 * 13 * Redistribution and use in source and binary forms, with or without 14 * modification, are permitted provided that the following conditions 15 * are met: 16 * 1. Redistributions of source code must retain the above copyright 17 * notice, this list of conditions and the following disclaimer. 18 * 2. Redistributions in binary form must reproduce the above copyright 19 * notice, this list of conditions and the following disclaimer in the 20 * documentation and/or other materials provided with the distribution. 21 * 22 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND 23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 25 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE 26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 32 * SUCH DAMAGE. 33 */ 34 35 #include <sys/cdefs.h> 36 __FBSDID("$FreeBSD$"); 37 38 #include "opt_inet.h" 39 #include "opt_inet6.h" 40 #include "opt_ipsec.h" 41 #include "opt_pcbgroup.h" 42 43 #include <sys/param.h> 44 #include <sys/systm.h> 45 #include <sys/hash.h> 46 #include <sys/refcount.h> 47 #include <sys/kernel.h> 48 #include <sys/sysctl.h> 49 #include <sys/limits.h> 50 #include <sys/lock.h> 51 #include <sys/mutex.h> 52 #include <sys/malloc.h> 53 #include <sys/mbuf.h> 54 #include <sys/proc.h> /* for proc0 declaration */ 55 #include <sys/random.h> 56 #include <sys/socket.h> 57 #include <sys/socketvar.h> 58 #include <sys/syslog.h> 59 #include <sys/ucred.h> 60 61 #include <sys/md5.h> 62 #include <crypto/siphash/siphash.h> 63 64 #include <vm/uma.h> 65 66 #include <net/if.h> 67 #include <net/if_var.h> 68 #include <net/route.h> 69 #include <net/vnet.h> 70 71 #include <netinet/in.h> 72 #include <netinet/in_systm.h> 73 #include <netinet/ip.h> 74 #include <netinet/in_var.h> 75 #include <netinet/in_pcb.h> 76 #include <netinet/ip_var.h> 77 #include <netinet/ip_options.h> 78 #ifdef INET6 79 #include <netinet/ip6.h> 80 #include <netinet/icmp6.h> 81 #include <netinet6/nd6.h> 82 #include <netinet6/ip6_var.h> 83 #include <netinet6/in6_pcb.h> 84 #endif 85 #include <netinet/tcp.h> 86 #include <netinet/tcp_fastopen.h> 87 #include <netinet/tcp_fsm.h> 88 #include <netinet/tcp_seq.h> 89 #include <netinet/tcp_timer.h> 90 #include <netinet/tcp_var.h> 91 #include <netinet/tcp_syncache.h> 92 #ifdef INET6 93 #include <netinet6/tcp6_var.h> 94 #endif 95 #ifdef TCP_OFFLOAD 96 #include <netinet/toecore.h> 97 #endif 98 99 #include <netipsec/ipsec_support.h> 100 101 #include <machine/in_cksum.h> 102 103 #include <security/mac/mac_framework.h> 104 105 static VNET_DEFINE(int, tcp_syncookies) = 1; 106 #define V_tcp_syncookies VNET(tcp_syncookies) 107 SYSCTL_INT(_net_inet_tcp, OID_AUTO, syncookies, CTLFLAG_VNET | CTLFLAG_RW, 108 &VNET_NAME(tcp_syncookies), 0, 109 "Use TCP SYN cookies if the syncache overflows"); 110 111 static VNET_DEFINE(int, tcp_syncookiesonly) = 0; 112 #define V_tcp_syncookiesonly VNET(tcp_syncookiesonly) 113 SYSCTL_INT(_net_inet_tcp, OID_AUTO, syncookies_only, CTLFLAG_VNET | CTLFLAG_RW, 114 &VNET_NAME(tcp_syncookiesonly), 0, 115 "Use only TCP SYN cookies"); 116 117 static VNET_DEFINE(int, functions_inherit_listen_socket_stack) = 1; 118 #define V_functions_inherit_listen_socket_stack \ 119 VNET(functions_inherit_listen_socket_stack) 120 SYSCTL_INT(_net_inet_tcp, OID_AUTO, functions_inherit_listen_socket_stack, 121 CTLFLAG_VNET | CTLFLAG_RW, 122 &VNET_NAME(functions_inherit_listen_socket_stack), 0, 123 "Inherit listen socket's stack"); 124 125 #ifdef TCP_OFFLOAD 126 #define ADDED_BY_TOE(sc) ((sc)->sc_tod != NULL) 127 #endif 128 129 static void syncache_drop(struct syncache *, struct syncache_head *); 130 static void syncache_free(struct syncache *); 131 static void syncache_insert(struct syncache *, struct syncache_head *); 132 static int syncache_respond(struct syncache *, struct syncache_head *, int, 133 const struct mbuf *); 134 static struct socket *syncache_socket(struct syncache *, struct socket *, 135 struct mbuf *m); 136 static void syncache_timeout(struct syncache *sc, struct syncache_head *sch, 137 int docallout); 138 static void syncache_timer(void *); 139 140 static uint32_t syncookie_mac(struct in_conninfo *, tcp_seq, uint8_t, 141 uint8_t *, uintptr_t); 142 static tcp_seq syncookie_generate(struct syncache_head *, struct syncache *); 143 static struct syncache 144 *syncookie_lookup(struct in_conninfo *, struct syncache_head *, 145 struct syncache *, struct tcphdr *, struct tcpopt *, 146 struct socket *); 147 static void syncookie_reseed(void *); 148 #ifdef INVARIANTS 149 static int syncookie_cmp(struct in_conninfo *inc, struct syncache_head *sch, 150 struct syncache *sc, struct tcphdr *th, struct tcpopt *to, 151 struct socket *lso); 152 #endif 153 154 /* 155 * Transmit the SYN,ACK fewer times than TCP_MAXRXTSHIFT specifies. 156 * 3 retransmits corresponds to a timeout of 3 * (1 + 2 + 4 + 8) == 45 seconds, 157 * the odds are that the user has given up attempting to connect by then. 158 */ 159 #define SYNCACHE_MAXREXMTS 3 160 161 /* Arbitrary values */ 162 #define TCP_SYNCACHE_HASHSIZE 512 163 #define TCP_SYNCACHE_BUCKETLIMIT 30 164 165 static VNET_DEFINE(struct tcp_syncache, tcp_syncache); 166 #define V_tcp_syncache VNET(tcp_syncache) 167 168 static SYSCTL_NODE(_net_inet_tcp, OID_AUTO, syncache, CTLFLAG_RW, 0, 169 "TCP SYN cache"); 170 171 SYSCTL_UINT(_net_inet_tcp_syncache, OID_AUTO, bucketlimit, CTLFLAG_VNET | CTLFLAG_RDTUN, 172 &VNET_NAME(tcp_syncache.bucket_limit), 0, 173 "Per-bucket hash limit for syncache"); 174 175 SYSCTL_UINT(_net_inet_tcp_syncache, OID_AUTO, cachelimit, CTLFLAG_VNET | CTLFLAG_RDTUN, 176 &VNET_NAME(tcp_syncache.cache_limit), 0, 177 "Overall entry limit for syncache"); 178 179 SYSCTL_UMA_CUR(_net_inet_tcp_syncache, OID_AUTO, count, CTLFLAG_VNET, 180 &VNET_NAME(tcp_syncache.zone), "Current number of entries in syncache"); 181 182 SYSCTL_UINT(_net_inet_tcp_syncache, OID_AUTO, hashsize, CTLFLAG_VNET | CTLFLAG_RDTUN, 183 &VNET_NAME(tcp_syncache.hashsize), 0, 184 "Size of TCP syncache hashtable"); 185 186 static int 187 sysctl_net_inet_tcp_syncache_rexmtlimit_check(SYSCTL_HANDLER_ARGS) 188 { 189 int error; 190 u_int new; 191 192 new = V_tcp_syncache.rexmt_limit; 193 error = sysctl_handle_int(oidp, &new, 0, req); 194 if ((error == 0) && (req->newptr != NULL)) { 195 if (new > TCP_MAXRXTSHIFT) 196 error = EINVAL; 197 else 198 V_tcp_syncache.rexmt_limit = new; 199 } 200 return (error); 201 } 202 203 SYSCTL_PROC(_net_inet_tcp_syncache, OID_AUTO, rexmtlimit, 204 CTLFLAG_VNET | CTLTYPE_UINT | CTLFLAG_RW, 205 &VNET_NAME(tcp_syncache.rexmt_limit), 0, 206 sysctl_net_inet_tcp_syncache_rexmtlimit_check, "UI", 207 "Limit on SYN/ACK retransmissions"); 208 209 VNET_DEFINE(int, tcp_sc_rst_sock_fail) = 1; 210 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, rst_on_sock_fail, 211 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(tcp_sc_rst_sock_fail), 0, 212 "Send reset on socket allocation failure"); 213 214 static MALLOC_DEFINE(M_SYNCACHE, "syncache", "TCP syncache"); 215 216 #define SCH_LOCK(sch) mtx_lock(&(sch)->sch_mtx) 217 #define SCH_UNLOCK(sch) mtx_unlock(&(sch)->sch_mtx) 218 #define SCH_LOCK_ASSERT(sch) mtx_assert(&(sch)->sch_mtx, MA_OWNED) 219 220 /* 221 * Requires the syncache entry to be already removed from the bucket list. 222 */ 223 static void 224 syncache_free(struct syncache *sc) 225 { 226 227 if (sc->sc_ipopts) 228 (void) m_free(sc->sc_ipopts); 229 if (sc->sc_cred) 230 crfree(sc->sc_cred); 231 #ifdef MAC 232 mac_syncache_destroy(&sc->sc_label); 233 #endif 234 235 uma_zfree(V_tcp_syncache.zone, sc); 236 } 237 238 void 239 syncache_init(void) 240 { 241 int i; 242 243 V_tcp_syncache.hashsize = TCP_SYNCACHE_HASHSIZE; 244 V_tcp_syncache.bucket_limit = TCP_SYNCACHE_BUCKETLIMIT; 245 V_tcp_syncache.rexmt_limit = SYNCACHE_MAXREXMTS; 246 V_tcp_syncache.hash_secret = arc4random(); 247 248 TUNABLE_INT_FETCH("net.inet.tcp.syncache.hashsize", 249 &V_tcp_syncache.hashsize); 250 TUNABLE_INT_FETCH("net.inet.tcp.syncache.bucketlimit", 251 &V_tcp_syncache.bucket_limit); 252 if (!powerof2(V_tcp_syncache.hashsize) || 253 V_tcp_syncache.hashsize == 0) { 254 printf("WARNING: syncache hash size is not a power of 2.\n"); 255 V_tcp_syncache.hashsize = TCP_SYNCACHE_HASHSIZE; 256 } 257 V_tcp_syncache.hashmask = V_tcp_syncache.hashsize - 1; 258 259 /* Set limits. */ 260 V_tcp_syncache.cache_limit = 261 V_tcp_syncache.hashsize * V_tcp_syncache.bucket_limit; 262 TUNABLE_INT_FETCH("net.inet.tcp.syncache.cachelimit", 263 &V_tcp_syncache.cache_limit); 264 265 /* Allocate the hash table. */ 266 V_tcp_syncache.hashbase = malloc(V_tcp_syncache.hashsize * 267 sizeof(struct syncache_head), M_SYNCACHE, M_WAITOK | M_ZERO); 268 269 #ifdef VIMAGE 270 V_tcp_syncache.vnet = curvnet; 271 #endif 272 273 /* Initialize the hash buckets. */ 274 for (i = 0; i < V_tcp_syncache.hashsize; i++) { 275 TAILQ_INIT(&V_tcp_syncache.hashbase[i].sch_bucket); 276 mtx_init(&V_tcp_syncache.hashbase[i].sch_mtx, "tcp_sc_head", 277 NULL, MTX_DEF); 278 callout_init_mtx(&V_tcp_syncache.hashbase[i].sch_timer, 279 &V_tcp_syncache.hashbase[i].sch_mtx, 0); 280 V_tcp_syncache.hashbase[i].sch_length = 0; 281 V_tcp_syncache.hashbase[i].sch_sc = &V_tcp_syncache; 282 V_tcp_syncache.hashbase[i].sch_last_overflow = 283 -(SYNCOOKIE_LIFETIME + 1); 284 } 285 286 /* Create the syncache entry zone. */ 287 V_tcp_syncache.zone = uma_zcreate("syncache", sizeof(struct syncache), 288 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0); 289 V_tcp_syncache.cache_limit = uma_zone_set_max(V_tcp_syncache.zone, 290 V_tcp_syncache.cache_limit); 291 292 /* Start the SYN cookie reseeder callout. */ 293 callout_init(&V_tcp_syncache.secret.reseed, 1); 294 arc4rand(V_tcp_syncache.secret.key[0], SYNCOOKIE_SECRET_SIZE, 0); 295 arc4rand(V_tcp_syncache.secret.key[1], SYNCOOKIE_SECRET_SIZE, 0); 296 callout_reset(&V_tcp_syncache.secret.reseed, SYNCOOKIE_LIFETIME * hz, 297 syncookie_reseed, &V_tcp_syncache); 298 } 299 300 #ifdef VIMAGE 301 void 302 syncache_destroy(void) 303 { 304 struct syncache_head *sch; 305 struct syncache *sc, *nsc; 306 int i; 307 308 /* 309 * Stop the re-seed timer before freeing resources. No need to 310 * possibly schedule it another time. 311 */ 312 callout_drain(&V_tcp_syncache.secret.reseed); 313 314 /* Cleanup hash buckets: stop timers, free entries, destroy locks. */ 315 for (i = 0; i < V_tcp_syncache.hashsize; i++) { 316 317 sch = &V_tcp_syncache.hashbase[i]; 318 callout_drain(&sch->sch_timer); 319 320 SCH_LOCK(sch); 321 TAILQ_FOREACH_SAFE(sc, &sch->sch_bucket, sc_hash, nsc) 322 syncache_drop(sc, sch); 323 SCH_UNLOCK(sch); 324 KASSERT(TAILQ_EMPTY(&sch->sch_bucket), 325 ("%s: sch->sch_bucket not empty", __func__)); 326 KASSERT(sch->sch_length == 0, ("%s: sch->sch_length %d not 0", 327 __func__, sch->sch_length)); 328 mtx_destroy(&sch->sch_mtx); 329 } 330 331 KASSERT(uma_zone_get_cur(V_tcp_syncache.zone) == 0, 332 ("%s: cache_count not 0", __func__)); 333 334 /* Free the allocated global resources. */ 335 uma_zdestroy(V_tcp_syncache.zone); 336 free(V_tcp_syncache.hashbase, M_SYNCACHE); 337 } 338 #endif 339 340 /* 341 * Inserts a syncache entry into the specified bucket row. 342 * Locks and unlocks the syncache_head autonomously. 343 */ 344 static void 345 syncache_insert(struct syncache *sc, struct syncache_head *sch) 346 { 347 struct syncache *sc2; 348 349 SCH_LOCK(sch); 350 351 /* 352 * Make sure that we don't overflow the per-bucket limit. 353 * If the bucket is full, toss the oldest element. 354 */ 355 if (sch->sch_length >= V_tcp_syncache.bucket_limit) { 356 KASSERT(!TAILQ_EMPTY(&sch->sch_bucket), 357 ("sch->sch_length incorrect")); 358 sc2 = TAILQ_LAST(&sch->sch_bucket, sch_head); 359 sch->sch_last_overflow = time_uptime; 360 syncache_drop(sc2, sch); 361 TCPSTAT_INC(tcps_sc_bucketoverflow); 362 } 363 364 /* Put it into the bucket. */ 365 TAILQ_INSERT_HEAD(&sch->sch_bucket, sc, sc_hash); 366 sch->sch_length++; 367 368 #ifdef TCP_OFFLOAD 369 if (ADDED_BY_TOE(sc)) { 370 struct toedev *tod = sc->sc_tod; 371 372 tod->tod_syncache_added(tod, sc->sc_todctx); 373 } 374 #endif 375 376 /* Reinitialize the bucket row's timer. */ 377 if (sch->sch_length == 1) 378 sch->sch_nextc = ticks + INT_MAX; 379 syncache_timeout(sc, sch, 1); 380 381 SCH_UNLOCK(sch); 382 383 TCPSTATES_INC(TCPS_SYN_RECEIVED); 384 TCPSTAT_INC(tcps_sc_added); 385 } 386 387 /* 388 * Remove and free entry from syncache bucket row. 389 * Expects locked syncache head. 390 */ 391 static void 392 syncache_drop(struct syncache *sc, struct syncache_head *sch) 393 { 394 395 SCH_LOCK_ASSERT(sch); 396 397 TCPSTATES_DEC(TCPS_SYN_RECEIVED); 398 TAILQ_REMOVE(&sch->sch_bucket, sc, sc_hash); 399 sch->sch_length--; 400 401 #ifdef TCP_OFFLOAD 402 if (ADDED_BY_TOE(sc)) { 403 struct toedev *tod = sc->sc_tod; 404 405 tod->tod_syncache_removed(tod, sc->sc_todctx); 406 } 407 #endif 408 409 syncache_free(sc); 410 } 411 412 /* 413 * Engage/reengage time on bucket row. 414 */ 415 static void 416 syncache_timeout(struct syncache *sc, struct syncache_head *sch, int docallout) 417 { 418 sc->sc_rxttime = ticks + 419 TCPTV_RTOBASE * (tcp_syn_backoff[sc->sc_rxmits]); 420 sc->sc_rxmits++; 421 if (TSTMP_LT(sc->sc_rxttime, sch->sch_nextc)) { 422 sch->sch_nextc = sc->sc_rxttime; 423 if (docallout) 424 callout_reset(&sch->sch_timer, sch->sch_nextc - ticks, 425 syncache_timer, (void *)sch); 426 } 427 } 428 429 /* 430 * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted. 431 * If we have retransmitted an entry the maximum number of times, expire it. 432 * One separate timer for each bucket row. 433 */ 434 static void 435 syncache_timer(void *xsch) 436 { 437 struct syncache_head *sch = (struct syncache_head *)xsch; 438 struct syncache *sc, *nsc; 439 int tick = ticks; 440 char *s; 441 442 CURVNET_SET(sch->sch_sc->vnet); 443 444 /* NB: syncache_head has already been locked by the callout. */ 445 SCH_LOCK_ASSERT(sch); 446 447 /* 448 * In the following cycle we may remove some entries and/or 449 * advance some timeouts, so re-initialize the bucket timer. 450 */ 451 sch->sch_nextc = tick + INT_MAX; 452 453 TAILQ_FOREACH_SAFE(sc, &sch->sch_bucket, sc_hash, nsc) { 454 /* 455 * We do not check if the listen socket still exists 456 * and accept the case where the listen socket may be 457 * gone by the time we resend the SYN/ACK. We do 458 * not expect this to happens often. If it does, 459 * then the RST will be sent by the time the remote 460 * host does the SYN/ACK->ACK. 461 */ 462 if (TSTMP_GT(sc->sc_rxttime, tick)) { 463 if (TSTMP_LT(sc->sc_rxttime, sch->sch_nextc)) 464 sch->sch_nextc = sc->sc_rxttime; 465 continue; 466 } 467 if (sc->sc_rxmits > V_tcp_syncache.rexmt_limit) { 468 if ((s = tcp_log_addrs(&sc->sc_inc, NULL, NULL, NULL))) { 469 log(LOG_DEBUG, "%s; %s: Retransmits exhausted, " 470 "giving up and removing syncache entry\n", 471 s, __func__); 472 free(s, M_TCPLOG); 473 } 474 syncache_drop(sc, sch); 475 TCPSTAT_INC(tcps_sc_stale); 476 continue; 477 } 478 if ((s = tcp_log_addrs(&sc->sc_inc, NULL, NULL, NULL))) { 479 log(LOG_DEBUG, "%s; %s: Response timeout, " 480 "retransmitting (%u) SYN|ACK\n", 481 s, __func__, sc->sc_rxmits); 482 free(s, M_TCPLOG); 483 } 484 485 syncache_respond(sc, sch, 1, NULL); 486 TCPSTAT_INC(tcps_sc_retransmitted); 487 syncache_timeout(sc, sch, 0); 488 } 489 if (!TAILQ_EMPTY(&(sch)->sch_bucket)) 490 callout_reset(&(sch)->sch_timer, (sch)->sch_nextc - tick, 491 syncache_timer, (void *)(sch)); 492 CURVNET_RESTORE(); 493 } 494 495 /* 496 * Find an entry in the syncache. 497 * Returns always with locked syncache_head plus a matching entry or NULL. 498 */ 499 static struct syncache * 500 syncache_lookup(struct in_conninfo *inc, struct syncache_head **schp) 501 { 502 struct syncache *sc; 503 struct syncache_head *sch; 504 uint32_t hash; 505 506 /* 507 * The hash is built on foreign port + local port + foreign address. 508 * We rely on the fact that struct in_conninfo starts with 16 bits 509 * of foreign port, then 16 bits of local port then followed by 128 510 * bits of foreign address. In case of IPv4 address, the first 3 511 * 32-bit words of the address always are zeroes. 512 */ 513 hash = jenkins_hash32((uint32_t *)&inc->inc_ie, 5, 514 V_tcp_syncache.hash_secret) & V_tcp_syncache.hashmask; 515 516 sch = &V_tcp_syncache.hashbase[hash]; 517 *schp = sch; 518 SCH_LOCK(sch); 519 520 /* Circle through bucket row to find matching entry. */ 521 TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash) 522 if (bcmp(&inc->inc_ie, &sc->sc_inc.inc_ie, 523 sizeof(struct in_endpoints)) == 0) 524 break; 525 526 return (sc); /* Always returns with locked sch. */ 527 } 528 529 /* 530 * This function is called when we get a RST for a 531 * non-existent connection, so that we can see if the 532 * connection is in the syn cache. If it is, zap it. 533 */ 534 void 535 syncache_chkrst(struct in_conninfo *inc, struct tcphdr *th) 536 { 537 struct syncache *sc; 538 struct syncache_head *sch; 539 char *s = NULL; 540 541 sc = syncache_lookup(inc, &sch); /* returns locked sch */ 542 SCH_LOCK_ASSERT(sch); 543 544 /* 545 * Any RST to our SYN|ACK must not carry ACK, SYN or FIN flags. 546 * See RFC 793 page 65, section SEGMENT ARRIVES. 547 */ 548 if (th->th_flags & (TH_ACK|TH_SYN|TH_FIN)) { 549 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) 550 log(LOG_DEBUG, "%s; %s: Spurious RST with ACK, SYN or " 551 "FIN flag set, segment ignored\n", s, __func__); 552 TCPSTAT_INC(tcps_badrst); 553 goto done; 554 } 555 556 /* 557 * No corresponding connection was found in syncache. 558 * If syncookies are enabled and possibly exclusively 559 * used, or we are under memory pressure, a valid RST 560 * may not find a syncache entry. In that case we're 561 * done and no SYN|ACK retransmissions will happen. 562 * Otherwise the RST was misdirected or spoofed. 563 */ 564 if (sc == NULL) { 565 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) 566 log(LOG_DEBUG, "%s; %s: Spurious RST without matching " 567 "syncache entry (possibly syncookie only), " 568 "segment ignored\n", s, __func__); 569 TCPSTAT_INC(tcps_badrst); 570 goto done; 571 } 572 573 /* 574 * If the RST bit is set, check the sequence number to see 575 * if this is a valid reset segment. 576 * RFC 793 page 37: 577 * In all states except SYN-SENT, all reset (RST) segments 578 * are validated by checking their SEQ-fields. A reset is 579 * valid if its sequence number is in the window. 580 * 581 * The sequence number in the reset segment is normally an 582 * echo of our outgoing acknowlegement numbers, but some hosts 583 * send a reset with the sequence number at the rightmost edge 584 * of our receive window, and we have to handle this case. 585 */ 586 if (SEQ_GEQ(th->th_seq, sc->sc_irs) && 587 SEQ_LEQ(th->th_seq, sc->sc_irs + sc->sc_wnd)) { 588 syncache_drop(sc, sch); 589 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) 590 log(LOG_DEBUG, "%s; %s: Our SYN|ACK was rejected, " 591 "connection attempt aborted by remote endpoint\n", 592 s, __func__); 593 TCPSTAT_INC(tcps_sc_reset); 594 } else { 595 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) 596 log(LOG_DEBUG, "%s; %s: RST with invalid SEQ %u != " 597 "IRS %u (+WND %u), segment ignored\n", 598 s, __func__, th->th_seq, sc->sc_irs, sc->sc_wnd); 599 TCPSTAT_INC(tcps_badrst); 600 } 601 602 done: 603 if (s != NULL) 604 free(s, M_TCPLOG); 605 SCH_UNLOCK(sch); 606 } 607 608 void 609 syncache_badack(struct in_conninfo *inc) 610 { 611 struct syncache *sc; 612 struct syncache_head *sch; 613 614 sc = syncache_lookup(inc, &sch); /* returns locked sch */ 615 SCH_LOCK_ASSERT(sch); 616 if (sc != NULL) { 617 syncache_drop(sc, sch); 618 TCPSTAT_INC(tcps_sc_badack); 619 } 620 SCH_UNLOCK(sch); 621 } 622 623 void 624 syncache_unreach(struct in_conninfo *inc, tcp_seq th_seq) 625 { 626 struct syncache *sc; 627 struct syncache_head *sch; 628 629 sc = syncache_lookup(inc, &sch); /* returns locked sch */ 630 SCH_LOCK_ASSERT(sch); 631 if (sc == NULL) 632 goto done; 633 634 /* If the sequence number != sc_iss, then it's a bogus ICMP msg */ 635 if (ntohl(th_seq) != sc->sc_iss) 636 goto done; 637 638 /* 639 * If we've rertransmitted 3 times and this is our second error, 640 * we remove the entry. Otherwise, we allow it to continue on. 641 * This prevents us from incorrectly nuking an entry during a 642 * spurious network outage. 643 * 644 * See tcp_notify(). 645 */ 646 if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxmits < 3 + 1) { 647 sc->sc_flags |= SCF_UNREACH; 648 goto done; 649 } 650 syncache_drop(sc, sch); 651 TCPSTAT_INC(tcps_sc_unreach); 652 done: 653 SCH_UNLOCK(sch); 654 } 655 656 /* 657 * Build a new TCP socket structure from a syncache entry. 658 * 659 * On success return the newly created socket with its underlying inp locked. 660 */ 661 static struct socket * 662 syncache_socket(struct syncache *sc, struct socket *lso, struct mbuf *m) 663 { 664 struct tcp_function_block *blk; 665 struct inpcb *inp = NULL; 666 struct socket *so; 667 struct tcpcb *tp; 668 int error; 669 char *s; 670 671 INP_INFO_RLOCK_ASSERT(&V_tcbinfo); 672 673 /* 674 * Ok, create the full blown connection, and set things up 675 * as they would have been set up if we had created the 676 * connection when the SYN arrived. If we can't create 677 * the connection, abort it. 678 */ 679 so = sonewconn(lso, 0); 680 if (so == NULL) { 681 /* 682 * Drop the connection; we will either send a RST or 683 * have the peer retransmit its SYN again after its 684 * RTO and try again. 685 */ 686 TCPSTAT_INC(tcps_listendrop); 687 if ((s = tcp_log_addrs(&sc->sc_inc, NULL, NULL, NULL))) { 688 log(LOG_DEBUG, "%s; %s: Socket create failed " 689 "due to limits or memory shortage\n", 690 s, __func__); 691 free(s, M_TCPLOG); 692 } 693 goto abort2; 694 } 695 #ifdef MAC 696 mac_socketpeer_set_from_mbuf(m, so); 697 #endif 698 699 inp = sotoinpcb(so); 700 inp->inp_inc.inc_fibnum = so->so_fibnum; 701 INP_WLOCK(inp); 702 /* 703 * Exclusive pcbinfo lock is not required in syncache socket case even 704 * if two inpcb locks can be acquired simultaneously: 705 * - the inpcb in LISTEN state, 706 * - the newly created inp. 707 * 708 * In this case, an inp cannot be at same time in LISTEN state and 709 * just created by an accept() call. 710 */ 711 INP_HASH_WLOCK(&V_tcbinfo); 712 713 /* Insert new socket into PCB hash list. */ 714 inp->inp_inc.inc_flags = sc->sc_inc.inc_flags; 715 #ifdef INET6 716 if (sc->sc_inc.inc_flags & INC_ISIPV6) { 717 inp->inp_vflag &= ~INP_IPV4; 718 inp->inp_vflag |= INP_IPV6; 719 inp->in6p_laddr = sc->sc_inc.inc6_laddr; 720 } else { 721 inp->inp_vflag &= ~INP_IPV6; 722 inp->inp_vflag |= INP_IPV4; 723 #endif 724 inp->inp_laddr = sc->sc_inc.inc_laddr; 725 #ifdef INET6 726 } 727 #endif 728 729 /* 730 * If there's an mbuf and it has a flowid, then let's initialise the 731 * inp with that particular flowid. 732 */ 733 if (m != NULL && M_HASHTYPE_GET(m) != M_HASHTYPE_NONE) { 734 inp->inp_flowid = m->m_pkthdr.flowid; 735 inp->inp_flowtype = M_HASHTYPE_GET(m); 736 } 737 738 /* 739 * Install in the reservation hash table for now, but don't yet 740 * install a connection group since the full 4-tuple isn't yet 741 * configured. 742 */ 743 inp->inp_lport = sc->sc_inc.inc_lport; 744 if ((error = in_pcbinshash_nopcbgroup(inp)) != 0) { 745 /* 746 * Undo the assignments above if we failed to 747 * put the PCB on the hash lists. 748 */ 749 #ifdef INET6 750 if (sc->sc_inc.inc_flags & INC_ISIPV6) 751 inp->in6p_laddr = in6addr_any; 752 else 753 #endif 754 inp->inp_laddr.s_addr = INADDR_ANY; 755 inp->inp_lport = 0; 756 if ((s = tcp_log_addrs(&sc->sc_inc, NULL, NULL, NULL))) { 757 log(LOG_DEBUG, "%s; %s: in_pcbinshash failed " 758 "with error %i\n", 759 s, __func__, error); 760 free(s, M_TCPLOG); 761 } 762 INP_HASH_WUNLOCK(&V_tcbinfo); 763 goto abort; 764 } 765 #ifdef INET6 766 if (sc->sc_inc.inc_flags & INC_ISIPV6) { 767 struct inpcb *oinp = sotoinpcb(lso); 768 struct in6_addr laddr6; 769 struct sockaddr_in6 sin6; 770 /* 771 * Inherit socket options from the listening socket. 772 * Note that in6p_inputopts are not (and should not be) 773 * copied, since it stores previously received options and is 774 * used to detect if each new option is different than the 775 * previous one and hence should be passed to a user. 776 * If we copied in6p_inputopts, a user would not be able to 777 * receive options just after calling the accept system call. 778 */ 779 inp->inp_flags |= oinp->inp_flags & INP_CONTROLOPTS; 780 if (oinp->in6p_outputopts) 781 inp->in6p_outputopts = 782 ip6_copypktopts(oinp->in6p_outputopts, M_NOWAIT); 783 784 sin6.sin6_family = AF_INET6; 785 sin6.sin6_len = sizeof(sin6); 786 sin6.sin6_addr = sc->sc_inc.inc6_faddr; 787 sin6.sin6_port = sc->sc_inc.inc_fport; 788 sin6.sin6_flowinfo = sin6.sin6_scope_id = 0; 789 laddr6 = inp->in6p_laddr; 790 if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) 791 inp->in6p_laddr = sc->sc_inc.inc6_laddr; 792 if ((error = in6_pcbconnect_mbuf(inp, (struct sockaddr *)&sin6, 793 thread0.td_ucred, m)) != 0) { 794 inp->in6p_laddr = laddr6; 795 if ((s = tcp_log_addrs(&sc->sc_inc, NULL, NULL, NULL))) { 796 log(LOG_DEBUG, "%s; %s: in6_pcbconnect failed " 797 "with error %i\n", 798 s, __func__, error); 799 free(s, M_TCPLOG); 800 } 801 INP_HASH_WUNLOCK(&V_tcbinfo); 802 goto abort; 803 } 804 /* Override flowlabel from in6_pcbconnect. */ 805 inp->inp_flow &= ~IPV6_FLOWLABEL_MASK; 806 inp->inp_flow |= sc->sc_flowlabel; 807 } 808 #endif /* INET6 */ 809 #if defined(INET) && defined(INET6) 810 else 811 #endif 812 #ifdef INET 813 { 814 struct in_addr laddr; 815 struct sockaddr_in sin; 816 817 inp->inp_options = (m) ? ip_srcroute(m) : NULL; 818 819 if (inp->inp_options == NULL) { 820 inp->inp_options = sc->sc_ipopts; 821 sc->sc_ipopts = NULL; 822 } 823 824 sin.sin_family = AF_INET; 825 sin.sin_len = sizeof(sin); 826 sin.sin_addr = sc->sc_inc.inc_faddr; 827 sin.sin_port = sc->sc_inc.inc_fport; 828 bzero((caddr_t)sin.sin_zero, sizeof(sin.sin_zero)); 829 laddr = inp->inp_laddr; 830 if (inp->inp_laddr.s_addr == INADDR_ANY) 831 inp->inp_laddr = sc->sc_inc.inc_laddr; 832 if ((error = in_pcbconnect_mbuf(inp, (struct sockaddr *)&sin, 833 thread0.td_ucred, m)) != 0) { 834 inp->inp_laddr = laddr; 835 if ((s = tcp_log_addrs(&sc->sc_inc, NULL, NULL, NULL))) { 836 log(LOG_DEBUG, "%s; %s: in_pcbconnect failed " 837 "with error %i\n", 838 s, __func__, error); 839 free(s, M_TCPLOG); 840 } 841 INP_HASH_WUNLOCK(&V_tcbinfo); 842 goto abort; 843 } 844 } 845 #endif /* INET */ 846 #if defined(IPSEC) || defined(IPSEC_SUPPORT) 847 /* Copy old policy into new socket's. */ 848 if (ipsec_copy_pcbpolicy(sotoinpcb(lso), inp) != 0) 849 printf("syncache_socket: could not copy policy\n"); 850 #endif 851 INP_HASH_WUNLOCK(&V_tcbinfo); 852 tp = intotcpcb(inp); 853 tcp_state_change(tp, TCPS_SYN_RECEIVED); 854 tp->iss = sc->sc_iss; 855 tp->irs = sc->sc_irs; 856 tcp_rcvseqinit(tp); 857 tcp_sendseqinit(tp); 858 blk = sototcpcb(lso)->t_fb; 859 if (V_functions_inherit_listen_socket_stack && blk != tp->t_fb) { 860 /* 861 * Our parents t_fb was not the default, 862 * we need to release our ref on tp->t_fb and 863 * pickup one on the new entry. 864 */ 865 struct tcp_function_block *rblk; 866 867 rblk = find_and_ref_tcp_fb(blk); 868 KASSERT(rblk != NULL, 869 ("cannot find blk %p out of syncache?", blk)); 870 if (tp->t_fb->tfb_tcp_fb_fini) 871 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 0); 872 refcount_release(&tp->t_fb->tfb_refcnt); 873 tp->t_fb = rblk; 874 /* 875 * XXXrrs this is quite dangerous, it is possible 876 * for the new function to fail to init. We also 877 * are not asking if the handoff_is_ok though at 878 * the very start thats probalbly ok. 879 */ 880 if (tp->t_fb->tfb_tcp_fb_init) { 881 (*tp->t_fb->tfb_tcp_fb_init)(tp); 882 } 883 } 884 tp->snd_wl1 = sc->sc_irs; 885 tp->snd_max = tp->iss + 1; 886 tp->snd_nxt = tp->iss + 1; 887 tp->rcv_up = sc->sc_irs + 1; 888 tp->rcv_wnd = sc->sc_wnd; 889 tp->rcv_adv += tp->rcv_wnd; 890 tp->last_ack_sent = tp->rcv_nxt; 891 892 tp->t_flags = sototcpcb(lso)->t_flags & (TF_NOPUSH|TF_NODELAY); 893 if (sc->sc_flags & SCF_NOOPT) 894 tp->t_flags |= TF_NOOPT; 895 else { 896 if (sc->sc_flags & SCF_WINSCALE) { 897 tp->t_flags |= TF_REQ_SCALE|TF_RCVD_SCALE; 898 tp->snd_scale = sc->sc_requested_s_scale; 899 tp->request_r_scale = sc->sc_requested_r_scale; 900 } 901 if (sc->sc_flags & SCF_TIMESTAMP) { 902 tp->t_flags |= TF_REQ_TSTMP|TF_RCVD_TSTMP; 903 tp->ts_recent = sc->sc_tsreflect; 904 tp->ts_recent_age = tcp_ts_getticks(); 905 tp->ts_offset = sc->sc_tsoff; 906 } 907 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE) 908 if (sc->sc_flags & SCF_SIGNATURE) 909 tp->t_flags |= TF_SIGNATURE; 910 #endif 911 if (sc->sc_flags & SCF_SACK) 912 tp->t_flags |= TF_SACK_PERMIT; 913 } 914 915 if (sc->sc_flags & SCF_ECN) 916 tp->t_flags |= TF_ECN_PERMIT; 917 918 /* 919 * Set up MSS and get cached values from tcp_hostcache. 920 * This might overwrite some of the defaults we just set. 921 */ 922 tcp_mss(tp, sc->sc_peer_mss); 923 924 /* 925 * If the SYN,ACK was retransmitted, indicate that CWND to be 926 * limited to one segment in cc_conn_init(). 927 * NB: sc_rxmits counts all SYN,ACK transmits, not just retransmits. 928 */ 929 if (sc->sc_rxmits > 1) 930 tp->snd_cwnd = 1; 931 932 #ifdef TCP_OFFLOAD 933 /* 934 * Allow a TOE driver to install its hooks. Note that we hold the 935 * pcbinfo lock too and that prevents tcp_usr_accept from accepting a 936 * new connection before the TOE driver has done its thing. 937 */ 938 if (ADDED_BY_TOE(sc)) { 939 struct toedev *tod = sc->sc_tod; 940 941 tod->tod_offload_socket(tod, sc->sc_todctx, so); 942 } 943 #endif 944 /* 945 * Copy and activate timers. 946 */ 947 tp->t_keepinit = sototcpcb(lso)->t_keepinit; 948 tp->t_keepidle = sototcpcb(lso)->t_keepidle; 949 tp->t_keepintvl = sototcpcb(lso)->t_keepintvl; 950 tp->t_keepcnt = sototcpcb(lso)->t_keepcnt; 951 tcp_timer_activate(tp, TT_KEEP, TP_KEEPINIT(tp)); 952 953 TCPSTAT_INC(tcps_accepts); 954 return (so); 955 956 abort: 957 INP_WUNLOCK(inp); 958 abort2: 959 if (so != NULL) 960 soabort(so); 961 return (NULL); 962 } 963 964 /* 965 * This function gets called when we receive an ACK for a 966 * socket in the LISTEN state. We look up the connection 967 * in the syncache, and if its there, we pull it out of 968 * the cache and turn it into a full-blown connection in 969 * the SYN-RECEIVED state. 970 * 971 * On syncache_socket() success the newly created socket 972 * has its underlying inp locked. 973 */ 974 int 975 syncache_expand(struct in_conninfo *inc, struct tcpopt *to, struct tcphdr *th, 976 struct socket **lsop, struct mbuf *m) 977 { 978 struct syncache *sc; 979 struct syncache_head *sch; 980 struct syncache scs; 981 char *s; 982 983 /* 984 * Global TCP locks are held because we manipulate the PCB lists 985 * and create a new socket. 986 */ 987 INP_INFO_RLOCK_ASSERT(&V_tcbinfo); 988 KASSERT((th->th_flags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK, 989 ("%s: can handle only ACK", __func__)); 990 991 sc = syncache_lookup(inc, &sch); /* returns locked sch */ 992 SCH_LOCK_ASSERT(sch); 993 994 #ifdef INVARIANTS 995 /* 996 * Test code for syncookies comparing the syncache stored 997 * values with the reconstructed values from the cookie. 998 */ 999 if (sc != NULL) 1000 syncookie_cmp(inc, sch, sc, th, to, *lsop); 1001 #endif 1002 1003 if (sc == NULL) { 1004 /* 1005 * There is no syncache entry, so see if this ACK is 1006 * a returning syncookie. To do this, first: 1007 * A. Check if syncookies are used in case of syncache 1008 * overflows 1009 * B. See if this socket has had a syncache entry dropped in 1010 * the recent past. We don't want to accept a bogus 1011 * syncookie if we've never received a SYN or accept it 1012 * twice. 1013 * C. check that the syncookie is valid. If it is, then 1014 * cobble up a fake syncache entry, and return. 1015 */ 1016 if (!V_tcp_syncookies) { 1017 SCH_UNLOCK(sch); 1018 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) 1019 log(LOG_DEBUG, "%s; %s: Spurious ACK, " 1020 "segment rejected (syncookies disabled)\n", 1021 s, __func__); 1022 goto failed; 1023 } 1024 if (!V_tcp_syncookiesonly && 1025 sch->sch_last_overflow < time_uptime - SYNCOOKIE_LIFETIME) { 1026 SCH_UNLOCK(sch); 1027 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) 1028 log(LOG_DEBUG, "%s; %s: Spurious ACK, " 1029 "segment rejected (no syncache entry)\n", 1030 s, __func__); 1031 goto failed; 1032 } 1033 bzero(&scs, sizeof(scs)); 1034 sc = syncookie_lookup(inc, sch, &scs, th, to, *lsop); 1035 SCH_UNLOCK(sch); 1036 if (sc == NULL) { 1037 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) 1038 log(LOG_DEBUG, "%s; %s: Segment failed " 1039 "SYNCOOKIE authentication, segment rejected " 1040 "(probably spoofed)\n", s, __func__); 1041 goto failed; 1042 } 1043 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE) 1044 /* If received ACK has MD5 signature, check it. */ 1045 if ((to->to_flags & TOF_SIGNATURE) != 0 && 1046 (!TCPMD5_ENABLED() || 1047 TCPMD5_INPUT(m, th, to->to_signature) != 0)) { 1048 /* Drop the ACK. */ 1049 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) { 1050 log(LOG_DEBUG, "%s; %s: Segment rejected, " 1051 "MD5 signature doesn't match.\n", 1052 s, __func__); 1053 free(s, M_TCPLOG); 1054 } 1055 TCPSTAT_INC(tcps_sig_err_sigopt); 1056 return (-1); /* Do not send RST */ 1057 } 1058 #endif /* TCP_SIGNATURE */ 1059 } else { 1060 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE) 1061 /* 1062 * If listening socket requested TCP digests, check that 1063 * received ACK has signature and it is correct. 1064 * If not, drop the ACK and leave sc entry in th cache, 1065 * because SYN was received with correct signature. 1066 */ 1067 if (sc->sc_flags & SCF_SIGNATURE) { 1068 if ((to->to_flags & TOF_SIGNATURE) == 0) { 1069 /* No signature */ 1070 TCPSTAT_INC(tcps_sig_err_nosigopt); 1071 SCH_UNLOCK(sch); 1072 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) { 1073 log(LOG_DEBUG, "%s; %s: Segment " 1074 "rejected, MD5 signature wasn't " 1075 "provided.\n", s, __func__); 1076 free(s, M_TCPLOG); 1077 } 1078 return (-1); /* Do not send RST */ 1079 } 1080 if (!TCPMD5_ENABLED() || 1081 TCPMD5_INPUT(m, th, to->to_signature) != 0) { 1082 /* Doesn't match or no SA */ 1083 SCH_UNLOCK(sch); 1084 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) { 1085 log(LOG_DEBUG, "%s; %s: Segment " 1086 "rejected, MD5 signature doesn't " 1087 "match.\n", s, __func__); 1088 free(s, M_TCPLOG); 1089 } 1090 return (-1); /* Do not send RST */ 1091 } 1092 } 1093 #endif /* TCP_SIGNATURE */ 1094 /* 1095 * Pull out the entry to unlock the bucket row. 1096 * 1097 * NOTE: We must decrease TCPS_SYN_RECEIVED count here, not 1098 * tcp_state_change(). The tcpcb is not existent at this 1099 * moment. A new one will be allocated via syncache_socket-> 1100 * sonewconn->tcp_usr_attach in TCPS_CLOSED state, then 1101 * syncache_socket() will change it to TCPS_SYN_RECEIVED. 1102 */ 1103 TCPSTATES_DEC(TCPS_SYN_RECEIVED); 1104 TAILQ_REMOVE(&sch->sch_bucket, sc, sc_hash); 1105 sch->sch_length--; 1106 #ifdef TCP_OFFLOAD 1107 if (ADDED_BY_TOE(sc)) { 1108 struct toedev *tod = sc->sc_tod; 1109 1110 tod->tod_syncache_removed(tod, sc->sc_todctx); 1111 } 1112 #endif 1113 SCH_UNLOCK(sch); 1114 } 1115 1116 /* 1117 * Segment validation: 1118 * ACK must match our initial sequence number + 1 (the SYN|ACK). 1119 */ 1120 if (th->th_ack != sc->sc_iss + 1) { 1121 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) 1122 log(LOG_DEBUG, "%s; %s: ACK %u != ISS+1 %u, segment " 1123 "rejected\n", s, __func__, th->th_ack, sc->sc_iss); 1124 goto failed; 1125 } 1126 1127 /* 1128 * The SEQ must fall in the window starting at the received 1129 * initial receive sequence number + 1 (the SYN). 1130 */ 1131 if (SEQ_LEQ(th->th_seq, sc->sc_irs) || 1132 SEQ_GT(th->th_seq, sc->sc_irs + sc->sc_wnd)) { 1133 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) 1134 log(LOG_DEBUG, "%s; %s: SEQ %u != IRS+1 %u, segment " 1135 "rejected\n", s, __func__, th->th_seq, sc->sc_irs); 1136 goto failed; 1137 } 1138 1139 /* 1140 * If timestamps were not negotiated during SYN/ACK they 1141 * must not appear on any segment during this session. 1142 */ 1143 if (!(sc->sc_flags & SCF_TIMESTAMP) && (to->to_flags & TOF_TS)) { 1144 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) 1145 log(LOG_DEBUG, "%s; %s: Timestamp not expected, " 1146 "segment rejected\n", s, __func__); 1147 goto failed; 1148 } 1149 1150 /* 1151 * If timestamps were negotiated during SYN/ACK they should 1152 * appear on every segment during this session. 1153 * XXXAO: This is only informal as there have been unverified 1154 * reports of non-compliants stacks. 1155 */ 1156 if ((sc->sc_flags & SCF_TIMESTAMP) && !(to->to_flags & TOF_TS)) { 1157 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) { 1158 log(LOG_DEBUG, "%s; %s: Timestamp missing, " 1159 "no action\n", s, __func__); 1160 free(s, M_TCPLOG); 1161 s = NULL; 1162 } 1163 } 1164 1165 /* 1166 * If timestamps were negotiated, the reflected timestamp 1167 * must be equal to what we actually sent in the SYN|ACK 1168 * except in the case of 0. Some boxes are known for sending 1169 * broken timestamp replies during the 3whs (and potentially 1170 * during the connection also). 1171 * 1172 * Accept the final ACK of 3whs with reflected timestamp of 0 1173 * instead of sending a RST and deleting the syncache entry. 1174 */ 1175 if ((to->to_flags & TOF_TS) && to->to_tsecr && 1176 to->to_tsecr != sc->sc_ts) { 1177 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) 1178 log(LOG_DEBUG, "%s; %s: TSECR %u != TS %u, " 1179 "segment rejected\n", 1180 s, __func__, to->to_tsecr, sc->sc_ts); 1181 goto failed; 1182 } 1183 1184 *lsop = syncache_socket(sc, *lsop, m); 1185 1186 if (*lsop == NULL) 1187 TCPSTAT_INC(tcps_sc_aborted); 1188 else 1189 TCPSTAT_INC(tcps_sc_completed); 1190 1191 /* how do we find the inp for the new socket? */ 1192 if (sc != &scs) 1193 syncache_free(sc); 1194 return (1); 1195 failed: 1196 if (sc != NULL && sc != &scs) 1197 syncache_free(sc); 1198 if (s != NULL) 1199 free(s, M_TCPLOG); 1200 *lsop = NULL; 1201 return (0); 1202 } 1203 1204 static void 1205 syncache_tfo_expand(struct syncache *sc, struct socket **lsop, struct mbuf *m, 1206 uint64_t response_cookie) 1207 { 1208 struct inpcb *inp; 1209 struct tcpcb *tp; 1210 unsigned int *pending_counter; 1211 1212 /* 1213 * Global TCP locks are held because we manipulate the PCB lists 1214 * and create a new socket. 1215 */ 1216 INP_INFO_RLOCK_ASSERT(&V_tcbinfo); 1217 1218 pending_counter = intotcpcb(sotoinpcb(*lsop))->t_tfo_pending; 1219 *lsop = syncache_socket(sc, *lsop, m); 1220 if (*lsop == NULL) { 1221 TCPSTAT_INC(tcps_sc_aborted); 1222 atomic_subtract_int(pending_counter, 1); 1223 } else { 1224 soisconnected(*lsop); 1225 inp = sotoinpcb(*lsop); 1226 tp = intotcpcb(inp); 1227 tp->t_flags |= TF_FASTOPEN; 1228 tp->t_tfo_cookie.server = response_cookie; 1229 tp->snd_max = tp->iss; 1230 tp->snd_nxt = tp->iss; 1231 tp->t_tfo_pending = pending_counter; 1232 TCPSTAT_INC(tcps_sc_completed); 1233 } 1234 } 1235 1236 /* 1237 * Given a LISTEN socket and an inbound SYN request, add 1238 * this to the syn cache, and send back a segment: 1239 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK> 1240 * to the source. 1241 * 1242 * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN. 1243 * Doing so would require that we hold onto the data and deliver it 1244 * to the application. However, if we are the target of a SYN-flood 1245 * DoS attack, an attacker could send data which would eventually 1246 * consume all available buffer space if it were ACKed. By not ACKing 1247 * the data, we avoid this DoS scenario. 1248 * 1249 * The exception to the above is when a SYN with a valid TCP Fast Open (TFO) 1250 * cookie is processed and a new socket is created. In this case, any data 1251 * accompanying the SYN will be queued to the socket by tcp_input() and will 1252 * be ACKed either when the application sends response data or the delayed 1253 * ACK timer expires, whichever comes first. 1254 */ 1255 int 1256 syncache_add(struct in_conninfo *inc, struct tcpopt *to, struct tcphdr *th, 1257 struct inpcb *inp, struct socket **lsop, struct mbuf *m, void *tod, 1258 void *todctx) 1259 { 1260 struct tcpcb *tp; 1261 struct socket *so; 1262 struct syncache *sc = NULL; 1263 struct syncache_head *sch; 1264 struct mbuf *ipopts = NULL; 1265 u_int ltflags; 1266 int win, ip_ttl, ip_tos; 1267 char *s; 1268 int rv = 0; 1269 #ifdef INET6 1270 int autoflowlabel = 0; 1271 #endif 1272 #ifdef MAC 1273 struct label *maclabel; 1274 #endif 1275 struct syncache scs; 1276 struct ucred *cred; 1277 uint64_t tfo_response_cookie; 1278 unsigned int *tfo_pending = NULL; 1279 int tfo_cookie_valid = 0; 1280 int tfo_response_cookie_valid = 0; 1281 1282 INP_WLOCK_ASSERT(inp); /* listen socket */ 1283 KASSERT((th->th_flags & (TH_RST|TH_ACK|TH_SYN)) == TH_SYN, 1284 ("%s: unexpected tcp flags", __func__)); 1285 1286 /* 1287 * Combine all so/tp operations very early to drop the INP lock as 1288 * soon as possible. 1289 */ 1290 so = *lsop; 1291 KASSERT(SOLISTENING(so), ("%s: %p not listening", __func__, so)); 1292 tp = sototcpcb(so); 1293 cred = crhold(so->so_cred); 1294 1295 #ifdef INET6 1296 if ((inc->inc_flags & INC_ISIPV6) && 1297 (inp->inp_flags & IN6P_AUTOFLOWLABEL)) 1298 autoflowlabel = 1; 1299 #endif 1300 ip_ttl = inp->inp_ip_ttl; 1301 ip_tos = inp->inp_ip_tos; 1302 win = so->sol_sbrcv_hiwat; 1303 ltflags = (tp->t_flags & (TF_NOOPT | TF_SIGNATURE)); 1304 1305 if (V_tcp_fastopen_server_enable && IS_FASTOPEN(tp->t_flags) && 1306 (tp->t_tfo_pending != NULL) && 1307 (to->to_flags & TOF_FASTOPEN)) { 1308 /* 1309 * Limit the number of pending TFO connections to 1310 * approximately half of the queue limit. This prevents TFO 1311 * SYN floods from starving the service by filling the 1312 * listen queue with bogus TFO connections. 1313 */ 1314 if (atomic_fetchadd_int(tp->t_tfo_pending, 1) <= 1315 (so->sol_qlimit / 2)) { 1316 int result; 1317 1318 result = tcp_fastopen_check_cookie(inc, 1319 to->to_tfo_cookie, to->to_tfo_len, 1320 &tfo_response_cookie); 1321 tfo_cookie_valid = (result > 0); 1322 tfo_response_cookie_valid = (result >= 0); 1323 } 1324 1325 /* 1326 * Remember the TFO pending counter as it will have to be 1327 * decremented below if we don't make it to syncache_tfo_expand(). 1328 */ 1329 tfo_pending = tp->t_tfo_pending; 1330 } 1331 1332 /* By the time we drop the lock these should no longer be used. */ 1333 so = NULL; 1334 tp = NULL; 1335 1336 #ifdef MAC 1337 if (mac_syncache_init(&maclabel) != 0) { 1338 INP_WUNLOCK(inp); 1339 goto done; 1340 } else 1341 mac_syncache_create(maclabel, inp); 1342 #endif 1343 if (!tfo_cookie_valid) 1344 INP_WUNLOCK(inp); 1345 1346 /* 1347 * Remember the IP options, if any. 1348 */ 1349 #ifdef INET6 1350 if (!(inc->inc_flags & INC_ISIPV6)) 1351 #endif 1352 #ifdef INET 1353 ipopts = (m) ? ip_srcroute(m) : NULL; 1354 #else 1355 ipopts = NULL; 1356 #endif 1357 1358 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE) 1359 /* 1360 * If listening socket requested TCP digests, check that received 1361 * SYN has signature and it is correct. If signature doesn't match 1362 * or TCP_SIGNATURE support isn't enabled, drop the packet. 1363 */ 1364 if (ltflags & TF_SIGNATURE) { 1365 if ((to->to_flags & TOF_SIGNATURE) == 0) { 1366 TCPSTAT_INC(tcps_sig_err_nosigopt); 1367 goto done; 1368 } 1369 if (!TCPMD5_ENABLED() || 1370 TCPMD5_INPUT(m, th, to->to_signature) != 0) 1371 goto done; 1372 } 1373 #endif /* TCP_SIGNATURE */ 1374 /* 1375 * See if we already have an entry for this connection. 1376 * If we do, resend the SYN,ACK, and reset the retransmit timer. 1377 * 1378 * XXX: should the syncache be re-initialized with the contents 1379 * of the new SYN here (which may have different options?) 1380 * 1381 * XXX: We do not check the sequence number to see if this is a 1382 * real retransmit or a new connection attempt. The question is 1383 * how to handle such a case; either ignore it as spoofed, or 1384 * drop the current entry and create a new one? 1385 */ 1386 sc = syncache_lookup(inc, &sch); /* returns locked entry */ 1387 SCH_LOCK_ASSERT(sch); 1388 if (sc != NULL) { 1389 if (tfo_cookie_valid) 1390 INP_WUNLOCK(inp); 1391 TCPSTAT_INC(tcps_sc_dupsyn); 1392 if (ipopts) { 1393 /* 1394 * If we were remembering a previous source route, 1395 * forget it and use the new one we've been given. 1396 */ 1397 if (sc->sc_ipopts) 1398 (void) m_free(sc->sc_ipopts); 1399 sc->sc_ipopts = ipopts; 1400 } 1401 /* 1402 * Update timestamp if present. 1403 */ 1404 if ((sc->sc_flags & SCF_TIMESTAMP) && (to->to_flags & TOF_TS)) 1405 sc->sc_tsreflect = to->to_tsval; 1406 else 1407 sc->sc_flags &= ~SCF_TIMESTAMP; 1408 #ifdef MAC 1409 /* 1410 * Since we have already unconditionally allocated label 1411 * storage, free it up. The syncache entry will already 1412 * have an initialized label we can use. 1413 */ 1414 mac_syncache_destroy(&maclabel); 1415 #endif 1416 /* Retransmit SYN|ACK and reset retransmit count. */ 1417 if ((s = tcp_log_addrs(&sc->sc_inc, th, NULL, NULL))) { 1418 log(LOG_DEBUG, "%s; %s: Received duplicate SYN, " 1419 "resetting timer and retransmitting SYN|ACK\n", 1420 s, __func__); 1421 free(s, M_TCPLOG); 1422 } 1423 if (syncache_respond(sc, sch, 1, m) == 0) { 1424 sc->sc_rxmits = 0; 1425 syncache_timeout(sc, sch, 1); 1426 TCPSTAT_INC(tcps_sndacks); 1427 TCPSTAT_INC(tcps_sndtotal); 1428 } 1429 SCH_UNLOCK(sch); 1430 goto done; 1431 } 1432 1433 if (tfo_cookie_valid) { 1434 bzero(&scs, sizeof(scs)); 1435 sc = &scs; 1436 goto skip_alloc; 1437 } 1438 1439 sc = uma_zalloc(V_tcp_syncache.zone, M_NOWAIT | M_ZERO); 1440 if (sc == NULL) { 1441 /* 1442 * The zone allocator couldn't provide more entries. 1443 * Treat this as if the cache was full; drop the oldest 1444 * entry and insert the new one. 1445 */ 1446 TCPSTAT_INC(tcps_sc_zonefail); 1447 if ((sc = TAILQ_LAST(&sch->sch_bucket, sch_head)) != NULL) { 1448 sch->sch_last_overflow = time_uptime; 1449 syncache_drop(sc, sch); 1450 } 1451 sc = uma_zalloc(V_tcp_syncache.zone, M_NOWAIT | M_ZERO); 1452 if (sc == NULL) { 1453 if (V_tcp_syncookies) { 1454 bzero(&scs, sizeof(scs)); 1455 sc = &scs; 1456 } else { 1457 SCH_UNLOCK(sch); 1458 if (ipopts) 1459 (void) m_free(ipopts); 1460 goto done; 1461 } 1462 } 1463 } 1464 1465 skip_alloc: 1466 if (!tfo_cookie_valid && tfo_response_cookie_valid) 1467 sc->sc_tfo_cookie = &tfo_response_cookie; 1468 1469 /* 1470 * Fill in the syncache values. 1471 */ 1472 #ifdef MAC 1473 sc->sc_label = maclabel; 1474 #endif 1475 sc->sc_cred = cred; 1476 cred = NULL; 1477 sc->sc_ipopts = ipopts; 1478 bcopy(inc, &sc->sc_inc, sizeof(struct in_conninfo)); 1479 #ifdef INET6 1480 if (!(inc->inc_flags & INC_ISIPV6)) 1481 #endif 1482 { 1483 sc->sc_ip_tos = ip_tos; 1484 sc->sc_ip_ttl = ip_ttl; 1485 } 1486 #ifdef TCP_OFFLOAD 1487 sc->sc_tod = tod; 1488 sc->sc_todctx = todctx; 1489 #endif 1490 sc->sc_irs = th->th_seq; 1491 sc->sc_iss = arc4random(); 1492 sc->sc_flags = 0; 1493 sc->sc_flowlabel = 0; 1494 1495 /* 1496 * Initial receive window: clip sbspace to [0 .. TCP_MAXWIN]. 1497 * win was derived from socket earlier in the function. 1498 */ 1499 win = imax(win, 0); 1500 win = imin(win, TCP_MAXWIN); 1501 sc->sc_wnd = win; 1502 1503 if (V_tcp_do_rfc1323) { 1504 /* 1505 * A timestamp received in a SYN makes 1506 * it ok to send timestamp requests and replies. 1507 */ 1508 if (to->to_flags & TOF_TS) { 1509 sc->sc_tsreflect = to->to_tsval; 1510 sc->sc_ts = tcp_ts_getticks(); 1511 sc->sc_flags |= SCF_TIMESTAMP; 1512 } 1513 if (to->to_flags & TOF_SCALE) { 1514 int wscale = 0; 1515 1516 /* 1517 * Pick the smallest possible scaling factor that 1518 * will still allow us to scale up to sb_max, aka 1519 * kern.ipc.maxsockbuf. 1520 * 1521 * We do this because there are broken firewalls that 1522 * will corrupt the window scale option, leading to 1523 * the other endpoint believing that our advertised 1524 * window is unscaled. At scale factors larger than 1525 * 5 the unscaled window will drop below 1500 bytes, 1526 * leading to serious problems when traversing these 1527 * broken firewalls. 1528 * 1529 * With the default maxsockbuf of 256K, a scale factor 1530 * of 3 will be chosen by this algorithm. Those who 1531 * choose a larger maxsockbuf should watch out 1532 * for the compatibility problems mentioned above. 1533 * 1534 * RFC1323: The Window field in a SYN (i.e., a <SYN> 1535 * or <SYN,ACK>) segment itself is never scaled. 1536 */ 1537 while (wscale < TCP_MAX_WINSHIFT && 1538 (TCP_MAXWIN << wscale) < sb_max) 1539 wscale++; 1540 sc->sc_requested_r_scale = wscale; 1541 sc->sc_requested_s_scale = to->to_wscale; 1542 sc->sc_flags |= SCF_WINSCALE; 1543 } 1544 } 1545 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE) 1546 /* 1547 * If listening socket requested TCP digests, flag this in the 1548 * syncache so that syncache_respond() will do the right thing 1549 * with the SYN+ACK. 1550 */ 1551 if (ltflags & TF_SIGNATURE) 1552 sc->sc_flags |= SCF_SIGNATURE; 1553 #endif /* TCP_SIGNATURE */ 1554 if (to->to_flags & TOF_SACKPERM) 1555 sc->sc_flags |= SCF_SACK; 1556 if (to->to_flags & TOF_MSS) 1557 sc->sc_peer_mss = to->to_mss; /* peer mss may be zero */ 1558 if (ltflags & TF_NOOPT) 1559 sc->sc_flags |= SCF_NOOPT; 1560 if ((th->th_flags & (TH_ECE|TH_CWR)) && V_tcp_do_ecn) 1561 sc->sc_flags |= SCF_ECN; 1562 1563 if (V_tcp_syncookies) 1564 sc->sc_iss = syncookie_generate(sch, sc); 1565 #ifdef INET6 1566 if (autoflowlabel) { 1567 if (V_tcp_syncookies) 1568 sc->sc_flowlabel = sc->sc_iss; 1569 else 1570 sc->sc_flowlabel = ip6_randomflowlabel(); 1571 sc->sc_flowlabel = htonl(sc->sc_flowlabel) & IPV6_FLOWLABEL_MASK; 1572 } 1573 #endif 1574 SCH_UNLOCK(sch); 1575 1576 if (tfo_cookie_valid) { 1577 syncache_tfo_expand(sc, lsop, m, tfo_response_cookie); 1578 /* INP_WUNLOCK(inp) will be performed by the caller */ 1579 rv = 1; 1580 goto tfo_expanded; 1581 } 1582 1583 /* 1584 * Do a standard 3-way handshake. 1585 */ 1586 if (syncache_respond(sc, sch, 0, m) == 0) { 1587 if (V_tcp_syncookies && V_tcp_syncookiesonly && sc != &scs) 1588 syncache_free(sc); 1589 else if (sc != &scs) 1590 syncache_insert(sc, sch); /* locks and unlocks sch */ 1591 TCPSTAT_INC(tcps_sndacks); 1592 TCPSTAT_INC(tcps_sndtotal); 1593 } else { 1594 if (sc != &scs) 1595 syncache_free(sc); 1596 TCPSTAT_INC(tcps_sc_dropped); 1597 } 1598 1599 done: 1600 if (m) { 1601 *lsop = NULL; 1602 m_freem(m); 1603 } 1604 /* 1605 * If tfo_pending is not NULL here, then a TFO SYN that did not 1606 * result in a new socket was processed and the associated pending 1607 * counter has not yet been decremented. All such TFO processing paths 1608 * transit this point. 1609 */ 1610 if (tfo_pending != NULL) 1611 tcp_fastopen_decrement_counter(tfo_pending); 1612 1613 tfo_expanded: 1614 if (cred != NULL) 1615 crfree(cred); 1616 #ifdef MAC 1617 if (sc == &scs) 1618 mac_syncache_destroy(&maclabel); 1619 #endif 1620 return (rv); 1621 } 1622 1623 /* 1624 * Send SYN|ACK to the peer. Either in response to the peer's SYN, 1625 * i.e. m0 != NULL, or upon 3WHS ACK timeout, i.e. m0 == NULL. 1626 */ 1627 static int 1628 syncache_respond(struct syncache *sc, struct syncache_head *sch, int locked, 1629 const struct mbuf *m0) 1630 { 1631 struct ip *ip = NULL; 1632 struct mbuf *m; 1633 struct tcphdr *th = NULL; 1634 int optlen, error = 0; /* Make compiler happy */ 1635 u_int16_t hlen, tlen, mssopt; 1636 struct tcpopt to; 1637 #ifdef INET6 1638 struct ip6_hdr *ip6 = NULL; 1639 #endif 1640 hlen = 1641 #ifdef INET6 1642 (sc->sc_inc.inc_flags & INC_ISIPV6) ? sizeof(struct ip6_hdr) : 1643 #endif 1644 sizeof(struct ip); 1645 tlen = hlen + sizeof(struct tcphdr); 1646 1647 /* Determine MSS we advertize to other end of connection. */ 1648 mssopt = max(tcp_mssopt(&sc->sc_inc), V_tcp_minmss); 1649 1650 /* XXX: Assume that the entire packet will fit in a header mbuf. */ 1651 KASSERT(max_linkhdr + tlen + TCP_MAXOLEN <= MHLEN, 1652 ("syncache: mbuf too small")); 1653 1654 /* Create the IP+TCP header from scratch. */ 1655 m = m_gethdr(M_NOWAIT, MT_DATA); 1656 if (m == NULL) 1657 return (ENOBUFS); 1658 #ifdef MAC 1659 mac_syncache_create_mbuf(sc->sc_label, m); 1660 #endif 1661 m->m_data += max_linkhdr; 1662 m->m_len = tlen; 1663 m->m_pkthdr.len = tlen; 1664 m->m_pkthdr.rcvif = NULL; 1665 1666 #ifdef INET6 1667 if (sc->sc_inc.inc_flags & INC_ISIPV6) { 1668 ip6 = mtod(m, struct ip6_hdr *); 1669 ip6->ip6_vfc = IPV6_VERSION; 1670 ip6->ip6_nxt = IPPROTO_TCP; 1671 ip6->ip6_src = sc->sc_inc.inc6_laddr; 1672 ip6->ip6_dst = sc->sc_inc.inc6_faddr; 1673 ip6->ip6_plen = htons(tlen - hlen); 1674 /* ip6_hlim is set after checksum */ 1675 ip6->ip6_flow &= ~IPV6_FLOWLABEL_MASK; 1676 ip6->ip6_flow |= sc->sc_flowlabel; 1677 1678 th = (struct tcphdr *)(ip6 + 1); 1679 } 1680 #endif 1681 #if defined(INET6) && defined(INET) 1682 else 1683 #endif 1684 #ifdef INET 1685 { 1686 ip = mtod(m, struct ip *); 1687 ip->ip_v = IPVERSION; 1688 ip->ip_hl = sizeof(struct ip) >> 2; 1689 ip->ip_len = htons(tlen); 1690 ip->ip_id = 0; 1691 ip->ip_off = 0; 1692 ip->ip_sum = 0; 1693 ip->ip_p = IPPROTO_TCP; 1694 ip->ip_src = sc->sc_inc.inc_laddr; 1695 ip->ip_dst = sc->sc_inc.inc_faddr; 1696 ip->ip_ttl = sc->sc_ip_ttl; 1697 ip->ip_tos = sc->sc_ip_tos; 1698 1699 /* 1700 * See if we should do MTU discovery. Route lookups are 1701 * expensive, so we will only unset the DF bit if: 1702 * 1703 * 1) path_mtu_discovery is disabled 1704 * 2) the SCF_UNREACH flag has been set 1705 */ 1706 if (V_path_mtu_discovery && ((sc->sc_flags & SCF_UNREACH) == 0)) 1707 ip->ip_off |= htons(IP_DF); 1708 1709 th = (struct tcphdr *)(ip + 1); 1710 } 1711 #endif /* INET */ 1712 th->th_sport = sc->sc_inc.inc_lport; 1713 th->th_dport = sc->sc_inc.inc_fport; 1714 1715 th->th_seq = htonl(sc->sc_iss); 1716 th->th_ack = htonl(sc->sc_irs + 1); 1717 th->th_off = sizeof(struct tcphdr) >> 2; 1718 th->th_x2 = 0; 1719 th->th_flags = TH_SYN|TH_ACK; 1720 th->th_win = htons(sc->sc_wnd); 1721 th->th_urp = 0; 1722 1723 if (sc->sc_flags & SCF_ECN) { 1724 th->th_flags |= TH_ECE; 1725 TCPSTAT_INC(tcps_ecn_shs); 1726 } 1727 1728 /* Tack on the TCP options. */ 1729 if ((sc->sc_flags & SCF_NOOPT) == 0) { 1730 to.to_flags = 0; 1731 1732 to.to_mss = mssopt; 1733 to.to_flags = TOF_MSS; 1734 if (sc->sc_flags & SCF_WINSCALE) { 1735 to.to_wscale = sc->sc_requested_r_scale; 1736 to.to_flags |= TOF_SCALE; 1737 } 1738 if (sc->sc_flags & SCF_TIMESTAMP) { 1739 /* Virgin timestamp or TCP cookie enhanced one. */ 1740 to.to_tsval = sc->sc_ts; 1741 to.to_tsecr = sc->sc_tsreflect; 1742 to.to_flags |= TOF_TS; 1743 } 1744 if (sc->sc_flags & SCF_SACK) 1745 to.to_flags |= TOF_SACKPERM; 1746 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE) 1747 if (sc->sc_flags & SCF_SIGNATURE) 1748 to.to_flags |= TOF_SIGNATURE; 1749 #endif 1750 if (sc->sc_tfo_cookie) { 1751 to.to_flags |= TOF_FASTOPEN; 1752 to.to_tfo_len = TCP_FASTOPEN_COOKIE_LEN; 1753 to.to_tfo_cookie = sc->sc_tfo_cookie; 1754 /* don't send cookie again when retransmitting response */ 1755 sc->sc_tfo_cookie = NULL; 1756 } 1757 optlen = tcp_addoptions(&to, (u_char *)(th + 1)); 1758 1759 /* Adjust headers by option size. */ 1760 th->th_off = (sizeof(struct tcphdr) + optlen) >> 2; 1761 m->m_len += optlen; 1762 m->m_pkthdr.len += optlen; 1763 #ifdef INET6 1764 if (sc->sc_inc.inc_flags & INC_ISIPV6) 1765 ip6->ip6_plen = htons(ntohs(ip6->ip6_plen) + optlen); 1766 else 1767 #endif 1768 ip->ip_len = htons(ntohs(ip->ip_len) + optlen); 1769 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE) 1770 if (sc->sc_flags & SCF_SIGNATURE) { 1771 KASSERT(to.to_flags & TOF_SIGNATURE, 1772 ("tcp_addoptions() didn't set tcp_signature")); 1773 1774 /* NOTE: to.to_signature is inside of mbuf */ 1775 if (!TCPMD5_ENABLED() || 1776 TCPMD5_OUTPUT(m, th, to.to_signature) != 0) { 1777 m_freem(m); 1778 return (EACCES); 1779 } 1780 } 1781 #endif 1782 } else 1783 optlen = 0; 1784 1785 M_SETFIB(m, sc->sc_inc.inc_fibnum); 1786 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum); 1787 /* 1788 * If we have peer's SYN and it has a flowid, then let's assign it to 1789 * our SYN|ACK. ip6_output() and ip_output() will not assign flowid 1790 * to SYN|ACK due to lack of inp here. 1791 */ 1792 if (m0 != NULL && M_HASHTYPE_GET(m0) != M_HASHTYPE_NONE) { 1793 m->m_pkthdr.flowid = m0->m_pkthdr.flowid; 1794 M_HASHTYPE_SET(m, M_HASHTYPE_GET(m0)); 1795 } 1796 #ifdef INET6 1797 if (sc->sc_inc.inc_flags & INC_ISIPV6) { 1798 m->m_pkthdr.csum_flags = CSUM_TCP_IPV6; 1799 th->th_sum = in6_cksum_pseudo(ip6, tlen + optlen - hlen, 1800 IPPROTO_TCP, 0); 1801 ip6->ip6_hlim = in6_selecthlim(NULL, NULL); 1802 #ifdef TCP_OFFLOAD 1803 if (ADDED_BY_TOE(sc)) { 1804 struct toedev *tod = sc->sc_tod; 1805 1806 error = tod->tod_syncache_respond(tod, sc->sc_todctx, m); 1807 1808 return (error); 1809 } 1810 #endif 1811 error = ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL); 1812 } 1813 #endif 1814 #if defined(INET6) && defined(INET) 1815 else 1816 #endif 1817 #ifdef INET 1818 { 1819 m->m_pkthdr.csum_flags = CSUM_TCP; 1820 th->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr, 1821 htons(tlen + optlen - hlen + IPPROTO_TCP)); 1822 #ifdef TCP_OFFLOAD 1823 if (ADDED_BY_TOE(sc)) { 1824 struct toedev *tod = sc->sc_tod; 1825 1826 error = tod->tod_syncache_respond(tod, sc->sc_todctx, m); 1827 1828 return (error); 1829 } 1830 #endif 1831 error = ip_output(m, sc->sc_ipopts, NULL, 0, NULL, NULL); 1832 } 1833 #endif 1834 return (error); 1835 } 1836 1837 /* 1838 * The purpose of syncookies is to handle spoofed SYN flooding DoS attacks 1839 * that exceed the capacity of the syncache by avoiding the storage of any 1840 * of the SYNs we receive. Syncookies defend against blind SYN flooding 1841 * attacks where the attacker does not have access to our responses. 1842 * 1843 * Syncookies encode and include all necessary information about the 1844 * connection setup within the SYN|ACK that we send back. That way we 1845 * can avoid keeping any local state until the ACK to our SYN|ACK returns 1846 * (if ever). Normally the syncache and syncookies are running in parallel 1847 * with the latter taking over when the former is exhausted. When matching 1848 * syncache entry is found the syncookie is ignored. 1849 * 1850 * The only reliable information persisting the 3WHS is our initial sequence 1851 * number ISS of 32 bits. Syncookies embed a cryptographically sufficient 1852 * strong hash (MAC) value and a few bits of TCP SYN options in the ISS 1853 * of our SYN|ACK. The MAC can be recomputed when the ACK to our SYN|ACK 1854 * returns and signifies a legitimate connection if it matches the ACK. 1855 * 1856 * The available space of 32 bits to store the hash and to encode the SYN 1857 * option information is very tight and we should have at least 24 bits for 1858 * the MAC to keep the number of guesses by blind spoofing reasonably high. 1859 * 1860 * SYN option information we have to encode to fully restore a connection: 1861 * MSS: is imporant to chose an optimal segment size to avoid IP level 1862 * fragmentation along the path. The common MSS values can be encoded 1863 * in a 3-bit table. Uncommon values are captured by the next lower value 1864 * in the table leading to a slight increase in packetization overhead. 1865 * WSCALE: is necessary to allow large windows to be used for high delay- 1866 * bandwidth product links. Not scaling the window when it was initially 1867 * negotiated is bad for performance as lack of scaling further decreases 1868 * the apparent available send window. We only need to encode the WSCALE 1869 * we received from the remote end. Our end can be recalculated at any 1870 * time. The common WSCALE values can be encoded in a 3-bit table. 1871 * Uncommon values are captured by the next lower value in the table 1872 * making us under-estimate the available window size halving our 1873 * theoretically possible maximum throughput for that connection. 1874 * SACK: Greatly assists in packet loss recovery and requires 1 bit. 1875 * TIMESTAMP and SIGNATURE is not encoded because they are permanent options 1876 * that are included in all segments on a connection. We enable them when 1877 * the ACK has them. 1878 * 1879 * Security of syncookies and attack vectors: 1880 * 1881 * The MAC is computed over (faddr||laddr||fport||lport||irs||flags||secmod) 1882 * together with the gloabl secret to make it unique per connection attempt. 1883 * Thus any change of any of those parameters results in a different MAC output 1884 * in an unpredictable way unless a collision is encountered. 24 bits of the 1885 * MAC are embedded into the ISS. 1886 * 1887 * To prevent replay attacks two rotating global secrets are updated with a 1888 * new random value every 15 seconds. The life-time of a syncookie is thus 1889 * 15-30 seconds. 1890 * 1891 * Vector 1: Attacking the secret. This requires finding a weakness in the 1892 * MAC itself or the way it is used here. The attacker can do a chosen plain 1893 * text attack by varying and testing the all parameters under his control. 1894 * The strength depends on the size and randomness of the secret, and the 1895 * cryptographic security of the MAC function. Due to the constant updating 1896 * of the secret the attacker has at most 29.999 seconds to find the secret 1897 * and launch spoofed connections. After that he has to start all over again. 1898 * 1899 * Vector 2: Collision attack on the MAC of a single ACK. With a 24 bit MAC 1900 * size an average of 4,823 attempts are required for a 50% chance of success 1901 * to spoof a single syncookie (birthday collision paradox). However the 1902 * attacker is blind and doesn't know if one of his attempts succeeded unless 1903 * he has a side channel to interfere success from. A single connection setup 1904 * success average of 90% requires 8,790 packets, 99.99% requires 17,578 packets. 1905 * This many attempts are required for each one blind spoofed connection. For 1906 * every additional spoofed connection he has to launch another N attempts. 1907 * Thus for a sustained rate 100 spoofed connections per second approximately 1908 * 1,800,000 packets per second would have to be sent. 1909 * 1910 * NB: The MAC function should be fast so that it doesn't become a CPU 1911 * exhaustion attack vector itself. 1912 * 1913 * References: 1914 * RFC4987 TCP SYN Flooding Attacks and Common Mitigations 1915 * SYN cookies were first proposed by cryptographer Dan J. Bernstein in 1996 1916 * http://cr.yp.to/syncookies.html (overview) 1917 * http://cr.yp.to/syncookies/archive (details) 1918 * 1919 * 1920 * Schematic construction of a syncookie enabled Initial Sequence Number: 1921 * 0 1 2 3 1922 * 12345678901234567890123456789012 1923 * |xxxxxxxxxxxxxxxxxxxxxxxxWWWMMMSP| 1924 * 1925 * x 24 MAC (truncated) 1926 * W 3 Send Window Scale index 1927 * M 3 MSS index 1928 * S 1 SACK permitted 1929 * P 1 Odd/even secret 1930 */ 1931 1932 /* 1933 * Distribution and probability of certain MSS values. Those in between are 1934 * rounded down to the next lower one. 1935 * [An Analysis of TCP Maximum Segment Sizes, S. Alcock and R. Nelson, 2011] 1936 * .2% .3% 5% 7% 7% 20% 15% 45% 1937 */ 1938 static int tcp_sc_msstab[] = { 216, 536, 1200, 1360, 1400, 1440, 1452, 1460 }; 1939 1940 /* 1941 * Distribution and probability of certain WSCALE values. We have to map the 1942 * (send) window scale (shift) option with a range of 0-14 from 4 bits into 3 1943 * bits based on prevalence of certain values. Where we don't have an exact 1944 * match for are rounded down to the next lower one letting us under-estimate 1945 * the true available window. At the moment this would happen only for the 1946 * very uncommon values 3, 5 and those above 8 (more than 16MB socket buffer 1947 * and window size). The absence of the WSCALE option (no scaling in either 1948 * direction) is encoded with index zero. 1949 * [WSCALE values histograms, Allman, 2012] 1950 * X 10 10 35 5 6 14 10% by host 1951 * X 11 4 5 5 18 49 3% by connections 1952 */ 1953 static int tcp_sc_wstab[] = { 0, 0, 1, 2, 4, 6, 7, 8 }; 1954 1955 /* 1956 * Compute the MAC for the SYN cookie. SIPHASH-2-4 is chosen for its speed 1957 * and good cryptographic properties. 1958 */ 1959 static uint32_t 1960 syncookie_mac(struct in_conninfo *inc, tcp_seq irs, uint8_t flags, 1961 uint8_t *secbits, uintptr_t secmod) 1962 { 1963 SIPHASH_CTX ctx; 1964 uint32_t siphash[2]; 1965 1966 SipHash24_Init(&ctx); 1967 SipHash_SetKey(&ctx, secbits); 1968 switch (inc->inc_flags & INC_ISIPV6) { 1969 #ifdef INET 1970 case 0: 1971 SipHash_Update(&ctx, &inc->inc_faddr, sizeof(inc->inc_faddr)); 1972 SipHash_Update(&ctx, &inc->inc_laddr, sizeof(inc->inc_laddr)); 1973 break; 1974 #endif 1975 #ifdef INET6 1976 case INC_ISIPV6: 1977 SipHash_Update(&ctx, &inc->inc6_faddr, sizeof(inc->inc6_faddr)); 1978 SipHash_Update(&ctx, &inc->inc6_laddr, sizeof(inc->inc6_laddr)); 1979 break; 1980 #endif 1981 } 1982 SipHash_Update(&ctx, &inc->inc_fport, sizeof(inc->inc_fport)); 1983 SipHash_Update(&ctx, &inc->inc_lport, sizeof(inc->inc_lport)); 1984 SipHash_Update(&ctx, &irs, sizeof(irs)); 1985 SipHash_Update(&ctx, &flags, sizeof(flags)); 1986 SipHash_Update(&ctx, &secmod, sizeof(secmod)); 1987 SipHash_Final((u_int8_t *)&siphash, &ctx); 1988 1989 return (siphash[0] ^ siphash[1]); 1990 } 1991 1992 static tcp_seq 1993 syncookie_generate(struct syncache_head *sch, struct syncache *sc) 1994 { 1995 u_int i, secbit, wscale; 1996 uint32_t iss, hash; 1997 uint8_t *secbits; 1998 union syncookie cookie; 1999 2000 SCH_LOCK_ASSERT(sch); 2001 2002 cookie.cookie = 0; 2003 2004 /* Map our computed MSS into the 3-bit index. */ 2005 for (i = nitems(tcp_sc_msstab) - 1; 2006 tcp_sc_msstab[i] > sc->sc_peer_mss && i > 0; 2007 i--) 2008 ; 2009 cookie.flags.mss_idx = i; 2010 2011 /* 2012 * Map the send window scale into the 3-bit index but only if 2013 * the wscale option was received. 2014 */ 2015 if (sc->sc_flags & SCF_WINSCALE) { 2016 wscale = sc->sc_requested_s_scale; 2017 for (i = nitems(tcp_sc_wstab) - 1; 2018 tcp_sc_wstab[i] > wscale && i > 0; 2019 i--) 2020 ; 2021 cookie.flags.wscale_idx = i; 2022 } 2023 2024 /* Can we do SACK? */ 2025 if (sc->sc_flags & SCF_SACK) 2026 cookie.flags.sack_ok = 1; 2027 2028 /* Which of the two secrets to use. */ 2029 secbit = sch->sch_sc->secret.oddeven & 0x1; 2030 cookie.flags.odd_even = secbit; 2031 2032 secbits = sch->sch_sc->secret.key[secbit]; 2033 hash = syncookie_mac(&sc->sc_inc, sc->sc_irs, cookie.cookie, secbits, 2034 (uintptr_t)sch); 2035 2036 /* 2037 * Put the flags into the hash and XOR them to get better ISS number 2038 * variance. This doesn't enhance the cryptographic strength and is 2039 * done to prevent the 8 cookie bits from showing up directly on the 2040 * wire. 2041 */ 2042 iss = hash & ~0xff; 2043 iss |= cookie.cookie ^ (hash >> 24); 2044 2045 /* Randomize the timestamp. */ 2046 if (sc->sc_flags & SCF_TIMESTAMP) { 2047 sc->sc_ts = arc4random(); 2048 sc->sc_tsoff = sc->sc_ts - tcp_ts_getticks(); 2049 } 2050 2051 TCPSTAT_INC(tcps_sc_sendcookie); 2052 return (iss); 2053 } 2054 2055 static struct syncache * 2056 syncookie_lookup(struct in_conninfo *inc, struct syncache_head *sch, 2057 struct syncache *sc, struct tcphdr *th, struct tcpopt *to, 2058 struct socket *lso) 2059 { 2060 uint32_t hash; 2061 uint8_t *secbits; 2062 tcp_seq ack, seq; 2063 int wnd, wscale = 0; 2064 union syncookie cookie; 2065 2066 SCH_LOCK_ASSERT(sch); 2067 2068 /* 2069 * Pull information out of SYN-ACK/ACK and revert sequence number 2070 * advances. 2071 */ 2072 ack = th->th_ack - 1; 2073 seq = th->th_seq - 1; 2074 2075 /* 2076 * Unpack the flags containing enough information to restore the 2077 * connection. 2078 */ 2079 cookie.cookie = (ack & 0xff) ^ (ack >> 24); 2080 2081 /* Which of the two secrets to use. */ 2082 secbits = sch->sch_sc->secret.key[cookie.flags.odd_even]; 2083 2084 hash = syncookie_mac(inc, seq, cookie.cookie, secbits, (uintptr_t)sch); 2085 2086 /* The recomputed hash matches the ACK if this was a genuine cookie. */ 2087 if ((ack & ~0xff) != (hash & ~0xff)) 2088 return (NULL); 2089 2090 /* Fill in the syncache values. */ 2091 sc->sc_flags = 0; 2092 bcopy(inc, &sc->sc_inc, sizeof(struct in_conninfo)); 2093 sc->sc_ipopts = NULL; 2094 2095 sc->sc_irs = seq; 2096 sc->sc_iss = ack; 2097 2098 switch (inc->inc_flags & INC_ISIPV6) { 2099 #ifdef INET 2100 case 0: 2101 sc->sc_ip_ttl = sotoinpcb(lso)->inp_ip_ttl; 2102 sc->sc_ip_tos = sotoinpcb(lso)->inp_ip_tos; 2103 break; 2104 #endif 2105 #ifdef INET6 2106 case INC_ISIPV6: 2107 if (sotoinpcb(lso)->inp_flags & IN6P_AUTOFLOWLABEL) 2108 sc->sc_flowlabel = sc->sc_iss & IPV6_FLOWLABEL_MASK; 2109 break; 2110 #endif 2111 } 2112 2113 sc->sc_peer_mss = tcp_sc_msstab[cookie.flags.mss_idx]; 2114 2115 /* We can simply recompute receive window scale we sent earlier. */ 2116 while (wscale < TCP_MAX_WINSHIFT && (TCP_MAXWIN << wscale) < sb_max) 2117 wscale++; 2118 2119 /* Only use wscale if it was enabled in the orignal SYN. */ 2120 if (cookie.flags.wscale_idx > 0) { 2121 sc->sc_requested_r_scale = wscale; 2122 sc->sc_requested_s_scale = tcp_sc_wstab[cookie.flags.wscale_idx]; 2123 sc->sc_flags |= SCF_WINSCALE; 2124 } 2125 2126 wnd = lso->sol_sbrcv_hiwat; 2127 wnd = imax(wnd, 0); 2128 wnd = imin(wnd, TCP_MAXWIN); 2129 sc->sc_wnd = wnd; 2130 2131 if (cookie.flags.sack_ok) 2132 sc->sc_flags |= SCF_SACK; 2133 2134 if (to->to_flags & TOF_TS) { 2135 sc->sc_flags |= SCF_TIMESTAMP; 2136 sc->sc_tsreflect = to->to_tsval; 2137 sc->sc_ts = to->to_tsecr; 2138 sc->sc_tsoff = to->to_tsecr - tcp_ts_getticks(); 2139 } 2140 2141 if (to->to_flags & TOF_SIGNATURE) 2142 sc->sc_flags |= SCF_SIGNATURE; 2143 2144 sc->sc_rxmits = 0; 2145 2146 TCPSTAT_INC(tcps_sc_recvcookie); 2147 return (sc); 2148 } 2149 2150 #ifdef INVARIANTS 2151 static int 2152 syncookie_cmp(struct in_conninfo *inc, struct syncache_head *sch, 2153 struct syncache *sc, struct tcphdr *th, struct tcpopt *to, 2154 struct socket *lso) 2155 { 2156 struct syncache scs, *scx; 2157 char *s; 2158 2159 bzero(&scs, sizeof(scs)); 2160 scx = syncookie_lookup(inc, sch, &scs, th, to, lso); 2161 2162 if ((s = tcp_log_addrs(inc, th, NULL, NULL)) == NULL) 2163 return (0); 2164 2165 if (scx != NULL) { 2166 if (sc->sc_peer_mss != scx->sc_peer_mss) 2167 log(LOG_DEBUG, "%s; %s: mss different %i vs %i\n", 2168 s, __func__, sc->sc_peer_mss, scx->sc_peer_mss); 2169 2170 if (sc->sc_requested_r_scale != scx->sc_requested_r_scale) 2171 log(LOG_DEBUG, "%s; %s: rwscale different %i vs %i\n", 2172 s, __func__, sc->sc_requested_r_scale, 2173 scx->sc_requested_r_scale); 2174 2175 if (sc->sc_requested_s_scale != scx->sc_requested_s_scale) 2176 log(LOG_DEBUG, "%s; %s: swscale different %i vs %i\n", 2177 s, __func__, sc->sc_requested_s_scale, 2178 scx->sc_requested_s_scale); 2179 2180 if ((sc->sc_flags & SCF_SACK) != (scx->sc_flags & SCF_SACK)) 2181 log(LOG_DEBUG, "%s; %s: SACK different\n", s, __func__); 2182 } 2183 2184 if (s != NULL) 2185 free(s, M_TCPLOG); 2186 return (0); 2187 } 2188 #endif /* INVARIANTS */ 2189 2190 static void 2191 syncookie_reseed(void *arg) 2192 { 2193 struct tcp_syncache *sc = arg; 2194 uint8_t *secbits; 2195 int secbit; 2196 2197 /* 2198 * Reseeding the secret doesn't have to be protected by a lock. 2199 * It only must be ensured that the new random values are visible 2200 * to all CPUs in a SMP environment. The atomic with release 2201 * semantics ensures that. 2202 */ 2203 secbit = (sc->secret.oddeven & 0x1) ? 0 : 1; 2204 secbits = sc->secret.key[secbit]; 2205 arc4rand(secbits, SYNCOOKIE_SECRET_SIZE, 0); 2206 atomic_add_rel_int(&sc->secret.oddeven, 1); 2207 2208 /* Reschedule ourself. */ 2209 callout_schedule(&sc->secret.reseed, SYNCOOKIE_LIFETIME * hz); 2210 } 2211 2212 /* 2213 * Exports the syncache entries to userland so that netstat can display 2214 * them alongside the other sockets. This function is intended to be 2215 * called only from tcp_pcblist. 2216 * 2217 * Due to concurrency on an active system, the number of pcbs exported 2218 * may have no relation to max_pcbs. max_pcbs merely indicates the 2219 * amount of space the caller allocated for this function to use. 2220 */ 2221 int 2222 syncache_pcblist(struct sysctl_req *req, int max_pcbs, int *pcbs_exported) 2223 { 2224 struct xtcpcb xt; 2225 struct syncache *sc; 2226 struct syncache_head *sch; 2227 int count, error, i; 2228 2229 for (count = 0, error = 0, i = 0; i < V_tcp_syncache.hashsize; i++) { 2230 sch = &V_tcp_syncache.hashbase[i]; 2231 SCH_LOCK(sch); 2232 TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash) { 2233 if (count >= max_pcbs) { 2234 SCH_UNLOCK(sch); 2235 goto exit; 2236 } 2237 if (cr_cansee(req->td->td_ucred, sc->sc_cred) != 0) 2238 continue; 2239 bzero(&xt, sizeof(xt)); 2240 xt.xt_len = sizeof(xt); 2241 if (sc->sc_inc.inc_flags & INC_ISIPV6) 2242 xt.xt_inp.inp_vflag = INP_IPV6; 2243 else 2244 xt.xt_inp.inp_vflag = INP_IPV4; 2245 bcopy(&sc->sc_inc, &xt.xt_inp.inp_inc, 2246 sizeof (struct in_conninfo)); 2247 xt.t_state = TCPS_SYN_RECEIVED; 2248 xt.xt_inp.xi_socket.xso_protocol = IPPROTO_TCP; 2249 xt.xt_inp.xi_socket.xso_len = sizeof (struct xsocket); 2250 xt.xt_inp.xi_socket.so_type = SOCK_STREAM; 2251 xt.xt_inp.xi_socket.so_state = SS_ISCONNECTING; 2252 error = SYSCTL_OUT(req, &xt, sizeof xt); 2253 if (error) { 2254 SCH_UNLOCK(sch); 2255 goto exit; 2256 } 2257 count++; 2258 } 2259 SCH_UNLOCK(sch); 2260 } 2261 exit: 2262 *pcbs_exported = count; 2263 return error; 2264 } 2265