2 /* $OpenBSD: ip_esp.c,v 1.69 2001/06/26 06:18:59 angelos Exp $ */
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).
8 * The original version of this code was written by John Ioannidis
9 * for BSD/OS in Athens, Greece, in November 1995.
11 * Ported to OpenBSD and NetBSD, with additional transforms, in December 1996,
12 * by Angelos D. Keromytis.
14 * Additional transforms and features in 1997 and 1998 by Angelos D. Keromytis
17 * Additional features in 1999 by Angelos D. Keromytis.
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.
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
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
39 #include "opt_inet6.h"
41 #include <sys/param.h>
42 #include <sys/systm.h>
44 #include <sys/socket.h>
45 #include <sys/syslog.h>
46 #include <sys/kernel.h>
48 #include <sys/random.h>
49 #include <sys/mutex.h>
50 #include <sys/sysctl.h>
51 #include <sys/mutex.h>
52 #include <machine/atomic.h>
57 #include <netinet/in.h>
58 #include <netinet/in_systm.h>
59 #include <netinet/ip.h>
60 #include <netinet/ip_ecn.h>
61 #include <netinet/ip6.h>
63 #include <netipsec/ipsec.h>
64 #include <netipsec/ah.h>
65 #include <netipsec/ah_var.h>
66 #include <netipsec/esp.h>
67 #include <netipsec/esp_var.h>
68 #include <netipsec/xform.h>
71 #include <netinet6/ip6_var.h>
72 #include <netipsec/ipsec6.h>
73 #include <netinet6/ip6_ecn.h>
76 #include <netipsec/key.h>
77 #include <netipsec/key_debug.h>
79 #include <opencrypto/cryptodev.h>
80 #include <opencrypto/xform.h>
82 VNET_DEFINE(int, esp_enable) = 1;
83 VNET_PCPUSTAT_DEFINE(struct espstat, espstat);
84 VNET_PCPUSTAT_SYSINIT(espstat);
87 VNET_PCPUSTAT_SYSUNINIT(espstat);
90 SYSCTL_DECL(_net_inet_esp);
91 SYSCTL_INT(_net_inet_esp, OID_AUTO, esp_enable,
92 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(esp_enable), 0, "");
93 SYSCTL_VNET_PCPUSTAT(_net_inet_esp, IPSECCTL_STATS, stats,
94 struct espstat, espstat,
95 "ESP statistics (struct espstat, netipsec/esp_var.h");
97 static struct timeval deswarn, blfwarn, castwarn, camelliawarn;
99 static int esp_input_cb(struct cryptop *op);
100 static int esp_output_cb(struct cryptop *crp);
103 esp_hdrsiz(struct secasvar *sav)
108 /*XXX not right for null algorithm--does it matter??*/
109 IPSEC_ASSERT(sav->tdb_encalgxform != NULL,
110 ("SA with null xform"));
111 if (sav->flags & SADB_X_EXT_OLD)
112 size = sizeof (struct esp);
114 size = sizeof (struct newesp);
115 size += sav->tdb_encalgxform->blocksize + 9;
116 /*XXX need alg check???*/
117 if (sav->tdb_authalgxform != NULL && sav->replay)
118 size += ah_hdrsiz(sav);
122 * + max iv length for CBC mode
124 * + sizeof (pad length field)
125 * + sizeof (next header field)
126 * + max icv supported.
128 size = sizeof (struct newesp) + EALG_MAX_BLOCK_LEN + 9 + 16;
134 * esp_init() is called when an SPI is being set up.
137 esp_init(struct secasvar *sav, struct xformsw *xsp)
139 const struct enc_xform *txform;
140 struct cryptoini cria, crie;
144 txform = enc_algorithm_lookup(sav->alg_enc);
145 if (txform == NULL) {
146 DPRINTF(("%s: unsupported encryption algorithm %d\n",
147 __func__, sav->alg_enc));
150 if (sav->key_enc == NULL) {
151 DPRINTF(("%s: no encoding key for %s algorithm\n",
152 __func__, txform->name));
155 if ((sav->flags & (SADB_X_EXT_OLD | SADB_X_EXT_IV4B)) ==
157 DPRINTF(("%s: 4-byte IV not supported with protocol\n",
162 switch (sav->alg_enc) {
163 case SADB_EALG_DESCBC:
164 if (ratecheck(&deswarn, &ipsec_warn_interval))
165 gone_in(13, "DES cipher for IPsec");
167 case SADB_X_EALG_BLOWFISHCBC:
168 if (ratecheck(&blfwarn, &ipsec_warn_interval))
169 gone_in(13, "Blowfish cipher for IPsec");
171 case SADB_X_EALG_CAST128CBC:
172 if (ratecheck(&castwarn, &ipsec_warn_interval))
173 gone_in(13, "CAST cipher for IPsec");
175 case SADB_X_EALG_CAMELLIACBC:
176 if (ratecheck(&camelliawarn, &ipsec_warn_interval))
177 gone_in(13, "Camellia cipher for IPsec");
181 /* subtract off the salt, RFC4106, 8.1 and RFC3686, 5.1 */
182 keylen = _KEYLEN(sav->key_enc) - SAV_ISCTRORGCM(sav) * 4;
183 if (txform->minkey > keylen || keylen > txform->maxkey) {
184 DPRINTF(("%s: invalid key length %u, must be in the range "
185 "[%u..%u] for algorithm %s\n", __func__,
186 keylen, txform->minkey, txform->maxkey,
191 if (SAV_ISCTRORGCM(sav))
192 sav->ivlen = 8; /* RFC4106 3.1 and RFC3686 3.1 */
194 sav->ivlen = txform->ivsize;
197 * Setup AH-related state.
199 if (sav->alg_auth != 0) {
200 error = ah_init0(sav, xsp, &cria);
205 /* NB: override anything set in ah_init0 */
206 sav->tdb_xform = xsp;
207 sav->tdb_encalgxform = txform;
210 * Whenever AES-GCM is used for encryption, one
211 * of the AES authentication algorithms is chosen
212 * as well, based on the key size.
214 if (sav->alg_enc == SADB_X_EALG_AESGCM16) {
216 case AES_128_GMAC_KEY_LEN:
217 sav->alg_auth = SADB_X_AALG_AES128GMAC;
218 sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_128;
220 case AES_192_GMAC_KEY_LEN:
221 sav->alg_auth = SADB_X_AALG_AES192GMAC;
222 sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_192;
224 case AES_256_GMAC_KEY_LEN:
225 sav->alg_auth = SADB_X_AALG_AES256GMAC;
226 sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_256;
229 DPRINTF(("%s: invalid key length %u"
230 "for algorithm %s\n", __func__,
231 keylen, txform->name));
234 bzero(&cria, sizeof(cria));
235 cria.cri_alg = sav->tdb_authalgxform->type;
236 cria.cri_key = sav->key_enc->key_data;
237 cria.cri_klen = _KEYBITS(sav->key_enc) - SAV_ISGCM(sav) * 32;
240 /* Initialize crypto session. */
241 bzero(&crie, sizeof(crie));
242 crie.cri_alg = sav->tdb_encalgxform->type;
243 crie.cri_key = sav->key_enc->key_data;
244 crie.cri_klen = _KEYBITS(sav->key_enc) - SAV_ISCTRORGCM(sav) * 32;
246 if (sav->tdb_authalgxform && sav->tdb_encalgxform) {
247 /* init both auth & enc */
248 crie.cri_next = &cria;
249 error = crypto_newsession(&sav->tdb_cryptoid,
250 &crie, V_crypto_support);
251 } else if (sav->tdb_encalgxform) {
252 error = crypto_newsession(&sav->tdb_cryptoid,
253 &crie, V_crypto_support);
254 } else if (sav->tdb_authalgxform) {
255 error = crypto_newsession(&sav->tdb_cryptoid,
256 &cria, V_crypto_support);
258 /* XXX cannot happen? */
259 DPRINTF(("%s: no encoding OR authentication xform!\n",
270 esp_zeroize(struct secasvar *sav)
272 /* NB: ah_zerorize free's the crypto session state */
273 int error = ah_zeroize(sav);
276 bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
277 sav->tdb_encalgxform = NULL;
278 sav->tdb_xform = NULL;
283 * ESP input processing, called (eventually) through the protocol switch.
286 esp_input(struct mbuf *m, struct secasvar *sav, int skip, int protoff)
288 IPSEC_DEBUG_DECLARE(char buf[128]);
289 const struct auth_hash *esph;
290 const struct enc_xform *espx;
291 struct xform_data *xd;
292 struct cryptodesc *crde;
296 crypto_session_t cryptoid;
297 int alen, error, hlen, plen;
299 IPSEC_ASSERT(sav != NULL, ("null SA"));
300 IPSEC_ASSERT(sav->tdb_encalgxform != NULL, ("null encoding xform"));
303 /* Valid IP Packet length ? */
304 if ( (skip&3) || (m->m_pkthdr.len&3) ){
305 DPRINTF(("%s: misaligned packet, skip %u pkt len %u",
306 __func__, skip, m->m_pkthdr.len));
307 ESPSTAT_INC(esps_badilen);
311 m = m_pullup(m, skip + sizeof(*esp));
313 DPRINTF(("%s: cannot pullup header\n", __func__));
314 ESPSTAT_INC(esps_hdrops); /*XXX*/
318 esp = (struct newesp *)(mtod(m, caddr_t) + skip);
320 esph = sav->tdb_authalgxform;
321 espx = sav->tdb_encalgxform;
323 /* Determine the ESP header and auth length */
324 if (sav->flags & SADB_X_EXT_OLD)
325 hlen = sizeof (struct esp) + sav->ivlen;
327 hlen = sizeof (struct newesp) + sav->ivlen;
329 alen = xform_ah_authsize(esph);
332 * Verify payload length is multiple of encryption algorithm
335 * NB: This works for the null algorithm because the blocksize
336 * is 4 and all packets must be 4-byte aligned regardless
339 plen = m->m_pkthdr.len - (skip + hlen + alen);
340 if ((plen & (espx->blocksize - 1)) || (plen <= 0)) {
341 DPRINTF(("%s: payload of %d octets not a multiple of %d octets,"
342 " SA %s/%08lx\n", __func__, plen, espx->blocksize,
343 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
344 (u_long)ntohl(sav->spi)));
345 ESPSTAT_INC(esps_badilen);
350 * Check sequence number.
353 if (esph != NULL && sav->replay != NULL && sav->replay->wsize != 0) {
354 if (ipsec_chkreplay(ntohl(esp->esp_seq), sav) == 0) {
355 SECASVAR_UNLOCK(sav);
356 DPRINTF(("%s: packet replay check for %s\n", __func__,
357 ipsec_sa2str(sav, buf, sizeof(buf))));
358 ESPSTAT_INC(esps_replay);
363 cryptoid = sav->tdb_cryptoid;
364 SECASVAR_UNLOCK(sav);
366 /* Update the counters */
367 ESPSTAT_ADD(esps_ibytes, m->m_pkthdr.len - (skip + hlen + alen));
369 /* Get crypto descriptors */
370 crp = crypto_getreq(esph && espx ? 2 : 1);
372 DPRINTF(("%s: failed to acquire crypto descriptors\n",
374 ESPSTAT_INC(esps_crypto);
379 /* Get IPsec-specific opaque pointer */
380 xd = malloc(sizeof(*xd) + alen, M_XDATA, M_NOWAIT | M_ZERO);
382 DPRINTF(("%s: failed to allocate xform_data\n", __func__));
383 ESPSTAT_INC(esps_crypto);
390 struct cryptodesc *crda = crp->crp_desc;
392 IPSEC_ASSERT(crda != NULL, ("null ah crypto descriptor"));
394 /* Authentication descriptor */
395 crda->crd_skip = skip;
397 crda->crd_len = 8; /* RFC4106 5, SPI + SN */
399 crda->crd_len = m->m_pkthdr.len - (skip + alen);
400 crda->crd_inject = m->m_pkthdr.len - alen;
402 crda->crd_alg = esph->type;
404 /* Copy the authenticator */
405 m_copydata(m, m->m_pkthdr.len - alen, alen,
408 /* Chain authentication request */
409 crde = crda->crd_next;
411 crde = crp->crp_desc;
414 /* Crypto operation descriptor */
415 crp->crp_ilen = m->m_pkthdr.len; /* Total input length */
416 crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
418 crp->crp_flags |= CRYPTO_F_ASYNC | CRYPTO_F_ASYNC_KEEPORDER;
419 crp->crp_buf = (caddr_t) m;
420 crp->crp_callback = esp_input_cb;
421 crp->crp_session = cryptoid;
422 crp->crp_opaque = (caddr_t) xd;
424 /* These are passed as-is to the callback */
426 xd->protoff = protoff;
428 xd->cryptoid = cryptoid;
431 /* Decryption descriptor */
432 IPSEC_ASSERT(crde != NULL, ("null esp crypto descriptor"));
433 crde->crd_skip = skip + hlen;
434 crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
435 crde->crd_inject = skip + hlen - sav->ivlen;
437 if (SAV_ISCTRORGCM(sav)) {
438 ivp = &crde->crd_iv[0];
440 /* GCM IV Format: RFC4106 4 */
441 /* CTR IV Format: RFC3686 4 */
442 /* Salt is last four bytes of key, RFC4106 8.1 */
443 /* Nonce is last four bytes of key, RFC3686 5.1 */
444 memcpy(ivp, sav->key_enc->key_data +
445 _KEYLEN(sav->key_enc) - 4, 4);
447 if (SAV_ISCTR(sav)) {
448 /* Initial block counter is 1, RFC3686 4 */
449 be32enc(&ivp[sav->ivlen + 4], 1);
452 m_copydata(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
453 crde->crd_flags |= CRD_F_IV_EXPLICIT;
456 crde->crd_alg = espx->type;
458 return (crypto_dispatch(crp));
466 * ESP input callback from the crypto driver.
469 esp_input_cb(struct cryptop *crp)
471 IPSEC_DEBUG_DECLARE(char buf[128]);
472 u_int8_t lastthree[3], aalg[AH_HMAC_MAXHASHLEN];
473 const struct auth_hash *esph;
475 struct cryptodesc *crd;
476 struct xform_data *xd;
477 struct secasvar *sav;
478 struct secasindex *saidx;
480 crypto_session_t cryptoid;
481 int hlen, skip, protoff, error, alen;
484 IPSEC_ASSERT(crd != NULL, ("null crypto descriptor!"));
486 m = (struct mbuf *) crp->crp_buf;
487 xd = (struct xform_data *) crp->crp_opaque;
488 CURVNET_SET(xd->vnet);
491 protoff = xd->protoff;
492 cryptoid = xd->cryptoid;
493 saidx = &sav->sah->saidx;
494 esph = sav->tdb_authalgxform;
496 /* Check for crypto errors */
497 if (crp->crp_etype) {
498 if (crp->crp_etype == EAGAIN) {
499 /* Reset the session ID */
500 if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
501 crypto_freesession(cryptoid);
502 xd->cryptoid = crp->crp_session;
504 return (crypto_dispatch(crp));
506 ESPSTAT_INC(esps_noxform);
507 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
508 error = crp->crp_etype;
512 /* Shouldn't happen... */
514 ESPSTAT_INC(esps_crypto);
515 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
519 ESPSTAT_INC(esps_hist[sav->alg_enc]);
521 /* If authentication was performed, check now. */
523 alen = xform_ah_authsize(esph);
524 AHSTAT_INC(ahs_hist[sav->alg_auth]);
525 /* Copy the authenticator from the packet */
526 m_copydata(m, m->m_pkthdr.len - alen, alen, aalg);
527 ptr = (caddr_t) (xd + 1);
529 /* Verify authenticator */
530 if (timingsafe_bcmp(ptr, aalg, alen) != 0) {
531 DPRINTF(("%s: authentication hash mismatch for "
532 "packet in SA %s/%08lx\n", __func__,
533 ipsec_address(&saidx->dst, buf, sizeof(buf)),
534 (u_long) ntohl(sav->spi)));
535 ESPSTAT_INC(esps_badauth);
539 m->m_flags |= M_AUTHIPDGM;
540 /* Remove trailing authenticator */
544 /* Release the crypto descriptors */
545 free(xd, M_XDATA), xd = NULL;
546 crypto_freereq(crp), crp = NULL;
549 * Packet is now decrypted.
551 m->m_flags |= M_DECRYPTED;
554 * Update replay sequence number, if appropriate.
559 m_copydata(m, skip + offsetof(struct newesp, esp_seq),
560 sizeof (seq), (caddr_t) &seq);
562 if (ipsec_updatereplay(ntohl(seq), sav)) {
563 SECASVAR_UNLOCK(sav);
564 DPRINTF(("%s: packet replay check for %s\n", __func__,
565 ipsec_sa2str(sav, buf, sizeof(buf))));
566 ESPSTAT_INC(esps_replay);
570 SECASVAR_UNLOCK(sav);
573 /* Determine the ESP header length */
574 if (sav->flags & SADB_X_EXT_OLD)
575 hlen = sizeof (struct esp) + sav->ivlen;
577 hlen = sizeof (struct newesp) + sav->ivlen;
579 /* Remove the ESP header and IV from the mbuf. */
580 error = m_striphdr(m, skip, hlen);
582 ESPSTAT_INC(esps_hdrops);
583 DPRINTF(("%s: bad mbuf chain, SA %s/%08lx\n", __func__,
584 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
585 (u_long) ntohl(sav->spi)));
589 /* Save the last three bytes of decrypted data */
590 m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
592 /* Verify pad length */
593 if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
594 ESPSTAT_INC(esps_badilen);
595 DPRINTF(("%s: invalid padding length %d for %u byte packet "
596 "in SA %s/%08lx\n", __func__, lastthree[1],
597 m->m_pkthdr.len - skip,
598 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
599 (u_long) ntohl(sav->spi)));
604 /* Verify correct decryption by checking the last padding bytes */
605 if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
606 if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
607 ESPSTAT_INC(esps_badenc);
608 DPRINTF(("%s: decryption failed for packet in "
609 "SA %s/%08lx\n", __func__, ipsec_address(
610 &sav->sah->saidx.dst, buf, sizeof(buf)),
611 (u_long) ntohl(sav->spi)));
617 /* Trim the mbuf chain to remove trailing authenticator and padding */
618 m_adj(m, -(lastthree[1] + 2));
620 /* Restore the Next Protocol field */
621 m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
623 switch (saidx->dst.sa.sa_family) {
626 error = ipsec6_common_input_cb(m, sav, skip, protoff);
631 error = ipsec4_common_input_cb(m, sav, skip, protoff);
635 panic("%s: Unexpected address family: %d saidx=%p", __func__,
636 saidx->dst.sa.sa_family, saidx);
653 * ESP output routine, called by ipsec[46]_perform_request().
656 esp_output(struct mbuf *m, struct secpolicy *sp, struct secasvar *sav,
657 u_int idx, int skip, int protoff)
659 IPSEC_DEBUG_DECLARE(char buf[IPSEC_ADDRSTRLEN]);
660 struct cryptodesc *crde = NULL, *crda = NULL;
662 const struct auth_hash *esph;
663 const struct enc_xform *espx;
664 struct mbuf *mo = NULL;
665 struct xform_data *xd;
666 struct secasindex *saidx;
670 crypto_session_t cryptoid;
671 int hlen, rlen, padding, blks, alen, i, roff;
672 int error, maxpacketsize;
675 IPSEC_ASSERT(sav != NULL, ("null SA"));
676 esph = sav->tdb_authalgxform;
677 espx = sav->tdb_encalgxform;
678 IPSEC_ASSERT(espx != NULL, ("null encoding xform"));
680 if (sav->flags & SADB_X_EXT_OLD)
681 hlen = sizeof (struct esp) + sav->ivlen;
683 hlen = sizeof (struct newesp) + sav->ivlen;
685 rlen = m->m_pkthdr.len - skip; /* Raw payload length. */
687 * RFC4303 2.4 Requires 4 byte alignment.
689 blks = MAX(4, espx->blocksize); /* Cipher blocksize */
691 /* XXX clamp padding length a la KAME??? */
692 padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
694 alen = xform_ah_authsize(esph);
696 ESPSTAT_INC(esps_output);
698 saidx = &sav->sah->saidx;
699 /* Check for maximum packet size violations. */
700 switch (saidx->dst.sa.sa_family) {
703 maxpacketsize = IP_MAXPACKET;
708 maxpacketsize = IPV6_MAXPACKET;
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 buf, sizeof(buf)), (u_long) ntohl(sav->spi)));
716 ESPSTAT_INC(esps_nopf);
717 error = EPFNOSUPPORT;
721 DPRINTF(("%s: skip %d hlen %d rlen %d padding %d alen %d blksd %d\n",
722 __func__, skip, hlen, rlen, padding, alen, blks)); */
723 if (skip + hlen + rlen + padding + alen > maxpacketsize) {
724 DPRINTF(("%s: packet in SA %s/%08lx got too big "
725 "(len %u, max len %u)\n", __func__,
726 ipsec_address(&saidx->dst, buf, sizeof(buf)),
727 (u_long) ntohl(sav->spi),
728 skip + hlen + rlen + padding + alen, maxpacketsize));
729 ESPSTAT_INC(esps_toobig);
734 /* Update the counters. */
735 ESPSTAT_ADD(esps_obytes, m->m_pkthdr.len - skip);
737 m = m_unshare(m, M_NOWAIT);
739 DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
740 ipsec_address(&saidx->dst, buf, sizeof(buf)),
741 (u_long) ntohl(sav->spi)));
742 ESPSTAT_INC(esps_hdrops);
747 /* Inject ESP header. */
748 mo = m_makespace(m, skip, hlen, &roff);
750 DPRINTF(("%s: %u byte ESP hdr inject failed for SA %s/%08lx\n",
751 __func__, hlen, ipsec_address(&saidx->dst, buf,
752 sizeof(buf)), (u_long) ntohl(sav->spi)));
753 ESPSTAT_INC(esps_hdrops); /* XXX diffs from openbsd */
758 /* Initialize ESP header. */
759 bcopy((caddr_t) &sav->spi, mtod(mo, caddr_t) + roff,
766 /* Emulate replay attack when ipsec_replay is TRUE. */
769 sav->replay->count++;
770 replay = htonl(sav->replay->count);
772 bcopy((caddr_t) &replay, mtod(mo, caddr_t) + roff +
773 sizeof(uint32_t), sizeof(uint32_t));
775 cryptoid = sav->tdb_cryptoid;
776 if (SAV_ISCTRORGCM(sav))
778 SECASVAR_UNLOCK(sav);
781 * Add padding -- better to do it ourselves than use the crypto engine,
782 * although if/when we support compression, we'd have to do that.
784 pad = (u_char *) m_pad(m, padding + alen);
786 DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
787 ipsec_address(&saidx->dst, buf, sizeof(buf)),
788 (u_long) ntohl(sav->spi)));
789 m = NULL; /* NB: free'd by m_pad */
795 * Add padding: random, zero, or self-describing.
796 * XXX catch unexpected setting
798 switch (sav->flags & SADB_X_EXT_PMASK) {
799 case SADB_X_EXT_PRAND:
800 arc4random_buf(pad, padding - 2);
802 case SADB_X_EXT_PZERO:
803 bzero(pad, padding - 2);
805 case SADB_X_EXT_PSEQ:
806 for (i = 0; i < padding - 2; i++)
811 /* Fix padding length and Next Protocol in padding itself. */
812 pad[padding - 2] = padding - 2;
813 m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
815 /* Fix Next Protocol in IPv4/IPv6 header. */
817 m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
819 /* Get crypto descriptors. */
820 crp = crypto_getreq(esph != NULL ? 2 : 1);
822 DPRINTF(("%s: failed to acquire crypto descriptors\n",
824 ESPSTAT_INC(esps_crypto);
829 /* IPsec-specific opaque crypto info. */
830 xd = malloc(sizeof(struct xform_data), M_XDATA, M_NOWAIT | M_ZERO);
833 DPRINTF(("%s: failed to allocate xform_data\n", __func__));
834 ESPSTAT_INC(esps_crypto);
839 crde = crp->crp_desc;
840 crda = crde->crd_next;
842 /* Encryption descriptor. */
843 crde->crd_skip = skip + hlen;
844 crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
845 crde->crd_flags = CRD_F_ENCRYPT;
846 crde->crd_inject = skip + hlen - sav->ivlen;
848 /* Encryption operation. */
849 crde->crd_alg = espx->type;
850 if (SAV_ISCTRORGCM(sav)) {
851 ivp = &crde->crd_iv[0];
853 /* GCM IV Format: RFC4106 4 */
854 /* CTR IV Format: RFC3686 4 */
855 /* Salt is last four bytes of key, RFC4106 8.1 */
856 /* Nonce is last four bytes of key, RFC3686 5.1 */
857 memcpy(ivp, sav->key_enc->key_data +
858 _KEYLEN(sav->key_enc) - 4, 4);
859 be64enc(&ivp[4], cntr);
860 if (SAV_ISCTR(sav)) {
861 /* Initial block counter is 1, RFC3686 4 */
862 /* XXXAE: should we use this only for first packet? */
863 be32enc(&ivp[sav->ivlen + 4], 1);
866 m_copyback(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
867 crde->crd_flags |= CRD_F_IV_EXPLICIT|CRD_F_IV_PRESENT;
870 /* Callback parameters */
874 xd->cryptoid = cryptoid;
877 /* Crypto operation descriptor. */
878 crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
879 crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
881 crp->crp_flags |= CRYPTO_F_ASYNC | CRYPTO_F_ASYNC_KEEPORDER;
882 crp->crp_buf = (caddr_t) m;
883 crp->crp_callback = esp_output_cb;
884 crp->crp_opaque = (caddr_t) xd;
885 crp->crp_session = cryptoid;
888 /* Authentication descriptor. */
889 crda->crd_alg = esph->type;
890 crda->crd_skip = skip;
892 crda->crd_len = 8; /* RFC4106 5, SPI + SN */
894 crda->crd_len = m->m_pkthdr.len - (skip + alen);
895 crda->crd_inject = m->m_pkthdr.len - alen;
898 return crypto_dispatch(crp);
907 * ESP output callback from the crypto driver.
910 esp_output_cb(struct cryptop *crp)
912 struct xform_data *xd;
913 struct secpolicy *sp;
914 struct secasvar *sav;
916 crypto_session_t cryptoid;
920 xd = (struct xform_data *) crp->crp_opaque;
921 CURVNET_SET(xd->vnet);
922 m = (struct mbuf *) crp->crp_buf;
926 cryptoid = xd->cryptoid;
928 /* Check for crypto errors. */
929 if (crp->crp_etype) {
930 if (crp->crp_etype == EAGAIN) {
931 /* Reset the session ID */
932 if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
933 crypto_freesession(cryptoid);
934 xd->cryptoid = crp->crp_session;
936 return (crypto_dispatch(crp));
938 ESPSTAT_INC(esps_noxform);
939 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
940 error = crp->crp_etype;
945 /* Shouldn't happen... */
947 ESPSTAT_INC(esps_crypto);
948 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
954 ESPSTAT_INC(esps_hist[sav->alg_enc]);
955 if (sav->tdb_authalgxform != NULL)
956 AHSTAT_INC(ahs_hist[sav->alg_auth]);
959 /* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
960 if (V_ipsec_integrity) {
961 static unsigned char ipseczeroes[AH_HMAC_MAXHASHLEN];
962 const struct auth_hash *esph;
965 * Corrupt HMAC if we want to test integrity verification of
968 esph = sav->tdb_authalgxform;
972 alen = xform_ah_authsize(esph);
973 m_copyback(m, m->m_pkthdr.len - alen,
979 /* NB: m is reclaimed by ipsec_process_done. */
980 error = ipsec_process_done(m, sp, sav, idx);
992 static struct xformsw esp_xformsw = {
994 .xf_name = "IPsec ESP",
996 .xf_zeroize = esp_zeroize,
997 .xf_input = esp_input,
998 .xf_output = esp_output,
1001 SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
1002 xform_attach, &esp_xformsw);
1003 SYSUNINIT(esp_xform_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
1004 xform_detach, &esp_xformsw);