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 int esp_input_cb(struct cryptop *op);
98 static int esp_output_cb(struct cryptop *crp);
101 esp_hdrsiz(struct secasvar *sav)
106 /*XXX not right for null algorithm--does it matter??*/
107 IPSEC_ASSERT(sav->tdb_encalgxform != NULL,
108 ("SA with null xform"));
109 if (sav->flags & SADB_X_EXT_OLD)
110 size = sizeof (struct esp);
112 size = sizeof (struct newesp);
113 size += sav->tdb_encalgxform->blocksize + 9;
114 /*XXX need alg check???*/
115 if (sav->tdb_authalgxform != NULL && sav->replay)
116 size += ah_hdrsiz(sav);
120 * + max iv length for CBC mode
122 * + sizeof (pad length field)
123 * + sizeof (next header field)
124 * + max icv supported.
126 size = sizeof (struct newesp) + EALG_MAX_BLOCK_LEN + 9 + 16;
132 * esp_init() is called when an SPI is being set up.
135 esp_init(struct secasvar *sav, struct xformsw *xsp)
137 const struct enc_xform *txform;
138 struct crypto_session_params csp;
142 txform = enc_algorithm_lookup(sav->alg_enc);
143 if (txform == NULL) {
144 DPRINTF(("%s: unsupported encryption algorithm %d\n",
145 __func__, sav->alg_enc));
148 if (sav->key_enc == NULL) {
149 DPRINTF(("%s: no encoding key for %s algorithm\n",
150 __func__, txform->name));
153 if ((sav->flags & (SADB_X_EXT_OLD | SADB_X_EXT_IV4B)) ==
155 DPRINTF(("%s: 4-byte IV not supported with protocol\n",
160 /* subtract off the salt, RFC4106, 8.1 and RFC3686, 5.1 */
161 keylen = _KEYLEN(sav->key_enc) - SAV_ISCTRORGCM(sav) * 4;
162 if (txform->minkey > keylen || keylen > txform->maxkey) {
163 DPRINTF(("%s: invalid key length %u, must be in the range "
164 "[%u..%u] for algorithm %s\n", __func__,
165 keylen, txform->minkey, txform->maxkey,
170 if (SAV_ISCTRORGCM(sav))
171 sav->ivlen = 8; /* RFC4106 3.1 and RFC3686 3.1 */
173 sav->ivlen = txform->ivsize;
175 memset(&csp, 0, sizeof(csp));
178 * Setup AH-related state.
180 if (sav->alg_auth != 0) {
181 error = ah_init0(sav, xsp, &csp);
186 /* NB: override anything set in ah_init0 */
187 sav->tdb_xform = xsp;
188 sav->tdb_encalgxform = txform;
191 * Whenever AES-GCM is used for encryption, one
192 * of the AES authentication algorithms is chosen
193 * as well, based on the key size.
195 if (sav->alg_enc == SADB_X_EALG_AESGCM16) {
197 case AES_128_GMAC_KEY_LEN:
198 sav->alg_auth = SADB_X_AALG_AES128GMAC;
199 sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_128;
201 case AES_192_GMAC_KEY_LEN:
202 sav->alg_auth = SADB_X_AALG_AES192GMAC;
203 sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_192;
205 case AES_256_GMAC_KEY_LEN:
206 sav->alg_auth = SADB_X_AALG_AES256GMAC;
207 sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_256;
210 DPRINTF(("%s: invalid key length %u"
211 "for algorithm %s\n", __func__,
212 keylen, txform->name));
215 csp.csp_mode = CSP_MODE_AEAD;
216 } else if (sav->alg_auth != 0)
217 csp.csp_mode = CSP_MODE_ETA;
219 csp.csp_mode = CSP_MODE_CIPHER;
221 /* Initialize crypto session. */
222 csp.csp_cipher_alg = sav->tdb_encalgxform->type;
223 if (csp.csp_cipher_alg != CRYPTO_NULL_CBC) {
224 csp.csp_cipher_key = sav->key_enc->key_data;
225 csp.csp_cipher_klen = _KEYBITS(sav->key_enc) / 8 -
226 SAV_ISCTRORGCM(sav) * 4;
228 csp.csp_ivlen = txform->ivsize;
230 error = crypto_newsession(&sav->tdb_cryptoid, &csp, V_crypto_support);
238 esp_zeroize(struct secasvar *sav)
240 /* NB: ah_zerorize free's the crypto session state */
241 int error = ah_zeroize(sav);
244 bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
245 sav->tdb_encalgxform = NULL;
246 sav->tdb_xform = NULL;
251 * ESP input processing, called (eventually) through the protocol switch.
254 esp_input(struct mbuf *m, struct secasvar *sav, int skip, int protoff)
256 IPSEC_DEBUG_DECLARE(char buf[128]);
257 const struct auth_hash *esph;
258 const struct enc_xform *espx;
259 struct xform_data *xd;
263 crypto_session_t cryptoid;
264 int alen, error, hlen, plen;
266 IPSEC_ASSERT(sav != NULL, ("null SA"));
267 IPSEC_ASSERT(sav->tdb_encalgxform != NULL, ("null encoding xform"));
270 /* Valid IP Packet length ? */
271 if ( (skip&3) || (m->m_pkthdr.len&3) ){
272 DPRINTF(("%s: misaligned packet, skip %u pkt len %u",
273 __func__, skip, m->m_pkthdr.len));
274 ESPSTAT_INC(esps_badilen);
278 if (m->m_len < skip + sizeof(*esp)) {
279 m = m_pullup(m, skip + sizeof(*esp));
281 DPRINTF(("%s: cannot pullup header\n", __func__));
282 ESPSTAT_INC(esps_hdrops); /*XXX*/
287 esp = (struct newesp *)(mtod(m, caddr_t) + skip);
289 esph = sav->tdb_authalgxform;
290 espx = sav->tdb_encalgxform;
292 /* Determine the ESP header and auth length */
293 if (sav->flags & SADB_X_EXT_OLD)
294 hlen = sizeof (struct esp) + sav->ivlen;
296 hlen = sizeof (struct newesp) + sav->ivlen;
298 alen = xform_ah_authsize(esph);
301 * Verify payload length is multiple of encryption algorithm
304 * NB: This works for the null algorithm because the blocksize
305 * is 4 and all packets must be 4-byte aligned regardless
308 plen = m->m_pkthdr.len - (skip + hlen + alen);
309 if ((plen & (espx->blocksize - 1)) || (plen <= 0)) {
310 DPRINTF(("%s: payload of %d octets not a multiple of %d octets,"
311 " SA %s/%08lx\n", __func__, plen, espx->blocksize,
312 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
313 (u_long)ntohl(sav->spi)));
314 ESPSTAT_INC(esps_badilen);
319 * Check sequence number.
322 if (esph != NULL && sav->replay != NULL && sav->replay->wsize != 0) {
323 if (ipsec_chkreplay(ntohl(esp->esp_seq), sav) == 0) {
324 SECASVAR_UNLOCK(sav);
325 DPRINTF(("%s: packet replay check for %s\n", __func__,
326 ipsec_sa2str(sav, buf, sizeof(buf))));
327 ESPSTAT_INC(esps_replay);
332 cryptoid = sav->tdb_cryptoid;
333 SECASVAR_UNLOCK(sav);
335 /* Update the counters */
336 ESPSTAT_ADD(esps_ibytes, m->m_pkthdr.len - (skip + hlen + alen));
338 /* Get crypto descriptors */
339 crp = crypto_getreq(cryptoid, M_NOWAIT);
341 DPRINTF(("%s: failed to acquire crypto descriptors\n",
343 ESPSTAT_INC(esps_crypto);
348 /* Get IPsec-specific opaque pointer */
349 xd = malloc(sizeof(*xd), M_XDATA, M_NOWAIT | M_ZERO);
351 DPRINTF(("%s: failed to allocate xform_data\n", __func__));
352 ESPSTAT_INC(esps_crypto);
359 crp->crp_op = CRYPTO_OP_VERIFY_DIGEST;
360 crp->crp_aad_start = skip;
362 crp->crp_aad_length = 8; /* RFC4106 5, SPI + SN */
364 crp->crp_aad_length = hlen;
365 crp->crp_digest_start = m->m_pkthdr.len - alen;
368 /* Crypto operation descriptor */
369 crp->crp_ilen = m->m_pkthdr.len; /* Total input length */
370 crp->crp_flags = CRYPTO_F_CBIFSYNC;
372 crp->crp_flags |= CRYPTO_F_ASYNC | CRYPTO_F_ASYNC_KEEPORDER;
374 crp->crp_buf_type = CRYPTO_BUF_MBUF;
375 crp->crp_callback = esp_input_cb;
376 crp->crp_opaque = xd;
378 /* These are passed as-is to the callback */
380 xd->protoff = protoff;
382 xd->cryptoid = cryptoid;
385 /* Decryption descriptor */
386 crp->crp_op |= CRYPTO_OP_DECRYPT;
387 crp->crp_payload_start = skip + hlen;
388 crp->crp_payload_length = m->m_pkthdr.len - (skip + hlen + alen);
390 /* Generate or read cipher IV. */
391 if (SAV_ISCTRORGCM(sav)) {
392 ivp = &crp->crp_iv[0];
395 * AES-GCM and AES-CTR use similar cipher IV formats
396 * defined in RFC 4106 section 4 and RFC 3686 section
399 * The first 4 bytes of the cipher IV contain an
400 * implicit salt, or nonce, obtained from the last 4
401 * bytes of the encryption key. The next 8 bytes hold
402 * an explicit IV unique to each packet. This
403 * explicit IV is used as the ESP IV for the packet.
404 * The last 4 bytes hold a big-endian block counter
405 * incremented for each block. For AES-GCM, the block
406 * counter's initial value is defined as part of the
407 * algorithm. For AES-CTR, the block counter's
408 * initial value for each packet is defined as 1 by
411 * ------------------------------------------
412 * | Salt | Explicit ESP IV | Block Counter |
413 * ------------------------------------------
414 * 4 bytes 8 bytes 4 bytes
416 memcpy(ivp, sav->key_enc->key_data +
417 _KEYLEN(sav->key_enc) - 4, 4);
418 m_copydata(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
419 if (SAV_ISCTR(sav)) {
420 be32enc(&ivp[sav->ivlen + 4], 1);
422 crp->crp_flags |= CRYPTO_F_IV_SEPARATE;
423 } else if (sav->ivlen != 0)
424 crp->crp_iv_start = skip + hlen - sav->ivlen;
426 return (crypto_dispatch(crp));
434 * ESP input callback from the crypto driver.
437 esp_input_cb(struct cryptop *crp)
439 IPSEC_DEBUG_DECLARE(char buf[128]);
440 uint8_t lastthree[3];
441 const struct auth_hash *esph;
443 struct xform_data *xd;
444 struct secasvar *sav;
445 struct secasindex *saidx;
446 crypto_session_t cryptoid;
447 int hlen, skip, protoff, error, alen;
450 xd = crp->crp_opaque;
451 CURVNET_SET(xd->vnet);
454 protoff = xd->protoff;
455 cryptoid = xd->cryptoid;
456 saidx = &sav->sah->saidx;
457 esph = sav->tdb_authalgxform;
459 /* Check for crypto errors */
460 if (crp->crp_etype) {
461 if (crp->crp_etype == EAGAIN) {
462 /* Reset the session ID */
463 if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
464 crypto_freesession(cryptoid);
465 xd->cryptoid = crp->crp_session;
467 return (crypto_dispatch(crp));
470 /* EBADMSG indicates authentication failure. */
471 if (!(crp->crp_etype == EBADMSG && esph != NULL)) {
472 ESPSTAT_INC(esps_noxform);
473 DPRINTF(("%s: crypto error %d\n", __func__,
475 error = crp->crp_etype;
480 /* Shouldn't happen... */
482 ESPSTAT_INC(esps_crypto);
483 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
487 ESPSTAT_INC(esps_hist[sav->alg_enc]);
489 /* If authentication was performed, check now. */
491 alen = xform_ah_authsize(esph);
492 AHSTAT_INC(ahs_hist[sav->alg_auth]);
493 if (crp->crp_etype == EBADMSG) {
494 DPRINTF(("%s: authentication hash mismatch for "
495 "packet in SA %s/%08lx\n", __func__,
496 ipsec_address(&saidx->dst, buf, sizeof(buf)),
497 (u_long) ntohl(sav->spi)));
498 ESPSTAT_INC(esps_badauth);
502 m->m_flags |= M_AUTHIPDGM;
503 /* Remove trailing authenticator */
507 /* Release the crypto descriptors */
508 free(xd, M_XDATA), xd = NULL;
509 crypto_freereq(crp), crp = NULL;
512 * Packet is now decrypted.
514 m->m_flags |= M_DECRYPTED;
517 * Update replay sequence number, if appropriate.
522 m_copydata(m, skip + offsetof(struct newesp, esp_seq),
523 sizeof (seq), (caddr_t) &seq);
525 if (ipsec_updatereplay(ntohl(seq), sav)) {
526 SECASVAR_UNLOCK(sav);
527 DPRINTF(("%s: packet replay check for %s\n", __func__,
528 ipsec_sa2str(sav, buf, sizeof(buf))));
529 ESPSTAT_INC(esps_replay);
533 SECASVAR_UNLOCK(sav);
536 /* Determine the ESP header length */
537 if (sav->flags & SADB_X_EXT_OLD)
538 hlen = sizeof (struct esp) + sav->ivlen;
540 hlen = sizeof (struct newesp) + sav->ivlen;
542 /* Remove the ESP header and IV from the mbuf. */
543 error = m_striphdr(m, skip, hlen);
545 ESPSTAT_INC(esps_hdrops);
546 DPRINTF(("%s: bad mbuf chain, SA %s/%08lx\n", __func__,
547 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
548 (u_long) ntohl(sav->spi)));
552 /* Save the last three bytes of decrypted data */
553 m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
555 /* Verify pad length */
556 if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
557 ESPSTAT_INC(esps_badilen);
558 DPRINTF(("%s: invalid padding length %d for %u byte packet "
559 "in SA %s/%08lx\n", __func__, lastthree[1],
560 m->m_pkthdr.len - skip,
561 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
562 (u_long) ntohl(sav->spi)));
567 /* Verify correct decryption by checking the last padding bytes */
568 if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
569 if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
570 ESPSTAT_INC(esps_badenc);
571 DPRINTF(("%s: decryption failed for packet in "
572 "SA %s/%08lx\n", __func__, ipsec_address(
573 &sav->sah->saidx.dst, buf, sizeof(buf)),
574 (u_long) ntohl(sav->spi)));
582 * Silently drop packet if next header field is IPPROTO_NONE.
584 if (lastthree[2] == IPPROTO_NONE)
587 /* Trim the mbuf chain to remove trailing authenticator and padding */
588 m_adj(m, -(lastthree[1] + 2));
590 /* Restore the Next Protocol field */
591 m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
593 switch (saidx->dst.sa.sa_family) {
596 error = ipsec6_common_input_cb(m, sav, skip, protoff);
601 error = ipsec4_common_input_cb(m, sav, skip, protoff);
605 panic("%s: Unexpected address family: %d saidx=%p", __func__,
606 saidx->dst.sa.sa_family, saidx);
623 * ESP output routine, called by ipsec[46]_perform_request().
626 esp_output(struct mbuf *m, struct secpolicy *sp, struct secasvar *sav,
627 u_int idx, int skip, int protoff)
629 IPSEC_DEBUG_DECLARE(char buf[IPSEC_ADDRSTRLEN]);
631 const struct auth_hash *esph;
632 const struct enc_xform *espx;
633 struct mbuf *mo = NULL;
634 struct xform_data *xd;
635 struct secasindex *saidx;
639 crypto_session_t cryptoid;
640 int hlen, rlen, padding, blks, alen, i, roff;
641 int error, maxpacketsize;
644 IPSEC_ASSERT(sav != NULL, ("null SA"));
645 esph = sav->tdb_authalgxform;
646 espx = sav->tdb_encalgxform;
647 IPSEC_ASSERT(espx != NULL, ("null encoding xform"));
649 if (sav->flags & SADB_X_EXT_OLD)
650 hlen = sizeof (struct esp) + sav->ivlen;
652 hlen = sizeof (struct newesp) + sav->ivlen;
654 rlen = m->m_pkthdr.len - skip; /* Raw payload length. */
656 * RFC4303 2.4 Requires 4 byte alignment.
658 blks = MAX(4, espx->blocksize); /* Cipher blocksize */
660 /* XXX clamp padding length a la KAME??? */
661 padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
663 alen = xform_ah_authsize(esph);
665 ESPSTAT_INC(esps_output);
667 saidx = &sav->sah->saidx;
668 /* Check for maximum packet size violations. */
669 switch (saidx->dst.sa.sa_family) {
672 maxpacketsize = IP_MAXPACKET;
677 maxpacketsize = IPV6_MAXPACKET;
681 DPRINTF(("%s: unknown/unsupported protocol "
682 "family %d, SA %s/%08lx\n", __func__,
683 saidx->dst.sa.sa_family, ipsec_address(&saidx->dst,
684 buf, sizeof(buf)), (u_long) ntohl(sav->spi)));
685 ESPSTAT_INC(esps_nopf);
686 error = EPFNOSUPPORT;
690 DPRINTF(("%s: skip %d hlen %d rlen %d padding %d alen %d blksd %d\n",
691 __func__, skip, hlen, rlen, padding, alen, blks)); */
692 if (skip + hlen + rlen + padding + alen > maxpacketsize) {
693 DPRINTF(("%s: packet in SA %s/%08lx got too big "
694 "(len %u, max len %u)\n", __func__,
695 ipsec_address(&saidx->dst, buf, sizeof(buf)),
696 (u_long) ntohl(sav->spi),
697 skip + hlen + rlen + padding + alen, maxpacketsize));
698 ESPSTAT_INC(esps_toobig);
703 /* Update the counters. */
704 ESPSTAT_ADD(esps_obytes, m->m_pkthdr.len - skip);
706 m = m_unshare(m, M_NOWAIT);
708 DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
709 ipsec_address(&saidx->dst, buf, sizeof(buf)),
710 (u_long) ntohl(sav->spi)));
711 ESPSTAT_INC(esps_hdrops);
716 /* Inject ESP header. */
717 mo = m_makespace(m, skip, hlen, &roff);
719 DPRINTF(("%s: %u byte ESP hdr inject failed for SA %s/%08lx\n",
720 __func__, hlen, ipsec_address(&saidx->dst, buf,
721 sizeof(buf)), (u_long) ntohl(sav->spi)));
722 ESPSTAT_INC(esps_hdrops); /* XXX diffs from openbsd */
727 /* Initialize ESP header. */
728 bcopy((caddr_t) &sav->spi, mtod(mo, caddr_t) + roff,
735 /* Emulate replay attack when ipsec_replay is TRUE. */
738 sav->replay->count++;
739 replay = htonl(sav->replay->count);
741 bcopy((caddr_t) &replay, mtod(mo, caddr_t) + roff +
742 sizeof(uint32_t), sizeof(uint32_t));
744 cryptoid = sav->tdb_cryptoid;
745 if (SAV_ISCTRORGCM(sav))
747 SECASVAR_UNLOCK(sav);
750 * Add padding -- better to do it ourselves than use the crypto engine,
751 * although if/when we support compression, we'd have to do that.
753 pad = (u_char *) m_pad(m, padding + alen);
755 DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
756 ipsec_address(&saidx->dst, buf, sizeof(buf)),
757 (u_long) ntohl(sav->spi)));
758 m = NULL; /* NB: free'd by m_pad */
764 * Add padding: random, zero, or self-describing.
765 * XXX catch unexpected setting
767 switch (sav->flags & SADB_X_EXT_PMASK) {
768 case SADB_X_EXT_PRAND:
769 arc4random_buf(pad, padding - 2);
771 case SADB_X_EXT_PZERO:
772 bzero(pad, padding - 2);
774 case SADB_X_EXT_PSEQ:
775 for (i = 0; i < padding - 2; i++)
780 /* Fix padding length and Next Protocol in padding itself. */
781 pad[padding - 2] = padding - 2;
782 m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
784 /* Fix Next Protocol in IPv4/IPv6 header. */
786 m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
788 /* Get crypto descriptor. */
789 crp = crypto_getreq(cryptoid, M_NOWAIT);
791 DPRINTF(("%s: failed to acquire crypto descriptor\n",
793 ESPSTAT_INC(esps_crypto);
798 /* IPsec-specific opaque crypto info. */
799 xd = malloc(sizeof(struct xform_data), M_XDATA, M_NOWAIT | M_ZERO);
802 DPRINTF(("%s: failed to allocate xform_data\n", __func__));
803 ESPSTAT_INC(esps_crypto);
808 /* Encryption descriptor. */
809 crp->crp_payload_start = skip + hlen;
810 crp->crp_payload_length = m->m_pkthdr.len - (skip + hlen + alen);
811 crp->crp_op = CRYPTO_OP_ENCRYPT;
813 /* Generate cipher and ESP IVs. */
814 ivp = &crp->crp_iv[0];
815 if (SAV_ISCTRORGCM(sav)) {
817 * See comment in esp_input() for details on the
818 * cipher IV. A simple per-SA counter stored in
819 * 'cntr' is used as the explicit ESP IV.
821 memcpy(ivp, sav->key_enc->key_data +
822 _KEYLEN(sav->key_enc) - 4, 4);
823 be64enc(&ivp[4], cntr);
824 if (SAV_ISCTR(sav)) {
825 be32enc(&ivp[sav->ivlen + 4], 1);
827 m_copyback(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
828 crp->crp_flags |= CRYPTO_F_IV_SEPARATE;
829 } else if (sav->ivlen != 0) {
830 arc4rand(ivp, sav->ivlen, 0);
831 crp->crp_iv_start = skip + hlen - sav->ivlen;
832 m_copyback(m, crp->crp_iv_start, sav->ivlen, ivp);
835 /* Callback parameters */
839 xd->cryptoid = cryptoid;
842 /* Crypto operation descriptor. */
843 crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
844 crp->crp_flags |= CRYPTO_F_CBIFSYNC;
846 crp->crp_flags |= CRYPTO_F_ASYNC | CRYPTO_F_ASYNC_KEEPORDER;
848 crp->crp_buf_type = CRYPTO_BUF_MBUF;
849 crp->crp_callback = esp_output_cb;
850 crp->crp_opaque = xd;
853 /* Authentication descriptor. */
854 crp->crp_op |= CRYPTO_OP_COMPUTE_DIGEST;
855 crp->crp_aad_start = skip;
857 crp->crp_aad_length = 8; /* RFC4106 5, SPI + SN */
859 crp->crp_aad_length = hlen;
860 crp->crp_digest_start = m->m_pkthdr.len - alen;
863 return crypto_dispatch(crp);
872 * ESP output callback from the crypto driver.
875 esp_output_cb(struct cryptop *crp)
877 struct xform_data *xd;
878 struct secpolicy *sp;
879 struct secasvar *sav;
881 crypto_session_t cryptoid;
885 xd = (struct xform_data *) crp->crp_opaque;
886 CURVNET_SET(xd->vnet);
887 m = (struct mbuf *) crp->crp_buf;
891 cryptoid = xd->cryptoid;
893 /* Check for crypto errors. */
894 if (crp->crp_etype) {
895 if (crp->crp_etype == EAGAIN) {
896 /* Reset the session ID */
897 if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
898 crypto_freesession(cryptoid);
899 xd->cryptoid = crp->crp_session;
901 return (crypto_dispatch(crp));
903 ESPSTAT_INC(esps_noxform);
904 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
905 error = crp->crp_etype;
910 /* Shouldn't happen... */
912 ESPSTAT_INC(esps_crypto);
913 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
919 ESPSTAT_INC(esps_hist[sav->alg_enc]);
920 if (sav->tdb_authalgxform != NULL)
921 AHSTAT_INC(ahs_hist[sav->alg_auth]);
924 /* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
925 if (V_ipsec_integrity) {
926 static unsigned char ipseczeroes[AH_HMAC_MAXHASHLEN];
927 const struct auth_hash *esph;
930 * Corrupt HMAC if we want to test integrity verification of
933 esph = sav->tdb_authalgxform;
937 alen = xform_ah_authsize(esph);
938 m_copyback(m, m->m_pkthdr.len - alen,
944 /* NB: m is reclaimed by ipsec_process_done. */
945 error = ipsec_process_done(m, sp, sav, idx);
957 static struct xformsw esp_xformsw = {
959 .xf_name = "IPsec ESP",
961 .xf_zeroize = esp_zeroize,
962 .xf_input = esp_input,
963 .xf_output = esp_output,
966 SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
967 xform_attach, &esp_xformsw);
968 SYSUNINIT(esp_xform_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
969 xform_detach, &esp_xformsw);