]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet/tcp_syncache.c
zfs: merge openzfs/zfs@c3b60eded (zfs-2.1-release) into stable/13
[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                 TCPSTAT_INC(tcps_sc_completed);
1372         }
1373 }
1374
1375 /*
1376  * Given a LISTEN socket and an inbound SYN request, add
1377  * this to the syn cache, and send back a segment:
1378  *      <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
1379  * to the source.
1380  *
1381  * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
1382  * Doing so would require that we hold onto the data and deliver it
1383  * to the application.  However, if we are the target of a SYN-flood
1384  * DoS attack, an attacker could send data which would eventually
1385  * consume all available buffer space if it were ACKed.  By not ACKing
1386  * the data, we avoid this DoS scenario.
1387  *
1388  * The exception to the above is when a SYN with a valid TCP Fast Open (TFO)
1389  * cookie is processed and a new socket is created.  In this case, any data
1390  * accompanying the SYN will be queued to the socket by tcp_input() and will
1391  * be ACKed either when the application sends response data or the delayed
1392  * ACK timer expires, whichever comes first.
1393  */
1394 int
1395 syncache_add(struct in_conninfo *inc, struct tcpopt *to, struct tcphdr *th,
1396     struct inpcb *inp, struct socket **lsop, struct mbuf *m, void *tod,
1397     void *todctx, uint8_t iptos, uint16_t port)
1398 {
1399         struct tcpcb *tp;
1400         struct socket *so;
1401         struct syncache *sc = NULL;
1402         struct syncache_head *sch;
1403         struct mbuf *ipopts = NULL;
1404         u_int ltflags;
1405         int win, ip_ttl, ip_tos;
1406         char *s;
1407         int rv = 0;
1408 #ifdef INET6
1409         int autoflowlabel = 0;
1410 #endif
1411 #ifdef MAC
1412         struct label *maclabel;
1413 #endif
1414         struct syncache scs;
1415         struct ucred *cred;
1416         uint64_t tfo_response_cookie;
1417         unsigned int *tfo_pending = NULL;
1418         int tfo_cookie_valid = 0;
1419         int tfo_response_cookie_valid = 0;
1420         bool locked;
1421
1422         INP_WLOCK_ASSERT(inp);                  /* listen socket */
1423         KASSERT((th->th_flags & (TH_RST|TH_ACK|TH_SYN)) == TH_SYN,
1424             ("%s: unexpected tcp flags", __func__));
1425
1426         /*
1427          * Combine all so/tp operations very early to drop the INP lock as
1428          * soon as possible.
1429          */
1430         so = *lsop;
1431         KASSERT(SOLISTENING(so), ("%s: %p not listening", __func__, so));
1432         tp = sototcpcb(so);
1433         cred = crhold(so->so_cred);
1434
1435 #ifdef INET6
1436         if (inc->inc_flags & INC_ISIPV6) {
1437                 if (inp->inp_flags & IN6P_AUTOFLOWLABEL) {
1438                         autoflowlabel = 1;
1439                 }
1440                 ip_ttl = in6_selecthlim(inp, NULL);
1441                 if ((inp->in6p_outputopts == NULL) ||
1442                     (inp->in6p_outputopts->ip6po_tclass == -1)) {
1443                         ip_tos = 0;
1444                 } else {
1445                         ip_tos = inp->in6p_outputopts->ip6po_tclass;
1446                 }
1447         }
1448 #endif
1449 #if defined(INET6) && defined(INET)
1450         else
1451 #endif
1452 #ifdef INET
1453         {
1454                 ip_ttl = inp->inp_ip_ttl;
1455                 ip_tos = inp->inp_ip_tos;
1456         }
1457 #endif
1458         win = so->sol_sbrcv_hiwat;
1459         ltflags = (tp->t_flags & (TF_NOOPT | TF_SIGNATURE));
1460
1461         if (V_tcp_fastopen_server_enable && IS_FASTOPEN(tp->t_flags) &&
1462             (tp->t_tfo_pending != NULL) &&
1463             (to->to_flags & TOF_FASTOPEN)) {
1464                 /*
1465                  * Limit the number of pending TFO connections to
1466                  * approximately half of the queue limit.  This prevents TFO
1467                  * SYN floods from starving the service by filling the
1468                  * listen queue with bogus TFO connections.
1469                  */
1470                 if (atomic_fetchadd_int(tp->t_tfo_pending, 1) <=
1471                     (so->sol_qlimit / 2)) {
1472                         int result;
1473
1474                         result = tcp_fastopen_check_cookie(inc,
1475                             to->to_tfo_cookie, to->to_tfo_len,
1476                             &tfo_response_cookie);
1477                         tfo_cookie_valid = (result > 0);
1478                         tfo_response_cookie_valid = (result >= 0);
1479                 }
1480
1481                 /*
1482                  * Remember the TFO pending counter as it will have to be
1483                  * decremented below if we don't make it to syncache_tfo_expand().
1484                  */
1485                 tfo_pending = tp->t_tfo_pending;
1486         }
1487
1488         /* By the time we drop the lock these should no longer be used. */
1489         so = NULL;
1490         tp = NULL;
1491
1492 #ifdef MAC
1493         if (mac_syncache_init(&maclabel) != 0) {
1494                 INP_WUNLOCK(inp);
1495                 goto done;
1496         } else
1497                 mac_syncache_create(maclabel, inp);
1498 #endif
1499         if (!tfo_cookie_valid)
1500                 INP_WUNLOCK(inp);
1501
1502         /*
1503          * Remember the IP options, if any.
1504          */
1505 #ifdef INET6
1506         if (!(inc->inc_flags & INC_ISIPV6))
1507 #endif
1508 #ifdef INET
1509                 ipopts = (m) ? ip_srcroute(m) : NULL;
1510 #else
1511                 ipopts = NULL;
1512 #endif
1513
1514 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1515         /*
1516          * If listening socket requested TCP digests, check that received
1517          * SYN has signature and it is correct. If signature doesn't match
1518          * or TCP_SIGNATURE support isn't enabled, drop the packet.
1519          */
1520         if (ltflags & TF_SIGNATURE) {
1521                 if ((to->to_flags & TOF_SIGNATURE) == 0) {
1522                         TCPSTAT_INC(tcps_sig_err_nosigopt);
1523                         goto done;
1524                 }
1525                 if (!TCPMD5_ENABLED() ||
1526                     TCPMD5_INPUT(m, th, to->to_signature) != 0)
1527                         goto done;
1528         }
1529 #endif  /* TCP_SIGNATURE */
1530         /*
1531          * See if we already have an entry for this connection.
1532          * If we do, resend the SYN,ACK, and reset the retransmit timer.
1533          *
1534          * XXX: should the syncache be re-initialized with the contents
1535          * of the new SYN here (which may have different options?)
1536          *
1537          * XXX: We do not check the sequence number to see if this is a
1538          * real retransmit or a new connection attempt.  The question is
1539          * how to handle such a case; either ignore it as spoofed, or
1540          * drop the current entry and create a new one?
1541          */
1542         if (syncache_cookiesonly()) {
1543                 sc = NULL;
1544                 sch = syncache_hashbucket(inc);
1545                 locked = false;
1546         } else {
1547                 sc = syncache_lookup(inc, &sch);        /* returns locked sch */
1548                 locked = true;
1549                 SCH_LOCK_ASSERT(sch);
1550         }
1551         if (sc != NULL) {
1552                 if (tfo_cookie_valid)
1553                         INP_WUNLOCK(inp);
1554                 TCPSTAT_INC(tcps_sc_dupsyn);
1555                 if (ipopts) {
1556                         /*
1557                          * If we were remembering a previous source route,
1558                          * forget it and use the new one we've been given.
1559                          */
1560                         if (sc->sc_ipopts)
1561                                 (void) m_free(sc->sc_ipopts);
1562                         sc->sc_ipopts = ipopts;
1563                 }
1564                 /*
1565                  * Update timestamp if present.
1566                  */
1567                 if ((sc->sc_flags & SCF_TIMESTAMP) && (to->to_flags & TOF_TS))
1568                         sc->sc_tsreflect = to->to_tsval;
1569                 else
1570                         sc->sc_flags &= ~SCF_TIMESTAMP;
1571                 /*
1572                  * Disable ECN if needed.
1573                  */
1574                 if ((sc->sc_flags & SCF_ECN) &&
1575                     ((th->th_flags & (TH_ECE|TH_CWR)) != (TH_ECE|TH_CWR))) {
1576                         sc->sc_flags &= ~SCF_ECN;
1577                 }
1578 #ifdef MAC
1579                 /*
1580                  * Since we have already unconditionally allocated label
1581                  * storage, free it up.  The syncache entry will already
1582                  * have an initialized label we can use.
1583                  */
1584                 mac_syncache_destroy(&maclabel);
1585 #endif
1586                 TCP_PROBE5(receive, NULL, NULL, m, NULL, th);
1587                 /* Retransmit SYN|ACK and reset retransmit count. */
1588                 if ((s = tcp_log_addrs(&sc->sc_inc, th, NULL, NULL))) {
1589                         log(LOG_DEBUG, "%s; %s: Received duplicate SYN, "
1590                             "resetting timer and retransmitting SYN|ACK\n",
1591                             s, __func__);
1592                         free(s, M_TCPLOG);
1593                 }
1594                 if (syncache_respond(sc, m, TH_SYN|TH_ACK) == 0) {
1595                         sc->sc_rxmits = 0;
1596                         syncache_timeout(sc, sch, 1);
1597                         TCPSTAT_INC(tcps_sndacks);
1598                         TCPSTAT_INC(tcps_sndtotal);
1599                 }
1600                 SCH_UNLOCK(sch);
1601                 goto donenoprobe;
1602         }
1603
1604         if (tfo_cookie_valid) {
1605                 bzero(&scs, sizeof(scs));
1606                 sc = &scs;
1607                 goto skip_alloc;
1608         }
1609
1610         /*
1611          * Skip allocating a syncache entry if we are just going to discard
1612          * it later.
1613          */
1614         if (!locked) {
1615                 bzero(&scs, sizeof(scs));
1616                 sc = &scs;
1617         } else
1618                 sc = uma_zalloc(V_tcp_syncache.zone, M_NOWAIT | M_ZERO);
1619         if (sc == NULL) {
1620                 /*
1621                  * The zone allocator couldn't provide more entries.
1622                  * Treat this as if the cache was full; drop the oldest
1623                  * entry and insert the new one.
1624                  */
1625                 TCPSTAT_INC(tcps_sc_zonefail);
1626                 if ((sc = TAILQ_LAST(&sch->sch_bucket, sch_head)) != NULL) {
1627                         sch->sch_last_overflow = time_uptime;
1628                         syncache_drop(sc, sch);
1629                         syncache_pause(inc);
1630                 }
1631                 sc = uma_zalloc(V_tcp_syncache.zone, M_NOWAIT | M_ZERO);
1632                 if (sc == NULL) {
1633                         if (V_tcp_syncookies) {
1634                                 bzero(&scs, sizeof(scs));
1635                                 sc = &scs;
1636                         } else {
1637                                 KASSERT(locked,
1638                                     ("%s: bucket unexpectedly unlocked",
1639                                     __func__));
1640                                 SCH_UNLOCK(sch);
1641                                 if (ipopts)
1642                                         (void) m_free(ipopts);
1643                                 goto done;
1644                         }
1645                 }
1646         }
1647
1648 skip_alloc:
1649         if (!tfo_cookie_valid && tfo_response_cookie_valid)
1650                 sc->sc_tfo_cookie = &tfo_response_cookie;
1651
1652         /*
1653          * Fill in the syncache values.
1654          */
1655 #ifdef MAC
1656         sc->sc_label = maclabel;
1657 #endif
1658         sc->sc_cred = cred;
1659         sc->sc_port = port;
1660         cred = NULL;
1661         sc->sc_ipopts = ipopts;
1662         bcopy(inc, &sc->sc_inc, sizeof(struct in_conninfo));
1663         sc->sc_ip_tos = ip_tos;
1664         sc->sc_ip_ttl = ip_ttl;
1665 #ifdef TCP_OFFLOAD
1666         sc->sc_tod = tod;
1667         sc->sc_todctx = todctx;
1668 #endif
1669         sc->sc_irs = th->th_seq;
1670         sc->sc_flags = 0;
1671         sc->sc_flowlabel = 0;
1672
1673         /*
1674          * Initial receive window: clip sbspace to [0 .. TCP_MAXWIN].
1675          * win was derived from socket earlier in the function.
1676          */
1677         win = imax(win, 0);
1678         win = imin(win, TCP_MAXWIN);
1679         sc->sc_wnd = win;
1680
1681         if (V_tcp_do_rfc1323 &&
1682             !(ltflags & TF_NOOPT)) {
1683                 /*
1684                  * A timestamp received in a SYN makes
1685                  * it ok to send timestamp requests and replies.
1686                  */
1687                 if (to->to_flags & TOF_TS) {
1688                         sc->sc_tsreflect = to->to_tsval;
1689                         sc->sc_flags |= SCF_TIMESTAMP;
1690                         sc->sc_tsoff = tcp_new_ts_offset(inc);
1691                 }
1692                 if (to->to_flags & TOF_SCALE) {
1693                         int wscale = 0;
1694
1695                         /*
1696                          * Pick the smallest possible scaling factor that
1697                          * will still allow us to scale up to sb_max, aka
1698                          * kern.ipc.maxsockbuf.
1699                          *
1700                          * We do this because there are broken firewalls that
1701                          * will corrupt the window scale option, leading to
1702                          * the other endpoint believing that our advertised
1703                          * window is unscaled.  At scale factors larger than
1704                          * 5 the unscaled window will drop below 1500 bytes,
1705                          * leading to serious problems when traversing these
1706                          * broken firewalls.
1707                          *
1708                          * With the default maxsockbuf of 256K, a scale factor
1709                          * of 3 will be chosen by this algorithm.  Those who
1710                          * choose a larger maxsockbuf should watch out
1711                          * for the compatibility problems mentioned above.
1712                          *
1713                          * RFC1323: The Window field in a SYN (i.e., a <SYN>
1714                          * or <SYN,ACK>) segment itself is never scaled.
1715                          */
1716                         while (wscale < TCP_MAX_WINSHIFT &&
1717                             (TCP_MAXWIN << wscale) < sb_max)
1718                                 wscale++;
1719                         sc->sc_requested_r_scale = wscale;
1720                         sc->sc_requested_s_scale = to->to_wscale;
1721                         sc->sc_flags |= SCF_WINSCALE;
1722                 }
1723         }
1724 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1725         /*
1726          * If listening socket requested TCP digests, flag this in the
1727          * syncache so that syncache_respond() will do the right thing
1728          * with the SYN+ACK.
1729          */
1730         if (ltflags & TF_SIGNATURE)
1731                 sc->sc_flags |= SCF_SIGNATURE;
1732 #endif  /* TCP_SIGNATURE */
1733         if (to->to_flags & TOF_SACKPERM)
1734                 sc->sc_flags |= SCF_SACK;
1735         if (to->to_flags & TOF_MSS)
1736                 sc->sc_peer_mss = to->to_mss;   /* peer mss may be zero */
1737         if (ltflags & TF_NOOPT)
1738                 sc->sc_flags |= SCF_NOOPT;
1739         if (((th->th_flags & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) &&
1740             V_tcp_do_ecn)
1741                 sc->sc_flags |= SCF_ECN;
1742
1743         if (V_tcp_syncookies)
1744                 sc->sc_iss = syncookie_generate(sch, sc);
1745         else
1746                 sc->sc_iss = arc4random();
1747 #ifdef INET6
1748         if (autoflowlabel) {
1749                 if (V_tcp_syncookies)
1750                         sc->sc_flowlabel = sc->sc_iss;
1751                 else
1752                         sc->sc_flowlabel = ip6_randomflowlabel();
1753                 sc->sc_flowlabel = htonl(sc->sc_flowlabel) & IPV6_FLOWLABEL_MASK;
1754         }
1755 #endif
1756         if (locked)
1757                 SCH_UNLOCK(sch);
1758
1759         if (tfo_cookie_valid) {
1760                 syncache_tfo_expand(sc, lsop, m, tfo_response_cookie);
1761                 /* INP_WUNLOCK(inp) will be performed by the caller */
1762                 rv = 1;
1763                 goto tfo_expanded;
1764         }
1765
1766         TCP_PROBE5(receive, NULL, NULL, m, NULL, th);
1767         /*
1768          * Do a standard 3-way handshake.
1769          */
1770         if (syncache_respond(sc, m, TH_SYN|TH_ACK) == 0) {
1771                 if (V_tcp_syncookies && V_tcp_syncookiesonly && sc != &scs)
1772                         syncache_free(sc);
1773                 else if (sc != &scs)
1774                         syncache_insert(sc, sch);   /* locks and unlocks sch */
1775                 TCPSTAT_INC(tcps_sndacks);
1776                 TCPSTAT_INC(tcps_sndtotal);
1777         } else {
1778                 if (sc != &scs)
1779                         syncache_free(sc);
1780                 TCPSTAT_INC(tcps_sc_dropped);
1781         }
1782         goto donenoprobe;
1783
1784 done:
1785         TCP_PROBE5(receive, NULL, NULL, m, NULL, th);
1786 donenoprobe:
1787         if (m) {
1788                 *lsop = NULL;
1789                 m_freem(m);
1790         }
1791         /*
1792          * If tfo_pending is not NULL here, then a TFO SYN that did not
1793          * result in a new socket was processed and the associated pending
1794          * counter has not yet been decremented.  All such TFO processing paths
1795          * transit this point.
1796          */
1797         if (tfo_pending != NULL)
1798                 tcp_fastopen_decrement_counter(tfo_pending);
1799
1800 tfo_expanded:
1801         if (cred != NULL)
1802                 crfree(cred);
1803 #ifdef MAC
1804         if (sc == &scs)
1805                 mac_syncache_destroy(&maclabel);
1806 #endif
1807         return (rv);
1808 }
1809
1810 /*
1811  * Send SYN|ACK or ACK to the peer.  Either in response to a peer's segment,
1812  * i.e. m0 != NULL, or upon 3WHS ACK timeout, i.e. m0 == NULL.
1813  */
1814 static int
1815 syncache_respond(struct syncache *sc, const struct mbuf *m0, int flags)
1816 {
1817         struct ip *ip = NULL;
1818         struct mbuf *m;
1819         struct tcphdr *th = NULL;
1820         struct udphdr *udp = NULL;
1821         int optlen, error = 0;  /* Make compiler happy */
1822         u_int16_t hlen, tlen, mssopt, ulen;
1823         struct tcpopt to;
1824 #ifdef INET6
1825         struct ip6_hdr *ip6 = NULL;
1826 #endif
1827
1828         NET_EPOCH_ASSERT();
1829
1830         hlen =
1831 #ifdef INET6
1832                (sc->sc_inc.inc_flags & INC_ISIPV6) ? sizeof(struct ip6_hdr) :
1833 #endif
1834                 sizeof(struct ip);
1835         tlen = hlen + sizeof(struct tcphdr);
1836         if (sc->sc_port) {
1837                 tlen += sizeof(struct udphdr);
1838         }
1839         /* Determine MSS we advertize to other end of connection. */
1840         mssopt = tcp_mssopt(&sc->sc_inc);
1841         if (sc->sc_port)
1842                 mssopt -= V_tcp_udp_tunneling_overhead;
1843         mssopt = max(mssopt, V_tcp_minmss);
1844
1845         /* XXX: Assume that the entire packet will fit in a header mbuf. */
1846         KASSERT(max_linkhdr + tlen + TCP_MAXOLEN <= MHLEN,
1847             ("syncache: mbuf too small"));
1848
1849         /* Create the IP+TCP header from scratch. */
1850         m = m_gethdr(M_NOWAIT, MT_DATA);
1851         if (m == NULL)
1852                 return (ENOBUFS);
1853 #ifdef MAC
1854         mac_syncache_create_mbuf(sc->sc_label, m);
1855 #endif
1856         m->m_data += max_linkhdr;
1857         m->m_len = tlen;
1858         m->m_pkthdr.len = tlen;
1859         m->m_pkthdr.rcvif = NULL;
1860
1861 #ifdef INET6
1862         if (sc->sc_inc.inc_flags & INC_ISIPV6) {
1863                 ip6 = mtod(m, struct ip6_hdr *);
1864                 ip6->ip6_vfc = IPV6_VERSION;
1865                 ip6->ip6_src = sc->sc_inc.inc6_laddr;
1866                 ip6->ip6_dst = sc->sc_inc.inc6_faddr;
1867                 ip6->ip6_plen = htons(tlen - hlen);
1868                 /* ip6_hlim is set after checksum */
1869                 /* Zero out traffic class and flow label. */
1870                 ip6->ip6_flow &= ~IPV6_FLOWINFO_MASK;
1871                 ip6->ip6_flow |= sc->sc_flowlabel;
1872                 if (sc->sc_port != 0) {
1873                         ip6->ip6_nxt = IPPROTO_UDP;
1874                         udp = (struct udphdr *)(ip6 + 1);
1875                         udp->uh_sport = htons(V_tcp_udp_tunneling_port);
1876                         udp->uh_dport = sc->sc_port;
1877                         ulen = (tlen - sizeof(struct ip6_hdr));
1878                         th = (struct tcphdr *)(udp + 1);
1879                 } else {
1880                         ip6->ip6_nxt = IPPROTO_TCP;
1881                         th = (struct tcphdr *)(ip6 + 1);
1882                 }
1883                 ip6->ip6_flow |= htonl(sc->sc_ip_tos << 20);
1884         }
1885 #endif
1886 #if defined(INET6) && defined(INET)
1887         else
1888 #endif
1889 #ifdef INET
1890         {
1891                 ip = mtod(m, struct ip *);
1892                 ip->ip_v = IPVERSION;
1893                 ip->ip_hl = sizeof(struct ip) >> 2;
1894                 ip->ip_len = htons(tlen);
1895                 ip->ip_id = 0;
1896                 ip->ip_off = 0;
1897                 ip->ip_sum = 0;
1898                 ip->ip_src = sc->sc_inc.inc_laddr;
1899                 ip->ip_dst = sc->sc_inc.inc_faddr;
1900                 ip->ip_ttl = sc->sc_ip_ttl;
1901                 ip->ip_tos = sc->sc_ip_tos;
1902
1903                 /*
1904                  * See if we should do MTU discovery.  Route lookups are
1905                  * expensive, so we will only unset the DF bit if:
1906                  *
1907                  *      1) path_mtu_discovery is disabled
1908                  *      2) the SCF_UNREACH flag has been set
1909                  */
1910                 if (V_path_mtu_discovery && ((sc->sc_flags & SCF_UNREACH) == 0))
1911                        ip->ip_off |= htons(IP_DF);
1912                 if (sc->sc_port == 0) {
1913                         ip->ip_p = IPPROTO_TCP;
1914                         th = (struct tcphdr *)(ip + 1);
1915                 } else {
1916                         ip->ip_p = IPPROTO_UDP;
1917                         udp = (struct udphdr *)(ip + 1);
1918                         udp->uh_sport = htons(V_tcp_udp_tunneling_port);
1919                         udp->uh_dport = sc->sc_port;
1920                         ulen = (tlen - sizeof(struct ip));
1921                         th = (struct tcphdr *)(udp + 1);
1922                 }
1923         }
1924 #endif /* INET */
1925         th->th_sport = sc->sc_inc.inc_lport;
1926         th->th_dport = sc->sc_inc.inc_fport;
1927
1928         if (flags & TH_SYN)
1929                 th->th_seq = htonl(sc->sc_iss);
1930         else
1931                 th->th_seq = htonl(sc->sc_iss + 1);
1932         th->th_ack = htonl(sc->sc_irs + 1);
1933         th->th_off = sizeof(struct tcphdr) >> 2;
1934         th->th_x2 = 0;
1935         th->th_flags = flags;
1936         th->th_win = htons(sc->sc_wnd);
1937         th->th_urp = 0;
1938
1939         if ((flags & TH_SYN) && (sc->sc_flags & SCF_ECN)) {
1940                 th->th_flags |= TH_ECE;
1941                 TCPSTAT_INC(tcps_ecn_shs);
1942         }
1943
1944         /* Tack on the TCP options. */
1945         if ((sc->sc_flags & SCF_NOOPT) == 0) {
1946                 to.to_flags = 0;
1947
1948                 if (flags & TH_SYN) {
1949                         to.to_mss = mssopt;
1950                         to.to_flags = TOF_MSS;
1951                         if (sc->sc_flags & SCF_WINSCALE) {
1952                                 to.to_wscale = sc->sc_requested_r_scale;
1953                                 to.to_flags |= TOF_SCALE;
1954                         }
1955                         if (sc->sc_flags & SCF_SACK)
1956                                 to.to_flags |= TOF_SACKPERM;
1957 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1958                         if (sc->sc_flags & SCF_SIGNATURE)
1959                                 to.to_flags |= TOF_SIGNATURE;
1960 #endif
1961                         if (sc->sc_tfo_cookie) {
1962                                 to.to_flags |= TOF_FASTOPEN;
1963                                 to.to_tfo_len = TCP_FASTOPEN_COOKIE_LEN;
1964                                 to.to_tfo_cookie = sc->sc_tfo_cookie;
1965                                 /* don't send cookie again when retransmitting response */
1966                                 sc->sc_tfo_cookie = NULL;
1967                         }
1968                 }
1969                 if (sc->sc_flags & SCF_TIMESTAMP) {
1970                         to.to_tsval = sc->sc_tsoff + tcp_ts_getticks();
1971                         to.to_tsecr = sc->sc_tsreflect;
1972                         to.to_flags |= TOF_TS;
1973                 }
1974                 optlen = tcp_addoptions(&to, (u_char *)(th + 1));
1975
1976                 /* Adjust headers by option size. */
1977                 th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
1978                 m->m_len += optlen;
1979                 m->m_pkthdr.len += optlen;
1980 #ifdef INET6
1981                 if (sc->sc_inc.inc_flags & INC_ISIPV6)
1982                         ip6->ip6_plen = htons(ntohs(ip6->ip6_plen) + optlen);
1983                 else
1984 #endif
1985                         ip->ip_len = htons(ntohs(ip->ip_len) + optlen);
1986 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1987                 if (sc->sc_flags & SCF_SIGNATURE) {
1988                         KASSERT(to.to_flags & TOF_SIGNATURE,
1989                             ("tcp_addoptions() didn't set tcp_signature"));
1990
1991                         /* NOTE: to.to_signature is inside of mbuf */
1992                         if (!TCPMD5_ENABLED() ||
1993                             TCPMD5_OUTPUT(m, th, to.to_signature) != 0) {
1994                                 m_freem(m);
1995                                 return (EACCES);
1996                         }
1997                 }
1998 #endif
1999         } else
2000                 optlen = 0;
2001
2002         if (udp) {
2003                 ulen += optlen;
2004                 udp->uh_ulen = htons(ulen);
2005         }
2006         M_SETFIB(m, sc->sc_inc.inc_fibnum);
2007         /*
2008          * If we have peer's SYN and it has a flowid, then let's assign it to
2009          * our SYN|ACK.  ip6_output() and ip_output() will not assign flowid
2010          * to SYN|ACK due to lack of inp here.
2011          */
2012         if (m0 != NULL && M_HASHTYPE_GET(m0) != M_HASHTYPE_NONE) {
2013                 m->m_pkthdr.flowid = m0->m_pkthdr.flowid;
2014                 M_HASHTYPE_SET(m, M_HASHTYPE_GET(m0));
2015         }
2016 #ifdef INET6
2017         if (sc->sc_inc.inc_flags & INC_ISIPV6) {
2018                 if (sc->sc_port) {
2019                         m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
2020                         m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
2021                         udp->uh_sum = in6_cksum_pseudo(ip6, ulen,
2022                               IPPROTO_UDP, 0);
2023                         th->th_sum = htons(0);
2024                 } else {
2025                         m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
2026                         m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
2027                         th->th_sum = in6_cksum_pseudo(ip6, tlen + optlen - hlen,
2028                             IPPROTO_TCP, 0);
2029                 }
2030                 ip6->ip6_hlim = sc->sc_ip_ttl;
2031 #ifdef TCP_OFFLOAD
2032                 if (ADDED_BY_TOE(sc)) {
2033                         struct toedev *tod = sc->sc_tod;
2034
2035                         error = tod->tod_syncache_respond(tod, sc->sc_todctx, m);
2036
2037                         return (error);
2038                 }
2039 #endif
2040                 TCP_PROBE5(send, NULL, NULL, ip6, NULL, th);
2041                 error = ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
2042         }
2043 #endif
2044 #if defined(INET6) && defined(INET)
2045         else
2046 #endif
2047 #ifdef INET
2048         {
2049                 if (sc->sc_port) {
2050                         m->m_pkthdr.csum_flags = CSUM_UDP;
2051                         m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
2052                         udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
2053                               ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP));
2054                         th->th_sum = htons(0);
2055                 } else {
2056                         m->m_pkthdr.csum_flags = CSUM_TCP;
2057                         m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
2058                         th->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
2059                             htons(tlen + optlen - hlen + IPPROTO_TCP));
2060                 }
2061 #ifdef TCP_OFFLOAD
2062                 if (ADDED_BY_TOE(sc)) {
2063                         struct toedev *tod = sc->sc_tod;
2064
2065                         error = tod->tod_syncache_respond(tod, sc->sc_todctx, m);
2066
2067                         return (error);
2068                 }
2069 #endif
2070                 TCP_PROBE5(send, NULL, NULL, ip, NULL, th);
2071                 error = ip_output(m, sc->sc_ipopts, NULL, 0, NULL, NULL);
2072         }
2073 #endif
2074         return (error);
2075 }
2076
2077 /*
2078  * The purpose of syncookies is to handle spoofed SYN flooding DoS attacks
2079  * that exceed the capacity of the syncache by avoiding the storage of any
2080  * of the SYNs we receive.  Syncookies defend against blind SYN flooding
2081  * attacks where the attacker does not have access to our responses.
2082  *
2083  * Syncookies encode and include all necessary information about the
2084  * connection setup within the SYN|ACK that we send back.  That way we
2085  * can avoid keeping any local state until the ACK to our SYN|ACK returns
2086  * (if ever).  Normally the syncache and syncookies are running in parallel
2087  * with the latter taking over when the former is exhausted.  When matching
2088  * syncache entry is found the syncookie is ignored.
2089  *
2090  * The only reliable information persisting the 3WHS is our initial sequence
2091  * number ISS of 32 bits.  Syncookies embed a cryptographically sufficient
2092  * strong hash (MAC) value and a few bits of TCP SYN options in the ISS
2093  * of our SYN|ACK.  The MAC can be recomputed when the ACK to our SYN|ACK
2094  * returns and signifies a legitimate connection if it matches the ACK.
2095  *
2096  * The available space of 32 bits to store the hash and to encode the SYN
2097  * option information is very tight and we should have at least 24 bits for
2098  * the MAC to keep the number of guesses by blind spoofing reasonably high.
2099  *
2100  * SYN option information we have to encode to fully restore a connection:
2101  * MSS: is imporant to chose an optimal segment size to avoid IP level
2102  *   fragmentation along the path.  The common MSS values can be encoded
2103  *   in a 3-bit table.  Uncommon values are captured by the next lower value
2104  *   in the table leading to a slight increase in packetization overhead.
2105  * WSCALE: is necessary to allow large windows to be used for high delay-
2106  *   bandwidth product links.  Not scaling the window when it was initially
2107  *   negotiated is bad for performance as lack of scaling further decreases
2108  *   the apparent available send window.  We only need to encode the WSCALE
2109  *   we received from the remote end.  Our end can be recalculated at any
2110  *   time.  The common WSCALE values can be encoded in a 3-bit table.
2111  *   Uncommon values are captured by the next lower value in the table
2112  *   making us under-estimate the available window size halving our
2113  *   theoretically possible maximum throughput for that connection.
2114  * SACK: Greatly assists in packet loss recovery and requires 1 bit.
2115  * TIMESTAMP and SIGNATURE is not encoded because they are permanent options
2116  *   that are included in all segments on a connection.  We enable them when
2117  *   the ACK has them.
2118  *
2119  * Security of syncookies and attack vectors:
2120  *
2121  * The MAC is computed over (faddr||laddr||fport||lport||irs||flags||secmod)
2122  * together with the gloabl secret to make it unique per connection attempt.
2123  * Thus any change of any of those parameters results in a different MAC output
2124  * in an unpredictable way unless a collision is encountered.  24 bits of the
2125  * MAC are embedded into the ISS.
2126  *
2127  * To prevent replay attacks two rotating global secrets are updated with a
2128  * new random value every 15 seconds.  The life-time of a syncookie is thus
2129  * 15-30 seconds.
2130  *
2131  * Vector 1: Attacking the secret.  This requires finding a weakness in the
2132  * MAC itself or the way it is used here.  The attacker can do a chosen plain
2133  * text attack by varying and testing the all parameters under his control.
2134  * The strength depends on the size and randomness of the secret, and the
2135  * cryptographic security of the MAC function.  Due to the constant updating
2136  * of the secret the attacker has at most 29.999 seconds to find the secret
2137  * and launch spoofed connections.  After that he has to start all over again.
2138  *
2139  * Vector 2: Collision attack on the MAC of a single ACK.  With a 24 bit MAC
2140  * size an average of 4,823 attempts are required for a 50% chance of success
2141  * to spoof a single syncookie (birthday collision paradox).  However the
2142  * attacker is blind and doesn't know if one of his attempts succeeded unless
2143  * he has a side channel to interfere success from.  A single connection setup
2144  * success average of 90% requires 8,790 packets, 99.99% requires 17,578 packets.
2145  * This many attempts are required for each one blind spoofed connection.  For
2146  * every additional spoofed connection he has to launch another N attempts.
2147  * Thus for a sustained rate 100 spoofed connections per second approximately
2148  * 1,800,000 packets per second would have to be sent.
2149  *
2150  * NB: The MAC function should be fast so that it doesn't become a CPU
2151  * exhaustion attack vector itself.
2152  *
2153  * References:
2154  *  RFC4987 TCP SYN Flooding Attacks and Common Mitigations
2155  *  SYN cookies were first proposed by cryptographer Dan J. Bernstein in 1996
2156  *   http://cr.yp.to/syncookies.html    (overview)
2157  *   http://cr.yp.to/syncookies/archive (details)
2158  *
2159  *
2160  * Schematic construction of a syncookie enabled Initial Sequence Number:
2161  *  0        1         2         3
2162  *  12345678901234567890123456789012
2163  * |xxxxxxxxxxxxxxxxxxxxxxxxWWWMMMSP|
2164  *
2165  *  x 24 MAC (truncated)
2166  *  W  3 Send Window Scale index
2167  *  M  3 MSS index
2168  *  S  1 SACK permitted
2169  *  P  1 Odd/even secret
2170  */
2171
2172 /*
2173  * Distribution and probability of certain MSS values.  Those in between are
2174  * rounded down to the next lower one.
2175  * [An Analysis of TCP Maximum Segment Sizes, S. Alcock and R. Nelson, 2011]
2176  *                            .2%  .3%   5%    7%    7%    20%   15%   45%
2177  */
2178 static int tcp_sc_msstab[] = { 216, 536, 1200, 1360, 1400, 1440, 1452, 1460 };
2179
2180 /*
2181  * Distribution and probability of certain WSCALE values.  We have to map the
2182  * (send) window scale (shift) option with a range of 0-14 from 4 bits into 3
2183  * bits based on prevalence of certain values.  Where we don't have an exact
2184  * match for are rounded down to the next lower one letting us under-estimate
2185  * the true available window.  At the moment this would happen only for the
2186  * very uncommon values 3, 5 and those above 8 (more than 16MB socket buffer
2187  * and window size).  The absence of the WSCALE option (no scaling in either
2188  * direction) is encoded with index zero.
2189  * [WSCALE values histograms, Allman, 2012]
2190  *                            X 10 10 35  5  6 14 10%   by host
2191  *                            X 11  4  5  5 18 49  3%   by connections
2192  */
2193 static int tcp_sc_wstab[] = { 0, 0, 1, 2, 4, 6, 7, 8 };
2194
2195 /*
2196  * Compute the MAC for the SYN cookie.  SIPHASH-2-4 is chosen for its speed
2197  * and good cryptographic properties.
2198  */
2199 static uint32_t
2200 syncookie_mac(struct in_conninfo *inc, tcp_seq irs, uint8_t flags,
2201     uint8_t *secbits, uintptr_t secmod)
2202 {
2203         SIPHASH_CTX ctx;
2204         uint32_t siphash[2];
2205
2206         SipHash24_Init(&ctx);
2207         SipHash_SetKey(&ctx, secbits);
2208         switch (inc->inc_flags & INC_ISIPV6) {
2209 #ifdef INET
2210         case 0:
2211                 SipHash_Update(&ctx, &inc->inc_faddr, sizeof(inc->inc_faddr));
2212                 SipHash_Update(&ctx, &inc->inc_laddr, sizeof(inc->inc_laddr));
2213                 break;
2214 #endif
2215 #ifdef INET6
2216         case INC_ISIPV6:
2217                 SipHash_Update(&ctx, &inc->inc6_faddr, sizeof(inc->inc6_faddr));
2218                 SipHash_Update(&ctx, &inc->inc6_laddr, sizeof(inc->inc6_laddr));
2219                 break;
2220 #endif
2221         }
2222         SipHash_Update(&ctx, &inc->inc_fport, sizeof(inc->inc_fport));
2223         SipHash_Update(&ctx, &inc->inc_lport, sizeof(inc->inc_lport));
2224         SipHash_Update(&ctx, &irs, sizeof(irs));
2225         SipHash_Update(&ctx, &flags, sizeof(flags));
2226         SipHash_Update(&ctx, &secmod, sizeof(secmod));
2227         SipHash_Final((u_int8_t *)&siphash, &ctx);
2228
2229         return (siphash[0] ^ siphash[1]);
2230 }
2231
2232 static tcp_seq
2233 syncookie_generate(struct syncache_head *sch, struct syncache *sc)
2234 {
2235         u_int i, secbit, wscale;
2236         uint32_t iss, hash;
2237         uint8_t *secbits;
2238         union syncookie cookie;
2239
2240         cookie.cookie = 0;
2241
2242         /* Map our computed MSS into the 3-bit index. */
2243         for (i = nitems(tcp_sc_msstab) - 1;
2244              tcp_sc_msstab[i] > sc->sc_peer_mss && i > 0;
2245              i--)
2246                 ;
2247         cookie.flags.mss_idx = i;
2248
2249         /*
2250          * Map the send window scale into the 3-bit index but only if
2251          * the wscale option was received.
2252          */
2253         if (sc->sc_flags & SCF_WINSCALE) {
2254                 wscale = sc->sc_requested_s_scale;
2255                 for (i = nitems(tcp_sc_wstab) - 1;
2256                     tcp_sc_wstab[i] > wscale && i > 0;
2257                      i--)
2258                         ;
2259                 cookie.flags.wscale_idx = i;
2260         }
2261
2262         /* Can we do SACK? */
2263         if (sc->sc_flags & SCF_SACK)
2264                 cookie.flags.sack_ok = 1;
2265
2266         /* Which of the two secrets to use. */
2267         secbit = V_tcp_syncache.secret.oddeven & 0x1;
2268         cookie.flags.odd_even = secbit;
2269
2270         secbits = V_tcp_syncache.secret.key[secbit];
2271         hash = syncookie_mac(&sc->sc_inc, sc->sc_irs, cookie.cookie, secbits,
2272             (uintptr_t)sch);
2273
2274         /*
2275          * Put the flags into the hash and XOR them to get better ISS number
2276          * variance.  This doesn't enhance the cryptographic strength and is
2277          * done to prevent the 8 cookie bits from showing up directly on the
2278          * wire.
2279          */
2280         iss = hash & ~0xff;
2281         iss |= cookie.cookie ^ (hash >> 24);
2282
2283         TCPSTAT_INC(tcps_sc_sendcookie);
2284         return (iss);
2285 }
2286
2287 static struct syncache *
2288 syncookie_lookup(struct in_conninfo *inc, struct syncache_head *sch,
2289     struct syncache *sc, struct tcphdr *th, struct tcpopt *to,
2290     struct socket *lso, uint16_t port)
2291 {
2292         uint32_t hash;
2293         uint8_t *secbits;
2294         tcp_seq ack, seq;
2295         int wnd, wscale = 0;
2296         union syncookie cookie;
2297
2298         /*
2299          * Pull information out of SYN-ACK/ACK and revert sequence number
2300          * advances.
2301          */
2302         ack = th->th_ack - 1;
2303         seq = th->th_seq - 1;
2304
2305         /*
2306          * Unpack the flags containing enough information to restore the
2307          * connection.
2308          */
2309         cookie.cookie = (ack & 0xff) ^ (ack >> 24);
2310
2311         /* Which of the two secrets to use. */
2312         secbits = V_tcp_syncache.secret.key[cookie.flags.odd_even];
2313
2314         hash = syncookie_mac(inc, seq, cookie.cookie, secbits, (uintptr_t)sch);
2315
2316         /* The recomputed hash matches the ACK if this was a genuine cookie. */
2317         if ((ack & ~0xff) != (hash & ~0xff))
2318                 return (NULL);
2319
2320         /* Fill in the syncache values. */
2321         sc->sc_flags = 0;
2322         bcopy(inc, &sc->sc_inc, sizeof(struct in_conninfo));
2323         sc->sc_ipopts = NULL;
2324
2325         sc->sc_irs = seq;
2326         sc->sc_iss = ack;
2327
2328         switch (inc->inc_flags & INC_ISIPV6) {
2329 #ifdef INET
2330         case 0:
2331                 sc->sc_ip_ttl = sotoinpcb(lso)->inp_ip_ttl;
2332                 sc->sc_ip_tos = sotoinpcb(lso)->inp_ip_tos;
2333                 break;
2334 #endif
2335 #ifdef INET6
2336         case INC_ISIPV6:
2337                 if (sotoinpcb(lso)->inp_flags & IN6P_AUTOFLOWLABEL)
2338                         sc->sc_flowlabel =
2339                             htonl(sc->sc_iss) & IPV6_FLOWLABEL_MASK;
2340                 break;
2341 #endif
2342         }
2343
2344         sc->sc_peer_mss = tcp_sc_msstab[cookie.flags.mss_idx];
2345
2346         /* We can simply recompute receive window scale we sent earlier. */
2347         while (wscale < TCP_MAX_WINSHIFT && (TCP_MAXWIN << wscale) < sb_max)
2348                 wscale++;
2349
2350         /* Only use wscale if it was enabled in the orignal SYN. */
2351         if (cookie.flags.wscale_idx > 0) {
2352                 sc->sc_requested_r_scale = wscale;
2353                 sc->sc_requested_s_scale = tcp_sc_wstab[cookie.flags.wscale_idx];
2354                 sc->sc_flags |= SCF_WINSCALE;
2355         }
2356
2357         wnd = lso->sol_sbrcv_hiwat;
2358         wnd = imax(wnd, 0);
2359         wnd = imin(wnd, TCP_MAXWIN);
2360         sc->sc_wnd = wnd;
2361
2362         if (cookie.flags.sack_ok)
2363                 sc->sc_flags |= SCF_SACK;
2364
2365         if (to->to_flags & TOF_TS) {
2366                 sc->sc_flags |= SCF_TIMESTAMP;
2367                 sc->sc_tsreflect = to->to_tsval;
2368                 sc->sc_tsoff = tcp_new_ts_offset(inc);
2369         }
2370
2371         if (to->to_flags & TOF_SIGNATURE)
2372                 sc->sc_flags |= SCF_SIGNATURE;
2373
2374         sc->sc_rxmits = 0;
2375
2376         sc->sc_port = port;
2377
2378         TCPSTAT_INC(tcps_sc_recvcookie);
2379         return (sc);
2380 }
2381
2382 #ifdef INVARIANTS
2383 static int
2384 syncookie_cmp(struct in_conninfo *inc, struct syncache_head *sch,
2385     struct syncache *sc, struct tcphdr *th, struct tcpopt *to,
2386     struct socket *lso, uint16_t port)
2387 {
2388         struct syncache scs, *scx;
2389         char *s;
2390
2391         bzero(&scs, sizeof(scs));
2392         scx = syncookie_lookup(inc, sch, &scs, th, to, lso, port);
2393
2394         if ((s = tcp_log_addrs(inc, th, NULL, NULL)) == NULL)
2395                 return (0);
2396
2397         if (scx != NULL) {
2398                 if (sc->sc_peer_mss != scx->sc_peer_mss)
2399                         log(LOG_DEBUG, "%s; %s: mss different %i vs %i\n",
2400                             s, __func__, sc->sc_peer_mss, scx->sc_peer_mss);
2401
2402                 if (sc->sc_requested_r_scale != scx->sc_requested_r_scale)
2403                         log(LOG_DEBUG, "%s; %s: rwscale different %i vs %i\n",
2404                             s, __func__, sc->sc_requested_r_scale,
2405                             scx->sc_requested_r_scale);
2406
2407                 if (sc->sc_requested_s_scale != scx->sc_requested_s_scale)
2408                         log(LOG_DEBUG, "%s; %s: swscale different %i vs %i\n",
2409                             s, __func__, sc->sc_requested_s_scale,
2410                             scx->sc_requested_s_scale);
2411
2412                 if ((sc->sc_flags & SCF_SACK) != (scx->sc_flags & SCF_SACK))
2413                         log(LOG_DEBUG, "%s; %s: SACK different\n", s, __func__);
2414         }
2415
2416         if (s != NULL)
2417                 free(s, M_TCPLOG);
2418         return (0);
2419 }
2420 #endif /* INVARIANTS */
2421
2422 static void
2423 syncookie_reseed(void *arg)
2424 {
2425         struct tcp_syncache *sc = arg;
2426         uint8_t *secbits;
2427         int secbit;
2428
2429         /*
2430          * Reseeding the secret doesn't have to be protected by a lock.
2431          * It only must be ensured that the new random values are visible
2432          * to all CPUs in a SMP environment.  The atomic with release
2433          * semantics ensures that.
2434          */
2435         secbit = (sc->secret.oddeven & 0x1) ? 0 : 1;
2436         secbits = sc->secret.key[secbit];
2437         arc4rand(secbits, SYNCOOKIE_SECRET_SIZE, 0);
2438         atomic_add_rel_int(&sc->secret.oddeven, 1);
2439
2440         /* Reschedule ourself. */
2441         callout_schedule(&sc->secret.reseed, SYNCOOKIE_LIFETIME * hz);
2442 }
2443
2444 /*
2445  * We have overflowed a bucket. Let's pause dealing with the syncache.
2446  * This function will increment the bucketoverflow statistics appropriately
2447  * (once per pause when pausing is enabled; otherwise, once per overflow).
2448  */
2449 static void
2450 syncache_pause(struct in_conninfo *inc)
2451 {
2452         time_t delta;
2453         const char *s;
2454
2455         /* XXX:
2456          * 2. Add sysctl read here so we don't get the benefit of this
2457          * change without the new sysctl.
2458          */
2459
2460         /*
2461          * Try an unlocked read. If we already know that another thread
2462          * has activated the feature, there is no need to proceed.
2463          */
2464         if (V_tcp_syncache.paused)
2465                 return;
2466
2467         /* Are cookied enabled? If not, we can't pause. */
2468         if (!V_tcp_syncookies) {
2469                 TCPSTAT_INC(tcps_sc_bucketoverflow);
2470                 return;
2471         }
2472
2473         /*
2474          * We may be the first thread to find an overflow. Get the lock
2475          * and evaluate if we need to take action.
2476          */
2477         mtx_lock(&V_tcp_syncache.pause_mtx);
2478         if (V_tcp_syncache.paused) {
2479                 mtx_unlock(&V_tcp_syncache.pause_mtx);
2480                 return;
2481         }
2482
2483         /* Activate protection. */
2484         V_tcp_syncache.paused = true;
2485         TCPSTAT_INC(tcps_sc_bucketoverflow);
2486
2487         /*
2488          * Determine the last backoff time. If we are seeing a re-newed
2489          * attack within that same time after last reactivating the syncache,
2490          * consider it an extension of the same attack.
2491          */
2492         delta = TCP_SYNCACHE_PAUSE_TIME << V_tcp_syncache.pause_backoff;
2493         if (V_tcp_syncache.pause_until + delta - time_uptime > 0) {
2494                 if (V_tcp_syncache.pause_backoff < TCP_SYNCACHE_MAX_BACKOFF) {
2495                         delta <<= 1;
2496                         V_tcp_syncache.pause_backoff++;
2497                 }
2498         } else {
2499                 delta = TCP_SYNCACHE_PAUSE_TIME;
2500                 V_tcp_syncache.pause_backoff = 0;
2501         }
2502
2503         /* Log a warning, including IP addresses, if able. */
2504         if (inc != NULL)
2505                 s = tcp_log_addrs(inc, NULL, NULL, NULL);
2506         else
2507                 s = (const char *)NULL;
2508         log(LOG_WARNING, "TCP syncache overflow detected; using syncookies for "
2509             "the next %lld seconds%s%s%s\n", (long long)delta,
2510             (s != NULL) ? " (last SYN: " : "", (s != NULL) ? s : "",
2511             (s != NULL) ? ")" : "");
2512         free(__DECONST(void *, s), M_TCPLOG);
2513
2514         /* Use the calculated delta to set a new pause time. */
2515         V_tcp_syncache.pause_until = time_uptime + delta;
2516         callout_reset(&V_tcp_syncache.pause_co, delta * hz, syncache_unpause,
2517             &V_tcp_syncache);
2518         mtx_unlock(&V_tcp_syncache.pause_mtx);
2519 }
2520
2521 /* Evaluate whether we need to unpause. */
2522 static void
2523 syncache_unpause(void *arg)
2524 {
2525         struct tcp_syncache *sc;
2526         time_t delta;
2527
2528         sc = arg;
2529         mtx_assert(&sc->pause_mtx, MA_OWNED | MA_NOTRECURSED);
2530         callout_deactivate(&sc->pause_co);
2531
2532         /*
2533          * Check to make sure we are not running early. If the pause
2534          * time has expired, then deactivate the protection.
2535          */
2536         if ((delta = sc->pause_until - time_uptime) > 0)
2537                 callout_schedule(&sc->pause_co, delta * hz);
2538         else
2539                 sc->paused = false;
2540 }
2541
2542 /*
2543  * Exports the syncache entries to userland so that netstat can display
2544  * them alongside the other sockets.  This function is intended to be
2545  * called only from tcp_pcblist.
2546  *
2547  * Due to concurrency on an active system, the number of pcbs exported
2548  * may have no relation to max_pcbs.  max_pcbs merely indicates the
2549  * amount of space the caller allocated for this function to use.
2550  */
2551 int
2552 syncache_pcblist(struct sysctl_req *req)
2553 {
2554         struct xtcpcb xt;
2555         struct syncache *sc;
2556         struct syncache_head *sch;
2557         int error, i;
2558
2559         bzero(&xt, sizeof(xt));
2560         xt.xt_len = sizeof(xt);
2561         xt.t_state = TCPS_SYN_RECEIVED;
2562         xt.xt_inp.xi_socket.xso_protocol = IPPROTO_TCP;
2563         xt.xt_inp.xi_socket.xso_len = sizeof (struct xsocket);
2564         xt.xt_inp.xi_socket.so_type = SOCK_STREAM;
2565         xt.xt_inp.xi_socket.so_state = SS_ISCONNECTING;
2566
2567         for (i = 0; i < V_tcp_syncache.hashsize; i++) {
2568                 sch = &V_tcp_syncache.hashbase[i];
2569                 SCH_LOCK(sch);
2570                 TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash) {
2571                         if (cr_cansee(req->td->td_ucred, sc->sc_cred) != 0)
2572                                 continue;
2573                         if (sc->sc_inc.inc_flags & INC_ISIPV6)
2574                                 xt.xt_inp.inp_vflag = INP_IPV6;
2575                         else
2576                                 xt.xt_inp.inp_vflag = INP_IPV4;
2577                         xt.xt_encaps_port = sc->sc_port;
2578                         bcopy(&sc->sc_inc, &xt.xt_inp.inp_inc,
2579                             sizeof (struct in_conninfo));
2580                         error = SYSCTL_OUT(req, &xt, sizeof xt);
2581                         if (error) {
2582                                 SCH_UNLOCK(sch);
2583                                 return (0);
2584                         }
2585                 }
2586                 SCH_UNLOCK(sch);
2587         }
2588
2589         return (0);
2590 }