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