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"
40 #include "opt_ipsec.h"
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/malloc.h>
46 #include <sys/socket.h>
47 #include <sys/syslog.h>
48 #include <sys/kernel.h>
50 #include <sys/random.h>
51 #include <sys/mutex.h>
52 #include <sys/sysctl.h>
53 #include <sys/mutex.h>
54 #include <machine/atomic.h>
59 #include <netinet/in.h>
60 #include <netinet/in_systm.h>
61 #include <netinet/ip.h>
62 #include <netinet/ip_ecn.h>
63 #include <netinet/ip6.h>
65 #include <netipsec/ipsec.h>
66 #include <netipsec/ah.h>
67 #include <netipsec/ah_var.h>
68 #include <netipsec/esp.h>
69 #include <netipsec/esp_var.h>
70 #include <netipsec/xform.h>
73 #include <netinet6/ip6_var.h>
74 #include <netipsec/ipsec6.h>
75 #include <netinet6/ip6_ecn.h>
78 #include <netipsec/key.h>
79 #include <netipsec/key_debug.h>
81 #include <opencrypto/cryptodev.h>
82 #include <opencrypto/xform.h>
86 VNET_DEFINE(int, esp_enable) = 1;
87 VNET_DEFINE_STATIC(int, esp_ctr_compatibility) = 1;
88 #define V_esp_ctr_compatibility VNET(esp_ctr_compatibility)
89 VNET_PCPUSTAT_DEFINE(struct espstat, espstat);
90 VNET_PCPUSTAT_SYSINIT(espstat);
93 VNET_PCPUSTAT_SYSUNINIT(espstat);
96 SYSCTL_DECL(_net_inet_esp);
97 SYSCTL_INT(_net_inet_esp, OID_AUTO, esp_enable,
98 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(esp_enable), 0, "");
99 SYSCTL_INT(_net_inet_esp, OID_AUTO, ctr_compatibility,
100 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(esp_ctr_compatibility), 0,
101 "Align AES-CTR encrypted transmitted frames to blocksize");
102 SYSCTL_VNET_PCPUSTAT(_net_inet_esp, IPSECCTL_STATS, stats,
103 struct espstat, espstat,
104 "ESP statistics (struct espstat, netipsec/esp_var.h");
106 static MALLOC_DEFINE(M_ESP, "esp", "IPsec ESP");
108 static int esp_input_cb(struct cryptop *op);
109 static int esp_output_cb(struct cryptop *crp);
112 esp_hdrsiz(struct secasvar *sav)
117 /*XXX not right for null algorithm--does it matter??*/
118 IPSEC_ASSERT(sav->tdb_encalgxform != NULL,
119 ("SA with null xform"));
120 if (sav->flags & SADB_X_EXT_OLD)
121 size = sizeof (struct esp);
123 size = sizeof (struct newesp);
124 size += sav->tdb_encalgxform->blocksize + 9;
125 /*XXX need alg check???*/
126 if (sav->tdb_authalgxform != NULL && sav->replay)
127 size += ah_hdrsiz(sav);
131 * + max iv length for CBC mode
133 * + sizeof (pad length field)
134 * + sizeof (next header field)
135 * + max icv supported.
137 size = sizeof (struct newesp) + EALG_MAX_BLOCK_LEN + 9 + 16;
143 * esp_init() is called when an SPI is being set up.
146 esp_init(struct secasvar *sav, struct xformsw *xsp)
148 const struct enc_xform *txform;
149 struct crypto_session_params csp;
153 txform = enc_algorithm_lookup(sav->alg_enc);
154 if (txform == NULL) {
155 DPRINTF(("%s: unsupported encryption algorithm %d\n",
156 __func__, sav->alg_enc));
159 if (sav->key_enc == NULL) {
160 DPRINTF(("%s: no encoding key for %s algorithm\n",
161 __func__, txform->name));
164 if ((sav->flags & (SADB_X_EXT_OLD | SADB_X_EXT_IV4B)) ==
166 DPRINTF(("%s: 4-byte IV not supported with protocol\n",
171 /* subtract off the salt, RFC4106, 8.1 and RFC3686, 5.1 */
172 keylen = _KEYLEN(sav->key_enc) - SAV_ISCTRORGCM(sav) * 4;
173 if (txform->minkey > keylen || keylen > txform->maxkey) {
174 DPRINTF(("%s: invalid key length %u, must be in the range "
175 "[%u..%u] for algorithm %s\n", __func__,
176 keylen, txform->minkey, txform->maxkey,
181 if (SAV_ISCTRORGCM(sav))
182 sav->ivlen = 8; /* RFC4106 3.1 and RFC3686 3.1 */
184 sav->ivlen = txform->ivsize;
186 memset(&csp, 0, sizeof(csp));
189 * Setup AH-related state.
191 if (sav->alg_auth != 0) {
192 error = ah_init0(sav, xsp, &csp);
197 /* NB: override anything set in ah_init0 */
198 sav->tdb_xform = xsp;
199 sav->tdb_encalgxform = txform;
202 * Whenever AES-GCM is used for encryption, one
203 * of the AES authentication algorithms is chosen
204 * as well, based on the key size.
206 if (sav->alg_enc == SADB_X_EALG_AESGCM16) {
208 case AES_128_GMAC_KEY_LEN:
209 sav->alg_auth = SADB_X_AALG_AES128GMAC;
210 sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_128;
212 case AES_192_GMAC_KEY_LEN:
213 sav->alg_auth = SADB_X_AALG_AES192GMAC;
214 sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_192;
216 case AES_256_GMAC_KEY_LEN:
217 sav->alg_auth = SADB_X_AALG_AES256GMAC;
218 sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_256;
221 DPRINTF(("%s: invalid key length %u"
222 "for algorithm %s\n", __func__,
223 keylen, txform->name));
226 csp.csp_mode = CSP_MODE_AEAD;
227 if (sav->flags & SADB_X_SAFLAGS_ESN)
228 csp.csp_flags |= CSP_F_SEPARATE_AAD;
229 } else if (sav->alg_auth != 0) {
230 csp.csp_mode = CSP_MODE_ETA;
231 if (sav->flags & SADB_X_SAFLAGS_ESN)
232 csp.csp_flags |= CSP_F_ESN;
234 csp.csp_mode = CSP_MODE_CIPHER;
236 /* Initialize crypto session. */
237 csp.csp_cipher_alg = sav->tdb_encalgxform->type;
238 if (csp.csp_cipher_alg != CRYPTO_NULL_CBC) {
239 csp.csp_cipher_key = sav->key_enc->key_data;
240 csp.csp_cipher_klen = _KEYBITS(sav->key_enc) / 8 -
241 SAV_ISCTRORGCM(sav) * 4;
243 csp.csp_ivlen = txform->ivsize;
245 error = crypto_newsession(&sav->tdb_cryptoid, &csp, V_crypto_support);
250 esp_cleanup(struct secasvar *sav)
253 crypto_freesession(sav->tdb_cryptoid);
254 sav->tdb_cryptoid = NULL;
255 sav->tdb_authalgxform = NULL;
256 sav->tdb_encalgxform = NULL;
260 * ESP input processing, called (eventually) through the protocol switch.
263 esp_input(struct mbuf *m, struct secasvar *sav, int skip, int protoff)
265 IPSEC_DEBUG_DECLARE(char buf[128]);
266 const struct auth_hash *esph;
267 const struct enc_xform *espx;
268 struct xform_data *xd;
272 crypto_session_t cryptoid;
273 int alen, error, hlen, plen;
275 const struct crypto_session_params *csp;
277 IPSEC_ASSERT(sav != NULL, ("null SA"));
278 IPSEC_ASSERT(sav->tdb_encalgxform != NULL, ("null encoding xform"));
281 /* Valid IP Packet length ? */
282 if ( (skip&3) || (m->m_pkthdr.len&3) ){
283 DPRINTF(("%s: misaligned packet, skip %u pkt len %u",
284 __func__, skip, m->m_pkthdr.len));
285 ESPSTAT_INC(esps_badilen);
289 if (m->m_len < skip + sizeof(*esp)) {
290 m = m_pullup(m, skip + sizeof(*esp));
292 DPRINTF(("%s: cannot pullup header\n", __func__));
293 ESPSTAT_INC(esps_hdrops); /*XXX*/
298 esp = (struct newesp *)(mtod(m, caddr_t) + skip);
300 esph = sav->tdb_authalgxform;
301 espx = sav->tdb_encalgxform;
303 /* Determine the ESP header and auth length */
304 if (sav->flags & SADB_X_EXT_OLD)
305 hlen = sizeof (struct esp) + sav->ivlen;
307 hlen = sizeof (struct newesp) + sav->ivlen;
309 alen = xform_ah_authsize(esph);
312 * Verify payload length is multiple of encryption algorithm
315 * NB: This works for the null algorithm because the blocksize
316 * is 4 and all packets must be 4-byte aligned regardless
319 plen = m->m_pkthdr.len - (skip + hlen + alen);
320 if ((plen & (espx->blocksize - 1)) || (plen <= 0)) {
321 DPRINTF(("%s: payload of %d octets not a multiple of %d octets,"
322 " SA %s/%08lx\n", __func__, plen, espx->blocksize,
323 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
324 (u_long)ntohl(sav->spi)));
325 ESPSTAT_INC(esps_badilen);
330 * Check sequence number.
333 if (esph != NULL && sav->replay != NULL && sav->replay->wsize != 0) {
334 if (ipsec_chkreplay(ntohl(esp->esp_seq), &seqh, sav) == 0) {
335 SECASVAR_UNLOCK(sav);
336 DPRINTF(("%s: packet replay check for %s\n", __func__,
337 ipsec_sa2str(sav, buf, sizeof(buf))));
338 ESPSTAT_INC(esps_replay);
344 cryptoid = sav->tdb_cryptoid;
345 SECASVAR_UNLOCK(sav);
347 /* Update the counters */
348 ESPSTAT_ADD(esps_ibytes, m->m_pkthdr.len - (skip + hlen + alen));
350 /* Get crypto descriptors */
351 crp = crypto_getreq(cryptoid, M_NOWAIT);
353 DPRINTF(("%s: failed to acquire crypto descriptors\n",
355 ESPSTAT_INC(esps_crypto);
360 /* Get IPsec-specific opaque pointer */
361 xd = malloc(sizeof(*xd), M_ESP, M_NOWAIT | M_ZERO);
363 DPRINTF(("%s: failed to allocate xform_data\n", __func__));
368 crp->crp_op = CRYPTO_OP_VERIFY_DIGEST;
370 crp->crp_aad_length = 8; /* RFC4106 5, SPI + SN */
372 crp->crp_aad_length = hlen;
374 csp = crypto_get_params(crp->crp_session);
375 if ((csp->csp_flags & CSP_F_SEPARATE_AAD) &&
376 (sav->replay != NULL) && (sav->replay->wsize != 0)) {
379 crp->crp_aad_length += sizeof(seqh);
380 crp->crp_aad = malloc(crp->crp_aad_length, M_ESP, M_NOWAIT);
381 if (crp->crp_aad == NULL) {
382 DPRINTF(("%s: failed to allocate xform_data\n",
388 m_copydata(m, skip, SPI_SIZE, crp->crp_aad);
392 bcopy(&seqh, (char *)crp->crp_aad + aad_skip, sizeof(seqh));
393 aad_skip += sizeof(seqh);
396 if (crp->crp_aad_length - aad_skip > 0)
397 m_copydata(m, skip + SPI_SIZE,
398 crp->crp_aad_length - aad_skip,
399 (char *)crp->crp_aad + aad_skip);
401 crp->crp_aad_start = skip;
403 if (csp->csp_flags & CSP_F_ESN &&
404 sav->replay != NULL && sav->replay->wsize != 0)
405 memcpy(crp->crp_esn, &seqh, sizeof(seqh));
407 crp->crp_digest_start = m->m_pkthdr.len - alen;
410 /* Crypto operation descriptor */
411 crp->crp_flags = CRYPTO_F_CBIFSYNC;
413 crp->crp_flags |= CRYPTO_F_ASYNC | CRYPTO_F_ASYNC_KEEPORDER;
414 crypto_use_mbuf(crp, m);
415 crp->crp_callback = esp_input_cb;
416 crp->crp_opaque = xd;
418 /* These are passed as-is to the callback */
420 xd->protoff = protoff;
422 xd->cryptoid = cryptoid;
425 /* Decryption descriptor */
426 crp->crp_op |= CRYPTO_OP_DECRYPT;
427 crp->crp_payload_start = skip + hlen;
428 crp->crp_payload_length = m->m_pkthdr.len - (skip + hlen + alen);
430 /* Generate or read cipher IV. */
431 if (SAV_ISCTRORGCM(sav)) {
432 ivp = &crp->crp_iv[0];
435 * AES-GCM and AES-CTR use similar cipher IV formats
436 * defined in RFC 4106 section 4 and RFC 3686 section
439 * The first 4 bytes of the cipher IV contain an
440 * implicit salt, or nonce, obtained from the last 4
441 * bytes of the encryption key. The next 8 bytes hold
442 * an explicit IV unique to each packet. This
443 * explicit IV is used as the ESP IV for the packet.
444 * The last 4 bytes hold a big-endian block counter
445 * incremented for each block. For AES-GCM, the block
446 * counter's initial value is defined as part of the
447 * algorithm. For AES-CTR, the block counter's
448 * initial value for each packet is defined as 1 by
451 * ------------------------------------------
452 * | Salt | Explicit ESP IV | Block Counter |
453 * ------------------------------------------
454 * 4 bytes 8 bytes 4 bytes
456 memcpy(ivp, sav->key_enc->key_data +
457 _KEYLEN(sav->key_enc) - 4, 4);
458 m_copydata(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
459 if (SAV_ISCTR(sav)) {
460 be32enc(&ivp[sav->ivlen + 4], 1);
462 crp->crp_flags |= CRYPTO_F_IV_SEPARATE;
463 } else if (sav->ivlen != 0)
464 crp->crp_iv_start = skip + hlen - sav->ivlen;
466 return (crypto_dispatch(crp));
472 ESPSTAT_INC(esps_crypto);
481 * ESP input callback from the crypto driver.
484 esp_input_cb(struct cryptop *crp)
486 IPSEC_DEBUG_DECLARE(char buf[128]);
487 uint8_t lastthree[3];
488 const struct auth_hash *esph;
490 struct xform_data *xd;
491 struct secasvar *sav;
492 struct secasindex *saidx;
493 crypto_session_t cryptoid;
494 int hlen, skip, protoff, error, alen;
496 m = crp->crp_buf.cb_mbuf;
497 xd = crp->crp_opaque;
498 CURVNET_SET(xd->vnet);
501 protoff = xd->protoff;
502 cryptoid = xd->cryptoid;
503 saidx = &sav->sah->saidx;
504 esph = sav->tdb_authalgxform;
506 /* Check for crypto errors */
507 if (crp->crp_etype) {
508 if (crp->crp_etype == EAGAIN) {
509 /* Reset the session ID */
510 if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
511 crypto_freesession(cryptoid);
512 xd->cryptoid = crp->crp_session;
514 return (crypto_dispatch(crp));
517 /* EBADMSG indicates authentication failure. */
518 if (!(crp->crp_etype == EBADMSG && esph != NULL)) {
519 ESPSTAT_INC(esps_noxform);
520 DPRINTF(("%s: crypto error %d\n", __func__,
522 error = crp->crp_etype;
527 /* Shouldn't happen... */
529 ESPSTAT_INC(esps_crypto);
530 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
534 ESPSTAT_INC(esps_hist[sav->alg_enc]);
536 /* If authentication was performed, check now. */
538 alen = xform_ah_authsize(esph);
539 AHSTAT_INC(ahs_hist[sav->alg_auth]);
540 if (crp->crp_etype == EBADMSG) {
541 DPRINTF(("%s: authentication hash mismatch for "
542 "packet in SA %s/%08lx\n", __func__,
543 ipsec_address(&saidx->dst, buf, sizeof(buf)),
544 (u_long) ntohl(sav->spi)));
545 ESPSTAT_INC(esps_badauth);
549 m->m_flags |= M_AUTHIPDGM;
550 /* Remove trailing authenticator */
554 /* Release the crypto descriptors */
555 free(xd, M_ESP), xd = NULL;
556 free(crp->crp_aad, M_ESP), crp->crp_aad = NULL;
557 crypto_freereq(crp), crp = NULL;
560 * Packet is now decrypted.
562 m->m_flags |= M_DECRYPTED;
565 * Update replay sequence number, if appropriate.
570 m_copydata(m, skip + offsetof(struct newesp, esp_seq),
571 sizeof (seq), (caddr_t) &seq);
573 if (ipsec_updatereplay(ntohl(seq), sav)) {
574 SECASVAR_UNLOCK(sav);
575 DPRINTF(("%s: packet replay check for %s\n", __func__,
576 ipsec_sa2str(sav, buf, sizeof(buf))));
577 ESPSTAT_INC(esps_replay);
581 SECASVAR_UNLOCK(sav);
584 /* Determine the ESP header length */
585 if (sav->flags & SADB_X_EXT_OLD)
586 hlen = sizeof (struct esp) + sav->ivlen;
588 hlen = sizeof (struct newesp) + sav->ivlen;
590 /* Remove the ESP header and IV from the mbuf. */
591 error = m_striphdr(m, skip, hlen);
593 ESPSTAT_INC(esps_hdrops);
594 DPRINTF(("%s: bad mbuf chain, SA %s/%08lx\n", __func__,
595 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
596 (u_long) ntohl(sav->spi)));
600 /* Save the last three bytes of decrypted data */
601 m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
603 /* Verify pad length */
604 if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
605 ESPSTAT_INC(esps_badilen);
606 DPRINTF(("%s: invalid padding length %d for %u byte packet "
607 "in SA %s/%08lx\n", __func__, lastthree[1],
608 m->m_pkthdr.len - skip,
609 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
610 (u_long) ntohl(sav->spi)));
615 /* Verify correct decryption by checking the last padding bytes */
616 if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
617 if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
618 ESPSTAT_INC(esps_badenc);
619 DPRINTF(("%s: decryption failed for packet in "
620 "SA %s/%08lx\n", __func__, ipsec_address(
621 &sav->sah->saidx.dst, buf, sizeof(buf)),
622 (u_long) ntohl(sav->spi)));
630 * Silently drop packet if next header field is IPPROTO_NONE.
632 if (lastthree[2] == IPPROTO_NONE)
635 /* Trim the mbuf chain to remove trailing authenticator and padding */
636 m_adj(m, -(lastthree[1] + 2));
638 /* Restore the Next Protocol field */
639 m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
641 switch (saidx->dst.sa.sa_family) {
644 error = ipsec6_common_input_cb(m, sav, skip, protoff);
649 error = ipsec4_common_input_cb(m, sav, skip, protoff);
653 panic("%s: Unexpected address family: %d saidx=%p", __func__,
654 saidx->dst.sa.sa_family, saidx);
667 free(crp->crp_aad, M_ESP);
673 * ESP output routine, called by ipsec[46]_perform_request().
676 esp_output(struct mbuf *m, struct secpolicy *sp, struct secasvar *sav,
677 u_int idx, int skip, int protoff)
679 IPSEC_DEBUG_DECLARE(char buf[IPSEC_ADDRSTRLEN]);
681 const struct auth_hash *esph;
682 const struct enc_xform *espx;
683 struct mbuf *mo = NULL;
684 struct xform_data *xd;
685 struct secasindex *saidx;
689 crypto_session_t cryptoid;
690 int hlen, rlen, padding, blks, alen, i, roff;
691 int error, maxpacketsize;
694 const struct crypto_session_params *csp;
696 IPSEC_ASSERT(sav != NULL, ("null SA"));
697 esph = sav->tdb_authalgxform;
698 espx = sav->tdb_encalgxform;
699 IPSEC_ASSERT(espx != NULL, ("null encoding xform"));
701 if (sav->flags & SADB_X_EXT_OLD)
702 hlen = sizeof (struct esp) + sav->ivlen;
704 hlen = sizeof (struct newesp) + sav->ivlen;
706 rlen = m->m_pkthdr.len - skip; /* Raw payload length. */
708 * RFC4303 2.4 Requires 4 byte alignment.
709 * Old versions of FreeBSD can't decrypt partial blocks encrypted
710 * with AES-CTR. Align payload to native_blocksize (16 bytes)
711 * in order to preserve compatibility.
713 if (SAV_ISCTR(sav) && V_esp_ctr_compatibility)
714 blks = MAX(4, espx->native_blocksize); /* Cipher blocksize */
716 blks = MAX(4, espx->blocksize);
718 /* XXX clamp padding length a la KAME??? */
719 padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
721 alen = xform_ah_authsize(esph);
723 ESPSTAT_INC(esps_output);
725 saidx = &sav->sah->saidx;
726 /* Check for maximum packet size violations. */
727 switch (saidx->dst.sa.sa_family) {
730 maxpacketsize = IP_MAXPACKET;
735 maxpacketsize = IPV6_MAXPACKET;
739 DPRINTF(("%s: unknown/unsupported protocol "
740 "family %d, SA %s/%08lx\n", __func__,
741 saidx->dst.sa.sa_family, ipsec_address(&saidx->dst,
742 buf, sizeof(buf)), (u_long) ntohl(sav->spi)));
743 ESPSTAT_INC(esps_nopf);
744 error = EPFNOSUPPORT;
748 DPRINTF(("%s: skip %d hlen %d rlen %d padding %d alen %d blksd %d\n",
749 __func__, skip, hlen, rlen, padding, alen, blks)); */
750 if (skip + hlen + rlen + padding + alen > maxpacketsize) {
751 DPRINTF(("%s: packet in SA %s/%08lx got too big "
752 "(len %u, max len %u)\n", __func__,
753 ipsec_address(&saidx->dst, buf, sizeof(buf)),
754 (u_long) ntohl(sav->spi),
755 skip + hlen + rlen + padding + alen, maxpacketsize));
756 ESPSTAT_INC(esps_toobig);
761 /* Update the counters. */
762 ESPSTAT_ADD(esps_obytes, m->m_pkthdr.len - skip);
764 m = m_unshare(m, M_NOWAIT);
766 DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
767 ipsec_address(&saidx->dst, buf, sizeof(buf)),
768 (u_long) ntohl(sav->spi)));
769 ESPSTAT_INC(esps_hdrops);
774 /* Inject ESP header. */
775 mo = m_makespace(m, skip, hlen, &roff);
777 DPRINTF(("%s: %u byte ESP hdr inject failed for SA %s/%08lx\n",
778 __func__, hlen, ipsec_address(&saidx->dst, buf,
779 sizeof(buf)), (u_long) ntohl(sav->spi)));
780 ESPSTAT_INC(esps_hdrops); /* XXX diffs from openbsd */
785 /* Initialize ESP header. */
786 bcopy((caddr_t) &sav->spi, mtod(mo, caddr_t) + roff,
793 /* Emulate replay attack when ipsec_replay is TRUE. */
796 sav->replay->count++;
797 replay = htonl((uint32_t)sav->replay->count);
799 bcopy((caddr_t) &replay, mtod(mo, caddr_t) + roff +
800 sizeof(uint32_t), sizeof(uint32_t));
802 seqh = htonl((uint32_t)(sav->replay->count >> IPSEC_SEQH_SHIFT));
804 cryptoid = sav->tdb_cryptoid;
805 if (SAV_ISCTRORGCM(sav))
807 SECASVAR_UNLOCK(sav);
810 * Add padding -- better to do it ourselves than use the crypto engine,
811 * although if/when we support compression, we'd have to do that.
813 pad = (u_char *) m_pad(m, padding + alen);
815 DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
816 ipsec_address(&saidx->dst, buf, sizeof(buf)),
817 (u_long) ntohl(sav->spi)));
818 m = NULL; /* NB: free'd by m_pad */
824 * Add padding: random, zero, or self-describing.
825 * XXX catch unexpected setting
827 switch (sav->flags & SADB_X_EXT_PMASK) {
828 case SADB_X_EXT_PRAND:
829 arc4random_buf(pad, padding - 2);
831 case SADB_X_EXT_PZERO:
832 bzero(pad, padding - 2);
834 case SADB_X_EXT_PSEQ:
835 for (i = 0; i < padding - 2; i++)
840 /* Fix padding length and Next Protocol in padding itself. */
841 pad[padding - 2] = padding - 2;
842 m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
844 /* Fix Next Protocol in IPv4/IPv6 header. */
846 m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
848 /* Get crypto descriptor. */
849 crp = crypto_getreq(cryptoid, M_NOWAIT);
851 DPRINTF(("%s: failed to acquire crypto descriptor\n",
853 ESPSTAT_INC(esps_crypto);
858 /* IPsec-specific opaque crypto info. */
859 xd = malloc(sizeof(struct xform_data), M_ESP, M_NOWAIT | M_ZERO);
861 DPRINTF(("%s: failed to allocate xform_data\n", __func__));
865 /* Encryption descriptor. */
866 crp->crp_payload_start = skip + hlen;
867 crp->crp_payload_length = m->m_pkthdr.len - (skip + hlen + alen);
868 crp->crp_op = CRYPTO_OP_ENCRYPT;
870 /* Generate cipher and ESP IVs. */
871 ivp = &crp->crp_iv[0];
872 if (SAV_ISCTRORGCM(sav)) {
874 * See comment in esp_input() for details on the
875 * cipher IV. A simple per-SA counter stored in
876 * 'cntr' is used as the explicit ESP IV.
878 memcpy(ivp, sav->key_enc->key_data +
879 _KEYLEN(sav->key_enc) - 4, 4);
880 be64enc(&ivp[4], cntr);
881 if (SAV_ISCTR(sav)) {
882 be32enc(&ivp[sav->ivlen + 4], 1);
884 m_copyback(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
885 crp->crp_flags |= CRYPTO_F_IV_SEPARATE;
886 } else if (sav->ivlen != 0) {
887 arc4rand(ivp, sav->ivlen, 0);
888 crp->crp_iv_start = skip + hlen - sav->ivlen;
889 m_copyback(m, crp->crp_iv_start, sav->ivlen, ivp);
892 /* Callback parameters */
896 xd->cryptoid = cryptoid;
899 /* Crypto operation descriptor. */
900 crp->crp_flags |= CRYPTO_F_CBIFSYNC;
902 crp->crp_flags |= CRYPTO_F_ASYNC | CRYPTO_F_ASYNC_KEEPORDER;
903 crypto_use_mbuf(crp, m);
904 crp->crp_callback = esp_output_cb;
905 crp->crp_opaque = xd;
908 /* Authentication descriptor. */
909 crp->crp_op |= CRYPTO_OP_COMPUTE_DIGEST;
911 crp->crp_aad_length = 8; /* RFC4106 5, SPI + SN */
913 crp->crp_aad_length = hlen;
915 csp = crypto_get_params(crp->crp_session);
916 if (csp->csp_flags & CSP_F_SEPARATE_AAD &&
917 sav->replay != NULL) {
920 crp->crp_aad_length += sizeof(seqh);
921 crp->crp_aad = malloc(crp->crp_aad_length, M_ESP, M_NOWAIT);
922 if (crp->crp_aad == NULL) {
923 DPRINTF(("%s: failed to allocate xform_data\n",
929 m_copydata(m, skip, SPI_SIZE, crp->crp_aad);
933 bcopy(&seqh, (char *)crp->crp_aad + aad_skip, sizeof(seqh));
934 aad_skip += sizeof(seqh);
937 if (crp->crp_aad_length - aad_skip > 0)
938 m_copydata(m, skip + SPI_SIZE,
939 crp->crp_aad_length - aad_skip,
940 (char *)crp->crp_aad + aad_skip);
942 crp->crp_aad_start = skip;
944 if (csp->csp_flags & CSP_F_ESN && sav->replay != NULL)
945 memcpy(crp->crp_esn, &seqh, sizeof(seqh));
947 crp->crp_digest_start = m->m_pkthdr.len - alen;
950 return crypto_dispatch(crp);
956 ESPSTAT_INC(esps_crypto);
966 * ESP output callback from the crypto driver.
969 esp_output_cb(struct cryptop *crp)
971 struct xform_data *xd;
972 struct secpolicy *sp;
973 struct secasvar *sav;
975 crypto_session_t cryptoid;
979 xd = (struct xform_data *) crp->crp_opaque;
980 CURVNET_SET(xd->vnet);
981 m = crp->crp_buf.cb_mbuf;
985 cryptoid = xd->cryptoid;
987 /* Check for crypto errors. */
988 if (crp->crp_etype) {
989 if (crp->crp_etype == EAGAIN) {
990 /* Reset the session ID */
991 if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
992 crypto_freesession(cryptoid);
993 xd->cryptoid = crp->crp_session;
995 return (crypto_dispatch(crp));
997 ESPSTAT_INC(esps_noxform);
998 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
999 error = crp->crp_etype;
1004 /* Shouldn't happen... */
1006 ESPSTAT_INC(esps_crypto);
1007 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
1012 free(crp->crp_aad, M_ESP);
1013 crypto_freereq(crp);
1014 ESPSTAT_INC(esps_hist[sav->alg_enc]);
1015 if (sav->tdb_authalgxform != NULL)
1016 AHSTAT_INC(ahs_hist[sav->alg_auth]);
1019 /* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
1020 if (V_ipsec_integrity) {
1021 static unsigned char ipseczeroes[AH_HMAC_MAXHASHLEN];
1022 const struct auth_hash *esph;
1025 * Corrupt HMAC if we want to test integrity verification of
1028 esph = sav->tdb_authalgxform;
1032 alen = xform_ah_authsize(esph);
1033 m_copyback(m, m->m_pkthdr.len - alen,
1039 /* NB: m is reclaimed by ipsec_process_done. */
1040 error = ipsec_process_done(m, sp, sav, idx);
1046 free(crp->crp_aad, M_ESP);
1047 crypto_freereq(crp);
1053 static struct xformsw esp_xformsw = {
1055 .xf_name = "IPsec ESP",
1056 .xf_init = esp_init,
1057 .xf_cleanup = esp_cleanup,
1058 .xf_input = esp_input,
1059 .xf_output = esp_output,
1062 SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
1063 xform_attach, &esp_xformsw);
1064 SYSUNINIT(esp_xform_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
1065 xform_detach, &esp_xformsw);