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 SECASVAR_RLOCK_TRACKER;
279 IPSEC_ASSERT(sav != NULL, ("null SA"));
280 IPSEC_ASSERT(sav->tdb_encalgxform != NULL, ("null encoding xform"));
283 /* Valid IP Packet length ? */
284 if ( (skip&3) || (m->m_pkthdr.len&3) ){
285 DPRINTF(("%s: misaligned packet, skip %u pkt len %u",
286 __func__, skip, m->m_pkthdr.len));
287 ESPSTAT_INC(esps_badilen);
291 if (m->m_len < skip + sizeof(*esp)) {
292 m = m_pullup(m, skip + sizeof(*esp));
294 DPRINTF(("%s: cannot pullup header\n", __func__));
295 ESPSTAT_INC(esps_hdrops); /*XXX*/
300 esp = (struct newesp *)(mtod(m, caddr_t) + skip);
302 esph = sav->tdb_authalgxform;
303 espx = sav->tdb_encalgxform;
305 /* Determine the ESP header and auth length */
306 if (sav->flags & SADB_X_EXT_OLD)
307 hlen = sizeof (struct esp) + sav->ivlen;
309 hlen = sizeof (struct newesp) + sav->ivlen;
311 alen = xform_ah_authsize(esph);
314 * Verify payload length is multiple of encryption algorithm
317 * NB: This works for the null algorithm because the blocksize
318 * is 4 and all packets must be 4-byte aligned regardless
321 plen = m->m_pkthdr.len - (skip + hlen + alen);
322 if ((plen & (espx->blocksize - 1)) || (plen <= 0)) {
323 DPRINTF(("%s: payload of %d octets not a multiple of %d octets,"
324 " SA %s/%08lx\n", __func__, plen, espx->blocksize,
325 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
326 (u_long)ntohl(sav->spi)));
327 ESPSTAT_INC(esps_badilen);
332 * Check sequence number.
335 if (esph != NULL && sav->replay != NULL && sav->replay->wsize != 0) {
336 if (ipsec_chkreplay(ntohl(esp->esp_seq), &seqh, sav) == 0) {
337 SECASVAR_RUNLOCK(sav);
338 DPRINTF(("%s: packet replay check for %s\n", __func__,
339 ipsec_sa2str(sav, buf, sizeof(buf))));
340 ESPSTAT_INC(esps_replay);
346 cryptoid = sav->tdb_cryptoid;
347 SECASVAR_RUNLOCK(sav);
349 /* Update the counters */
350 ESPSTAT_ADD(esps_ibytes, m->m_pkthdr.len - (skip + hlen + alen));
352 /* Get crypto descriptors */
353 crp = crypto_getreq(cryptoid, M_NOWAIT);
355 DPRINTF(("%s: failed to acquire crypto descriptors\n",
357 ESPSTAT_INC(esps_crypto);
362 /* Get IPsec-specific opaque pointer */
363 xd = malloc(sizeof(*xd), M_ESP, M_NOWAIT | M_ZERO);
365 DPRINTF(("%s: failed to allocate xform_data\n", __func__));
370 crp->crp_op = CRYPTO_OP_VERIFY_DIGEST;
372 crp->crp_aad_length = 8; /* RFC4106 5, SPI + SN */
374 crp->crp_aad_length = hlen;
376 csp = crypto_get_params(crp->crp_session);
377 if ((csp->csp_flags & CSP_F_SEPARATE_AAD) &&
378 (sav->replay != NULL) && (sav->replay->wsize != 0)) {
381 crp->crp_aad_length += sizeof(seqh);
382 crp->crp_aad = malloc(crp->crp_aad_length, M_ESP, M_NOWAIT);
383 if (crp->crp_aad == NULL) {
384 DPRINTF(("%s: failed to allocate xform_data\n",
390 m_copydata(m, skip, SPI_SIZE, crp->crp_aad);
394 bcopy(&seqh, (char *)crp->crp_aad + aad_skip, sizeof(seqh));
395 aad_skip += sizeof(seqh);
398 if (crp->crp_aad_length - aad_skip > 0)
399 m_copydata(m, skip + SPI_SIZE,
400 crp->crp_aad_length - aad_skip,
401 (char *)crp->crp_aad + aad_skip);
403 crp->crp_aad_start = skip;
405 if (csp->csp_flags & CSP_F_ESN &&
406 sav->replay != NULL && sav->replay->wsize != 0)
407 memcpy(crp->crp_esn, &seqh, sizeof(seqh));
409 crp->crp_digest_start = m->m_pkthdr.len - alen;
412 /* Crypto operation descriptor */
413 crp->crp_flags = CRYPTO_F_CBIFSYNC;
415 crp->crp_flags |= CRYPTO_F_ASYNC | CRYPTO_F_ASYNC_KEEPORDER;
416 crypto_use_mbuf(crp, m);
417 crp->crp_callback = esp_input_cb;
418 crp->crp_opaque = xd;
420 /* These are passed as-is to the callback */
422 xd->protoff = protoff;
424 xd->cryptoid = cryptoid;
427 /* Decryption descriptor */
428 crp->crp_op |= CRYPTO_OP_DECRYPT;
429 crp->crp_payload_start = skip + hlen;
430 crp->crp_payload_length = m->m_pkthdr.len - (skip + hlen + alen);
432 /* Generate or read cipher IV. */
433 if (SAV_ISCTRORGCM(sav)) {
434 ivp = &crp->crp_iv[0];
437 * AES-GCM and AES-CTR use similar cipher IV formats
438 * defined in RFC 4106 section 4 and RFC 3686 section
441 * The first 4 bytes of the cipher IV contain an
442 * implicit salt, or nonce, obtained from the last 4
443 * bytes of the encryption key. The next 8 bytes hold
444 * an explicit IV unique to each packet. This
445 * explicit IV is used as the ESP IV for the packet.
446 * The last 4 bytes hold a big-endian block counter
447 * incremented for each block. For AES-GCM, the block
448 * counter's initial value is defined as part of the
449 * algorithm. For AES-CTR, the block counter's
450 * initial value for each packet is defined as 1 by
453 * ------------------------------------------
454 * | Salt | Explicit ESP IV | Block Counter |
455 * ------------------------------------------
456 * 4 bytes 8 bytes 4 bytes
458 memcpy(ivp, sav->key_enc->key_data +
459 _KEYLEN(sav->key_enc) - 4, 4);
460 m_copydata(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
461 if (SAV_ISCTR(sav)) {
462 be32enc(&ivp[sav->ivlen + 4], 1);
464 crp->crp_flags |= CRYPTO_F_IV_SEPARATE;
465 } else if (sav->ivlen != 0)
466 crp->crp_iv_start = skip + hlen - sav->ivlen;
468 return (crypto_dispatch(crp));
474 ESPSTAT_INC(esps_crypto);
483 * ESP input callback from the crypto driver.
486 esp_input_cb(struct cryptop *crp)
488 IPSEC_DEBUG_DECLARE(char buf[128]);
489 uint8_t lastthree[3];
490 const struct auth_hash *esph;
492 struct xform_data *xd;
493 struct secasvar *sav;
494 struct secasindex *saidx;
495 crypto_session_t cryptoid;
496 int hlen, skip, protoff, error, alen;
498 SECASVAR_RLOCK_TRACKER;
500 m = crp->crp_buf.cb_mbuf;
501 xd = crp->crp_opaque;
502 CURVNET_SET(xd->vnet);
505 protoff = xd->protoff;
506 cryptoid = xd->cryptoid;
507 saidx = &sav->sah->saidx;
508 esph = sav->tdb_authalgxform;
510 /* Check for crypto errors */
511 if (crp->crp_etype) {
512 if (crp->crp_etype == EAGAIN) {
513 /* Reset the session ID */
514 if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
515 crypto_freesession(cryptoid);
516 xd->cryptoid = crp->crp_session;
518 return (crypto_dispatch(crp));
521 /* EBADMSG indicates authentication failure. */
522 if (!(crp->crp_etype == EBADMSG && esph != NULL)) {
523 ESPSTAT_INC(esps_noxform);
524 DPRINTF(("%s: crypto error %d\n", __func__,
526 error = crp->crp_etype;
531 /* Shouldn't happen... */
533 ESPSTAT_INC(esps_crypto);
534 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
538 ESPSTAT_INC(esps_hist[sav->alg_enc]);
540 /* If authentication was performed, check now. */
542 alen = xform_ah_authsize(esph);
543 AHSTAT_INC(ahs_hist[sav->alg_auth]);
544 if (crp->crp_etype == EBADMSG) {
545 DPRINTF(("%s: authentication hash mismatch for "
546 "packet in SA %s/%08lx\n", __func__,
547 ipsec_address(&saidx->dst, buf, sizeof(buf)),
548 (u_long) ntohl(sav->spi)));
549 ESPSTAT_INC(esps_badauth);
553 m->m_flags |= M_AUTHIPDGM;
554 /* Remove trailing authenticator */
558 /* Release the crypto descriptors */
559 free(xd, M_ESP), xd = NULL;
560 free(crp->crp_aad, M_ESP), crp->crp_aad = NULL;
561 crypto_freereq(crp), crp = NULL;
564 * Packet is now decrypted.
566 m->m_flags |= M_DECRYPTED;
569 * Update replay sequence number, if appropriate.
574 m_copydata(m, skip + offsetof(struct newesp, esp_seq),
575 sizeof (seq), (caddr_t) &seq);
577 if (ipsec_updatereplay(ntohl(seq), sav)) {
578 SECASVAR_RUNLOCK(sav);
579 DPRINTF(("%s: packet replay check for %s\n", __func__,
580 ipsec_sa2str(sav, buf, sizeof(buf))));
581 ESPSTAT_INC(esps_replay);
585 SECASVAR_RUNLOCK(sav);
588 /* Determine the ESP header length */
589 if (sav->flags & SADB_X_EXT_OLD)
590 hlen = sizeof (struct esp) + sav->ivlen;
592 hlen = sizeof (struct newesp) + sav->ivlen;
594 /* Remove the ESP header and IV from the mbuf. */
595 error = m_striphdr(m, skip, hlen);
597 ESPSTAT_INC(esps_hdrops);
598 DPRINTF(("%s: bad mbuf chain, SA %s/%08lx\n", __func__,
599 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
600 (u_long) ntohl(sav->spi)));
604 /* Save the last three bytes of decrypted data */
605 m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
607 /* Verify pad length */
608 if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
609 ESPSTAT_INC(esps_badilen);
610 DPRINTF(("%s: invalid padding length %d for %u byte packet "
611 "in SA %s/%08lx\n", __func__, lastthree[1],
612 m->m_pkthdr.len - skip,
613 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
614 (u_long) ntohl(sav->spi)));
619 /* Verify correct decryption by checking the last padding bytes */
620 if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
621 if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
622 ESPSTAT_INC(esps_badenc);
623 DPRINTF(("%s: decryption failed for packet in "
624 "SA %s/%08lx\n", __func__, ipsec_address(
625 &sav->sah->saidx.dst, buf, sizeof(buf)),
626 (u_long) ntohl(sav->spi)));
634 * Silently drop packet if next header field is IPPROTO_NONE.
636 if (lastthree[2] == IPPROTO_NONE)
639 /* Trim the mbuf chain to remove trailing authenticator and padding */
640 m_adj(m, -(lastthree[1] + 2));
642 /* Restore the Next Protocol field */
643 m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
645 switch (saidx->dst.sa.sa_family) {
648 error = ipsec6_common_input_cb(m, sav, skip, protoff);
653 error = ipsec4_common_input_cb(m, sav, skip, protoff);
657 panic("%s: Unexpected address family: %d saidx=%p", __func__,
658 saidx->dst.sa.sa_family, saidx);
671 free(crp->crp_aad, M_ESP);
677 * ESP output routine, called by ipsec[46]_perform_request().
680 esp_output(struct mbuf *m, struct secpolicy *sp, struct secasvar *sav,
681 u_int idx, int skip, int protoff)
683 IPSEC_DEBUG_DECLARE(char buf[IPSEC_ADDRSTRLEN]);
685 const struct auth_hash *esph;
686 const struct enc_xform *espx;
687 struct mbuf *mo = NULL;
688 struct xform_data *xd;
689 struct secasindex *saidx;
693 crypto_session_t cryptoid;
694 int hlen, rlen, padding, blks, alen, i, roff;
695 int error, maxpacketsize;
698 const struct crypto_session_params *csp;
700 SECASVAR_RLOCK_TRACKER;
702 IPSEC_ASSERT(sav != NULL, ("null SA"));
703 esph = sav->tdb_authalgxform;
704 espx = sav->tdb_encalgxform;
705 IPSEC_ASSERT(espx != NULL, ("null encoding xform"));
707 if (sav->flags & SADB_X_EXT_OLD)
708 hlen = sizeof (struct esp) + sav->ivlen;
710 hlen = sizeof (struct newesp) + sav->ivlen;
712 rlen = m->m_pkthdr.len - skip; /* Raw payload length. */
714 * RFC4303 2.4 Requires 4 byte alignment.
715 * Old versions of FreeBSD can't decrypt partial blocks encrypted
716 * with AES-CTR. Align payload to native_blocksize (16 bytes)
717 * in order to preserve compatibility.
719 if (SAV_ISCTR(sav) && V_esp_ctr_compatibility)
720 blks = MAX(4, espx->native_blocksize); /* Cipher blocksize */
722 blks = MAX(4, espx->blocksize);
724 /* XXX clamp padding length a la KAME??? */
725 padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
727 alen = xform_ah_authsize(esph);
729 ESPSTAT_INC(esps_output);
731 saidx = &sav->sah->saidx;
732 /* Check for maximum packet size violations. */
733 switch (saidx->dst.sa.sa_family) {
736 maxpacketsize = IP_MAXPACKET;
741 maxpacketsize = IPV6_MAXPACKET;
745 DPRINTF(("%s: unknown/unsupported protocol "
746 "family %d, SA %s/%08lx\n", __func__,
747 saidx->dst.sa.sa_family, ipsec_address(&saidx->dst,
748 buf, sizeof(buf)), (u_long) ntohl(sav->spi)));
749 ESPSTAT_INC(esps_nopf);
750 error = EPFNOSUPPORT;
754 DPRINTF(("%s: skip %d hlen %d rlen %d padding %d alen %d blksd %d\n",
755 __func__, skip, hlen, rlen, padding, alen, blks)); */
756 if (skip + hlen + rlen + padding + alen > maxpacketsize) {
757 DPRINTF(("%s: packet in SA %s/%08lx got too big "
758 "(len %u, max len %u)\n", __func__,
759 ipsec_address(&saidx->dst, buf, sizeof(buf)),
760 (u_long) ntohl(sav->spi),
761 skip + hlen + rlen + padding + alen, maxpacketsize));
762 ESPSTAT_INC(esps_toobig);
767 /* Update the counters. */
768 ESPSTAT_ADD(esps_obytes, m->m_pkthdr.len - skip);
770 m = m_unshare(m, M_NOWAIT);
772 DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
773 ipsec_address(&saidx->dst, buf, sizeof(buf)),
774 (u_long) ntohl(sav->spi)));
775 ESPSTAT_INC(esps_hdrops);
780 /* Inject ESP header. */
781 mo = m_makespace(m, skip, hlen, &roff);
783 DPRINTF(("%s: %u byte ESP hdr inject failed for SA %s/%08lx\n",
784 __func__, hlen, ipsec_address(&saidx->dst, buf,
785 sizeof(buf)), (u_long) ntohl(sav->spi)));
786 ESPSTAT_INC(esps_hdrops); /* XXX diffs from openbsd */
791 /* Initialize ESP header. */
792 bcopy((caddr_t) &sav->spi, mtod(mo, caddr_t) + roff,
798 SECREPLAY_LOCK(sav->replay);
800 /* Emulate replay attack when ipsec_replay is TRUE. */
803 sav->replay->count++;
804 replay = htonl((uint32_t)sav->replay->count);
806 bcopy((caddr_t) &replay, mtod(mo, caddr_t) + roff +
807 sizeof(uint32_t), sizeof(uint32_t));
809 seqh = htonl((uint32_t)(sav->replay->count >> IPSEC_SEQH_SHIFT));
810 SECREPLAY_UNLOCK(sav->replay);
812 cryptoid = sav->tdb_cryptoid;
813 if (SAV_ISCTRORGCM(sav))
815 SECASVAR_RUNLOCK(sav);
818 * Add padding -- better to do it ourselves than use the crypto engine,
819 * although if/when we support compression, we'd have to do that.
821 pad = (u_char *) m_pad(m, padding + alen);
823 DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
824 ipsec_address(&saidx->dst, buf, sizeof(buf)),
825 (u_long) ntohl(sav->spi)));
826 m = NULL; /* NB: free'd by m_pad */
832 * Add padding: random, zero, or self-describing.
833 * XXX catch unexpected setting
835 switch (sav->flags & SADB_X_EXT_PMASK) {
836 case SADB_X_EXT_PRAND:
837 arc4random_buf(pad, padding - 2);
839 case SADB_X_EXT_PZERO:
840 bzero(pad, padding - 2);
842 case SADB_X_EXT_PSEQ:
843 for (i = 0; i < padding - 2; i++)
848 /* Fix padding length and Next Protocol in padding itself. */
849 pad[padding - 2] = padding - 2;
850 m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
852 /* Fix Next Protocol in IPv4/IPv6 header. */
854 m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
856 /* Get crypto descriptor. */
857 crp = crypto_getreq(cryptoid, M_NOWAIT);
859 DPRINTF(("%s: failed to acquire crypto descriptor\n",
861 ESPSTAT_INC(esps_crypto);
866 /* IPsec-specific opaque crypto info. */
867 xd = malloc(sizeof(struct xform_data), M_ESP, M_NOWAIT | M_ZERO);
869 DPRINTF(("%s: failed to allocate xform_data\n", __func__));
873 /* Encryption descriptor. */
874 crp->crp_payload_start = skip + hlen;
875 crp->crp_payload_length = m->m_pkthdr.len - (skip + hlen + alen);
876 crp->crp_op = CRYPTO_OP_ENCRYPT;
878 /* Generate cipher and ESP IVs. */
879 ivp = &crp->crp_iv[0];
880 if (SAV_ISCTRORGCM(sav)) {
882 * See comment in esp_input() for details on the
883 * cipher IV. A simple per-SA counter stored in
884 * 'cntr' is used as the explicit ESP IV.
886 memcpy(ivp, sav->key_enc->key_data +
887 _KEYLEN(sav->key_enc) - 4, 4);
888 be64enc(&ivp[4], cntr);
889 if (SAV_ISCTR(sav)) {
890 be32enc(&ivp[sav->ivlen + 4], 1);
892 m_copyback(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
893 crp->crp_flags |= CRYPTO_F_IV_SEPARATE;
894 } else if (sav->ivlen != 0) {
895 arc4rand(ivp, sav->ivlen, 0);
896 crp->crp_iv_start = skip + hlen - sav->ivlen;
897 m_copyback(m, crp->crp_iv_start, sav->ivlen, ivp);
900 /* Callback parameters */
904 xd->cryptoid = cryptoid;
907 /* Crypto operation descriptor. */
908 crp->crp_flags |= CRYPTO_F_CBIFSYNC;
910 crp->crp_flags |= CRYPTO_F_ASYNC | CRYPTO_F_ASYNC_KEEPORDER;
911 crypto_use_mbuf(crp, m);
912 crp->crp_callback = esp_output_cb;
913 crp->crp_opaque = xd;
916 /* Authentication descriptor. */
917 crp->crp_op |= CRYPTO_OP_COMPUTE_DIGEST;
919 crp->crp_aad_length = 8; /* RFC4106 5, SPI + SN */
921 crp->crp_aad_length = hlen;
923 csp = crypto_get_params(crp->crp_session);
924 if (csp->csp_flags & CSP_F_SEPARATE_AAD &&
925 sav->replay != NULL) {
928 crp->crp_aad_length += sizeof(seqh);
929 crp->crp_aad = malloc(crp->crp_aad_length, M_ESP, M_NOWAIT);
930 if (crp->crp_aad == NULL) {
931 DPRINTF(("%s: failed to allocate xform_data\n",
937 m_copydata(m, skip, SPI_SIZE, crp->crp_aad);
941 bcopy(&seqh, (char *)crp->crp_aad + aad_skip, sizeof(seqh));
942 aad_skip += sizeof(seqh);
945 if (crp->crp_aad_length - aad_skip > 0)
946 m_copydata(m, skip + SPI_SIZE,
947 crp->crp_aad_length - aad_skip,
948 (char *)crp->crp_aad + aad_skip);
950 crp->crp_aad_start = skip;
952 if (csp->csp_flags & CSP_F_ESN && sav->replay != NULL)
953 memcpy(crp->crp_esn, &seqh, sizeof(seqh));
955 crp->crp_digest_start = m->m_pkthdr.len - alen;
958 return crypto_dispatch(crp);
964 ESPSTAT_INC(esps_crypto);
974 * ESP output callback from the crypto driver.
977 esp_output_cb(struct cryptop *crp)
979 struct xform_data *xd;
980 struct secpolicy *sp;
981 struct secasvar *sav;
983 crypto_session_t cryptoid;
987 xd = (struct xform_data *) crp->crp_opaque;
988 CURVNET_SET(xd->vnet);
989 m = crp->crp_buf.cb_mbuf;
993 cryptoid = xd->cryptoid;
995 /* Check for crypto errors. */
996 if (crp->crp_etype) {
997 if (crp->crp_etype == EAGAIN) {
998 /* Reset the session ID */
999 if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
1000 crypto_freesession(cryptoid);
1001 xd->cryptoid = crp->crp_session;
1003 return (crypto_dispatch(crp));
1005 ESPSTAT_INC(esps_noxform);
1006 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
1007 error = crp->crp_etype;
1012 /* Shouldn't happen... */
1014 ESPSTAT_INC(esps_crypto);
1015 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
1020 free(crp->crp_aad, M_ESP);
1021 crypto_freereq(crp);
1022 ESPSTAT_INC(esps_hist[sav->alg_enc]);
1023 if (sav->tdb_authalgxform != NULL)
1024 AHSTAT_INC(ahs_hist[sav->alg_auth]);
1027 /* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
1028 if (V_ipsec_integrity) {
1029 static unsigned char ipseczeroes[AH_HMAC_MAXHASHLEN];
1030 const struct auth_hash *esph;
1033 * Corrupt HMAC if we want to test integrity verification of
1036 esph = sav->tdb_authalgxform;
1040 alen = xform_ah_authsize(esph);
1041 m_copyback(m, m->m_pkthdr.len - alen,
1047 /* NB: m is reclaimed by ipsec_process_done. */
1048 error = ipsec_process_done(m, sp, sav, idx);
1054 free(crp->crp_aad, M_ESP);
1055 crypto_freereq(crp);
1061 static struct xformsw esp_xformsw = {
1063 .xf_name = "IPsec ESP",
1064 .xf_init = esp_init,
1065 .xf_cleanup = esp_cleanup,
1066 .xf_input = esp_input,
1067 .xf_output = esp_output,
1070 SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
1071 xform_attach, &esp_xformsw);
1072 SYSUNINIT(esp_xform_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
1073 xform_detach, &esp_xformsw);