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