1 /*- 2 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995 3 * The Regents of the University of California. All rights reserved. 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions 7 * are met: 8 * 1. Redistributions of source code must retain the above copyright 9 * notice, this list of conditions and the following disclaimer. 10 * 2. Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13 * 4. Neither the name of the University nor the names of its contributors 14 * may be used to endorse or promote products derived from this software 15 * without specific prior written permission. 16 * 17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 27 * SUCH DAMAGE. 28 * 29 * @(#)tcp_subr.c 8.2 (Berkeley) 5/24/95 30 */ 31 32 #include <sys/cdefs.h> 33 __FBSDID("$FreeBSD$"); 34 35 #include "opt_compat.h" 36 #include "opt_inet.h" 37 #include "opt_inet6.h" 38 #include "opt_ipsec.h" 39 #include "opt_tcpdebug.h" 40 41 #include <sys/param.h> 42 #include <sys/systm.h> 43 #include <sys/callout.h> 44 #include <sys/kernel.h> 45 #include <sys/sysctl.h> 46 #include <sys/jail.h> 47 #include <sys/malloc.h> 48 #include <sys/mbuf.h> 49 #ifdef INET6 50 #include <sys/domain.h> 51 #endif 52 #include <sys/priv.h> 53 #include <sys/proc.h> 54 #include <sys/socket.h> 55 #include <sys/socketvar.h> 56 #include <sys/protosw.h> 57 #include <sys/random.h> 58 59 #include <vm/uma.h> 60 61 #include <net/route.h> 62 #include <net/if.h> 63 #include <net/vnet.h> 64 65 #include <netinet/cc.h> 66 #include <netinet/in.h> 67 #include <netinet/in_systm.h> 68 #include <netinet/ip.h> 69 #ifdef INET6 70 #include <netinet/ip6.h> 71 #endif 72 #include <netinet/in_pcb.h> 73 #ifdef INET6 74 #include <netinet6/in6_pcb.h> 75 #endif 76 #include <netinet/in_var.h> 77 #include <netinet/ip_var.h> 78 #ifdef INET6 79 #include <netinet6/ip6_var.h> 80 #include <netinet6/scope6_var.h> 81 #include <netinet6/nd6.h> 82 #endif 83 #include <netinet/ip_icmp.h> 84 #include <netinet/tcp_fsm.h> 85 #include <netinet/tcp_seq.h> 86 #include <netinet/tcp_timer.h> 87 #include <netinet/tcp_var.h> 88 #include <netinet/tcp_syncache.h> 89 #include <netinet/tcp_offload.h> 90 #ifdef INET6 91 #include <netinet6/tcp6_var.h> 92 #endif 93 #include <netinet/tcpip.h> 94 #ifdef TCPDEBUG 95 #include <netinet/tcp_debug.h> 96 #endif 97 #include <netinet6/ip6protosw.h> 98 99 #ifdef IPSEC 100 #include <netipsec/ipsec.h> 101 #include <netipsec/xform.h> 102 #ifdef INET6 103 #include <netipsec/ipsec6.h> 104 #endif 105 #include <netipsec/key.h> 106 #include <sys/syslog.h> 107 #endif /*IPSEC*/ 108 109 #include <machine/in_cksum.h> 110 #include <sys/md5.h> 111 112 #include <security/mac/mac_framework.h> 113 114 VNET_DEFINE(int, tcp_mssdflt) = TCP_MSS; 115 #ifdef INET6 116 VNET_DEFINE(int, tcp_v6mssdflt) = TCP6_MSS; 117 #endif 118 119 static int 120 sysctl_net_inet_tcp_mss_check(SYSCTL_HANDLER_ARGS) 121 { 122 int error, new; 123 124 new = V_tcp_mssdflt; 125 error = sysctl_handle_int(oidp, &new, 0, req); 126 if (error == 0 && req->newptr) { 127 if (new < TCP_MINMSS) 128 error = EINVAL; 129 else 130 V_tcp_mssdflt = new; 131 } 132 return (error); 133 } 134 135 SYSCTL_VNET_PROC(_net_inet_tcp, TCPCTL_MSSDFLT, mssdflt, 136 CTLTYPE_INT|CTLFLAG_RW, &VNET_NAME(tcp_mssdflt), 0, 137 &sysctl_net_inet_tcp_mss_check, "I", 138 "Default TCP Maximum Segment Size"); 139 140 #ifdef INET6 141 static int 142 sysctl_net_inet_tcp_mss_v6_check(SYSCTL_HANDLER_ARGS) 143 { 144 int error, new; 145 146 new = V_tcp_v6mssdflt; 147 error = sysctl_handle_int(oidp, &new, 0, req); 148 if (error == 0 && req->newptr) { 149 if (new < TCP_MINMSS) 150 error = EINVAL; 151 else 152 V_tcp_v6mssdflt = new; 153 } 154 return (error); 155 } 156 157 SYSCTL_VNET_PROC(_net_inet_tcp, TCPCTL_V6MSSDFLT, v6mssdflt, 158 CTLTYPE_INT|CTLFLAG_RW, &VNET_NAME(tcp_v6mssdflt), 0, 159 &sysctl_net_inet_tcp_mss_v6_check, "I", 160 "Default TCP Maximum Segment Size for IPv6"); 161 #endif 162 163 /* 164 * Minimum MSS we accept and use. This prevents DoS attacks where 165 * we are forced to a ridiculous low MSS like 20 and send hundreds 166 * of packets instead of one. The effect scales with the available 167 * bandwidth and quickly saturates the CPU and network interface 168 * with packet generation and sending. Set to zero to disable MINMSS 169 * checking. This setting prevents us from sending too small packets. 170 */ 171 VNET_DEFINE(int, tcp_minmss) = TCP_MINMSS; 172 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, minmss, CTLFLAG_RW, 173 &VNET_NAME(tcp_minmss), 0, 174 "Minmum TCP Maximum Segment Size"); 175 176 VNET_DEFINE(int, tcp_do_rfc1323) = 1; 177 SYSCTL_VNET_INT(_net_inet_tcp, TCPCTL_DO_RFC1323, rfc1323, CTLFLAG_RW, 178 &VNET_NAME(tcp_do_rfc1323), 0, 179 "Enable rfc1323 (high performance TCP) extensions"); 180 181 static int tcp_log_debug = 0; 182 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_debug, CTLFLAG_RW, 183 &tcp_log_debug, 0, "Log errors caused by incoming TCP segments"); 184 185 static int tcp_tcbhashsize = 0; 186 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tcbhashsize, CTLFLAG_RDTUN, 187 &tcp_tcbhashsize, 0, "Size of TCP control-block hashtable"); 188 189 static int do_tcpdrain = 1; 190 SYSCTL_INT(_net_inet_tcp, OID_AUTO, do_tcpdrain, CTLFLAG_RW, &do_tcpdrain, 0, 191 "Enable tcp_drain routine for extra help when low on mbufs"); 192 193 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, pcbcount, CTLFLAG_RD, 194 &VNET_NAME(tcbinfo.ipi_count), 0, "Number of active PCBs"); 195 196 static VNET_DEFINE(int, icmp_may_rst) = 1; 197 #define V_icmp_may_rst VNET(icmp_may_rst) 198 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, icmp_may_rst, CTLFLAG_RW, 199 &VNET_NAME(icmp_may_rst), 0, 200 "Certain ICMP unreachable messages may abort connections in SYN_SENT"); 201 202 static VNET_DEFINE(int, tcp_isn_reseed_interval) = 0; 203 #define V_tcp_isn_reseed_interval VNET(tcp_isn_reseed_interval) 204 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, isn_reseed_interval, CTLFLAG_RW, 205 &VNET_NAME(tcp_isn_reseed_interval), 0, 206 "Seconds between reseeding of ISN secret"); 207 208 #ifdef TCP_SORECEIVE_STREAM 209 static int tcp_soreceive_stream = 0; 210 SYSCTL_INT(_net_inet_tcp, OID_AUTO, soreceive_stream, CTLFLAG_RDTUN, 211 &tcp_soreceive_stream, 0, "Using soreceive_stream for TCP sockets"); 212 #endif 213 214 VNET_DEFINE(uma_zone_t, sack_hole_zone); 215 #define V_sack_hole_zone VNET(sack_hole_zone) 216 217 static struct inpcb *tcp_notify(struct inpcb *, int); 218 static void tcp_isn_tick(void *); 219 static char * tcp_log_addr(struct in_conninfo *inc, struct tcphdr *th, 220 void *ip4hdr, const void *ip6hdr); 221 222 /* 223 * Target size of TCP PCB hash tables. Must be a power of two. 224 * 225 * Note that this can be overridden by the kernel environment 226 * variable net.inet.tcp.tcbhashsize 227 */ 228 #ifndef TCBHASHSIZE 229 #define TCBHASHSIZE 512 230 #endif 231 232 /* 233 * XXX 234 * Callouts should be moved into struct tcp directly. They are currently 235 * separate because the tcpcb structure is exported to userland for sysctl 236 * parsing purposes, which do not know about callouts. 237 */ 238 struct tcpcb_mem { 239 struct tcpcb tcb; 240 struct tcp_timer tt; 241 struct cc_var ccv; 242 }; 243 244 static VNET_DEFINE(uma_zone_t, tcpcb_zone); 245 #define V_tcpcb_zone VNET(tcpcb_zone) 246 247 MALLOC_DEFINE(M_TCPLOG, "tcplog", "TCP address and flags print buffers"); 248 struct callout isn_callout; 249 static struct mtx isn_mtx; 250 251 #define ISN_LOCK_INIT() mtx_init(&isn_mtx, "isn_mtx", NULL, MTX_DEF) 252 #define ISN_LOCK() mtx_lock(&isn_mtx) 253 #define ISN_UNLOCK() mtx_unlock(&isn_mtx) 254 255 /* 256 * TCP initialization. 257 */ 258 static void 259 tcp_zone_change(void *tag) 260 { 261 262 uma_zone_set_max(V_tcbinfo.ipi_zone, maxsockets); 263 uma_zone_set_max(V_tcpcb_zone, maxsockets); 264 tcp_tw_zone_change(); 265 } 266 267 static int 268 tcp_inpcb_init(void *mem, int size, int flags) 269 { 270 struct inpcb *inp = mem; 271 272 INP_LOCK_INIT(inp, "inp", "tcpinp"); 273 return (0); 274 } 275 276 void 277 tcp_init(void) 278 { 279 int hashsize; 280 281 hashsize = TCBHASHSIZE; 282 TUNABLE_INT_FETCH("net.inet.tcp.tcbhashsize", &hashsize); 283 if (!powerof2(hashsize)) { 284 printf("WARNING: TCB hash size not a power of 2\n"); 285 hashsize = 512; /* safe default */ 286 } 287 in_pcbinfo_init(&V_tcbinfo, "tcp", &V_tcb, hashsize, hashsize, 288 "tcp_inpcb", tcp_inpcb_init, NULL, UMA_ZONE_NOFREE); 289 290 /* 291 * These have to be type stable for the benefit of the timers. 292 */ 293 V_tcpcb_zone = uma_zcreate("tcpcb", sizeof(struct tcpcb_mem), 294 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE); 295 uma_zone_set_max(V_tcpcb_zone, maxsockets); 296 297 tcp_tw_init(); 298 syncache_init(); 299 tcp_hc_init(); 300 tcp_reass_init(); 301 302 TUNABLE_INT_FETCH("net.inet.tcp.sack.enable", &V_tcp_do_sack); 303 V_sack_hole_zone = uma_zcreate("sackhole", sizeof(struct sackhole), 304 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE); 305 306 /* Skip initialization of globals for non-default instances. */ 307 if (!IS_DEFAULT_VNET(curvnet)) 308 return; 309 310 /* XXX virtualize those bellow? */ 311 tcp_delacktime = TCPTV_DELACK; 312 tcp_keepinit = TCPTV_KEEP_INIT; 313 tcp_keepidle = TCPTV_KEEP_IDLE; 314 tcp_keepintvl = TCPTV_KEEPINTVL; 315 tcp_maxpersistidle = TCPTV_KEEP_IDLE; 316 tcp_msl = TCPTV_MSL; 317 tcp_rexmit_min = TCPTV_MIN; 318 if (tcp_rexmit_min < 1) 319 tcp_rexmit_min = 1; 320 tcp_rexmit_slop = TCPTV_CPU_VAR; 321 tcp_finwait2_timeout = TCPTV_FINWAIT2_TIMEOUT; 322 tcp_tcbhashsize = hashsize; 323 324 #ifdef TCP_SORECEIVE_STREAM 325 TUNABLE_INT_FETCH("net.inet.tcp.soreceive_stream", &tcp_soreceive_stream); 326 if (tcp_soreceive_stream) { 327 tcp_usrreqs.pru_soreceive = soreceive_stream; 328 tcp6_usrreqs.pru_soreceive = soreceive_stream; 329 } 330 #endif 331 332 #ifdef INET6 333 #define TCP_MINPROTOHDR (sizeof(struct ip6_hdr) + sizeof(struct tcphdr)) 334 #else /* INET6 */ 335 #define TCP_MINPROTOHDR (sizeof(struct tcpiphdr)) 336 #endif /* INET6 */ 337 if (max_protohdr < TCP_MINPROTOHDR) 338 max_protohdr = TCP_MINPROTOHDR; 339 if (max_linkhdr + TCP_MINPROTOHDR > MHLEN) 340 panic("tcp_init"); 341 #undef TCP_MINPROTOHDR 342 343 ISN_LOCK_INIT(); 344 callout_init(&isn_callout, CALLOUT_MPSAFE); 345 callout_reset(&isn_callout, hz/100, tcp_isn_tick, NULL); 346 EVENTHANDLER_REGISTER(shutdown_pre_sync, tcp_fini, NULL, 347 SHUTDOWN_PRI_DEFAULT); 348 EVENTHANDLER_REGISTER(maxsockets_change, tcp_zone_change, NULL, 349 EVENTHANDLER_PRI_ANY); 350 } 351 352 #ifdef VIMAGE 353 void 354 tcp_destroy(void) 355 { 356 357 tcp_reass_destroy(); 358 tcp_hc_destroy(); 359 syncache_destroy(); 360 tcp_tw_destroy(); 361 in_pcbinfo_destroy(&V_tcbinfo); 362 uma_zdestroy(V_sack_hole_zone); 363 uma_zdestroy(V_tcpcb_zone); 364 } 365 #endif 366 367 void 368 tcp_fini(void *xtp) 369 { 370 371 callout_stop(&isn_callout); 372 } 373 374 /* 375 * Fill in the IP and TCP headers for an outgoing packet, given the tcpcb. 376 * tcp_template used to store this data in mbufs, but we now recopy it out 377 * of the tcpcb each time to conserve mbufs. 378 */ 379 void 380 tcpip_fillheaders(struct inpcb *inp, void *ip_ptr, void *tcp_ptr) 381 { 382 struct tcphdr *th = (struct tcphdr *)tcp_ptr; 383 384 INP_WLOCK_ASSERT(inp); 385 386 #ifdef INET6 387 if ((inp->inp_vflag & INP_IPV6) != 0) { 388 struct ip6_hdr *ip6; 389 390 ip6 = (struct ip6_hdr *)ip_ptr; 391 ip6->ip6_flow = (ip6->ip6_flow & ~IPV6_FLOWINFO_MASK) | 392 (inp->inp_flow & IPV6_FLOWINFO_MASK); 393 ip6->ip6_vfc = (ip6->ip6_vfc & ~IPV6_VERSION_MASK) | 394 (IPV6_VERSION & IPV6_VERSION_MASK); 395 ip6->ip6_nxt = IPPROTO_TCP; 396 ip6->ip6_plen = htons(sizeof(struct tcphdr)); 397 ip6->ip6_src = inp->in6p_laddr; 398 ip6->ip6_dst = inp->in6p_faddr; 399 } else 400 #endif 401 { 402 struct ip *ip; 403 404 ip = (struct ip *)ip_ptr; 405 ip->ip_v = IPVERSION; 406 ip->ip_hl = 5; 407 ip->ip_tos = inp->inp_ip_tos; 408 ip->ip_len = 0; 409 ip->ip_id = 0; 410 ip->ip_off = 0; 411 ip->ip_ttl = inp->inp_ip_ttl; 412 ip->ip_sum = 0; 413 ip->ip_p = IPPROTO_TCP; 414 ip->ip_src = inp->inp_laddr; 415 ip->ip_dst = inp->inp_faddr; 416 } 417 th->th_sport = inp->inp_lport; 418 th->th_dport = inp->inp_fport; 419 th->th_seq = 0; 420 th->th_ack = 0; 421 th->th_x2 = 0; 422 th->th_off = 5; 423 th->th_flags = 0; 424 th->th_win = 0; 425 th->th_urp = 0; 426 th->th_sum = 0; /* in_pseudo() is called later for ipv4 */ 427 } 428 429 /* 430 * Create template to be used to send tcp packets on a connection. 431 * Allocates an mbuf and fills in a skeletal tcp/ip header. The only 432 * use for this function is in keepalives, which use tcp_respond. 433 */ 434 struct tcptemp * 435 tcpip_maketemplate(struct inpcb *inp) 436 { 437 struct tcptemp *t; 438 439 t = malloc(sizeof(*t), M_TEMP, M_NOWAIT); 440 if (t == NULL) 441 return (NULL); 442 tcpip_fillheaders(inp, (void *)&t->tt_ipgen, (void *)&t->tt_t); 443 return (t); 444 } 445 446 /* 447 * Send a single message to the TCP at address specified by 448 * the given TCP/IP header. If m == NULL, then we make a copy 449 * of the tcpiphdr at ti and send directly to the addressed host. 450 * This is used to force keep alive messages out using the TCP 451 * template for a connection. If flags are given then we send 452 * a message back to the TCP which originated the * segment ti, 453 * and discard the mbuf containing it and any other attached mbufs. 454 * 455 * In any case the ack and sequence number of the transmitted 456 * segment are as specified by the parameters. 457 * 458 * NOTE: If m != NULL, then ti must point to *inside* the mbuf. 459 */ 460 void 461 tcp_respond(struct tcpcb *tp, void *ipgen, struct tcphdr *th, struct mbuf *m, 462 tcp_seq ack, tcp_seq seq, int flags) 463 { 464 int tlen; 465 int win = 0; 466 struct ip *ip; 467 struct tcphdr *nth; 468 #ifdef INET6 469 struct ip6_hdr *ip6; 470 int isipv6; 471 #endif /* INET6 */ 472 int ipflags = 0; 473 struct inpcb *inp; 474 475 KASSERT(tp != NULL || m != NULL, ("tcp_respond: tp and m both NULL")); 476 477 #ifdef INET6 478 isipv6 = ((struct ip *)ipgen)->ip_v == 6; 479 ip6 = ipgen; 480 #endif /* INET6 */ 481 ip = ipgen; 482 483 if (tp != NULL) { 484 inp = tp->t_inpcb; 485 KASSERT(inp != NULL, ("tcp control block w/o inpcb")); 486 INP_WLOCK_ASSERT(inp); 487 } else 488 inp = NULL; 489 490 if (tp != NULL) { 491 if (!(flags & TH_RST)) { 492 win = sbspace(&inp->inp_socket->so_rcv); 493 if (win > (long)TCP_MAXWIN << tp->rcv_scale) 494 win = (long)TCP_MAXWIN << tp->rcv_scale; 495 } 496 } 497 if (m == NULL) { 498 m = m_gethdr(M_DONTWAIT, MT_DATA); 499 if (m == NULL) 500 return; 501 tlen = 0; 502 m->m_data += max_linkhdr; 503 #ifdef INET6 504 if (isipv6) { 505 bcopy((caddr_t)ip6, mtod(m, caddr_t), 506 sizeof(struct ip6_hdr)); 507 ip6 = mtod(m, struct ip6_hdr *); 508 nth = (struct tcphdr *)(ip6 + 1); 509 } else 510 #endif /* INET6 */ 511 { 512 bcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip)); 513 ip = mtod(m, struct ip *); 514 nth = (struct tcphdr *)(ip + 1); 515 } 516 bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr)); 517 flags = TH_ACK; 518 } else { 519 /* 520 * reuse the mbuf. 521 * XXX MRT We inherrit the FIB, which is lucky. 522 */ 523 m_freem(m->m_next); 524 m->m_next = NULL; 525 m->m_data = (caddr_t)ipgen; 526 /* m_len is set later */ 527 tlen = 0; 528 #define xchg(a,b,type) { type t; t=a; a=b; b=t; } 529 #ifdef INET6 530 if (isipv6) { 531 xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr); 532 nth = (struct tcphdr *)(ip6 + 1); 533 } else 534 #endif /* INET6 */ 535 { 536 xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, uint32_t); 537 nth = (struct tcphdr *)(ip + 1); 538 } 539 if (th != nth) { 540 /* 541 * this is usually a case when an extension header 542 * exists between the IPv6 header and the 543 * TCP header. 544 */ 545 nth->th_sport = th->th_sport; 546 nth->th_dport = th->th_dport; 547 } 548 xchg(nth->th_dport, nth->th_sport, uint16_t); 549 #undef xchg 550 } 551 #ifdef INET6 552 if (isipv6) { 553 ip6->ip6_flow = 0; 554 ip6->ip6_vfc = IPV6_VERSION; 555 ip6->ip6_nxt = IPPROTO_TCP; 556 ip6->ip6_plen = htons((u_short)(sizeof (struct tcphdr) + 557 tlen)); 558 tlen += sizeof (struct ip6_hdr) + sizeof (struct tcphdr); 559 } else 560 #endif 561 { 562 tlen += sizeof (struct tcpiphdr); 563 ip->ip_len = tlen; 564 ip->ip_ttl = V_ip_defttl; 565 if (V_path_mtu_discovery) 566 ip->ip_off |= IP_DF; 567 } 568 m->m_len = tlen; 569 m->m_pkthdr.len = tlen; 570 m->m_pkthdr.rcvif = NULL; 571 #ifdef MAC 572 if (inp != NULL) { 573 /* 574 * Packet is associated with a socket, so allow the 575 * label of the response to reflect the socket label. 576 */ 577 INP_WLOCK_ASSERT(inp); 578 mac_inpcb_create_mbuf(inp, m); 579 } else { 580 /* 581 * Packet is not associated with a socket, so possibly 582 * update the label in place. 583 */ 584 mac_netinet_tcp_reply(m); 585 } 586 #endif 587 nth->th_seq = htonl(seq); 588 nth->th_ack = htonl(ack); 589 nth->th_x2 = 0; 590 nth->th_off = sizeof (struct tcphdr) >> 2; 591 nth->th_flags = flags; 592 if (tp != NULL) 593 nth->th_win = htons((u_short) (win >> tp->rcv_scale)); 594 else 595 nth->th_win = htons((u_short)win); 596 nth->th_urp = 0; 597 #ifdef INET6 598 if (isipv6) { 599 nth->th_sum = 0; 600 nth->th_sum = in6_cksum(m, IPPROTO_TCP, 601 sizeof(struct ip6_hdr), 602 tlen - sizeof(struct ip6_hdr)); 603 ip6->ip6_hlim = in6_selecthlim(tp != NULL ? tp->t_inpcb : 604 NULL, NULL); 605 } else 606 #endif /* INET6 */ 607 { 608 nth->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr, 609 htons((u_short)(tlen - sizeof(struct ip) + ip->ip_p))); 610 m->m_pkthdr.csum_flags = CSUM_TCP; 611 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum); 612 } 613 #ifdef TCPDEBUG 614 if (tp == NULL || (inp->inp_socket->so_options & SO_DEBUG)) 615 tcp_trace(TA_OUTPUT, 0, tp, mtod(m, void *), th, 0); 616 #endif 617 #ifdef INET6 618 if (isipv6) 619 (void) ip6_output(m, NULL, NULL, ipflags, NULL, NULL, inp); 620 else 621 #endif /* INET6 */ 622 (void) ip_output(m, NULL, NULL, ipflags, NULL, inp); 623 } 624 625 /* 626 * Create a new TCP control block, making an 627 * empty reassembly queue and hooking it to the argument 628 * protocol control block. The `inp' parameter must have 629 * come from the zone allocator set up in tcp_init(). 630 */ 631 struct tcpcb * 632 tcp_newtcpcb(struct inpcb *inp) 633 { 634 struct tcpcb_mem *tm; 635 struct tcpcb *tp; 636 #ifdef INET6 637 int isipv6 = (inp->inp_vflag & INP_IPV6) != 0; 638 #endif /* INET6 */ 639 640 tm = uma_zalloc(V_tcpcb_zone, M_NOWAIT | M_ZERO); 641 if (tm == NULL) 642 return (NULL); 643 tp = &tm->tcb; 644 645 /* Initialise cc_var struct for this tcpcb. */ 646 tp->ccv = &tm->ccv; 647 tp->ccv->type = IPPROTO_TCP; 648 tp->ccv->ccvc.tcp = tp; 649 650 /* 651 * Use the current system default CC algorithm. 652 */ 653 CC_LIST_RLOCK(); 654 KASSERT(!STAILQ_EMPTY(&cc_list), ("cc_list is empty!")); 655 CC_ALGO(tp) = CC_DEFAULT(); 656 CC_LIST_RUNLOCK(); 657 658 if (CC_ALGO(tp)->cb_init != NULL) 659 if (CC_ALGO(tp)->cb_init(tp->ccv) > 0) { 660 uma_zfree(V_tcpcb_zone, tm); 661 return (NULL); 662 } 663 664 #ifdef VIMAGE 665 tp->t_vnet = inp->inp_vnet; 666 #endif 667 tp->t_timers = &tm->tt; 668 /* LIST_INIT(&tp->t_segq); */ /* XXX covered by M_ZERO */ 669 tp->t_maxseg = tp->t_maxopd = 670 #ifdef INET6 671 isipv6 ? V_tcp_v6mssdflt : 672 #endif /* INET6 */ 673 V_tcp_mssdflt; 674 675 /* Set up our timeouts. */ 676 callout_init(&tp->t_timers->tt_rexmt, CALLOUT_MPSAFE); 677 callout_init(&tp->t_timers->tt_persist, CALLOUT_MPSAFE); 678 callout_init(&tp->t_timers->tt_keep, CALLOUT_MPSAFE); 679 callout_init(&tp->t_timers->tt_2msl, CALLOUT_MPSAFE); 680 callout_init(&tp->t_timers->tt_delack, CALLOUT_MPSAFE); 681 682 if (V_tcp_do_rfc1323) 683 tp->t_flags = (TF_REQ_SCALE|TF_REQ_TSTMP); 684 if (V_tcp_do_sack) 685 tp->t_flags |= TF_SACK_PERMIT; 686 TAILQ_INIT(&tp->snd_holes); 687 tp->t_inpcb = inp; /* XXX */ 688 /* 689 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no 690 * rtt estimate. Set rttvar so that srtt + 4 * rttvar gives 691 * reasonable initial retransmit time. 692 */ 693 tp->t_srtt = TCPTV_SRTTBASE; 694 tp->t_rttvar = ((TCPTV_RTOBASE - TCPTV_SRTTBASE) << TCP_RTTVAR_SHIFT) / 4; 695 tp->t_rttmin = tcp_rexmit_min; 696 tp->t_rxtcur = TCPTV_RTOBASE; 697 tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT; 698 tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT; 699 tp->t_rcvtime = ticks; 700 /* 701 * IPv4 TTL initialization is necessary for an IPv6 socket as well, 702 * because the socket may be bound to an IPv6 wildcard address, 703 * which may match an IPv4-mapped IPv6 address. 704 */ 705 inp->inp_ip_ttl = V_ip_defttl; 706 inp->inp_ppcb = tp; 707 return (tp); /* XXX */ 708 } 709 710 /* 711 * Switch the congestion control algorithm back to NewReno for any active 712 * control blocks using an algorithm which is about to go away. 713 * This ensures the CC framework can allow the unload to proceed without leaving 714 * any dangling pointers which would trigger a panic. 715 * Returning non-zero would inform the CC framework that something went wrong 716 * and it would be unsafe to allow the unload to proceed. However, there is no 717 * way for this to occur with this implementation so we always return zero. 718 */ 719 int 720 tcp_ccalgounload(struct cc_algo *unload_algo) 721 { 722 struct cc_algo *tmpalgo; 723 struct inpcb *inp; 724 struct tcpcb *tp; 725 VNET_ITERATOR_DECL(vnet_iter); 726 727 /* 728 * Check all active control blocks across all network stacks and change 729 * any that are using "unload_algo" back to NewReno. If "unload_algo" 730 * requires cleanup code to be run, call it. 731 */ 732 VNET_LIST_RLOCK(); 733 VNET_FOREACH(vnet_iter) { 734 CURVNET_SET(vnet_iter); 735 INP_INFO_RLOCK(&V_tcbinfo); 736 /* 737 * New connections already part way through being initialised 738 * with the CC algo we're removing will not race with this code 739 * because the INP_INFO_WLOCK is held during initialisation. We 740 * therefore don't enter the loop below until the connection 741 * list has stabilised. 742 */ 743 LIST_FOREACH(inp, &V_tcb, inp_list) { 744 INP_WLOCK(inp); 745 /* Important to skip tcptw structs. */ 746 if (!(inp->inp_flags & INP_TIMEWAIT) && 747 (tp = intotcpcb(inp)) != NULL) { 748 /* 749 * By holding INP_WLOCK here, we are assured 750 * that the connection is not currently 751 * executing inside the CC module's functions 752 * i.e. it is safe to make the switch back to 753 * NewReno. 754 */ 755 if (CC_ALGO(tp) == unload_algo) { 756 tmpalgo = CC_ALGO(tp); 757 /* NewReno does not require any init. */ 758 CC_ALGO(tp) = &newreno_cc_algo; 759 if (tmpalgo->cb_destroy != NULL) 760 tmpalgo->cb_destroy(tp->ccv); 761 } 762 } 763 INP_WUNLOCK(inp); 764 } 765 INP_INFO_RUNLOCK(&V_tcbinfo); 766 CURVNET_RESTORE(); 767 } 768 VNET_LIST_RUNLOCK(); 769 770 return (0); 771 } 772 773 /* 774 * Drop a TCP connection, reporting 775 * the specified error. If connection is synchronized, 776 * then send a RST to peer. 777 */ 778 struct tcpcb * 779 tcp_drop(struct tcpcb *tp, int errno) 780 { 781 struct socket *so = tp->t_inpcb->inp_socket; 782 783 INP_INFO_WLOCK_ASSERT(&V_tcbinfo); 784 INP_WLOCK_ASSERT(tp->t_inpcb); 785 786 if (TCPS_HAVERCVDSYN(tp->t_state)) { 787 tp->t_state = TCPS_CLOSED; 788 (void) tcp_output_reset(tp); 789 TCPSTAT_INC(tcps_drops); 790 } else 791 TCPSTAT_INC(tcps_conndrops); 792 if (errno == ETIMEDOUT && tp->t_softerror) 793 errno = tp->t_softerror; 794 so->so_error = errno; 795 return (tcp_close(tp)); 796 } 797 798 void 799 tcp_discardcb(struct tcpcb *tp) 800 { 801 struct inpcb *inp = tp->t_inpcb; 802 struct socket *so = inp->inp_socket; 803 #ifdef INET6 804 int isipv6 = (inp->inp_vflag & INP_IPV6) != 0; 805 #endif /* INET6 */ 806 807 INP_WLOCK_ASSERT(inp); 808 809 /* 810 * Make sure that all of our timers are stopped before we delete the 811 * PCB. 812 * 813 * XXXRW: Really, we would like to use callout_drain() here in order 814 * to avoid races experienced in tcp_timer.c where a timer is already 815 * executing at this point. However, we can't, both because we're 816 * running in a context where we can't sleep, and also because we 817 * hold locks required by the timers. What we instead need to do is 818 * test to see if callout_drain() is required, and if so, defer some 819 * portion of the remainder of tcp_discardcb() to an asynchronous 820 * context that can callout_drain() and then continue. Some care 821 * will be required to ensure that no further processing takes place 822 * on the tcpcb, even though it hasn't been freed (a flag?). 823 */ 824 callout_stop(&tp->t_timers->tt_rexmt); 825 callout_stop(&tp->t_timers->tt_persist); 826 callout_stop(&tp->t_timers->tt_keep); 827 callout_stop(&tp->t_timers->tt_2msl); 828 callout_stop(&tp->t_timers->tt_delack); 829 830 /* 831 * If we got enough samples through the srtt filter, 832 * save the rtt and rttvar in the routing entry. 833 * 'Enough' is arbitrarily defined as 4 rtt samples. 834 * 4 samples is enough for the srtt filter to converge 835 * to within enough % of the correct value; fewer samples 836 * and we could save a bogus rtt. The danger is not high 837 * as tcp quickly recovers from everything. 838 * XXX: Works very well but needs some more statistics! 839 */ 840 if (tp->t_rttupdated >= 4) { 841 struct hc_metrics_lite metrics; 842 u_long ssthresh; 843 844 bzero(&metrics, sizeof(metrics)); 845 /* 846 * Update the ssthresh always when the conditions below 847 * are satisfied. This gives us better new start value 848 * for the congestion avoidance for new connections. 849 * ssthresh is only set if packet loss occured on a session. 850 * 851 * XXXRW: 'so' may be NULL here, and/or socket buffer may be 852 * being torn down. Ideally this code would not use 'so'. 853 */ 854 ssthresh = tp->snd_ssthresh; 855 if (ssthresh != 0 && ssthresh < so->so_snd.sb_hiwat / 2) { 856 /* 857 * convert the limit from user data bytes to 858 * packets then to packet data bytes. 859 */ 860 ssthresh = (ssthresh + tp->t_maxseg / 2) / tp->t_maxseg; 861 if (ssthresh < 2) 862 ssthresh = 2; 863 ssthresh *= (u_long)(tp->t_maxseg + 864 #ifdef INET6 865 (isipv6 ? sizeof (struct ip6_hdr) + 866 sizeof (struct tcphdr) : 867 #endif 868 sizeof (struct tcpiphdr) 869 #ifdef INET6 870 ) 871 #endif 872 ); 873 } else 874 ssthresh = 0; 875 metrics.rmx_ssthresh = ssthresh; 876 877 metrics.rmx_rtt = tp->t_srtt; 878 metrics.rmx_rttvar = tp->t_rttvar; 879 metrics.rmx_cwnd = tp->snd_cwnd; 880 metrics.rmx_sendpipe = 0; 881 metrics.rmx_recvpipe = 0; 882 883 tcp_hc_update(&inp->inp_inc, &metrics); 884 } 885 886 /* free the reassembly queue, if any */ 887 tcp_reass_flush(tp); 888 /* Disconnect offload device, if any. */ 889 tcp_offload_detach(tp); 890 891 tcp_free_sackholes(tp); 892 893 /* Allow the CC algorithm to clean up after itself. */ 894 if (CC_ALGO(tp)->cb_destroy != NULL) 895 CC_ALGO(tp)->cb_destroy(tp->ccv); 896 897 CC_ALGO(tp) = NULL; 898 inp->inp_ppcb = NULL; 899 tp->t_inpcb = NULL; 900 uma_zfree(V_tcpcb_zone, tp); 901 } 902 903 /* 904 * Attempt to close a TCP control block, marking it as dropped, and freeing 905 * the socket if we hold the only reference. 906 */ 907 struct tcpcb * 908 tcp_close(struct tcpcb *tp) 909 { 910 struct inpcb *inp = tp->t_inpcb; 911 struct socket *so; 912 913 INP_INFO_WLOCK_ASSERT(&V_tcbinfo); 914 INP_WLOCK_ASSERT(inp); 915 916 /* Notify any offload devices of listener close */ 917 if (tp->t_state == TCPS_LISTEN) 918 tcp_offload_listen_close(tp); 919 in_pcbdrop(inp); 920 TCPSTAT_INC(tcps_closed); 921 KASSERT(inp->inp_socket != NULL, ("tcp_close: inp_socket NULL")); 922 so = inp->inp_socket; 923 soisdisconnected(so); 924 if (inp->inp_flags & INP_SOCKREF) { 925 KASSERT(so->so_state & SS_PROTOREF, 926 ("tcp_close: !SS_PROTOREF")); 927 inp->inp_flags &= ~INP_SOCKREF; 928 INP_WUNLOCK(inp); 929 ACCEPT_LOCK(); 930 SOCK_LOCK(so); 931 so->so_state &= ~SS_PROTOREF; 932 sofree(so); 933 return (NULL); 934 } 935 return (tp); 936 } 937 938 void 939 tcp_drain(void) 940 { 941 VNET_ITERATOR_DECL(vnet_iter); 942 943 if (!do_tcpdrain) 944 return; 945 946 VNET_LIST_RLOCK_NOSLEEP(); 947 VNET_FOREACH(vnet_iter) { 948 CURVNET_SET(vnet_iter); 949 struct inpcb *inpb; 950 struct tcpcb *tcpb; 951 952 /* 953 * Walk the tcpbs, if existing, and flush the reassembly queue, 954 * if there is one... 955 * XXX: The "Net/3" implementation doesn't imply that the TCP 956 * reassembly queue should be flushed, but in a situation 957 * where we're really low on mbufs, this is potentially 958 * usefull. 959 */ 960 INP_INFO_RLOCK(&V_tcbinfo); 961 LIST_FOREACH(inpb, V_tcbinfo.ipi_listhead, inp_list) { 962 if (inpb->inp_flags & INP_TIMEWAIT) 963 continue; 964 INP_WLOCK(inpb); 965 if ((tcpb = intotcpcb(inpb)) != NULL) { 966 tcp_reass_flush(tcpb); 967 tcp_clean_sackreport(tcpb); 968 } 969 INP_WUNLOCK(inpb); 970 } 971 INP_INFO_RUNLOCK(&V_tcbinfo); 972 CURVNET_RESTORE(); 973 } 974 VNET_LIST_RUNLOCK_NOSLEEP(); 975 } 976 977 /* 978 * Notify a tcp user of an asynchronous error; 979 * store error as soft error, but wake up user 980 * (for now, won't do anything until can select for soft error). 981 * 982 * Do not wake up user since there currently is no mechanism for 983 * reporting soft errors (yet - a kqueue filter may be added). 984 */ 985 static struct inpcb * 986 tcp_notify(struct inpcb *inp, int error) 987 { 988 struct tcpcb *tp; 989 990 INP_INFO_WLOCK_ASSERT(&V_tcbinfo); 991 INP_WLOCK_ASSERT(inp); 992 993 if ((inp->inp_flags & INP_TIMEWAIT) || 994 (inp->inp_flags & INP_DROPPED)) 995 return (inp); 996 997 tp = intotcpcb(inp); 998 KASSERT(tp != NULL, ("tcp_notify: tp == NULL")); 999 1000 /* 1001 * Ignore some errors if we are hooked up. 1002 * If connection hasn't completed, has retransmitted several times, 1003 * and receives a second error, give up now. This is better 1004 * than waiting a long time to establish a connection that 1005 * can never complete. 1006 */ 1007 if (tp->t_state == TCPS_ESTABLISHED && 1008 (error == EHOSTUNREACH || error == ENETUNREACH || 1009 error == EHOSTDOWN)) { 1010 return (inp); 1011 } else if (tp->t_state < TCPS_ESTABLISHED && tp->t_rxtshift > 3 && 1012 tp->t_softerror) { 1013 tp = tcp_drop(tp, error); 1014 if (tp != NULL) 1015 return (inp); 1016 else 1017 return (NULL); 1018 } else { 1019 tp->t_softerror = error; 1020 return (inp); 1021 } 1022 #if 0 1023 wakeup( &so->so_timeo); 1024 sorwakeup(so); 1025 sowwakeup(so); 1026 #endif 1027 } 1028 1029 static int 1030 tcp_pcblist(SYSCTL_HANDLER_ARGS) 1031 { 1032 int error, i, m, n, pcb_count; 1033 struct inpcb *inp, **inp_list; 1034 inp_gen_t gencnt; 1035 struct xinpgen xig; 1036 1037 /* 1038 * The process of preparing the TCB list is too time-consuming and 1039 * resource-intensive to repeat twice on every request. 1040 */ 1041 if (req->oldptr == NULL) { 1042 n = V_tcbinfo.ipi_count + syncache_pcbcount(); 1043 n += imax(n / 8, 10); 1044 req->oldidx = 2 * (sizeof xig) + n * sizeof(struct xtcpcb); 1045 return (0); 1046 } 1047 1048 if (req->newptr != NULL) 1049 return (EPERM); 1050 1051 /* 1052 * OK, now we're committed to doing something. 1053 */ 1054 INP_INFO_RLOCK(&V_tcbinfo); 1055 gencnt = V_tcbinfo.ipi_gencnt; 1056 n = V_tcbinfo.ipi_count; 1057 INP_INFO_RUNLOCK(&V_tcbinfo); 1058 1059 m = syncache_pcbcount(); 1060 1061 error = sysctl_wire_old_buffer(req, 2 * (sizeof xig) 1062 + (n + m) * sizeof(struct xtcpcb)); 1063 if (error != 0) 1064 return (error); 1065 1066 xig.xig_len = sizeof xig; 1067 xig.xig_count = n + m; 1068 xig.xig_gen = gencnt; 1069 xig.xig_sogen = so_gencnt; 1070 error = SYSCTL_OUT(req, &xig, sizeof xig); 1071 if (error) 1072 return (error); 1073 1074 error = syncache_pcblist(req, m, &pcb_count); 1075 if (error) 1076 return (error); 1077 1078 inp_list = malloc(n * sizeof *inp_list, M_TEMP, M_WAITOK); 1079 if (inp_list == NULL) 1080 return (ENOMEM); 1081 1082 INP_INFO_RLOCK(&V_tcbinfo); 1083 for (inp = LIST_FIRST(V_tcbinfo.ipi_listhead), i = 0; 1084 inp != NULL && i < n; inp = LIST_NEXT(inp, inp_list)) { 1085 INP_WLOCK(inp); 1086 if (inp->inp_gencnt <= gencnt) { 1087 /* 1088 * XXX: This use of cr_cansee(), introduced with 1089 * TCP state changes, is not quite right, but for 1090 * now, better than nothing. 1091 */ 1092 if (inp->inp_flags & INP_TIMEWAIT) { 1093 if (intotw(inp) != NULL) 1094 error = cr_cansee(req->td->td_ucred, 1095 intotw(inp)->tw_cred); 1096 else 1097 error = EINVAL; /* Skip this inp. */ 1098 } else 1099 error = cr_canseeinpcb(req->td->td_ucred, inp); 1100 if (error == 0) { 1101 in_pcbref(inp); 1102 inp_list[i++] = inp; 1103 } 1104 } 1105 INP_WUNLOCK(inp); 1106 } 1107 INP_INFO_RUNLOCK(&V_tcbinfo); 1108 n = i; 1109 1110 error = 0; 1111 for (i = 0; i < n; i++) { 1112 inp = inp_list[i]; 1113 INP_RLOCK(inp); 1114 if (inp->inp_gencnt <= gencnt) { 1115 struct xtcpcb xt; 1116 void *inp_ppcb; 1117 1118 bzero(&xt, sizeof(xt)); 1119 xt.xt_len = sizeof xt; 1120 /* XXX should avoid extra copy */ 1121 bcopy(inp, &xt.xt_inp, sizeof *inp); 1122 inp_ppcb = inp->inp_ppcb; 1123 if (inp_ppcb == NULL) 1124 bzero((char *) &xt.xt_tp, sizeof xt.xt_tp); 1125 else if (inp->inp_flags & INP_TIMEWAIT) { 1126 bzero((char *) &xt.xt_tp, sizeof xt.xt_tp); 1127 xt.xt_tp.t_state = TCPS_TIME_WAIT; 1128 } else { 1129 bcopy(inp_ppcb, &xt.xt_tp, sizeof xt.xt_tp); 1130 if (xt.xt_tp.t_timers) 1131 tcp_timer_to_xtimer(&xt.xt_tp, xt.xt_tp.t_timers, &xt.xt_timer); 1132 } 1133 if (inp->inp_socket != NULL) 1134 sotoxsocket(inp->inp_socket, &xt.xt_socket); 1135 else { 1136 bzero(&xt.xt_socket, sizeof xt.xt_socket); 1137 xt.xt_socket.xso_protocol = IPPROTO_TCP; 1138 } 1139 xt.xt_inp.inp_gencnt = inp->inp_gencnt; 1140 INP_RUNLOCK(inp); 1141 error = SYSCTL_OUT(req, &xt, sizeof xt); 1142 } else 1143 INP_RUNLOCK(inp); 1144 } 1145 INP_INFO_WLOCK(&V_tcbinfo); 1146 for (i = 0; i < n; i++) { 1147 inp = inp_list[i]; 1148 INP_WLOCK(inp); 1149 if (!in_pcbrele(inp)) 1150 INP_WUNLOCK(inp); 1151 } 1152 INP_INFO_WUNLOCK(&V_tcbinfo); 1153 1154 if (!error) { 1155 /* 1156 * Give the user an updated idea of our state. 1157 * If the generation differs from what we told 1158 * her before, she knows that something happened 1159 * while we were processing this request, and it 1160 * might be necessary to retry. 1161 */ 1162 INP_INFO_RLOCK(&V_tcbinfo); 1163 xig.xig_gen = V_tcbinfo.ipi_gencnt; 1164 xig.xig_sogen = so_gencnt; 1165 xig.xig_count = V_tcbinfo.ipi_count + pcb_count; 1166 INP_INFO_RUNLOCK(&V_tcbinfo); 1167 error = SYSCTL_OUT(req, &xig, sizeof xig); 1168 } 1169 free(inp_list, M_TEMP); 1170 return (error); 1171 } 1172 1173 SYSCTL_PROC(_net_inet_tcp, TCPCTL_PCBLIST, pcblist, CTLFLAG_RD, 0, 0, 1174 tcp_pcblist, "S,xtcpcb", "List of active TCP connections"); 1175 1176 static int 1177 tcp_getcred(SYSCTL_HANDLER_ARGS) 1178 { 1179 struct xucred xuc; 1180 struct sockaddr_in addrs[2]; 1181 struct inpcb *inp; 1182 int error; 1183 1184 error = priv_check(req->td, PRIV_NETINET_GETCRED); 1185 if (error) 1186 return (error); 1187 error = SYSCTL_IN(req, addrs, sizeof(addrs)); 1188 if (error) 1189 return (error); 1190 INP_INFO_RLOCK(&V_tcbinfo); 1191 inp = in_pcblookup_hash(&V_tcbinfo, addrs[1].sin_addr, 1192 addrs[1].sin_port, addrs[0].sin_addr, addrs[0].sin_port, 0, NULL); 1193 if (inp != NULL) { 1194 INP_RLOCK(inp); 1195 INP_INFO_RUNLOCK(&V_tcbinfo); 1196 if (inp->inp_socket == NULL) 1197 error = ENOENT; 1198 if (error == 0) 1199 error = cr_canseeinpcb(req->td->td_ucred, inp); 1200 if (error == 0) 1201 cru2x(inp->inp_cred, &xuc); 1202 INP_RUNLOCK(inp); 1203 } else { 1204 INP_INFO_RUNLOCK(&V_tcbinfo); 1205 error = ENOENT; 1206 } 1207 if (error == 0) 1208 error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred)); 1209 return (error); 1210 } 1211 1212 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, getcred, 1213 CTLTYPE_OPAQUE|CTLFLAG_RW|CTLFLAG_PRISON, 0, 0, 1214 tcp_getcred, "S,xucred", "Get the xucred of a TCP connection"); 1215 1216 #ifdef INET6 1217 static int 1218 tcp6_getcred(SYSCTL_HANDLER_ARGS) 1219 { 1220 struct xucred xuc; 1221 struct sockaddr_in6 addrs[2]; 1222 struct inpcb *inp; 1223 int error, mapped = 0; 1224 1225 error = priv_check(req->td, PRIV_NETINET_GETCRED); 1226 if (error) 1227 return (error); 1228 error = SYSCTL_IN(req, addrs, sizeof(addrs)); 1229 if (error) 1230 return (error); 1231 if ((error = sa6_embedscope(&addrs[0], V_ip6_use_defzone)) != 0 || 1232 (error = sa6_embedscope(&addrs[1], V_ip6_use_defzone)) != 0) { 1233 return (error); 1234 } 1235 if (IN6_IS_ADDR_V4MAPPED(&addrs[0].sin6_addr)) { 1236 if (IN6_IS_ADDR_V4MAPPED(&addrs[1].sin6_addr)) 1237 mapped = 1; 1238 else 1239 return (EINVAL); 1240 } 1241 1242 INP_INFO_RLOCK(&V_tcbinfo); 1243 if (mapped == 1) 1244 inp = in_pcblookup_hash(&V_tcbinfo, 1245 *(struct in_addr *)&addrs[1].sin6_addr.s6_addr[12], 1246 addrs[1].sin6_port, 1247 *(struct in_addr *)&addrs[0].sin6_addr.s6_addr[12], 1248 addrs[0].sin6_port, 1249 0, NULL); 1250 else 1251 inp = in6_pcblookup_hash(&V_tcbinfo, 1252 &addrs[1].sin6_addr, addrs[1].sin6_port, 1253 &addrs[0].sin6_addr, addrs[0].sin6_port, 0, NULL); 1254 if (inp != NULL) { 1255 INP_RLOCK(inp); 1256 INP_INFO_RUNLOCK(&V_tcbinfo); 1257 if (inp->inp_socket == NULL) 1258 error = ENOENT; 1259 if (error == 0) 1260 error = cr_canseeinpcb(req->td->td_ucred, inp); 1261 if (error == 0) 1262 cru2x(inp->inp_cred, &xuc); 1263 INP_RUNLOCK(inp); 1264 } else { 1265 INP_INFO_RUNLOCK(&V_tcbinfo); 1266 error = ENOENT; 1267 } 1268 if (error == 0) 1269 error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred)); 1270 return (error); 1271 } 1272 1273 SYSCTL_PROC(_net_inet6_tcp6, OID_AUTO, getcred, 1274 CTLTYPE_OPAQUE|CTLFLAG_RW|CTLFLAG_PRISON, 0, 0, 1275 tcp6_getcred, "S,xucred", "Get the xucred of a TCP6 connection"); 1276 #endif 1277 1278 1279 void 1280 tcp_ctlinput(int cmd, struct sockaddr *sa, void *vip) 1281 { 1282 struct ip *ip = vip; 1283 struct tcphdr *th; 1284 struct in_addr faddr; 1285 struct inpcb *inp; 1286 struct tcpcb *tp; 1287 struct inpcb *(*notify)(struct inpcb *, int) = tcp_notify; 1288 struct icmp *icp; 1289 struct in_conninfo inc; 1290 tcp_seq icmp_tcp_seq; 1291 int mtu; 1292 1293 faddr = ((struct sockaddr_in *)sa)->sin_addr; 1294 if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY) 1295 return; 1296 1297 if (cmd == PRC_MSGSIZE) 1298 notify = tcp_mtudisc; 1299 else if (V_icmp_may_rst && (cmd == PRC_UNREACH_ADMIN_PROHIB || 1300 cmd == PRC_UNREACH_PORT || cmd == PRC_TIMXCEED_INTRANS) && ip) 1301 notify = tcp_drop_syn_sent; 1302 /* 1303 * Redirects don't need to be handled up here. 1304 */ 1305 else if (PRC_IS_REDIRECT(cmd)) 1306 return; 1307 /* 1308 * Source quench is depreciated. 1309 */ 1310 else if (cmd == PRC_QUENCH) 1311 return; 1312 /* 1313 * Hostdead is ugly because it goes linearly through all PCBs. 1314 * XXX: We never get this from ICMP, otherwise it makes an 1315 * excellent DoS attack on machines with many connections. 1316 */ 1317 else if (cmd == PRC_HOSTDEAD) 1318 ip = NULL; 1319 else if ((unsigned)cmd >= PRC_NCMDS || inetctlerrmap[cmd] == 0) 1320 return; 1321 if (ip != NULL) { 1322 icp = (struct icmp *)((caddr_t)ip 1323 - offsetof(struct icmp, icmp_ip)); 1324 th = (struct tcphdr *)((caddr_t)ip 1325 + (ip->ip_hl << 2)); 1326 INP_INFO_WLOCK(&V_tcbinfo); 1327 inp = in_pcblookup_hash(&V_tcbinfo, faddr, th->th_dport, 1328 ip->ip_src, th->th_sport, 0, NULL); 1329 if (inp != NULL) { 1330 INP_WLOCK(inp); 1331 if (!(inp->inp_flags & INP_TIMEWAIT) && 1332 !(inp->inp_flags & INP_DROPPED) && 1333 !(inp->inp_socket == NULL)) { 1334 icmp_tcp_seq = htonl(th->th_seq); 1335 tp = intotcpcb(inp); 1336 if (SEQ_GEQ(icmp_tcp_seq, tp->snd_una) && 1337 SEQ_LT(icmp_tcp_seq, tp->snd_max)) { 1338 if (cmd == PRC_MSGSIZE) { 1339 /* 1340 * MTU discovery: 1341 * If we got a needfrag set the MTU 1342 * in the route to the suggested new 1343 * value (if given) and then notify. 1344 */ 1345 bzero(&inc, sizeof(inc)); 1346 inc.inc_faddr = faddr; 1347 inc.inc_fibnum = 1348 inp->inp_inc.inc_fibnum; 1349 1350 mtu = ntohs(icp->icmp_nextmtu); 1351 /* 1352 * If no alternative MTU was 1353 * proposed, try the next smaller 1354 * one. ip->ip_len has already 1355 * been swapped in icmp_input(). 1356 */ 1357 if (!mtu) 1358 mtu = ip_next_mtu(ip->ip_len, 1359 1); 1360 if (mtu < V_tcp_minmss 1361 + sizeof(struct tcpiphdr)) 1362 mtu = V_tcp_minmss 1363 + sizeof(struct tcpiphdr); 1364 /* 1365 * Only cache the the MTU if it 1366 * is smaller than the interface 1367 * or route MTU. tcp_mtudisc() 1368 * will do right thing by itself. 1369 */ 1370 if (mtu <= tcp_maxmtu(&inc, NULL)) 1371 tcp_hc_updatemtu(&inc, mtu); 1372 } 1373 1374 inp = (*notify)(inp, inetctlerrmap[cmd]); 1375 } 1376 } 1377 if (inp != NULL) 1378 INP_WUNLOCK(inp); 1379 } else { 1380 bzero(&inc, sizeof(inc)); 1381 inc.inc_fport = th->th_dport; 1382 inc.inc_lport = th->th_sport; 1383 inc.inc_faddr = faddr; 1384 inc.inc_laddr = ip->ip_src; 1385 syncache_unreach(&inc, th); 1386 } 1387 INP_INFO_WUNLOCK(&V_tcbinfo); 1388 } else 1389 in_pcbnotifyall(&V_tcbinfo, faddr, inetctlerrmap[cmd], notify); 1390 } 1391 1392 #ifdef INET6 1393 void 1394 tcp6_ctlinput(int cmd, struct sockaddr *sa, void *d) 1395 { 1396 struct tcphdr th; 1397 struct inpcb *(*notify)(struct inpcb *, int) = tcp_notify; 1398 struct ip6_hdr *ip6; 1399 struct mbuf *m; 1400 struct ip6ctlparam *ip6cp = NULL; 1401 const struct sockaddr_in6 *sa6_src = NULL; 1402 int off; 1403 struct tcp_portonly { 1404 u_int16_t th_sport; 1405 u_int16_t th_dport; 1406 } *thp; 1407 1408 if (sa->sa_family != AF_INET6 || 1409 sa->sa_len != sizeof(struct sockaddr_in6)) 1410 return; 1411 1412 if (cmd == PRC_MSGSIZE) 1413 notify = tcp_mtudisc; 1414 else if (!PRC_IS_REDIRECT(cmd) && 1415 ((unsigned)cmd >= PRC_NCMDS || inet6ctlerrmap[cmd] == 0)) 1416 return; 1417 /* Source quench is depreciated. */ 1418 else if (cmd == PRC_QUENCH) 1419 return; 1420 1421 /* if the parameter is from icmp6, decode it. */ 1422 if (d != NULL) { 1423 ip6cp = (struct ip6ctlparam *)d; 1424 m = ip6cp->ip6c_m; 1425 ip6 = ip6cp->ip6c_ip6; 1426 off = ip6cp->ip6c_off; 1427 sa6_src = ip6cp->ip6c_src; 1428 } else { 1429 m = NULL; 1430 ip6 = NULL; 1431 off = 0; /* fool gcc */ 1432 sa6_src = &sa6_any; 1433 } 1434 1435 if (ip6 != NULL) { 1436 struct in_conninfo inc; 1437 /* 1438 * XXX: We assume that when IPV6 is non NULL, 1439 * M and OFF are valid. 1440 */ 1441 1442 /* check if we can safely examine src and dst ports */ 1443 if (m->m_pkthdr.len < off + sizeof(*thp)) 1444 return; 1445 1446 bzero(&th, sizeof(th)); 1447 m_copydata(m, off, sizeof(*thp), (caddr_t)&th); 1448 1449 in6_pcbnotify(&V_tcbinfo, sa, th.th_dport, 1450 (struct sockaddr *)ip6cp->ip6c_src, 1451 th.th_sport, cmd, NULL, notify); 1452 1453 bzero(&inc, sizeof(inc)); 1454 inc.inc_fport = th.th_dport; 1455 inc.inc_lport = th.th_sport; 1456 inc.inc6_faddr = ((struct sockaddr_in6 *)sa)->sin6_addr; 1457 inc.inc6_laddr = ip6cp->ip6c_src->sin6_addr; 1458 inc.inc_flags |= INC_ISIPV6; 1459 INP_INFO_WLOCK(&V_tcbinfo); 1460 syncache_unreach(&inc, &th); 1461 INP_INFO_WUNLOCK(&V_tcbinfo); 1462 } else 1463 in6_pcbnotify(&V_tcbinfo, sa, 0, (const struct sockaddr *)sa6_src, 1464 0, cmd, NULL, notify); 1465 } 1466 #endif /* INET6 */ 1467 1468 1469 /* 1470 * Following is where TCP initial sequence number generation occurs. 1471 * 1472 * There are two places where we must use initial sequence numbers: 1473 * 1. In SYN-ACK packets. 1474 * 2. In SYN packets. 1475 * 1476 * All ISNs for SYN-ACK packets are generated by the syncache. See 1477 * tcp_syncache.c for details. 1478 * 1479 * The ISNs in SYN packets must be monotonic; TIME_WAIT recycling 1480 * depends on this property. In addition, these ISNs should be 1481 * unguessable so as to prevent connection hijacking. To satisfy 1482 * the requirements of this situation, the algorithm outlined in 1483 * RFC 1948 is used, with only small modifications. 1484 * 1485 * Implementation details: 1486 * 1487 * Time is based off the system timer, and is corrected so that it 1488 * increases by one megabyte per second. This allows for proper 1489 * recycling on high speed LANs while still leaving over an hour 1490 * before rollover. 1491 * 1492 * As reading the *exact* system time is too expensive to be done 1493 * whenever setting up a TCP connection, we increment the time 1494 * offset in two ways. First, a small random positive increment 1495 * is added to isn_offset for each connection that is set up. 1496 * Second, the function tcp_isn_tick fires once per clock tick 1497 * and increments isn_offset as necessary so that sequence numbers 1498 * are incremented at approximately ISN_BYTES_PER_SECOND. The 1499 * random positive increments serve only to ensure that the same 1500 * exact sequence number is never sent out twice (as could otherwise 1501 * happen when a port is recycled in less than the system tick 1502 * interval.) 1503 * 1504 * net.inet.tcp.isn_reseed_interval controls the number of seconds 1505 * between seeding of isn_secret. This is normally set to zero, 1506 * as reseeding should not be necessary. 1507 * 1508 * Locking of the global variables isn_secret, isn_last_reseed, isn_offset, 1509 * isn_offset_old, and isn_ctx is performed using the TCP pcbinfo lock. In 1510 * general, this means holding an exclusive (write) lock. 1511 */ 1512 1513 #define ISN_BYTES_PER_SECOND 1048576 1514 #define ISN_STATIC_INCREMENT 4096 1515 #define ISN_RANDOM_INCREMENT (4096 - 1) 1516 1517 static VNET_DEFINE(u_char, isn_secret[32]); 1518 static VNET_DEFINE(int, isn_last_reseed); 1519 static VNET_DEFINE(u_int32_t, isn_offset); 1520 static VNET_DEFINE(u_int32_t, isn_offset_old); 1521 1522 #define V_isn_secret VNET(isn_secret) 1523 #define V_isn_last_reseed VNET(isn_last_reseed) 1524 #define V_isn_offset VNET(isn_offset) 1525 #define V_isn_offset_old VNET(isn_offset_old) 1526 1527 tcp_seq 1528 tcp_new_isn(struct tcpcb *tp) 1529 { 1530 MD5_CTX isn_ctx; 1531 u_int32_t md5_buffer[4]; 1532 tcp_seq new_isn; 1533 1534 INP_WLOCK_ASSERT(tp->t_inpcb); 1535 1536 ISN_LOCK(); 1537 /* Seed if this is the first use, reseed if requested. */ 1538 if ((V_isn_last_reseed == 0) || ((V_tcp_isn_reseed_interval > 0) && 1539 (((u_int)V_isn_last_reseed + (u_int)V_tcp_isn_reseed_interval*hz) 1540 < (u_int)ticks))) { 1541 read_random(&V_isn_secret, sizeof(V_isn_secret)); 1542 V_isn_last_reseed = ticks; 1543 } 1544 1545 /* Compute the md5 hash and return the ISN. */ 1546 MD5Init(&isn_ctx); 1547 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_fport, sizeof(u_short)); 1548 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_lport, sizeof(u_short)); 1549 #ifdef INET6 1550 if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0) { 1551 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->in6p_faddr, 1552 sizeof(struct in6_addr)); 1553 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->in6p_laddr, 1554 sizeof(struct in6_addr)); 1555 } else 1556 #endif 1557 { 1558 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_faddr, 1559 sizeof(struct in_addr)); 1560 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_laddr, 1561 sizeof(struct in_addr)); 1562 } 1563 MD5Update(&isn_ctx, (u_char *) &V_isn_secret, sizeof(V_isn_secret)); 1564 MD5Final((u_char *) &md5_buffer, &isn_ctx); 1565 new_isn = (tcp_seq) md5_buffer[0]; 1566 V_isn_offset += ISN_STATIC_INCREMENT + 1567 (arc4random() & ISN_RANDOM_INCREMENT); 1568 new_isn += V_isn_offset; 1569 ISN_UNLOCK(); 1570 return (new_isn); 1571 } 1572 1573 /* 1574 * Increment the offset to the next ISN_BYTES_PER_SECOND / 100 boundary 1575 * to keep time flowing at a relatively constant rate. If the random 1576 * increments have already pushed us past the projected offset, do nothing. 1577 */ 1578 static void 1579 tcp_isn_tick(void *xtp) 1580 { 1581 VNET_ITERATOR_DECL(vnet_iter); 1582 u_int32_t projected_offset; 1583 1584 VNET_LIST_RLOCK_NOSLEEP(); 1585 ISN_LOCK(); 1586 VNET_FOREACH(vnet_iter) { 1587 CURVNET_SET(vnet_iter); /* XXX appease INVARIANTS */ 1588 projected_offset = 1589 V_isn_offset_old + ISN_BYTES_PER_SECOND / 100; 1590 1591 if (SEQ_GT(projected_offset, V_isn_offset)) 1592 V_isn_offset = projected_offset; 1593 1594 V_isn_offset_old = V_isn_offset; 1595 CURVNET_RESTORE(); 1596 } 1597 ISN_UNLOCK(); 1598 VNET_LIST_RUNLOCK_NOSLEEP(); 1599 callout_reset(&isn_callout, hz/100, tcp_isn_tick, NULL); 1600 } 1601 1602 /* 1603 * When a specific ICMP unreachable message is received and the 1604 * connection state is SYN-SENT, drop the connection. This behavior 1605 * is controlled by the icmp_may_rst sysctl. 1606 */ 1607 struct inpcb * 1608 tcp_drop_syn_sent(struct inpcb *inp, int errno) 1609 { 1610 struct tcpcb *tp; 1611 1612 INP_INFO_WLOCK_ASSERT(&V_tcbinfo); 1613 INP_WLOCK_ASSERT(inp); 1614 1615 if ((inp->inp_flags & INP_TIMEWAIT) || 1616 (inp->inp_flags & INP_DROPPED)) 1617 return (inp); 1618 1619 tp = intotcpcb(inp); 1620 if (tp->t_state != TCPS_SYN_SENT) 1621 return (inp); 1622 1623 tp = tcp_drop(tp, errno); 1624 if (tp != NULL) 1625 return (inp); 1626 else 1627 return (NULL); 1628 } 1629 1630 /* 1631 * When `need fragmentation' ICMP is received, update our idea of the MSS 1632 * based on the new value in the route. Also nudge TCP to send something, 1633 * since we know the packet we just sent was dropped. 1634 * This duplicates some code in the tcp_mss() function in tcp_input.c. 1635 */ 1636 struct inpcb * 1637 tcp_mtudisc(struct inpcb *inp, int errno) 1638 { 1639 struct tcpcb *tp; 1640 struct socket *so; 1641 1642 INP_WLOCK_ASSERT(inp); 1643 if ((inp->inp_flags & INP_TIMEWAIT) || 1644 (inp->inp_flags & INP_DROPPED)) 1645 return (inp); 1646 1647 tp = intotcpcb(inp); 1648 KASSERT(tp != NULL, ("tcp_mtudisc: tp == NULL")); 1649 1650 tcp_mss_update(tp, -1, NULL, NULL); 1651 1652 so = inp->inp_socket; 1653 SOCKBUF_LOCK(&so->so_snd); 1654 /* If the mss is larger than the socket buffer, decrease the mss. */ 1655 if (so->so_snd.sb_hiwat < tp->t_maxseg) 1656 tp->t_maxseg = so->so_snd.sb_hiwat; 1657 SOCKBUF_UNLOCK(&so->so_snd); 1658 1659 TCPSTAT_INC(tcps_mturesent); 1660 tp->t_rtttime = 0; 1661 tp->snd_nxt = tp->snd_una; 1662 tcp_free_sackholes(tp); 1663 tp->snd_recover = tp->snd_max; 1664 if (tp->t_flags & TF_SACK_PERMIT) 1665 EXIT_FASTRECOVERY(tp->t_flags); 1666 tcp_output_send(tp); 1667 return (inp); 1668 } 1669 1670 /* 1671 * Look-up the routing entry to the peer of this inpcb. If no route 1672 * is found and it cannot be allocated, then return 0. This routine 1673 * is called by TCP routines that access the rmx structure and by 1674 * tcp_mss_update to get the peer/interface MTU. 1675 */ 1676 u_long 1677 tcp_maxmtu(struct in_conninfo *inc, int *flags) 1678 { 1679 struct route sro; 1680 struct sockaddr_in *dst; 1681 struct ifnet *ifp; 1682 u_long maxmtu = 0; 1683 1684 KASSERT(inc != NULL, ("tcp_maxmtu with NULL in_conninfo pointer")); 1685 1686 bzero(&sro, sizeof(sro)); 1687 if (inc->inc_faddr.s_addr != INADDR_ANY) { 1688 dst = (struct sockaddr_in *)&sro.ro_dst; 1689 dst->sin_family = AF_INET; 1690 dst->sin_len = sizeof(*dst); 1691 dst->sin_addr = inc->inc_faddr; 1692 in_rtalloc_ign(&sro, 0, inc->inc_fibnum); 1693 } 1694 if (sro.ro_rt != NULL) { 1695 ifp = sro.ro_rt->rt_ifp; 1696 if (sro.ro_rt->rt_rmx.rmx_mtu == 0) 1697 maxmtu = ifp->if_mtu; 1698 else 1699 maxmtu = min(sro.ro_rt->rt_rmx.rmx_mtu, ifp->if_mtu); 1700 1701 /* Report additional interface capabilities. */ 1702 if (flags != NULL) { 1703 if (ifp->if_capenable & IFCAP_TSO4 && 1704 ifp->if_hwassist & CSUM_TSO) 1705 *flags |= CSUM_TSO; 1706 } 1707 RTFREE(sro.ro_rt); 1708 } 1709 return (maxmtu); 1710 } 1711 1712 #ifdef INET6 1713 u_long 1714 tcp_maxmtu6(struct in_conninfo *inc, int *flags) 1715 { 1716 struct route_in6 sro6; 1717 struct ifnet *ifp; 1718 u_long maxmtu = 0; 1719 1720 KASSERT(inc != NULL, ("tcp_maxmtu6 with NULL in_conninfo pointer")); 1721 1722 bzero(&sro6, sizeof(sro6)); 1723 if (!IN6_IS_ADDR_UNSPECIFIED(&inc->inc6_faddr)) { 1724 sro6.ro_dst.sin6_family = AF_INET6; 1725 sro6.ro_dst.sin6_len = sizeof(struct sockaddr_in6); 1726 sro6.ro_dst.sin6_addr = inc->inc6_faddr; 1727 rtalloc_ign((struct route *)&sro6, 0); 1728 } 1729 if (sro6.ro_rt != NULL) { 1730 ifp = sro6.ro_rt->rt_ifp; 1731 if (sro6.ro_rt->rt_rmx.rmx_mtu == 0) 1732 maxmtu = IN6_LINKMTU(sro6.ro_rt->rt_ifp); 1733 else 1734 maxmtu = min(sro6.ro_rt->rt_rmx.rmx_mtu, 1735 IN6_LINKMTU(sro6.ro_rt->rt_ifp)); 1736 1737 /* Report additional interface capabilities. */ 1738 if (flags != NULL) { 1739 if (ifp->if_capenable & IFCAP_TSO6 && 1740 ifp->if_hwassist & CSUM_TSO) 1741 *flags |= CSUM_TSO; 1742 } 1743 RTFREE(sro6.ro_rt); 1744 } 1745 1746 return (maxmtu); 1747 } 1748 #endif /* INET6 */ 1749 1750 #ifdef IPSEC 1751 /* compute ESP/AH header size for TCP, including outer IP header. */ 1752 size_t 1753 ipsec_hdrsiz_tcp(struct tcpcb *tp) 1754 { 1755 struct inpcb *inp; 1756 struct mbuf *m; 1757 size_t hdrsiz; 1758 struct ip *ip; 1759 #ifdef INET6 1760 struct ip6_hdr *ip6; 1761 #endif 1762 struct tcphdr *th; 1763 1764 if ((tp == NULL) || ((inp = tp->t_inpcb) == NULL)) 1765 return (0); 1766 MGETHDR(m, M_DONTWAIT, MT_DATA); 1767 if (!m) 1768 return (0); 1769 1770 #ifdef INET6 1771 if ((inp->inp_vflag & INP_IPV6) != 0) { 1772 ip6 = mtod(m, struct ip6_hdr *); 1773 th = (struct tcphdr *)(ip6 + 1); 1774 m->m_pkthdr.len = m->m_len = 1775 sizeof(struct ip6_hdr) + sizeof(struct tcphdr); 1776 tcpip_fillheaders(inp, ip6, th); 1777 hdrsiz = ipsec_hdrsiz(m, IPSEC_DIR_OUTBOUND, inp); 1778 } else 1779 #endif /* INET6 */ 1780 { 1781 ip = mtod(m, struct ip *); 1782 th = (struct tcphdr *)(ip + 1); 1783 m->m_pkthdr.len = m->m_len = sizeof(struct tcpiphdr); 1784 tcpip_fillheaders(inp, ip, th); 1785 hdrsiz = ipsec_hdrsiz(m, IPSEC_DIR_OUTBOUND, inp); 1786 } 1787 1788 m_free(m); 1789 return (hdrsiz); 1790 } 1791 #endif /* IPSEC */ 1792 1793 #ifdef TCP_SIGNATURE 1794 /* 1795 * Callback function invoked by m_apply() to digest TCP segment data 1796 * contained within an mbuf chain. 1797 */ 1798 static int 1799 tcp_signature_apply(void *fstate, void *data, u_int len) 1800 { 1801 1802 MD5Update(fstate, (u_char *)data, len); 1803 return (0); 1804 } 1805 1806 /* 1807 * Compute TCP-MD5 hash of a TCP segment. (RFC2385) 1808 * 1809 * Parameters: 1810 * m pointer to head of mbuf chain 1811 * _unused 1812 * len length of TCP segment data, excluding options 1813 * optlen length of TCP segment options 1814 * buf pointer to storage for computed MD5 digest 1815 * direction direction of flow (IPSEC_DIR_INBOUND or OUTBOUND) 1816 * 1817 * We do this over ip, tcphdr, segment data, and the key in the SADB. 1818 * When called from tcp_input(), we can be sure that th_sum has been 1819 * zeroed out and verified already. 1820 * 1821 * Return 0 if successful, otherwise return -1. 1822 * 1823 * XXX The key is retrieved from the system's PF_KEY SADB, by keying a 1824 * search with the destination IP address, and a 'magic SPI' to be 1825 * determined by the application. This is hardcoded elsewhere to 1179 1826 * right now. Another branch of this code exists which uses the SPD to 1827 * specify per-application flows but it is unstable. 1828 */ 1829 int 1830 tcp_signature_compute(struct mbuf *m, int _unused, int len, int optlen, 1831 u_char *buf, u_int direction) 1832 { 1833 union sockaddr_union dst; 1834 struct ippseudo ippseudo; 1835 MD5_CTX ctx; 1836 int doff; 1837 struct ip *ip; 1838 struct ipovly *ipovly; 1839 struct secasvar *sav; 1840 struct tcphdr *th; 1841 #ifdef INET6 1842 struct ip6_hdr *ip6; 1843 struct in6_addr in6; 1844 char ip6buf[INET6_ADDRSTRLEN]; 1845 uint32_t plen; 1846 uint16_t nhdr; 1847 #endif 1848 u_short savecsum; 1849 1850 KASSERT(m != NULL, ("NULL mbuf chain")); 1851 KASSERT(buf != NULL, ("NULL signature pointer")); 1852 1853 /* Extract the destination from the IP header in the mbuf. */ 1854 bzero(&dst, sizeof(union sockaddr_union)); 1855 ip = mtod(m, struct ip *); 1856 #ifdef INET6 1857 ip6 = NULL; /* Make the compiler happy. */ 1858 #endif 1859 switch (ip->ip_v) { 1860 case IPVERSION: 1861 dst.sa.sa_len = sizeof(struct sockaddr_in); 1862 dst.sa.sa_family = AF_INET; 1863 dst.sin.sin_addr = (direction == IPSEC_DIR_INBOUND) ? 1864 ip->ip_src : ip->ip_dst; 1865 break; 1866 #ifdef INET6 1867 case (IPV6_VERSION >> 4): 1868 ip6 = mtod(m, struct ip6_hdr *); 1869 dst.sa.sa_len = sizeof(struct sockaddr_in6); 1870 dst.sa.sa_family = AF_INET6; 1871 dst.sin6.sin6_addr = (direction == IPSEC_DIR_INBOUND) ? 1872 ip6->ip6_src : ip6->ip6_dst; 1873 break; 1874 #endif 1875 default: 1876 return (EINVAL); 1877 /* NOTREACHED */ 1878 break; 1879 } 1880 1881 /* Look up an SADB entry which matches the address of the peer. */ 1882 sav = KEY_ALLOCSA(&dst, IPPROTO_TCP, htonl(TCP_SIG_SPI)); 1883 if (sav == NULL) { 1884 ipseclog((LOG_ERR, "%s: SADB lookup failed for %s\n", __func__, 1885 (ip->ip_v == IPVERSION) ? inet_ntoa(dst.sin.sin_addr) : 1886 #ifdef INET6 1887 (ip->ip_v == (IPV6_VERSION >> 4)) ? 1888 ip6_sprintf(ip6buf, &dst.sin6.sin6_addr) : 1889 #endif 1890 "(unsupported)")); 1891 return (EINVAL); 1892 } 1893 1894 MD5Init(&ctx); 1895 /* 1896 * Step 1: Update MD5 hash with IP(v6) pseudo-header. 1897 * 1898 * XXX The ippseudo header MUST be digested in network byte order, 1899 * or else we'll fail the regression test. Assume all fields we've 1900 * been doing arithmetic on have been in host byte order. 1901 * XXX One cannot depend on ipovly->ih_len here. When called from 1902 * tcp_output(), the underlying ip_len member has not yet been set. 1903 */ 1904 switch (ip->ip_v) { 1905 case IPVERSION: 1906 ipovly = (struct ipovly *)ip; 1907 ippseudo.ippseudo_src = ipovly->ih_src; 1908 ippseudo.ippseudo_dst = ipovly->ih_dst; 1909 ippseudo.ippseudo_pad = 0; 1910 ippseudo.ippseudo_p = IPPROTO_TCP; 1911 ippseudo.ippseudo_len = htons(len + sizeof(struct tcphdr) + 1912 optlen); 1913 MD5Update(&ctx, (char *)&ippseudo, sizeof(struct ippseudo)); 1914 1915 th = (struct tcphdr *)((u_char *)ip + sizeof(struct ip)); 1916 doff = sizeof(struct ip) + sizeof(struct tcphdr) + optlen; 1917 break; 1918 #ifdef INET6 1919 /* 1920 * RFC 2385, 2.0 Proposal 1921 * For IPv6, the pseudo-header is as described in RFC 2460, namely the 1922 * 128-bit source IPv6 address, 128-bit destination IPv6 address, zero- 1923 * extended next header value (to form 32 bits), and 32-bit segment 1924 * length. 1925 * Note: Upper-Layer Packet Length comes before Next Header. 1926 */ 1927 case (IPV6_VERSION >> 4): 1928 in6 = ip6->ip6_src; 1929 in6_clearscope(&in6); 1930 MD5Update(&ctx, (char *)&in6, sizeof(struct in6_addr)); 1931 in6 = ip6->ip6_dst; 1932 in6_clearscope(&in6); 1933 MD5Update(&ctx, (char *)&in6, sizeof(struct in6_addr)); 1934 plen = htonl(len + sizeof(struct tcphdr) + optlen); 1935 MD5Update(&ctx, (char *)&plen, sizeof(uint32_t)); 1936 nhdr = 0; 1937 MD5Update(&ctx, (char *)&nhdr, sizeof(uint8_t)); 1938 MD5Update(&ctx, (char *)&nhdr, sizeof(uint8_t)); 1939 MD5Update(&ctx, (char *)&nhdr, sizeof(uint8_t)); 1940 nhdr = IPPROTO_TCP; 1941 MD5Update(&ctx, (char *)&nhdr, sizeof(uint8_t)); 1942 1943 th = (struct tcphdr *)((u_char *)ip6 + sizeof(struct ip6_hdr)); 1944 doff = sizeof(struct ip6_hdr) + sizeof(struct tcphdr) + optlen; 1945 break; 1946 #endif 1947 default: 1948 return (EINVAL); 1949 /* NOTREACHED */ 1950 break; 1951 } 1952 1953 1954 /* 1955 * Step 2: Update MD5 hash with TCP header, excluding options. 1956 * The TCP checksum must be set to zero. 1957 */ 1958 savecsum = th->th_sum; 1959 th->th_sum = 0; 1960 MD5Update(&ctx, (char *)th, sizeof(struct tcphdr)); 1961 th->th_sum = savecsum; 1962 1963 /* 1964 * Step 3: Update MD5 hash with TCP segment data. 1965 * Use m_apply() to avoid an early m_pullup(). 1966 */ 1967 if (len > 0) 1968 m_apply(m, doff, len, tcp_signature_apply, &ctx); 1969 1970 /* 1971 * Step 4: Update MD5 hash with shared secret. 1972 */ 1973 MD5Update(&ctx, sav->key_auth->key_data, _KEYLEN(sav->key_auth)); 1974 MD5Final(buf, &ctx); 1975 1976 key_sa_recordxfer(sav, m); 1977 KEY_FREESAV(&sav); 1978 return (0); 1979 } 1980 #endif /* TCP_SIGNATURE */ 1981 1982 static int 1983 sysctl_drop(SYSCTL_HANDLER_ARGS) 1984 { 1985 /* addrs[0] is a foreign socket, addrs[1] is a local one. */ 1986 struct sockaddr_storage addrs[2]; 1987 struct inpcb *inp; 1988 struct tcpcb *tp; 1989 struct tcptw *tw; 1990 struct sockaddr_in *fin, *lin; 1991 #ifdef INET6 1992 struct sockaddr_in6 *fin6, *lin6; 1993 #endif 1994 int error; 1995 1996 inp = NULL; 1997 fin = lin = NULL; 1998 #ifdef INET6 1999 fin6 = lin6 = NULL; 2000 #endif 2001 error = 0; 2002 2003 if (req->oldptr != NULL || req->oldlen != 0) 2004 return (EINVAL); 2005 if (req->newptr == NULL) 2006 return (EPERM); 2007 if (req->newlen < sizeof(addrs)) 2008 return (ENOMEM); 2009 error = SYSCTL_IN(req, &addrs, sizeof(addrs)); 2010 if (error) 2011 return (error); 2012 2013 switch (addrs[0].ss_family) { 2014 #ifdef INET6 2015 case AF_INET6: 2016 fin6 = (struct sockaddr_in6 *)&addrs[0]; 2017 lin6 = (struct sockaddr_in6 *)&addrs[1]; 2018 if (fin6->sin6_len != sizeof(struct sockaddr_in6) || 2019 lin6->sin6_len != sizeof(struct sockaddr_in6)) 2020 return (EINVAL); 2021 if (IN6_IS_ADDR_V4MAPPED(&fin6->sin6_addr)) { 2022 if (!IN6_IS_ADDR_V4MAPPED(&lin6->sin6_addr)) 2023 return (EINVAL); 2024 in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[0]); 2025 in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[1]); 2026 fin = (struct sockaddr_in *)&addrs[0]; 2027 lin = (struct sockaddr_in *)&addrs[1]; 2028 break; 2029 } 2030 error = sa6_embedscope(fin6, V_ip6_use_defzone); 2031 if (error) 2032 return (error); 2033 error = sa6_embedscope(lin6, V_ip6_use_defzone); 2034 if (error) 2035 return (error); 2036 break; 2037 #endif 2038 case AF_INET: 2039 fin = (struct sockaddr_in *)&addrs[0]; 2040 lin = (struct sockaddr_in *)&addrs[1]; 2041 if (fin->sin_len != sizeof(struct sockaddr_in) || 2042 lin->sin_len != sizeof(struct sockaddr_in)) 2043 return (EINVAL); 2044 break; 2045 default: 2046 return (EINVAL); 2047 } 2048 INP_INFO_WLOCK(&V_tcbinfo); 2049 switch (addrs[0].ss_family) { 2050 #ifdef INET6 2051 case AF_INET6: 2052 inp = in6_pcblookup_hash(&V_tcbinfo, &fin6->sin6_addr, 2053 fin6->sin6_port, &lin6->sin6_addr, lin6->sin6_port, 0, 2054 NULL); 2055 break; 2056 #endif 2057 case AF_INET: 2058 inp = in_pcblookup_hash(&V_tcbinfo, fin->sin_addr, 2059 fin->sin_port, lin->sin_addr, lin->sin_port, 0, NULL); 2060 break; 2061 } 2062 if (inp != NULL) { 2063 INP_WLOCK(inp); 2064 if (inp->inp_flags & INP_TIMEWAIT) { 2065 /* 2066 * XXXRW: There currently exists a state where an 2067 * inpcb is present, but its timewait state has been 2068 * discarded. For now, don't allow dropping of this 2069 * type of inpcb. 2070 */ 2071 tw = intotw(inp); 2072 if (tw != NULL) 2073 tcp_twclose(tw, 0); 2074 else 2075 INP_WUNLOCK(inp); 2076 } else if (!(inp->inp_flags & INP_DROPPED) && 2077 !(inp->inp_socket->so_options & SO_ACCEPTCONN)) { 2078 tp = intotcpcb(inp); 2079 tp = tcp_drop(tp, ECONNABORTED); 2080 if (tp != NULL) 2081 INP_WUNLOCK(inp); 2082 } else 2083 INP_WUNLOCK(inp); 2084 } else 2085 error = ESRCH; 2086 INP_INFO_WUNLOCK(&V_tcbinfo); 2087 return (error); 2088 } 2089 2090 SYSCTL_PROC(_net_inet_tcp, TCPCTL_DROP, drop, 2091 CTLTYPE_STRUCT|CTLFLAG_WR|CTLFLAG_SKIP, NULL, 2092 0, sysctl_drop, "", "Drop TCP connection"); 2093 2094 /* 2095 * Generate a standardized TCP log line for use throughout the 2096 * tcp subsystem. Memory allocation is done with M_NOWAIT to 2097 * allow use in the interrupt context. 2098 * 2099 * NB: The caller MUST free(s, M_TCPLOG) the returned string. 2100 * NB: The function may return NULL if memory allocation failed. 2101 * 2102 * Due to header inclusion and ordering limitations the struct ip 2103 * and ip6_hdr pointers have to be passed as void pointers. 2104 */ 2105 char * 2106 tcp_log_vain(struct in_conninfo *inc, struct tcphdr *th, void *ip4hdr, 2107 const void *ip6hdr) 2108 { 2109 2110 /* Is logging enabled? */ 2111 if (tcp_log_in_vain == 0) 2112 return (NULL); 2113 2114 return (tcp_log_addr(inc, th, ip4hdr, ip6hdr)); 2115 } 2116 2117 char * 2118 tcp_log_addrs(struct in_conninfo *inc, struct tcphdr *th, void *ip4hdr, 2119 const void *ip6hdr) 2120 { 2121 2122 /* Is logging enabled? */ 2123 if (tcp_log_debug == 0) 2124 return (NULL); 2125 2126 return (tcp_log_addr(inc, th, ip4hdr, ip6hdr)); 2127 } 2128 2129 static char * 2130 tcp_log_addr(struct in_conninfo *inc, struct tcphdr *th, void *ip4hdr, 2131 const void *ip6hdr) 2132 { 2133 char *s, *sp; 2134 size_t size; 2135 struct ip *ip; 2136 #ifdef INET6 2137 const struct ip6_hdr *ip6; 2138 2139 ip6 = (const struct ip6_hdr *)ip6hdr; 2140 #endif /* INET6 */ 2141 ip = (struct ip *)ip4hdr; 2142 2143 /* 2144 * The log line looks like this: 2145 * "TCP: [1.2.3.4]:50332 to [1.2.3.4]:80 tcpflags 0x2<SYN>" 2146 */ 2147 size = sizeof("TCP: []:12345 to []:12345 tcpflags 0x2<>") + 2148 sizeof(PRINT_TH_FLAGS) + 1 + 2149 #ifdef INET6 2150 2 * INET6_ADDRSTRLEN; 2151 #else 2152 2 * INET_ADDRSTRLEN; 2153 #endif /* INET6 */ 2154 2155 s = malloc(size, M_TCPLOG, M_ZERO|M_NOWAIT); 2156 if (s == NULL) 2157 return (NULL); 2158 2159 strcat(s, "TCP: ["); 2160 sp = s + strlen(s); 2161 2162 if (inc && ((inc->inc_flags & INC_ISIPV6) == 0)) { 2163 inet_ntoa_r(inc->inc_faddr, sp); 2164 sp = s + strlen(s); 2165 sprintf(sp, "]:%i to [", ntohs(inc->inc_fport)); 2166 sp = s + strlen(s); 2167 inet_ntoa_r(inc->inc_laddr, sp); 2168 sp = s + strlen(s); 2169 sprintf(sp, "]:%i", ntohs(inc->inc_lport)); 2170 #ifdef INET6 2171 } else if (inc) { 2172 ip6_sprintf(sp, &inc->inc6_faddr); 2173 sp = s + strlen(s); 2174 sprintf(sp, "]:%i to [", ntohs(inc->inc_fport)); 2175 sp = s + strlen(s); 2176 ip6_sprintf(sp, &inc->inc6_laddr); 2177 sp = s + strlen(s); 2178 sprintf(sp, "]:%i", ntohs(inc->inc_lport)); 2179 } else if (ip6 && th) { 2180 ip6_sprintf(sp, &ip6->ip6_src); 2181 sp = s + strlen(s); 2182 sprintf(sp, "]:%i to [", ntohs(th->th_sport)); 2183 sp = s + strlen(s); 2184 ip6_sprintf(sp, &ip6->ip6_dst); 2185 sp = s + strlen(s); 2186 sprintf(sp, "]:%i", ntohs(th->th_dport)); 2187 #endif /* INET6 */ 2188 } else if (ip && th) { 2189 inet_ntoa_r(ip->ip_src, sp); 2190 sp = s + strlen(s); 2191 sprintf(sp, "]:%i to [", ntohs(th->th_sport)); 2192 sp = s + strlen(s); 2193 inet_ntoa_r(ip->ip_dst, sp); 2194 sp = s + strlen(s); 2195 sprintf(sp, "]:%i", ntohs(th->th_dport)); 2196 } else { 2197 free(s, M_TCPLOG); 2198 return (NULL); 2199 } 2200 sp = s + strlen(s); 2201 if (th) 2202 sprintf(sp, " tcpflags 0x%b", th->th_flags, PRINT_TH_FLAGS); 2203 if (*(s + size - 1) != '\0') 2204 panic("%s: string too long", __func__); 2205 return (s); 2206 } 2207