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