xref: /freebsd/sys/netipsec/xform_esp.c (revision 7bd6fde3)
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 
52 #include <netinet/in.h>
53 #include <netinet/in_systm.h>
54 #include <netinet/ip.h>
55 #include <netinet/ip_ecn.h>
56 #include <netinet/ip6.h>
57 
58 #include <net/route.h>
59 #include <netipsec/ipsec.h>
60 #include <netipsec/ah.h>
61 #include <netipsec/ah_var.h>
62 #include <netipsec/esp.h>
63 #include <netipsec/esp_var.h>
64 #include <netipsec/xform.h>
65 
66 #ifdef INET6
67 #include <netinet6/ip6_var.h>
68 #include <netipsec/ipsec6.h>
69 #include <netinet6/ip6_ecn.h>
70 #endif
71 
72 #include <netipsec/key.h>
73 #include <netipsec/key_debug.h>
74 
75 #include <opencrypto/cryptodev.h>
76 #include <opencrypto/xform.h>
77 
78 int	esp_enable = 1;
79 struct	espstat espstat;
80 
81 SYSCTL_DECL(_net_inet_esp);
82 SYSCTL_INT(_net_inet_esp, OID_AUTO,
83 	esp_enable,	CTLFLAG_RW,	&esp_enable,	0, "");
84 SYSCTL_STRUCT(_net_inet_esp, IPSECCTL_STATS,
85 	stats,		CTLFLAG_RD,	&espstat,	espstat, "");
86 
87 static	int esp_max_ivlen;		/* max iv length over all algorithms */
88 
89 static int esp_input_cb(struct cryptop *op);
90 static int esp_output_cb(struct cryptop *crp);
91 
92 /*
93  * NB: this is public for use by the PF_KEY support.
94  * NB: if you add support here; be sure to add code to esp_attach below!
95  */
96 struct enc_xform *
97 esp_algorithm_lookup(int alg)
98 {
99 	if (alg >= ESP_ALG_MAX)
100 		return NULL;
101 	switch (alg) {
102 	case SADB_EALG_DESCBC:
103 		return &enc_xform_des;
104 	case SADB_EALG_3DESCBC:
105 		return &enc_xform_3des;
106 	case SADB_X_EALG_AES:
107 		return &enc_xform_rijndael128;
108 	case SADB_X_EALG_BLOWFISHCBC:
109 		return &enc_xform_blf;
110 	case SADB_X_EALG_CAST128CBC:
111 		return &enc_xform_cast5;
112 	case SADB_X_EALG_SKIPJACK:
113 		return &enc_xform_skipjack;
114 	case SADB_EALG_NULL:
115 		return &enc_xform_null;
116 	}
117 	return NULL;
118 }
119 
120 size_t
121 esp_hdrsiz(struct secasvar *sav)
122 {
123 	size_t size;
124 
125 	if (sav != NULL) {
126 		/*XXX not right for null algorithm--does it matter??*/
127 		IPSEC_ASSERT(sav->tdb_encalgxform != NULL,
128 			("SA with null xform"));
129 		if (sav->flags & SADB_X_EXT_OLD)
130 			size = sizeof (struct esp);
131 		else
132 			size = sizeof (struct newesp);
133 		size += sav->tdb_encalgxform->blocksize + 9;
134 		/*XXX need alg check???*/
135 		if (sav->tdb_authalgxform != NULL && sav->replay)
136 			size += ah_hdrsiz(sav);
137 	} else {
138 		/*
139 		 *   base header size
140 		 * + max iv length for CBC mode
141 		 * + max pad length
142 		 * + sizeof (pad length field)
143 		 * + sizeof (next header field)
144 		 * + max icv supported.
145 		 */
146 		size = sizeof (struct newesp) + esp_max_ivlen + 9 + 16;
147 	}
148 	return size;
149 }
150 
151 /*
152  * esp_init() is called when an SPI is being set up.
153  */
154 static int
155 esp_init(struct secasvar *sav, struct xformsw *xsp)
156 {
157 	struct enc_xform *txform;
158 	struct cryptoini cria, crie;
159 	int keylen;
160 	int error;
161 
162 	txform = esp_algorithm_lookup(sav->alg_enc);
163 	if (txform == NULL) {
164 		DPRINTF(("%s: unsupported encryption algorithm %d\n",
165 			__func__, sav->alg_enc));
166 		return EINVAL;
167 	}
168 	if (sav->key_enc == NULL) {
169 		DPRINTF(("%s: no encoding key for %s algorithm\n",
170 			 __func__, txform->name));
171 		return EINVAL;
172 	}
173 	if ((sav->flags&(SADB_X_EXT_OLD|SADB_X_EXT_IV4B)) == SADB_X_EXT_IV4B) {
174 		DPRINTF(("%s: 4-byte IV not supported with protocol\n",
175 			__func__));
176 		return EINVAL;
177 	}
178 	keylen = _KEYLEN(sav->key_enc);
179 	if (txform->minkey > keylen || keylen > txform->maxkey) {
180 		DPRINTF(("%s: invalid key length %u, must be in the range "
181 			"[%u..%u] for algorithm %s\n", __func__,
182 			keylen, txform->minkey, txform->maxkey,
183 			txform->name));
184 		return EINVAL;
185 	}
186 
187 	/*
188 	 * NB: The null xform needs a non-zero blocksize to keep the
189 	 *      crypto code happy but if we use it to set ivlen then
190 	 *      the ESP header will be processed incorrectly.  The
191 	 *      compromise is to force it to zero here.
192 	 */
193 	sav->ivlen = (txform == &enc_xform_null ? 0 : txform->blocksize);
194 	sav->iv = (caddr_t) malloc(sav->ivlen, M_XDATA, M_WAITOK);
195 	if (sav->iv == NULL) {
196 		DPRINTF(("%s: no memory for IV\n", __func__));
197 		return EINVAL;
198 	}
199 	key_randomfill(sav->iv, sav->ivlen);	/*XXX*/
200 
201 	/*
202 	 * Setup AH-related state.
203 	 */
204 	if (sav->alg_auth != 0) {
205 		error = ah_init0(sav, xsp, &cria);
206 		if (error)
207 			return error;
208 	}
209 
210 	/* NB: override anything set in ah_init0 */
211 	sav->tdb_xform = xsp;
212 	sav->tdb_encalgxform = txform;
213 
214 	/* Initialize crypto session. */
215 	bzero(&crie, sizeof (crie));
216 	crie.cri_alg = sav->tdb_encalgxform->type;
217 	crie.cri_klen = _KEYBITS(sav->key_enc);
218 	crie.cri_key = sav->key_enc->key_data;
219 	/* XXX Rounds ? */
220 
221 	if (sav->tdb_authalgxform && sav->tdb_encalgxform) {
222 		/* init both auth & enc */
223 		crie.cri_next = &cria;
224 		error = crypto_newsession(&sav->tdb_cryptoid,
225 					  &crie, crypto_support);
226 	} else if (sav->tdb_encalgxform) {
227 		error = crypto_newsession(&sav->tdb_cryptoid,
228 					  &crie, crypto_support);
229 	} else if (sav->tdb_authalgxform) {
230 		error = crypto_newsession(&sav->tdb_cryptoid,
231 					  &cria, crypto_support);
232 	} else {
233 		/* XXX cannot happen? */
234 		DPRINTF(("%s: no encoding OR authentication xform!\n",
235 			__func__));
236 		error = EINVAL;
237 	}
238 	return error;
239 }
240 
241 /*
242  * Paranoia.
243  */
244 static int
245 esp_zeroize(struct secasvar *sav)
246 {
247 	/* NB: ah_zerorize free's the crypto session state */
248 	int error = ah_zeroize(sav);
249 
250 	if (sav->key_enc)
251 		bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
252 	if (sav->iv) {
253 		free(sav->iv, M_XDATA);
254 		sav->iv = NULL;
255 	}
256 	sav->tdb_encalgxform = NULL;
257 	sav->tdb_xform = NULL;
258 	return error;
259 }
260 
261 /*
262  * ESP input processing, called (eventually) through the protocol switch.
263  */
264 static int
265 esp_input(struct mbuf *m, struct secasvar *sav, int skip, int protoff)
266 {
267 	struct auth_hash *esph;
268 	struct enc_xform *espx;
269 	struct tdb_ident *tdbi;
270 	struct tdb_crypto *tc;
271 	int plen, alen, hlen;
272 	struct m_tag *mtag;
273 	struct newesp *esp;
274 
275 	struct cryptodesc *crde;
276 	struct cryptop *crp;
277 
278 	IPSEC_SPLASSERT_SOFTNET(__func__);
279 
280 	IPSEC_ASSERT(sav != NULL, ("null SA"));
281 	IPSEC_ASSERT(sav->tdb_encalgxform != NULL, ("null encoding xform"));
282 	IPSEC_ASSERT((skip&3) == 0 && (m->m_pkthdr.len&3) == 0,
283 		("misaligned packet, skip %u pkt len %u",
284 			skip, m->m_pkthdr.len));
285 
286 	/* XXX don't pullup, just copy header */
287 	IP6_EXTHDR_GET(esp, struct newesp *, m, skip, sizeof (struct newesp));
288 
289 	esph = sav->tdb_authalgxform;
290 	espx = sav->tdb_encalgxform;
291 
292 	/* Determine the ESP header length */
293 	if (sav->flags & SADB_X_EXT_OLD)
294 		hlen = sizeof (struct esp) + sav->ivlen;
295 	else
296 		hlen = sizeof (struct newesp) + sav->ivlen;
297 	/* Authenticator hash size */
298 	alen = esph ? AH_HMAC_HASHLEN : 0;
299 
300 	/*
301 	 * Verify payload length is multiple of encryption algorithm
302 	 * block size.
303 	 *
304 	 * NB: This works for the null algorithm because the blocksize
305 	 *     is 4 and all packets must be 4-byte aligned regardless
306 	 *     of the algorithm.
307 	 */
308 	plen = m->m_pkthdr.len - (skip + hlen + alen);
309 	if ((plen & (espx->blocksize - 1)) || (plen <= 0)) {
310 		DPRINTF(("%s: payload of %d octets not a multiple of %d octets,"
311 		    "  SA %s/%08lx\n", __func__,
312 		    plen, espx->blocksize,
313 		    ipsec_address(&sav->sah->saidx.dst),
314 		    (u_long) ntohl(sav->spi)));
315 		espstat.esps_badilen++;
316 		m_freem(m);
317 		return EINVAL;
318 	}
319 
320 	/*
321 	 * Check sequence number.
322 	 */
323 	if (esph && sav->replay && !ipsec_chkreplay(ntohl(esp->esp_seq), sav)) {
324 		DPRINTF(("%s: packet replay check for %s\n", __func__,
325 		    ipsec_logsastr(sav)));	/*XXX*/
326 		espstat.esps_replay++;
327 		m_freem(m);
328 		return ENOBUFS;		/*XXX*/
329 	}
330 
331 	/* Update the counters */
332 	espstat.esps_ibytes += m->m_pkthdr.len - (skip + hlen + alen);
333 
334 	/* Find out if we've already done crypto */
335 	for (mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_CRYPTO_DONE, NULL);
336 	     mtag != NULL;
337 	     mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_CRYPTO_DONE, mtag)) {
338 		tdbi = (struct tdb_ident *) (mtag + 1);
339 		if (tdbi->proto == sav->sah->saidx.proto &&
340 		    tdbi->spi == sav->spi &&
341 		    !bcmp(&tdbi->dst, &sav->sah->saidx.dst,
342 			  sizeof(union sockaddr_union)))
343 			break;
344 	}
345 
346 	/* Get crypto descriptors */
347 	crp = crypto_getreq(esph && espx ? 2 : 1);
348 	if (crp == NULL) {
349 		DPRINTF(("%s: failed to acquire crypto descriptors\n",
350 			__func__));
351 		espstat.esps_crypto++;
352 		m_freem(m);
353 		return ENOBUFS;
354 	}
355 
356 	/* Get IPsec-specific opaque pointer */
357 	if (esph == NULL || mtag != NULL)
358 		tc = (struct tdb_crypto *) malloc(sizeof(struct tdb_crypto),
359 		    M_XDATA, M_NOWAIT|M_ZERO);
360 	else
361 		tc = (struct tdb_crypto *) malloc(sizeof(struct tdb_crypto) + alen,
362 		    M_XDATA, M_NOWAIT|M_ZERO);
363 	if (tc == NULL) {
364 		crypto_freereq(crp);
365 		DPRINTF(("%s: failed to allocate tdb_crypto\n", __func__));
366 		espstat.esps_crypto++;
367 		m_freem(m);
368 		return ENOBUFS;
369 	}
370 
371 	tc->tc_ptr = (caddr_t) mtag;
372 
373 	if (esph) {
374 		struct cryptodesc *crda = crp->crp_desc;
375 
376 		IPSEC_ASSERT(crda != NULL, ("null ah crypto descriptor"));
377 
378 		/* Authentication descriptor */
379 		crda->crd_skip = skip;
380 		crda->crd_len = m->m_pkthdr.len - (skip + alen);
381 		crda->crd_inject = m->m_pkthdr.len - alen;
382 
383 		crda->crd_alg = esph->type;
384 		crda->crd_key = sav->key_auth->key_data;
385 		crda->crd_klen = _KEYBITS(sav->key_auth);
386 
387 		/* Copy the authenticator */
388 		if (mtag == NULL)
389 			m_copydata(m, m->m_pkthdr.len - alen, alen,
390 				   (caddr_t) (tc + 1));
391 
392 		/* Chain authentication request */
393 		crde = crda->crd_next;
394 	} else {
395 		crde = crp->crp_desc;
396 	}
397 
398 	/* Crypto operation descriptor */
399 	crp->crp_ilen = m->m_pkthdr.len; /* Total input length */
400 	crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
401 	crp->crp_buf = (caddr_t) m;
402 	crp->crp_callback = esp_input_cb;
403 	crp->crp_sid = sav->tdb_cryptoid;
404 	crp->crp_opaque = (caddr_t) tc;
405 
406 	/* These are passed as-is to the callback */
407 	tc->tc_spi = sav->spi;
408 	tc->tc_dst = sav->sah->saidx.dst;
409 	tc->tc_proto = sav->sah->saidx.proto;
410 	tc->tc_protoff = protoff;
411 	tc->tc_skip = skip;
412 
413 	/* Decryption descriptor */
414 	if (espx) {
415 		IPSEC_ASSERT(crde != NULL, ("null esp crypto descriptor"));
416 		crde->crd_skip = skip + hlen;
417 		crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
418 		crde->crd_inject = skip + hlen - sav->ivlen;
419 
420 		crde->crd_alg = espx->type;
421 		crde->crd_key = sav->key_enc->key_data;
422 		crde->crd_klen = _KEYBITS(sav->key_enc);
423 		/* XXX Rounds ? */
424 	}
425 
426 	if (mtag == NULL)
427 		return crypto_dispatch(crp);
428 	else
429 		return esp_input_cb(crp);
430 }
431 
432 #ifdef INET6
433 #define	IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff, mtag) do {		     \
434 	if (saidx->dst.sa.sa_family == AF_INET6) {			     \
435 		error = ipsec6_common_input_cb(m, sav, skip, protoff, mtag); \
436 	} else {							     \
437 		error = ipsec4_common_input_cb(m, sav, skip, protoff, mtag); \
438 	}								     \
439 } while (0)
440 #else
441 #define	IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff, mtag)		     \
442 	(error = ipsec4_common_input_cb(m, sav, skip, protoff, mtag))
443 #endif
444 
445 /*
446  * ESP input callback from the crypto driver.
447  */
448 static int
449 esp_input_cb(struct cryptop *crp)
450 {
451 	u_int8_t lastthree[3], aalg[AH_HMAC_HASHLEN];
452 	int hlen, skip, protoff, error;
453 	struct mbuf *m;
454 	struct cryptodesc *crd;
455 	struct auth_hash *esph;
456 	struct enc_xform *espx;
457 	struct tdb_crypto *tc;
458 	struct m_tag *mtag;
459 	struct secasvar *sav;
460 	struct secasindex *saidx;
461 	caddr_t ptr;
462 
463 	NET_LOCK_GIANT();
464 
465 	crd = crp->crp_desc;
466 	IPSEC_ASSERT(crd != NULL, ("null crypto descriptor!"));
467 
468 	tc = (struct tdb_crypto *) crp->crp_opaque;
469 	IPSEC_ASSERT(tc != NULL, ("null opaque crypto data area!"));
470 	skip = tc->tc_skip;
471 	protoff = tc->tc_protoff;
472 	mtag = (struct m_tag *) tc->tc_ptr;
473 	m = (struct mbuf *) crp->crp_buf;
474 
475 	sav = KEY_ALLOCSA(&tc->tc_dst, tc->tc_proto, tc->tc_spi);
476 	if (sav == NULL) {
477 		espstat.esps_notdb++;
478 		DPRINTF(("%s: SA gone during crypto (SA %s/%08lx proto %u)\n",
479 		    __func__, ipsec_address(&tc->tc_dst),
480 		    (u_long) ntohl(tc->tc_spi), tc->tc_proto));
481 		error = ENOBUFS;		/*XXX*/
482 		goto bad;
483 	}
484 
485 	saidx = &sav->sah->saidx;
486 	IPSEC_ASSERT(saidx->dst.sa.sa_family == AF_INET ||
487 		saidx->dst.sa.sa_family == AF_INET6,
488 		("unexpected protocol family %u", saidx->dst.sa.sa_family));
489 
490 	esph = sav->tdb_authalgxform;
491 	espx = sav->tdb_encalgxform;
492 
493 	/* Check for crypto errors */
494 	if (crp->crp_etype) {
495 		/* Reset the session ID */
496 		if (sav->tdb_cryptoid != 0)
497 			sav->tdb_cryptoid = crp->crp_sid;
498 
499 		if (crp->crp_etype == EAGAIN) {
500 			KEY_FREESAV(&sav);
501 			error = crypto_dispatch(crp);
502 			NET_UNLOCK_GIANT();
503 			return error;
504 		}
505 
506 		espstat.esps_noxform++;
507 		DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
508 		error = crp->crp_etype;
509 		goto bad;
510 	}
511 
512 	/* Shouldn't happen... */
513 	if (m == NULL) {
514 		espstat.esps_crypto++;
515 		DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
516 		error = EINVAL;
517 		goto bad;
518 	}
519 	espstat.esps_hist[sav->alg_enc]++;
520 
521 	/* If authentication was performed, check now. */
522 	if (esph != NULL) {
523 		/*
524 		 * If we have a tag, it means an IPsec-aware NIC did
525 		 * the verification for us.  Otherwise we need to
526 		 * check the authentication calculation.
527 		 */
528 		ahstat.ahs_hist[sav->alg_auth]++;
529 		if (mtag == NULL) {
530 			/* Copy the authenticator from the packet */
531 			m_copydata(m, m->m_pkthdr.len - AH_HMAC_HASHLEN,
532 				AH_HMAC_HASHLEN, aalg);
533 
534 			ptr = (caddr_t) (tc + 1);
535 
536 			/* Verify authenticator */
537 			if (bcmp(ptr, aalg, AH_HMAC_HASHLEN) != 0) {
538 				DPRINTF(("%s: "
539 		    "authentication hash mismatch for packet in SA %s/%08lx\n",
540 				    __func__,
541 				    ipsec_address(&saidx->dst),
542 				    (u_long) ntohl(sav->spi)));
543 				espstat.esps_badauth++;
544 				error = EACCES;
545 				goto bad;
546 			}
547 		}
548 
549 		/* Remove trailing authenticator */
550 		m_adj(m, -AH_HMAC_HASHLEN);
551 	}
552 
553 	/* Release the crypto descriptors */
554 	free(tc, M_XDATA), tc = NULL;
555 	crypto_freereq(crp), crp = NULL;
556 
557 	/*
558 	 * Packet is now decrypted.
559 	 */
560 	m->m_flags |= M_DECRYPTED;
561 
562 	/*
563 	 * Update replay sequence number, if appropriate.
564 	 */
565 	if (sav->replay) {
566 		u_int32_t seq;
567 
568 		m_copydata(m, skip + offsetof(struct newesp, esp_seq),
569 			   sizeof (seq), (caddr_t) &seq);
570 		if (ipsec_updatereplay(ntohl(seq), sav)) {
571 			DPRINTF(("%s: packet replay check for %s\n", __func__,
572 			    ipsec_logsastr(sav)));
573 			espstat.esps_replay++;
574 			error = ENOBUFS;
575 			goto bad;
576 		}
577 	}
578 
579 	/* Determine the ESP header length */
580 	if (sav->flags & SADB_X_EXT_OLD)
581 		hlen = sizeof (struct esp) + sav->ivlen;
582 	else
583 		hlen = sizeof (struct newesp) + sav->ivlen;
584 
585 	/* Remove the ESP header and IV from the mbuf. */
586 	error = m_striphdr(m, skip, hlen);
587 	if (error) {
588 		espstat.esps_hdrops++;
589 		DPRINTF(("%s: bad mbuf chain, SA %s/%08lx\n", __func__,
590 		    ipsec_address(&sav->sah->saidx.dst),
591 		    (u_long) ntohl(sav->spi)));
592 		goto bad;
593 	}
594 
595 	/* Save the last three bytes of decrypted data */
596 	m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
597 
598 	/* Verify pad length */
599 	if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
600 		espstat.esps_badilen++;
601 		DPRINTF(("%s: invalid padding length %d for %u byte packet "
602 			"in SA %s/%08lx\n", __func__,
603 			 lastthree[1], m->m_pkthdr.len - skip,
604 			 ipsec_address(&sav->sah->saidx.dst),
605 			 (u_long) ntohl(sav->spi)));
606 		error = EINVAL;
607 		goto bad;
608 	}
609 
610 	/* Verify correct decryption by checking the last padding bytes */
611 	if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
612 		if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
613 			espstat.esps_badenc++;
614 			DPRINTF(("%s: decryption failed for packet in "
615 				"SA %s/%08lx\n", __func__,
616 				ipsec_address(&sav->sah->saidx.dst),
617 				(u_long) ntohl(sav->spi)));
618 			error = EINVAL;
619 			goto bad;
620 		}
621 	}
622 
623 	/* Trim the mbuf chain to remove trailing authenticator and padding */
624 	m_adj(m, -(lastthree[1] + 2));
625 
626 	/* Restore the Next Protocol field */
627 	m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
628 
629 	IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff, mtag);
630 
631 	KEY_FREESAV(&sav);
632 	NET_UNLOCK_GIANT();
633 	return error;
634 bad:
635 	if (sav)
636 		KEY_FREESAV(&sav);
637 	if (m != NULL)
638 		m_freem(m);
639 	if (tc != NULL)
640 		free(tc, M_XDATA);
641 	if (crp != NULL)
642 		crypto_freereq(crp);
643 	NET_UNLOCK_GIANT();
644 	return error;
645 }
646 
647 /*
648  * ESP output routine, called by ipsec[46]_process_packet().
649  */
650 static int
651 esp_output(
652 	struct mbuf *m,
653 	struct ipsecrequest *isr,
654 	struct mbuf **mp,
655 	int skip,
656 	int protoff
657 )
658 {
659 	struct enc_xform *espx;
660 	struct auth_hash *esph;
661 	int hlen, rlen, plen, padding, blks, alen, i, roff;
662 	struct mbuf *mo = (struct mbuf *) NULL;
663 	struct tdb_crypto *tc;
664 	struct secasvar *sav;
665 	struct secasindex *saidx;
666 	unsigned char *pad;
667 	u_int8_t prot;
668 	int error, maxpacketsize;
669 
670 	struct cryptodesc *crde = NULL, *crda = NULL;
671 	struct cryptop *crp;
672 
673 	IPSEC_SPLASSERT_SOFTNET(__func__);
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 	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 		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 		espstat.esps_toobig++;
732 		error = EMSGSIZE;
733 		goto bad;
734 	}
735 
736 	/* Update the counters. */
737 	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 		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 		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 (!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 		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 		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 	struct tdb_crypto *tc;
892 	struct ipsecrequest *isr;
893 	struct secasvar *sav;
894 	struct mbuf *m;
895 	int err, error;
896 
897 	NET_LOCK_GIANT();
898 
899 	tc = (struct tdb_crypto *) crp->crp_opaque;
900 	IPSEC_ASSERT(tc != NULL, ("null opaque data area!"));
901 	m = (struct mbuf *) crp->crp_buf;
902 
903 	isr = tc->tc_isr;
904 	IPSECREQUEST_LOCK(isr);
905 	sav = KEY_ALLOCSA(&tc->tc_dst, tc->tc_proto, tc->tc_spi);
906 	if (sav == NULL) {
907 		espstat.esps_notdb++;
908 		DPRINTF(("%s: SA gone during crypto (SA %s/%08lx proto %u)\n",
909 		    __func__, ipsec_address(&tc->tc_dst),
910 		    (u_long) ntohl(tc->tc_spi), tc->tc_proto));
911 		error = ENOBUFS;		/*XXX*/
912 		goto bad;
913 	}
914 	IPSEC_ASSERT(isr->sav == sav,
915 		("SA changed was %p now %p\n", isr->sav, sav));
916 
917 	/* Check for crypto errors. */
918 	if (crp->crp_etype) {
919 		/* Reset session ID. */
920 		if (sav->tdb_cryptoid != 0)
921 			sav->tdb_cryptoid = crp->crp_sid;
922 
923 		if (crp->crp_etype == EAGAIN) {
924 			KEY_FREESAV(&sav);
925 			IPSECREQUEST_UNLOCK(isr);
926 			error = crypto_dispatch(crp);
927 			NET_UNLOCK_GIANT();
928 			return error;
929 		}
930 
931 		espstat.esps_noxform++;
932 		DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
933 		error = crp->crp_etype;
934 		goto bad;
935 	}
936 
937 	/* Shouldn't happen... */
938 	if (m == NULL) {
939 		espstat.esps_crypto++;
940 		DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
941 		error = EINVAL;
942 		goto bad;
943 	}
944 	espstat.esps_hist[sav->alg_enc]++;
945 	if (sav->tdb_authalgxform != NULL)
946 		ahstat.ahs_hist[sav->alg_auth]++;
947 
948 	/* Release crypto descriptors. */
949 	free(tc, M_XDATA);
950 	crypto_freereq(crp);
951 
952 #ifdef REGRESSION
953 	/* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
954 	if (ipsec_integrity) {
955 		static unsigned char ipseczeroes[AH_HMAC_HASHLEN];
956 		struct auth_hash *esph;
957 
958 		/*
959 		 * Corrupt HMAC if we want to test integrity verification of
960 		 * the other side.
961 		 */
962 		esph = sav->tdb_authalgxform;
963 		if (esph !=  NULL) {
964 			m_copyback(m, m->m_pkthdr.len - AH_HMAC_HASHLEN,
965 			    AH_HMAC_HASHLEN, ipseczeroes);
966 		}
967 	}
968 #endif
969 
970 	/* NB: m is reclaimed by ipsec_process_done. */
971 	err = ipsec_process_done(m, isr);
972 	KEY_FREESAV(&sav);
973 	IPSECREQUEST_UNLOCK(isr);
974 	NET_UNLOCK_GIANT();
975 	return err;
976 bad:
977 	if (sav)
978 		KEY_FREESAV(&sav);
979 	IPSECREQUEST_UNLOCK(isr);
980 	if (m)
981 		m_freem(m);
982 	free(tc, M_XDATA);
983 	crypto_freereq(crp);
984 	NET_UNLOCK_GIANT();
985 	return error;
986 }
987 
988 static struct xformsw esp_xformsw = {
989 	XF_ESP,		XFT_CONF|XFT_AUTH,	"IPsec ESP",
990 	esp_init,	esp_zeroize,		esp_input,
991 	esp_output
992 };
993 
994 static void
995 esp_attach(void)
996 {
997 #define	MAXIV(xform)					\
998 	if (xform.blocksize > esp_max_ivlen)		\
999 		esp_max_ivlen = xform.blocksize		\
1000 
1001 	esp_max_ivlen = 0;
1002 	MAXIV(enc_xform_des);		/* SADB_EALG_DESCBC */
1003 	MAXIV(enc_xform_3des);		/* SADB_EALG_3DESCBC */
1004 	MAXIV(enc_xform_rijndael128);	/* SADB_X_EALG_AES */
1005 	MAXIV(enc_xform_blf);		/* SADB_X_EALG_BLOWFISHCBC */
1006 	MAXIV(enc_xform_cast5);		/* SADB_X_EALG_CAST128CBC */
1007 	MAXIV(enc_xform_skipjack);	/* SADB_X_EALG_SKIPJACK */
1008 	MAXIV(enc_xform_null);		/* SADB_EALG_NULL */
1009 
1010 	xform_register(&esp_xformsw);
1011 #undef MAXIV
1012 }
1013 SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE, esp_attach, NULL);
1014