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, tdeswarn;
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_EALG_3DESCBC:
168 if (ratecheck(&tdeswarn, &ipsec_warn_interval))
169 gone_in(13, "3DES cipher for IPsec");
171 case SADB_X_EALG_BLOWFISHCBC:
172 if (ratecheck(&blfwarn, &ipsec_warn_interval))
173 gone_in(13, "Blowfish cipher for IPsec");
175 case SADB_X_EALG_CAST128CBC:
176 if (ratecheck(&castwarn, &ipsec_warn_interval))
177 gone_in(13, "CAST cipher for IPsec");
179 case SADB_X_EALG_CAMELLIACBC:
180 if (ratecheck(&camelliawarn, &ipsec_warn_interval))
181 gone_in(13, "Camellia cipher for IPsec");
185 /* subtract off the salt, RFC4106, 8.1 and RFC3686, 5.1 */
186 keylen = _KEYLEN(sav->key_enc) - SAV_ISCTRORGCM(sav) * 4;
187 if (txform->minkey > keylen || keylen > txform->maxkey) {
188 DPRINTF(("%s: invalid key length %u, must be in the range "
189 "[%u..%u] for algorithm %s\n", __func__,
190 keylen, txform->minkey, txform->maxkey,
195 if (SAV_ISCTRORGCM(sav))
196 sav->ivlen = 8; /* RFC4106 3.1 and RFC3686 3.1 */
198 sav->ivlen = txform->ivsize;
201 * Setup AH-related state.
203 if (sav->alg_auth != 0) {
204 error = ah_init0(sav, xsp, &cria);
209 /* NB: override anything set in ah_init0 */
210 sav->tdb_xform = xsp;
211 sav->tdb_encalgxform = txform;
214 * Whenever AES-GCM is used for encryption, one
215 * of the AES authentication algorithms is chosen
216 * as well, based on the key size.
218 if (sav->alg_enc == SADB_X_EALG_AESGCM16) {
220 case AES_128_GMAC_KEY_LEN:
221 sav->alg_auth = SADB_X_AALG_AES128GMAC;
222 sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_128;
224 case AES_192_GMAC_KEY_LEN:
225 sav->alg_auth = SADB_X_AALG_AES192GMAC;
226 sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_192;
228 case AES_256_GMAC_KEY_LEN:
229 sav->alg_auth = SADB_X_AALG_AES256GMAC;
230 sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_256;
233 DPRINTF(("%s: invalid key length %u"
234 "for algorithm %s\n", __func__,
235 keylen, txform->name));
238 bzero(&cria, sizeof(cria));
239 cria.cri_alg = sav->tdb_authalgxform->type;
240 cria.cri_key = sav->key_enc->key_data;
241 cria.cri_klen = _KEYBITS(sav->key_enc) - SAV_ISGCM(sav) * 32;
244 /* Initialize crypto session. */
245 bzero(&crie, sizeof(crie));
246 crie.cri_alg = sav->tdb_encalgxform->type;
247 crie.cri_key = sav->key_enc->key_data;
248 crie.cri_klen = _KEYBITS(sav->key_enc) - SAV_ISCTRORGCM(sav) * 32;
250 if (sav->tdb_authalgxform && sav->tdb_encalgxform) {
251 /* init both auth & enc */
252 crie.cri_next = &cria;
253 error = crypto_newsession(&sav->tdb_cryptoid,
254 &crie, V_crypto_support);
255 } else if (sav->tdb_encalgxform) {
256 error = crypto_newsession(&sav->tdb_cryptoid,
257 &crie, V_crypto_support);
258 } else if (sav->tdb_authalgxform) {
259 error = crypto_newsession(&sav->tdb_cryptoid,
260 &cria, V_crypto_support);
262 /* XXX cannot happen? */
263 DPRINTF(("%s: no encoding OR authentication xform!\n",
274 esp_zeroize(struct secasvar *sav)
276 /* NB: ah_zerorize free's the crypto session state */
277 int error = ah_zeroize(sav);
280 bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
281 sav->tdb_encalgxform = NULL;
282 sav->tdb_xform = NULL;
287 * ESP input processing, called (eventually) through the protocol switch.
290 esp_input(struct mbuf *m, struct secasvar *sav, int skip, int protoff)
292 IPSEC_DEBUG_DECLARE(char buf[128]);
293 const struct auth_hash *esph;
294 const struct enc_xform *espx;
295 struct xform_data *xd;
296 struct cryptodesc *crde;
300 crypto_session_t cryptoid;
301 int alen, error, hlen, plen;
303 IPSEC_ASSERT(sav != NULL, ("null SA"));
304 IPSEC_ASSERT(sav->tdb_encalgxform != NULL, ("null encoding xform"));
307 /* Valid IP Packet length ? */
308 if ( (skip&3) || (m->m_pkthdr.len&3) ){
309 DPRINTF(("%s: misaligned packet, skip %u pkt len %u",
310 __func__, skip, m->m_pkthdr.len));
311 ESPSTAT_INC(esps_badilen);
315 if (m->m_len < skip + sizeof(*esp)) {
316 m = m_pullup(m, skip + sizeof(*esp));
318 DPRINTF(("%s: cannot pullup header\n", __func__));
319 ESPSTAT_INC(esps_hdrops); /*XXX*/
324 esp = (struct newesp *)(mtod(m, caddr_t) + skip);
326 esph = sav->tdb_authalgxform;
327 espx = sav->tdb_encalgxform;
329 /* Determine the ESP header and auth length */
330 if (sav->flags & SADB_X_EXT_OLD)
331 hlen = sizeof (struct esp) + sav->ivlen;
333 hlen = sizeof (struct newesp) + sav->ivlen;
335 alen = xform_ah_authsize(esph);
338 * Verify payload length is multiple of encryption algorithm
341 * NB: This works for the null algorithm because the blocksize
342 * is 4 and all packets must be 4-byte aligned regardless
345 plen = m->m_pkthdr.len - (skip + hlen + alen);
346 if ((plen & (espx->blocksize - 1)) || (plen <= 0)) {
347 DPRINTF(("%s: payload of %d octets not a multiple of %d octets,"
348 " SA %s/%08lx\n", __func__, plen, espx->blocksize,
349 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
350 (u_long)ntohl(sav->spi)));
351 ESPSTAT_INC(esps_badilen);
356 * Check sequence number.
359 if (esph != NULL && sav->replay != NULL && sav->replay->wsize != 0) {
360 if (ipsec_chkreplay(ntohl(esp->esp_seq), sav) == 0) {
361 SECASVAR_UNLOCK(sav);
362 DPRINTF(("%s: packet replay check for %s\n", __func__,
363 ipsec_sa2str(sav, buf, sizeof(buf))));
364 ESPSTAT_INC(esps_replay);
369 cryptoid = sav->tdb_cryptoid;
370 SECASVAR_UNLOCK(sav);
372 /* Update the counters */
373 ESPSTAT_ADD(esps_ibytes, m->m_pkthdr.len - (skip + hlen + alen));
375 /* Get crypto descriptors */
376 crp = crypto_getreq(esph && espx ? 2 : 1);
378 DPRINTF(("%s: failed to acquire crypto descriptors\n",
380 ESPSTAT_INC(esps_crypto);
385 /* Get IPsec-specific opaque pointer */
386 xd = malloc(sizeof(*xd) + alen, M_XDATA, M_NOWAIT | M_ZERO);
388 DPRINTF(("%s: failed to allocate xform_data\n", __func__));
389 ESPSTAT_INC(esps_crypto);
396 struct cryptodesc *crda = crp->crp_desc;
398 IPSEC_ASSERT(crda != NULL, ("null ah crypto descriptor"));
400 /* Authentication descriptor */
401 crda->crd_skip = skip;
403 crda->crd_len = 8; /* RFC4106 5, SPI + SN */
405 crda->crd_len = m->m_pkthdr.len - (skip + alen);
406 crda->crd_inject = m->m_pkthdr.len - alen;
408 crda->crd_alg = esph->type;
410 /* Copy the authenticator */
411 m_copydata(m, m->m_pkthdr.len - alen, alen,
414 /* Chain authentication request */
415 crde = crda->crd_next;
417 crde = crp->crp_desc;
420 /* Crypto operation descriptor */
421 crp->crp_ilen = m->m_pkthdr.len; /* Total input length */
422 crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
424 crp->crp_flags |= CRYPTO_F_ASYNC | CRYPTO_F_ASYNC_KEEPORDER;
425 crp->crp_buf = (caddr_t) m;
426 crp->crp_callback = esp_input_cb;
427 crp->crp_session = cryptoid;
428 crp->crp_opaque = (caddr_t) xd;
430 /* These are passed as-is to the callback */
432 xd->protoff = protoff;
434 xd->cryptoid = cryptoid;
437 /* Decryption descriptor */
438 IPSEC_ASSERT(crde != NULL, ("null esp crypto descriptor"));
439 crde->crd_skip = skip + hlen;
440 crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
441 crde->crd_inject = skip + hlen - sav->ivlen;
443 if (SAV_ISCTRORGCM(sav)) {
444 ivp = &crde->crd_iv[0];
446 /* GCM IV Format: RFC4106 4 */
447 /* CTR IV Format: RFC3686 4 */
448 /* Salt is last four bytes of key, RFC4106 8.1 */
449 /* Nonce is last four bytes of key, RFC3686 5.1 */
450 memcpy(ivp, sav->key_enc->key_data +
451 _KEYLEN(sav->key_enc) - 4, 4);
453 if (SAV_ISCTR(sav)) {
454 /* Initial block counter is 1, RFC3686 4 */
455 be32enc(&ivp[sav->ivlen + 4], 1);
458 m_copydata(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
459 crde->crd_flags |= CRD_F_IV_EXPLICIT;
462 crde->crd_alg = espx->type;
464 return (crypto_dispatch(crp));
472 * ESP input callback from the crypto driver.
475 esp_input_cb(struct cryptop *crp)
477 IPSEC_DEBUG_DECLARE(char buf[128]);
478 u_int8_t lastthree[3], aalg[AH_HMAC_MAXHASHLEN];
479 const struct auth_hash *esph;
481 struct cryptodesc *crd;
482 struct xform_data *xd;
483 struct secasvar *sav;
484 struct secasindex *saidx;
486 crypto_session_t cryptoid;
487 int hlen, skip, protoff, error, alen;
490 IPSEC_ASSERT(crd != NULL, ("null crypto descriptor!"));
492 m = (struct mbuf *) crp->crp_buf;
493 xd = (struct xform_data *) crp->crp_opaque;
494 CURVNET_SET(xd->vnet);
497 protoff = xd->protoff;
498 cryptoid = xd->cryptoid;
499 saidx = &sav->sah->saidx;
500 esph = sav->tdb_authalgxform;
502 /* Check for crypto errors */
503 if (crp->crp_etype) {
504 if (crp->crp_etype == EAGAIN) {
505 /* Reset the session ID */
506 if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
507 crypto_freesession(cryptoid);
508 xd->cryptoid = crp->crp_session;
510 return (crypto_dispatch(crp));
512 ESPSTAT_INC(esps_noxform);
513 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
514 error = crp->crp_etype;
518 /* Shouldn't happen... */
520 ESPSTAT_INC(esps_crypto);
521 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
525 ESPSTAT_INC(esps_hist[sav->alg_enc]);
527 /* If authentication was performed, check now. */
529 alen = xform_ah_authsize(esph);
530 AHSTAT_INC(ahs_hist[sav->alg_auth]);
531 /* Copy the authenticator from the packet */
532 m_copydata(m, m->m_pkthdr.len - alen, alen, aalg);
533 ptr = (caddr_t) (xd + 1);
535 /* Verify authenticator */
536 if (timingsafe_bcmp(ptr, aalg, alen) != 0) {
537 DPRINTF(("%s: authentication hash mismatch for "
538 "packet in SA %s/%08lx\n", __func__,
539 ipsec_address(&saidx->dst, buf, sizeof(buf)),
540 (u_long) ntohl(sav->spi)));
541 ESPSTAT_INC(esps_badauth);
545 m->m_flags |= M_AUTHIPDGM;
546 /* Remove trailing authenticator */
550 /* Release the crypto descriptors */
551 free(xd, M_XDATA), xd = NULL;
552 crypto_freereq(crp), crp = NULL;
555 * Packet is now decrypted.
557 m->m_flags |= M_DECRYPTED;
560 * Update replay sequence number, if appropriate.
565 m_copydata(m, skip + offsetof(struct newesp, esp_seq),
566 sizeof (seq), (caddr_t) &seq);
568 if (ipsec_updatereplay(ntohl(seq), sav)) {
569 SECASVAR_UNLOCK(sav);
570 DPRINTF(("%s: packet replay check for %s\n", __func__,
571 ipsec_sa2str(sav, buf, sizeof(buf))));
572 ESPSTAT_INC(esps_replay);
576 SECASVAR_UNLOCK(sav);
579 /* Determine the ESP header length */
580 if (sav->flags & SADB_X_EXT_OLD)
581 hlen = sizeof (struct esp) + sav->ivlen;
583 hlen = sizeof (struct newesp) + sav->ivlen;
585 /* Remove the ESP header and IV from the mbuf. */
586 error = m_striphdr(m, skip, hlen);
588 ESPSTAT_INC(esps_hdrops);
589 DPRINTF(("%s: bad mbuf chain, SA %s/%08lx\n", __func__,
590 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
591 (u_long) ntohl(sav->spi)));
595 /* Save the last three bytes of decrypted data */
596 m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
598 /* Verify pad length */
599 if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
600 ESPSTAT_INC(esps_badilen);
601 DPRINTF(("%s: invalid padding length %d for %u byte packet "
602 "in SA %s/%08lx\n", __func__, lastthree[1],
603 m->m_pkthdr.len - skip,
604 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
605 (u_long) ntohl(sav->spi)));
610 /* Verify correct decryption by checking the last padding bytes */
611 if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
612 if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
613 ESPSTAT_INC(esps_badenc);
614 DPRINTF(("%s: decryption failed for packet in "
615 "SA %s/%08lx\n", __func__, ipsec_address(
616 &sav->sah->saidx.dst, buf, sizeof(buf)),
617 (u_long) ntohl(sav->spi)));
625 * Silently drop packet if next header field is IPPROTO_NONE.
627 if (lastthree[2] == IPPROTO_NONE)
630 /* Trim the mbuf chain to remove trailing authenticator and padding */
631 m_adj(m, -(lastthree[1] + 2));
633 /* Restore the Next Protocol field */
634 m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
636 switch (saidx->dst.sa.sa_family) {
639 error = ipsec6_common_input_cb(m, sav, skip, protoff);
644 error = ipsec4_common_input_cb(m, sav, skip, protoff);
648 panic("%s: Unexpected address family: %d saidx=%p", __func__,
649 saidx->dst.sa.sa_family, saidx);
666 * ESP output routine, called by ipsec[46]_perform_request().
669 esp_output(struct mbuf *m, struct secpolicy *sp, struct secasvar *sav,
670 u_int idx, int skip, int protoff)
672 IPSEC_DEBUG_DECLARE(char buf[IPSEC_ADDRSTRLEN]);
673 struct cryptodesc *crde = NULL, *crda = NULL;
675 const struct auth_hash *esph;
676 const struct enc_xform *espx;
677 struct mbuf *mo = NULL;
678 struct xform_data *xd;
679 struct secasindex *saidx;
683 crypto_session_t cryptoid;
684 int hlen, rlen, padding, blks, alen, i, roff;
685 int error, maxpacketsize;
688 IPSEC_ASSERT(sav != NULL, ("null SA"));
689 esph = sav->tdb_authalgxform;
690 espx = sav->tdb_encalgxform;
691 IPSEC_ASSERT(espx != NULL, ("null encoding xform"));
693 if (sav->flags & SADB_X_EXT_OLD)
694 hlen = sizeof (struct esp) + sav->ivlen;
696 hlen = sizeof (struct newesp) + sav->ivlen;
698 rlen = m->m_pkthdr.len - skip; /* Raw payload length. */
700 * RFC4303 2.4 Requires 4 byte alignment.
702 blks = MAX(4, espx->blocksize); /* Cipher blocksize */
704 /* XXX clamp padding length a la KAME??? */
705 padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
707 alen = xform_ah_authsize(esph);
709 ESPSTAT_INC(esps_output);
711 saidx = &sav->sah->saidx;
712 /* Check for maximum packet size violations. */
713 switch (saidx->dst.sa.sa_family) {
716 maxpacketsize = IP_MAXPACKET;
721 maxpacketsize = IPV6_MAXPACKET;
725 DPRINTF(("%s: unknown/unsupported protocol "
726 "family %d, SA %s/%08lx\n", __func__,
727 saidx->dst.sa.sa_family, ipsec_address(&saidx->dst,
728 buf, sizeof(buf)), (u_long) ntohl(sav->spi)));
729 ESPSTAT_INC(esps_nopf);
730 error = EPFNOSUPPORT;
734 DPRINTF(("%s: skip %d hlen %d rlen %d padding %d alen %d blksd %d\n",
735 __func__, skip, hlen, rlen, padding, alen, blks)); */
736 if (skip + hlen + rlen + padding + alen > maxpacketsize) {
737 DPRINTF(("%s: packet in SA %s/%08lx got too big "
738 "(len %u, max len %u)\n", __func__,
739 ipsec_address(&saidx->dst, buf, sizeof(buf)),
740 (u_long) ntohl(sav->spi),
741 skip + hlen + rlen + padding + alen, maxpacketsize));
742 ESPSTAT_INC(esps_toobig);
747 /* Update the counters. */
748 ESPSTAT_ADD(esps_obytes, m->m_pkthdr.len - skip);
750 m = m_unshare(m, M_NOWAIT);
752 DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
753 ipsec_address(&saidx->dst, buf, sizeof(buf)),
754 (u_long) ntohl(sav->spi)));
755 ESPSTAT_INC(esps_hdrops);
760 /* Inject ESP header. */
761 mo = m_makespace(m, skip, hlen, &roff);
763 DPRINTF(("%s: %u byte ESP hdr inject failed for SA %s/%08lx\n",
764 __func__, hlen, ipsec_address(&saidx->dst, buf,
765 sizeof(buf)), (u_long) ntohl(sav->spi)));
766 ESPSTAT_INC(esps_hdrops); /* XXX diffs from openbsd */
771 /* Initialize ESP header. */
772 bcopy((caddr_t) &sav->spi, mtod(mo, caddr_t) + roff,
779 /* Emulate replay attack when ipsec_replay is TRUE. */
782 sav->replay->count++;
783 replay = htonl(sav->replay->count);
785 bcopy((caddr_t) &replay, mtod(mo, caddr_t) + roff +
786 sizeof(uint32_t), sizeof(uint32_t));
788 cryptoid = sav->tdb_cryptoid;
789 if (SAV_ISCTRORGCM(sav))
791 SECASVAR_UNLOCK(sav);
794 * Add padding -- better to do it ourselves than use the crypto engine,
795 * although if/when we support compression, we'd have to do that.
797 pad = (u_char *) m_pad(m, padding + alen);
799 DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
800 ipsec_address(&saidx->dst, buf, sizeof(buf)),
801 (u_long) ntohl(sav->spi)));
802 m = NULL; /* NB: free'd by m_pad */
808 * Add padding: random, zero, or self-describing.
809 * XXX catch unexpected setting
811 switch (sav->flags & SADB_X_EXT_PMASK) {
812 case SADB_X_EXT_PRAND:
813 (void) read_random(pad, padding - 2);
815 case SADB_X_EXT_PZERO:
816 bzero(pad, padding - 2);
818 case SADB_X_EXT_PSEQ:
819 for (i = 0; i < padding - 2; i++)
824 /* Fix padding length and Next Protocol in padding itself. */
825 pad[padding - 2] = padding - 2;
826 m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
828 /* Fix Next Protocol in IPv4/IPv6 header. */
830 m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
832 /* Get crypto descriptors. */
833 crp = crypto_getreq(esph != NULL ? 2 : 1);
835 DPRINTF(("%s: failed to acquire crypto descriptors\n",
837 ESPSTAT_INC(esps_crypto);
842 /* IPsec-specific opaque crypto info. */
843 xd = malloc(sizeof(struct xform_data), M_XDATA, M_NOWAIT | M_ZERO);
846 DPRINTF(("%s: failed to allocate xform_data\n", __func__));
847 ESPSTAT_INC(esps_crypto);
852 crde = crp->crp_desc;
853 crda = crde->crd_next;
855 /* Encryption descriptor. */
856 crde->crd_skip = skip + hlen;
857 crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
858 crde->crd_flags = CRD_F_ENCRYPT;
859 crde->crd_inject = skip + hlen - sav->ivlen;
861 /* Encryption operation. */
862 crde->crd_alg = espx->type;
863 if (SAV_ISCTRORGCM(sav)) {
864 ivp = &crde->crd_iv[0];
866 /* GCM IV Format: RFC4106 4 */
867 /* CTR IV Format: RFC3686 4 */
868 /* Salt is last four bytes of key, RFC4106 8.1 */
869 /* Nonce is last four bytes of key, RFC3686 5.1 */
870 memcpy(ivp, sav->key_enc->key_data +
871 _KEYLEN(sav->key_enc) - 4, 4);
872 be64enc(&ivp[4], cntr);
873 if (SAV_ISCTR(sav)) {
874 /* Initial block counter is 1, RFC3686 4 */
875 /* XXXAE: should we use this only for first packet? */
876 be32enc(&ivp[sav->ivlen + 4], 1);
879 m_copyback(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
880 crde->crd_flags |= CRD_F_IV_EXPLICIT|CRD_F_IV_PRESENT;
883 /* Callback parameters */
887 xd->cryptoid = cryptoid;
890 /* Crypto operation descriptor. */
891 crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
892 crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
894 crp->crp_flags |= CRYPTO_F_ASYNC | CRYPTO_F_ASYNC_KEEPORDER;
895 crp->crp_buf = (caddr_t) m;
896 crp->crp_callback = esp_output_cb;
897 crp->crp_opaque = (caddr_t) xd;
898 crp->crp_session = cryptoid;
901 /* Authentication descriptor. */
902 crda->crd_alg = esph->type;
903 crda->crd_skip = skip;
905 crda->crd_len = 8; /* RFC4106 5, SPI + SN */
907 crda->crd_len = m->m_pkthdr.len - (skip + alen);
908 crda->crd_inject = m->m_pkthdr.len - alen;
911 return crypto_dispatch(crp);
920 * ESP output callback from the crypto driver.
923 esp_output_cb(struct cryptop *crp)
925 struct xform_data *xd;
926 struct secpolicy *sp;
927 struct secasvar *sav;
929 crypto_session_t cryptoid;
933 xd = (struct xform_data *) crp->crp_opaque;
934 CURVNET_SET(xd->vnet);
935 m = (struct mbuf *) crp->crp_buf;
939 cryptoid = xd->cryptoid;
941 /* Check for crypto errors. */
942 if (crp->crp_etype) {
943 if (crp->crp_etype == EAGAIN) {
944 /* Reset the session ID */
945 if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
946 crypto_freesession(cryptoid);
947 xd->cryptoid = crp->crp_session;
949 return (crypto_dispatch(crp));
951 ESPSTAT_INC(esps_noxform);
952 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
953 error = crp->crp_etype;
958 /* Shouldn't happen... */
960 ESPSTAT_INC(esps_crypto);
961 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
967 ESPSTAT_INC(esps_hist[sav->alg_enc]);
968 if (sav->tdb_authalgxform != NULL)
969 AHSTAT_INC(ahs_hist[sav->alg_auth]);
972 /* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
973 if (V_ipsec_integrity) {
974 static unsigned char ipseczeroes[AH_HMAC_MAXHASHLEN];
975 const struct auth_hash *esph;
978 * Corrupt HMAC if we want to test integrity verification of
981 esph = sav->tdb_authalgxform;
985 alen = xform_ah_authsize(esph);
986 m_copyback(m, m->m_pkthdr.len - alen,
992 /* NB: m is reclaimed by ipsec_process_done. */
993 error = ipsec_process_done(m, sp, sav, idx);
1005 static struct xformsw esp_xformsw = {
1007 .xf_name = "IPsec ESP",
1008 .xf_init = esp_init,
1009 .xf_zeroize = esp_zeroize,
1010 .xf_input = esp_input,
1011 .xf_output = esp_output,
1014 SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
1015 xform_attach, &esp_xformsw);
1016 SYSUNINIT(esp_xform_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
1017 xform_detach, &esp_xformsw);