xref: /freebsd/sys/netpfil/pf/pf_syncookies.c (revision 4bb3b365776458bd8f710e40f97e2c68994e3306)
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 union pf_syncookie {
92 	uint8_t		cookie;
93 	struct {
94 		uint8_t	oddeven:1,
95 			sack_ok:1,
96 			wscale_idx:3,
97 			mss_idx:3;
98 	} flags;
99 };
100 
101 #define	PF_SYNCOOKIE_SECRET_SIZE	SIPHASH_KEY_LENGTH
102 #define	PF_SYNCOOKIE_SECRET_LIFETIME	15 /* seconds */
103 
104 /* Protected by PF_RULES_xLOCK. */
105 struct pf_syncookie_status {
106 	struct callout	keytimeout;
107 	uint8_t		oddeven;
108 	uint8_t		key[2][SIPHASH_KEY_LENGTH];
109 	uint32_t	hiwat;	/* absolute; # of states */
110 	uint32_t	lowat;
111 };
112 VNET_DEFINE_STATIC(struct pf_syncookie_status, pf_syncookie_status);
113 #define V_pf_syncookie_status	VNET(pf_syncookie_status)
114 
115 static int	pf_syncookies_setmode(u_int8_t);
116 void		pf_syncookie_rotate(void *);
117 void		pf_syncookie_newkey(void);
118 uint32_t	pf_syncookie_mac(struct pf_pdesc *, union pf_syncookie,
119 		    uint32_t);
120 uint32_t	pf_syncookie_generate(struct pf_pdesc *, uint16_t);
121 
122 void
pf_syncookies_init(void)123 pf_syncookies_init(void)
124 {
125 	callout_init(&V_pf_syncookie_status.keytimeout, 1);
126 	PF_RULES_WLOCK();
127 
128 	V_pf_syncookie_status.hiwat = PF_SYNCOOKIES_HIWATPCT *
129 	    V_pf_limits[PF_LIMIT_STATES].limit / 100;
130 	V_pf_syncookie_status.lowat = PF_SYNCOOKIES_LOWATPCT *
131 	    V_pf_limits[PF_LIMIT_STATES].limit / 100;
132 	pf_syncookies_setmode(PF_SYNCOOKIES_ADAPTIVE);
133 
134 	PF_RULES_WUNLOCK();
135 }
136 
137 void
pf_syncookies_cleanup(void)138 pf_syncookies_cleanup(void)
139 {
140 	callout_stop(&V_pf_syncookie_status.keytimeout);
141 }
142 
143 int
pf_get_syncookies(struct pfioc_nv * nv)144 pf_get_syncookies(struct pfioc_nv *nv)
145 {
146 	nvlist_t	*nvl = NULL;
147 	void		*nvlpacked = NULL;
148 	int		 error;
149 
150 #define ERROUT(x)	ERROUT_FUNCTION(errout, x)
151 
152 	nvl = nvlist_create(0);
153 	if (nvl == NULL)
154 		ERROUT(ENOMEM);
155 
156 	nvlist_add_bool(nvl, "enabled",
157 	    V_pf_status.syncookies_mode != PF_SYNCOOKIES_NEVER);
158 	nvlist_add_bool(nvl, "adaptive",
159 	    V_pf_status.syncookies_mode == PF_SYNCOOKIES_ADAPTIVE);
160 	nvlist_add_number(nvl, "highwater", V_pf_syncookie_status.hiwat);
161 	nvlist_add_number(nvl, "lowwater", V_pf_syncookie_status.lowat);
162 	nvlist_add_number(nvl, "halfopen_states",
163 	    atomic_load_32(&V_pf_status.states_halfopen));
164 
165 	nvlpacked = nvlist_pack(nvl, &nv->len);
166 	if (nvlpacked == NULL)
167 		ERROUT(ENOMEM);
168 
169 	if (nv->size == 0) {
170 		ERROUT(0);
171 	} else if (nv->size < nv->len) {
172 		ERROUT(ENOSPC);
173 	}
174 
175 	error = copyout(nvlpacked, nv->data, nv->len);
176 
177 #undef ERROUT
178 errout:
179 	nvlist_destroy(nvl);
180 	free(nvlpacked, M_NVLIST);
181 
182 	return (error);
183 }
184 
185 int
pf_set_syncookies(struct pfioc_nv * nv)186 pf_set_syncookies(struct pfioc_nv *nv)
187 {
188 	nvlist_t	*nvl = NULL;
189 	void		*nvlpacked = NULL;
190 	int		 error;
191 	bool		 enabled, adaptive;
192 	uint32_t	 hiwat, lowat;
193 	uint8_t		 newmode;
194 
195 #define ERROUT(x)	ERROUT_FUNCTION(errout, x)
196 
197 	if (nv->len > pf_ioctl_maxcount)
198 		return (ENOMEM);
199 
200 	nvlpacked = malloc(nv->len, M_NVLIST, M_WAITOK);
201 	error = copyin(nv->data, nvlpacked, nv->len);
202 	if (error)
203 		ERROUT(error);
204 
205 	nvl = nvlist_unpack(nvlpacked, nv->len, 0);
206 	if (nvl == NULL)
207 		ERROUT(EBADMSG);
208 
209 	if (! nvlist_exists_bool(nvl, "enabled")
210 	    || ! nvlist_exists_bool(nvl, "adaptive"))
211 		ERROUT(EBADMSG);
212 
213 	enabled = nvlist_get_bool(nvl, "enabled");
214 	adaptive = nvlist_get_bool(nvl, "adaptive");
215 	PFNV_CHK(pf_nvuint32_opt(nvl, "highwater", &hiwat,
216 	    V_pf_syncookie_status.hiwat));
217 	PFNV_CHK(pf_nvuint32_opt(nvl, "lowwater", &lowat,
218 	    V_pf_syncookie_status.lowat));
219 
220 	if (lowat >= hiwat)
221 		ERROUT(EINVAL);
222 
223 	newmode = PF_SYNCOOKIES_NEVER;
224 	if (enabled)
225 		newmode = adaptive ? PF_SYNCOOKIES_ADAPTIVE : PF_SYNCOOKIES_ALWAYS;
226 
227 	PF_RULES_WLOCK();
228 	error = pf_syncookies_setmode(newmode);
229 
230 	V_pf_syncookie_status.lowat = lowat;
231 	V_pf_syncookie_status.hiwat = hiwat;
232 
233 	PF_RULES_WUNLOCK();
234 
235 #undef ERROUT
236 errout:
237 	nvlist_destroy(nvl);
238 	free(nvlpacked, M_NVLIST);
239 
240 	return (error);
241 }
242 
243 static int
pf_syncookies_setmode(u_int8_t mode)244 pf_syncookies_setmode(u_int8_t mode)
245 {
246 	if (mode > PF_SYNCOOKIES_MODE_MAX)
247 		return (EINVAL);
248 
249 	if (V_pf_status.syncookies_mode == mode)
250 		return (0);
251 
252 	V_pf_status.syncookies_mode = mode;
253 	if (V_pf_status.syncookies_mode == PF_SYNCOOKIES_ALWAYS) {
254 		pf_syncookie_newkey();
255 		V_pf_status.syncookies_active = true;
256 	}
257 	return (0);
258 }
259 
260 int
pf_synflood_check(struct pf_pdesc * pd)261 pf_synflood_check(struct pf_pdesc *pd)
262 {
263 	MPASS(pd->proto == IPPROTO_TCP);
264 	PF_RULES_RASSERT();
265 
266 	if (pd->pf_mtag && (pd->pf_mtag->flags & PF_MTAG_FLAG_SYNCOOKIE_RECREATED))
267 		return (0);
268 
269 	if (V_pf_status.syncookies_mode != PF_SYNCOOKIES_ADAPTIVE)
270 		return (V_pf_status.syncookies_mode);
271 
272 	if (!V_pf_status.syncookies_active &&
273 	    atomic_load_32(&V_pf_status.states_halfopen) >
274 	    V_pf_syncookie_status.hiwat) {
275 		/* We'd want to 'pf_syncookie_newkey()' here, but that requires
276 		 * the rules write lock, which we can't get with the read lock
277 		 * held. */
278 		callout_reset(&V_pf_syncookie_status.keytimeout, 0,
279 		    pf_syncookie_rotate, curvnet);
280 		V_pf_status.syncookies_active = true;
281 		DPFPRINTF(LOG_WARNING,
282 		    "synflood detected, enabling syncookies");
283 		// XXXTODO V_pf_status.lcounters[LCNT_SYNFLOODS]++;
284 	}
285 
286 	return (V_pf_status.syncookies_active);
287 }
288 
289 void
pf_syncookie_send(struct pf_pdesc * pd)290 pf_syncookie_send(struct pf_pdesc *pd)
291 {
292 	uint16_t	mss;
293 	uint32_t	iss;
294 
295 	mss = max(V_tcp_mssdflt, pf_get_mss(pd));
296 	iss = pf_syncookie_generate(pd, mss);
297 	pf_send_tcp(NULL, pd->af, pd->dst, pd->src, *pd->dport, *pd->sport,
298 	    iss, ntohl(pd->hdr.tcp.th_seq) + 1, TH_SYN|TH_ACK, 0, mss,
299 	    0, M_SKIP_FIREWALL | (pd->m->m_flags & M_LOOP), 0, 0,
300 	    pd->act.rtableid);
301 	counter_u64_add(V_pf_status.lcounters[KLCNT_SYNCOOKIES_SENT], 1);
302 	/* XXX Maybe only in adaptive mode? */
303 	atomic_add_64(&V_pf_status.syncookies_inflight[V_pf_syncookie_status.oddeven],
304 	    1);
305 }
306 
307 bool
pf_syncookie_check(struct pf_pdesc * pd)308 pf_syncookie_check(struct pf_pdesc *pd)
309 {
310 	uint32_t		 hash, ack, seq;
311 	union pf_syncookie	 cookie;
312 
313 	MPASS(pd->proto == IPPROTO_TCP);
314 	PF_RULES_RASSERT();
315 
316 	seq = ntohl(pd->hdr.tcp.th_seq) - 1;
317 	ack = ntohl(pd->hdr.tcp.th_ack) - 1;
318 	cookie.cookie = (ack & 0xff) ^ (ack >> 24);
319 
320 	/* we don't know oddeven before setting the cookie (union) */
321 	if (atomic_load_64(&V_pf_status.syncookies_inflight[cookie.flags.oddeven])
322 	    == 0)
323 		return (0);
324 
325 	hash = pf_syncookie_mac(pd, cookie, seq);
326 	if ((ack & ~0xff) != (hash & ~0xff))
327 		return (false);
328 
329 	return (true);
330 }
331 
332 uint8_t
pf_syncookie_validate(struct pf_pdesc * pd)333 pf_syncookie_validate(struct pf_pdesc *pd)
334 {
335 	uint32_t		 ack;
336 	union pf_syncookie	 cookie;
337 
338 	if (! pf_syncookie_check(pd))
339 		return (0);
340 
341 	ack = ntohl(pd->hdr.tcp.th_ack) - 1;
342 	cookie.cookie = (ack & 0xff) ^ (ack >> 24);
343 
344 	counter_u64_add(V_pf_status.lcounters[KLCNT_SYNCOOKIES_VALID], 1);
345 	atomic_add_64(&V_pf_status.syncookies_inflight[cookie.flags.oddeven], -1);
346 
347 	return (1);
348 }
349 
350 /*
351  * all following functions private
352  */
353 void
pf_syncookie_rotate(void * arg)354 pf_syncookie_rotate(void *arg)
355 {
356 	CURVNET_SET((struct vnet *)arg);
357 
358 	/* do we want to disable syncookies? */
359 	if (V_pf_status.syncookies_active &&
360 	    ((V_pf_status.syncookies_mode == PF_SYNCOOKIES_ADAPTIVE &&
361 	    (atomic_load_32(&V_pf_status.states_halfopen) +
362 	    atomic_load_64(&V_pf_status.syncookies_inflight[0]) +
363 	    atomic_load_64(&V_pf_status.syncookies_inflight[1])) <
364 	    V_pf_syncookie_status.lowat) ||
365 	    V_pf_status.syncookies_mode == PF_SYNCOOKIES_NEVER)
366 			) {
367 		V_pf_status.syncookies_active = false;
368 		DPFPRINTF(PF_DEBUG_MISC, "syncookies disabled");
369 	}
370 
371 	/* nothing in flight any more? delete keys and return */
372 	if (!V_pf_status.syncookies_active &&
373 	    atomic_load_64(&V_pf_status.syncookies_inflight[0]) == 0 &&
374 	    atomic_load_64(&V_pf_status.syncookies_inflight[1]) == 0) {
375 		memset(V_pf_syncookie_status.key[0], 0,
376 		    PF_SYNCOOKIE_SECRET_SIZE);
377 		memset(V_pf_syncookie_status.key[1], 0,
378 		    PF_SYNCOOKIE_SECRET_SIZE);
379 		CURVNET_RESTORE();
380 		return;
381 	}
382 
383 	PF_RULES_WLOCK();
384 	/* new key, including timeout */
385 	pf_syncookie_newkey();
386 	PF_RULES_WUNLOCK();
387 
388 	CURVNET_RESTORE();
389 }
390 
391 void
pf_syncookie_newkey(void)392 pf_syncookie_newkey(void)
393 {
394 	PF_RULES_WASSERT();
395 
396 	MPASS(V_pf_syncookie_status.oddeven < 2);
397 	V_pf_syncookie_status.oddeven = (V_pf_syncookie_status.oddeven + 1) & 0x1;
398 	atomic_store_64(&V_pf_status.syncookies_inflight[V_pf_syncookie_status.oddeven], 0);
399 	arc4random_buf(V_pf_syncookie_status.key[V_pf_syncookie_status.oddeven],
400 	    PF_SYNCOOKIE_SECRET_SIZE);
401 	callout_reset(&V_pf_syncookie_status.keytimeout,
402 	    PF_SYNCOOKIE_SECRET_LIFETIME * hz, pf_syncookie_rotate, curvnet);
403 }
404 
405 /*
406  * Distribution and probability of certain MSS values.  Those in between are
407  * rounded down to the next lower one.
408  * [An Analysis of TCP Maximum Segment Sizes, S. Alcock and R. Nelson, 2011]
409  *   .2%  .3%   5%    7%    7%    20%   15%   45%
410  */
411 static int pf_syncookie_msstab[] =
412     { 216, 536, 1200, 1360, 1400, 1440, 1452, 1460 };
413 
414 /*
415  * Distribution and probability of certain WSCALE values.
416  * The absence of the WSCALE option is encoded with index zero.
417  * [WSCALE values histograms, Allman, 2012]
418  *                                  X 10 10 35  5  6 14 10%   by host
419  *                                  X 11  4  5  5 18 49  3%   by connections
420  */
421 static int pf_syncookie_wstab[] = { 0, 0, 1, 2, 4, 6, 7, 8 };
422 
423 uint32_t
pf_syncookie_mac(struct pf_pdesc * pd,union pf_syncookie cookie,uint32_t seq)424 pf_syncookie_mac(struct pf_pdesc *pd, union pf_syncookie cookie, uint32_t seq)
425 {
426 	SIPHASH_CTX	ctx;
427 	uint32_t	siphash[2];
428 
429 	PF_RULES_RASSERT();
430 	MPASS(pd->proto == IPPROTO_TCP);
431 
432 	SipHash24_Init(&ctx);
433 	SipHash_SetKey(&ctx, V_pf_syncookie_status.key[cookie.flags.oddeven]);
434 
435 	switch (pd->af) {
436 	case AF_INET:
437 		SipHash_Update(&ctx, pd->src, sizeof(pd->src->v4));
438 		SipHash_Update(&ctx, pd->dst, sizeof(pd->dst->v4));
439 		break;
440 	case AF_INET6:
441 		SipHash_Update(&ctx, pd->src, sizeof(pd->src->v6));
442 		SipHash_Update(&ctx, pd->dst, sizeof(pd->dst->v6));
443 		break;
444 	default:
445 		panic("unknown address family");
446 	}
447 
448 	SipHash_Update(&ctx, pd->sport, sizeof(*pd->sport));
449 	SipHash_Update(&ctx, pd->dport, sizeof(*pd->dport));
450 	SipHash_Update(&ctx, &seq, sizeof(seq));
451 	SipHash_Update(&ctx, &cookie, sizeof(cookie));
452 	SipHash_Final((uint8_t *)&siphash, &ctx);
453 
454 	return (siphash[0] ^ siphash[1]);
455 }
456 
457 uint32_t
pf_syncookie_generate(struct pf_pdesc * pd,uint16_t mss)458 pf_syncookie_generate(struct pf_pdesc *pd, uint16_t mss)
459 {
460 	uint8_t			 i, wscale;
461 	uint32_t		 iss, hash;
462 	union pf_syncookie	 cookie;
463 
464 	PF_RULES_RASSERT();
465 
466 	cookie.cookie = 0;
467 
468 	/* map MSS */
469 	for (i = nitems(pf_syncookie_msstab) - 1;
470 	    pf_syncookie_msstab[i] > mss && i > 0; i--)
471 		/* nada */;
472 	cookie.flags.mss_idx = i;
473 
474 	/* map WSCALE */
475 	wscale = pf_get_wscale(pd);
476 	for (i = nitems(pf_syncookie_wstab) - 1;
477 	    pf_syncookie_wstab[i] > wscale && i > 0; i--)
478 		/* nada */;
479 	cookie.flags.wscale_idx = i;
480 	cookie.flags.sack_ok = 0;	/* XXX */
481 
482 	cookie.flags.oddeven = V_pf_syncookie_status.oddeven;
483 	hash = pf_syncookie_mac(pd, cookie, ntohl(pd->hdr.tcp.th_seq));
484 
485 	/*
486 	 * Put the flags into the hash and XOR them to get better ISS number
487 	 * variance.  This doesn't enhance the cryptographic strength and is
488 	 * done to prevent the 8 cookie bits from showing up directly on the
489 	 * wire.
490 	 */
491 	iss = hash & ~0xff;
492 	iss |= cookie.cookie ^ (hash >> 24);
493 
494 	return (iss);
495 }
496 
497 struct mbuf *
pf_syncookie_recreate_syn(struct pf_pdesc * pd)498 pf_syncookie_recreate_syn(struct pf_pdesc *pd)
499 {
500 	uint8_t			 wscale;
501 	uint16_t		 mss;
502 	uint32_t		 ack, seq;
503 	union pf_syncookie	 cookie;
504 
505 	seq = ntohl(pd->hdr.tcp.th_seq) - 1;
506 	ack = ntohl(pd->hdr.tcp.th_ack) - 1;
507 	cookie.cookie = (ack & 0xff) ^ (ack >> 24);
508 
509 	if (cookie.flags.mss_idx >= nitems(pf_syncookie_msstab) ||
510 	    cookie.flags.wscale_idx >= nitems(pf_syncookie_wstab))
511 		return (NULL);
512 
513 	mss = pf_syncookie_msstab[cookie.flags.mss_idx];
514 	wscale = pf_syncookie_wstab[cookie.flags.wscale_idx];
515 
516 	return (pf_build_tcp(NULL, pd->af, pd->src, pd->dst, *pd->sport,
517 	    *pd->dport, seq, 0, TH_SYN, wscale, mss, pd->ttl,
518 	    (pd->m->m_flags & M_LOOP), 0, PF_MTAG_FLAG_SYNCOOKIE_RECREATED,
519 	    cookie.flags.sack_ok, pd->act.rtableid));
520 }
521