xref: /freebsd/sys/netipsec/xform_esp.c (revision aa0a1e58)
1 /*	$FreeBSD$	*/
2 /*	$OpenBSD: ip_esp.c,v 1.69 2001/06/26 06:18:59 angelos Exp $ */
3 /*-
4  * The authors of this code are John Ioannidis (ji@tla.org),
5  * Angelos D. Keromytis (kermit@csd.uch.gr) and
6  * Niels Provos (provos@physnet.uni-hamburg.de).
7  *
8  * The original version of this code was written by John Ioannidis
9  * for BSD/OS in Athens, Greece, in November 1995.
10  *
11  * Ported to OpenBSD and NetBSD, with additional transforms, in December 1996,
12  * by Angelos D. Keromytis.
13  *
14  * Additional transforms and features in 1997 and 1998 by Angelos D. Keromytis
15  * and Niels Provos.
16  *
17  * Additional features in 1999 by Angelos D. Keromytis.
18  *
19  * Copyright (C) 1995, 1996, 1997, 1998, 1999 by John Ioannidis,
20  * Angelos D. Keromytis and Niels Provos.
21  * Copyright (c) 2001 Angelos D. Keromytis.
22  *
23  * Permission to use, copy, and modify this software with or without fee
24  * is hereby granted, provided that this entire notice is included in
25  * all copies of any software which is or includes a copy or
26  * modification of this software.
27  * You may use this code under the GNU public license if you so wish. Please
28  * contribute changes back to the authors under this freer than GPL license
29  * so that we may further the use of strong encryption without limitations to
30  * all.
31  *
32  * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
33  * IMPLIED WARRANTY. IN PARTICULAR, NONE OF THE AUTHORS MAKES ANY
34  * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
35  * MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
36  * PURPOSE.
37  */
38 #include "opt_inet.h"
39 #include "opt_inet6.h"
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/mbuf.h>
44 #include <sys/socket.h>
45 #include <sys/syslog.h>
46 #include <sys/kernel.h>
47 #include <sys/random.h>
48 #include <sys/sysctl.h>
49 
50 #include <net/if.h>
51 #include <net/vnet.h>
52 
53 #include <netinet/in.h>
54 #include <netinet/in_systm.h>
55 #include <netinet/ip.h>
56 #include <netinet/ip_ecn.h>
57 #include <netinet/ip6.h>
58 
59 #include <net/route.h>
60 #include <netipsec/ipsec.h>
61 #include <netipsec/ah.h>
62 #include <netipsec/ah_var.h>
63 #include <netipsec/esp.h>
64 #include <netipsec/esp_var.h>
65 #include <netipsec/xform.h>
66 
67 #ifdef INET6
68 #include <netinet6/ip6_var.h>
69 #include <netipsec/ipsec6.h>
70 #include <netinet6/ip6_ecn.h>
71 #endif
72 
73 #include <netipsec/key.h>
74 #include <netipsec/key_debug.h>
75 
76 #include <opencrypto/cryptodev.h>
77 #include <opencrypto/xform.h>
78 
79 VNET_DEFINE(int, esp_enable) = 1;
80 VNET_DEFINE(struct espstat, espstat);
81 
82 SYSCTL_DECL(_net_inet_esp);
83 SYSCTL_VNET_INT(_net_inet_esp, OID_AUTO,
84 	esp_enable,	CTLFLAG_RW,	&VNET_NAME(esp_enable),	0, "");
85 SYSCTL_VNET_STRUCT(_net_inet_esp, IPSECCTL_STATS,
86 	stats,		CTLFLAG_RD,	&VNET_NAME(espstat),	espstat, "");
87 
88 static VNET_DEFINE(int, esp_max_ivlen);	/* max iv length over all algorithms */
89 #define	V_esp_max_ivlen	VNET(esp_max_ivlen)
90 
91 static int esp_input_cb(struct cryptop *op);
92 static int esp_output_cb(struct cryptop *crp);
93 
94 /*
95  * NB: this is public for use by the PF_KEY support.
96  * NB: if you add support here; be sure to add code to esp_attach below!
97  */
98 struct enc_xform *
99 esp_algorithm_lookup(int alg)
100 {
101 	if (alg >= ESP_ALG_MAX)
102 		return NULL;
103 	switch (alg) {
104 	case SADB_EALG_DESCBC:
105 		return &enc_xform_des;
106 	case SADB_EALG_3DESCBC:
107 		return &enc_xform_3des;
108 	case SADB_X_EALG_AES:
109 		return &enc_xform_rijndael128;
110 	case SADB_X_EALG_BLOWFISHCBC:
111 		return &enc_xform_blf;
112 	case SADB_X_EALG_CAST128CBC:
113 		return &enc_xform_cast5;
114 	case SADB_X_EALG_SKIPJACK:
115 		return &enc_xform_skipjack;
116 	case SADB_EALG_NULL:
117 		return &enc_xform_null;
118 	case SADB_X_EALG_CAMELLIACBC:
119 		return &enc_xform_camellia;
120 	}
121 	return NULL;
122 }
123 
124 size_t
125 esp_hdrsiz(struct secasvar *sav)
126 {
127 	size_t size;
128 
129 	if (sav != NULL) {
130 		/*XXX not right for null algorithm--does it matter??*/
131 		IPSEC_ASSERT(sav->tdb_encalgxform != NULL,
132 			("SA with null xform"));
133 		if (sav->flags & SADB_X_EXT_OLD)
134 			size = sizeof (struct esp);
135 		else
136 			size = sizeof (struct newesp);
137 		size += sav->tdb_encalgxform->blocksize + 9;
138 		/*XXX need alg check???*/
139 		if (sav->tdb_authalgxform != NULL && sav->replay)
140 			size += ah_hdrsiz(sav);
141 	} else {
142 		/*
143 		 *   base header size
144 		 * + max iv length for CBC mode
145 		 * + max pad length
146 		 * + sizeof (pad length field)
147 		 * + sizeof (next header field)
148 		 * + max icv supported.
149 		 */
150 		size = sizeof (struct newesp) + V_esp_max_ivlen + 9 + 16;
151 	}
152 	return size;
153 }
154 
155 /*
156  * esp_init() is called when an SPI is being set up.
157  */
158 static int
159 esp_init(struct secasvar *sav, struct xformsw *xsp)
160 {
161 	struct enc_xform *txform;
162 	struct cryptoini cria, crie;
163 	int keylen;
164 	int error;
165 
166 	txform = esp_algorithm_lookup(sav->alg_enc);
167 	if (txform == NULL) {
168 		DPRINTF(("%s: unsupported encryption algorithm %d\n",
169 			__func__, sav->alg_enc));
170 		return EINVAL;
171 	}
172 	if (sav->key_enc == NULL) {
173 		DPRINTF(("%s: no encoding key for %s algorithm\n",
174 			 __func__, txform->name));
175 		return EINVAL;
176 	}
177 	if ((sav->flags&(SADB_X_EXT_OLD|SADB_X_EXT_IV4B)) == SADB_X_EXT_IV4B) {
178 		DPRINTF(("%s: 4-byte IV not supported with protocol\n",
179 			__func__));
180 		return EINVAL;
181 	}
182 	keylen = _KEYLEN(sav->key_enc);
183 	if (txform->minkey > keylen || keylen > txform->maxkey) {
184 		DPRINTF(("%s: invalid key length %u, must be in the range "
185 			"[%u..%u] for algorithm %s\n", __func__,
186 			keylen, txform->minkey, txform->maxkey,
187 			txform->name));
188 		return EINVAL;
189 	}
190 
191 	/*
192 	 * NB: The null xform needs a non-zero blocksize to keep the
193 	 *      crypto code happy but if we use it to set ivlen then
194 	 *      the ESP header will be processed incorrectly.  The
195 	 *      compromise is to force it to zero here.
196 	 */
197 	sav->ivlen = (txform == &enc_xform_null ? 0 : txform->blocksize);
198 	sav->iv = (caddr_t) malloc(sav->ivlen, M_XDATA, M_WAITOK);
199 	if (sav->iv == NULL) {
200 		DPRINTF(("%s: no memory for IV\n", __func__));
201 		return EINVAL;
202 	}
203 	key_randomfill(sav->iv, sav->ivlen);	/*XXX*/
204 
205 	/*
206 	 * Setup AH-related state.
207 	 */
208 	if (sav->alg_auth != 0) {
209 		error = ah_init0(sav, xsp, &cria);
210 		if (error)
211 			return error;
212 	}
213 
214 	/* NB: override anything set in ah_init0 */
215 	sav->tdb_xform = xsp;
216 	sav->tdb_encalgxform = txform;
217 
218 	/* Initialize crypto session. */
219 	bzero(&crie, sizeof (crie));
220 	crie.cri_alg = sav->tdb_encalgxform->type;
221 	crie.cri_klen = _KEYBITS(sav->key_enc);
222 	crie.cri_key = sav->key_enc->key_data;
223 	/* XXX Rounds ? */
224 
225 	if (sav->tdb_authalgxform && sav->tdb_encalgxform) {
226 		/* init both auth & enc */
227 		crie.cri_next = &cria;
228 		error = crypto_newsession(&sav->tdb_cryptoid,
229 					  &crie, V_crypto_support);
230 	} else if (sav->tdb_encalgxform) {
231 		error = crypto_newsession(&sav->tdb_cryptoid,
232 					  &crie, V_crypto_support);
233 	} else if (sav->tdb_authalgxform) {
234 		error = crypto_newsession(&sav->tdb_cryptoid,
235 					  &cria, V_crypto_support);
236 	} else {
237 		/* XXX cannot happen? */
238 		DPRINTF(("%s: no encoding OR authentication xform!\n",
239 			__func__));
240 		error = EINVAL;
241 	}
242 	return error;
243 }
244 
245 /*
246  * Paranoia.
247  */
248 static int
249 esp_zeroize(struct secasvar *sav)
250 {
251 	/* NB: ah_zerorize free's the crypto session state */
252 	int error = ah_zeroize(sav);
253 
254 	if (sav->key_enc)
255 		bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
256 	if (sav->iv) {
257 		free(sav->iv, M_XDATA);
258 		sav->iv = NULL;
259 	}
260 	sav->tdb_encalgxform = NULL;
261 	sav->tdb_xform = NULL;
262 	return error;
263 }
264 
265 /*
266  * ESP input processing, called (eventually) through the protocol switch.
267  */
268 static int
269 esp_input(struct mbuf *m, struct secasvar *sav, int skip, int protoff)
270 {
271 	struct auth_hash *esph;
272 	struct enc_xform *espx;
273 	struct tdb_ident *tdbi;
274 	struct tdb_crypto *tc;
275 	int plen, alen, hlen;
276 	struct m_tag *mtag;
277 	struct newesp *esp;
278 
279 	struct cryptodesc *crde;
280 	struct cryptop *crp;
281 
282 	IPSEC_ASSERT(sav != NULL, ("null SA"));
283 	IPSEC_ASSERT(sav->tdb_encalgxform != NULL, ("null encoding xform"));
284 
285 	/* Valid IP Packet length ? */
286 	if ( (skip&3) || (m->m_pkthdr.len&3) ){
287 		DPRINTF(("%s: misaligned packet, skip %u pkt len %u",
288 				__func__, skip, m->m_pkthdr.len));
289 		V_espstat.esps_badilen++;
290 		m_freem(m);
291 		return EINVAL;
292 	}
293 
294 	/* XXX don't pullup, just copy header */
295 	IP6_EXTHDR_GET(esp, struct newesp *, m, skip, sizeof (struct newesp));
296 
297 	esph = sav->tdb_authalgxform;
298 	espx = sav->tdb_encalgxform;
299 
300 	/* Determine the ESP header length */
301 	if (sav->flags & SADB_X_EXT_OLD)
302 		hlen = sizeof (struct esp) + sav->ivlen;
303 	else
304 		hlen = sizeof (struct newesp) + sav->ivlen;
305 	/* Authenticator hash size */
306 	if (esph != NULL) {
307 		switch (esph->type) {
308 		case CRYPTO_SHA2_256_HMAC:
309 		case CRYPTO_SHA2_384_HMAC:
310 		case CRYPTO_SHA2_512_HMAC:
311 			alen = esph->hashsize/2;
312 			break;
313 		default:
314 			alen = AH_HMAC_HASHLEN;
315 			break;
316 		}
317 	}else
318 		alen = 0;
319 
320 	/*
321 	 * Verify payload length is multiple of encryption algorithm
322 	 * block size.
323 	 *
324 	 * NB: This works for the null algorithm because the blocksize
325 	 *     is 4 and all packets must be 4-byte aligned regardless
326 	 *     of the algorithm.
327 	 */
328 	plen = m->m_pkthdr.len - (skip + hlen + alen);
329 	if ((plen & (espx->blocksize - 1)) || (plen <= 0)) {
330 		DPRINTF(("%s: payload of %d octets not a multiple of %d octets,"
331 		    "  SA %s/%08lx\n", __func__,
332 		    plen, espx->blocksize,
333 		    ipsec_address(&sav->sah->saidx.dst),
334 		    (u_long) ntohl(sav->spi)));
335 		V_espstat.esps_badilen++;
336 		m_freem(m);
337 		return EINVAL;
338 	}
339 
340 	/*
341 	 * Check sequence number.
342 	 */
343 	if (esph && sav->replay && !ipsec_chkreplay(ntohl(esp->esp_seq), sav)) {
344 		DPRINTF(("%s: packet replay check for %s\n", __func__,
345 		    ipsec_logsastr(sav)));	/*XXX*/
346 		V_espstat.esps_replay++;
347 		m_freem(m);
348 		return ENOBUFS;		/*XXX*/
349 	}
350 
351 	/* Update the counters */
352 	V_espstat.esps_ibytes += m->m_pkthdr.len - (skip + hlen + alen);
353 
354 	/* Find out if we've already done crypto */
355 	for (mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_CRYPTO_DONE, NULL);
356 	     mtag != NULL;
357 	     mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_CRYPTO_DONE, mtag)) {
358 		tdbi = (struct tdb_ident *) (mtag + 1);
359 		if (tdbi->proto == sav->sah->saidx.proto &&
360 		    tdbi->spi == sav->spi &&
361 		    !bcmp(&tdbi->dst, &sav->sah->saidx.dst,
362 			  sizeof(union sockaddr_union)))
363 			break;
364 	}
365 
366 	/* Get crypto descriptors */
367 	crp = crypto_getreq(esph && espx ? 2 : 1);
368 	if (crp == NULL) {
369 		DPRINTF(("%s: failed to acquire crypto descriptors\n",
370 			__func__));
371 		V_espstat.esps_crypto++;
372 		m_freem(m);
373 		return ENOBUFS;
374 	}
375 
376 	/* Get IPsec-specific opaque pointer */
377 	if (esph == NULL || mtag != NULL)
378 		tc = (struct tdb_crypto *) malloc(sizeof(struct tdb_crypto),
379 		    M_XDATA, M_NOWAIT|M_ZERO);
380 	else
381 		tc = (struct tdb_crypto *) malloc(sizeof(struct tdb_crypto) + alen,
382 		    M_XDATA, M_NOWAIT|M_ZERO);
383 	if (tc == NULL) {
384 		crypto_freereq(crp);
385 		DPRINTF(("%s: failed to allocate tdb_crypto\n", __func__));
386 		V_espstat.esps_crypto++;
387 		m_freem(m);
388 		return ENOBUFS;
389 	}
390 
391 	tc->tc_ptr = (caddr_t) mtag;
392 
393 	if (esph) {
394 		struct cryptodesc *crda = crp->crp_desc;
395 
396 		IPSEC_ASSERT(crda != NULL, ("null ah crypto descriptor"));
397 
398 		/* Authentication descriptor */
399 		crda->crd_skip = skip;
400 		crda->crd_len = m->m_pkthdr.len - (skip + alen);
401 		crda->crd_inject = m->m_pkthdr.len - alen;
402 
403 		crda->crd_alg = esph->type;
404 		crda->crd_key = sav->key_auth->key_data;
405 		crda->crd_klen = _KEYBITS(sav->key_auth);
406 
407 		/* Copy the authenticator */
408 		if (mtag == NULL)
409 			m_copydata(m, m->m_pkthdr.len - alen, alen,
410 				   (caddr_t) (tc + 1));
411 
412 		/* Chain authentication request */
413 		crde = crda->crd_next;
414 	} else {
415 		crde = crp->crp_desc;
416 	}
417 
418 	/* Crypto operation descriptor */
419 	crp->crp_ilen = m->m_pkthdr.len; /* Total input length */
420 	crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
421 	crp->crp_buf = (caddr_t) m;
422 	crp->crp_callback = esp_input_cb;
423 	crp->crp_sid = sav->tdb_cryptoid;
424 	crp->crp_opaque = (caddr_t) tc;
425 
426 	/* These are passed as-is to the callback */
427 	tc->tc_spi = sav->spi;
428 	tc->tc_dst = sav->sah->saidx.dst;
429 	tc->tc_proto = sav->sah->saidx.proto;
430 	tc->tc_protoff = protoff;
431 	tc->tc_skip = skip;
432 
433 	/* Decryption descriptor */
434 	if (espx) {
435 		IPSEC_ASSERT(crde != NULL, ("null esp crypto descriptor"));
436 		crde->crd_skip = skip + hlen;
437 		crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
438 		crde->crd_inject = skip + hlen - sav->ivlen;
439 
440 		crde->crd_alg = espx->type;
441 		crde->crd_key = sav->key_enc->key_data;
442 		crde->crd_klen = _KEYBITS(sav->key_enc);
443 		/* XXX Rounds ? */
444 	}
445 
446 	if (mtag == NULL)
447 		return crypto_dispatch(crp);
448 	else
449 		return esp_input_cb(crp);
450 }
451 
452 #ifdef INET6
453 #define	IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff, mtag) do {		     \
454 	if (saidx->dst.sa.sa_family == AF_INET6) {			     \
455 		error = ipsec6_common_input_cb(m, sav, skip, protoff, mtag); \
456 	} else {							     \
457 		error = ipsec4_common_input_cb(m, sav, skip, protoff, mtag); \
458 	}								     \
459 } while (0)
460 #else
461 #define	IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff, mtag)		     \
462 	(error = ipsec4_common_input_cb(m, sav, skip, protoff, mtag))
463 #endif
464 
465 /*
466  * ESP input callback from the crypto driver.
467  */
468 static int
469 esp_input_cb(struct cryptop *crp)
470 {
471 	u_int8_t lastthree[3], aalg[AH_HMAC_MAXHASHLEN];
472 	int hlen, skip, protoff, error, alen;
473 	struct mbuf *m;
474 	struct cryptodesc *crd;
475 	struct auth_hash *esph;
476 	struct enc_xform *espx;
477 	struct tdb_crypto *tc;
478 	struct m_tag *mtag;
479 	struct secasvar *sav;
480 	struct secasindex *saidx;
481 	caddr_t ptr;
482 
483 	crd = crp->crp_desc;
484 	IPSEC_ASSERT(crd != NULL, ("null crypto descriptor!"));
485 
486 	tc = (struct tdb_crypto *) crp->crp_opaque;
487 	IPSEC_ASSERT(tc != NULL, ("null opaque crypto data area!"));
488 	skip = tc->tc_skip;
489 	protoff = tc->tc_protoff;
490 	mtag = (struct m_tag *) tc->tc_ptr;
491 	m = (struct mbuf *) crp->crp_buf;
492 
493 	sav = KEY_ALLOCSA(&tc->tc_dst, tc->tc_proto, tc->tc_spi);
494 	if (sav == NULL) {
495 		V_espstat.esps_notdb++;
496 		DPRINTF(("%s: SA gone during crypto (SA %s/%08lx proto %u)\n",
497 		    __func__, ipsec_address(&tc->tc_dst),
498 		    (u_long) ntohl(tc->tc_spi), tc->tc_proto));
499 		error = ENOBUFS;		/*XXX*/
500 		goto bad;
501 	}
502 
503 	saidx = &sav->sah->saidx;
504 	IPSEC_ASSERT(saidx->dst.sa.sa_family == AF_INET ||
505 		saidx->dst.sa.sa_family == AF_INET6,
506 		("unexpected protocol family %u", saidx->dst.sa.sa_family));
507 
508 	esph = sav->tdb_authalgxform;
509 	espx = sav->tdb_encalgxform;
510 
511 	/* Check for crypto errors */
512 	if (crp->crp_etype) {
513 		/* Reset the session ID */
514 		if (sav->tdb_cryptoid != 0)
515 			sav->tdb_cryptoid = crp->crp_sid;
516 
517 		if (crp->crp_etype == EAGAIN) {
518 			KEY_FREESAV(&sav);
519 			error = crypto_dispatch(crp);
520 			return error;
521 		}
522 
523 		V_espstat.esps_noxform++;
524 		DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
525 		error = crp->crp_etype;
526 		goto bad;
527 	}
528 
529 	/* Shouldn't happen... */
530 	if (m == NULL) {
531 		V_espstat.esps_crypto++;
532 		DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
533 		error = EINVAL;
534 		goto bad;
535 	}
536 	V_espstat.esps_hist[sav->alg_enc]++;
537 
538 	/* If authentication was performed, check now. */
539 	if (esph != NULL) {
540 		switch (esph->type) {
541 		case CRYPTO_SHA2_256_HMAC:
542 		case CRYPTO_SHA2_384_HMAC:
543 		case CRYPTO_SHA2_512_HMAC:
544 			alen = esph->hashsize/2;
545 			break;
546 		default:
547 			alen = AH_HMAC_HASHLEN;
548 			break;
549 		}
550 		/*
551 		 * If we have a tag, it means an IPsec-aware NIC did
552 		 * the verification for us.  Otherwise we need to
553 		 * check the authentication calculation.
554 		 */
555 		V_ahstat.ahs_hist[sav->alg_auth]++;
556 		if (mtag == NULL) {
557 			/* Copy the authenticator from the packet */
558 			m_copydata(m, m->m_pkthdr.len - alen,
559 				alen, aalg);
560 
561 			ptr = (caddr_t) (tc + 1);
562 
563 			/* Verify authenticator */
564 			if (bcmp(ptr, aalg, alen) != 0) {
565 				DPRINTF(("%s: "
566 		    "authentication hash mismatch for packet in SA %s/%08lx\n",
567 				    __func__,
568 				    ipsec_address(&saidx->dst),
569 				    (u_long) ntohl(sav->spi)));
570 				V_espstat.esps_badauth++;
571 				error = EACCES;
572 				goto bad;
573 			}
574 		}
575 
576 		/* Remove trailing authenticator */
577 		m_adj(m, -alen);
578 	}
579 
580 	/* Release the crypto descriptors */
581 	free(tc, M_XDATA), tc = NULL;
582 	crypto_freereq(crp), crp = NULL;
583 
584 	/*
585 	 * Packet is now decrypted.
586 	 */
587 	m->m_flags |= M_DECRYPTED;
588 
589 	/*
590 	 * Update replay sequence number, if appropriate.
591 	 */
592 	if (sav->replay) {
593 		u_int32_t seq;
594 
595 		m_copydata(m, skip + offsetof(struct newesp, esp_seq),
596 			   sizeof (seq), (caddr_t) &seq);
597 		if (ipsec_updatereplay(ntohl(seq), sav)) {
598 			DPRINTF(("%s: packet replay check for %s\n", __func__,
599 			    ipsec_logsastr(sav)));
600 			V_espstat.esps_replay++;
601 			error = ENOBUFS;
602 			goto bad;
603 		}
604 	}
605 
606 	/* Determine the ESP header length */
607 	if (sav->flags & SADB_X_EXT_OLD)
608 		hlen = sizeof (struct esp) + sav->ivlen;
609 	else
610 		hlen = sizeof (struct newesp) + sav->ivlen;
611 
612 	/* Remove the ESP header and IV from the mbuf. */
613 	error = m_striphdr(m, skip, hlen);
614 	if (error) {
615 		V_espstat.esps_hdrops++;
616 		DPRINTF(("%s: bad mbuf chain, SA %s/%08lx\n", __func__,
617 		    ipsec_address(&sav->sah->saidx.dst),
618 		    (u_long) ntohl(sav->spi)));
619 		goto bad;
620 	}
621 
622 	/* Save the last three bytes of decrypted data */
623 	m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
624 
625 	/* Verify pad length */
626 	if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
627 		V_espstat.esps_badilen++;
628 		DPRINTF(("%s: invalid padding length %d for %u byte packet "
629 			"in SA %s/%08lx\n", __func__,
630 			 lastthree[1], m->m_pkthdr.len - skip,
631 			 ipsec_address(&sav->sah->saidx.dst),
632 			 (u_long) ntohl(sav->spi)));
633 		error = EINVAL;
634 		goto bad;
635 	}
636 
637 	/* Verify correct decryption by checking the last padding bytes */
638 	if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
639 		if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
640 			V_espstat.esps_badenc++;
641 			DPRINTF(("%s: decryption failed for packet in "
642 				"SA %s/%08lx\n", __func__,
643 				ipsec_address(&sav->sah->saidx.dst),
644 				(u_long) ntohl(sav->spi)));
645 			error = EINVAL;
646 			goto bad;
647 		}
648 	}
649 
650 	/* Trim the mbuf chain to remove trailing authenticator and padding */
651 	m_adj(m, -(lastthree[1] + 2));
652 
653 	/* Restore the Next Protocol field */
654 	m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
655 
656 	IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff, mtag);
657 
658 	KEY_FREESAV(&sav);
659 	return error;
660 bad:
661 	if (sav)
662 		KEY_FREESAV(&sav);
663 	if (m != NULL)
664 		m_freem(m);
665 	if (tc != NULL)
666 		free(tc, M_XDATA);
667 	if (crp != NULL)
668 		crypto_freereq(crp);
669 	return error;
670 }
671 
672 /*
673  * ESP output routine, called by ipsec[46]_process_packet().
674  */
675 static int
676 esp_output(
677 	struct mbuf *m,
678 	struct ipsecrequest *isr,
679 	struct mbuf **mp,
680 	int skip,
681 	int protoff
682 )
683 {
684 	struct enc_xform *espx;
685 	struct auth_hash *esph;
686 	int hlen, rlen, plen, padding, blks, alen, i, roff;
687 	struct mbuf *mo = (struct mbuf *) NULL;
688 	struct tdb_crypto *tc;
689 	struct secasvar *sav;
690 	struct secasindex *saidx;
691 	unsigned char *pad;
692 	u_int8_t prot;
693 	int error, maxpacketsize;
694 
695 	struct cryptodesc *crde = NULL, *crda = NULL;
696 	struct cryptop *crp;
697 
698 	sav = isr->sav;
699 	IPSEC_ASSERT(sav != NULL, ("null SA"));
700 	esph = sav->tdb_authalgxform;
701 	espx = sav->tdb_encalgxform;
702 	IPSEC_ASSERT(espx != NULL, ("null encoding xform"));
703 
704 	if (sav->flags & SADB_X_EXT_OLD)
705 		hlen = sizeof (struct esp) + sav->ivlen;
706 	else
707 		hlen = sizeof (struct newesp) + sav->ivlen;
708 
709 	rlen = m->m_pkthdr.len - skip;	/* Raw payload length. */
710 	/*
711 	 * NB: The null encoding transform has a blocksize of 4
712 	 *     so that headers are properly aligned.
713 	 */
714 	blks = espx->blocksize;		/* IV blocksize */
715 
716 	/* XXX clamp padding length a la KAME??? */
717 	padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
718 	plen = rlen + padding;		/* Padded payload length. */
719 
720 	if (esph)
721 		switch (esph->type) {
722 		case CRYPTO_SHA2_256_HMAC:
723 		case CRYPTO_SHA2_384_HMAC:
724 		case CRYPTO_SHA2_512_HMAC:
725 			alen = esph->hashsize/2;
726 			break;
727 		default:
728 		alen = AH_HMAC_HASHLEN;
729 			break;
730 		}
731 	else
732 		alen = 0;
733 
734 	V_espstat.esps_output++;
735 
736 	saidx = &sav->sah->saidx;
737 	/* Check for maximum packet size violations. */
738 	switch (saidx->dst.sa.sa_family) {
739 #ifdef INET
740 	case AF_INET:
741 		maxpacketsize = IP_MAXPACKET;
742 		break;
743 #endif /* INET */
744 #ifdef INET6
745 	case AF_INET6:
746 		maxpacketsize = IPV6_MAXPACKET;
747 		break;
748 #endif /* INET6 */
749 	default:
750 		DPRINTF(("%s: unknown/unsupported protocol "
751 		    "family %d, SA %s/%08lx\n", __func__,
752 		    saidx->dst.sa.sa_family, ipsec_address(&saidx->dst),
753 		    (u_long) ntohl(sav->spi)));
754 		V_espstat.esps_nopf++;
755 		error = EPFNOSUPPORT;
756 		goto bad;
757 	}
758 	if (skip + hlen + rlen + padding + alen > maxpacketsize) {
759 		DPRINTF(("%s: packet in SA %s/%08lx got too big "
760 		    "(len %u, max len %u)\n", __func__,
761 		    ipsec_address(&saidx->dst), (u_long) ntohl(sav->spi),
762 		    skip + hlen + rlen + padding + alen, maxpacketsize));
763 		V_espstat.esps_toobig++;
764 		error = EMSGSIZE;
765 		goto bad;
766 	}
767 
768 	/* Update the counters. */
769 	V_espstat.esps_obytes += m->m_pkthdr.len - skip;
770 
771 	m = m_unshare(m, M_NOWAIT);
772 	if (m == NULL) {
773 		DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
774 		    ipsec_address(&saidx->dst), (u_long) ntohl(sav->spi)));
775 		V_espstat.esps_hdrops++;
776 		error = ENOBUFS;
777 		goto bad;
778 	}
779 
780 	/* Inject ESP header. */
781 	mo = m_makespace(m, skip, hlen, &roff);
782 	if (mo == NULL) {
783 		DPRINTF(("%s: %u byte ESP hdr inject failed for SA %s/%08lx\n",
784 		    __func__, hlen, ipsec_address(&saidx->dst),
785 		    (u_long) ntohl(sav->spi)));
786 		V_espstat.esps_hdrops++;		/* XXX diffs from openbsd */
787 		error = ENOBUFS;
788 		goto bad;
789 	}
790 
791 	/* Initialize ESP header. */
792 	bcopy((caddr_t) &sav->spi, mtod(mo, caddr_t) + roff, sizeof(u_int32_t));
793 	if (sav->replay) {
794 		u_int32_t replay;
795 
796 #ifdef REGRESSION
797 		/* Emulate replay attack when ipsec_replay is TRUE. */
798 		if (!V_ipsec_replay)
799 #endif
800 			sav->replay->count++;
801 		replay = htonl(sav->replay->count);
802 		bcopy((caddr_t) &replay,
803 		    mtod(mo, caddr_t) + roff + sizeof(u_int32_t),
804 		    sizeof(u_int32_t));
805 	}
806 
807 	/*
808 	 * Add padding -- better to do it ourselves than use the crypto engine,
809 	 * although if/when we support compression, we'd have to do that.
810 	 */
811 	pad = (u_char *) m_pad(m, padding + alen);
812 	if (pad == NULL) {
813 		DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
814 		    ipsec_address(&saidx->dst), (u_long) ntohl(sav->spi)));
815 		m = NULL;		/* NB: free'd by m_pad */
816 		error = ENOBUFS;
817 		goto bad;
818 	}
819 
820 	/*
821 	 * Add padding: random, zero, or self-describing.
822 	 * XXX catch unexpected setting
823 	 */
824 	switch (sav->flags & SADB_X_EXT_PMASK) {
825 	case SADB_X_EXT_PRAND:
826 		(void) read_random(pad, padding - 2);
827 		break;
828 	case SADB_X_EXT_PZERO:
829 		bzero(pad, padding - 2);
830 		break;
831 	case SADB_X_EXT_PSEQ:
832 		for (i = 0; i < padding - 2; i++)
833 			pad[i] = i+1;
834 		break;
835 	}
836 
837 	/* Fix padding length and Next Protocol in padding itself. */
838 	pad[padding - 2] = padding - 2;
839 	m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
840 
841 	/* Fix Next Protocol in IPv4/IPv6 header. */
842 	prot = IPPROTO_ESP;
843 	m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
844 
845 	/* Get crypto descriptors. */
846 	crp = crypto_getreq(esph && espx ? 2 : 1);
847 	if (crp == NULL) {
848 		DPRINTF(("%s: failed to acquire crypto descriptors\n",
849 			__func__));
850 		V_espstat.esps_crypto++;
851 		error = ENOBUFS;
852 		goto bad;
853 	}
854 
855 	if (espx) {
856 		crde = crp->crp_desc;
857 		crda = crde->crd_next;
858 
859 		/* Encryption descriptor. */
860 		crde->crd_skip = skip + hlen;
861 		crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
862 		crde->crd_flags = CRD_F_ENCRYPT;
863 		crde->crd_inject = skip + hlen - sav->ivlen;
864 
865 		/* Encryption operation. */
866 		crde->crd_alg = espx->type;
867 		crde->crd_key = sav->key_enc->key_data;
868 		crde->crd_klen = _KEYBITS(sav->key_enc);
869 		/* XXX Rounds ? */
870 	} else
871 		crda = crp->crp_desc;
872 
873 	/* IPsec-specific opaque crypto info. */
874 	tc = (struct tdb_crypto *) malloc(sizeof(struct tdb_crypto),
875 		M_XDATA, M_NOWAIT|M_ZERO);
876 	if (tc == NULL) {
877 		crypto_freereq(crp);
878 		DPRINTF(("%s: failed to allocate tdb_crypto\n", __func__));
879 		V_espstat.esps_crypto++;
880 		error = ENOBUFS;
881 		goto bad;
882 	}
883 
884 	/* Callback parameters */
885 	tc->tc_isr = isr;
886 	tc->tc_spi = sav->spi;
887 	tc->tc_dst = saidx->dst;
888 	tc->tc_proto = saidx->proto;
889 
890 	/* Crypto operation descriptor. */
891 	crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
892 	crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
893 	crp->crp_buf = (caddr_t) m;
894 	crp->crp_callback = esp_output_cb;
895 	crp->crp_opaque = (caddr_t) tc;
896 	crp->crp_sid = sav->tdb_cryptoid;
897 
898 	if (esph) {
899 		/* Authentication descriptor. */
900 		crda->crd_skip = skip;
901 		crda->crd_len = m->m_pkthdr.len - (skip + alen);
902 		crda->crd_inject = m->m_pkthdr.len - alen;
903 
904 		/* Authentication operation. */
905 		crda->crd_alg = esph->type;
906 		crda->crd_key = sav->key_auth->key_data;
907 		crda->crd_klen = _KEYBITS(sav->key_auth);
908 	}
909 
910 	return crypto_dispatch(crp);
911 bad:
912 	if (m)
913 		m_freem(m);
914 	return (error);
915 }
916 
917 /*
918  * ESP output callback from the crypto driver.
919  */
920 static int
921 esp_output_cb(struct cryptop *crp)
922 {
923 	struct tdb_crypto *tc;
924 	struct ipsecrequest *isr;
925 	struct secasvar *sav;
926 	struct mbuf *m;
927 	int err, error;
928 
929 	tc = (struct tdb_crypto *) crp->crp_opaque;
930 	IPSEC_ASSERT(tc != NULL, ("null opaque data area!"));
931 	m = (struct mbuf *) crp->crp_buf;
932 
933 	isr = tc->tc_isr;
934 	IPSECREQUEST_LOCK(isr);
935 	sav = KEY_ALLOCSA(&tc->tc_dst, tc->tc_proto, tc->tc_spi);
936 	if (sav == NULL) {
937 		V_espstat.esps_notdb++;
938 		DPRINTF(("%s: SA gone during crypto (SA %s/%08lx proto %u)\n",
939 		    __func__, ipsec_address(&tc->tc_dst),
940 		    (u_long) ntohl(tc->tc_spi), tc->tc_proto));
941 		error = ENOBUFS;		/*XXX*/
942 		goto bad;
943 	}
944 	IPSEC_ASSERT(isr->sav == sav,
945 		("SA changed was %p now %p\n", isr->sav, sav));
946 
947 	/* Check for crypto errors. */
948 	if (crp->crp_etype) {
949 		/* Reset session ID. */
950 		if (sav->tdb_cryptoid != 0)
951 			sav->tdb_cryptoid = crp->crp_sid;
952 
953 		if (crp->crp_etype == EAGAIN) {
954 			KEY_FREESAV(&sav);
955 			IPSECREQUEST_UNLOCK(isr);
956 			error = crypto_dispatch(crp);
957 			return error;
958 		}
959 
960 		V_espstat.esps_noxform++;
961 		DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
962 		error = crp->crp_etype;
963 		goto bad;
964 	}
965 
966 	/* Shouldn't happen... */
967 	if (m == NULL) {
968 		V_espstat.esps_crypto++;
969 		DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
970 		error = EINVAL;
971 		goto bad;
972 	}
973 	V_espstat.esps_hist[sav->alg_enc]++;
974 	if (sav->tdb_authalgxform != NULL)
975 		V_ahstat.ahs_hist[sav->alg_auth]++;
976 
977 	/* Release crypto descriptors. */
978 	free(tc, M_XDATA);
979 	crypto_freereq(crp);
980 
981 #ifdef REGRESSION
982 	/* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
983 	if (V_ipsec_integrity) {
984 		static unsigned char ipseczeroes[AH_HMAC_MAXHASHLEN];
985 		struct auth_hash *esph;
986 
987 		/*
988 		 * Corrupt HMAC if we want to test integrity verification of
989 		 * the other side.
990 		 */
991 		esph = sav->tdb_authalgxform;
992 		if (esph !=  NULL) {
993 			int alen;
994 
995 			switch (esph->type) {
996 			case CRYPTO_SHA2_256_HMAC:
997 			case CRYPTO_SHA2_384_HMAC:
998 			case CRYPTO_SHA2_512_HMAC:
999 				alen = esph->hashsize/2;
1000 				break;
1001 			default:
1002 				alen = AH_HMAC_HASHLEN;
1003 				break;
1004 			}
1005 			m_copyback(m, m->m_pkthdr.len - alen,
1006 			    alen, ipseczeroes);
1007 		}
1008 	}
1009 #endif
1010 
1011 	/* NB: m is reclaimed by ipsec_process_done. */
1012 	err = ipsec_process_done(m, isr);
1013 	KEY_FREESAV(&sav);
1014 	IPSECREQUEST_UNLOCK(isr);
1015 	return err;
1016 bad:
1017 	if (sav)
1018 		KEY_FREESAV(&sav);
1019 	IPSECREQUEST_UNLOCK(isr);
1020 	if (m)
1021 		m_freem(m);
1022 	free(tc, M_XDATA);
1023 	crypto_freereq(crp);
1024 	return error;
1025 }
1026 
1027 static struct xformsw esp_xformsw = {
1028 	XF_ESP,		XFT_CONF|XFT_AUTH,	"IPsec ESP",
1029 	esp_init,	esp_zeroize,		esp_input,
1030 	esp_output
1031 };
1032 
1033 static void
1034 esp_attach(void)
1035 {
1036 #define	MAXIV(xform)					\
1037 	if (xform.blocksize > V_esp_max_ivlen)		\
1038 		V_esp_max_ivlen = xform.blocksize	\
1039 
1040 	MAXIV(enc_xform_des);		/* SADB_EALG_DESCBC */
1041 	MAXIV(enc_xform_3des);		/* SADB_EALG_3DESCBC */
1042 	MAXIV(enc_xform_rijndael128);	/* SADB_X_EALG_AES */
1043 	MAXIV(enc_xform_blf);		/* SADB_X_EALG_BLOWFISHCBC */
1044 	MAXIV(enc_xform_cast5);		/* SADB_X_EALG_CAST128CBC */
1045 	MAXIV(enc_xform_skipjack);	/* SADB_X_EALG_SKIPJACK */
1046 	MAXIV(enc_xform_null);		/* SADB_EALG_NULL */
1047 	MAXIV(enc_xform_camellia);	/* SADB_X_EALG_CAMELLIACBC */
1048 
1049 	xform_register(&esp_xformsw);
1050 #undef MAXIV
1051 }
1052 SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE, esp_attach, NULL);
1053