1 /*-
2  * Copyright (c) 2016-2020 Netflix, Inc.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23  * SUCH DAMAGE.
24  *
25  */
26 /*
27  * Author: Randall Stewart <rrs@netflix.com>
28  * This work is based on the ACM Queue paper
29  * BBR - Congestion Based Congestion Control
30  * and also numerous discussions with Neal, Yuchung and Van.
31  */
32 
33 #include <sys/cdefs.h>
34 #include "opt_inet.h"
35 #include "opt_inet6.h"
36 #include "opt_ipsec.h"
37 #include "opt_ratelimit.h"
38 #include <sys/param.h>
39 #include <sys/arb.h>
40 #include <sys/module.h>
41 #include <sys/kernel.h>
42 #ifdef TCP_HHOOK
43 #include <sys/hhook.h>
44 #endif
45 #include <sys/malloc.h>
46 #include <sys/mbuf.h>
47 #include <sys/proc.h>
48 #include <sys/qmath.h>
49 #include <sys/socket.h>
50 #include <sys/socketvar.h>
51 #include <sys/sysctl.h>
52 #include <sys/systm.h>
53 #include <sys/tree.h>
54 #ifdef NETFLIX_STATS
55 #include <sys/stats.h> /* Must come after qmath.h and tree.h */
56 #endif
57 #include <sys/refcount.h>
58 #include <sys/queue.h>
59 #include <sys/smp.h>
60 #include <sys/kthread.h>
61 #include <sys/lock.h>
62 #include <sys/mutex.h>
63 #include <sys/tim_filter.h>
64 #include <sys/time.h>
65 #include <vm/uma.h>
66 #include <sys/kern_prefetch.h>
67 
68 #include <net/route.h>
69 #include <net/vnet.h>
70 #include <net/ethernet.h>
71 #include <net/bpf.h>
72 
73 #define TCPSTATES		/* for logging */
74 
75 #include <netinet/in.h>
76 #include <netinet/in_kdtrace.h>
77 #include <netinet/in_pcb.h>
78 #include <netinet/ip.h>
79 #include <netinet/ip_icmp.h>	/* required for icmp_var.h */
80 #include <netinet/icmp_var.h>	/* for ICMP_BANDLIM */
81 #include <netinet/ip_var.h>
82 #include <netinet/ip6.h>
83 #include <netinet6/in6_pcb.h>
84 #include <netinet6/ip6_var.h>
85 #include <netinet/tcp.h>
86 #include <netinet/tcp_fsm.h>
87 #include <netinet/tcp_seq.h>
88 #include <netinet/tcp_timer.h>
89 #include <netinet/tcp_var.h>
90 #include <netinet/tcpip.h>
91 #include <netinet/tcp_ecn.h>
92 #include <netinet/tcp_hpts.h>
93 #include <netinet/tcp_lro.h>
94 #include <netinet/cc/cc.h>
95 #include <netinet/tcp_log_buf.h>
96 #ifdef TCP_OFFLOAD
97 #include <netinet/tcp_offload.h>
98 #endif
99 #ifdef INET6
100 #include <netinet6/tcp6_var.h>
101 #endif
102 #include <netinet/tcp_fastopen.h>
103 
104 #include <netipsec/ipsec_support.h>
105 #include <net/if.h>
106 #include <net/if_var.h>
107 #include <net/if_private.h>
108 
109 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
110 #include <netipsec/ipsec.h>
111 #include <netipsec/ipsec6.h>
112 #endif				/* IPSEC */
113 
114 #include <netinet/udp.h>
115 #include <netinet/udp_var.h>
116 #include <machine/in_cksum.h>
117 
118 #ifdef MAC
119 #include <security/mac/mac_framework.h>
120 #endif
121 #include "rack_bbr_common.h"
122 
123 /*
124  * Common TCP Functions - These are shared by borth
125  * rack and BBR.
126  */
127 static int
ctf_get_enet_type(struct ifnet * ifp,struct mbuf * m)128 ctf_get_enet_type(struct ifnet *ifp, struct mbuf *m)
129 {
130 	struct ether_header *eh;
131 #ifdef INET6
132 	struct ip6_hdr *ip6 = NULL;	/* Keep compiler happy. */
133 #endif
134 #ifdef INET
135 	struct ip *ip = NULL;		/* Keep compiler happy. */
136 #endif
137 #if defined(INET) || defined(INET6)
138 	struct tcphdr *th;
139 	int32_t tlen;
140 	uint16_t drop_hdrlen;
141 #endif
142 	uint16_t etype;
143 #ifdef INET
144 	uint8_t iptos;
145 #endif
146 
147 	/* Is it the easy way? */
148 	if (m->m_flags & M_LRO_EHDRSTRP)
149 		return (m->m_pkthdr.lro_etype);
150 	/*
151 	 * Ok this is the old style call, the ethernet header is here.
152 	 * This also means no checksum or BPF were done. This
153 	 * can happen if the race to setup the inp fails and
154 	 * LRO sees no INP at packet input, but by the time
155 	 * we queue the packets an INP gets there. Its rare
156 	 * but it can occur so we will handle it. Note that
157 	 * this means duplicated work but with the rarity of it
158 	 * its not worth worrying about.
159 	 */
160 	/* Let the BPF see the packet */
161 	if (bpf_peers_present(ifp->if_bpf))
162 		ETHER_BPF_MTAP(ifp, m);
163 	/* Now the csum */
164 	eh = mtod(m, struct ether_header *);
165 	etype = ntohs(eh->ether_type);
166 	m_adj(m,  sizeof(*eh));
167 	switch (etype) {
168 #ifdef INET6
169 		case ETHERTYPE_IPV6:
170 		{
171 			if (m->m_len < (sizeof(*ip6) + sizeof(*th))) {
172 				m = m_pullup(m, sizeof(*ip6) + sizeof(*th));
173 				if (m == NULL) {
174 					KMOD_TCPSTAT_INC(tcps_rcvshort);
175 					return (-1);
176 				}
177 			}
178 			ip6 = (struct ip6_hdr *)(eh + 1);
179 			th = (struct tcphdr *)(ip6 + 1);
180 			drop_hdrlen = sizeof(*ip6);
181 			tlen = ntohs(ip6->ip6_plen);
182 			if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID_IPV6) {
183 				if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
184 					th->th_sum = m->m_pkthdr.csum_data;
185 				else
186 					th->th_sum = in6_cksum_pseudo(ip6, tlen,
187 								      IPPROTO_TCP,
188 								      m->m_pkthdr.csum_data);
189 				th->th_sum ^= 0xffff;
190 			} else
191 				th->th_sum = in6_cksum(m, IPPROTO_TCP, drop_hdrlen, tlen);
192 			if (th->th_sum) {
193 				KMOD_TCPSTAT_INC(tcps_rcvbadsum);
194 				m_freem(m);
195 				return (-1);
196 			}
197 			return (etype);
198 		}
199 #endif
200 #ifdef INET
201 		case ETHERTYPE_IP:
202 		{
203 			if (m->m_len < sizeof (struct tcpiphdr)) {
204 				m = m_pullup(m, sizeof (struct tcpiphdr));
205 				if (m == NULL) {
206 					KMOD_TCPSTAT_INC(tcps_rcvshort);
207 					return (-1);
208 				}
209 			}
210 			ip = (struct ip *)(eh + 1);
211 			th = (struct tcphdr *)(ip + 1);
212 			drop_hdrlen = sizeof(*ip);
213 			iptos = ip->ip_tos;
214 			tlen = ntohs(ip->ip_len) - sizeof(struct ip);
215 			if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
216 				if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
217 					th->th_sum = m->m_pkthdr.csum_data;
218 				else
219 					th->th_sum = in_pseudo(ip->ip_src.s_addr,
220 							       ip->ip_dst.s_addr,
221 							       htonl(m->m_pkthdr.csum_data + tlen + IPPROTO_TCP));
222 				th->th_sum ^= 0xffff;
223 			} else {
224 				int len;
225 				struct ipovly *ipov = (struct ipovly *)ip;
226 				/*
227 				 * Checksum extended TCP header and data.
228 				 */
229 				len = drop_hdrlen + tlen;
230 				bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
231 				ipov->ih_len = htons(tlen);
232 				th->th_sum = in_cksum(m, len);
233 				/* Reset length for SDT probes. */
234 				ip->ip_len = htons(len);
235 				/* Reset TOS bits */
236 				ip->ip_tos = iptos;
237 				/* Re-initialization for later version check */
238 				ip->ip_v = IPVERSION;
239 				ip->ip_hl = sizeof(*ip) >> 2;
240 			}
241 			if (th->th_sum) {
242 				KMOD_TCPSTAT_INC(tcps_rcvbadsum);
243 				m_freem(m);
244 				return (-1);
245 			}
246 			break;
247 		}
248 #endif
249 	};
250 	return (etype);
251 }
252 
253 /*
254  * The function ctf_process_inbound_raw() is used by
255  * transport developers to do the steps needed to
256  * support MBUF Queuing i.e. the flags in
257  * inp->inp_flags2:
258  *
259  * - INP_SUPPORTS_MBUFQ
260  * - INP_MBUF_QUEUE_READY
261  * - INP_DONT_SACK_QUEUE
262  * - INP_MBUF_ACKCMP
263  *
264  * These flags help control how LRO will deliver
265  * packets to the transport. You first set in inp_flags2
266  * the INP_SUPPORTS_MBUFQ to tell the LRO code that you
267  * will gladly take a queue of packets instead of a compressed
268  * single packet. You also set in your t_fb pointer the
269  * tfb_do_queued_segments to point to ctf_process_inbound_raw.
270  *
271  * This then gets you lists of inbound ACK's/Data instead
272  * of a condensed compressed ACK/DATA packet. Why would you
273  * want that? This will get you access to all the arrival
274  * times of at least LRO and possibly at the Hardware (if
275  * the interface card supports that) of the actual ACK/DATA.
276  * In some transport designs this is important since knowing
277  * the actual time we got the packet is useful information.
278  *
279  * A new special type of mbuf may also be supported by the transport
280  * if it has set the INP_MBUF_ACKCMP flag. If its set, LRO will
281  * possibly create a M_ACKCMP type mbuf. This is a mbuf with
282  * an array of "acks". One thing also to note is that when this
283  * occurs a subsequent LRO may find at the back of the untouched
284  * mbuf queue chain a M_ACKCMP and append on to it. This means
285  * that until the transport pulls in the mbuf chain queued
286  * for it more ack's may get on the mbufs that were already
287  * delivered. There currently is a limit of 6 acks condensed
288  * into 1 mbuf which means often when this is occuring, we
289  * don't get that effect but it does happen.
290  *
291  * Now there are some interesting Caveats that the transport
292  * designer needs to take into account when using this feature.
293  *
294  * 1) It is used with HPTS and pacing, when the pacing timer
295  *    for output calls it will first call the input.
296  * 2) When you set INP_MBUF_QUEUE_READY this tells LRO
297  *    queue normal packets, I am busy pacing out data and
298  *    will process the queued packets before my tfb_tcp_output
299  *    call from pacing. If a non-normal packet arrives, (e.g. sack)
300  *    you will be awoken immediately.
301  * 3) Finally you can add the INP_DONT_SACK_QUEUE to not even
302  *    be awoken if a SACK has arrived. You would do this when
303  *    you were not only running a pacing for output timer
304  *    but a Rack timer as well i.e. you know you are in recovery
305  *    and are in the process (via the timers) of dealing with
306  *    the loss.
307  *
308  * Now a critical thing you must be aware of here is that the
309  * use of the flags has a far greater scope then just your
310  * typical LRO. Why? Well thats because in the normal compressed
311  * LRO case at the end of a driver interupt all packets are going
312  * to get presented to the transport no matter if there is one
313  * or 100. With the MBUF_QUEUE model, this is not true. You will
314  * only be awoken to process the queue of packets when:
315  *     a) The flags discussed above allow it.
316  *          <or>
317  *     b) You exceed a ack or data limit (by default the
318  *        ack limit is infinity (64k acks) and the data
319  *        limit is 64k of new TCP data)
320  *         <or>
321  *     c) The push bit has been set by the peer
322  */
323 
324 static int
ctf_process_inbound_raw(struct tcpcb * tp,struct mbuf * m,int has_pkt)325 ctf_process_inbound_raw(struct tcpcb *tp, struct mbuf *m, int has_pkt)
326 {
327 	/*
328 	 * We are passed a raw change of mbuf packets
329 	 * that arrived in LRO. They are linked via
330 	 * the m_nextpkt link in the pkt-headers.
331 	 *
332 	 * We process each one by:
333 	 * a) saving off the next
334 	 * b) stripping off the ether-header
335 	 * c) formulating the arguments for tfb_do_segment_nounlock()
336 	 * d) calling each mbuf to tfb_do_segment_nounlock()
337 	 *    after adjusting the time to match the arrival time.
338 	 * Note that the LRO code assures no IP options are present.
339 	 *
340 	 * The symantics for calling tfb_do_segment_nounlock() are the
341 	 * following:
342 	 * 1) It returns 0 if all went well and you (the caller) need
343 	 *    to release the lock.
344 	 * 2) If nxt_pkt is set, then the function will surpress calls
345 	 *    to tcp_output() since you are promising to call again
346 	 *    with another packet.
347 	 * 3) If it returns 1, then you must free all the packets being
348 	 *    shipped in, the tcb has been destroyed (or about to be destroyed).
349 	 */
350 	struct mbuf *m_save;
351 	struct tcphdr *th;
352 #ifdef INET6
353 	struct ip6_hdr *ip6 = NULL;	/* Keep compiler happy. */
354 #endif
355 #ifdef INET
356 	struct ip *ip = NULL;		/* Keep compiler happy. */
357 #endif
358 	struct ifnet *ifp;
359 	struct timeval tv;
360 	struct inpcb *inp __diagused;
361 	int32_t retval, nxt_pkt, tlen, off;
362 	int etype = 0;
363 	uint16_t drop_hdrlen;
364 	uint8_t iptos, no_vn=0;
365 
366 	inp = tptoinpcb(tp);
367 	INP_WLOCK_ASSERT(inp);
368 	NET_EPOCH_ASSERT();
369 
370 	if (m)
371 		ifp = m_rcvif(m);
372 	else
373 		ifp = NULL;
374 	if (ifp == NULL) {
375 		/*
376 		 * We probably should not work around
377 		 * but kassert, since lro alwasy sets rcvif.
378 		 */
379 		no_vn = 1;
380 		goto skip_vnet;
381 	}
382 	CURVNET_SET(ifp->if_vnet);
383 skip_vnet:
384 	tcp_get_usecs(&tv);
385 	while (m) {
386 		m_save = m->m_nextpkt;
387 		m->m_nextpkt = NULL;
388 		if ((m->m_flags & M_ACKCMP) == 0) {
389 			/* Now lets get the ether header */
390 			etype = ctf_get_enet_type(ifp, m);
391 			if (etype == -1) {
392 				/* Skip this packet it was freed by checksum */
393 				goto skipped_pkt;
394 			}
395 			KASSERT(((etype == ETHERTYPE_IPV6) || (etype == ETHERTYPE_IP)),
396 				("tp:%p m:%p etype:0x%x -- not IP or IPv6", tp, m, etype));
397 			/* Trim off the ethernet header */
398 			switch (etype) {
399 #ifdef INET6
400 			case ETHERTYPE_IPV6:
401 				ip6 = mtod(m, struct ip6_hdr *);
402 				th = (struct tcphdr *)(ip6 + 1);
403 				tlen = ntohs(ip6->ip6_plen);
404 				drop_hdrlen = sizeof(*ip6);
405 				iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
406 				break;
407 #endif
408 #ifdef INET
409 			case ETHERTYPE_IP:
410 				ip = mtod(m, struct ip *);
411 				th = (struct tcphdr *)(ip + 1);
412 				drop_hdrlen = sizeof(*ip);
413 				iptos = ip->ip_tos;
414 				tlen = ntohs(ip->ip_len) - sizeof(struct ip);
415 				break;
416 #endif
417 			} /* end switch */
418 			off = th->th_off << 2;
419 			if (off < sizeof (struct tcphdr) || off > tlen) {
420 				printf("off:%d < hdrlen:%zu || > tlen:%u -- dump\n",
421 				       off,
422 				       sizeof(struct tcphdr),
423 				       tlen);
424 				KMOD_TCPSTAT_INC(tcps_rcvbadoff);
425 				m_freem(m);
426 				goto skipped_pkt;
427 			}
428 			tlen -= off;
429 			drop_hdrlen += off;
430 			/*
431 			 * Now lets setup the timeval to be when we should
432 			 * have been called (if we can).
433 			 */
434 			m->m_pkthdr.lro_nsegs = 1;
435 			/* Now what about next packet? */
436 		} else {
437 			/*
438 			 * This mbuf is an array of acks that have
439 			 * been compressed. We assert the inp has
440 			 * the flag set to enable this!
441 			 */
442 			KASSERT((tp->t_flags2 & TF2_MBUF_ACKCMP),
443 			    ("tp:%p no TF2_MBUF_ACKCMP flags?", tp));
444 			tlen = 0;
445 			drop_hdrlen = 0;
446 			th = NULL;
447 			iptos = 0;
448 		}
449 		tcp_get_usecs(&tv);
450 		if (m_save || has_pkt)
451 			nxt_pkt = 1;
452 		else
453 			nxt_pkt = 0;
454 		if ((m->m_flags & M_ACKCMP) == 0)
455 			KMOD_TCPSTAT_INC(tcps_rcvtotal);
456 		else
457 			KMOD_TCPSTAT_ADD(tcps_rcvtotal, (m->m_len / sizeof(struct tcp_ackent)));
458 		retval = (*tp->t_fb->tfb_do_segment_nounlock)(tp, m, th,
459 		    drop_hdrlen, tlen, iptos, nxt_pkt, &tv);
460 		if (retval) {
461 			/* We lost the lock and tcb probably */
462 			m = m_save;
463 			while(m) {
464 				m_save = m->m_nextpkt;
465 				m->m_nextpkt = NULL;
466 				m_freem(m);
467 				m = m_save;
468 			}
469 			if (no_vn == 0) {
470 				CURVNET_RESTORE();
471 			}
472 			INP_UNLOCK_ASSERT(inp);
473 			return(retval);
474 		}
475 skipped_pkt:
476 		m = m_save;
477 	}
478 	if (no_vn == 0) {
479 		CURVNET_RESTORE();
480 	}
481 	return(retval);
482 }
483 
484 int
ctf_do_queued_segments(struct tcpcb * tp,int have_pkt)485 ctf_do_queued_segments(struct tcpcb *tp, int have_pkt)
486 {
487 	struct mbuf *m;
488 
489 	/* First lets see if we have old packets */
490 	if ((m = STAILQ_FIRST(&tp->t_inqueue)) != NULL) {
491 		STAILQ_INIT(&tp->t_inqueue);
492 		if (ctf_process_inbound_raw(tp, m, have_pkt)) {
493 			/* We lost the tcpcb (maybe a RST came in)? */
494 			return(1);
495 		}
496 	}
497 	return (0);
498 }
499 
500 uint32_t
ctf_outstanding(struct tcpcb * tp)501 ctf_outstanding(struct tcpcb *tp)
502 {
503 	uint32_t bytes_out;
504 
505 	bytes_out = tp->snd_max - tp->snd_una;
506 	if (tp->t_state < TCPS_ESTABLISHED)
507 		bytes_out++;
508 	if (tp->t_flags & TF_SENTFIN)
509 		bytes_out++;
510 	return (bytes_out);
511 }
512 
513 uint32_t
ctf_flight_size(struct tcpcb * tp,uint32_t rc_sacked)514 ctf_flight_size(struct tcpcb *tp, uint32_t rc_sacked)
515 {
516 	if (rc_sacked <= ctf_outstanding(tp))
517 		return(ctf_outstanding(tp) - rc_sacked);
518 	else {
519 		return (0);
520 	}
521 }
522 
523 void
ctf_do_dropwithreset(struct mbuf * m,struct tcpcb * tp,struct tcphdr * th,int32_t rstreason,int32_t tlen)524 ctf_do_dropwithreset(struct mbuf *m, struct tcpcb *tp, struct tcphdr *th,
525     int32_t rstreason, int32_t tlen)
526 {
527 	if (tp != NULL) {
528 		tcp_dropwithreset(m, th, tp, tlen, rstreason);
529 		INP_WUNLOCK(tptoinpcb(tp));
530 	} else
531 		tcp_dropwithreset(m, th, NULL, tlen, rstreason);
532 }
533 
534 void
ctf_ack_war_checks(struct tcpcb * tp,uint32_t * ts,uint32_t * cnt)535 ctf_ack_war_checks(struct tcpcb *tp, uint32_t *ts, uint32_t *cnt)
536 {
537 	if ((ts != NULL) && (cnt != NULL) &&
538 	    (tcp_ack_war_time_window > 0) &&
539 	    (tcp_ack_war_cnt > 0)) {
540 		/* We are possibly doing ack war prevention */
541 		uint32_t cts;
542 
543 		/*
544 		 * We use a msec tick here which gives us
545 		 * roughly 49 days. We don't need the
546 		 * precision of a microsecond timestamp which
547 		 * would only give us hours.
548 		 */
549 		cts = tcp_ts_getticks();
550 		if (TSTMP_LT((*ts), cts)) {
551 			/* Timestamp is in the past */
552 			*cnt = 0;
553 			*ts = (cts + tcp_ack_war_time_window);
554 		}
555 		if (*cnt < tcp_ack_war_cnt) {
556 			*cnt = (*cnt + 1);
557 			tp->t_flags |= TF_ACKNOW;
558 		} else
559 			tp->t_flags &= ~TF_ACKNOW;
560 	} else
561 		tp->t_flags |= TF_ACKNOW;
562 }
563 
564 /*
565  * ctf_drop_checks returns 1 for you should not proceed. It places
566  * in ret_val what should be returned 1/0 by the caller. The 1 indicates
567  * that the TCB is unlocked and probably dropped. The 0 indicates the
568  * TCB is still valid and locked.
569  */
570 int
_ctf_drop_checks(struct tcpopt * to,struct mbuf * m,struct tcphdr * th,struct tcpcb * tp,int32_t * tlenp,int32_t * thf,int32_t * drop_hdrlen,int32_t * ret_val,uint32_t * ts,uint32_t * cnt)571 _ctf_drop_checks(struct tcpopt *to, struct mbuf *m, struct tcphdr *th,
572 		 struct tcpcb *tp, int32_t *tlenp,
573 		 int32_t *thf, int32_t *drop_hdrlen, int32_t *ret_val,
574 		 uint32_t *ts, uint32_t *cnt)
575 {
576 	int32_t todrop;
577 	int32_t thflags;
578 	int32_t tlen;
579 
580 	thflags = *thf;
581 	tlen = *tlenp;
582 	todrop = tp->rcv_nxt - th->th_seq;
583 	if (todrop > 0) {
584 		if (thflags & TH_SYN) {
585 			thflags &= ~TH_SYN;
586 			th->th_seq++;
587 			if (th->th_urp > 1)
588 				th->th_urp--;
589 			else
590 				thflags &= ~TH_URG;
591 			todrop--;
592 		}
593 		/*
594 		 * Following if statement from Stevens, vol. 2, p. 960.
595 		 */
596 		if (todrop > tlen
597 		    || (todrop == tlen && (thflags & TH_FIN) == 0)) {
598 			/*
599 			 * Any valid FIN must be to the left of the window.
600 			 * At this point the FIN must be a duplicate or out
601 			 * of sequence; drop it.
602 			 */
603 			thflags &= ~TH_FIN;
604 			/*
605 			 * Send an ACK to resynchronize and drop any data.
606 			 * But keep on processing for RST or ACK.
607 			 */
608 			ctf_ack_war_checks(tp, ts, cnt);
609 			todrop = tlen;
610 			KMOD_TCPSTAT_INC(tcps_rcvduppack);
611 			KMOD_TCPSTAT_ADD(tcps_rcvdupbyte, todrop);
612 		} else {
613 			KMOD_TCPSTAT_INC(tcps_rcvpartduppack);
614 			KMOD_TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop);
615 		}
616 		/*
617 		 * DSACK - add SACK block for dropped range
618 		 */
619 		if ((todrop > 0) && (tp->t_flags & TF_SACK_PERMIT)) {
620 			/*
621 			 * ACK now, as the next in-sequence segment
622 			 * will clear the DSACK block again
623 			 */
624 			ctf_ack_war_checks(tp, ts, cnt);
625 			if (tp->t_flags & TF_ACKNOW)
626 				tcp_update_sack_list(tp, th->th_seq,
627 						     th->th_seq + todrop);
628 		}
629 		*drop_hdrlen += todrop;	/* drop from the top afterwards */
630 		th->th_seq += todrop;
631 		tlen -= todrop;
632 		if (th->th_urp > todrop)
633 			th->th_urp -= todrop;
634 		else {
635 			thflags &= ~TH_URG;
636 			th->th_urp = 0;
637 		}
638 	}
639 	/*
640 	 * If segment ends after window, drop trailing data (and PUSH and
641 	 * FIN); if nothing left, just ACK.
642 	 */
643 	todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
644 	if (todrop > 0) {
645 		KMOD_TCPSTAT_INC(tcps_rcvpackafterwin);
646 		if (todrop >= tlen) {
647 			KMOD_TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen);
648 			/*
649 			 * If window is closed can only take segments at
650 			 * window edge, and have to drop data and PUSH from
651 			 * incoming segments.  Continue processing, but
652 			 * remember to ack.  Otherwise, drop segment and
653 			 * ack.
654 			 */
655 			if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
656 				ctf_ack_war_checks(tp, ts, cnt);
657 				KMOD_TCPSTAT_INC(tcps_rcvwinprobe);
658 			} else {
659 				__ctf_do_dropafterack(m, tp, th, thflags, tlen, ret_val, ts, cnt);
660 				return (1);
661 			}
662 		} else
663 			KMOD_TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
664 		m_adj(m, -todrop);
665 		tlen -= todrop;
666 		thflags &= ~(TH_PUSH | TH_FIN);
667 	}
668 	*thf = thflags;
669 	*tlenp = tlen;
670 	return (0);
671 }
672 
673 /*
674  * The value in ret_val informs the caller
675  * if we dropped the tcb (and lock) or not.
676  * 1 = we dropped it, 0 = the TCB is still locked
677  * and valid.
678  */
679 void
__ctf_do_dropafterack(struct mbuf * m,struct tcpcb * tp,struct tcphdr * th,int32_t thflags,int32_t tlen,int32_t * ret_val,uint32_t * ts,uint32_t * cnt)680 __ctf_do_dropafterack(struct mbuf *m, struct tcpcb *tp, struct tcphdr *th, int32_t thflags, int32_t tlen, int32_t *ret_val, uint32_t *ts, uint32_t *cnt)
681 {
682 	/*
683 	 * Generate an ACK dropping incoming segment if it occupies sequence
684 	 * space, where the ACK reflects our state.
685 	 *
686 	 * We can now skip the test for the RST flag since all paths to this
687 	 * code happen after packets containing RST have been dropped.
688 	 *
689 	 * In the SYN-RECEIVED state, don't send an ACK unless the segment
690 	 * we received passes the SYN-RECEIVED ACK test. If it fails send a
691 	 * RST.  This breaks the loop in the "LAND" DoS attack, and also
692 	 * prevents an ACK storm between two listening ports that have been
693 	 * sent forged SYN segments, each with the source address of the
694 	 * other.
695 	 */
696 	if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
697 	    (SEQ_GT(tp->snd_una, th->th_ack) ||
698 	    SEQ_GT(th->th_ack, tp->snd_max))) {
699 		*ret_val = 1;
700 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
701 		return;
702 	} else
703 		*ret_val = 0;
704 	ctf_ack_war_checks(tp, ts, cnt);
705 	if (m)
706 		m_freem(m);
707 }
708 
709 void
ctf_do_drop(struct mbuf * m,struct tcpcb * tp)710 ctf_do_drop(struct mbuf *m, struct tcpcb *tp)
711 {
712 
713 	/*
714 	 * Drop space held by incoming segment and return.
715 	 */
716 	if (tp != NULL)
717 		INP_WUNLOCK(tptoinpcb(tp));
718 	if (m)
719 		m_freem(m);
720 }
721 
722 int
__ctf_process_rst(struct mbuf * m,struct tcphdr * th,struct socket * so,struct tcpcb * tp,uint32_t * ts,uint32_t * cnt)723 __ctf_process_rst(struct mbuf *m, struct tcphdr *th, struct socket *so,
724 		struct tcpcb *tp, uint32_t *ts, uint32_t *cnt)
725 {
726 	/*
727 	 * RFC5961 Section 3.2
728 	 *
729 	 * - RST drops connection only if SEG.SEQ == RCV.NXT. - If RST is in
730 	 * window, we send challenge ACK.
731 	 *
732 	 * Note: to take into account delayed ACKs, we should test against
733 	 * last_ack_sent instead of rcv_nxt. Note 2: we handle special case
734 	 * of closed window, not covered by the RFC.
735 	 */
736 	int dropped = 0;
737 
738 	if ((SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
739 	    SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) ||
740 	    (tp->rcv_wnd == 0 && tp->last_ack_sent == th->th_seq)) {
741 		KASSERT(tp->t_state != TCPS_SYN_SENT,
742 		    ("%s: TH_RST for TCPS_SYN_SENT th %p tp %p",
743 		    __func__, th, tp));
744 
745 		if (V_tcp_insecure_rst ||
746 		    (tp->last_ack_sent == th->th_seq) ||
747 		    (tp->rcv_nxt == th->th_seq)) {
748 			KMOD_TCPSTAT_INC(tcps_drops);
749 			/* Drop the connection. */
750 			switch (tp->t_state) {
751 			case TCPS_SYN_RECEIVED:
752 				so->so_error = ECONNREFUSED;
753 				goto close;
754 			case TCPS_ESTABLISHED:
755 			case TCPS_FIN_WAIT_1:
756 			case TCPS_FIN_WAIT_2:
757 			case TCPS_CLOSE_WAIT:
758 			case TCPS_CLOSING:
759 			case TCPS_LAST_ACK:
760 				so->so_error = ECONNRESET;
761 		close:
762 				tcp_state_change(tp, TCPS_CLOSED);
763 				/* FALLTHROUGH */
764 			default:
765 				tcp_log_end_status(tp, TCP_EI_STATUS_CLIENT_RST);
766 				tp = tcp_close(tp);
767 			}
768 			dropped = 1;
769 			ctf_do_drop(m, tp);
770 		} else {
771 			int send_challenge;
772 
773 			KMOD_TCPSTAT_INC(tcps_badrst);
774 			if ((ts != NULL) && (cnt != NULL) &&
775 			    (tcp_ack_war_time_window > 0) &&
776 			    (tcp_ack_war_cnt > 0)) {
777 				/* We are possibly preventing an  ack-rst  war prevention */
778 				uint32_t cts;
779 
780 				/*
781 				 * We use a msec tick here which gives us
782 				 * roughly 49 days. We don't need the
783 				 * precision of a microsecond timestamp which
784 				 * would only give us hours.
785 				 */
786 				cts = tcp_ts_getticks();
787 				if (TSTMP_LT((*ts), cts)) {
788 					/* Timestamp is in the past */
789 					*cnt = 0;
790 					*ts = (cts + tcp_ack_war_time_window);
791 				}
792 				if (*cnt < tcp_ack_war_cnt) {
793 					*cnt = (*cnt + 1);
794 					send_challenge = 1;
795 				} else
796 					send_challenge = 0;
797 			} else
798 				send_challenge = 1;
799 			if (send_challenge) {
800 				/* Send challenge ACK. */
801 				tcp_respond(tp, mtod(m, void *), th, m,
802 					    tp->rcv_nxt, tp->snd_nxt, TH_ACK);
803 				tp->last_ack_sent = tp->rcv_nxt;
804 			}
805 		}
806 	} else {
807 		m_freem(m);
808 	}
809 	return (dropped);
810 }
811 
812 /*
813  * The value in ret_val informs the caller
814  * if we dropped the tcb (and lock) or not.
815  * 1 = we dropped it, 0 = the TCB is still locked
816  * and valid.
817  */
818 void
ctf_challenge_ack(struct mbuf * m,struct tcphdr * th,struct tcpcb * tp,uint8_t iptos,int32_t * ret_val)819 ctf_challenge_ack(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp, uint8_t iptos, int32_t * ret_val)
820 {
821 
822 	NET_EPOCH_ASSERT();
823 
824 	KMOD_TCPSTAT_INC(tcps_badsyn);
825 	if (V_tcp_insecure_syn &&
826 	    SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
827 	    SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
828 		tp = tcp_drop(tp, ECONNRESET);
829 		*ret_val = 1;
830 		ctf_do_drop(m, tp);
831 	} else {
832 		tcp_ecn_input_syn_sent(tp, tcp_get_flags(th), iptos);
833 		/* Send challenge ACK. */
834 		tcp_respond(tp, mtod(m, void *), th, m, tp->rcv_nxt,
835 		    tp->snd_nxt, TH_ACK);
836 		tp->last_ack_sent = tp->rcv_nxt;
837 		m = NULL;
838 		*ret_val = 0;
839 		ctf_do_drop(m, NULL);
840 	}
841 }
842 
843 /*
844  * ctf_ts_check returns 1 for you should not proceed, the state
845  * machine should return. It places in ret_val what should
846  * be returned 1/0 by the caller (hpts_do_segment). The 1 indicates
847  * that the TCB is unlocked and probably dropped. The 0 indicates the
848  * TCB is still valid and locked.
849  */
850 int
ctf_ts_check(struct mbuf * m,struct tcphdr * th,struct tcpcb * tp,int32_t tlen,int32_t thflags,int32_t * ret_val)851 ctf_ts_check(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
852     int32_t tlen, int32_t thflags, int32_t * ret_val)
853 {
854 
855 	if (tcp_ts_getticks() - tp->ts_recent_age > TCP_PAWS_IDLE) {
856 		/*
857 		 * Invalidate ts_recent.  If this segment updates ts_recent,
858 		 * the age will be reset later and ts_recent will get a
859 		 * valid value.  If it does not, setting ts_recent to zero
860 		 * will at least satisfy the requirement that zero be placed
861 		 * in the timestamp echo reply when ts_recent isn't valid.
862 		 * The age isn't reset until we get a valid ts_recent
863 		 * because we don't want out-of-order segments to be dropped
864 		 * when ts_recent is old.
865 		 */
866 		tp->ts_recent = 0;
867 	} else {
868 		KMOD_TCPSTAT_INC(tcps_rcvduppack);
869 		KMOD_TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
870 		KMOD_TCPSTAT_INC(tcps_pawsdrop);
871 		*ret_val = 0;
872 		if (tlen) {
873 			ctf_do_dropafterack(m, tp, th, thflags, tlen, ret_val);
874 		} else {
875 			ctf_do_drop(m, NULL);
876 		}
877 		return (1);
878 	}
879 	return (0);
880 }
881 
882 int
ctf_ts_check_ac(struct tcpcb * tp,int32_t thflags)883 ctf_ts_check_ac(struct tcpcb *tp, int32_t thflags)
884 {
885 
886 	if (tcp_ts_getticks() - tp->ts_recent_age > TCP_PAWS_IDLE) {
887 		/*
888 		 * Invalidate ts_recent.  If this segment updates ts_recent,
889 		 * the age will be reset later and ts_recent will get a
890 		 * valid value.  If it does not, setting ts_recent to zero
891 		 * will at least satisfy the requirement that zero be placed
892 		 * in the timestamp echo reply when ts_recent isn't valid.
893 		 * The age isn't reset until we get a valid ts_recent
894 		 * because we don't want out-of-order segments to be dropped
895 		 * when ts_recent is old.
896 		 */
897 		tp->ts_recent = 0;
898 	} else {
899 		KMOD_TCPSTAT_INC(tcps_rcvduppack);
900 		KMOD_TCPSTAT_INC(tcps_pawsdrop);
901 		return (1);
902 	}
903 	return (0);
904 }
905 
906 
907 
908 void
ctf_calc_rwin(struct socket * so,struct tcpcb * tp)909 ctf_calc_rwin(struct socket *so, struct tcpcb *tp)
910 {
911 	int32_t win;
912 
913 	/*
914 	 * Calculate amount of space in receive window, and then do TCP
915 	 * input processing. Receive window is amount of space in rcv queue,
916 	 * but not less than advertised window.
917 	 */
918 	win = sbspace(&so->so_rcv);
919 	if (win < 0)
920 		win = 0;
921 	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
922 }
923 
924 void
ctf_do_dropwithreset_conn(struct mbuf * m,struct tcpcb * tp,struct tcphdr * th,int32_t rstreason,int32_t tlen)925 ctf_do_dropwithreset_conn(struct mbuf *m, struct tcpcb *tp, struct tcphdr *th,
926     int32_t rstreason, int32_t tlen)
927 {
928 
929 	tcp_dropwithreset(m, th, tp, tlen, rstreason);
930 	tp = tcp_drop(tp, ETIMEDOUT);
931 	if (tp)
932 		INP_WUNLOCK(tptoinpcb(tp));
933 }
934 
935 uint32_t
ctf_fixed_maxseg(struct tcpcb * tp)936 ctf_fixed_maxseg(struct tcpcb *tp)
937 {
938 	return (tcp_fixed_maxseg(tp));
939 }
940 
941 void
ctf_log_sack_filter(struct tcpcb * tp,int num_sack_blks,struct sackblk * sack_blocks)942 ctf_log_sack_filter(struct tcpcb *tp, int num_sack_blks, struct sackblk *sack_blocks)
943 {
944 	if (tcp_bblogging_on(tp)) {
945 		union tcp_log_stackspecific log;
946 		struct timeval tv;
947 
948 		memset(&log, 0, sizeof(log));
949 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
950 		log.u_bbr.flex8 = num_sack_blks;
951 		if (num_sack_blks > 0) {
952 			log.u_bbr.flex1 = sack_blocks[0].start;
953 			log.u_bbr.flex2 = sack_blocks[0].end;
954 		}
955 		if (num_sack_blks > 1) {
956 			log.u_bbr.flex3 = sack_blocks[1].start;
957 			log.u_bbr.flex4 = sack_blocks[1].end;
958 		}
959 		if (num_sack_blks > 2) {
960 			log.u_bbr.flex5 = sack_blocks[2].start;
961 			log.u_bbr.flex6 = sack_blocks[2].end;
962 		}
963 		if (num_sack_blks > 3) {
964 			log.u_bbr.applimited = sack_blocks[3].start;
965 			log.u_bbr.pkts_out = sack_blocks[3].end;
966 		}
967 		TCP_LOG_EVENTP(tp, NULL,
968 		    &tptosocket(tp)->so_rcv,
969 		    &tptosocket(tp)->so_snd,
970 		    TCP_SACK_FILTER_RES, 0,
971 		    0, &log, false, &tv);
972 	}
973 }
974 
975 uint32_t
ctf_decay_count(uint32_t count,uint32_t decay)976 ctf_decay_count(uint32_t count, uint32_t decay)
977 {
978 	/*
979 	 * Given a count, decay it by a set percentage. The
980 	 * percentage is in thousands i.e. 100% = 1000,
981 	 * 19.3% = 193.
982 	 */
983 	uint64_t perc_count, decay_per;
984 	uint32_t decayed_count;
985 	if (decay > 1000) {
986 		/* We don't raise it */
987 		return (count);
988 	}
989 	perc_count = count;
990 	decay_per = decay;
991 	perc_count *= decay_per;
992 	perc_count /= 1000;
993 	/*
994 	 * So now perc_count holds the
995 	 * count decay value.
996 	 */
997 	decayed_count = count - (uint32_t)perc_count;
998 	return(decayed_count);
999 }
1000 
1001 int32_t
ctf_progress_timeout_check(struct tcpcb * tp,bool log)1002 ctf_progress_timeout_check(struct tcpcb *tp, bool log)
1003 {
1004 	if (tp->t_maxunacktime && tp->t_acktime && TSTMP_GT(ticks, tp->t_acktime)) {
1005 		if ((ticks - tp->t_acktime) >= tp->t_maxunacktime) {
1006 			/*
1007 			 * There is an assumption that the caller
1008 			 * will drop the connection so we will
1009 			 * increment the counters here.
1010 			 */
1011 			if (log)
1012 				tcp_log_end_status(tp, TCP_EI_STATUS_PROGRESS);
1013 #ifdef NETFLIX_STATS
1014 			KMOD_TCPSTAT_INC(tcps_progdrops);
1015 #endif
1016 			return (1);
1017 		}
1018 	}
1019 	return (0);
1020 }
1021