]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet/tcp_syncache.c
LinuxKPI: 802.11: fix types and whitespace
[FreeBSD/FreeBSD.git] / sys / netinet / tcp_syncache.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2001 McAfee, Inc.
5  * Copyright (c) 2006,2013 Andre Oppermann, Internet Business Solutions AG
6  * All rights reserved.
7  *
8  * This software was developed for the FreeBSD Project by Jonathan Lemon
9  * and McAfee Research, the Security Research Division of McAfee, Inc. under
10  * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the
11  * DARPA CHATS research program. [2001 McAfee, Inc.]
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37
38 #include "opt_inet.h"
39 #include "opt_inet6.h"
40 #include "opt_ipsec.h"
41 #include "opt_pcbgroup.h"
42
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/hash.h>
46 #include <sys/refcount.h>
47 #include <sys/kernel.h>
48 #include <sys/sysctl.h>
49 #include <sys/limits.h>
50 #include <sys/lock.h>
51 #include <sys/mutex.h>
52 #include <sys/malloc.h>
53 #include <sys/mbuf.h>
54 #include <sys/proc.h>           /* for proc0 declaration */
55 #include <sys/random.h>
56 #include <sys/socket.h>
57 #include <sys/socketvar.h>
58 #include <sys/syslog.h>
59 #include <sys/ucred.h>
60
61 #include <sys/md5.h>
62 #include <crypto/siphash/siphash.h>
63
64 #include <vm/uma.h>
65
66 #include <net/if.h>
67 #include <net/if_var.h>
68 #include <net/route.h>
69 #include <net/vnet.h>
70
71 #include <netinet/in.h>
72 #include <netinet/in_kdtrace.h>
73 #include <netinet/in_systm.h>
74 #include <netinet/ip.h>
75 #include <netinet/in_var.h>
76 #include <netinet/in_pcb.h>
77 #include <netinet/ip_var.h>
78 #include <netinet/ip_options.h>
79 #ifdef INET6
80 #include <netinet/ip6.h>
81 #include <netinet/icmp6.h>
82 #include <netinet6/nd6.h>
83 #include <netinet6/ip6_var.h>
84 #include <netinet6/in6_pcb.h>
85 #endif
86 #include <netinet/tcp.h>
87 #include <netinet/tcp_fastopen.h>
88 #include <netinet/tcp_fsm.h>
89 #include <netinet/tcp_seq.h>
90 #include <netinet/tcp_timer.h>
91 #include <netinet/tcp_var.h>
92 #include <netinet/tcp_syncache.h>
93 #ifdef INET6
94 #include <netinet6/tcp6_var.h>
95 #endif
96 #ifdef TCP_OFFLOAD
97 #include <netinet/toecore.h>
98 #endif
99 #include <netinet/udp.h>
100 #include <netinet/udp_var.h>
101
102 #include <netipsec/ipsec_support.h>
103
104 #include <machine/in_cksum.h>
105
106 #include <security/mac/mac_framework.h>
107
108 VNET_DEFINE_STATIC(int, tcp_syncookies) = 1;
109 #define V_tcp_syncookies                VNET(tcp_syncookies)
110 SYSCTL_INT(_net_inet_tcp, OID_AUTO, syncookies, CTLFLAG_VNET | CTLFLAG_RW,
111     &VNET_NAME(tcp_syncookies), 0,
112     "Use TCP SYN cookies if the syncache overflows");
113
114 VNET_DEFINE_STATIC(int, tcp_syncookiesonly) = 0;
115 #define V_tcp_syncookiesonly            VNET(tcp_syncookiesonly)
116 SYSCTL_INT(_net_inet_tcp, OID_AUTO, syncookies_only, CTLFLAG_VNET | CTLFLAG_RW,
117     &VNET_NAME(tcp_syncookiesonly), 0,
118     "Use only TCP SYN cookies");
119
120 VNET_DEFINE_STATIC(int, functions_inherit_listen_socket_stack) = 1;
121 #define V_functions_inherit_listen_socket_stack \
122     VNET(functions_inherit_listen_socket_stack)
123 SYSCTL_INT(_net_inet_tcp, OID_AUTO, functions_inherit_listen_socket_stack,
124     CTLFLAG_VNET | CTLFLAG_RW,
125     &VNET_NAME(functions_inherit_listen_socket_stack), 0,
126     "Inherit listen socket's stack");
127
128 #ifdef TCP_OFFLOAD
129 #define ADDED_BY_TOE(sc) ((sc)->sc_tod != NULL)
130 #endif
131
132 static void      syncache_drop(struct syncache *, struct syncache_head *);
133 static void      syncache_free(struct syncache *);
134 static void      syncache_insert(struct syncache *, struct syncache_head *);
135 static int       syncache_respond(struct syncache *, const struct mbuf *, int);
136 static struct    socket *syncache_socket(struct syncache *, struct socket *,
137                     struct mbuf *m);
138 static void      syncache_timeout(struct syncache *sc, struct syncache_head *sch,
139                     int docallout);
140 static void      syncache_timer(void *);
141
142 static uint32_t  syncookie_mac(struct in_conninfo *, tcp_seq, uint8_t,
143                     uint8_t *, uintptr_t);
144 static tcp_seq   syncookie_generate(struct syncache_head *, struct syncache *);
145 static struct syncache
146                 *syncookie_lookup(struct in_conninfo *, struct syncache_head *,
147                     struct syncache *, struct tcphdr *, struct tcpopt *,
148                     struct socket *, uint16_t);
149 static void     syncache_pause(struct in_conninfo *);
150 static void     syncache_unpause(void *);
151 static void      syncookie_reseed(void *);
152 #ifdef INVARIANTS
153 static int       syncookie_cmp(struct in_conninfo *inc, struct syncache_head *sch,
154                     struct syncache *sc, struct tcphdr *th, struct tcpopt *to,
155                     struct socket *lso, uint16_t port);
156 #endif
157
158 /*
159  * Transmit the SYN,ACK fewer times than TCP_MAXRXTSHIFT specifies.
160  * 3 retransmits corresponds to a timeout with default values of
161  * tcp_rexmit_initial * (             1 +
162  *                       tcp_backoff[1] +
163  *                       tcp_backoff[2] +
164  *                       tcp_backoff[3]) + 3 * tcp_rexmit_slop,
165  * 1000 ms * (1 + 2 + 4 + 8) +  3 * 200 ms = 15600 ms,
166  * the odds are that the user has given up attempting to connect by then.
167  */
168 #define SYNCACHE_MAXREXMTS              3
169
170 /* Arbitrary values */
171 #define TCP_SYNCACHE_HASHSIZE           512
172 #define TCP_SYNCACHE_BUCKETLIMIT        30
173
174 VNET_DEFINE_STATIC(struct tcp_syncache, tcp_syncache);
175 #define V_tcp_syncache                  VNET(tcp_syncache)
176
177 static SYSCTL_NODE(_net_inet_tcp, OID_AUTO, syncache,
178     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
179     "TCP SYN cache");
180
181 SYSCTL_UINT(_net_inet_tcp_syncache, OID_AUTO, bucketlimit, CTLFLAG_VNET | CTLFLAG_RDTUN,
182     &VNET_NAME(tcp_syncache.bucket_limit), 0,
183     "Per-bucket hash limit for syncache");
184
185 SYSCTL_UINT(_net_inet_tcp_syncache, OID_AUTO, cachelimit, CTLFLAG_VNET | CTLFLAG_RDTUN,
186     &VNET_NAME(tcp_syncache.cache_limit), 0,
187     "Overall entry limit for syncache");
188
189 SYSCTL_UMA_CUR(_net_inet_tcp_syncache, OID_AUTO, count, CTLFLAG_VNET,
190     &VNET_NAME(tcp_syncache.zone), "Current number of entries in syncache");
191
192 SYSCTL_UINT(_net_inet_tcp_syncache, OID_AUTO, hashsize, CTLFLAG_VNET | CTLFLAG_RDTUN,
193     &VNET_NAME(tcp_syncache.hashsize), 0,
194     "Size of TCP syncache hashtable");
195
196 static int
197 sysctl_net_inet_tcp_syncache_rexmtlimit_check(SYSCTL_HANDLER_ARGS)
198 {
199         int error;
200         u_int new;
201
202         new = V_tcp_syncache.rexmt_limit;
203         error = sysctl_handle_int(oidp, &new, 0, req);
204         if ((error == 0) && (req->newptr != NULL)) {
205                 if (new > TCP_MAXRXTSHIFT)
206                         error = EINVAL;
207                 else
208                         V_tcp_syncache.rexmt_limit = new;
209         }
210         return (error);
211 }
212
213 SYSCTL_PROC(_net_inet_tcp_syncache, OID_AUTO, rexmtlimit,
214     CTLFLAG_VNET | CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
215     &VNET_NAME(tcp_syncache.rexmt_limit), 0,
216     sysctl_net_inet_tcp_syncache_rexmtlimit_check, "UI",
217     "Limit on SYN/ACK retransmissions");
218
219 VNET_DEFINE(int, tcp_sc_rst_sock_fail) = 1;
220 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, rst_on_sock_fail,
221     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(tcp_sc_rst_sock_fail), 0,
222     "Send reset on socket allocation failure");
223
224 static MALLOC_DEFINE(M_SYNCACHE, "syncache", "TCP syncache");
225
226 #define SCH_LOCK(sch)           mtx_lock(&(sch)->sch_mtx)
227 #define SCH_UNLOCK(sch)         mtx_unlock(&(sch)->sch_mtx)
228 #define SCH_LOCK_ASSERT(sch)    mtx_assert(&(sch)->sch_mtx, MA_OWNED)
229
230 /*
231  * Requires the syncache entry to be already removed from the bucket list.
232  */
233 static void
234 syncache_free(struct syncache *sc)
235 {
236
237         if (sc->sc_ipopts)
238                 (void) m_free(sc->sc_ipopts);
239         if (sc->sc_cred)
240                 crfree(sc->sc_cred);
241 #ifdef MAC
242         mac_syncache_destroy(&sc->sc_label);
243 #endif
244
245         uma_zfree(V_tcp_syncache.zone, sc);
246 }
247
248 void
249 syncache_init(void)
250 {
251         int i;
252
253         V_tcp_syncache.hashsize = TCP_SYNCACHE_HASHSIZE;
254         V_tcp_syncache.bucket_limit = TCP_SYNCACHE_BUCKETLIMIT;
255         V_tcp_syncache.rexmt_limit = SYNCACHE_MAXREXMTS;
256         V_tcp_syncache.hash_secret = arc4random();
257
258         TUNABLE_INT_FETCH("net.inet.tcp.syncache.hashsize",
259             &V_tcp_syncache.hashsize);
260         TUNABLE_INT_FETCH("net.inet.tcp.syncache.bucketlimit",
261             &V_tcp_syncache.bucket_limit);
262         if (!powerof2(V_tcp_syncache.hashsize) ||
263             V_tcp_syncache.hashsize == 0) {
264                 printf("WARNING: syncache hash size is not a power of 2.\n");
265                 V_tcp_syncache.hashsize = TCP_SYNCACHE_HASHSIZE;
266         }
267         V_tcp_syncache.hashmask = V_tcp_syncache.hashsize - 1;
268
269         /* Set limits. */
270         V_tcp_syncache.cache_limit =
271             V_tcp_syncache.hashsize * V_tcp_syncache.bucket_limit;
272         TUNABLE_INT_FETCH("net.inet.tcp.syncache.cachelimit",
273             &V_tcp_syncache.cache_limit);
274
275         /* Allocate the hash table. */
276         V_tcp_syncache.hashbase = malloc(V_tcp_syncache.hashsize *
277             sizeof(struct syncache_head), M_SYNCACHE, M_WAITOK | M_ZERO);
278
279 #ifdef VIMAGE
280         V_tcp_syncache.vnet = curvnet;
281 #endif
282
283         /* Initialize the hash buckets. */
284         for (i = 0; i < V_tcp_syncache.hashsize; i++) {
285                 TAILQ_INIT(&V_tcp_syncache.hashbase[i].sch_bucket);
286                 mtx_init(&V_tcp_syncache.hashbase[i].sch_mtx, "tcp_sc_head",
287                          NULL, MTX_DEF);
288                 callout_init_mtx(&V_tcp_syncache.hashbase[i].sch_timer,
289                          &V_tcp_syncache.hashbase[i].sch_mtx, 0);
290                 V_tcp_syncache.hashbase[i].sch_length = 0;
291                 V_tcp_syncache.hashbase[i].sch_sc = &V_tcp_syncache;
292                 V_tcp_syncache.hashbase[i].sch_last_overflow =
293                     -(SYNCOOKIE_LIFETIME + 1);
294         }
295
296         /* Create the syncache entry zone. */
297         V_tcp_syncache.zone = uma_zcreate("syncache", sizeof(struct syncache),
298             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
299         V_tcp_syncache.cache_limit = uma_zone_set_max(V_tcp_syncache.zone,
300             V_tcp_syncache.cache_limit);
301
302         /* Start the SYN cookie reseeder callout. */
303         callout_init(&V_tcp_syncache.secret.reseed, 1);
304         arc4rand(V_tcp_syncache.secret.key[0], SYNCOOKIE_SECRET_SIZE, 0);
305         arc4rand(V_tcp_syncache.secret.key[1], SYNCOOKIE_SECRET_SIZE, 0);
306         callout_reset(&V_tcp_syncache.secret.reseed, SYNCOOKIE_LIFETIME * hz,
307             syncookie_reseed, &V_tcp_syncache);
308
309         /* Initialize the pause machinery. */
310         mtx_init(&V_tcp_syncache.pause_mtx, "tcp_sc_pause", NULL, MTX_DEF);
311         callout_init_mtx(&V_tcp_syncache.pause_co, &V_tcp_syncache.pause_mtx,
312             0);
313         V_tcp_syncache.pause_until = time_uptime - TCP_SYNCACHE_PAUSE_TIME;
314         V_tcp_syncache.pause_backoff = 0;
315         V_tcp_syncache.paused = false;
316 }
317
318 #ifdef VIMAGE
319 void
320 syncache_destroy(void)
321 {
322         struct syncache_head *sch;
323         struct syncache *sc, *nsc;
324         int i;
325
326         /*
327          * Stop the re-seed timer before freeing resources.  No need to
328          * possibly schedule it another time.
329          */
330         callout_drain(&V_tcp_syncache.secret.reseed);
331
332         /* Stop the SYN cache pause callout. */
333         mtx_lock(&V_tcp_syncache.pause_mtx);
334         if (callout_stop(&V_tcp_syncache.pause_co) == 0) {
335                 mtx_unlock(&V_tcp_syncache.pause_mtx);
336                 callout_drain(&V_tcp_syncache.pause_co);
337         } else
338                 mtx_unlock(&V_tcp_syncache.pause_mtx);
339
340         /* Cleanup hash buckets: stop timers, free entries, destroy locks. */
341         for (i = 0; i < V_tcp_syncache.hashsize; i++) {
342                 sch = &V_tcp_syncache.hashbase[i];
343                 callout_drain(&sch->sch_timer);
344
345                 SCH_LOCK(sch);
346                 TAILQ_FOREACH_SAFE(sc, &sch->sch_bucket, sc_hash, nsc)
347                         syncache_drop(sc, sch);
348                 SCH_UNLOCK(sch);
349                 KASSERT(TAILQ_EMPTY(&sch->sch_bucket),
350                     ("%s: sch->sch_bucket not empty", __func__));
351                 KASSERT(sch->sch_length == 0, ("%s: sch->sch_length %d not 0",
352                     __func__, sch->sch_length));
353                 mtx_destroy(&sch->sch_mtx);
354         }
355
356         KASSERT(uma_zone_get_cur(V_tcp_syncache.zone) == 0,
357             ("%s: cache_count not 0", __func__));
358
359         /* Free the allocated global resources. */
360         uma_zdestroy(V_tcp_syncache.zone);
361         free(V_tcp_syncache.hashbase, M_SYNCACHE);
362         mtx_destroy(&V_tcp_syncache.pause_mtx);
363 }
364 #endif
365
366 /*
367  * Inserts a syncache entry into the specified bucket row.
368  * Locks and unlocks the syncache_head autonomously.
369  */
370 static void
371 syncache_insert(struct syncache *sc, struct syncache_head *sch)
372 {
373         struct syncache *sc2;
374
375         SCH_LOCK(sch);
376
377         /*
378          * Make sure that we don't overflow the per-bucket limit.
379          * If the bucket is full, toss the oldest element.
380          */
381         if (sch->sch_length >= V_tcp_syncache.bucket_limit) {
382                 KASSERT(!TAILQ_EMPTY(&sch->sch_bucket),
383                         ("sch->sch_length incorrect"));
384                 syncache_pause(&sc->sc_inc);
385                 sc2 = TAILQ_LAST(&sch->sch_bucket, sch_head);
386                 sch->sch_last_overflow = time_uptime;
387                 syncache_drop(sc2, sch);
388         }
389
390         /* Put it into the bucket. */
391         TAILQ_INSERT_HEAD(&sch->sch_bucket, sc, sc_hash);
392         sch->sch_length++;
393
394 #ifdef TCP_OFFLOAD
395         if (ADDED_BY_TOE(sc)) {
396                 struct toedev *tod = sc->sc_tod;
397
398                 tod->tod_syncache_added(tod, sc->sc_todctx);
399         }
400 #endif
401
402         /* Reinitialize the bucket row's timer. */
403         if (sch->sch_length == 1)
404                 sch->sch_nextc = ticks + INT_MAX;
405         syncache_timeout(sc, sch, 1);
406
407         SCH_UNLOCK(sch);
408
409         TCPSTATES_INC(TCPS_SYN_RECEIVED);
410         TCPSTAT_INC(tcps_sc_added);
411 }
412
413 /*
414  * Remove and free entry from syncache bucket row.
415  * Expects locked syncache head.
416  */
417 static void
418 syncache_drop(struct syncache *sc, struct syncache_head *sch)
419 {
420
421         SCH_LOCK_ASSERT(sch);
422
423         TCPSTATES_DEC(TCPS_SYN_RECEIVED);
424         TAILQ_REMOVE(&sch->sch_bucket, sc, sc_hash);
425         sch->sch_length--;
426
427 #ifdef TCP_OFFLOAD
428         if (ADDED_BY_TOE(sc)) {
429                 struct toedev *tod = sc->sc_tod;
430
431                 tod->tod_syncache_removed(tod, sc->sc_todctx);
432         }
433 #endif
434
435         syncache_free(sc);
436 }
437
438 /*
439  * Engage/reengage time on bucket row.
440  */
441 static void
442 syncache_timeout(struct syncache *sc, struct syncache_head *sch, int docallout)
443 {
444         int rexmt;
445
446         if (sc->sc_rxmits == 0)
447                 rexmt = tcp_rexmit_initial;
448         else
449                 TCPT_RANGESET(rexmt,
450                     tcp_rexmit_initial * tcp_backoff[sc->sc_rxmits],
451                     tcp_rexmit_min, TCPTV_REXMTMAX);
452         sc->sc_rxttime = ticks + rexmt;
453         sc->sc_rxmits++;
454         if (TSTMP_LT(sc->sc_rxttime, sch->sch_nextc)) {
455                 sch->sch_nextc = sc->sc_rxttime;
456                 if (docallout)
457                         callout_reset(&sch->sch_timer, sch->sch_nextc - ticks,
458                             syncache_timer, (void *)sch);
459         }
460 }
461
462 /*
463  * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted.
464  * If we have retransmitted an entry the maximum number of times, expire it.
465  * One separate timer for each bucket row.
466  */
467 static void
468 syncache_timer(void *xsch)
469 {
470         struct syncache_head *sch = (struct syncache_head *)xsch;
471         struct syncache *sc, *nsc;
472         struct epoch_tracker et;
473         int tick = ticks;
474         char *s;
475         bool paused;
476
477         CURVNET_SET(sch->sch_sc->vnet);
478
479         /* NB: syncache_head has already been locked by the callout. */
480         SCH_LOCK_ASSERT(sch);
481
482         /*
483          * In the following cycle we may remove some entries and/or
484          * advance some timeouts, so re-initialize the bucket timer.
485          */
486         sch->sch_nextc = tick + INT_MAX;
487
488         /*
489          * If we have paused processing, unconditionally remove
490          * all syncache entries.
491          */
492         mtx_lock(&V_tcp_syncache.pause_mtx);
493         paused = V_tcp_syncache.paused;
494         mtx_unlock(&V_tcp_syncache.pause_mtx);
495
496         TAILQ_FOREACH_SAFE(sc, &sch->sch_bucket, sc_hash, nsc) {
497                 if (paused) {
498                         syncache_drop(sc, sch);
499                         continue;
500                 }
501                 /*
502                  * We do not check if the listen socket still exists
503                  * and accept the case where the listen socket may be
504                  * gone by the time we resend the SYN/ACK.  We do
505                  * not expect this to happens often. If it does,
506                  * then the RST will be sent by the time the remote
507                  * host does the SYN/ACK->ACK.
508                  */
509                 if (TSTMP_GT(sc->sc_rxttime, tick)) {
510                         if (TSTMP_LT(sc->sc_rxttime, sch->sch_nextc))
511                                 sch->sch_nextc = sc->sc_rxttime;
512                         continue;
513                 }
514                 if (sc->sc_rxmits > V_tcp_ecn_maxretries) {
515                         sc->sc_flags &= ~SCF_ECN;
516                 }
517                 if (sc->sc_rxmits > V_tcp_syncache.rexmt_limit) {
518                         if ((s = tcp_log_addrs(&sc->sc_inc, NULL, NULL, NULL))) {
519                                 log(LOG_DEBUG, "%s; %s: Retransmits exhausted, "
520                                     "giving up and removing syncache entry\n",
521                                     s, __func__);
522                                 free(s, M_TCPLOG);
523                         }
524                         syncache_drop(sc, sch);
525                         TCPSTAT_INC(tcps_sc_stale);
526                         continue;
527                 }
528                 if ((s = tcp_log_addrs(&sc->sc_inc, NULL, NULL, NULL))) {
529                         log(LOG_DEBUG, "%s; %s: Response timeout, "
530                             "retransmitting (%u) SYN|ACK\n",
531                             s, __func__, sc->sc_rxmits);
532                         free(s, M_TCPLOG);
533                 }
534
535                 NET_EPOCH_ENTER(et);
536                 syncache_respond(sc, NULL, TH_SYN|TH_ACK);
537                 NET_EPOCH_EXIT(et);
538                 TCPSTAT_INC(tcps_sc_retransmitted);
539                 syncache_timeout(sc, sch, 0);
540         }
541         if (!TAILQ_EMPTY(&(sch)->sch_bucket))
542                 callout_reset(&(sch)->sch_timer, (sch)->sch_nextc - tick,
543                         syncache_timer, (void *)(sch));
544         CURVNET_RESTORE();
545 }
546
547 /*
548  * Returns true if the system is only using cookies at the moment.
549  * This could be due to a sysadmin decision to only use cookies, or it
550  * could be due to the system detecting an attack.
551  */
552 static inline bool
553 syncache_cookiesonly(void)
554 {
555
556         return (V_tcp_syncookies && (V_tcp_syncache.paused ||
557             V_tcp_syncookiesonly));
558 }
559
560 /*
561  * Find the hash bucket for the given connection.
562  */
563 static struct syncache_head *
564 syncache_hashbucket(struct in_conninfo *inc)
565 {
566         uint32_t hash;
567
568         /*
569          * The hash is built on foreign port + local port + foreign address.
570          * We rely on the fact that struct in_conninfo starts with 16 bits
571          * of foreign port, then 16 bits of local port then followed by 128
572          * bits of foreign address.  In case of IPv4 address, the first 3
573          * 32-bit words of the address always are zeroes.
574          */
575         hash = jenkins_hash32((uint32_t *)&inc->inc_ie, 5,
576             V_tcp_syncache.hash_secret) & V_tcp_syncache.hashmask;
577
578         return (&V_tcp_syncache.hashbase[hash]);
579 }
580
581 /*
582  * Find an entry in the syncache.
583  * Returns always with locked syncache_head plus a matching entry or NULL.
584  */
585 static struct syncache *
586 syncache_lookup(struct in_conninfo *inc, struct syncache_head **schp)
587 {
588         struct syncache *sc;
589         struct syncache_head *sch;
590
591         *schp = sch = syncache_hashbucket(inc);
592         SCH_LOCK(sch);
593
594         /* Circle through bucket row to find matching entry. */
595         TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash)
596                 if (bcmp(&inc->inc_ie, &sc->sc_inc.inc_ie,
597                     sizeof(struct in_endpoints)) == 0)
598                         break;
599
600         return (sc);    /* Always returns with locked sch. */
601 }
602
603 /*
604  * This function is called when we get a RST for a
605  * non-existent connection, so that we can see if the
606  * connection is in the syn cache.  If it is, zap it.
607  * If required send a challenge ACK.
608  */
609 void
610 syncache_chkrst(struct in_conninfo *inc, struct tcphdr *th, struct mbuf *m,
611     uint16_t port)
612 {
613         struct syncache *sc;
614         struct syncache_head *sch;
615         char *s = NULL;
616
617         if (syncache_cookiesonly())
618                 return;
619         sc = syncache_lookup(inc, &sch);        /* returns locked sch */
620         SCH_LOCK_ASSERT(sch);
621
622         /*
623          * Any RST to our SYN|ACK must not carry ACK, SYN or FIN flags.
624          * See RFC 793 page 65, section SEGMENT ARRIVES.
625          */
626         if (th->th_flags & (TH_ACK|TH_SYN|TH_FIN)) {
627                 if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
628                         log(LOG_DEBUG, "%s; %s: Spurious RST with ACK, SYN or "
629                             "FIN flag set, segment ignored\n", s, __func__);
630                 TCPSTAT_INC(tcps_badrst);
631                 goto done;
632         }
633
634         /*
635          * No corresponding connection was found in syncache.
636          * If syncookies are enabled and possibly exclusively
637          * used, or we are under memory pressure, a valid RST
638          * may not find a syncache entry.  In that case we're
639          * done and no SYN|ACK retransmissions will happen.
640          * Otherwise the RST was misdirected or spoofed.
641          */
642         if (sc == NULL) {
643                 if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
644                         log(LOG_DEBUG, "%s; %s: Spurious RST without matching "
645                             "syncache entry (possibly syncookie only), "
646                             "segment ignored\n", s, __func__);
647                 TCPSTAT_INC(tcps_badrst);
648                 goto done;
649         }
650
651         /* The remote UDP encaps port does not match. */
652         if (sc->sc_port != port) {
653                 if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
654                         log(LOG_DEBUG, "%s; %s: Spurious RST with matching "
655                             "syncache entry but non-matching UDP encaps port, "
656                             "segment ignored\n", s, __func__);
657                 TCPSTAT_INC(tcps_badrst);
658                 goto done;
659         }
660
661         /*
662          * If the RST bit is set, check the sequence number to see
663          * if this is a valid reset segment.
664          *
665          * RFC 793 page 37:
666          *   In all states except SYN-SENT, all reset (RST) segments
667          *   are validated by checking their SEQ-fields.  A reset is
668          *   valid if its sequence number is in the window.
669          *
670          * RFC 793 page 69:
671          *   There are four cases for the acceptability test for an incoming
672          *   segment:
673          *
674          * Segment Receive  Test
675          * Length  Window
676          * ------- -------  -------------------------------------------
677          *    0       0     SEG.SEQ = RCV.NXT
678          *    0      >0     RCV.NXT =< SEG.SEQ < RCV.NXT+RCV.WND
679          *   >0       0     not acceptable
680          *   >0      >0     RCV.NXT =< SEG.SEQ < RCV.NXT+RCV.WND
681          *               or RCV.NXT =< SEG.SEQ+SEG.LEN-1 < RCV.NXT+RCV.WND
682          *
683          * Note that when receiving a SYN segment in the LISTEN state,
684          * IRS is set to SEG.SEQ and RCV.NXT is set to SEG.SEQ+1, as
685          * described in RFC 793, page 66.
686          */
687         if ((SEQ_GEQ(th->th_seq, sc->sc_irs + 1) &&
688             SEQ_LT(th->th_seq, sc->sc_irs + 1 + sc->sc_wnd)) ||
689             (sc->sc_wnd == 0 && th->th_seq == sc->sc_irs + 1)) {
690                 if (V_tcp_insecure_rst ||
691                     th->th_seq == sc->sc_irs + 1) {
692                         syncache_drop(sc, sch);
693                         if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
694                                 log(LOG_DEBUG,
695                                     "%s; %s: Our SYN|ACK was rejected, "
696                                     "connection attempt aborted by remote "
697                                     "endpoint\n",
698                                     s, __func__);
699                         TCPSTAT_INC(tcps_sc_reset);
700                 } else {
701                         TCPSTAT_INC(tcps_badrst);
702                         /* Send challenge ACK. */
703                         if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
704                                 log(LOG_DEBUG, "%s; %s: RST with invalid "
705                                     " SEQ %u != NXT %u (+WND %u), "
706                                     "sending challenge ACK\n",
707                                     s, __func__,
708                                     th->th_seq, sc->sc_irs + 1, sc->sc_wnd);
709                         syncache_respond(sc, m, TH_ACK);
710                 }
711         } else {
712                 if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
713                         log(LOG_DEBUG, "%s; %s: RST with invalid SEQ %u != "
714                             "NXT %u (+WND %u), segment ignored\n",
715                             s, __func__,
716                             th->th_seq, sc->sc_irs + 1, sc->sc_wnd);
717                 TCPSTAT_INC(tcps_badrst);
718         }
719
720 done:
721         if (s != NULL)
722                 free(s, M_TCPLOG);
723         SCH_UNLOCK(sch);
724 }
725
726 void
727 syncache_badack(struct in_conninfo *inc, uint16_t port)
728 {
729         struct syncache *sc;
730         struct syncache_head *sch;
731
732         if (syncache_cookiesonly())
733                 return;
734         sc = syncache_lookup(inc, &sch);        /* returns locked sch */
735         SCH_LOCK_ASSERT(sch);
736         if ((sc != NULL) && (sc->sc_port == port)) {
737                 syncache_drop(sc, sch);
738                 TCPSTAT_INC(tcps_sc_badack);
739         }
740         SCH_UNLOCK(sch);
741 }
742
743 void
744 syncache_unreach(struct in_conninfo *inc, tcp_seq th_seq, uint16_t port)
745 {
746         struct syncache *sc;
747         struct syncache_head *sch;
748
749         if (syncache_cookiesonly())
750                 return;
751         sc = syncache_lookup(inc, &sch);        /* returns locked sch */
752         SCH_LOCK_ASSERT(sch);
753         if (sc == NULL)
754                 goto done;
755
756         /* If the port != sc_port, then it's a bogus ICMP msg */
757         if (port != sc->sc_port)
758                 goto done;
759
760         /* If the sequence number != sc_iss, then it's a bogus ICMP msg */
761         if (ntohl(th_seq) != sc->sc_iss)
762                 goto done;
763
764         /*
765          * If we've rertransmitted 3 times and this is our second error,
766          * we remove the entry.  Otherwise, we allow it to continue on.
767          * This prevents us from incorrectly nuking an entry during a
768          * spurious network outage.
769          *
770          * See tcp_notify().
771          */
772         if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxmits < 3 + 1) {
773                 sc->sc_flags |= SCF_UNREACH;
774                 goto done;
775         }
776         syncache_drop(sc, sch);
777         TCPSTAT_INC(tcps_sc_unreach);
778 done:
779         SCH_UNLOCK(sch);
780 }
781
782 /*
783  * Build a new TCP socket structure from a syncache entry.
784  *
785  * On success return the newly created socket with its underlying inp locked.
786  */
787 static struct socket *
788 syncache_socket(struct syncache *sc, struct socket *lso, struct mbuf *m)
789 {
790         struct tcp_function_block *blk;
791         struct inpcb *inp = NULL;
792         struct socket *so;
793         struct tcpcb *tp;
794         int error;
795         char *s;
796
797         NET_EPOCH_ASSERT();
798
799         /*
800          * Ok, create the full blown connection, and set things up
801          * as they would have been set up if we had created the
802          * connection when the SYN arrived.  If we can't create
803          * the connection, abort it.
804          */
805         so = sonewconn(lso, 0);
806         if (so == NULL) {
807                 /*
808                  * Drop the connection; we will either send a RST or
809                  * have the peer retransmit its SYN again after its
810                  * RTO and try again.
811                  */
812                 TCPSTAT_INC(tcps_listendrop);
813                 if ((s = tcp_log_addrs(&sc->sc_inc, NULL, NULL, NULL))) {
814                         log(LOG_DEBUG, "%s; %s: Socket create failed "
815                             "due to limits or memory shortage\n",
816                             s, __func__);
817                         free(s, M_TCPLOG);
818                 }
819                 goto abort2;
820         }
821 #ifdef MAC
822         mac_socketpeer_set_from_mbuf(m, so);
823 #endif
824
825         inp = sotoinpcb(so);
826         inp->inp_inc.inc_fibnum = so->so_fibnum;
827         INP_WLOCK(inp);
828         /*
829          * Exclusive pcbinfo lock is not required in syncache socket case even
830          * if two inpcb locks can be acquired simultaneously:
831          *  - the inpcb in LISTEN state,
832          *  - the newly created inp.
833          *
834          * In this case, an inp cannot be at same time in LISTEN state and
835          * just created by an accept() call.
836          */
837         INP_HASH_WLOCK(&V_tcbinfo);
838
839         /* Insert new socket into PCB hash list. */
840         inp->inp_inc.inc_flags = sc->sc_inc.inc_flags;
841 #ifdef INET6
842         if (sc->sc_inc.inc_flags & INC_ISIPV6) {
843                 inp->inp_vflag &= ~INP_IPV4;
844                 inp->inp_vflag |= INP_IPV6;
845                 inp->in6p_laddr = sc->sc_inc.inc6_laddr;
846         } else {
847                 inp->inp_vflag &= ~INP_IPV6;
848                 inp->inp_vflag |= INP_IPV4;
849 #endif
850                 inp->inp_ip_ttl = sc->sc_ip_ttl;
851                 inp->inp_ip_tos = sc->sc_ip_tos;
852                 inp->inp_laddr = sc->sc_inc.inc_laddr;
853 #ifdef INET6
854         }
855 #endif
856
857         /*
858          * If there's an mbuf and it has a flowid, then let's initialise the
859          * inp with that particular flowid.
860          */
861         if (m != NULL && M_HASHTYPE_GET(m) != M_HASHTYPE_NONE) {
862                 inp->inp_flowid = m->m_pkthdr.flowid;
863                 inp->inp_flowtype = M_HASHTYPE_GET(m);
864 #ifdef NUMA
865                 inp->inp_numa_domain = m->m_pkthdr.numa_domain;
866 #endif
867         }
868
869         inp->inp_lport = sc->sc_inc.inc_lport;
870 #ifdef INET6
871         if (inp->inp_vflag & INP_IPV6PROTO) {
872                 struct inpcb *oinp = sotoinpcb(lso);
873
874                 /*
875                  * Inherit socket options from the listening socket.
876                  * Note that in6p_inputopts are not (and should not be)
877                  * copied, since it stores previously received options and is
878                  * used to detect if each new option is different than the
879                  * previous one and hence should be passed to a user.
880                  * If we copied in6p_inputopts, a user would not be able to
881                  * receive options just after calling the accept system call.
882                  */
883                 inp->inp_flags |= oinp->inp_flags & INP_CONTROLOPTS;
884                 if (oinp->in6p_outputopts)
885                         inp->in6p_outputopts =
886                             ip6_copypktopts(oinp->in6p_outputopts, M_NOWAIT);
887                 inp->in6p_hops = oinp->in6p_hops;
888         }
889
890         if (sc->sc_inc.inc_flags & INC_ISIPV6) {
891                 struct in6_addr laddr6;
892                 struct sockaddr_in6 sin6;
893
894                 sin6.sin6_family = AF_INET6;
895                 sin6.sin6_len = sizeof(sin6);
896                 sin6.sin6_addr = sc->sc_inc.inc6_faddr;
897                 sin6.sin6_port = sc->sc_inc.inc_fport;
898                 sin6.sin6_flowinfo = sin6.sin6_scope_id = 0;
899                 laddr6 = inp->in6p_laddr;
900                 if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr))
901                         inp->in6p_laddr = sc->sc_inc.inc6_laddr;
902                 if ((error = in6_pcbconnect_mbuf(inp, (struct sockaddr *)&sin6,
903                     thread0.td_ucred, m, false)) != 0) {
904                         inp->in6p_laddr = laddr6;
905                         if ((s = tcp_log_addrs(&sc->sc_inc, NULL, NULL, NULL))) {
906                                 log(LOG_DEBUG, "%s; %s: in6_pcbconnect failed "
907                                     "with error %i\n",
908                                     s, __func__, error);
909                                 free(s, M_TCPLOG);
910                         }
911                         INP_HASH_WUNLOCK(&V_tcbinfo);
912                         goto abort;
913                 }
914                 /* Override flowlabel from in6_pcbconnect. */
915                 inp->inp_flow &= ~IPV6_FLOWLABEL_MASK;
916                 inp->inp_flow |= sc->sc_flowlabel;
917         }
918 #endif /* INET6 */
919 #if defined(INET) && defined(INET6)
920         else
921 #endif
922 #ifdef INET
923         {
924                 struct in_addr laddr;
925                 struct sockaddr_in sin;
926
927                 inp->inp_options = (m) ? ip_srcroute(m) : NULL;
928
929                 if (inp->inp_options == NULL) {
930                         inp->inp_options = sc->sc_ipopts;
931                         sc->sc_ipopts = NULL;
932                 }
933
934                 sin.sin_family = AF_INET;
935                 sin.sin_len = sizeof(sin);
936                 sin.sin_addr = sc->sc_inc.inc_faddr;
937                 sin.sin_port = sc->sc_inc.inc_fport;
938                 bzero((caddr_t)sin.sin_zero, sizeof(sin.sin_zero));
939                 laddr = inp->inp_laddr;
940                 if (inp->inp_laddr.s_addr == INADDR_ANY)
941                         inp->inp_laddr = sc->sc_inc.inc_laddr;
942                 if ((error = in_pcbconnect_mbuf(inp, (struct sockaddr *)&sin,
943                     thread0.td_ucred, m, false)) != 0) {
944                         inp->inp_laddr = laddr;
945                         if ((s = tcp_log_addrs(&sc->sc_inc, NULL, NULL, NULL))) {
946                                 log(LOG_DEBUG, "%s; %s: in_pcbconnect failed "
947                                     "with error %i\n",
948                                     s, __func__, error);
949                                 free(s, M_TCPLOG);
950                         }
951                         INP_HASH_WUNLOCK(&V_tcbinfo);
952                         goto abort;
953                 }
954         }
955 #endif /* INET */
956 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
957         /* Copy old policy into new socket's. */
958         if (ipsec_copy_pcbpolicy(sotoinpcb(lso), inp) != 0)
959                 printf("syncache_socket: could not copy policy\n");
960 #endif
961         INP_HASH_WUNLOCK(&V_tcbinfo);
962         tp = intotcpcb(inp);
963         tcp_state_change(tp, TCPS_SYN_RECEIVED);
964         tp->iss = sc->sc_iss;
965         tp->irs = sc->sc_irs;
966         tp->t_port = sc->sc_port;
967         tcp_rcvseqinit(tp);
968         tcp_sendseqinit(tp);
969         blk = sototcpcb(lso)->t_fb;
970         if (V_functions_inherit_listen_socket_stack && blk != tp->t_fb) {
971                 /*
972                  * Our parents t_fb was not the default,
973                  * we need to release our ref on tp->t_fb and
974                  * pickup one on the new entry.
975                  */
976                 struct tcp_function_block *rblk;
977
978                 rblk = find_and_ref_tcp_fb(blk);
979                 KASSERT(rblk != NULL,
980                     ("cannot find blk %p out of syncache?", blk));
981                 if (tp->t_fb->tfb_tcp_fb_fini)
982                         (*tp->t_fb->tfb_tcp_fb_fini)(tp, 0);
983                 refcount_release(&tp->t_fb->tfb_refcnt);
984                 tp->t_fb = rblk;
985                 /*
986                  * XXXrrs this is quite dangerous, it is possible
987                  * for the new function to fail to init. We also
988                  * are not asking if the handoff_is_ok though at
989                  * the very start thats probalbly ok.
990                  */
991                 if (tp->t_fb->tfb_tcp_fb_init) {
992                         (*tp->t_fb->tfb_tcp_fb_init)(tp);
993                 }
994         }
995         tp->snd_wl1 = sc->sc_irs;
996         tp->snd_max = tp->iss + 1;
997         tp->snd_nxt = tp->iss + 1;
998         tp->rcv_up = sc->sc_irs + 1;
999         tp->rcv_wnd = sc->sc_wnd;
1000         tp->rcv_adv += tp->rcv_wnd;
1001         tp->last_ack_sent = tp->rcv_nxt;
1002
1003         tp->t_flags = sototcpcb(lso)->t_flags & (TF_NOPUSH|TF_NODELAY);
1004         if (sc->sc_flags & SCF_NOOPT)
1005                 tp->t_flags |= TF_NOOPT;
1006         else {
1007                 if (sc->sc_flags & SCF_WINSCALE) {
1008                         tp->t_flags |= TF_REQ_SCALE|TF_RCVD_SCALE;
1009                         tp->snd_scale = sc->sc_requested_s_scale;
1010                         tp->request_r_scale = sc->sc_requested_r_scale;
1011                 }
1012                 if (sc->sc_flags & SCF_TIMESTAMP) {
1013                         tp->t_flags |= TF_REQ_TSTMP|TF_RCVD_TSTMP;
1014                         tp->ts_recent = sc->sc_tsreflect;
1015                         tp->ts_recent_age = tcp_ts_getticks();
1016                         tp->ts_offset = sc->sc_tsoff;
1017                 }
1018 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1019                 if (sc->sc_flags & SCF_SIGNATURE)
1020                         tp->t_flags |= TF_SIGNATURE;
1021 #endif
1022                 if (sc->sc_flags & SCF_SACK)
1023                         tp->t_flags |= TF_SACK_PERMIT;
1024         }
1025
1026         if (sc->sc_flags & SCF_ECN)
1027                 tp->t_flags2 |= TF2_ECN_PERMIT;
1028
1029         /*
1030          * Set up MSS and get cached values from tcp_hostcache.
1031          * This might overwrite some of the defaults we just set.
1032          */
1033         tcp_mss(tp, sc->sc_peer_mss);
1034
1035         /*
1036          * If the SYN,ACK was retransmitted, indicate that CWND to be
1037          * limited to one segment in cc_conn_init().
1038          * NB: sc_rxmits counts all SYN,ACK transmits, not just retransmits.
1039          */
1040         if (sc->sc_rxmits > 1)
1041                 tp->snd_cwnd = 1;
1042
1043 #ifdef TCP_OFFLOAD
1044         /*
1045          * Allow a TOE driver to install its hooks.  Note that we hold the
1046          * pcbinfo lock too and that prevents tcp_usr_accept from accepting a
1047          * new connection before the TOE driver has done its thing.
1048          */
1049         if (ADDED_BY_TOE(sc)) {
1050                 struct toedev *tod = sc->sc_tod;
1051
1052                 tod->tod_offload_socket(tod, sc->sc_todctx, so);
1053         }
1054 #endif
1055         /*
1056          * Copy and activate timers.
1057          */
1058         tp->t_keepinit = sototcpcb(lso)->t_keepinit;
1059         tp->t_keepidle = sototcpcb(lso)->t_keepidle;
1060         tp->t_keepintvl = sototcpcb(lso)->t_keepintvl;
1061         tp->t_keepcnt = sototcpcb(lso)->t_keepcnt;
1062         tcp_timer_activate(tp, TT_KEEP, TP_KEEPINIT(tp));
1063
1064         TCPSTAT_INC(tcps_accepts);
1065         return (so);
1066
1067 abort:
1068         INP_WUNLOCK(inp);
1069 abort2:
1070         if (so != NULL)
1071                 soabort(so);
1072         return (NULL);
1073 }
1074
1075 /*
1076  * This function gets called when we receive an ACK for a
1077  * socket in the LISTEN state.  We look up the connection
1078  * in the syncache, and if its there, we pull it out of
1079  * the cache and turn it into a full-blown connection in
1080  * the SYN-RECEIVED state.
1081  *
1082  * On syncache_socket() success the newly created socket
1083  * has its underlying inp locked.
1084  */
1085 int
1086 syncache_expand(struct in_conninfo *inc, struct tcpopt *to, struct tcphdr *th,
1087     struct socket **lsop, struct mbuf *m, uint16_t port)
1088 {
1089         struct syncache *sc;
1090         struct syncache_head *sch;
1091         struct syncache scs;
1092         char *s;
1093         bool locked;
1094
1095         NET_EPOCH_ASSERT();
1096         KASSERT((th->th_flags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK,
1097             ("%s: can handle only ACK", __func__));
1098
1099         if (syncache_cookiesonly()) {
1100                 sc = NULL;
1101                 sch = syncache_hashbucket(inc);
1102                 locked = false;
1103         } else {
1104                 sc = syncache_lookup(inc, &sch);        /* returns locked sch */
1105                 locked = true;
1106                 SCH_LOCK_ASSERT(sch);
1107         }
1108
1109 #ifdef INVARIANTS
1110         /*
1111          * Test code for syncookies comparing the syncache stored
1112          * values with the reconstructed values from the cookie.
1113          */
1114         if (sc != NULL)
1115                 syncookie_cmp(inc, sch, sc, th, to, *lsop, port);
1116 #endif
1117
1118         if (sc == NULL) {
1119                 /*
1120                  * There is no syncache entry, so see if this ACK is
1121                  * a returning syncookie.  To do this, first:
1122                  *  A. Check if syncookies are used in case of syncache
1123                  *     overflows
1124                  *  B. See if this socket has had a syncache entry dropped in
1125                  *     the recent past. We don't want to accept a bogus
1126                  *     syncookie if we've never received a SYN or accept it
1127                  *     twice.
1128                  *  C. check that the syncookie is valid.  If it is, then
1129                  *     cobble up a fake syncache entry, and return.
1130                  */
1131                 if (locked && !V_tcp_syncookies) {
1132                         SCH_UNLOCK(sch);
1133                         if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
1134                                 log(LOG_DEBUG, "%s; %s: Spurious ACK, "
1135                                     "segment rejected (syncookies disabled)\n",
1136                                     s, __func__);
1137                         goto failed;
1138                 }
1139                 if (locked && !V_tcp_syncookiesonly &&
1140                     sch->sch_last_overflow < time_uptime - SYNCOOKIE_LIFETIME) {
1141                         SCH_UNLOCK(sch);
1142                         if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
1143                                 log(LOG_DEBUG, "%s; %s: Spurious ACK, "
1144                                     "segment rejected (no syncache entry)\n",
1145                                     s, __func__);
1146                         goto failed;
1147                 }
1148                 bzero(&scs, sizeof(scs));
1149                 sc = syncookie_lookup(inc, sch, &scs, th, to, *lsop, port);
1150                 if (locked)
1151                         SCH_UNLOCK(sch);
1152                 if (sc == NULL) {
1153                         if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
1154                                 log(LOG_DEBUG, "%s; %s: Segment failed "
1155                                     "SYNCOOKIE authentication, segment rejected "
1156                                     "(probably spoofed)\n", s, __func__);
1157                         goto failed;
1158                 }
1159 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1160                 /* If received ACK has MD5 signature, check it. */
1161                 if ((to->to_flags & TOF_SIGNATURE) != 0 &&
1162                     (!TCPMD5_ENABLED() ||
1163                     TCPMD5_INPUT(m, th, to->to_signature) != 0)) {
1164                         /* Drop the ACK. */
1165                         if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1166                                 log(LOG_DEBUG, "%s; %s: Segment rejected, "
1167                                     "MD5 signature doesn't match.\n",
1168                                     s, __func__);
1169                                 free(s, M_TCPLOG);
1170                         }
1171                         TCPSTAT_INC(tcps_sig_err_sigopt);
1172                         return (-1); /* Do not send RST */
1173                 }
1174 #endif /* TCP_SIGNATURE */
1175         } else {
1176                 if (sc->sc_port != port) {
1177                         SCH_UNLOCK(sch);
1178                         return (0);
1179                 }
1180 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1181                 /*
1182                  * If listening socket requested TCP digests, check that
1183                  * received ACK has signature and it is correct.
1184                  * If not, drop the ACK and leave sc entry in th cache,
1185                  * because SYN was received with correct signature.
1186                  */
1187                 if (sc->sc_flags & SCF_SIGNATURE) {
1188                         if ((to->to_flags & TOF_SIGNATURE) == 0) {
1189                                 /* No signature */
1190                                 TCPSTAT_INC(tcps_sig_err_nosigopt);
1191                                 SCH_UNLOCK(sch);
1192                                 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1193                                         log(LOG_DEBUG, "%s; %s: Segment "
1194                                             "rejected, MD5 signature wasn't "
1195                                             "provided.\n", s, __func__);
1196                                         free(s, M_TCPLOG);
1197                                 }
1198                                 return (-1); /* Do not send RST */
1199                         }
1200                         if (!TCPMD5_ENABLED() ||
1201                             TCPMD5_INPUT(m, th, to->to_signature) != 0) {
1202                                 /* Doesn't match or no SA */
1203                                 SCH_UNLOCK(sch);
1204                                 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1205                                         log(LOG_DEBUG, "%s; %s: Segment "
1206                                             "rejected, MD5 signature doesn't "
1207                                             "match.\n", s, __func__);
1208                                         free(s, M_TCPLOG);
1209                                 }
1210                                 return (-1); /* Do not send RST */
1211                         }
1212                 }
1213 #endif /* TCP_SIGNATURE */
1214
1215                 /*
1216                  * RFC 7323 PAWS: If we have a timestamp on this segment and
1217                  * it's less than ts_recent, drop it.
1218                  * XXXMT: RFC 7323 also requires to send an ACK.
1219                  *        In tcp_input.c this is only done for TCP segments
1220                  *        with user data, so be consistent here and just drop
1221                  *        the segment.
1222                  */
1223                 if (sc->sc_flags & SCF_TIMESTAMP && to->to_flags & TOF_TS &&
1224                     TSTMP_LT(to->to_tsval, sc->sc_tsreflect)) {
1225                         SCH_UNLOCK(sch);
1226                         if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1227                                 log(LOG_DEBUG,
1228                                     "%s; %s: SEG.TSval %u < TS.Recent %u, "
1229                                     "segment dropped\n", s, __func__,
1230                                     to->to_tsval, sc->sc_tsreflect);
1231                                 free(s, M_TCPLOG);
1232                         }
1233                         return (-1);  /* Do not send RST */
1234                 }
1235
1236                 /*
1237                  * If timestamps were not negotiated during SYN/ACK and a
1238                  * segment with a timestamp is received, ignore the
1239                  * timestamp and process the packet normally.
1240                  * See section 3.2 of RFC 7323.
1241                  */
1242                 if (!(sc->sc_flags & SCF_TIMESTAMP) &&
1243                     (to->to_flags & TOF_TS)) {
1244                         if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1245                                 log(LOG_DEBUG, "%s; %s: Timestamp not "
1246                                     "expected, segment processed normally\n",
1247                                     s, __func__);
1248                                 free(s, M_TCPLOG);
1249                                 s = NULL;
1250                         }
1251                 }
1252
1253                 /*
1254                  * If timestamps were negotiated during SYN/ACK and a
1255                  * segment without a timestamp is received, silently drop
1256                  * the segment, unless the missing timestamps are tolerated.
1257                  * See section 3.2 of RFC 7323.
1258                  */
1259                 if ((sc->sc_flags & SCF_TIMESTAMP) &&
1260                     !(to->to_flags & TOF_TS)) {
1261                         if (V_tcp_tolerate_missing_ts) {
1262                                 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1263                                         log(LOG_DEBUG,
1264                                             "%s; %s: Timestamp missing, "
1265                                             "segment processed normally\n",
1266                                             s, __func__);
1267                                         free(s, M_TCPLOG);
1268                                 }
1269                         } else {
1270                                 SCH_UNLOCK(sch);
1271                                 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1272                                         log(LOG_DEBUG,
1273                                             "%s; %s: Timestamp missing, "
1274                                             "segment silently dropped\n",
1275                                             s, __func__);
1276                                         free(s, M_TCPLOG);
1277                                 }
1278                                 return (-1);  /* Do not send RST */
1279                         }
1280                 }
1281
1282                 /*
1283                  * Pull out the entry to unlock the bucket row.
1284                  *
1285                  * NOTE: We must decrease TCPS_SYN_RECEIVED count here, not
1286                  * tcp_state_change().  The tcpcb is not existent at this
1287                  * moment.  A new one will be allocated via syncache_socket->
1288                  * sonewconn->tcp_usr_attach in TCPS_CLOSED state, then
1289                  * syncache_socket() will change it to TCPS_SYN_RECEIVED.
1290                  */
1291                 TCPSTATES_DEC(TCPS_SYN_RECEIVED);
1292                 TAILQ_REMOVE(&sch->sch_bucket, sc, sc_hash);
1293                 sch->sch_length--;
1294 #ifdef TCP_OFFLOAD
1295                 if (ADDED_BY_TOE(sc)) {
1296                         struct toedev *tod = sc->sc_tod;
1297
1298                         tod->tod_syncache_removed(tod, sc->sc_todctx);
1299                 }
1300 #endif
1301                 SCH_UNLOCK(sch);
1302         }
1303
1304         /*
1305          * Segment validation:
1306          * ACK must match our initial sequence number + 1 (the SYN|ACK).
1307          */
1308         if (th->th_ack != sc->sc_iss + 1) {
1309                 if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
1310                         log(LOG_DEBUG, "%s; %s: ACK %u != ISS+1 %u, segment "
1311                             "rejected\n", s, __func__, th->th_ack, sc->sc_iss);
1312                 goto failed;
1313         }
1314
1315         /*
1316          * The SEQ must fall in the window starting at the received
1317          * initial receive sequence number + 1 (the SYN).
1318          */
1319         if (SEQ_LEQ(th->th_seq, sc->sc_irs) ||
1320             SEQ_GT(th->th_seq, sc->sc_irs + sc->sc_wnd)) {
1321                 if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
1322                         log(LOG_DEBUG, "%s; %s: SEQ %u != IRS+1 %u, segment "
1323                             "rejected\n", s, __func__, th->th_seq, sc->sc_irs);
1324                 goto failed;
1325         }
1326
1327         *lsop = syncache_socket(sc, *lsop, m);
1328
1329         if (*lsop == NULL)
1330                 TCPSTAT_INC(tcps_sc_aborted);
1331         else
1332                 TCPSTAT_INC(tcps_sc_completed);
1333
1334 /* how do we find the inp for the new socket? */
1335         if (sc != &scs)
1336                 syncache_free(sc);
1337         return (1);
1338 failed:
1339         if (sc != NULL && sc != &scs)
1340                 syncache_free(sc);
1341         if (s != NULL)
1342                 free(s, M_TCPLOG);
1343         *lsop = NULL;
1344         return (0);
1345 }
1346
1347 static void
1348 syncache_tfo_expand(struct syncache *sc, struct socket **lsop, struct mbuf *m,
1349     uint64_t response_cookie)
1350 {
1351         struct inpcb *inp;
1352         struct tcpcb *tp;
1353         unsigned int *pending_counter;
1354
1355         NET_EPOCH_ASSERT();
1356
1357         pending_counter = intotcpcb(sotoinpcb(*lsop))->t_tfo_pending;
1358         *lsop = syncache_socket(sc, *lsop, m);
1359         if (*lsop == NULL) {
1360                 TCPSTAT_INC(tcps_sc_aborted);
1361                 atomic_subtract_int(pending_counter, 1);
1362         } else {
1363                 soisconnected(*lsop);
1364                 inp = sotoinpcb(*lsop);
1365                 tp = intotcpcb(inp);
1366                 tp->t_flags |= TF_FASTOPEN;
1367                 tp->t_tfo_cookie.server = response_cookie;
1368                 tp->snd_max = tp->iss;
1369                 tp->snd_nxt = tp->iss;
1370                 tp->t_tfo_pending = pending_counter;
1371                 TCPSTATES_INC(TCPS_SYN_RECEIVED);
1372                 TCPSTAT_INC(tcps_sc_completed);
1373         }
1374 }
1375
1376 /*
1377  * Given a LISTEN socket and an inbound SYN request, add
1378  * this to the syn cache, and send back a segment:
1379  *      <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
1380  * to the source.
1381  *
1382  * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
1383  * Doing so would require that we hold onto the data and deliver it
1384  * to the application.  However, if we are the target of a SYN-flood
1385  * DoS attack, an attacker could send data which would eventually
1386  * consume all available buffer space if it were ACKed.  By not ACKing
1387  * the data, we avoid this DoS scenario.
1388  *
1389  * The exception to the above is when a SYN with a valid TCP Fast Open (TFO)
1390  * cookie is processed and a new socket is created.  In this case, any data
1391  * accompanying the SYN will be queued to the socket by tcp_input() and will
1392  * be ACKed either when the application sends response data or the delayed
1393  * ACK timer expires, whichever comes first.
1394  */
1395 int
1396 syncache_add(struct in_conninfo *inc, struct tcpopt *to, struct tcphdr *th,
1397     struct inpcb *inp, struct socket **lsop, struct mbuf *m, void *tod,
1398     void *todctx, uint8_t iptos, uint16_t port)
1399 {
1400         struct tcpcb *tp;
1401         struct socket *so;
1402         struct syncache *sc = NULL;
1403         struct syncache_head *sch;
1404         struct mbuf *ipopts = NULL;
1405         u_int ltflags;
1406         int win, ip_ttl, ip_tos;
1407         char *s;
1408         int rv = 0;
1409 #ifdef INET6
1410         int autoflowlabel = 0;
1411 #endif
1412 #ifdef MAC
1413         struct label *maclabel;
1414 #endif
1415         struct syncache scs;
1416         struct ucred *cred;
1417         uint64_t tfo_response_cookie;
1418         unsigned int *tfo_pending = NULL;
1419         int tfo_cookie_valid = 0;
1420         int tfo_response_cookie_valid = 0;
1421         bool locked;
1422
1423         INP_WLOCK_ASSERT(inp);                  /* listen socket */
1424         KASSERT((th->th_flags & (TH_RST|TH_ACK|TH_SYN)) == TH_SYN,
1425             ("%s: unexpected tcp flags", __func__));
1426
1427         /*
1428          * Combine all so/tp operations very early to drop the INP lock as
1429          * soon as possible.
1430          */
1431         so = *lsop;
1432         KASSERT(SOLISTENING(so), ("%s: %p not listening", __func__, so));
1433         tp = sototcpcb(so);
1434         cred = crhold(so->so_cred);
1435
1436 #ifdef INET6
1437         if (inc->inc_flags & INC_ISIPV6) {
1438                 if (inp->inp_flags & IN6P_AUTOFLOWLABEL) {
1439                         autoflowlabel = 1;
1440                 }
1441                 ip_ttl = in6_selecthlim(inp, NULL);
1442                 if ((inp->in6p_outputopts == NULL) ||
1443                     (inp->in6p_outputopts->ip6po_tclass == -1)) {
1444                         ip_tos = 0;
1445                 } else {
1446                         ip_tos = inp->in6p_outputopts->ip6po_tclass;
1447                 }
1448         }
1449 #endif
1450 #if defined(INET6) && defined(INET)
1451         else
1452 #endif
1453 #ifdef INET
1454         {
1455                 ip_ttl = inp->inp_ip_ttl;
1456                 ip_tos = inp->inp_ip_tos;
1457         }
1458 #endif
1459         win = so->sol_sbrcv_hiwat;
1460         ltflags = (tp->t_flags & (TF_NOOPT | TF_SIGNATURE));
1461
1462         if (V_tcp_fastopen_server_enable && IS_FASTOPEN(tp->t_flags) &&
1463             (tp->t_tfo_pending != NULL) &&
1464             (to->to_flags & TOF_FASTOPEN)) {
1465                 /*
1466                  * Limit the number of pending TFO connections to
1467                  * approximately half of the queue limit.  This prevents TFO
1468                  * SYN floods from starving the service by filling the
1469                  * listen queue with bogus TFO connections.
1470                  */
1471                 if (atomic_fetchadd_int(tp->t_tfo_pending, 1) <=
1472                     (so->sol_qlimit / 2)) {
1473                         int result;
1474
1475                         result = tcp_fastopen_check_cookie(inc,
1476                             to->to_tfo_cookie, to->to_tfo_len,
1477                             &tfo_response_cookie);
1478                         tfo_cookie_valid = (result > 0);
1479                         tfo_response_cookie_valid = (result >= 0);
1480                 }
1481
1482                 /*
1483                  * Remember the TFO pending counter as it will have to be
1484                  * decremented below if we don't make it to syncache_tfo_expand().
1485                  */
1486                 tfo_pending = tp->t_tfo_pending;
1487         }
1488
1489         /* By the time we drop the lock these should no longer be used. */
1490         so = NULL;
1491         tp = NULL;
1492
1493 #ifdef MAC
1494         if (mac_syncache_init(&maclabel) != 0) {
1495                 INP_WUNLOCK(inp);
1496                 goto done;
1497         } else
1498                 mac_syncache_create(maclabel, inp);
1499 #endif
1500         if (!tfo_cookie_valid)
1501                 INP_WUNLOCK(inp);
1502
1503         /*
1504          * Remember the IP options, if any.
1505          */
1506 #ifdef INET6
1507         if (!(inc->inc_flags & INC_ISIPV6))
1508 #endif
1509 #ifdef INET
1510                 ipopts = (m) ? ip_srcroute(m) : NULL;
1511 #else
1512                 ipopts = NULL;
1513 #endif
1514
1515 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1516         /*
1517          * When the socket is TCP-MD5 enabled check that,
1518          *  - a signed packet is valid
1519          *  - a non-signed packet does not have a security association
1520          *
1521          *  If a signed packet fails validation or a non-signed packet has a
1522          *  security association, the packet will be dropped.
1523          */
1524         if (ltflags & TF_SIGNATURE) {
1525                 if (to->to_flags & TOF_SIGNATURE) {
1526                         if (!TCPMD5_ENABLED() ||
1527                             TCPMD5_INPUT(m, th, to->to_signature) != 0)
1528                                 goto done;
1529                 } else {
1530                         if (TCPMD5_ENABLED() &&
1531                             TCPMD5_INPUT(m, NULL, NULL) != ENOENT)
1532                                 goto done;
1533                 }
1534         } else if (to->to_flags & TOF_SIGNATURE)
1535                 goto done;
1536 #endif  /* TCP_SIGNATURE */
1537         /*
1538          * See if we already have an entry for this connection.
1539          * If we do, resend the SYN,ACK, and reset the retransmit timer.
1540          *
1541          * XXX: should the syncache be re-initialized with the contents
1542          * of the new SYN here (which may have different options?)
1543          *
1544          * XXX: We do not check the sequence number to see if this is a
1545          * real retransmit or a new connection attempt.  The question is
1546          * how to handle such a case; either ignore it as spoofed, or
1547          * drop the current entry and create a new one?
1548          */
1549         if (syncache_cookiesonly()) {
1550                 sc = NULL;
1551                 sch = syncache_hashbucket(inc);
1552                 locked = false;
1553         } else {
1554                 sc = syncache_lookup(inc, &sch);        /* returns locked sch */
1555                 locked = true;
1556                 SCH_LOCK_ASSERT(sch);
1557         }
1558         if (sc != NULL) {
1559                 if (tfo_cookie_valid)
1560                         INP_WUNLOCK(inp);
1561                 TCPSTAT_INC(tcps_sc_dupsyn);
1562                 if (ipopts) {
1563                         /*
1564                          * If we were remembering a previous source route,
1565                          * forget it and use the new one we've been given.
1566                          */
1567                         if (sc->sc_ipopts)
1568                                 (void) m_free(sc->sc_ipopts);
1569                         sc->sc_ipopts = ipopts;
1570                 }
1571                 /*
1572                  * Update timestamp if present.
1573                  */
1574                 if ((sc->sc_flags & SCF_TIMESTAMP) && (to->to_flags & TOF_TS))
1575                         sc->sc_tsreflect = to->to_tsval;
1576                 else
1577                         sc->sc_flags &= ~SCF_TIMESTAMP;
1578                 /*
1579                  * Disable ECN if needed.
1580                  */
1581                 if ((sc->sc_flags & SCF_ECN) &&
1582                     ((th->th_flags & (TH_ECE|TH_CWR)) != (TH_ECE|TH_CWR))) {
1583                         sc->sc_flags &= ~SCF_ECN;
1584                 }
1585 #ifdef MAC
1586                 /*
1587                  * Since we have already unconditionally allocated label
1588                  * storage, free it up.  The syncache entry will already
1589                  * have an initialized label we can use.
1590                  */
1591                 mac_syncache_destroy(&maclabel);
1592 #endif
1593                 TCP_PROBE5(receive, NULL, NULL, m, NULL, th);
1594                 /* Retransmit SYN|ACK and reset retransmit count. */
1595                 if ((s = tcp_log_addrs(&sc->sc_inc, th, NULL, NULL))) {
1596                         log(LOG_DEBUG, "%s; %s: Received duplicate SYN, "
1597                             "resetting timer and retransmitting SYN|ACK\n",
1598                             s, __func__);
1599                         free(s, M_TCPLOG);
1600                 }
1601                 if (syncache_respond(sc, m, TH_SYN|TH_ACK) == 0) {
1602                         sc->sc_rxmits = 0;
1603                         syncache_timeout(sc, sch, 1);
1604                         TCPSTAT_INC(tcps_sndacks);
1605                         TCPSTAT_INC(tcps_sndtotal);
1606                 }
1607                 SCH_UNLOCK(sch);
1608                 goto donenoprobe;
1609         }
1610
1611         if (tfo_cookie_valid) {
1612                 bzero(&scs, sizeof(scs));
1613                 sc = &scs;
1614                 goto skip_alloc;
1615         }
1616
1617         /*
1618          * Skip allocating a syncache entry if we are just going to discard
1619          * it later.
1620          */
1621         if (!locked) {
1622                 bzero(&scs, sizeof(scs));
1623                 sc = &scs;
1624         } else
1625                 sc = uma_zalloc(V_tcp_syncache.zone, M_NOWAIT | M_ZERO);
1626         if (sc == NULL) {
1627                 /*
1628                  * The zone allocator couldn't provide more entries.
1629                  * Treat this as if the cache was full; drop the oldest
1630                  * entry and insert the new one.
1631                  */
1632                 TCPSTAT_INC(tcps_sc_zonefail);
1633                 if ((sc = TAILQ_LAST(&sch->sch_bucket, sch_head)) != NULL) {
1634                         sch->sch_last_overflow = time_uptime;
1635                         syncache_drop(sc, sch);
1636                         syncache_pause(inc);
1637                 }
1638                 sc = uma_zalloc(V_tcp_syncache.zone, M_NOWAIT | M_ZERO);
1639                 if (sc == NULL) {
1640                         if (V_tcp_syncookies) {
1641                                 bzero(&scs, sizeof(scs));
1642                                 sc = &scs;
1643                         } else {
1644                                 KASSERT(locked,
1645                                     ("%s: bucket unexpectedly unlocked",
1646                                     __func__));
1647                                 SCH_UNLOCK(sch);
1648                                 if (ipopts)
1649                                         (void) m_free(ipopts);
1650                                 goto done;
1651                         }
1652                 }
1653         }
1654
1655 skip_alloc:
1656         if (!tfo_cookie_valid && tfo_response_cookie_valid)
1657                 sc->sc_tfo_cookie = &tfo_response_cookie;
1658
1659         /*
1660          * Fill in the syncache values.
1661          */
1662 #ifdef MAC
1663         sc->sc_label = maclabel;
1664 #endif
1665         sc->sc_cred = cred;
1666         sc->sc_port = port;
1667         cred = NULL;
1668         sc->sc_ipopts = ipopts;
1669         bcopy(inc, &sc->sc_inc, sizeof(struct in_conninfo));
1670         sc->sc_ip_tos = ip_tos;
1671         sc->sc_ip_ttl = ip_ttl;
1672 #ifdef TCP_OFFLOAD
1673         sc->sc_tod = tod;
1674         sc->sc_todctx = todctx;
1675 #endif
1676         sc->sc_irs = th->th_seq;
1677         sc->sc_flags = 0;
1678         sc->sc_flowlabel = 0;
1679
1680         /*
1681          * Initial receive window: clip sbspace to [0 .. TCP_MAXWIN].
1682          * win was derived from socket earlier in the function.
1683          */
1684         win = imax(win, 0);
1685         win = imin(win, TCP_MAXWIN);
1686         sc->sc_wnd = win;
1687
1688         if (V_tcp_do_rfc1323 &&
1689             !(ltflags & TF_NOOPT)) {
1690                 /*
1691                  * A timestamp received in a SYN makes
1692                  * it ok to send timestamp requests and replies.
1693                  */
1694                 if (to->to_flags & TOF_TS) {
1695                         sc->sc_tsreflect = to->to_tsval;
1696                         sc->sc_flags |= SCF_TIMESTAMP;
1697                         sc->sc_tsoff = tcp_new_ts_offset(inc);
1698                 }
1699                 if (to->to_flags & TOF_SCALE) {
1700                         int wscale = 0;
1701
1702                         /*
1703                          * Pick the smallest possible scaling factor that
1704                          * will still allow us to scale up to sb_max, aka
1705                          * kern.ipc.maxsockbuf.
1706                          *
1707                          * We do this because there are broken firewalls that
1708                          * will corrupt the window scale option, leading to
1709                          * the other endpoint believing that our advertised
1710                          * window is unscaled.  At scale factors larger than
1711                          * 5 the unscaled window will drop below 1500 bytes,
1712                          * leading to serious problems when traversing these
1713                          * broken firewalls.
1714                          *
1715                          * With the default maxsockbuf of 256K, a scale factor
1716                          * of 3 will be chosen by this algorithm.  Those who
1717                          * choose a larger maxsockbuf should watch out
1718                          * for the compatibility problems mentioned above.
1719                          *
1720                          * RFC1323: The Window field in a SYN (i.e., a <SYN>
1721                          * or <SYN,ACK>) segment itself is never scaled.
1722                          */
1723                         while (wscale < TCP_MAX_WINSHIFT &&
1724                             (TCP_MAXWIN << wscale) < sb_max)
1725                                 wscale++;
1726                         sc->sc_requested_r_scale = wscale;
1727                         sc->sc_requested_s_scale = to->to_wscale;
1728                         sc->sc_flags |= SCF_WINSCALE;
1729                 }
1730         }
1731 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1732         /*
1733          * If incoming packet has an MD5 signature, flag this in the
1734          * syncache so that syncache_respond() will do the right thing
1735          * with the SYN+ACK.
1736          */
1737         if (to->to_flags & TOF_SIGNATURE)
1738                 sc->sc_flags |= SCF_SIGNATURE;
1739 #endif  /* TCP_SIGNATURE */
1740         if (to->to_flags & TOF_SACKPERM)
1741                 sc->sc_flags |= SCF_SACK;
1742         if (to->to_flags & TOF_MSS)
1743                 sc->sc_peer_mss = to->to_mss;   /* peer mss may be zero */
1744         if (ltflags & TF_NOOPT)
1745                 sc->sc_flags |= SCF_NOOPT;
1746         if (((th->th_flags & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) &&
1747             V_tcp_do_ecn)
1748                 sc->sc_flags |= SCF_ECN;
1749
1750         if (V_tcp_syncookies)
1751                 sc->sc_iss = syncookie_generate(sch, sc);
1752         else
1753                 sc->sc_iss = arc4random();
1754 #ifdef INET6
1755         if (autoflowlabel) {
1756                 if (V_tcp_syncookies)
1757                         sc->sc_flowlabel = sc->sc_iss;
1758                 else
1759                         sc->sc_flowlabel = ip6_randomflowlabel();
1760                 sc->sc_flowlabel = htonl(sc->sc_flowlabel) & IPV6_FLOWLABEL_MASK;
1761         }
1762 #endif
1763         if (locked)
1764                 SCH_UNLOCK(sch);
1765
1766         if (tfo_cookie_valid) {
1767                 syncache_tfo_expand(sc, lsop, m, tfo_response_cookie);
1768                 /* INP_WUNLOCK(inp) will be performed by the caller */
1769                 rv = 1;
1770                 goto tfo_expanded;
1771         }
1772
1773         TCP_PROBE5(receive, NULL, NULL, m, NULL, th);
1774         /*
1775          * Do a standard 3-way handshake.
1776          */
1777         if (syncache_respond(sc, m, TH_SYN|TH_ACK) == 0) {
1778                 if (V_tcp_syncookies && V_tcp_syncookiesonly && sc != &scs)
1779                         syncache_free(sc);
1780                 else if (sc != &scs)
1781                         syncache_insert(sc, sch);   /* locks and unlocks sch */
1782                 TCPSTAT_INC(tcps_sndacks);
1783                 TCPSTAT_INC(tcps_sndtotal);
1784         } else {
1785                 if (sc != &scs)
1786                         syncache_free(sc);
1787                 TCPSTAT_INC(tcps_sc_dropped);
1788         }
1789         goto donenoprobe;
1790
1791 done:
1792         TCP_PROBE5(receive, NULL, NULL, m, NULL, th);
1793 donenoprobe:
1794         if (m) {
1795                 *lsop = NULL;
1796                 m_freem(m);
1797         }
1798         /*
1799          * If tfo_pending is not NULL here, then a TFO SYN that did not
1800          * result in a new socket was processed and the associated pending
1801          * counter has not yet been decremented.  All such TFO processing paths
1802          * transit this point.
1803          */
1804         if (tfo_pending != NULL)
1805                 tcp_fastopen_decrement_counter(tfo_pending);
1806
1807 tfo_expanded:
1808         if (cred != NULL)
1809                 crfree(cred);
1810 #ifdef MAC
1811         if (sc == &scs)
1812                 mac_syncache_destroy(&maclabel);
1813 #endif
1814         return (rv);
1815 }
1816
1817 /*
1818  * Send SYN|ACK or ACK to the peer.  Either in response to a peer's segment,
1819  * i.e. m0 != NULL, or upon 3WHS ACK timeout, i.e. m0 == NULL.
1820  */
1821 static int
1822 syncache_respond(struct syncache *sc, const struct mbuf *m0, int flags)
1823 {
1824         struct ip *ip = NULL;
1825         struct mbuf *m;
1826         struct tcphdr *th = NULL;
1827         struct udphdr *udp = NULL;
1828         int optlen, error = 0;  /* Make compiler happy */
1829         u_int16_t hlen, tlen, mssopt, ulen;
1830         struct tcpopt to;
1831 #ifdef INET6
1832         struct ip6_hdr *ip6 = NULL;
1833 #endif
1834
1835         NET_EPOCH_ASSERT();
1836
1837         hlen =
1838 #ifdef INET6
1839                (sc->sc_inc.inc_flags & INC_ISIPV6) ? sizeof(struct ip6_hdr) :
1840 #endif
1841                 sizeof(struct ip);
1842         tlen = hlen + sizeof(struct tcphdr);
1843         if (sc->sc_port) {
1844                 tlen += sizeof(struct udphdr);
1845         }
1846         /* Determine MSS we advertize to other end of connection. */
1847         mssopt = tcp_mssopt(&sc->sc_inc);
1848         if (sc->sc_port)
1849                 mssopt -= V_tcp_udp_tunneling_overhead;
1850         mssopt = max(mssopt, V_tcp_minmss);
1851
1852         /* XXX: Assume that the entire packet will fit in a header mbuf. */
1853         KASSERT(max_linkhdr + tlen + TCP_MAXOLEN <= MHLEN,
1854             ("syncache: mbuf too small: hlen %u, sc_port %u, max_linkhdr %d + "
1855             "tlen %d + TCP_MAXOLEN %ju <= MHLEN %d", hlen, sc->sc_port,
1856             max_linkhdr, tlen, (uintmax_t)TCP_MAXOLEN, MHLEN));
1857
1858         /* Create the IP+TCP header from scratch. */
1859         m = m_gethdr(M_NOWAIT, MT_DATA);
1860         if (m == NULL)
1861                 return (ENOBUFS);
1862 #ifdef MAC
1863         mac_syncache_create_mbuf(sc->sc_label, m);
1864 #endif
1865         m->m_data += max_linkhdr;
1866         m->m_len = tlen;
1867         m->m_pkthdr.len = tlen;
1868         m->m_pkthdr.rcvif = NULL;
1869
1870 #ifdef INET6
1871         if (sc->sc_inc.inc_flags & INC_ISIPV6) {
1872                 ip6 = mtod(m, struct ip6_hdr *);
1873                 ip6->ip6_vfc = IPV6_VERSION;
1874                 ip6->ip6_src = sc->sc_inc.inc6_laddr;
1875                 ip6->ip6_dst = sc->sc_inc.inc6_faddr;
1876                 ip6->ip6_plen = htons(tlen - hlen);
1877                 /* ip6_hlim is set after checksum */
1878                 /* Zero out traffic class and flow label. */
1879                 ip6->ip6_flow &= ~IPV6_FLOWINFO_MASK;
1880                 ip6->ip6_flow |= sc->sc_flowlabel;
1881                 if (sc->sc_port != 0) {
1882                         ip6->ip6_nxt = IPPROTO_UDP;
1883                         udp = (struct udphdr *)(ip6 + 1);
1884                         udp->uh_sport = htons(V_tcp_udp_tunneling_port);
1885                         udp->uh_dport = sc->sc_port;
1886                         ulen = (tlen - sizeof(struct ip6_hdr));
1887                         th = (struct tcphdr *)(udp + 1);
1888                 } else {
1889                         ip6->ip6_nxt = IPPROTO_TCP;
1890                         th = (struct tcphdr *)(ip6 + 1);
1891                 }
1892                 ip6->ip6_flow |= htonl(sc->sc_ip_tos << 20);
1893         }
1894 #endif
1895 #if defined(INET6) && defined(INET)
1896         else
1897 #endif
1898 #ifdef INET
1899         {
1900                 ip = mtod(m, struct ip *);
1901                 ip->ip_v = IPVERSION;
1902                 ip->ip_hl = sizeof(struct ip) >> 2;
1903                 ip->ip_len = htons(tlen);
1904                 ip->ip_id = 0;
1905                 ip->ip_off = 0;
1906                 ip->ip_sum = 0;
1907                 ip->ip_src = sc->sc_inc.inc_laddr;
1908                 ip->ip_dst = sc->sc_inc.inc_faddr;
1909                 ip->ip_ttl = sc->sc_ip_ttl;
1910                 ip->ip_tos = sc->sc_ip_tos;
1911
1912                 /*
1913                  * See if we should do MTU discovery.  Route lookups are
1914                  * expensive, so we will only unset the DF bit if:
1915                  *
1916                  *      1) path_mtu_discovery is disabled
1917                  *      2) the SCF_UNREACH flag has been set
1918                  */
1919                 if (V_path_mtu_discovery && ((sc->sc_flags & SCF_UNREACH) == 0))
1920                        ip->ip_off |= htons(IP_DF);
1921                 if (sc->sc_port == 0) {
1922                         ip->ip_p = IPPROTO_TCP;
1923                         th = (struct tcphdr *)(ip + 1);
1924                 } else {
1925                         ip->ip_p = IPPROTO_UDP;
1926                         udp = (struct udphdr *)(ip + 1);
1927                         udp->uh_sport = htons(V_tcp_udp_tunneling_port);
1928                         udp->uh_dport = sc->sc_port;
1929                         ulen = (tlen - sizeof(struct ip));
1930                         th = (struct tcphdr *)(udp + 1);
1931                 }
1932         }
1933 #endif /* INET */
1934         th->th_sport = sc->sc_inc.inc_lport;
1935         th->th_dport = sc->sc_inc.inc_fport;
1936
1937         if (flags & TH_SYN)
1938                 th->th_seq = htonl(sc->sc_iss);
1939         else
1940                 th->th_seq = htonl(sc->sc_iss + 1);
1941         th->th_ack = htonl(sc->sc_irs + 1);
1942         th->th_off = sizeof(struct tcphdr) >> 2;
1943         th->th_x2 = 0;
1944         th->th_flags = flags;
1945         th->th_win = htons(sc->sc_wnd);
1946         th->th_urp = 0;
1947
1948         if ((flags & TH_SYN) && (sc->sc_flags & SCF_ECN)) {
1949                 th->th_flags |= TH_ECE;
1950                 TCPSTAT_INC(tcps_ecn_shs);
1951         }
1952
1953         /* Tack on the TCP options. */
1954         if ((sc->sc_flags & SCF_NOOPT) == 0) {
1955                 to.to_flags = 0;
1956
1957                 if (flags & TH_SYN) {
1958                         to.to_mss = mssopt;
1959                         to.to_flags = TOF_MSS;
1960                         if (sc->sc_flags & SCF_WINSCALE) {
1961                                 to.to_wscale = sc->sc_requested_r_scale;
1962                                 to.to_flags |= TOF_SCALE;
1963                         }
1964                         if (sc->sc_flags & SCF_SACK)
1965                                 to.to_flags |= TOF_SACKPERM;
1966 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1967                         if (sc->sc_flags & SCF_SIGNATURE)
1968                                 to.to_flags |= TOF_SIGNATURE;
1969 #endif
1970                         if (sc->sc_tfo_cookie) {
1971                                 to.to_flags |= TOF_FASTOPEN;
1972                                 to.to_tfo_len = TCP_FASTOPEN_COOKIE_LEN;
1973                                 to.to_tfo_cookie = sc->sc_tfo_cookie;
1974                                 /* don't send cookie again when retransmitting response */
1975                                 sc->sc_tfo_cookie = NULL;
1976                         }
1977                 }
1978                 if (sc->sc_flags & SCF_TIMESTAMP) {
1979                         to.to_tsval = sc->sc_tsoff + tcp_ts_getticks();
1980                         to.to_tsecr = sc->sc_tsreflect;
1981                         to.to_flags |= TOF_TS;
1982                 }
1983                 optlen = tcp_addoptions(&to, (u_char *)(th + 1));
1984
1985                 /* Adjust headers by option size. */
1986                 th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
1987                 m->m_len += optlen;
1988                 m->m_pkthdr.len += optlen;
1989 #ifdef INET6
1990                 if (sc->sc_inc.inc_flags & INC_ISIPV6)
1991                         ip6->ip6_plen = htons(ntohs(ip6->ip6_plen) + optlen);
1992                 else
1993 #endif
1994                         ip->ip_len = htons(ntohs(ip->ip_len) + optlen);
1995 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1996                 if (sc->sc_flags & SCF_SIGNATURE) {
1997                         KASSERT(to.to_flags & TOF_SIGNATURE,
1998                             ("tcp_addoptions() didn't set tcp_signature"));
1999
2000                         /* NOTE: to.to_signature is inside of mbuf */
2001                         if (!TCPMD5_ENABLED() ||
2002                             TCPMD5_OUTPUT(m, th, to.to_signature) != 0) {
2003                                 m_freem(m);
2004                                 return (EACCES);
2005                         }
2006                 }
2007 #endif
2008         } else
2009                 optlen = 0;
2010
2011         if (udp) {
2012                 ulen += optlen;
2013                 udp->uh_ulen = htons(ulen);
2014         }
2015         M_SETFIB(m, sc->sc_inc.inc_fibnum);
2016         /*
2017          * If we have peer's SYN and it has a flowid, then let's assign it to
2018          * our SYN|ACK.  ip6_output() and ip_output() will not assign flowid
2019          * to SYN|ACK due to lack of inp here.
2020          */
2021         if (m0 != NULL && M_HASHTYPE_GET(m0) != M_HASHTYPE_NONE) {
2022                 m->m_pkthdr.flowid = m0->m_pkthdr.flowid;
2023                 M_HASHTYPE_SET(m, M_HASHTYPE_GET(m0));
2024         }
2025 #ifdef INET6
2026         if (sc->sc_inc.inc_flags & INC_ISIPV6) {
2027                 if (sc->sc_port) {
2028                         m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
2029                         m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
2030                         udp->uh_sum = in6_cksum_pseudo(ip6, ulen,
2031                               IPPROTO_UDP, 0);
2032                         th->th_sum = htons(0);
2033                 } else {
2034                         m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
2035                         m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
2036                         th->th_sum = in6_cksum_pseudo(ip6, tlen + optlen - hlen,
2037                             IPPROTO_TCP, 0);
2038                 }
2039                 ip6->ip6_hlim = sc->sc_ip_ttl;
2040 #ifdef TCP_OFFLOAD
2041                 if (ADDED_BY_TOE(sc)) {
2042                         struct toedev *tod = sc->sc_tod;
2043
2044                         error = tod->tod_syncache_respond(tod, sc->sc_todctx, m);
2045
2046                         return (error);
2047                 }
2048 #endif
2049                 TCP_PROBE5(send, NULL, NULL, ip6, NULL, th);
2050                 error = ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
2051         }
2052 #endif
2053 #if defined(INET6) && defined(INET)
2054         else
2055 #endif
2056 #ifdef INET
2057         {
2058                 if (sc->sc_port) {
2059                         m->m_pkthdr.csum_flags = CSUM_UDP;
2060                         m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
2061                         udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
2062                               ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP));
2063                         th->th_sum = htons(0);
2064                 } else {
2065                         m->m_pkthdr.csum_flags = CSUM_TCP;
2066                         m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
2067                         th->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
2068                             htons(tlen + optlen - hlen + IPPROTO_TCP));
2069                 }
2070 #ifdef TCP_OFFLOAD
2071                 if (ADDED_BY_TOE(sc)) {
2072                         struct toedev *tod = sc->sc_tod;
2073
2074                         error = tod->tod_syncache_respond(tod, sc->sc_todctx, m);
2075
2076                         return (error);
2077                 }
2078 #endif
2079                 TCP_PROBE5(send, NULL, NULL, ip, NULL, th);
2080                 error = ip_output(m, sc->sc_ipopts, NULL, 0, NULL, NULL);
2081         }
2082 #endif
2083         return (error);
2084 }
2085
2086 /*
2087  * The purpose of syncookies is to handle spoofed SYN flooding DoS attacks
2088  * that exceed the capacity of the syncache by avoiding the storage of any
2089  * of the SYNs we receive.  Syncookies defend against blind SYN flooding
2090  * attacks where the attacker does not have access to our responses.
2091  *
2092  * Syncookies encode and include all necessary information about the
2093  * connection setup within the SYN|ACK that we send back.  That way we
2094  * can avoid keeping any local state until the ACK to our SYN|ACK returns
2095  * (if ever).  Normally the syncache and syncookies are running in parallel
2096  * with the latter taking over when the former is exhausted.  When matching
2097  * syncache entry is found the syncookie is ignored.
2098  *
2099  * The only reliable information persisting the 3WHS is our initial sequence
2100  * number ISS of 32 bits.  Syncookies embed a cryptographically sufficient
2101  * strong hash (MAC) value and a few bits of TCP SYN options in the ISS
2102  * of our SYN|ACK.  The MAC can be recomputed when the ACK to our SYN|ACK
2103  * returns and signifies a legitimate connection if it matches the ACK.
2104  *
2105  * The available space of 32 bits to store the hash and to encode the SYN
2106  * option information is very tight and we should have at least 24 bits for
2107  * the MAC to keep the number of guesses by blind spoofing reasonably high.
2108  *
2109  * SYN option information we have to encode to fully restore a connection:
2110  * MSS: is imporant to chose an optimal segment size to avoid IP level
2111  *   fragmentation along the path.  The common MSS values can be encoded
2112  *   in a 3-bit table.  Uncommon values are captured by the next lower value
2113  *   in the table leading to a slight increase in packetization overhead.
2114  * WSCALE: is necessary to allow large windows to be used for high delay-
2115  *   bandwidth product links.  Not scaling the window when it was initially
2116  *   negotiated is bad for performance as lack of scaling further decreases
2117  *   the apparent available send window.  We only need to encode the WSCALE
2118  *   we received from the remote end.  Our end can be recalculated at any
2119  *   time.  The common WSCALE values can be encoded in a 3-bit table.
2120  *   Uncommon values are captured by the next lower value in the table
2121  *   making us under-estimate the available window size halving our
2122  *   theoretically possible maximum throughput for that connection.
2123  * SACK: Greatly assists in packet loss recovery and requires 1 bit.
2124  * TIMESTAMP and SIGNATURE is not encoded because they are permanent options
2125  *   that are included in all segments on a connection.  We enable them when
2126  *   the ACK has them.
2127  *
2128  * Security of syncookies and attack vectors:
2129  *
2130  * The MAC is computed over (faddr||laddr||fport||lport||irs||flags||secmod)
2131  * together with the gloabl secret to make it unique per connection attempt.
2132  * Thus any change of any of those parameters results in a different MAC output
2133  * in an unpredictable way unless a collision is encountered.  24 bits of the
2134  * MAC are embedded into the ISS.
2135  *
2136  * To prevent replay attacks two rotating global secrets are updated with a
2137  * new random value every 15 seconds.  The life-time of a syncookie is thus
2138  * 15-30 seconds.
2139  *
2140  * Vector 1: Attacking the secret.  This requires finding a weakness in the
2141  * MAC itself or the way it is used here.  The attacker can do a chosen plain
2142  * text attack by varying and testing the all parameters under his control.
2143  * The strength depends on the size and randomness of the secret, and the
2144  * cryptographic security of the MAC function.  Due to the constant updating
2145  * of the secret the attacker has at most 29.999 seconds to find the secret
2146  * and launch spoofed connections.  After that he has to start all over again.
2147  *
2148  * Vector 2: Collision attack on the MAC of a single ACK.  With a 24 bit MAC
2149  * size an average of 4,823 attempts are required for a 50% chance of success
2150  * to spoof a single syncookie (birthday collision paradox).  However the
2151  * attacker is blind and doesn't know if one of his attempts succeeded unless
2152  * he has a side channel to interfere success from.  A single connection setup
2153  * success average of 90% requires 8,790 packets, 99.99% requires 17,578 packets.
2154  * This many attempts are required for each one blind spoofed connection.  For
2155  * every additional spoofed connection he has to launch another N attempts.
2156  * Thus for a sustained rate 100 spoofed connections per second approximately
2157  * 1,800,000 packets per second would have to be sent.
2158  *
2159  * NB: The MAC function should be fast so that it doesn't become a CPU
2160  * exhaustion attack vector itself.
2161  *
2162  * References:
2163  *  RFC4987 TCP SYN Flooding Attacks and Common Mitigations
2164  *  SYN cookies were first proposed by cryptographer Dan J. Bernstein in 1996
2165  *   http://cr.yp.to/syncookies.html    (overview)
2166  *   http://cr.yp.to/syncookies/archive (details)
2167  *
2168  *
2169  * Schematic construction of a syncookie enabled Initial Sequence Number:
2170  *  0        1         2         3
2171  *  12345678901234567890123456789012
2172  * |xxxxxxxxxxxxxxxxxxxxxxxxWWWMMMSP|
2173  *
2174  *  x 24 MAC (truncated)
2175  *  W  3 Send Window Scale index
2176  *  M  3 MSS index
2177  *  S  1 SACK permitted
2178  *  P  1 Odd/even secret
2179  */
2180
2181 /*
2182  * Distribution and probability of certain MSS values.  Those in between are
2183  * rounded down to the next lower one.
2184  * [An Analysis of TCP Maximum Segment Sizes, S. Alcock and R. Nelson, 2011]
2185  *                            .2%  .3%   5%    7%    7%    20%   15%   45%
2186  */
2187 static int tcp_sc_msstab[] = { 216, 536, 1200, 1360, 1400, 1440, 1452, 1460 };
2188
2189 /*
2190  * Distribution and probability of certain WSCALE values.  We have to map the
2191  * (send) window scale (shift) option with a range of 0-14 from 4 bits into 3
2192  * bits based on prevalence of certain values.  Where we don't have an exact
2193  * match for are rounded down to the next lower one letting us under-estimate
2194  * the true available window.  At the moment this would happen only for the
2195  * very uncommon values 3, 5 and those above 8 (more than 16MB socket buffer
2196  * and window size).  The absence of the WSCALE option (no scaling in either
2197  * direction) is encoded with index zero.
2198  * [WSCALE values histograms, Allman, 2012]
2199  *                            X 10 10 35  5  6 14 10%   by host
2200  *                            X 11  4  5  5 18 49  3%   by connections
2201  */
2202 static int tcp_sc_wstab[] = { 0, 0, 1, 2, 4, 6, 7, 8 };
2203
2204 /*
2205  * Compute the MAC for the SYN cookie.  SIPHASH-2-4 is chosen for its speed
2206  * and good cryptographic properties.
2207  */
2208 static uint32_t
2209 syncookie_mac(struct in_conninfo *inc, tcp_seq irs, uint8_t flags,
2210     uint8_t *secbits, uintptr_t secmod)
2211 {
2212         SIPHASH_CTX ctx;
2213         uint32_t siphash[2];
2214
2215         SipHash24_Init(&ctx);
2216         SipHash_SetKey(&ctx, secbits);
2217         switch (inc->inc_flags & INC_ISIPV6) {
2218 #ifdef INET
2219         case 0:
2220                 SipHash_Update(&ctx, &inc->inc_faddr, sizeof(inc->inc_faddr));
2221                 SipHash_Update(&ctx, &inc->inc_laddr, sizeof(inc->inc_laddr));
2222                 break;
2223 #endif
2224 #ifdef INET6
2225         case INC_ISIPV6:
2226                 SipHash_Update(&ctx, &inc->inc6_faddr, sizeof(inc->inc6_faddr));
2227                 SipHash_Update(&ctx, &inc->inc6_laddr, sizeof(inc->inc6_laddr));
2228                 break;
2229 #endif
2230         }
2231         SipHash_Update(&ctx, &inc->inc_fport, sizeof(inc->inc_fport));
2232         SipHash_Update(&ctx, &inc->inc_lport, sizeof(inc->inc_lport));
2233         SipHash_Update(&ctx, &irs, sizeof(irs));
2234         SipHash_Update(&ctx, &flags, sizeof(flags));
2235         SipHash_Update(&ctx, &secmod, sizeof(secmod));
2236         SipHash_Final((u_int8_t *)&siphash, &ctx);
2237
2238         return (siphash[0] ^ siphash[1]);
2239 }
2240
2241 static tcp_seq
2242 syncookie_generate(struct syncache_head *sch, struct syncache *sc)
2243 {
2244         u_int i, secbit, wscale;
2245         uint32_t iss, hash;
2246         uint8_t *secbits;
2247         union syncookie cookie;
2248
2249         cookie.cookie = 0;
2250
2251         /* Map our computed MSS into the 3-bit index. */
2252         for (i = nitems(tcp_sc_msstab) - 1;
2253              tcp_sc_msstab[i] > sc->sc_peer_mss && i > 0;
2254              i--)
2255                 ;
2256         cookie.flags.mss_idx = i;
2257
2258         /*
2259          * Map the send window scale into the 3-bit index but only if
2260          * the wscale option was received.
2261          */
2262         if (sc->sc_flags & SCF_WINSCALE) {
2263                 wscale = sc->sc_requested_s_scale;
2264                 for (i = nitems(tcp_sc_wstab) - 1;
2265                     tcp_sc_wstab[i] > wscale && i > 0;
2266                      i--)
2267                         ;
2268                 cookie.flags.wscale_idx = i;
2269         }
2270
2271         /* Can we do SACK? */
2272         if (sc->sc_flags & SCF_SACK)
2273                 cookie.flags.sack_ok = 1;
2274
2275         /* Which of the two secrets to use. */
2276         secbit = V_tcp_syncache.secret.oddeven & 0x1;
2277         cookie.flags.odd_even = secbit;
2278
2279         secbits = V_tcp_syncache.secret.key[secbit];
2280         hash = syncookie_mac(&sc->sc_inc, sc->sc_irs, cookie.cookie, secbits,
2281             (uintptr_t)sch);
2282
2283         /*
2284          * Put the flags into the hash and XOR them to get better ISS number
2285          * variance.  This doesn't enhance the cryptographic strength and is
2286          * done to prevent the 8 cookie bits from showing up directly on the
2287          * wire.
2288          */
2289         iss = hash & ~0xff;
2290         iss |= cookie.cookie ^ (hash >> 24);
2291
2292         TCPSTAT_INC(tcps_sc_sendcookie);
2293         return (iss);
2294 }
2295
2296 static struct syncache *
2297 syncookie_lookup(struct in_conninfo *inc, struct syncache_head *sch,
2298     struct syncache *sc, struct tcphdr *th, struct tcpopt *to,
2299     struct socket *lso, uint16_t port)
2300 {
2301         uint32_t hash;
2302         uint8_t *secbits;
2303         tcp_seq ack, seq;
2304         int wnd, wscale = 0;
2305         union syncookie cookie;
2306
2307         /*
2308          * Pull information out of SYN-ACK/ACK and revert sequence number
2309          * advances.
2310          */
2311         ack = th->th_ack - 1;
2312         seq = th->th_seq - 1;
2313
2314         /*
2315          * Unpack the flags containing enough information to restore the
2316          * connection.
2317          */
2318         cookie.cookie = (ack & 0xff) ^ (ack >> 24);
2319
2320         /* Which of the two secrets to use. */
2321         secbits = V_tcp_syncache.secret.key[cookie.flags.odd_even];
2322
2323         hash = syncookie_mac(inc, seq, cookie.cookie, secbits, (uintptr_t)sch);
2324
2325         /* The recomputed hash matches the ACK if this was a genuine cookie. */
2326         if ((ack & ~0xff) != (hash & ~0xff))
2327                 return (NULL);
2328
2329         /* Fill in the syncache values. */
2330         sc->sc_flags = 0;
2331         bcopy(inc, &sc->sc_inc, sizeof(struct in_conninfo));
2332         sc->sc_ipopts = NULL;
2333
2334         sc->sc_irs = seq;
2335         sc->sc_iss = ack;
2336
2337         switch (inc->inc_flags & INC_ISIPV6) {
2338 #ifdef INET
2339         case 0:
2340                 sc->sc_ip_ttl = sotoinpcb(lso)->inp_ip_ttl;
2341                 sc->sc_ip_tos = sotoinpcb(lso)->inp_ip_tos;
2342                 break;
2343 #endif
2344 #ifdef INET6
2345         case INC_ISIPV6:
2346                 if (sotoinpcb(lso)->inp_flags & IN6P_AUTOFLOWLABEL)
2347                         sc->sc_flowlabel =
2348                             htonl(sc->sc_iss) & IPV6_FLOWLABEL_MASK;
2349                 break;
2350 #endif
2351         }
2352
2353         sc->sc_peer_mss = tcp_sc_msstab[cookie.flags.mss_idx];
2354
2355         /* We can simply recompute receive window scale we sent earlier. */
2356         while (wscale < TCP_MAX_WINSHIFT && (TCP_MAXWIN << wscale) < sb_max)
2357                 wscale++;
2358
2359         /* Only use wscale if it was enabled in the orignal SYN. */
2360         if (cookie.flags.wscale_idx > 0) {
2361                 sc->sc_requested_r_scale = wscale;
2362                 sc->sc_requested_s_scale = tcp_sc_wstab[cookie.flags.wscale_idx];
2363                 sc->sc_flags |= SCF_WINSCALE;
2364         }
2365
2366         wnd = lso->sol_sbrcv_hiwat;
2367         wnd = imax(wnd, 0);
2368         wnd = imin(wnd, TCP_MAXWIN);
2369         sc->sc_wnd = wnd;
2370
2371         if (cookie.flags.sack_ok)
2372                 sc->sc_flags |= SCF_SACK;
2373
2374         if (to->to_flags & TOF_TS) {
2375                 sc->sc_flags |= SCF_TIMESTAMP;
2376                 sc->sc_tsreflect = to->to_tsval;
2377                 sc->sc_tsoff = tcp_new_ts_offset(inc);
2378         }
2379
2380         if (to->to_flags & TOF_SIGNATURE)
2381                 sc->sc_flags |= SCF_SIGNATURE;
2382
2383         sc->sc_rxmits = 0;
2384
2385         sc->sc_port = port;
2386
2387         TCPSTAT_INC(tcps_sc_recvcookie);
2388         return (sc);
2389 }
2390
2391 #ifdef INVARIANTS
2392 static int
2393 syncookie_cmp(struct in_conninfo *inc, struct syncache_head *sch,
2394     struct syncache *sc, struct tcphdr *th, struct tcpopt *to,
2395     struct socket *lso, uint16_t port)
2396 {
2397         struct syncache scs, *scx;
2398         char *s;
2399
2400         bzero(&scs, sizeof(scs));
2401         scx = syncookie_lookup(inc, sch, &scs, th, to, lso, port);
2402
2403         if ((s = tcp_log_addrs(inc, th, NULL, NULL)) == NULL)
2404                 return (0);
2405
2406         if (scx != NULL) {
2407                 if (sc->sc_peer_mss != scx->sc_peer_mss)
2408                         log(LOG_DEBUG, "%s; %s: mss different %i vs %i\n",
2409                             s, __func__, sc->sc_peer_mss, scx->sc_peer_mss);
2410
2411                 if (sc->sc_requested_r_scale != scx->sc_requested_r_scale)
2412                         log(LOG_DEBUG, "%s; %s: rwscale different %i vs %i\n",
2413                             s, __func__, sc->sc_requested_r_scale,
2414                             scx->sc_requested_r_scale);
2415
2416                 if (sc->sc_requested_s_scale != scx->sc_requested_s_scale)
2417                         log(LOG_DEBUG, "%s; %s: swscale different %i vs %i\n",
2418                             s, __func__, sc->sc_requested_s_scale,
2419                             scx->sc_requested_s_scale);
2420
2421                 if ((sc->sc_flags & SCF_SACK) != (scx->sc_flags & SCF_SACK))
2422                         log(LOG_DEBUG, "%s; %s: SACK different\n", s, __func__);
2423         }
2424
2425         if (s != NULL)
2426                 free(s, M_TCPLOG);
2427         return (0);
2428 }
2429 #endif /* INVARIANTS */
2430
2431 static void
2432 syncookie_reseed(void *arg)
2433 {
2434         struct tcp_syncache *sc = arg;
2435         uint8_t *secbits;
2436         int secbit;
2437
2438         /*
2439          * Reseeding the secret doesn't have to be protected by a lock.
2440          * It only must be ensured that the new random values are visible
2441          * to all CPUs in a SMP environment.  The atomic with release
2442          * semantics ensures that.
2443          */
2444         secbit = (sc->secret.oddeven & 0x1) ? 0 : 1;
2445         secbits = sc->secret.key[secbit];
2446         arc4rand(secbits, SYNCOOKIE_SECRET_SIZE, 0);
2447         atomic_add_rel_int(&sc->secret.oddeven, 1);
2448
2449         /* Reschedule ourself. */
2450         callout_schedule(&sc->secret.reseed, SYNCOOKIE_LIFETIME * hz);
2451 }
2452
2453 /*
2454  * We have overflowed a bucket. Let's pause dealing with the syncache.
2455  * This function will increment the bucketoverflow statistics appropriately
2456  * (once per pause when pausing is enabled; otherwise, once per overflow).
2457  */
2458 static void
2459 syncache_pause(struct in_conninfo *inc)
2460 {
2461         time_t delta;
2462         const char *s;
2463
2464         /* XXX:
2465          * 2. Add sysctl read here so we don't get the benefit of this
2466          * change without the new sysctl.
2467          */
2468
2469         /*
2470          * Try an unlocked read. If we already know that another thread
2471          * has activated the feature, there is no need to proceed.
2472          */
2473         if (V_tcp_syncache.paused)
2474                 return;
2475
2476         /* Are cookied enabled? If not, we can't pause. */
2477         if (!V_tcp_syncookies) {
2478                 TCPSTAT_INC(tcps_sc_bucketoverflow);
2479                 return;
2480         }
2481
2482         /*
2483          * We may be the first thread to find an overflow. Get the lock
2484          * and evaluate if we need to take action.
2485          */
2486         mtx_lock(&V_tcp_syncache.pause_mtx);
2487         if (V_tcp_syncache.paused) {
2488                 mtx_unlock(&V_tcp_syncache.pause_mtx);
2489                 return;
2490         }
2491
2492         /* Activate protection. */
2493         V_tcp_syncache.paused = true;
2494         TCPSTAT_INC(tcps_sc_bucketoverflow);
2495
2496         /*
2497          * Determine the last backoff time. If we are seeing a re-newed
2498          * attack within that same time after last reactivating the syncache,
2499          * consider it an extension of the same attack.
2500          */
2501         delta = TCP_SYNCACHE_PAUSE_TIME << V_tcp_syncache.pause_backoff;
2502         if (V_tcp_syncache.pause_until + delta - time_uptime > 0) {
2503                 if (V_tcp_syncache.pause_backoff < TCP_SYNCACHE_MAX_BACKOFF) {
2504                         delta <<= 1;
2505                         V_tcp_syncache.pause_backoff++;
2506                 }
2507         } else {
2508                 delta = TCP_SYNCACHE_PAUSE_TIME;
2509                 V_tcp_syncache.pause_backoff = 0;
2510         }
2511
2512         /* Log a warning, including IP addresses, if able. */
2513         if (inc != NULL)
2514                 s = tcp_log_addrs(inc, NULL, NULL, NULL);
2515         else
2516                 s = (const char *)NULL;
2517         log(LOG_WARNING, "TCP syncache overflow detected; using syncookies for "
2518             "the next %lld seconds%s%s%s\n", (long long)delta,
2519             (s != NULL) ? " (last SYN: " : "", (s != NULL) ? s : "",
2520             (s != NULL) ? ")" : "");
2521         free(__DECONST(void *, s), M_TCPLOG);
2522
2523         /* Use the calculated delta to set a new pause time. */
2524         V_tcp_syncache.pause_until = time_uptime + delta;
2525         callout_reset(&V_tcp_syncache.pause_co, delta * hz, syncache_unpause,
2526             &V_tcp_syncache);
2527         mtx_unlock(&V_tcp_syncache.pause_mtx);
2528 }
2529
2530 /* Evaluate whether we need to unpause. */
2531 static void
2532 syncache_unpause(void *arg)
2533 {
2534         struct tcp_syncache *sc;
2535         time_t delta;
2536
2537         sc = arg;
2538         mtx_assert(&sc->pause_mtx, MA_OWNED | MA_NOTRECURSED);
2539         callout_deactivate(&sc->pause_co);
2540
2541         /*
2542          * Check to make sure we are not running early. If the pause
2543          * time has expired, then deactivate the protection.
2544          */
2545         if ((delta = sc->pause_until - time_uptime) > 0)
2546                 callout_schedule(&sc->pause_co, delta * hz);
2547         else
2548                 sc->paused = false;
2549 }
2550
2551 /*
2552  * Exports the syncache entries to userland so that netstat can display
2553  * them alongside the other sockets.  This function is intended to be
2554  * called only from tcp_pcblist.
2555  *
2556  * Due to concurrency on an active system, the number of pcbs exported
2557  * may have no relation to max_pcbs.  max_pcbs merely indicates the
2558  * amount of space the caller allocated for this function to use.
2559  */
2560 int
2561 syncache_pcblist(struct sysctl_req *req)
2562 {
2563         struct xtcpcb xt;
2564         struct syncache *sc;
2565         struct syncache_head *sch;
2566         int error, i;
2567
2568         bzero(&xt, sizeof(xt));
2569         xt.xt_len = sizeof(xt);
2570         xt.t_state = TCPS_SYN_RECEIVED;
2571         xt.xt_inp.xi_socket.xso_protocol = IPPROTO_TCP;
2572         xt.xt_inp.xi_socket.xso_len = sizeof (struct xsocket);
2573         xt.xt_inp.xi_socket.so_type = SOCK_STREAM;
2574         xt.xt_inp.xi_socket.so_state = SS_ISCONNECTING;
2575
2576         for (i = 0; i < V_tcp_syncache.hashsize; i++) {
2577                 sch = &V_tcp_syncache.hashbase[i];
2578                 SCH_LOCK(sch);
2579                 TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash) {
2580                         if (cr_cansee(req->td->td_ucred, sc->sc_cred) != 0)
2581                                 continue;
2582                         if (sc->sc_inc.inc_flags & INC_ISIPV6)
2583                                 xt.xt_inp.inp_vflag = INP_IPV6;
2584                         else
2585                                 xt.xt_inp.inp_vflag = INP_IPV4;
2586                         xt.xt_encaps_port = sc->sc_port;
2587                         bcopy(&sc->sc_inc, &xt.xt_inp.inp_inc,
2588                             sizeof (struct in_conninfo));
2589                         error = SYSCTL_OUT(req, &xt, sizeof xt);
2590                         if (error) {
2591                                 SCH_UNLOCK(sch);
2592                                 return (0);
2593                         }
2594                 }
2595                 SCH_UNLOCK(sch);
2596         }
2597
2598         return (0);
2599 }