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