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>
45 #include <sys/socket.h>
46 #include <sys/syslog.h>
47 #include <sys/kernel.h>
49 #include <sys/random.h>
50 #include <sys/mutex.h>
51 #include <sys/sysctl.h>
52 #include <sys/mutex.h>
53 #include <machine/atomic.h>
58 #include <netinet/in.h>
59 #include <netinet/in_systm.h>
60 #include <netinet/ip.h>
61 #include <netinet/ip_ecn.h>
62 #include <netinet/ip6.h>
64 #include <netipsec/ipsec.h>
65 #include <netipsec/ah.h>
66 #include <netipsec/ah_var.h>
67 #include <netipsec/esp.h>
68 #include <netipsec/esp_var.h>
69 #include <netipsec/xform.h>
72 #include <netinet6/ip6_var.h>
73 #include <netipsec/ipsec6.h>
74 #include <netinet6/ip6_ecn.h>
77 #include <netipsec/key.h>
78 #include <netipsec/key_debug.h>
80 #include <opencrypto/cryptodev.h>
81 #include <opencrypto/xform.h>
83 VNET_DEFINE(int, esp_enable) = 1;
84 VNET_DEFINE_STATIC(int, esp_ctr_compatibility) = 1;
85 #define V_esp_ctr_compatibility VNET(esp_ctr_compatibility)
86 VNET_PCPUSTAT_DEFINE(struct espstat, espstat);
87 VNET_PCPUSTAT_SYSINIT(espstat);
90 VNET_PCPUSTAT_SYSUNINIT(espstat);
93 SYSCTL_DECL(_net_inet_esp);
94 SYSCTL_INT(_net_inet_esp, OID_AUTO, esp_enable,
95 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(esp_enable), 0, "");
96 SYSCTL_INT(_net_inet_esp, OID_AUTO, ctr_compatibility,
97 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(esp_ctr_compatibility), 0,
98 "Align AES-CTR encrypted transmitted frames to blocksize");
99 SYSCTL_VNET_PCPUSTAT(_net_inet_esp, IPSECCTL_STATS, stats,
100 struct espstat, espstat,
101 "ESP statistics (struct espstat, netipsec/esp_var.h");
103 static int esp_input_cb(struct cryptop *op);
104 static int esp_output_cb(struct cryptop *crp);
107 esp_hdrsiz(struct secasvar *sav)
112 /*XXX not right for null algorithm--does it matter??*/
113 IPSEC_ASSERT(sav->tdb_encalgxform != NULL,
114 ("SA with null xform"));
115 if (sav->flags & SADB_X_EXT_OLD)
116 size = sizeof (struct esp);
118 size = sizeof (struct newesp);
119 size += sav->tdb_encalgxform->blocksize + 9;
120 /*XXX need alg check???*/
121 if (sav->tdb_authalgxform != NULL && sav->replay)
122 size += ah_hdrsiz(sav);
126 * + max iv length for CBC mode
128 * + sizeof (pad length field)
129 * + sizeof (next header field)
130 * + max icv supported.
132 size = sizeof (struct newesp) + EALG_MAX_BLOCK_LEN + 9 + 16;
138 * esp_init() is called when an SPI is being set up.
141 esp_init(struct secasvar *sav, struct xformsw *xsp)
143 const struct enc_xform *txform;
144 struct crypto_session_params csp;
148 txform = enc_algorithm_lookup(sav->alg_enc);
149 if (txform == NULL) {
150 DPRINTF(("%s: unsupported encryption algorithm %d\n",
151 __func__, sav->alg_enc));
154 if (sav->key_enc == NULL) {
155 DPRINTF(("%s: no encoding key for %s algorithm\n",
156 __func__, txform->name));
159 if ((sav->flags & (SADB_X_EXT_OLD | SADB_X_EXT_IV4B)) ==
161 DPRINTF(("%s: 4-byte IV not supported with protocol\n",
166 /* subtract off the salt, RFC4106, 8.1 and RFC3686, 5.1 */
167 keylen = _KEYLEN(sav->key_enc) - SAV_ISCTRORGCM(sav) * 4;
168 if (txform->minkey > keylen || keylen > txform->maxkey) {
169 DPRINTF(("%s: invalid key length %u, must be in the range "
170 "[%u..%u] for algorithm %s\n", __func__,
171 keylen, txform->minkey, txform->maxkey,
176 if (SAV_ISCTRORGCM(sav))
177 sav->ivlen = 8; /* RFC4106 3.1 and RFC3686 3.1 */
179 sav->ivlen = txform->ivsize;
181 memset(&csp, 0, sizeof(csp));
184 * Setup AH-related state.
186 if (sav->alg_auth != 0) {
187 error = ah_init0(sav, xsp, &csp);
192 /* NB: override anything set in ah_init0 */
193 sav->tdb_xform = xsp;
194 sav->tdb_encalgxform = txform;
197 * Whenever AES-GCM is used for encryption, one
198 * of the AES authentication algorithms is chosen
199 * as well, based on the key size.
201 if (sav->alg_enc == SADB_X_EALG_AESGCM16) {
203 case AES_128_GMAC_KEY_LEN:
204 sav->alg_auth = SADB_X_AALG_AES128GMAC;
205 sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_128;
207 case AES_192_GMAC_KEY_LEN:
208 sav->alg_auth = SADB_X_AALG_AES192GMAC;
209 sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_192;
211 case AES_256_GMAC_KEY_LEN:
212 sav->alg_auth = SADB_X_AALG_AES256GMAC;
213 sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_256;
216 DPRINTF(("%s: invalid key length %u"
217 "for algorithm %s\n", __func__,
218 keylen, txform->name));
221 csp.csp_mode = CSP_MODE_AEAD;
222 } else if (sav->alg_auth != 0)
223 csp.csp_mode = CSP_MODE_ETA;
225 csp.csp_mode = CSP_MODE_CIPHER;
227 /* Initialize crypto session. */
228 csp.csp_cipher_alg = sav->tdb_encalgxform->type;
229 if (csp.csp_cipher_alg != CRYPTO_NULL_CBC) {
230 csp.csp_cipher_key = sav->key_enc->key_data;
231 csp.csp_cipher_klen = _KEYBITS(sav->key_enc) / 8 -
232 SAV_ISCTRORGCM(sav) * 4;
234 csp.csp_ivlen = txform->ivsize;
236 error = crypto_newsession(&sav->tdb_cryptoid, &csp, V_crypto_support);
241 esp_cleanup(struct secasvar *sav)
244 crypto_freesession(sav->tdb_cryptoid);
245 sav->tdb_cryptoid = NULL;
246 sav->tdb_authalgxform = NULL;
247 sav->tdb_encalgxform = 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_flags = CRYPTO_F_CBIFSYNC;
371 crp->crp_flags |= CRYPTO_F_ASYNC | CRYPTO_F_ASYNC_KEEPORDER;
372 crypto_use_mbuf(crp, m);
373 crp->crp_callback = esp_input_cb;
374 crp->crp_opaque = xd;
376 /* These are passed as-is to the callback */
378 xd->protoff = protoff;
380 xd->cryptoid = cryptoid;
383 /* Decryption descriptor */
384 crp->crp_op |= CRYPTO_OP_DECRYPT;
385 crp->crp_payload_start = skip + hlen;
386 crp->crp_payload_length = m->m_pkthdr.len - (skip + hlen + alen);
388 /* Generate or read cipher IV. */
389 if (SAV_ISCTRORGCM(sav)) {
390 ivp = &crp->crp_iv[0];
393 * AES-GCM and AES-CTR use similar cipher IV formats
394 * defined in RFC 4106 section 4 and RFC 3686 section
397 * The first 4 bytes of the cipher IV contain an
398 * implicit salt, or nonce, obtained from the last 4
399 * bytes of the encryption key. The next 8 bytes hold
400 * an explicit IV unique to each packet. This
401 * explicit IV is used as the ESP IV for the packet.
402 * The last 4 bytes hold a big-endian block counter
403 * incremented for each block. For AES-GCM, the block
404 * counter's initial value is defined as part of the
405 * algorithm. For AES-CTR, the block counter's
406 * initial value for each packet is defined as 1 by
409 * ------------------------------------------
410 * | Salt | Explicit ESP IV | Block Counter |
411 * ------------------------------------------
412 * 4 bytes 8 bytes 4 bytes
414 memcpy(ivp, sav->key_enc->key_data +
415 _KEYLEN(sav->key_enc) - 4, 4);
416 m_copydata(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
417 if (SAV_ISCTR(sav)) {
418 be32enc(&ivp[sav->ivlen + 4], 1);
420 crp->crp_flags |= CRYPTO_F_IV_SEPARATE;
421 } else if (sav->ivlen != 0)
422 crp->crp_iv_start = skip + hlen - sav->ivlen;
424 return (crypto_dispatch(crp));
432 * ESP input callback from the crypto driver.
435 esp_input_cb(struct cryptop *crp)
437 IPSEC_DEBUG_DECLARE(char buf[128]);
438 uint8_t lastthree[3];
439 const struct auth_hash *esph;
441 struct xform_data *xd;
442 struct secasvar *sav;
443 struct secasindex *saidx;
444 crypto_session_t cryptoid;
445 int hlen, skip, protoff, error, alen;
447 m = crp->crp_buf.cb_mbuf;
448 xd = crp->crp_opaque;
449 CURVNET_SET(xd->vnet);
452 protoff = xd->protoff;
453 cryptoid = xd->cryptoid;
454 saidx = &sav->sah->saidx;
455 esph = sav->tdb_authalgxform;
457 /* Check for crypto errors */
458 if (crp->crp_etype) {
459 if (crp->crp_etype == EAGAIN) {
460 /* Reset the session ID */
461 if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
462 crypto_freesession(cryptoid);
463 xd->cryptoid = crp->crp_session;
465 return (crypto_dispatch(crp));
468 /* EBADMSG indicates authentication failure. */
469 if (!(crp->crp_etype == EBADMSG && esph != NULL)) {
470 ESPSTAT_INC(esps_noxform);
471 DPRINTF(("%s: crypto error %d\n", __func__,
473 error = crp->crp_etype;
478 /* Shouldn't happen... */
480 ESPSTAT_INC(esps_crypto);
481 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
485 ESPSTAT_INC(esps_hist[sav->alg_enc]);
487 /* If authentication was performed, check now. */
489 alen = xform_ah_authsize(esph);
490 AHSTAT_INC(ahs_hist[sav->alg_auth]);
491 if (crp->crp_etype == EBADMSG) {
492 DPRINTF(("%s: authentication hash mismatch for "
493 "packet in SA %s/%08lx\n", __func__,
494 ipsec_address(&saidx->dst, buf, sizeof(buf)),
495 (u_long) ntohl(sav->spi)));
496 ESPSTAT_INC(esps_badauth);
500 m->m_flags |= M_AUTHIPDGM;
501 /* Remove trailing authenticator */
505 /* Release the crypto descriptors */
506 free(xd, M_XDATA), xd = NULL;
507 crypto_freereq(crp), crp = NULL;
510 * Packet is now decrypted.
512 m->m_flags |= M_DECRYPTED;
515 * Update replay sequence number, if appropriate.
520 m_copydata(m, skip + offsetof(struct newesp, esp_seq),
521 sizeof (seq), (caddr_t) &seq);
523 if (ipsec_updatereplay(ntohl(seq), sav)) {
524 SECASVAR_UNLOCK(sav);
525 DPRINTF(("%s: packet replay check for %s\n", __func__,
526 ipsec_sa2str(sav, buf, sizeof(buf))));
527 ESPSTAT_INC(esps_replay);
531 SECASVAR_UNLOCK(sav);
534 /* Determine the ESP header length */
535 if (sav->flags & SADB_X_EXT_OLD)
536 hlen = sizeof (struct esp) + sav->ivlen;
538 hlen = sizeof (struct newesp) + sav->ivlen;
540 /* Remove the ESP header and IV from the mbuf. */
541 error = m_striphdr(m, skip, hlen);
543 ESPSTAT_INC(esps_hdrops);
544 DPRINTF(("%s: bad mbuf chain, SA %s/%08lx\n", __func__,
545 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
546 (u_long) ntohl(sav->spi)));
550 /* Save the last three bytes of decrypted data */
551 m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
553 /* Verify pad length */
554 if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
555 ESPSTAT_INC(esps_badilen);
556 DPRINTF(("%s: invalid padding length %d for %u byte packet "
557 "in SA %s/%08lx\n", __func__, lastthree[1],
558 m->m_pkthdr.len - skip,
559 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
560 (u_long) ntohl(sav->spi)));
565 /* Verify correct decryption by checking the last padding bytes */
566 if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
567 if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
568 ESPSTAT_INC(esps_badenc);
569 DPRINTF(("%s: decryption failed for packet in "
570 "SA %s/%08lx\n", __func__, ipsec_address(
571 &sav->sah->saidx.dst, buf, sizeof(buf)),
572 (u_long) ntohl(sav->spi)));
580 * Silently drop packet if next header field is IPPROTO_NONE.
582 if (lastthree[2] == IPPROTO_NONE)
585 /* Trim the mbuf chain to remove trailing authenticator and padding */
586 m_adj(m, -(lastthree[1] + 2));
588 /* Restore the Next Protocol field */
589 m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
591 switch (saidx->dst.sa.sa_family) {
594 error = ipsec6_common_input_cb(m, sav, skip, protoff);
599 error = ipsec4_common_input_cb(m, sav, skip, protoff);
603 panic("%s: Unexpected address family: %d saidx=%p", __func__,
604 saidx->dst.sa.sa_family, saidx);
621 * ESP output routine, called by ipsec[46]_perform_request().
624 esp_output(struct mbuf *m, struct secpolicy *sp, struct secasvar *sav,
625 u_int idx, int skip, int protoff)
627 IPSEC_DEBUG_DECLARE(char buf[IPSEC_ADDRSTRLEN]);
629 const struct auth_hash *esph;
630 const struct enc_xform *espx;
631 struct mbuf *mo = NULL;
632 struct xform_data *xd;
633 struct secasindex *saidx;
637 crypto_session_t cryptoid;
638 int hlen, rlen, padding, blks, alen, i, roff;
639 int error, maxpacketsize;
642 IPSEC_ASSERT(sav != NULL, ("null SA"));
643 esph = sav->tdb_authalgxform;
644 espx = sav->tdb_encalgxform;
645 IPSEC_ASSERT(espx != NULL, ("null encoding xform"));
647 if (sav->flags & SADB_X_EXT_OLD)
648 hlen = sizeof (struct esp) + sav->ivlen;
650 hlen = sizeof (struct newesp) + sav->ivlen;
652 rlen = m->m_pkthdr.len - skip; /* Raw payload length. */
654 * RFC4303 2.4 Requires 4 byte alignment.
655 * Old versions of FreeBSD can't decrypt partial blocks encrypted
656 * with AES-CTR. Align payload to native_blocksize (16 bytes)
657 * in order to preserve compatibility.
659 if (SAV_ISCTR(sav) && V_esp_ctr_compatibility)
660 blks = MAX(4, espx->native_blocksize); /* Cipher blocksize */
662 blks = MAX(4, espx->blocksize);
664 /* XXX clamp padding length a la KAME??? */
665 padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
667 alen = xform_ah_authsize(esph);
669 ESPSTAT_INC(esps_output);
671 saidx = &sav->sah->saidx;
672 /* Check for maximum packet size violations. */
673 switch (saidx->dst.sa.sa_family) {
676 maxpacketsize = IP_MAXPACKET;
681 maxpacketsize = IPV6_MAXPACKET;
685 DPRINTF(("%s: unknown/unsupported protocol "
686 "family %d, SA %s/%08lx\n", __func__,
687 saidx->dst.sa.sa_family, ipsec_address(&saidx->dst,
688 buf, sizeof(buf)), (u_long) ntohl(sav->spi)));
689 ESPSTAT_INC(esps_nopf);
690 error = EPFNOSUPPORT;
694 DPRINTF(("%s: skip %d hlen %d rlen %d padding %d alen %d blksd %d\n",
695 __func__, skip, hlen, rlen, padding, alen, blks)); */
696 if (skip + hlen + rlen + padding + alen > maxpacketsize) {
697 DPRINTF(("%s: packet in SA %s/%08lx got too big "
698 "(len %u, max len %u)\n", __func__,
699 ipsec_address(&saidx->dst, buf, sizeof(buf)),
700 (u_long) ntohl(sav->spi),
701 skip + hlen + rlen + padding + alen, maxpacketsize));
702 ESPSTAT_INC(esps_toobig);
707 /* Update the counters. */
708 ESPSTAT_ADD(esps_obytes, m->m_pkthdr.len - skip);
710 m = m_unshare(m, M_NOWAIT);
712 DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
713 ipsec_address(&saidx->dst, buf, sizeof(buf)),
714 (u_long) ntohl(sav->spi)));
715 ESPSTAT_INC(esps_hdrops);
720 /* Inject ESP header. */
721 mo = m_makespace(m, skip, hlen, &roff);
723 DPRINTF(("%s: %u byte ESP hdr inject failed for SA %s/%08lx\n",
724 __func__, hlen, ipsec_address(&saidx->dst, buf,
725 sizeof(buf)), (u_long) ntohl(sav->spi)));
726 ESPSTAT_INC(esps_hdrops); /* XXX diffs from openbsd */
731 /* Initialize ESP header. */
732 bcopy((caddr_t) &sav->spi, mtod(mo, caddr_t) + roff,
739 /* Emulate replay attack when ipsec_replay is TRUE. */
742 sav->replay->count++;
743 replay = htonl(sav->replay->count);
745 bcopy((caddr_t) &replay, mtod(mo, caddr_t) + roff +
746 sizeof(uint32_t), sizeof(uint32_t));
748 cryptoid = sav->tdb_cryptoid;
749 if (SAV_ISCTRORGCM(sav))
751 SECASVAR_UNLOCK(sav);
754 * Add padding -- better to do it ourselves than use the crypto engine,
755 * although if/when we support compression, we'd have to do that.
757 pad = (u_char *) m_pad(m, padding + alen);
759 DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
760 ipsec_address(&saidx->dst, buf, sizeof(buf)),
761 (u_long) ntohl(sav->spi)));
762 m = NULL; /* NB: free'd by m_pad */
768 * Add padding: random, zero, or self-describing.
769 * XXX catch unexpected setting
771 switch (sav->flags & SADB_X_EXT_PMASK) {
772 case SADB_X_EXT_PRAND:
773 arc4random_buf(pad, padding - 2);
775 case SADB_X_EXT_PZERO:
776 bzero(pad, padding - 2);
778 case SADB_X_EXT_PSEQ:
779 for (i = 0; i < padding - 2; i++)
784 /* Fix padding length and Next Protocol in padding itself. */
785 pad[padding - 2] = padding - 2;
786 m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
788 /* Fix Next Protocol in IPv4/IPv6 header. */
790 m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
792 /* Get crypto descriptor. */
793 crp = crypto_getreq(cryptoid, M_NOWAIT);
795 DPRINTF(("%s: failed to acquire crypto descriptor\n",
797 ESPSTAT_INC(esps_crypto);
802 /* IPsec-specific opaque crypto info. */
803 xd = malloc(sizeof(struct xform_data), M_XDATA, M_NOWAIT | M_ZERO);
806 DPRINTF(("%s: failed to allocate xform_data\n", __func__));
807 ESPSTAT_INC(esps_crypto);
812 /* Encryption descriptor. */
813 crp->crp_payload_start = skip + hlen;
814 crp->crp_payload_length = m->m_pkthdr.len - (skip + hlen + alen);
815 crp->crp_op = CRYPTO_OP_ENCRYPT;
817 /* Generate cipher and ESP IVs. */
818 ivp = &crp->crp_iv[0];
819 if (SAV_ISCTRORGCM(sav)) {
821 * See comment in esp_input() for details on the
822 * cipher IV. A simple per-SA counter stored in
823 * 'cntr' is used as the explicit ESP IV.
825 memcpy(ivp, sav->key_enc->key_data +
826 _KEYLEN(sav->key_enc) - 4, 4);
827 be64enc(&ivp[4], cntr);
828 if (SAV_ISCTR(sav)) {
829 be32enc(&ivp[sav->ivlen + 4], 1);
831 m_copyback(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
832 crp->crp_flags |= CRYPTO_F_IV_SEPARATE;
833 } else if (sav->ivlen != 0) {
834 arc4rand(ivp, sav->ivlen, 0);
835 crp->crp_iv_start = skip + hlen - sav->ivlen;
836 m_copyback(m, crp->crp_iv_start, sav->ivlen, ivp);
839 /* Callback parameters */
843 xd->cryptoid = cryptoid;
846 /* Crypto operation descriptor. */
847 crp->crp_flags |= CRYPTO_F_CBIFSYNC;
849 crp->crp_flags |= CRYPTO_F_ASYNC | CRYPTO_F_ASYNC_KEEPORDER;
850 crypto_use_mbuf(crp, m);
851 crp->crp_callback = esp_output_cb;
852 crp->crp_opaque = xd;
855 /* Authentication descriptor. */
856 crp->crp_op |= CRYPTO_OP_COMPUTE_DIGEST;
857 crp->crp_aad_start = skip;
859 crp->crp_aad_length = 8; /* RFC4106 5, SPI + SN */
861 crp->crp_aad_length = hlen;
862 crp->crp_digest_start = m->m_pkthdr.len - alen;
865 return crypto_dispatch(crp);
874 * ESP output callback from the crypto driver.
877 esp_output_cb(struct cryptop *crp)
879 struct xform_data *xd;
880 struct secpolicy *sp;
881 struct secasvar *sav;
883 crypto_session_t cryptoid;
887 xd = (struct xform_data *) crp->crp_opaque;
888 CURVNET_SET(xd->vnet);
889 m = crp->crp_buf.cb_mbuf;
893 cryptoid = xd->cryptoid;
895 /* Check for crypto errors. */
896 if (crp->crp_etype) {
897 if (crp->crp_etype == EAGAIN) {
898 /* Reset the session ID */
899 if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
900 crypto_freesession(cryptoid);
901 xd->cryptoid = crp->crp_session;
903 return (crypto_dispatch(crp));
905 ESPSTAT_INC(esps_noxform);
906 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
907 error = crp->crp_etype;
912 /* Shouldn't happen... */
914 ESPSTAT_INC(esps_crypto);
915 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
921 ESPSTAT_INC(esps_hist[sav->alg_enc]);
922 if (sav->tdb_authalgxform != NULL)
923 AHSTAT_INC(ahs_hist[sav->alg_auth]);
926 /* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
927 if (V_ipsec_integrity) {
928 static unsigned char ipseczeroes[AH_HMAC_MAXHASHLEN];
929 const struct auth_hash *esph;
932 * Corrupt HMAC if we want to test integrity verification of
935 esph = sav->tdb_authalgxform;
939 alen = xform_ah_authsize(esph);
940 m_copyback(m, m->m_pkthdr.len - alen,
946 /* NB: m is reclaimed by ipsec_process_done. */
947 error = ipsec_process_done(m, sp, sav, idx);
959 static struct xformsw esp_xformsw = {
961 .xf_name = "IPsec ESP",
963 .xf_cleanup = esp_cleanup,
964 .xf_input = esp_input,
965 .xf_output = esp_output,
968 SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
969 xform_attach, &esp_xformsw);
970 SYSUNINIT(esp_xform_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
971 xform_detach, &esp_xformsw);