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