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;
98 static struct timeval warninterval = { .tv_sec = 1, .tv_usec = 0 };
100 static int esp_input_cb(struct cryptop *op);
101 static int esp_output_cb(struct cryptop *crp);
104 esp_hdrsiz(struct secasvar *sav)
109 /*XXX not right for null algorithm--does it matter??*/
110 IPSEC_ASSERT(sav->tdb_encalgxform != NULL,
111 ("SA with null xform"));
112 if (sav->flags & SADB_X_EXT_OLD)
113 size = sizeof (struct esp);
115 size = sizeof (struct newesp);
116 size += sav->tdb_encalgxform->blocksize + 9;
117 /*XXX need alg check???*/
118 if (sav->tdb_authalgxform != NULL && sav->replay)
119 size += ah_hdrsiz(sav);
123 * + max iv length for CBC mode
125 * + sizeof (pad length field)
126 * + sizeof (next header field)
127 * + max icv supported.
129 size = sizeof (struct newesp) + EALG_MAX_BLOCK_LEN + 9 + 16;
135 * esp_init() is called when an SPI is being set up.
138 esp_init(struct secasvar *sav, struct xformsw *xsp)
140 const struct enc_xform *txform;
141 struct cryptoini cria, crie;
145 txform = enc_algorithm_lookup(sav->alg_enc);
146 if (txform == NULL) {
147 DPRINTF(("%s: unsupported encryption algorithm %d\n",
148 __func__, sav->alg_enc));
151 if (sav->key_enc == NULL) {
152 DPRINTF(("%s: no encoding key for %s algorithm\n",
153 __func__, txform->name));
156 if ((sav->flags & (SADB_X_EXT_OLD | SADB_X_EXT_IV4B)) ==
158 DPRINTF(("%s: 4-byte IV not supported with protocol\n",
163 switch (sav->alg_enc) {
164 case SADB_EALG_DESCBC:
165 if (ratecheck(&deswarn, &warninterval))
166 gone_in(13, "DES cipher for IPsec");
168 case SADB_X_EALG_BLOWFISHCBC:
169 if (ratecheck(&blfwarn, &warninterval))
170 gone_in(13, "Blowfish cipher for IPsec");
172 case SADB_X_EALG_CAST128CBC:
173 if (ratecheck(&castwarn, &warninterval))
174 gone_in(13, "CAST cipher for IPsec");
176 case SADB_X_EALG_CAMELLIACBC:
177 if (ratecheck(&camelliawarn, &warninterval))
178 gone_in(13, "Camellia cipher for IPsec");
182 /* subtract off the salt, RFC4106, 8.1 and RFC3686, 5.1 */
183 keylen = _KEYLEN(sav->key_enc) - SAV_ISCTRORGCM(sav) * 4;
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,
192 if (SAV_ISCTRORGCM(sav))
193 sav->ivlen = 8; /* RFC4106 3.1 and RFC3686 3.1 */
195 sav->ivlen = txform->ivsize;
198 * Setup AH-related state.
200 if (sav->alg_auth != 0) {
201 error = ah_init0(sav, xsp, &cria);
206 /* NB: override anything set in ah_init0 */
207 sav->tdb_xform = xsp;
208 sav->tdb_encalgxform = txform;
211 * Whenever AES-GCM is used for encryption, one
212 * of the AES authentication algorithms is chosen
213 * as well, based on the key size.
215 if (sav->alg_enc == SADB_X_EALG_AESGCM16) {
217 case AES_128_GMAC_KEY_LEN:
218 sav->alg_auth = SADB_X_AALG_AES128GMAC;
219 sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_128;
221 case AES_192_GMAC_KEY_LEN:
222 sav->alg_auth = SADB_X_AALG_AES192GMAC;
223 sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_192;
225 case AES_256_GMAC_KEY_LEN:
226 sav->alg_auth = SADB_X_AALG_AES256GMAC;
227 sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_256;
230 DPRINTF(("%s: invalid key length %u"
231 "for algorithm %s\n", __func__,
232 keylen, txform->name));
235 bzero(&cria, sizeof(cria));
236 cria.cri_alg = sav->tdb_authalgxform->type;
237 cria.cri_key = sav->key_enc->key_data;
238 cria.cri_klen = _KEYBITS(sav->key_enc) - SAV_ISGCM(sav) * 32;
241 /* Initialize crypto session. */
242 bzero(&crie, sizeof(crie));
243 crie.cri_alg = sav->tdb_encalgxform->type;
244 crie.cri_key = sav->key_enc->key_data;
245 crie.cri_klen = _KEYBITS(sav->key_enc) - SAV_ISCTRORGCM(sav) * 32;
247 if (sav->tdb_authalgxform && sav->tdb_encalgxform) {
248 /* init both auth & enc */
249 crie.cri_next = &cria;
250 error = crypto_newsession(&sav->tdb_cryptoid,
251 &crie, V_crypto_support);
252 } else if (sav->tdb_encalgxform) {
253 error = crypto_newsession(&sav->tdb_cryptoid,
254 &crie, V_crypto_support);
255 } else if (sav->tdb_authalgxform) {
256 error = crypto_newsession(&sav->tdb_cryptoid,
257 &cria, V_crypto_support);
259 /* XXX cannot happen? */
260 DPRINTF(("%s: no encoding OR authentication xform!\n",
271 esp_zeroize(struct secasvar *sav)
273 /* NB: ah_zerorize free's the crypto session state */
274 int error = ah_zeroize(sav);
277 bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
278 sav->tdb_encalgxform = NULL;
279 sav->tdb_xform = NULL;
284 * ESP input processing, called (eventually) through the protocol switch.
287 esp_input(struct mbuf *m, struct secasvar *sav, int skip, int protoff)
289 IPSEC_DEBUG_DECLARE(char buf[128]);
290 const struct auth_hash *esph;
291 const struct enc_xform *espx;
292 struct xform_data *xd;
293 struct cryptodesc *crde;
297 crypto_session_t cryptoid;
298 int alen, error, hlen, plen;
300 IPSEC_ASSERT(sav != NULL, ("null SA"));
301 IPSEC_ASSERT(sav->tdb_encalgxform != NULL, ("null encoding xform"));
304 /* Valid IP Packet length ? */
305 if ( (skip&3) || (m->m_pkthdr.len&3) ){
306 DPRINTF(("%s: misaligned packet, skip %u pkt len %u",
307 __func__, skip, m->m_pkthdr.len));
308 ESPSTAT_INC(esps_badilen);
311 /* XXX don't pullup, just copy header */
312 IP6_EXTHDR_GET(esp, struct newesp *, m, skip, sizeof (struct newesp));
314 esph = sav->tdb_authalgxform;
315 espx = sav->tdb_encalgxform;
317 /* Determine the ESP header and auth length */
318 if (sav->flags & SADB_X_EXT_OLD)
319 hlen = sizeof (struct esp) + sav->ivlen;
321 hlen = sizeof (struct newesp) + sav->ivlen;
323 alen = xform_ah_authsize(esph);
326 * Verify payload length is multiple of encryption algorithm
329 * NB: This works for the null algorithm because the blocksize
330 * is 4 and all packets must be 4-byte aligned regardless
333 plen = m->m_pkthdr.len - (skip + hlen + alen);
334 if ((plen & (espx->blocksize - 1)) || (plen <= 0)) {
335 DPRINTF(("%s: payload of %d octets not a multiple of %d octets,"
336 " SA %s/%08lx\n", __func__, plen, espx->blocksize,
337 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
338 (u_long)ntohl(sav->spi)));
339 ESPSTAT_INC(esps_badilen);
344 * Check sequence number.
347 if (esph != NULL && sav->replay != NULL && sav->replay->wsize != 0) {
348 if (ipsec_chkreplay(ntohl(esp->esp_seq), sav) == 0) {
349 SECASVAR_UNLOCK(sav);
350 DPRINTF(("%s: packet replay check for %s\n", __func__,
351 ipsec_sa2str(sav, buf, sizeof(buf))));
352 ESPSTAT_INC(esps_replay);
357 cryptoid = sav->tdb_cryptoid;
358 SECASVAR_UNLOCK(sav);
360 /* Update the counters */
361 ESPSTAT_ADD(esps_ibytes, m->m_pkthdr.len - (skip + hlen + alen));
363 /* Get crypto descriptors */
364 crp = crypto_getreq(esph && espx ? 2 : 1);
366 DPRINTF(("%s: failed to acquire crypto descriptors\n",
368 ESPSTAT_INC(esps_crypto);
373 /* Get IPsec-specific opaque pointer */
374 xd = malloc(sizeof(*xd) + alen, M_XDATA, M_NOWAIT | M_ZERO);
376 DPRINTF(("%s: failed to allocate xform_data\n", __func__));
377 ESPSTAT_INC(esps_crypto);
384 struct cryptodesc *crda = crp->crp_desc;
386 IPSEC_ASSERT(crda != NULL, ("null ah crypto descriptor"));
388 /* Authentication descriptor */
389 crda->crd_skip = skip;
391 crda->crd_len = 8; /* RFC4106 5, SPI + SN */
393 crda->crd_len = m->m_pkthdr.len - (skip + alen);
394 crda->crd_inject = m->m_pkthdr.len - alen;
396 crda->crd_alg = esph->type;
398 /* Copy the authenticator */
399 m_copydata(m, m->m_pkthdr.len - alen, alen,
402 /* Chain authentication request */
403 crde = crda->crd_next;
405 crde = crp->crp_desc;
408 /* Crypto operation descriptor */
409 crp->crp_ilen = m->m_pkthdr.len; /* Total input length */
410 crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
412 crp->crp_flags |= CRYPTO_F_ASYNC | CRYPTO_F_ASYNC_KEEPORDER;
413 crp->crp_buf = (caddr_t) m;
414 crp->crp_callback = esp_input_cb;
415 crp->crp_session = cryptoid;
416 crp->crp_opaque = (caddr_t) xd;
418 /* These are passed as-is to the callback */
420 xd->protoff = protoff;
422 xd->cryptoid = cryptoid;
425 /* Decryption descriptor */
426 IPSEC_ASSERT(crde != NULL, ("null esp crypto descriptor"));
427 crde->crd_skip = skip + hlen;
428 crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
429 crde->crd_inject = skip + hlen - sav->ivlen;
431 if (SAV_ISCTRORGCM(sav)) {
432 ivp = &crde->crd_iv[0];
434 /* GCM IV Format: RFC4106 4 */
435 /* CTR IV Format: RFC3686 4 */
436 /* Salt is last four bytes of key, RFC4106 8.1 */
437 /* Nonce is last four bytes of key, RFC3686 5.1 */
438 memcpy(ivp, sav->key_enc->key_data +
439 _KEYLEN(sav->key_enc) - 4, 4);
441 if (SAV_ISCTR(sav)) {
442 /* Initial block counter is 1, RFC3686 4 */
443 be32enc(&ivp[sav->ivlen + 4], 1);
446 m_copydata(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
447 crde->crd_flags |= CRD_F_IV_EXPLICIT;
450 crde->crd_alg = espx->type;
452 return (crypto_dispatch(crp));
460 * ESP input callback from the crypto driver.
463 esp_input_cb(struct cryptop *crp)
465 IPSEC_DEBUG_DECLARE(char buf[128]);
466 u_int8_t lastthree[3], aalg[AH_HMAC_MAXHASHLEN];
467 const struct auth_hash *esph;
469 struct cryptodesc *crd;
470 struct xform_data *xd;
471 struct secasvar *sav;
472 struct secasindex *saidx;
474 crypto_session_t cryptoid;
475 int hlen, skip, protoff, error, alen;
478 IPSEC_ASSERT(crd != NULL, ("null crypto descriptor!"));
480 m = (struct mbuf *) crp->crp_buf;
481 xd = (struct xform_data *) crp->crp_opaque;
482 CURVNET_SET(xd->vnet);
485 protoff = xd->protoff;
486 cryptoid = xd->cryptoid;
487 saidx = &sav->sah->saidx;
488 esph = sav->tdb_authalgxform;
490 /* Check for crypto errors */
491 if (crp->crp_etype) {
492 if (crp->crp_etype == EAGAIN) {
493 /* Reset the session ID */
494 if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
495 crypto_freesession(cryptoid);
496 xd->cryptoid = crp->crp_session;
498 return (crypto_dispatch(crp));
500 ESPSTAT_INC(esps_noxform);
501 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
502 error = crp->crp_etype;
506 /* Shouldn't happen... */
508 ESPSTAT_INC(esps_crypto);
509 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
513 ESPSTAT_INC(esps_hist[sav->alg_enc]);
515 /* If authentication was performed, check now. */
517 alen = xform_ah_authsize(esph);
518 AHSTAT_INC(ahs_hist[sav->alg_auth]);
519 /* Copy the authenticator from the packet */
520 m_copydata(m, m->m_pkthdr.len - alen, alen, aalg);
521 ptr = (caddr_t) (xd + 1);
523 /* Verify authenticator */
524 if (timingsafe_bcmp(ptr, aalg, alen) != 0) {
525 DPRINTF(("%s: authentication hash mismatch for "
526 "packet in SA %s/%08lx\n", __func__,
527 ipsec_address(&saidx->dst, buf, sizeof(buf)),
528 (u_long) ntohl(sav->spi)));
529 ESPSTAT_INC(esps_badauth);
533 m->m_flags |= M_AUTHIPDGM;
534 /* Remove trailing authenticator */
538 /* Release the crypto descriptors */
539 free(xd, M_XDATA), xd = NULL;
540 crypto_freereq(crp), crp = NULL;
543 * Packet is now decrypted.
545 m->m_flags |= M_DECRYPTED;
548 * Update replay sequence number, if appropriate.
553 m_copydata(m, skip + offsetof(struct newesp, esp_seq),
554 sizeof (seq), (caddr_t) &seq);
556 if (ipsec_updatereplay(ntohl(seq), sav)) {
557 SECASVAR_UNLOCK(sav);
558 DPRINTF(("%s: packet replay check for %s\n", __func__,
559 ipsec_sa2str(sav, buf, sizeof(buf))));
560 ESPSTAT_INC(esps_replay);
564 SECASVAR_UNLOCK(sav);
567 /* Determine the ESP header length */
568 if (sav->flags & SADB_X_EXT_OLD)
569 hlen = sizeof (struct esp) + sav->ivlen;
571 hlen = sizeof (struct newesp) + sav->ivlen;
573 /* Remove the ESP header and IV from the mbuf. */
574 error = m_striphdr(m, skip, hlen);
576 ESPSTAT_INC(esps_hdrops);
577 DPRINTF(("%s: bad mbuf chain, SA %s/%08lx\n", __func__,
578 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
579 (u_long) ntohl(sav->spi)));
583 /* Save the last three bytes of decrypted data */
584 m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
586 /* Verify pad length */
587 if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
588 ESPSTAT_INC(esps_badilen);
589 DPRINTF(("%s: invalid padding length %d for %u byte packet "
590 "in SA %s/%08lx\n", __func__, lastthree[1],
591 m->m_pkthdr.len - skip,
592 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
593 (u_long) ntohl(sav->spi)));
598 /* Verify correct decryption by checking the last padding bytes */
599 if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
600 if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
601 ESPSTAT_INC(esps_badenc);
602 DPRINTF(("%s: decryption failed for packet in "
603 "SA %s/%08lx\n", __func__, ipsec_address(
604 &sav->sah->saidx.dst, buf, sizeof(buf)),
605 (u_long) ntohl(sav->spi)));
611 /* Trim the mbuf chain to remove trailing authenticator and padding */
612 m_adj(m, -(lastthree[1] + 2));
614 /* Restore the Next Protocol field */
615 m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
617 switch (saidx->dst.sa.sa_family) {
620 error = ipsec6_common_input_cb(m, sav, skip, protoff);
625 error = ipsec4_common_input_cb(m, sav, skip, protoff);
629 panic("%s: Unexpected address family: %d saidx=%p", __func__,
630 saidx->dst.sa.sa_family, saidx);
647 * ESP output routine, called by ipsec[46]_perform_request().
650 esp_output(struct mbuf *m, struct secpolicy *sp, struct secasvar *sav,
651 u_int idx, int skip, int protoff)
653 IPSEC_DEBUG_DECLARE(char buf[IPSEC_ADDRSTRLEN]);
654 struct cryptodesc *crde = NULL, *crda = NULL;
656 const struct auth_hash *esph;
657 const struct enc_xform *espx;
658 struct mbuf *mo = NULL;
659 struct xform_data *xd;
660 struct secasindex *saidx;
664 crypto_session_t cryptoid;
665 int hlen, rlen, padding, blks, alen, i, roff;
666 int error, maxpacketsize;
669 IPSEC_ASSERT(sav != NULL, ("null SA"));
670 esph = sav->tdb_authalgxform;
671 espx = sav->tdb_encalgxform;
672 IPSEC_ASSERT(espx != NULL, ("null encoding xform"));
674 if (sav->flags & SADB_X_EXT_OLD)
675 hlen = sizeof (struct esp) + sav->ivlen;
677 hlen = sizeof (struct newesp) + sav->ivlen;
679 rlen = m->m_pkthdr.len - skip; /* Raw payload length. */
681 * RFC4303 2.4 Requires 4 byte alignment.
683 blks = MAX(4, espx->blocksize); /* Cipher blocksize */
685 /* XXX clamp padding length a la KAME??? */
686 padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
688 alen = xform_ah_authsize(esph);
690 ESPSTAT_INC(esps_output);
692 saidx = &sav->sah->saidx;
693 /* Check for maximum packet size violations. */
694 switch (saidx->dst.sa.sa_family) {
697 maxpacketsize = IP_MAXPACKET;
702 maxpacketsize = IPV6_MAXPACKET;
706 DPRINTF(("%s: unknown/unsupported protocol "
707 "family %d, SA %s/%08lx\n", __func__,
708 saidx->dst.sa.sa_family, ipsec_address(&saidx->dst,
709 buf, sizeof(buf)), (u_long) ntohl(sav->spi)));
710 ESPSTAT_INC(esps_nopf);
711 error = EPFNOSUPPORT;
715 DPRINTF(("%s: skip %d hlen %d rlen %d padding %d alen %d blksd %d\n",
716 __func__, skip, hlen, rlen, padding, alen, blks)); */
717 if (skip + hlen + rlen + padding + alen > maxpacketsize) {
718 DPRINTF(("%s: packet in SA %s/%08lx got too big "
719 "(len %u, max len %u)\n", __func__,
720 ipsec_address(&saidx->dst, buf, sizeof(buf)),
721 (u_long) ntohl(sav->spi),
722 skip + hlen + rlen + padding + alen, maxpacketsize));
723 ESPSTAT_INC(esps_toobig);
728 /* Update the counters. */
729 ESPSTAT_ADD(esps_obytes, m->m_pkthdr.len - skip);
731 m = m_unshare(m, M_NOWAIT);
733 DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
734 ipsec_address(&saidx->dst, buf, sizeof(buf)),
735 (u_long) ntohl(sav->spi)));
736 ESPSTAT_INC(esps_hdrops);
741 /* Inject ESP header. */
742 mo = m_makespace(m, skip, hlen, &roff);
744 DPRINTF(("%s: %u byte ESP hdr inject failed for SA %s/%08lx\n",
745 __func__, hlen, ipsec_address(&saidx->dst, buf,
746 sizeof(buf)), (u_long) ntohl(sav->spi)));
747 ESPSTAT_INC(esps_hdrops); /* XXX diffs from openbsd */
752 /* Initialize ESP header. */
753 bcopy((caddr_t) &sav->spi, mtod(mo, caddr_t) + roff,
760 /* Emulate replay attack when ipsec_replay is TRUE. */
763 sav->replay->count++;
764 replay = htonl(sav->replay->count);
766 bcopy((caddr_t) &replay, mtod(mo, caddr_t) + roff +
767 sizeof(uint32_t), sizeof(uint32_t));
769 cryptoid = sav->tdb_cryptoid;
770 if (SAV_ISCTRORGCM(sav))
772 SECASVAR_UNLOCK(sav);
775 * Add padding -- better to do it ourselves than use the crypto engine,
776 * although if/when we support compression, we'd have to do that.
778 pad = (u_char *) m_pad(m, padding + alen);
780 DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
781 ipsec_address(&saidx->dst, buf, sizeof(buf)),
782 (u_long) ntohl(sav->spi)));
783 m = NULL; /* NB: free'd by m_pad */
789 * Add padding: random, zero, or self-describing.
790 * XXX catch unexpected setting
792 switch (sav->flags & SADB_X_EXT_PMASK) {
793 case SADB_X_EXT_PRAND:
794 arc4random_buf(pad, padding - 2);
796 case SADB_X_EXT_PZERO:
797 bzero(pad, padding - 2);
799 case SADB_X_EXT_PSEQ:
800 for (i = 0; i < padding - 2; i++)
805 /* Fix padding length and Next Protocol in padding itself. */
806 pad[padding - 2] = padding - 2;
807 m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
809 /* Fix Next Protocol in IPv4/IPv6 header. */
811 m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
813 /* Get crypto descriptors. */
814 crp = crypto_getreq(esph != NULL ? 2 : 1);
816 DPRINTF(("%s: failed to acquire crypto descriptors\n",
818 ESPSTAT_INC(esps_crypto);
823 /* IPsec-specific opaque crypto info. */
824 xd = malloc(sizeof(struct xform_data), M_XDATA, M_NOWAIT | M_ZERO);
827 DPRINTF(("%s: failed to allocate xform_data\n", __func__));
828 ESPSTAT_INC(esps_crypto);
833 crde = crp->crp_desc;
834 crda = crde->crd_next;
836 /* Encryption descriptor. */
837 crde->crd_skip = skip + hlen;
838 crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
839 crde->crd_flags = CRD_F_ENCRYPT;
840 crde->crd_inject = skip + hlen - sav->ivlen;
842 /* Encryption operation. */
843 crde->crd_alg = espx->type;
844 if (SAV_ISCTRORGCM(sav)) {
845 ivp = &crde->crd_iv[0];
847 /* GCM IV Format: RFC4106 4 */
848 /* CTR IV Format: RFC3686 4 */
849 /* Salt is last four bytes of key, RFC4106 8.1 */
850 /* Nonce is last four bytes of key, RFC3686 5.1 */
851 memcpy(ivp, sav->key_enc->key_data +
852 _KEYLEN(sav->key_enc) - 4, 4);
853 be64enc(&ivp[4], cntr);
854 if (SAV_ISCTR(sav)) {
855 /* Initial block counter is 1, RFC3686 4 */
856 /* XXXAE: should we use this only for first packet? */
857 be32enc(&ivp[sav->ivlen + 4], 1);
860 m_copyback(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
861 crde->crd_flags |= CRD_F_IV_EXPLICIT|CRD_F_IV_PRESENT;
864 /* Callback parameters */
868 xd->cryptoid = cryptoid;
871 /* Crypto operation descriptor. */
872 crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
873 crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
875 crp->crp_flags |= CRYPTO_F_ASYNC | CRYPTO_F_ASYNC_KEEPORDER;
876 crp->crp_buf = (caddr_t) m;
877 crp->crp_callback = esp_output_cb;
878 crp->crp_opaque = (caddr_t) xd;
879 crp->crp_session = cryptoid;
882 /* Authentication descriptor. */
883 crda->crd_alg = esph->type;
884 crda->crd_skip = skip;
886 crda->crd_len = 8; /* RFC4106 5, SPI + SN */
888 crda->crd_len = m->m_pkthdr.len - (skip + alen);
889 crda->crd_inject = m->m_pkthdr.len - alen;
892 return crypto_dispatch(crp);
901 * ESP output callback from the crypto driver.
904 esp_output_cb(struct cryptop *crp)
906 struct xform_data *xd;
907 struct secpolicy *sp;
908 struct secasvar *sav;
910 crypto_session_t cryptoid;
914 xd = (struct xform_data *) crp->crp_opaque;
915 CURVNET_SET(xd->vnet);
916 m = (struct mbuf *) crp->crp_buf;
920 cryptoid = xd->cryptoid;
922 /* Check for crypto errors. */
923 if (crp->crp_etype) {
924 if (crp->crp_etype == EAGAIN) {
925 /* Reset the session ID */
926 if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
927 crypto_freesession(cryptoid);
928 xd->cryptoid = crp->crp_session;
930 return (crypto_dispatch(crp));
932 ESPSTAT_INC(esps_noxform);
933 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
934 error = crp->crp_etype;
939 /* Shouldn't happen... */
941 ESPSTAT_INC(esps_crypto);
942 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
948 ESPSTAT_INC(esps_hist[sav->alg_enc]);
949 if (sav->tdb_authalgxform != NULL)
950 AHSTAT_INC(ahs_hist[sav->alg_auth]);
953 /* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
954 if (V_ipsec_integrity) {
955 static unsigned char ipseczeroes[AH_HMAC_MAXHASHLEN];
956 const struct auth_hash *esph;
959 * Corrupt HMAC if we want to test integrity verification of
962 esph = sav->tdb_authalgxform;
966 alen = xform_ah_authsize(esph);
967 m_copyback(m, m->m_pkthdr.len - alen,
973 /* NB: m is reclaimed by ipsec_process_done. */
974 error = ipsec_process_done(m, sp, sav, idx);
986 static struct xformsw esp_xformsw = {
988 .xf_name = "IPsec ESP",
990 .xf_zeroize = esp_zeroize,
991 .xf_input = esp_input,
992 .xf_output = esp_output,
995 SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
996 xform_attach, &esp_xformsw);
997 SYSUNINIT(esp_xform_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
998 xform_detach, &esp_xformsw);