xref: /freebsd/sys/netpfil/pf/pf_syncookies.c (revision 87b759f0fa1f7554d50ce640c40138512bbded44)
1 /*	$OpenBSD: pf_syncookies.c,v 1.7 2018/09/10 15:54:28 henning Exp $ */
2 
3 /* Copyright (c) 2016,2017 Henning Brauer <henning@openbsd.org>
4  * Copyright (c) 2016 Alexandr Nedvedicky <sashan@openbsd.org>
5  *
6  * syncookie parts based on FreeBSD sys/netinet/tcp_syncache.c
7  *
8  * Copyright (c) 2001 McAfee, Inc.
9  * Copyright (c) 2006,2013 Andre Oppermann, Internet Business Solutions AG
10  * All rights reserved.
11  *
12  * This software was developed for the FreeBSD Project by Jonathan Lemon
13  * and McAfee Research, the Security Research Division of McAfee, Inc. under
14  * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the
15  * DARPA CHATS research program. [2001 McAfee, Inc.]
16  *
17  * Redistribution and use in source and binary forms, with or without
18  * modification, are permitted provided that the following conditions
19  * are met:
20  * 1. Redistributions of source code must retain the above copyright
21  *    notice, this list of conditions and the following disclaimer.
22  * 2. Redistributions in binary form must reproduce the above copyright
23  *    notice, this list of conditions and the following disclaimer in the
24  *    documentation and/or other materials provided with the distribution.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  */
38 
39 /*
40  * when we're under synflood, we use syncookies to prevent state table
41  * exhaustion. Trigger for the synflood mode is the number of half-open
42  * connections in the state table.
43  * We leave synflood mode when the number of half-open states - including
44  * in-flight syncookies - drops far enough again
45  */
46 
47 /*
48  * syncookie enabled Initial Sequence Number:
49  *  24 bit MAC
50  *   3 bit WSCALE index
51  *   3 bit MSS index
52  *   1 bit SACK permitted
53  *   1 bit odd/even secret
54  *
55  * References:
56  *  RFC4987 TCP SYN Flooding Attacks and Common Mitigations
57  *  http://cr.yp.to/syncookies.html    (overview)
58  *  http://cr.yp.to/syncookies/archive (details)
59  */
60 
61 //#include "pflog.h"
62 
63 #include <sys/param.h>
64 #include <sys/systm.h>
65 #include <sys/mbuf.h>
66 #include <sys/filio.h>
67 #include <sys/socket.h>
68 #include <sys/socketvar.h>
69 #include <sys/kernel.h>
70 #include <sys/time.h>
71 #include <sys/proc.h>
72 #include <sys/rwlock.h>
73 #include <sys/syslog.h>
74 
75 #include <crypto/siphash/siphash.h>
76 
77 #include <net/if.h>
78 #include <net/if_var.h>
79 #include <net/if_types.h>
80 #include <net/route.h>
81 
82 #include <netinet/in.h>
83 #include <netinet/in_pcb.h>
84 #include <netinet/ip.h>
85 #include <netinet/tcp.h>
86 #include <netinet/tcp_var.h>
87 
88 #include <net/pfvar.h>
89 #include <netpfil/pf/pf_nv.h>
90 
91 #define	DPFPRINTF(n, x)	if (V_pf_status.debug >= (n)) printf x
92 
93 union pf_syncookie {
94 	uint8_t		cookie;
95 	struct {
96 		uint8_t	oddeven:1,
97 			sack_ok:1,
98 			wscale_idx:3,
99 			mss_idx:3;
100 	} flags;
101 };
102 
103 #define	PF_SYNCOOKIE_SECRET_SIZE	SIPHASH_KEY_LENGTH
104 #define	PF_SYNCOOKIE_SECRET_LIFETIME	15 /* seconds */
105 
106 /* Protected by PF_RULES_xLOCK. */
107 struct pf_syncookie_status {
108 	struct callout	keytimeout;
109 	uint8_t		oddeven;
110 	uint8_t		key[2][SIPHASH_KEY_LENGTH];
111 	uint32_t	hiwat;	/* absolute; # of states */
112 	uint32_t	lowat;
113 };
114 VNET_DEFINE_STATIC(struct pf_syncookie_status, pf_syncookie_status);
115 #define V_pf_syncookie_status	VNET(pf_syncookie_status)
116 
117 static int	pf_syncookies_setmode(u_int8_t);
118 void		pf_syncookie_rotate(void *);
119 void		pf_syncookie_newkey(void);
120 uint32_t	pf_syncookie_mac(struct pf_pdesc *, union pf_syncookie,
121 		    uint32_t);
122 uint32_t	pf_syncookie_generate(struct pf_pdesc *, uint16_t);
123 
124 void
125 pf_syncookies_init(void)
126 {
127 	callout_init(&V_pf_syncookie_status.keytimeout, 1);
128 	PF_RULES_WLOCK();
129 
130 	V_pf_syncookie_status.hiwat = PF_SYNCOOKIES_HIWATPCT *
131 	    V_pf_limits[PF_LIMIT_STATES].limit / 100;
132 	V_pf_syncookie_status.lowat = PF_SYNCOOKIES_LOWATPCT *
133 	    V_pf_limits[PF_LIMIT_STATES].limit / 100;
134 	pf_syncookies_setmode(PF_SYNCOOKIES_ADAPTIVE);
135 
136 	PF_RULES_WUNLOCK();
137 }
138 
139 void
140 pf_syncookies_cleanup(void)
141 {
142 	callout_stop(&V_pf_syncookie_status.keytimeout);
143 }
144 
145 int
146 pf_get_syncookies(struct pfioc_nv *nv)
147 {
148 	nvlist_t	*nvl = NULL;
149 	void		*nvlpacked = NULL;
150 	int		 error;
151 
152 #define ERROUT(x)	ERROUT_FUNCTION(errout, x)
153 
154 	nvl = nvlist_create(0);
155 	if (nvl == NULL)
156 		ERROUT(ENOMEM);
157 
158 	nvlist_add_bool(nvl, "enabled",
159 	    V_pf_status.syncookies_mode != PF_SYNCOOKIES_NEVER);
160 	nvlist_add_bool(nvl, "adaptive",
161 	    V_pf_status.syncookies_mode == PF_SYNCOOKIES_ADAPTIVE);
162 	nvlist_add_number(nvl, "highwater", V_pf_syncookie_status.hiwat);
163 	nvlist_add_number(nvl, "lowwater", V_pf_syncookie_status.lowat);
164 	nvlist_add_number(nvl, "halfopen_states",
165 	    atomic_load_32(&V_pf_status.states_halfopen));
166 
167 	nvlpacked = nvlist_pack(nvl, &nv->len);
168 	if (nvlpacked == NULL)
169 		ERROUT(ENOMEM);
170 
171 	if (nv->size == 0) {
172 		ERROUT(0);
173 	} else if (nv->size < nv->len) {
174 		ERROUT(ENOSPC);
175 	}
176 
177 	error = copyout(nvlpacked, nv->data, nv->len);
178 
179 #undef ERROUT
180 errout:
181 	nvlist_destroy(nvl);
182 	free(nvlpacked, M_NVLIST);
183 
184 	return (error);
185 }
186 
187 int
188 pf_set_syncookies(struct pfioc_nv *nv)
189 {
190 	nvlist_t	*nvl = NULL;
191 	void		*nvlpacked = NULL;
192 	int		 error;
193 	bool		 enabled, adaptive;
194 	uint32_t	 hiwat, lowat;
195 	uint8_t		 newmode;
196 
197 #define ERROUT(x)	ERROUT_FUNCTION(errout, x)
198 
199 	if (nv->len > pf_ioctl_maxcount)
200 		return (ENOMEM);
201 
202 	nvlpacked = malloc(nv->len, M_NVLIST, M_WAITOK);
203 	error = copyin(nv->data, nvlpacked, nv->len);
204 	if (error)
205 		ERROUT(error);
206 
207 	nvl = nvlist_unpack(nvlpacked, nv->len, 0);
208 	if (nvl == NULL)
209 		ERROUT(EBADMSG);
210 
211 	if (! nvlist_exists_bool(nvl, "enabled")
212 	    || ! nvlist_exists_bool(nvl, "adaptive"))
213 		ERROUT(EBADMSG);
214 
215 	enabled = nvlist_get_bool(nvl, "enabled");
216 	adaptive = nvlist_get_bool(nvl, "adaptive");
217 	PFNV_CHK(pf_nvuint32_opt(nvl, "highwater", &hiwat,
218 	    V_pf_syncookie_status.hiwat));
219 	PFNV_CHK(pf_nvuint32_opt(nvl, "lowwater", &lowat,
220 	    V_pf_syncookie_status.lowat));
221 
222 	if (lowat >= hiwat)
223 		ERROUT(EINVAL);
224 
225 	newmode = PF_SYNCOOKIES_NEVER;
226 	if (enabled)
227 		newmode = adaptive ? PF_SYNCOOKIES_ADAPTIVE : PF_SYNCOOKIES_ALWAYS;
228 
229 	PF_RULES_WLOCK();
230 	error = pf_syncookies_setmode(newmode);
231 
232 	V_pf_syncookie_status.lowat = lowat;
233 	V_pf_syncookie_status.hiwat = hiwat;
234 
235 	PF_RULES_WUNLOCK();
236 
237 #undef ERROUT
238 errout:
239 	nvlist_destroy(nvl);
240 	free(nvlpacked, M_NVLIST);
241 
242 	return (error);
243 }
244 
245 static int
246 pf_syncookies_setmode(u_int8_t mode)
247 {
248 	if (mode > PF_SYNCOOKIES_MODE_MAX)
249 		return (EINVAL);
250 
251 	if (V_pf_status.syncookies_mode == mode)
252 		return (0);
253 
254 	V_pf_status.syncookies_mode = mode;
255 	if (V_pf_status.syncookies_mode == PF_SYNCOOKIES_ALWAYS) {
256 		pf_syncookie_newkey();
257 		V_pf_status.syncookies_active = true;
258 	}
259 	return (0);
260 }
261 
262 int
263 pf_synflood_check(struct pf_pdesc *pd)
264 {
265 	MPASS(pd->proto == IPPROTO_TCP);
266 	PF_RULES_RASSERT();
267 
268 	if (pd->pf_mtag && (pd->pf_mtag->flags & PF_MTAG_FLAG_SYNCOOKIE_RECREATED))
269 		return (0);
270 
271 	if (V_pf_status.syncookies_mode != PF_SYNCOOKIES_ADAPTIVE)
272 		return (V_pf_status.syncookies_mode);
273 
274 	if (!V_pf_status.syncookies_active &&
275 	    atomic_load_32(&V_pf_status.states_halfopen) >
276 	    V_pf_syncookie_status.hiwat) {
277 		/* We'd want to 'pf_syncookie_newkey()' here, but that requires
278 		 * the rules write lock, which we can't get with the read lock
279 		 * held. */
280 		callout_reset(&V_pf_syncookie_status.keytimeout, 0,
281 		    pf_syncookie_rotate, curvnet);
282 		V_pf_status.syncookies_active = true;
283 		DPFPRINTF(LOG_WARNING,
284 		    ("synflood detected, enabling syncookies\n"));
285 		// XXXTODO V_pf_status.lcounters[LCNT_SYNFLOODS]++;
286 	}
287 
288 	return (V_pf_status.syncookies_active);
289 }
290 
291 void
292 pf_syncookie_send(struct pf_pdesc *pd)
293 {
294 	uint16_t	mss;
295 	uint32_t	iss;
296 
297 	mss = max(V_tcp_mssdflt, pf_get_mss(pd));
298 	iss = pf_syncookie_generate(pd, mss);
299 	pf_send_tcp(NULL, pd->af, pd->dst, pd->src, *pd->dport, *pd->sport,
300 	    iss, ntohl(pd->hdr.tcp.th_seq) + 1, TH_SYN|TH_ACK, 0, mss,
301 	    0, true, 0, 0, pd->act.rtableid);
302 	counter_u64_add(V_pf_status.lcounters[KLCNT_SYNCOOKIES_SENT], 1);
303 	/* XXX Maybe only in adaptive mode? */
304 	atomic_add_64(&V_pf_status.syncookies_inflight[V_pf_syncookie_status.oddeven],
305 	    1);
306 }
307 
308 bool
309 pf_syncookie_check(struct pf_pdesc *pd)
310 {
311 	uint32_t		 hash, ack, seq;
312 	union pf_syncookie	 cookie;
313 
314 	MPASS(pd->proto == IPPROTO_TCP);
315 	PF_RULES_RASSERT();
316 
317 	seq = ntohl(pd->hdr.tcp.th_seq) - 1;
318 	ack = ntohl(pd->hdr.tcp.th_ack) - 1;
319 	cookie.cookie = (ack & 0xff) ^ (ack >> 24);
320 
321 	/* we don't know oddeven before setting the cookie (union) */
322 	if (atomic_load_64(&V_pf_status.syncookies_inflight[cookie.flags.oddeven])
323 	    == 0)
324 		return (0);
325 
326 	hash = pf_syncookie_mac(pd, cookie, seq);
327 	if ((ack & ~0xff) != (hash & ~0xff))
328 		return (false);
329 
330 	return (true);
331 }
332 
333 uint8_t
334 pf_syncookie_validate(struct pf_pdesc *pd)
335 {
336 	uint32_t		 ack;
337 	union pf_syncookie	 cookie;
338 
339 	if (! pf_syncookie_check(pd))
340 		return (0);
341 
342 	ack = ntohl(pd->hdr.tcp.th_ack) - 1;
343 	cookie.cookie = (ack & 0xff) ^ (ack >> 24);
344 
345 	counter_u64_add(V_pf_status.lcounters[KLCNT_SYNCOOKIES_VALID], 1);
346 	atomic_add_64(&V_pf_status.syncookies_inflight[cookie.flags.oddeven], -1);
347 
348 	return (1);
349 }
350 
351 /*
352  * all following functions private
353  */
354 void
355 pf_syncookie_rotate(void *arg)
356 {
357 	CURVNET_SET((struct vnet *)arg);
358 
359 	/* do we want to disable syncookies? */
360 	if (V_pf_status.syncookies_active &&
361 	    ((V_pf_status.syncookies_mode == PF_SYNCOOKIES_ADAPTIVE &&
362 	    (atomic_load_32(&V_pf_status.states_halfopen) +
363 	    atomic_load_64(&V_pf_status.syncookies_inflight[0]) +
364 	    atomic_load_64(&V_pf_status.syncookies_inflight[1])) <
365 	    V_pf_syncookie_status.lowat) ||
366 	    V_pf_status.syncookies_mode == PF_SYNCOOKIES_NEVER)
367 			) {
368 		V_pf_status.syncookies_active = false;
369 		DPFPRINTF(PF_DEBUG_MISC, ("syncookies disabled\n"));
370 	}
371 
372 	/* nothing in flight any more? delete keys and return */
373 	if (!V_pf_status.syncookies_active &&
374 	    atomic_load_64(&V_pf_status.syncookies_inflight[0]) == 0 &&
375 	    atomic_load_64(&V_pf_status.syncookies_inflight[1]) == 0) {
376 		memset(V_pf_syncookie_status.key[0], 0,
377 		    PF_SYNCOOKIE_SECRET_SIZE);
378 		memset(V_pf_syncookie_status.key[1], 0,
379 		    PF_SYNCOOKIE_SECRET_SIZE);
380 		CURVNET_RESTORE();
381 		return;
382 	}
383 
384 	PF_RULES_WLOCK();
385 	/* new key, including timeout */
386 	pf_syncookie_newkey();
387 	PF_RULES_WUNLOCK();
388 
389 	CURVNET_RESTORE();
390 }
391 
392 void
393 pf_syncookie_newkey(void)
394 {
395 	PF_RULES_WASSERT();
396 
397 	MPASS(V_pf_syncookie_status.oddeven < 2);
398 	V_pf_syncookie_status.oddeven = (V_pf_syncookie_status.oddeven + 1) & 0x1;
399 	atomic_store_64(&V_pf_status.syncookies_inflight[V_pf_syncookie_status.oddeven], 0);
400 	arc4random_buf(V_pf_syncookie_status.key[V_pf_syncookie_status.oddeven],
401 	    PF_SYNCOOKIE_SECRET_SIZE);
402 	callout_reset(&V_pf_syncookie_status.keytimeout,
403 	    PF_SYNCOOKIE_SECRET_LIFETIME * hz, pf_syncookie_rotate, curvnet);
404 }
405 
406 /*
407  * Distribution and probability of certain MSS values.  Those in between are
408  * rounded down to the next lower one.
409  * [An Analysis of TCP Maximum Segment Sizes, S. Alcock and R. Nelson, 2011]
410  *   .2%  .3%   5%    7%    7%    20%   15%   45%
411  */
412 static int pf_syncookie_msstab[] =
413     { 216, 536, 1200, 1360, 1400, 1440, 1452, 1460 };
414 
415 /*
416  * Distribution and probability of certain WSCALE values.
417  * The absence of the WSCALE option is encoded with index zero.
418  * [WSCALE values histograms, Allman, 2012]
419  *                                  X 10 10 35  5  6 14 10%   by host
420  *                                  X 11  4  5  5 18 49  3%   by connections
421  */
422 static int pf_syncookie_wstab[] = { 0, 0, 1, 2, 4, 6, 7, 8 };
423 
424 uint32_t
425 pf_syncookie_mac(struct pf_pdesc *pd, union pf_syncookie cookie, uint32_t seq)
426 {
427 	SIPHASH_CTX	ctx;
428 	uint32_t	siphash[2];
429 
430 	PF_RULES_RASSERT();
431 	MPASS(pd->proto == IPPROTO_TCP);
432 
433 	SipHash24_Init(&ctx);
434 	SipHash_SetKey(&ctx, V_pf_syncookie_status.key[cookie.flags.oddeven]);
435 
436 	switch (pd->af) {
437 	case AF_INET:
438 		SipHash_Update(&ctx, pd->src, sizeof(pd->src->v4));
439 		SipHash_Update(&ctx, pd->dst, sizeof(pd->dst->v4));
440 		break;
441 	case AF_INET6:
442 		SipHash_Update(&ctx, pd->src, sizeof(pd->src->v6));
443 		SipHash_Update(&ctx, pd->dst, sizeof(pd->dst->v6));
444 		break;
445 	default:
446 		panic("unknown address family");
447 	}
448 
449 	SipHash_Update(&ctx, pd->sport, sizeof(*pd->sport));
450 	SipHash_Update(&ctx, pd->dport, sizeof(*pd->dport));
451 	SipHash_Update(&ctx, &seq, sizeof(seq));
452 	SipHash_Update(&ctx, &cookie, sizeof(cookie));
453 	SipHash_Final((uint8_t *)&siphash, &ctx);
454 
455 	return (siphash[0] ^ siphash[1]);
456 }
457 
458 uint32_t
459 pf_syncookie_generate(struct pf_pdesc *pd, uint16_t mss)
460 {
461 	uint8_t			 i, wscale;
462 	uint32_t		 iss, hash;
463 	union pf_syncookie	 cookie;
464 
465 	PF_RULES_RASSERT();
466 
467 	cookie.cookie = 0;
468 
469 	/* map MSS */
470 	for (i = nitems(pf_syncookie_msstab) - 1;
471 	    pf_syncookie_msstab[i] > mss && i > 0; i--)
472 		/* nada */;
473 	cookie.flags.mss_idx = i;
474 
475 	/* map WSCALE */
476 	wscale = pf_get_wscale(pd);
477 	for (i = nitems(pf_syncookie_wstab) - 1;
478 	    pf_syncookie_wstab[i] > wscale && i > 0; i--)
479 		/* nada */;
480 	cookie.flags.wscale_idx = i;
481 	cookie.flags.sack_ok = 0;	/* XXX */
482 
483 	cookie.flags.oddeven = V_pf_syncookie_status.oddeven;
484 	hash = pf_syncookie_mac(pd, cookie, ntohl(pd->hdr.tcp.th_seq));
485 
486 	/*
487 	 * Put the flags into the hash and XOR them to get better ISS number
488 	 * variance.  This doesn't enhance the cryptographic strength and is
489 	 * done to prevent the 8 cookie bits from showing up directly on the
490 	 * wire.
491 	 */
492 	iss = hash & ~0xff;
493 	iss |= cookie.cookie ^ (hash >> 24);
494 
495 	return (iss);
496 }
497 
498 struct mbuf *
499 pf_syncookie_recreate_syn(struct pf_pdesc *pd)
500 {
501 	uint8_t			 wscale;
502 	uint16_t		 mss;
503 	uint32_t		 ack, seq;
504 	union pf_syncookie	 cookie;
505 
506 	seq = ntohl(pd->hdr.tcp.th_seq) - 1;
507 	ack = ntohl(pd->hdr.tcp.th_ack) - 1;
508 	cookie.cookie = (ack & 0xff) ^ (ack >> 24);
509 
510 	if (cookie.flags.mss_idx >= nitems(pf_syncookie_msstab) ||
511 	    cookie.flags.wscale_idx >= nitems(pf_syncookie_wstab))
512 		return (NULL);
513 
514 	mss = pf_syncookie_msstab[cookie.flags.mss_idx];
515 	wscale = pf_syncookie_wstab[cookie.flags.wscale_idx];
516 
517 	return (pf_build_tcp(NULL, pd->af, pd->src, pd->dst, *pd->sport,
518 	    *pd->dport, seq, 0, TH_SYN, wscale, mss, pd->ttl, false, 0,
519 	    PF_MTAG_FLAG_SYNCOOKIE_RECREATED, pd->act.rtableid));
520 }
521