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