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