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>
85 VNET_DEFINE(int, esp_enable) = 1;
86 VNET_DEFINE_STATIC(int, esp_ctr_compatibility) = 1;
87 #define V_esp_ctr_compatibility VNET(esp_ctr_compatibility)
88 VNET_PCPUSTAT_DEFINE(struct espstat, espstat);
89 VNET_PCPUSTAT_SYSINIT(espstat);
92 VNET_PCPUSTAT_SYSUNINIT(espstat);
95 SYSCTL_DECL(_net_inet_esp);
96 SYSCTL_INT(_net_inet_esp, OID_AUTO, esp_enable,
97 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(esp_enable), 0, "");
98 SYSCTL_INT(_net_inet_esp, OID_AUTO, ctr_compatibility,
99 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(esp_ctr_compatibility), 0,
100 "Align AES-CTR encrypted transmitted frames to blocksize");
101 SYSCTL_VNET_PCPUSTAT(_net_inet_esp, IPSECCTL_STATS, stats,
102 struct espstat, espstat,
103 "ESP statistics (struct espstat, netipsec/esp_var.h");
105 static int esp_input_cb(struct cryptop *op);
106 static int esp_output_cb(struct cryptop *crp);
109 esp_hdrsiz(struct secasvar *sav)
114 /*XXX not right for null algorithm--does it matter??*/
115 IPSEC_ASSERT(sav->tdb_encalgxform != NULL,
116 ("SA with null xform"));
117 if (sav->flags & SADB_X_EXT_OLD)
118 size = sizeof (struct esp);
120 size = sizeof (struct newesp);
121 size += sav->tdb_encalgxform->blocksize + 9;
122 /*XXX need alg check???*/
123 if (sav->tdb_authalgxform != NULL && sav->replay)
124 size += ah_hdrsiz(sav);
128 * + max iv length for CBC mode
130 * + sizeof (pad length field)
131 * + sizeof (next header field)
132 * + max icv supported.
134 size = sizeof (struct newesp) + EALG_MAX_BLOCK_LEN + 9 + 16;
140 * esp_init() is called when an SPI is being set up.
143 esp_init(struct secasvar *sav, struct xformsw *xsp)
145 const struct enc_xform *txform;
146 struct crypto_session_params csp;
150 txform = enc_algorithm_lookup(sav->alg_enc);
151 if (txform == NULL) {
152 DPRINTF(("%s: unsupported encryption algorithm %d\n",
153 __func__, sav->alg_enc));
156 if (sav->key_enc == NULL) {
157 DPRINTF(("%s: no encoding key for %s algorithm\n",
158 __func__, txform->name));
161 if ((sav->flags & (SADB_X_EXT_OLD | SADB_X_EXT_IV4B)) ==
163 DPRINTF(("%s: 4-byte IV not supported with protocol\n",
168 /* subtract off the salt, RFC4106, 8.1 and RFC3686, 5.1 */
169 keylen = _KEYLEN(sav->key_enc) - SAV_ISCTRORGCM(sav) * 4;
170 if (txform->minkey > keylen || keylen > txform->maxkey) {
171 DPRINTF(("%s: invalid key length %u, must be in the range "
172 "[%u..%u] for algorithm %s\n", __func__,
173 keylen, txform->minkey, txform->maxkey,
178 if (SAV_ISCTRORGCM(sav))
179 sav->ivlen = 8; /* RFC4106 3.1 and RFC3686 3.1 */
181 sav->ivlen = txform->ivsize;
183 memset(&csp, 0, sizeof(csp));
186 * Setup AH-related state.
188 if (sav->alg_auth != 0) {
189 error = ah_init0(sav, xsp, &csp);
194 /* NB: override anything set in ah_init0 */
195 sav->tdb_xform = xsp;
196 sav->tdb_encalgxform = txform;
199 * Whenever AES-GCM is used for encryption, one
200 * of the AES authentication algorithms is chosen
201 * as well, based on the key size.
203 if (sav->alg_enc == SADB_X_EALG_AESGCM16) {
205 case AES_128_GMAC_KEY_LEN:
206 sav->alg_auth = SADB_X_AALG_AES128GMAC;
207 sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_128;
209 case AES_192_GMAC_KEY_LEN:
210 sav->alg_auth = SADB_X_AALG_AES192GMAC;
211 sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_192;
213 case AES_256_GMAC_KEY_LEN:
214 sav->alg_auth = SADB_X_AALG_AES256GMAC;
215 sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_256;
218 DPRINTF(("%s: invalid key length %u"
219 "for algorithm %s\n", __func__,
220 keylen, txform->name));
223 csp.csp_mode = CSP_MODE_AEAD;
224 if (sav->flags & SADB_X_SAFLAGS_ESN)
225 csp.csp_flags |= CSP_F_SEPARATE_AAD;
226 } else if (sav->alg_auth != 0) {
227 csp.csp_mode = CSP_MODE_ETA;
228 if (sav->flags & SADB_X_SAFLAGS_ESN)
229 csp.csp_flags |= CSP_F_ESN;
231 csp.csp_mode = CSP_MODE_CIPHER;
233 /* Initialize crypto session. */
234 csp.csp_cipher_alg = sav->tdb_encalgxform->type;
235 if (csp.csp_cipher_alg != CRYPTO_NULL_CBC) {
236 csp.csp_cipher_key = sav->key_enc->key_data;
237 csp.csp_cipher_klen = _KEYBITS(sav->key_enc) / 8 -
238 SAV_ISCTRORGCM(sav) * 4;
240 csp.csp_ivlen = txform->ivsize;
242 error = crypto_newsession(&sav->tdb_cryptoid, &csp, V_crypto_support);
247 esp_cleanup(struct secasvar *sav)
250 crypto_freesession(sav->tdb_cryptoid);
251 sav->tdb_cryptoid = NULL;
252 sav->tdb_authalgxform = NULL;
253 sav->tdb_encalgxform = NULL;
257 * ESP input processing, called (eventually) through the protocol switch.
260 esp_input(struct mbuf *m, struct secasvar *sav, int skip, int protoff)
262 IPSEC_DEBUG_DECLARE(char buf[128]);
263 const struct auth_hash *esph;
264 const struct enc_xform *espx;
265 struct xform_data *xd;
269 crypto_session_t cryptoid;
270 int alen, error, hlen, plen;
272 const struct crypto_session_params *csp;
274 IPSEC_ASSERT(sav != NULL, ("null SA"));
275 IPSEC_ASSERT(sav->tdb_encalgxform != NULL, ("null encoding xform"));
278 /* Valid IP Packet length ? */
279 if ( (skip&3) || (m->m_pkthdr.len&3) ){
280 DPRINTF(("%s: misaligned packet, skip %u pkt len %u",
281 __func__, skip, m->m_pkthdr.len));
282 ESPSTAT_INC(esps_badilen);
286 if (m->m_len < skip + sizeof(*esp)) {
287 m = m_pullup(m, skip + sizeof(*esp));
289 DPRINTF(("%s: cannot pullup header\n", __func__));
290 ESPSTAT_INC(esps_hdrops); /*XXX*/
295 esp = (struct newesp *)(mtod(m, caddr_t) + skip);
297 esph = sav->tdb_authalgxform;
298 espx = sav->tdb_encalgxform;
300 /* Determine the ESP header and auth length */
301 if (sav->flags & SADB_X_EXT_OLD)
302 hlen = sizeof (struct esp) + sav->ivlen;
304 hlen = sizeof (struct newesp) + sav->ivlen;
306 alen = xform_ah_authsize(esph);
309 * Verify payload length is multiple of encryption algorithm
312 * NB: This works for the null algorithm because the blocksize
313 * is 4 and all packets must be 4-byte aligned regardless
316 plen = m->m_pkthdr.len - (skip + hlen + alen);
317 if ((plen & (espx->blocksize - 1)) || (plen <= 0)) {
318 DPRINTF(("%s: payload of %d octets not a multiple of %d octets,"
319 " SA %s/%08lx\n", __func__, plen, espx->blocksize,
320 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
321 (u_long)ntohl(sav->spi)));
322 ESPSTAT_INC(esps_badilen);
327 * Check sequence number.
330 if (esph != NULL && sav->replay != NULL && sav->replay->wsize != 0) {
331 if (ipsec_chkreplay(ntohl(esp->esp_seq), &seqh, sav) == 0) {
332 SECASVAR_UNLOCK(sav);
333 DPRINTF(("%s: packet replay check for %s\n", __func__,
334 ipsec_sa2str(sav, buf, sizeof(buf))));
335 ESPSTAT_INC(esps_replay);
341 cryptoid = sav->tdb_cryptoid;
342 SECASVAR_UNLOCK(sav);
344 /* Update the counters */
345 ESPSTAT_ADD(esps_ibytes, m->m_pkthdr.len - (skip + hlen + alen));
347 /* Get crypto descriptors */
348 crp = crypto_getreq(cryptoid, M_NOWAIT);
350 DPRINTF(("%s: failed to acquire crypto descriptors\n",
352 ESPSTAT_INC(esps_crypto);
357 /* Get IPsec-specific opaque pointer */
358 xd = malloc(sizeof(*xd), M_XDATA, M_NOWAIT | M_ZERO);
360 DPRINTF(("%s: failed to allocate xform_data\n", __func__));
365 crp->crp_op = CRYPTO_OP_VERIFY_DIGEST;
367 crp->crp_aad_length = 8; /* RFC4106 5, SPI + SN */
369 crp->crp_aad_length = hlen;
371 csp = crypto_get_params(crp->crp_session);
372 if ((csp->csp_flags & CSP_F_SEPARATE_AAD) &&
373 (sav->replay != NULL) && (sav->replay->wsize != 0)) {
376 crp->crp_aad_length += sizeof(seqh);
377 crp->crp_aad = malloc(crp->crp_aad_length, M_XDATA, M_NOWAIT);
378 if (crp->crp_aad == NULL) {
379 DPRINTF(("%s: failed to allocate xform_data\n",
385 m_copydata(m, skip, SPI_SIZE, crp->crp_aad);
389 bcopy(&seqh, (char *)crp->crp_aad + aad_skip, sizeof(seqh));
390 aad_skip += sizeof(seqh);
393 if (crp->crp_aad_length - aad_skip > 0)
394 m_copydata(m, skip + SPI_SIZE,
395 crp->crp_aad_length - aad_skip,
396 (char *)crp->crp_aad + aad_skip);
398 crp->crp_aad_start = skip;
400 if (csp->csp_flags & CSP_F_ESN &&
401 sav->replay != NULL && sav->replay->wsize != 0)
402 memcpy(crp->crp_esn, &seqh, sizeof(seqh));
404 crp->crp_digest_start = m->m_pkthdr.len - alen;
407 /* Crypto operation descriptor */
408 crp->crp_flags = CRYPTO_F_CBIFSYNC;
410 crp->crp_flags |= CRYPTO_F_ASYNC | CRYPTO_F_ASYNC_KEEPORDER;
411 crypto_use_mbuf(crp, m);
412 crp->crp_callback = esp_input_cb;
413 crp->crp_opaque = xd;
415 /* These are passed as-is to the callback */
417 xd->protoff = protoff;
419 xd->cryptoid = cryptoid;
422 /* Decryption descriptor */
423 crp->crp_op |= CRYPTO_OP_DECRYPT;
424 crp->crp_payload_start = skip + hlen;
425 crp->crp_payload_length = m->m_pkthdr.len - (skip + hlen + alen);
427 /* Generate or read cipher IV. */
428 if (SAV_ISCTRORGCM(sav)) {
429 ivp = &crp->crp_iv[0];
432 * AES-GCM and AES-CTR use similar cipher IV formats
433 * defined in RFC 4106 section 4 and RFC 3686 section
436 * The first 4 bytes of the cipher IV contain an
437 * implicit salt, or nonce, obtained from the last 4
438 * bytes of the encryption key. The next 8 bytes hold
439 * an explicit IV unique to each packet. This
440 * explicit IV is used as the ESP IV for the packet.
441 * The last 4 bytes hold a big-endian block counter
442 * incremented for each block. For AES-GCM, the block
443 * counter's initial value is defined as part of the
444 * algorithm. For AES-CTR, the block counter's
445 * initial value for each packet is defined as 1 by
448 * ------------------------------------------
449 * | Salt | Explicit ESP IV | Block Counter |
450 * ------------------------------------------
451 * 4 bytes 8 bytes 4 bytes
453 memcpy(ivp, sav->key_enc->key_data +
454 _KEYLEN(sav->key_enc) - 4, 4);
455 m_copydata(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
456 if (SAV_ISCTR(sav)) {
457 be32enc(&ivp[sav->ivlen + 4], 1);
459 crp->crp_flags |= CRYPTO_F_IV_SEPARATE;
460 } else if (sav->ivlen != 0)
461 crp->crp_iv_start = skip + hlen - sav->ivlen;
463 return (crypto_dispatch(crp));
469 ESPSTAT_INC(esps_crypto);
478 * ESP input callback from the crypto driver.
481 esp_input_cb(struct cryptop *crp)
483 IPSEC_DEBUG_DECLARE(char buf[128]);
484 uint8_t lastthree[3];
485 const struct auth_hash *esph;
487 struct xform_data *xd;
488 struct secasvar *sav;
489 struct secasindex *saidx;
490 crypto_session_t cryptoid;
491 int hlen, skip, protoff, error, alen;
493 m = crp->crp_buf.cb_mbuf;
494 xd = crp->crp_opaque;
495 CURVNET_SET(xd->vnet);
498 protoff = xd->protoff;
499 cryptoid = xd->cryptoid;
500 saidx = &sav->sah->saidx;
501 esph = sav->tdb_authalgxform;
503 /* Check for crypto errors */
504 if (crp->crp_etype) {
505 if (crp->crp_etype == EAGAIN) {
506 /* Reset the session ID */
507 if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
508 crypto_freesession(cryptoid);
509 xd->cryptoid = crp->crp_session;
511 return (crypto_dispatch(crp));
514 /* EBADMSG indicates authentication failure. */
515 if (!(crp->crp_etype == EBADMSG && esph != NULL)) {
516 ESPSTAT_INC(esps_noxform);
517 DPRINTF(("%s: crypto error %d\n", __func__,
519 error = crp->crp_etype;
524 /* Shouldn't happen... */
526 ESPSTAT_INC(esps_crypto);
527 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
531 ESPSTAT_INC(esps_hist[sav->alg_enc]);
533 /* If authentication was performed, check now. */
535 alen = xform_ah_authsize(esph);
536 AHSTAT_INC(ahs_hist[sav->alg_auth]);
537 if (crp->crp_etype == EBADMSG) {
538 DPRINTF(("%s: authentication hash mismatch for "
539 "packet in SA %s/%08lx\n", __func__,
540 ipsec_address(&saidx->dst, buf, sizeof(buf)),
541 (u_long) ntohl(sav->spi)));
542 ESPSTAT_INC(esps_badauth);
546 m->m_flags |= M_AUTHIPDGM;
547 /* Remove trailing authenticator */
551 /* Release the crypto descriptors */
552 free(xd, M_XDATA), xd = NULL;
553 free(crp->crp_aad, M_XDATA), crp->crp_aad = NULL;
554 crypto_freereq(crp), crp = NULL;
557 * Packet is now decrypted.
559 m->m_flags |= M_DECRYPTED;
562 * Update replay sequence number, if appropriate.
567 m_copydata(m, skip + offsetof(struct newesp, esp_seq),
568 sizeof (seq), (caddr_t) &seq);
570 if (ipsec_updatereplay(ntohl(seq), sav)) {
571 SECASVAR_UNLOCK(sav);
572 DPRINTF(("%s: packet replay check for %s\n", __func__,
573 ipsec_sa2str(sav, buf, sizeof(buf))));
574 ESPSTAT_INC(esps_replay);
578 SECASVAR_UNLOCK(sav);
581 /* Determine the ESP header length */
582 if (sav->flags & SADB_X_EXT_OLD)
583 hlen = sizeof (struct esp) + sav->ivlen;
585 hlen = sizeof (struct newesp) + sav->ivlen;
587 /* Remove the ESP header and IV from the mbuf. */
588 error = m_striphdr(m, skip, hlen);
590 ESPSTAT_INC(esps_hdrops);
591 DPRINTF(("%s: bad mbuf chain, SA %s/%08lx\n", __func__,
592 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
593 (u_long) ntohl(sav->spi)));
597 /* Save the last three bytes of decrypted data */
598 m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
600 /* Verify pad length */
601 if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
602 ESPSTAT_INC(esps_badilen);
603 DPRINTF(("%s: invalid padding length %d for %u byte packet "
604 "in SA %s/%08lx\n", __func__, lastthree[1],
605 m->m_pkthdr.len - skip,
606 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
607 (u_long) ntohl(sav->spi)));
612 /* Verify correct decryption by checking the last padding bytes */
613 if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
614 if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
615 ESPSTAT_INC(esps_badenc);
616 DPRINTF(("%s: decryption failed for packet in "
617 "SA %s/%08lx\n", __func__, ipsec_address(
618 &sav->sah->saidx.dst, buf, sizeof(buf)),
619 (u_long) ntohl(sav->spi)));
627 * Silently drop packet if next header field is IPPROTO_NONE.
629 if (lastthree[2] == IPPROTO_NONE)
632 /* Trim the mbuf chain to remove trailing authenticator and padding */
633 m_adj(m, -(lastthree[1] + 2));
635 /* Restore the Next Protocol field */
636 m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
638 switch (saidx->dst.sa.sa_family) {
641 error = ipsec6_common_input_cb(m, sav, skip, protoff);
646 error = ipsec4_common_input_cb(m, sav, skip, protoff);
650 panic("%s: Unexpected address family: %d saidx=%p", __func__,
651 saidx->dst.sa.sa_family, saidx);
664 free(crp->crp_aad, M_XDATA);
670 * ESP output routine, called by ipsec[46]_perform_request().
673 esp_output(struct mbuf *m, struct secpolicy *sp, struct secasvar *sav,
674 u_int idx, int skip, int protoff)
676 IPSEC_DEBUG_DECLARE(char buf[IPSEC_ADDRSTRLEN]);
678 const struct auth_hash *esph;
679 const struct enc_xform *espx;
680 struct mbuf *mo = NULL;
681 struct xform_data *xd;
682 struct secasindex *saidx;
686 crypto_session_t cryptoid;
687 int hlen, rlen, padding, blks, alen, i, roff;
688 int error, maxpacketsize;
691 const struct crypto_session_params *csp;
693 IPSEC_ASSERT(sav != NULL, ("null SA"));
694 esph = sav->tdb_authalgxform;
695 espx = sav->tdb_encalgxform;
696 IPSEC_ASSERT(espx != NULL, ("null encoding xform"));
698 if (sav->flags & SADB_X_EXT_OLD)
699 hlen = sizeof (struct esp) + sav->ivlen;
701 hlen = sizeof (struct newesp) + sav->ivlen;
703 rlen = m->m_pkthdr.len - skip; /* Raw payload length. */
705 * RFC4303 2.4 Requires 4 byte alignment.
706 * Old versions of FreeBSD can't decrypt partial blocks encrypted
707 * with AES-CTR. Align payload to native_blocksize (16 bytes)
708 * in order to preserve compatibility.
710 if (SAV_ISCTR(sav) && V_esp_ctr_compatibility)
711 blks = MAX(4, espx->native_blocksize); /* Cipher blocksize */
713 blks = MAX(4, espx->blocksize);
715 /* XXX clamp padding length a la KAME??? */
716 padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
718 alen = xform_ah_authsize(esph);
720 ESPSTAT_INC(esps_output);
722 saidx = &sav->sah->saidx;
723 /* Check for maximum packet size violations. */
724 switch (saidx->dst.sa.sa_family) {
727 maxpacketsize = IP_MAXPACKET;
732 maxpacketsize = IPV6_MAXPACKET;
736 DPRINTF(("%s: unknown/unsupported protocol "
737 "family %d, SA %s/%08lx\n", __func__,
738 saidx->dst.sa.sa_family, ipsec_address(&saidx->dst,
739 buf, sizeof(buf)), (u_long) ntohl(sav->spi)));
740 ESPSTAT_INC(esps_nopf);
741 error = EPFNOSUPPORT;
745 DPRINTF(("%s: skip %d hlen %d rlen %d padding %d alen %d blksd %d\n",
746 __func__, skip, hlen, rlen, padding, alen, blks)); */
747 if (skip + hlen + rlen + padding + alen > maxpacketsize) {
748 DPRINTF(("%s: packet in SA %s/%08lx got too big "
749 "(len %u, max len %u)\n", __func__,
750 ipsec_address(&saidx->dst, buf, sizeof(buf)),
751 (u_long) ntohl(sav->spi),
752 skip + hlen + rlen + padding + alen, maxpacketsize));
753 ESPSTAT_INC(esps_toobig);
758 /* Update the counters. */
759 ESPSTAT_ADD(esps_obytes, m->m_pkthdr.len - skip);
761 m = m_unshare(m, M_NOWAIT);
763 DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
764 ipsec_address(&saidx->dst, buf, sizeof(buf)),
765 (u_long) ntohl(sav->spi)));
766 ESPSTAT_INC(esps_hdrops);
771 /* Inject ESP header. */
772 mo = m_makespace(m, skip, hlen, &roff);
774 DPRINTF(("%s: %u byte ESP hdr inject failed for SA %s/%08lx\n",
775 __func__, hlen, ipsec_address(&saidx->dst, buf,
776 sizeof(buf)), (u_long) ntohl(sav->spi)));
777 ESPSTAT_INC(esps_hdrops); /* XXX diffs from openbsd */
782 /* Initialize ESP header. */
783 bcopy((caddr_t) &sav->spi, mtod(mo, caddr_t) + roff,
790 /* Emulate replay attack when ipsec_replay is TRUE. */
793 sav->replay->count++;
794 replay = htonl((uint32_t)sav->replay->count);
796 bcopy((caddr_t) &replay, mtod(mo, caddr_t) + roff +
797 sizeof(uint32_t), sizeof(uint32_t));
799 seqh = htonl((uint32_t)(sav->replay->count >> IPSEC_SEQH_SHIFT));
801 cryptoid = sav->tdb_cryptoid;
802 if (SAV_ISCTRORGCM(sav))
804 SECASVAR_UNLOCK(sav);
807 * Add padding -- better to do it ourselves than use the crypto engine,
808 * although if/when we support compression, we'd have to do that.
810 pad = (u_char *) m_pad(m, padding + alen);
812 DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
813 ipsec_address(&saidx->dst, buf, sizeof(buf)),
814 (u_long) ntohl(sav->spi)));
815 m = NULL; /* NB: free'd by m_pad */
821 * Add padding: random, zero, or self-describing.
822 * XXX catch unexpected setting
824 switch (sav->flags & SADB_X_EXT_PMASK) {
825 case SADB_X_EXT_PRAND:
826 arc4random_buf(pad, padding - 2);
828 case SADB_X_EXT_PZERO:
829 bzero(pad, padding - 2);
831 case SADB_X_EXT_PSEQ:
832 for (i = 0; i < padding - 2; i++)
837 /* Fix padding length and Next Protocol in padding itself. */
838 pad[padding - 2] = padding - 2;
839 m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
841 /* Fix Next Protocol in IPv4/IPv6 header. */
843 m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
845 /* Get crypto descriptor. */
846 crp = crypto_getreq(cryptoid, M_NOWAIT);
848 DPRINTF(("%s: failed to acquire crypto descriptor\n",
850 ESPSTAT_INC(esps_crypto);
855 /* IPsec-specific opaque crypto info. */
856 xd = malloc(sizeof(struct xform_data), M_XDATA, M_NOWAIT | M_ZERO);
858 DPRINTF(("%s: failed to allocate xform_data\n", __func__));
862 /* Encryption descriptor. */
863 crp->crp_payload_start = skip + hlen;
864 crp->crp_payload_length = m->m_pkthdr.len - (skip + hlen + alen);
865 crp->crp_op = CRYPTO_OP_ENCRYPT;
867 /* Generate cipher and ESP IVs. */
868 ivp = &crp->crp_iv[0];
869 if (SAV_ISCTRORGCM(sav)) {
871 * See comment in esp_input() for details on the
872 * cipher IV. A simple per-SA counter stored in
873 * 'cntr' is used as the explicit ESP IV.
875 memcpy(ivp, sav->key_enc->key_data +
876 _KEYLEN(sav->key_enc) - 4, 4);
877 be64enc(&ivp[4], cntr);
878 if (SAV_ISCTR(sav)) {
879 be32enc(&ivp[sav->ivlen + 4], 1);
881 m_copyback(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
882 crp->crp_flags |= CRYPTO_F_IV_SEPARATE;
883 } else if (sav->ivlen != 0) {
884 arc4rand(ivp, sav->ivlen, 0);
885 crp->crp_iv_start = skip + hlen - sav->ivlen;
886 m_copyback(m, crp->crp_iv_start, sav->ivlen, ivp);
889 /* Callback parameters */
893 xd->cryptoid = cryptoid;
896 /* Crypto operation descriptor. */
897 crp->crp_flags |= CRYPTO_F_CBIFSYNC;
899 crp->crp_flags |= CRYPTO_F_ASYNC | CRYPTO_F_ASYNC_KEEPORDER;
900 crypto_use_mbuf(crp, m);
901 crp->crp_callback = esp_output_cb;
902 crp->crp_opaque = xd;
905 /* Authentication descriptor. */
906 crp->crp_op |= CRYPTO_OP_COMPUTE_DIGEST;
908 crp->crp_aad_length = 8; /* RFC4106 5, SPI + SN */
910 crp->crp_aad_length = hlen;
912 csp = crypto_get_params(crp->crp_session);
913 if (csp->csp_flags & CSP_F_SEPARATE_AAD &&
914 sav->replay != NULL) {
917 crp->crp_aad_length += sizeof(seqh);
918 crp->crp_aad = malloc(crp->crp_aad_length, M_XDATA, M_NOWAIT);
919 if (crp->crp_aad == NULL) {
920 DPRINTF(("%s: failed to allocate xform_data\n",
926 m_copydata(m, skip, SPI_SIZE, crp->crp_aad);
930 bcopy(&seqh, (char *)crp->crp_aad + aad_skip, sizeof(seqh));
931 aad_skip += sizeof(seqh);
934 if (crp->crp_aad_length - aad_skip > 0)
935 m_copydata(m, skip + SPI_SIZE,
936 crp->crp_aad_length - aad_skip,
937 (char *)crp->crp_aad + aad_skip);
939 crp->crp_aad_start = skip;
941 if (csp->csp_flags & CSP_F_ESN && sav->replay != NULL)
942 memcpy(crp->crp_esn, &seqh, sizeof(seqh));
944 crp->crp_digest_start = m->m_pkthdr.len - alen;
947 return crypto_dispatch(crp);
953 ESPSTAT_INC(esps_crypto);
963 * ESP output callback from the crypto driver.
966 esp_output_cb(struct cryptop *crp)
968 struct xform_data *xd;
969 struct secpolicy *sp;
970 struct secasvar *sav;
972 crypto_session_t cryptoid;
976 xd = (struct xform_data *) crp->crp_opaque;
977 CURVNET_SET(xd->vnet);
978 m = crp->crp_buf.cb_mbuf;
982 cryptoid = xd->cryptoid;
984 /* Check for crypto errors. */
985 if (crp->crp_etype) {
986 if (crp->crp_etype == EAGAIN) {
987 /* Reset the session ID */
988 if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
989 crypto_freesession(cryptoid);
990 xd->cryptoid = crp->crp_session;
992 return (crypto_dispatch(crp));
994 ESPSTAT_INC(esps_noxform);
995 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
996 error = crp->crp_etype;
1001 /* Shouldn't happen... */
1003 ESPSTAT_INC(esps_crypto);
1004 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
1009 free(crp->crp_aad, M_XDATA);
1010 crypto_freereq(crp);
1011 ESPSTAT_INC(esps_hist[sav->alg_enc]);
1012 if (sav->tdb_authalgxform != NULL)
1013 AHSTAT_INC(ahs_hist[sav->alg_auth]);
1016 /* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
1017 if (V_ipsec_integrity) {
1018 static unsigned char ipseczeroes[AH_HMAC_MAXHASHLEN];
1019 const struct auth_hash *esph;
1022 * Corrupt HMAC if we want to test integrity verification of
1025 esph = sav->tdb_authalgxform;
1029 alen = xform_ah_authsize(esph);
1030 m_copyback(m, m->m_pkthdr.len - alen,
1036 /* NB: m is reclaimed by ipsec_process_done. */
1037 error = ipsec_process_done(m, sp, sav, idx);
1043 free(crp->crp_aad, M_XDATA);
1044 crypto_freereq(crp);
1050 static struct xformsw esp_xformsw = {
1052 .xf_name = "IPsec ESP",
1053 .xf_init = esp_init,
1054 .xf_cleanup = esp_cleanup,
1055 .xf_input = esp_input,
1056 .xf_output = esp_output,
1059 SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
1060 xform_attach, &esp_xformsw);
1061 SYSUNINIT(esp_xform_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
1062 xform_detach, &esp_xformsw);