xref: /openbsd/sys/netinet/tcp_subr.c (revision cbb583bb)
1 /*	$OpenBSD: tcp_subr.c,v 1.206 2025/01/22 09:37:06 bluhm Exp $	*/
2 /*	$NetBSD: tcp_subr.c,v 1.22 1996/02/13 23:44:00 christos Exp $	*/
3 
4 /*
5  * Copyright (c) 1982, 1986, 1988, 1990, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	@(#)COPYRIGHT	1.1 (NRL) 17 January 1995
33  *
34  * NRL grants permission for redistribution and use in source and binary
35  * forms, with or without modification, of the software and documentation
36  * created at NRL provided that the following conditions are met:
37  *
38  * 1. Redistributions of source code must retain the above copyright
39  *    notice, this list of conditions and the following disclaimer.
40  * 2. Redistributions in binary form must reproduce the above copyright
41  *    notice, this list of conditions and the following disclaimer in the
42  *    documentation and/or other materials provided with the distribution.
43  * 3. All advertising materials mentioning features or use of this software
44  *    must display the following acknowledgements:
45  *	This product includes software developed by the University of
46  *	California, Berkeley and its contributors.
47  *	This product includes software developed at the Information
48  *	Technology Division, US Naval Research Laboratory.
49  * 4. Neither the name of the NRL nor the names of its contributors
50  *    may be used to endorse or promote products derived from this software
51  *    without specific prior written permission.
52  *
53  * THE SOFTWARE PROVIDED BY NRL IS PROVIDED BY NRL AND CONTRIBUTORS ``AS
54  * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
55  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
56  * PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL NRL OR
57  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
58  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
59  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
60  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
61  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
62  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
63  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
64  *
65  * The views and conclusions contained in the software and documentation
66  * are those of the authors and should not be interpreted as representing
67  * official policies, either expressed or implied, of the US Naval
68  * Research Laboratory (NRL).
69  */
70 
71 #include <sys/param.h>
72 #include <sys/systm.h>
73 #include <sys/mbuf.h>
74 #include <sys/mutex.h>
75 #include <sys/socket.h>
76 #include <sys/socketvar.h>
77 #include <sys/timeout.h>
78 #include <sys/protosw.h>
79 #include <sys/kernel.h>
80 #include <sys/pool.h>
81 
82 #include <net/route.h>
83 
84 #include <netinet/in.h>
85 #include <netinet/ip.h>
86 #include <netinet/in_pcb.h>
87 #include <netinet/ip_var.h>
88 #include <netinet6/ip6_var.h>
89 #include <netinet/ip_icmp.h>
90 #include <netinet/tcp.h>
91 #include <netinet/tcp_fsm.h>
92 #include <netinet/tcp_seq.h>
93 #include <netinet/tcp_timer.h>
94 #include <netinet/tcp_var.h>
95 
96 #ifdef INET6
97 #include <netinet6/ip6protosw.h>
98 #endif /* INET6 */
99 
100 #include <crypto/md5.h>
101 #include <crypto/sha2.h>
102 
103 /*
104  * Locks used to protect struct members in this file:
105  *	I	immutable after creation
106  *	T	tcp_timer_mtx		global tcp timer data structures
107  */
108 
109 struct mutex tcp_timer_mtx = MUTEX_INITIALIZER(IPL_SOFTNET);
110 
111 /* patchable/settable parameters for tcp */
112 int	tcp_mssdflt = TCP_MSS;
113 int	tcp_rttdflt = TCPTV_SRTTDFLT;
114 
115 /* values controllable via sysctl */
116 int	tcp_do_rfc1323 = 1;
117 int	tcp_do_sack = 1;	/* RFC 2018 selective ACKs */
118 int	tcp_ack_on_push = 0;	/* set to enable immediate ACK-on-PUSH */
119 #ifdef TCP_ECN
120 int	tcp_do_ecn = 0;		/* RFC3168 ECN enabled/disabled? */
121 #endif
122 int	tcp_do_rfc3390 = 2;	/* Increase TCP's Initial Window to 10*mss */
123 int	tcp_do_tso = 1;		/* TCP segmentation offload for output */
124 
125 #ifndef TCB_INITIAL_HASH_SIZE
126 #define	TCB_INITIAL_HASH_SIZE	128
127 #endif
128 
129 int tcp_reass_limit = NMBCLUSTERS / 8; /* hardlimit for tcpqe_pool */
130 int tcp_sackhole_limit = 32*1024; /* hardlimit for sackhl_pool */
131 
132 struct pool tcpcb_pool;
133 struct pool tcpqe_pool;
134 struct pool sackhl_pool;
135 
136 struct cpumem *tcpcounters;		/* tcp statistics */
137 
138 u_char		tcp_secret[16];	/* [I] */
139 SHA2_CTX	tcp_secret_ctx;	/* [I] */
140 tcp_seq		tcp_iss;	/* [T] updated by timer and connection */
141 uint64_t	tcp_starttime;	/* [I] random offset for tcp_now() */
142 
143 /*
144  * Tcp initialization
145  */
146 void
tcp_init(void)147 tcp_init(void)
148 {
149 	tcp_iss = 1;		/* wrong */
150 	/* 0 is treated special so add 1, 63 bits to count is enough */
151 	arc4random_buf(&tcp_starttime, sizeof(tcp_starttime));
152 	tcp_starttime = 1ULL + (tcp_starttime / 2);
153 	pool_init(&tcpcb_pool, sizeof(struct tcpcb), 0, IPL_SOFTNET, 0,
154 	    "tcpcb", NULL);
155 	pool_init(&tcpqe_pool, sizeof(struct tcpqent), 0, IPL_SOFTNET, 0,
156 	    "tcpqe", NULL);
157 	pool_sethardlimit(&tcpqe_pool, tcp_reass_limit, NULL, 0);
158 	pool_init(&sackhl_pool, sizeof(struct sackhole), 0, IPL_SOFTNET, 0,
159 	    "sackhl", NULL);
160 	pool_sethardlimit(&sackhl_pool, tcp_sackhole_limit, NULL, 0);
161 	in_pcbinit(&tcbtable, TCB_INITIAL_HASH_SIZE);
162 #ifdef INET6
163 	in_pcbinit(&tcb6table, TCB_INITIAL_HASH_SIZE);
164 #endif
165 	tcpcounters = counters_alloc(tcps_ncounters);
166 
167 	arc4random_buf(tcp_secret, sizeof(tcp_secret));
168 	SHA512Init(&tcp_secret_ctx);
169 	SHA512Update(&tcp_secret_ctx, tcp_secret, sizeof(tcp_secret));
170 
171 #ifdef INET6
172 	/*
173 	 * Since sizeof(struct ip6_hdr) > sizeof(struct ip), we
174 	 * do max length checks/computations only on the former.
175 	 */
176 	if (max_protohdr < (sizeof(struct ip6_hdr) + sizeof(struct tcphdr)))
177 		max_protohdr = (sizeof(struct ip6_hdr) + sizeof(struct tcphdr));
178 	if ((max_linkhdr + sizeof(struct ip6_hdr) + sizeof(struct tcphdr)) >
179 	    MHLEN)
180 		panic("tcp_init");
181 
182 	icmp6_mtudisc_callback_register(tcp6_mtudisc_callback);
183 #endif /* INET6 */
184 
185 	/* Initialize the compressed state engine. */
186 	syn_cache_init();
187 }
188 
189 /*
190  * Create template to be used to send tcp packets on a connection.
191  * Call after host entry created, allocates an mbuf and fills
192  * in a skeletal tcp/ip header, minimizing the amount of work
193  * necessary when the connection is used.
194  *
195  * To support IPv6 in addition to IPv4 and considering that the sizes of
196  * the IPv4 and IPv6 headers are not the same, we now use a separate pointer
197  * for the TCP header.  Also, we made the former tcpiphdr header pointer
198  * into just an IP overlay pointer, with casting as appropriate for v6. rja
199  */
200 struct mbuf *
tcp_template(struct tcpcb * tp)201 tcp_template(struct tcpcb *tp)
202 {
203 	struct inpcb *inp = tp->t_inpcb;
204 	struct mbuf *m;
205 	struct tcphdr *th;
206 
207 	CTASSERT(sizeof(struct ip) + sizeof(struct tcphdr) <= MHLEN);
208 	CTASSERT(sizeof(struct ip6_hdr) + sizeof(struct tcphdr) <= MHLEN);
209 
210 	if ((m = tp->t_template) == 0) {
211 		m = m_get(M_DONTWAIT, MT_HEADER);
212 		if (m == NULL)
213 			return (0);
214 
215 		switch (tp->pf) {
216 		case 0:	/*default to PF_INET*/
217 		case AF_INET:
218 			m->m_len = sizeof(struct ip);
219 			break;
220 #ifdef INET6
221 		case AF_INET6:
222 			m->m_len = sizeof(struct ip6_hdr);
223 			break;
224 #endif /* INET6 */
225 		}
226 		m->m_len += sizeof (struct tcphdr);
227 	}
228 
229 	switch(tp->pf) {
230 	case AF_INET:
231 		{
232 			struct ipovly *ipovly;
233 
234 			ipovly = mtod(m, struct ipovly *);
235 
236 			bzero(ipovly->ih_x1, sizeof ipovly->ih_x1);
237 			ipovly->ih_pr = IPPROTO_TCP;
238 			ipovly->ih_len = htons(sizeof (struct tcphdr));
239 			ipovly->ih_src = inp->inp_laddr;
240 			ipovly->ih_dst = inp->inp_faddr;
241 
242 			th = (struct tcphdr *)(mtod(m, caddr_t) +
243 				sizeof(struct ip));
244 		}
245 		break;
246 #ifdef INET6
247 	case AF_INET6:
248 		{
249 			struct ip6_hdr *ip6;
250 
251 			ip6 = mtod(m, struct ip6_hdr *);
252 
253 			ip6->ip6_src = inp->inp_laddr6;
254 			ip6->ip6_dst = inp->inp_faddr6;
255 			ip6->ip6_flow = htonl(0x60000000) |
256 			    (inp->inp_flowinfo & IPV6_FLOWLABEL_MASK);
257 
258 			ip6->ip6_nxt = IPPROTO_TCP;
259 			ip6->ip6_plen = htons(sizeof(struct tcphdr)); /*XXX*/
260 			ip6->ip6_hlim = in6_selecthlim(inp);	/*XXX*/
261 
262 			th = (struct tcphdr *)(mtod(m, caddr_t) +
263 				sizeof(struct ip6_hdr));
264 		}
265 		break;
266 #endif /* INET6 */
267 	}
268 
269 	th->th_sport = inp->inp_lport;
270 	th->th_dport = inp->inp_fport;
271 	th->th_seq = 0;
272 	th->th_ack = 0;
273 	th->th_x2  = 0;
274 	th->th_off = 5;
275 	th->th_flags = 0;
276 	th->th_win = 0;
277 	th->th_urp = 0;
278 	th->th_sum = 0;
279 	return (m);
280 }
281 
282 /*
283  * Send a single message to the TCP at address specified by
284  * the given TCP/IP header.  If m == 0, then we make a copy
285  * of the tcpiphdr at ti and send directly to the addressed host.
286  * This is used to force keep alive messages out using the TCP
287  * template for a connection tp->t_template.  If flags are given
288  * then we send a message back to the TCP which originated the
289  * segment ti, and discard the mbuf containing it and any other
290  * attached mbufs.
291  *
292  * In any case the ack and sequence number of the transmitted
293  * segment are as specified by the parameters.
294  */
295 void
tcp_respond(struct tcpcb * tp,caddr_t template,struct tcphdr * th0,tcp_seq ack,tcp_seq seq,int flags,u_int rtableid,uint64_t now)296 tcp_respond(struct tcpcb *tp, caddr_t template, struct tcphdr *th0,
297     tcp_seq ack, tcp_seq seq, int flags, u_int rtableid, uint64_t now)
298 {
299 	int tlen;
300 	int win = 0;
301 	struct mbuf *m = NULL;
302 	struct tcphdr *th;
303 	struct ip *ip;
304 #ifdef INET6
305 	struct ip6_hdr *ip6;
306 #endif
307 	int af;		/* af on wire */
308 
309 	if (tp) {
310 		struct socket *so = tp->t_inpcb->inp_socket;
311 		win = sbspace(so, &so->so_rcv);
312 		/*
313 		 * If this is called with an unconnected
314 		 * socket/tp/pcb (tp->pf is 0), we lose.
315 		 */
316 		af = tp->pf;
317 	} else
318 		af = (((struct ip *)template)->ip_v == 6) ? AF_INET6 : AF_INET;
319 
320 	m = m_gethdr(M_DONTWAIT, MT_HEADER);
321 	if (m == NULL)
322 		return;
323 	m->m_data += max_linkhdr;
324 	tlen = 0;
325 
326 #define xchg(a,b,type) do { type t; t=a; a=b; b=t; } while (0)
327 	switch (af) {
328 #ifdef INET6
329 	case AF_INET6:
330 		ip6 = mtod(m, struct ip6_hdr *);
331 		th = (struct tcphdr *)(ip6 + 1);
332 		tlen = sizeof(*ip6) + sizeof(*th);
333 		if (th0) {
334 			memcpy(ip6, template, sizeof(*ip6));
335 			memcpy(th, th0, sizeof(*th));
336 			xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
337 		} else {
338 			memcpy(ip6, template, tlen);
339 		}
340 		break;
341 #endif /* INET6 */
342 	case AF_INET:
343 		ip = mtod(m, struct ip *);
344 		th = (struct tcphdr *)(ip + 1);
345 		tlen = sizeof(*ip) + sizeof(*th);
346 		if (th0) {
347 			memcpy(ip, template, sizeof(*ip));
348 			memcpy(th, th0, sizeof(*th));
349 			xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, u_int32_t);
350 		} else {
351 			memcpy(ip, template, tlen);
352 		}
353 		break;
354 	}
355 	if (th0)
356 		xchg(th->th_dport, th->th_sport, u_int16_t);
357 	else
358 		flags = TH_ACK;
359 #undef xchg
360 
361 	th->th_seq = htonl(seq);
362 	th->th_ack = htonl(ack);
363 	th->th_x2 = 0;
364 	th->th_off = sizeof (struct tcphdr) >> 2;
365 	th->th_flags = flags;
366 	if (tp)
367 		win >>= tp->rcv_scale;
368 	if (win > TCP_MAXWIN)
369 		win = TCP_MAXWIN;
370 	th->th_win = htons((u_int16_t)win);
371 	th->th_urp = 0;
372 
373 	if (tp && (tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
374 	    (flags & TH_RST) == 0 && (tp->t_flags & TF_RCVD_TSTMP)) {
375 		u_int32_t *lp = (u_int32_t *)(th + 1);
376 		/* Form timestamp option as shown in appendix A of RFC 1323. */
377 		*lp++ = htonl(TCPOPT_TSTAMP_HDR);
378 		*lp++ = htonl(now + tp->ts_modulate);
379 		*lp   = htonl(tp->ts_recent);
380 		tlen += TCPOLEN_TSTAMP_APPA;
381 		th->th_off = (sizeof(struct tcphdr) + TCPOLEN_TSTAMP_APPA) >> 2;
382 	}
383 
384 	m->m_len = tlen;
385 	m->m_pkthdr.len = tlen;
386 	m->m_pkthdr.ph_ifidx = 0;
387 	m->m_pkthdr.csum_flags |= M_TCP_CSUM_OUT;
388 
389 	/* force routing table */
390 	if (tp)
391 		m->m_pkthdr.ph_rtableid = tp->t_inpcb->inp_rtableid;
392 	else
393 		m->m_pkthdr.ph_rtableid = rtableid;
394 
395 	switch (af) {
396 #ifdef INET6
397 	case AF_INET6:
398 		ip6->ip6_flow = htonl(0x60000000);
399 		ip6->ip6_nxt  = IPPROTO_TCP;
400 		ip6->ip6_hlim = in6_selecthlim(tp ? tp->t_inpcb : NULL); /*XXX*/
401 		ip6->ip6_plen = tlen - sizeof(struct ip6_hdr);
402 		ip6->ip6_plen = htons(ip6->ip6_plen);
403 		ip6_output(m, tp ? tp->t_inpcb->inp_outputopts6 : NULL,
404 		    tp ? &tp->t_inpcb->inp_route : NULL,
405 		    0, NULL,
406 		    tp ? &tp->t_inpcb->inp_seclevel : NULL);
407 		break;
408 #endif /* INET6 */
409 	case AF_INET:
410 		ip->ip_len = htons(tlen);
411 		ip->ip_ttl = ip_defttl;
412 		ip->ip_tos = 0;
413 		ip_output(m, NULL,
414 		    tp ? &tp->t_inpcb->inp_route : NULL,
415 		    ip_mtudisc ? IP_MTUDISC : 0, NULL,
416 		    tp ? &tp->t_inpcb->inp_seclevel : NULL, 0);
417 		break;
418 	}
419 }
420 
421 /*
422  * Create a new TCP control block, making an
423  * empty reassembly queue and hooking it to the argument
424  * protocol control block.
425  */
426 struct tcpcb *
tcp_newtcpcb(struct inpcb * inp,int wait)427 tcp_newtcpcb(struct inpcb *inp, int wait)
428 {
429 	struct tcpcb *tp;
430 	int i;
431 
432 	tp = pool_get(&tcpcb_pool, (wait == M_WAIT ? PR_WAITOK : PR_NOWAIT) |
433 	    PR_ZERO);
434 	if (tp == NULL)
435 		return (NULL);
436 	TAILQ_INIT(&tp->t_segq);
437 	tp->t_maxseg = atomic_load_int(&tcp_mssdflt);
438 	tp->t_maxopd = 0;
439 
440 	tp->t_inpcb = inp;
441 	for (i = 0; i < TCPT_NTIMERS; i++)
442 		TCP_TIMER_INIT(tp, i);
443 	timeout_set_flags(&tp->t_timer_reaper, tcp_timer_reaper, tp,
444 	    KCLOCK_NONE, TIMEOUT_PROC | TIMEOUT_MPSAFE);
445 
446 	tp->sack_enable = atomic_load_int(&tcp_do_sack);
447 	tp->t_flags = atomic_load_int(&tcp_do_rfc1323) ?
448 	    (TF_REQ_SCALE|TF_REQ_TSTMP) : 0;
449 	/*
450 	 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
451 	 * rtt estimate.  Set rttvar so that srtt + 2 * rttvar gives
452 	 * reasonable initial retransmit time.
453 	 */
454 	tp->t_srtt = TCPTV_SRTTBASE;
455 	tp->t_rttvar = tcp_rttdflt <<
456 	    (TCP_RTTVAR_SHIFT + TCP_RTT_BASE_SHIFT - 1);
457 	tp->t_rttmin = TCPTV_MIN;
458 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
459 	    TCPTV_MIN, TCPTV_REXMTMAX);
460 	tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
461 	tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
462 
463 	tp->t_pmtud_mtu_sent = 0;
464 	tp->t_pmtud_mss_acked = 0;
465 
466 #ifdef INET6
467 	if (ISSET(inp->inp_flags, INP_IPV6)) {
468 		tp->pf = PF_INET6;
469 		inp->inp_ipv6.ip6_hlim = ip6_defhlim;
470 	} else
471 #endif
472 	{
473 		tp->pf = PF_INET;
474 		inp->inp_ip.ip_ttl = ip_defttl;
475 	}
476 
477 	inp->inp_ppcb = (caddr_t)tp;
478 	return (tp);
479 }
480 
481 /*
482  * Drop a TCP connection, reporting
483  * the specified error.  If connection is synchronized,
484  * then send a RST to peer.
485  */
486 struct tcpcb *
tcp_drop(struct tcpcb * tp,int errno)487 tcp_drop(struct tcpcb *tp, int errno)
488 {
489 	struct socket *so = tp->t_inpcb->inp_socket;
490 
491 	if (TCPS_HAVERCVDSYN(tp->t_state)) {
492 		tp->t_state = TCPS_CLOSED;
493 		(void) tcp_output(tp);
494 		tcpstat_inc(tcps_drops);
495 	} else
496 		tcpstat_inc(tcps_conndrops);
497 	if (errno == ETIMEDOUT && tp->t_softerror)
498 		errno = tp->t_softerror;
499 	so->so_error = errno;
500 	return (tcp_close(tp));
501 }
502 
503 /*
504  * Close a TCP control block:
505  *	discard all space held by the tcp
506  *	discard internet protocol block
507  *	wake up any sleepers
508  */
509 struct tcpcb *
tcp_close(struct tcpcb * tp)510 tcp_close(struct tcpcb *tp)
511 {
512 	struct inpcb *inp = tp->t_inpcb;
513 	struct socket *so = inp->inp_socket;
514 	struct sackhole *p, *q;
515 
516 	/* free the reassembly queue, if any */
517 	tcp_freeq(tp);
518 
519 	tcp_canceltimers(tp);
520 	syn_cache_cleanup(tp);
521 
522 	/* Free SACK holes. */
523 	q = p = tp->snd_holes;
524 	while (p != 0) {
525 		q = p->next;
526 		pool_put(&sackhl_pool, p);
527 		p = q;
528 	}
529 
530 	m_free(tp->t_template);
531 	/* Free tcpcb after all pending timers have been run. */
532 	timeout_add(&tp->t_timer_reaper, 0);
533 	inp->inp_ppcb = NULL;
534 	soisdisconnected(so);
535 	in_pcbdetach(inp);
536 	tcpstat_inc(tcps_closed);
537 	return (NULL);
538 }
539 
540 int
tcp_freeq(struct tcpcb * tp)541 tcp_freeq(struct tcpcb *tp)
542 {
543 	struct tcpqent *qe;
544 	int rv = 0;
545 
546 	while ((qe = TAILQ_FIRST(&tp->t_segq)) != NULL) {
547 		TAILQ_REMOVE(&tp->t_segq, qe, tcpqe_q);
548 		m_freem(qe->tcpqe_m);
549 		pool_put(&tcpqe_pool, qe);
550 		rv = 1;
551 	}
552 	return (rv);
553 }
554 
555 /*
556  * Compute proper scaling value for receiver window from buffer space
557  */
558 
559 void
tcp_rscale(struct tcpcb * tp,u_long hiwat)560 tcp_rscale(struct tcpcb *tp, u_long hiwat)
561 {
562 	tp->request_r_scale = 0;
563 	while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
564 	       TCP_MAXWIN << tp->request_r_scale < hiwat)
565 		tp->request_r_scale++;
566 }
567 
568 /*
569  * Notify a tcp user of an asynchronous error;
570  * store error as soft error, but wake up user
571  * (for now, won't do anything until can select for soft error).
572  */
573 void
tcp_notify(struct inpcb * inp,int error)574 tcp_notify(struct inpcb *inp, int error)
575 {
576 	struct tcpcb *tp = intotcpcb(inp);
577 	struct socket *so = inp->inp_socket;
578 
579 	/*
580 	 * Ignore some errors if we are hooked up.
581 	 * If connection hasn't completed, has retransmitted several times,
582 	 * and receives a second error, give up now.  This is better
583 	 * than waiting a long time to establish a connection that
584 	 * can never complete.
585 	 */
586 	if (tp->t_state == TCPS_ESTABLISHED &&
587 	     (error == EHOSTUNREACH || error == ENETUNREACH ||
588 	      error == EHOSTDOWN)) {
589 		return;
590 	} else if (TCPS_HAVEESTABLISHED(tp->t_state) == 0 &&
591 	    tp->t_rxtshift > 3 && tp->t_softerror)
592 		so->so_error = error;
593 	else
594 		tp->t_softerror = error;
595 	wakeup((caddr_t) &so->so_timeo);
596 	sorwakeup(so);
597 	sowwakeup(so);
598 }
599 
600 #ifdef INET6
601 void
tcp6_ctlinput(int cmd,struct sockaddr * sa,u_int rdomain,void * d)602 tcp6_ctlinput(int cmd, struct sockaddr *sa, u_int rdomain, void *d)
603 {
604 	struct tcphdr th;
605 	struct tcpcb *tp;
606 	void (*notify)(struct inpcb *, int) = tcp_notify;
607 	struct ip6_hdr *ip6;
608 	const struct sockaddr_in6 *sa6_src = NULL;
609 	struct sockaddr_in6 *sa6 = satosin6(sa);
610 	struct inpcb *inp;
611 	struct mbuf *m;
612 	tcp_seq seq;
613 	int off;
614 	struct {
615 		u_int16_t th_sport;
616 		u_int16_t th_dport;
617 		u_int32_t th_seq;
618 	} *thp;
619 
620 	CTASSERT(sizeof(*thp) <= sizeof(th));
621 	if (sa->sa_family != AF_INET6 ||
622 	    sa->sa_len != sizeof(struct sockaddr_in6) ||
623 	    IN6_IS_ADDR_UNSPECIFIED(&sa6->sin6_addr) ||
624 	    IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
625 		return;
626 	if ((unsigned)cmd >= PRC_NCMDS)
627 		return;
628 	else if (cmd == PRC_QUENCH) {
629 		/*
630 		 * Don't honor ICMP Source Quench messages meant for
631 		 * TCP connections.
632 		 */
633 		/* XXX there's no PRC_QUENCH in IPv6 */
634 		return;
635 	} else if (PRC_IS_REDIRECT(cmd))
636 		notify = in_rtchange, d = NULL;
637 	else if (cmd == PRC_MSGSIZE)
638 		; /* special code is present, see below */
639 	else if (cmd == PRC_HOSTDEAD)
640 		d = NULL;
641 	else if (inet6ctlerrmap[cmd] == 0)
642 		return;
643 
644 	/* if the parameter is from icmp6, decode it. */
645 	if (d != NULL) {
646 		struct ip6ctlparam *ip6cp = (struct ip6ctlparam *)d;
647 		m = ip6cp->ip6c_m;
648 		ip6 = ip6cp->ip6c_ip6;
649 		off = ip6cp->ip6c_off;
650 		sa6_src = ip6cp->ip6c_src;
651 	} else {
652 		m = NULL;
653 		ip6 = NULL;
654 		sa6_src = &sa6_any;
655 	}
656 
657 	if (ip6) {
658 		/*
659 		 * XXX: We assume that when ip6 is non NULL,
660 		 * M and OFF are valid.
661 		 */
662 
663 		/* check if we can safely examine src and dst ports */
664 		if (m->m_pkthdr.len < off + sizeof(*thp))
665 			return;
666 
667 		bzero(&th, sizeof(th));
668 		m_copydata(m, off, sizeof(*thp), &th);
669 
670 		/*
671 		 * Check to see if we have a valid TCP connection
672 		 * corresponding to the address in the ICMPv6 message
673 		 * payload.
674 		 */
675 		inp = in6_pcblookup(&tcb6table, &sa6->sin6_addr,
676 		    th.th_dport, &sa6_src->sin6_addr, th.th_sport, rdomain);
677 		if (cmd == PRC_MSGSIZE) {
678 			/*
679 			 * Depending on the value of "valid" and routing table
680 			 * size (mtudisc_{hi,lo}wat), we will:
681 			 * - recalculate the new MTU and create the
682 			 *   corresponding routing entry, or
683 			 * - ignore the MTU change notification.
684 			 */
685 			icmp6_mtudisc_update((struct ip6ctlparam *)d,
686 			    inp != NULL);
687 			in_pcbunref(inp);
688 			return;
689 		}
690 		if (inp) {
691 			seq = ntohl(th.th_seq);
692 			if ((tp = intotcpcb(inp)) &&
693 			    SEQ_GEQ(seq, tp->snd_una) &&
694 			    SEQ_LT(seq, tp->snd_max))
695 				notify(inp, inet6ctlerrmap[cmd]);
696 		} else if (inet6ctlerrmap[cmd] == EHOSTUNREACH ||
697 		    inet6ctlerrmap[cmd] == ENETUNREACH ||
698 		    inet6ctlerrmap[cmd] == EHOSTDOWN)
699 			syn_cache_unreach(sin6tosa_const(sa6_src), sa, &th,
700 			    rdomain);
701 		in_pcbunref(inp);
702 	} else {
703 		in6_pcbnotify(&tcb6table, sa6, 0,
704 		    sa6_src, 0, rdomain, cmd, NULL, notify);
705 	}
706 }
707 #endif
708 
709 void
tcp_ctlinput(int cmd,struct sockaddr * sa,u_int rdomain,void * v)710 tcp_ctlinput(int cmd, struct sockaddr *sa, u_int rdomain, void *v)
711 {
712 	struct ip *ip = v;
713 	struct tcphdr *th;
714 	struct tcpcb *tp;
715 	struct inpcb *inp;
716 	struct in_addr faddr;
717 	tcp_seq seq;
718 	u_int mtu;
719 	void (*notify)(struct inpcb *, int) = tcp_notify;
720 	int errno;
721 
722 	if (sa->sa_family != AF_INET)
723 		return;
724 	faddr = satosin(sa)->sin_addr;
725 	if (faddr.s_addr == INADDR_ANY)
726 		return;
727 
728 	if ((unsigned)cmd >= PRC_NCMDS)
729 		return;
730 	errno = inetctlerrmap[cmd];
731 	if (cmd == PRC_QUENCH)
732 		/*
733 		 * Don't honor ICMP Source Quench messages meant for
734 		 * TCP connections.
735 		 */
736 		return;
737 	else if (PRC_IS_REDIRECT(cmd))
738 		notify = in_rtchange, ip = 0;
739 	else if (cmd == PRC_MSGSIZE && ip_mtudisc && ip) {
740 		/*
741 		 * Verify that the packet in the icmp payload refers
742 		 * to an existing TCP connection.
743 		 */
744 		th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
745 		seq = ntohl(th->th_seq);
746 		inp = in_pcblookup(&tcbtable,
747 		    ip->ip_dst, th->th_dport, ip->ip_src, th->th_sport,
748 		    rdomain);
749 		if (inp && (tp = intotcpcb(inp)) &&
750 		    SEQ_GEQ(seq, tp->snd_una) &&
751 		    SEQ_LT(seq, tp->snd_max)) {
752 			struct icmp *icp;
753 			icp = (struct icmp *)((caddr_t)ip -
754 					      offsetof(struct icmp, icmp_ip));
755 
756 			/*
757 			 * If the ICMP message advertises a Next-Hop MTU
758 			 * equal or larger than the maximum packet size we have
759 			 * ever sent, drop the message.
760 			 */
761 			mtu = (u_int)ntohs(icp->icmp_nextmtu);
762 			if (mtu >= tp->t_pmtud_mtu_sent) {
763 				in_pcbunref(inp);
764 				return;
765 			}
766 			if (mtu >= tcp_hdrsz(tp) + tp->t_pmtud_mss_acked) {
767 				/*
768 				 * Calculate new MTU, and create corresponding
769 				 * route (traditional PMTUD).
770 				 */
771 				tp->t_flags &= ~TF_PMTUD_PEND;
772 				icmp_mtudisc(icp, inp->inp_rtableid);
773 			} else {
774 				/*
775 				 * Record the information got in the ICMP
776 				 * message; act on it later.
777 				 * If we had already recorded an ICMP message,
778 				 * replace the old one only if the new message
779 				 * refers to an older TCP segment
780 				 */
781 				if (tp->t_flags & TF_PMTUD_PEND) {
782 					if (SEQ_LT(tp->t_pmtud_th_seq, seq)) {
783 						in_pcbunref(inp);
784 						return;
785 					}
786 				} else
787 					tp->t_flags |= TF_PMTUD_PEND;
788 				tp->t_pmtud_th_seq = seq;
789 				tp->t_pmtud_nextmtu = icp->icmp_nextmtu;
790 				tp->t_pmtud_ip_len = icp->icmp_ip.ip_len;
791 				tp->t_pmtud_ip_hl = icp->icmp_ip.ip_hl;
792 				in_pcbunref(inp);
793 				return;
794 			}
795 		} else {
796 			/* ignore if we don't have a matching connection */
797 			in_pcbunref(inp);
798 			return;
799 		}
800 		in_pcbunref(inp);
801 		notify = tcp_mtudisc, ip = 0;
802 	} else if (cmd == PRC_MTUINC)
803 		notify = tcp_mtudisc_increase, ip = 0;
804 	else if (cmd == PRC_HOSTDEAD)
805 		ip = 0;
806 	else if (errno == 0)
807 		return;
808 
809 	if (ip) {
810 		th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
811 		inp = in_pcblookup(&tcbtable,
812 		    ip->ip_dst, th->th_dport, ip->ip_src, th->th_sport,
813 		    rdomain);
814 		if (inp) {
815 			seq = ntohl(th->th_seq);
816 			if ((tp = intotcpcb(inp)) &&
817 			    SEQ_GEQ(seq, tp->snd_una) &&
818 			    SEQ_LT(seq, tp->snd_max))
819 				notify(inp, errno);
820 		} else if (inetctlerrmap[cmd] == EHOSTUNREACH ||
821 		    inetctlerrmap[cmd] == ENETUNREACH ||
822 		    inetctlerrmap[cmd] == EHOSTDOWN) {
823 			struct sockaddr_in sin;
824 
825 			bzero(&sin, sizeof(sin));
826 			sin.sin_len = sizeof(sin);
827 			sin.sin_family = AF_INET;
828 			sin.sin_port = th->th_sport;
829 			sin.sin_addr = ip->ip_src;
830 			syn_cache_unreach(sintosa(&sin), sa, th, rdomain);
831 		}
832 		in_pcbunref(inp);
833 	} else
834 		in_pcbnotifyall(&tcbtable, satosin(sa), rdomain, errno, notify);
835 }
836 
837 
838 #ifdef INET6
839 /*
840  * Path MTU Discovery handlers.
841  */
842 void
tcp6_mtudisc_callback(struct sockaddr_in6 * sin6,u_int rdomain)843 tcp6_mtudisc_callback(struct sockaddr_in6 *sin6, u_int rdomain)
844 {
845 	in6_pcbnotify(&tcb6table, sin6, 0,
846 	    &sa6_any, 0, rdomain, PRC_MSGSIZE, NULL, tcp_mtudisc);
847 }
848 #endif /* INET6 */
849 
850 /*
851  * On receipt of path MTU corrections, flush old route and replace it
852  * with the new one.  Retransmit all unacknowledged packets, to ensure
853  * that all packets will be received.
854  */
855 void
tcp_mtudisc(struct inpcb * inp,int errno)856 tcp_mtudisc(struct inpcb *inp, int errno)
857 {
858 	struct tcpcb *tp = intotcpcb(inp);
859 	struct rtentry *rt;
860 	int orig_maxseg, change = 0;
861 
862 	if (tp == NULL)
863 		return;
864 	orig_maxseg = tp->t_maxseg;
865 
866 	rt = in_pcbrtentry(inp);
867 	if (rt != NULL) {
868 		unsigned int orig_mtulock = (rt->rt_locks & RTV_MTU);
869 
870 		/*
871 		 * If this was not a host route, remove and realloc.
872 		 */
873 		if ((rt->rt_flags & RTF_HOST) == 0) {
874 			in_rtchange(inp, errno);
875 			if ((rt = in_pcbrtentry(inp)) == NULL)
876 				return;
877 		}
878 		if (orig_mtulock < (rt->rt_locks & RTV_MTU))
879 			change = 1;
880 	}
881 	tcp_mss(tp, -1);
882 	if (orig_maxseg > tp->t_maxseg)
883 		change = 1;
884 
885 	/*
886 	 * Resend unacknowledged packets
887 	 */
888 	tp->snd_nxt = tp->snd_una;
889 	if (change || errno > 0)
890 		tcp_output(tp);
891 }
892 
893 void
tcp_mtudisc_increase(struct inpcb * inp,int errno)894 tcp_mtudisc_increase(struct inpcb *inp, int errno)
895 {
896 	struct tcpcb *tp = intotcpcb(inp);
897 	struct rtentry *rt = in_pcbrtentry(inp);
898 
899 	if (tp != 0 && rt != 0) {
900 		/*
901 		 * If this was a host route, remove and realloc.
902 		 */
903 		if (rt->rt_flags & RTF_HOST)
904 			in_rtchange(inp, errno);
905 
906 		/* also takes care of congestion window */
907 		tcp_mss(tp, -1);
908 	}
909 }
910 
911 /*
912  * Generate new ISNs with a method based on RFC1948
913  */
914 #define TCP_ISS_CONN_INC 4096
915 
916 void
tcp_set_iss_tsm(struct tcpcb * tp)917 tcp_set_iss_tsm(struct tcpcb *tp)
918 {
919 	SHA2_CTX ctx;
920 	union {
921 		uint8_t bytes[SHA512_DIGEST_LENGTH];
922 		uint32_t words[2];
923 	} digest;
924 	u_int rdomain = rtable_l2(tp->t_inpcb->inp_rtableid);
925 	tcp_seq iss;
926 
927 	mtx_enter(&tcp_timer_mtx);
928 	tcp_iss += TCP_ISS_CONN_INC;
929 	iss = tcp_iss;
930 	mtx_leave(&tcp_timer_mtx);
931 
932 	ctx = tcp_secret_ctx;
933 	SHA512Update(&ctx, &rdomain, sizeof(rdomain));
934 	SHA512Update(&ctx, &tp->t_inpcb->inp_lport, sizeof(u_short));
935 	SHA512Update(&ctx, &tp->t_inpcb->inp_fport, sizeof(u_short));
936 	if (tp->pf == AF_INET6) {
937 		SHA512Update(&ctx, &tp->t_inpcb->inp_laddr6,
938 		    sizeof(struct in6_addr));
939 		SHA512Update(&ctx, &tp->t_inpcb->inp_faddr6,
940 		    sizeof(struct in6_addr));
941 	} else {
942 		SHA512Update(&ctx, &tp->t_inpcb->inp_laddr,
943 		    sizeof(struct in_addr));
944 		SHA512Update(&ctx, &tp->t_inpcb->inp_faddr,
945 		    sizeof(struct in_addr));
946 	}
947 	SHA512Final(digest.bytes, &ctx);
948 	tp->iss = digest.words[0] + iss;
949 	tp->ts_modulate = digest.words[1];
950 }
951 
952 #ifdef TCP_SIGNATURE
953 int
tcp_signature_tdb_attach(void)954 tcp_signature_tdb_attach(void)
955 {
956 	return (0);
957 }
958 
959 int
tcp_signature_tdb_init(struct tdb * tdbp,const struct xformsw * xsp,struct ipsecinit * ii)960 tcp_signature_tdb_init(struct tdb *tdbp, const struct xformsw *xsp,
961     struct ipsecinit *ii)
962 {
963 	if ((ii->ii_authkeylen < 1) || (ii->ii_authkeylen > 80))
964 		return (EINVAL);
965 
966 	tdbp->tdb_amxkey = malloc(ii->ii_authkeylen, M_XDATA, M_NOWAIT);
967 	if (tdbp->tdb_amxkey == NULL)
968 		return (ENOMEM);
969 	memcpy(tdbp->tdb_amxkey, ii->ii_authkey, ii->ii_authkeylen);
970 	tdbp->tdb_amxkeylen = ii->ii_authkeylen;
971 
972 	return (0);
973 }
974 
975 int
tcp_signature_tdb_zeroize(struct tdb * tdbp)976 tcp_signature_tdb_zeroize(struct tdb *tdbp)
977 {
978 	if (tdbp->tdb_amxkey) {
979 		explicit_bzero(tdbp->tdb_amxkey, tdbp->tdb_amxkeylen);
980 		free(tdbp->tdb_amxkey, M_XDATA, tdbp->tdb_amxkeylen);
981 		tdbp->tdb_amxkey = NULL;
982 	}
983 
984 	return (0);
985 }
986 
987 int
tcp_signature_tdb_input(struct mbuf ** mp,struct tdb * tdbp,int skip,int protoff)988 tcp_signature_tdb_input(struct mbuf **mp, struct tdb *tdbp, int skip,
989     int protoff)
990 {
991 	m_freemp(mp);
992 	return (IPPROTO_DONE);
993 }
994 
995 int
tcp_signature_tdb_output(struct mbuf * m,struct tdb * tdbp,int skip,int protoff)996 tcp_signature_tdb_output(struct mbuf *m, struct tdb *tdbp, int skip,
997     int protoff)
998 {
999 	m_freem(m);
1000 	return (EINVAL);
1001 }
1002 
1003 int
tcp_signature_apply(caddr_t fstate,caddr_t data,unsigned int len)1004 tcp_signature_apply(caddr_t fstate, caddr_t data, unsigned int len)
1005 {
1006 	MD5Update((MD5_CTX *)fstate, (char *)data, len);
1007 	return 0;
1008 }
1009 
1010 int
tcp_signature(struct tdb * tdb,int af,struct mbuf * m,struct tcphdr * th,int iphlen,int doswap,char * sig)1011 tcp_signature(struct tdb *tdb, int af, struct mbuf *m, struct tcphdr *th,
1012     int iphlen, int doswap, char *sig)
1013 {
1014 	MD5_CTX ctx;
1015 	int len;
1016 	struct tcphdr th0;
1017 
1018 	MD5Init(&ctx);
1019 
1020 	switch(af) {
1021 	case 0:
1022 	case AF_INET: {
1023 		struct ippseudo ippseudo;
1024 		struct ip *ip;
1025 
1026 		ip = mtod(m, struct ip *);
1027 
1028 		ippseudo.ippseudo_src = ip->ip_src;
1029 		ippseudo.ippseudo_dst = ip->ip_dst;
1030 		ippseudo.ippseudo_pad = 0;
1031 		ippseudo.ippseudo_p = IPPROTO_TCP;
1032 		ippseudo.ippseudo_len = htons(m->m_pkthdr.len - iphlen);
1033 
1034 		MD5Update(&ctx, (char *)&ippseudo,
1035 		    sizeof(struct ippseudo));
1036 		break;
1037 		}
1038 #ifdef INET6
1039 	case AF_INET6: {
1040 		struct ip6_hdr_pseudo ip6pseudo;
1041 		struct ip6_hdr *ip6;
1042 
1043 		ip6 = mtod(m, struct ip6_hdr *);
1044 		bzero(&ip6pseudo, sizeof(ip6pseudo));
1045 		ip6pseudo.ip6ph_src = ip6->ip6_src;
1046 		ip6pseudo.ip6ph_dst = ip6->ip6_dst;
1047 		in6_clearscope(&ip6pseudo.ip6ph_src);
1048 		in6_clearscope(&ip6pseudo.ip6ph_dst);
1049 		ip6pseudo.ip6ph_nxt = IPPROTO_TCP;
1050 		ip6pseudo.ip6ph_len = htonl(m->m_pkthdr.len - iphlen);
1051 
1052 		MD5Update(&ctx, (char *)&ip6pseudo,
1053 		    sizeof(ip6pseudo));
1054 		break;
1055 		}
1056 #endif
1057 	}
1058 
1059 	th0 = *th;
1060 	th0.th_sum = 0;
1061 
1062 	if (doswap) {
1063 		th0.th_seq = htonl(th0.th_seq);
1064 		th0.th_ack = htonl(th0.th_ack);
1065 		th0.th_win = htons(th0.th_win);
1066 		th0.th_urp = htons(th0.th_urp);
1067 	}
1068 	MD5Update(&ctx, (char *)&th0, sizeof(th0));
1069 
1070 	len = m->m_pkthdr.len - iphlen - th->th_off * sizeof(uint32_t);
1071 
1072 	if (len > 0 &&
1073 	    m_apply(m, iphlen + th->th_off * sizeof(uint32_t), len,
1074 	    tcp_signature_apply, (caddr_t)&ctx))
1075 		return (-1);
1076 
1077 	MD5Update(&ctx, tdb->tdb_amxkey, tdb->tdb_amxkeylen);
1078 	MD5Final(sig, &ctx);
1079 
1080 	return (0);
1081 }
1082 #endif /* TCP_SIGNATURE */
1083