1 /* $OpenBSD: ip_esp.c,v 1.69 2001/06/26 06:18:59 angelos Exp $ */
3 * The authors of this code are John Ioannidis (ji@tla.org),
4 * Angelos D. Keromytis (kermit@csd.uch.gr) and
5 * Niels Provos (provos@physnet.uni-hamburg.de).
7 * The original version of this code was written by John Ioannidis
8 * for BSD/OS in Athens, Greece, in November 1995.
10 * Ported to OpenBSD and NetBSD, with additional transforms, in December 1996,
11 * by Angelos D. Keromytis.
13 * Additional transforms and features in 1997 and 1998 by Angelos D. Keromytis
16 * Additional features in 1999 by Angelos D. Keromytis.
18 * Copyright (C) 1995, 1996, 1997, 1998, 1999 by John Ioannidis,
19 * Angelos D. Keromytis and Niels Provos.
20 * Copyright (c) 2001 Angelos D. Keromytis.
22 * Permission to use, copy, and modify this software with or without fee
23 * is hereby granted, provided that this entire notice is included in
24 * all copies of any software which is or includes a copy or
25 * modification of this software.
26 * You may use this code under the GNU public license if you so wish. Please
27 * contribute changes back to the authors under this freer than GPL license
28 * so that we may further the use of strong encryption without limitations to
31 * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
32 * IMPLIED WARRANTY. IN PARTICULAR, NONE OF THE AUTHORS MAKES ANY
33 * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
34 * MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
38 #include "opt_inet6.h"
39 #include "opt_ipsec.h"
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/malloc.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 MALLOC_DEFINE(M_ESP, "esp", "IPsec ESP");
107 static int esp_input_cb(struct cryptop *op);
108 static int esp_output_cb(struct cryptop *crp);
111 esp_hdrsiz(struct secasvar *sav)
116 /*XXX not right for null algorithm--does it matter??*/
117 IPSEC_ASSERT(sav->tdb_encalgxform != NULL,
118 ("SA with null xform"));
119 if (sav->flags & SADB_X_EXT_OLD)
120 size = sizeof (struct esp);
122 size = sizeof (struct newesp);
123 size += sav->tdb_encalgxform->blocksize + 9;
124 /*XXX need alg check???*/
125 if (sav->tdb_authalgxform != NULL && sav->replay)
126 size += ah_hdrsiz(sav);
130 * + max iv length for CBC mode
132 * + sizeof (pad length field)
133 * + sizeof (next header field)
134 * + max icv supported.
136 size = sizeof (struct newesp) + EALG_MAX_BLOCK_LEN + 9 + 16;
142 * esp_init() is called when an SPI is being set up.
145 esp_init(struct secasvar *sav, struct xformsw *xsp)
147 const struct enc_xform *txform;
148 struct crypto_session_params csp;
152 txform = enc_algorithm_lookup(sav->alg_enc);
153 if (txform == NULL) {
154 DPRINTF(("%s: unsupported encryption algorithm %d\n",
155 __func__, sav->alg_enc));
158 if (sav->key_enc == NULL) {
159 DPRINTF(("%s: no encoding key for %s algorithm\n",
160 __func__, txform->name));
163 if ((sav->flags & (SADB_X_EXT_OLD | SADB_X_EXT_IV4B)) ==
165 DPRINTF(("%s: 4-byte IV not supported with protocol\n",
170 /* subtract off the salt, RFC4106, 8.1 and RFC3686, 5.1 */
171 keylen = _KEYLEN(sav->key_enc) - SAV_ISCTRORGCM(sav) * 4 -
172 SAV_ISCHACHA(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) || SAV_ISCHACHA(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_enc == SADB_X_EALG_CHACHA20POLY1305) {
230 sav->alg_auth = SADB_X_AALG_CHACHA20POLY1305;
231 sav->tdb_authalgxform = &auth_hash_poly1305;
232 csp.csp_mode = CSP_MODE_AEAD;
233 if (sav->flags & SADB_X_SAFLAGS_ESN)
234 csp.csp_flags |= CSP_F_SEPARATE_AAD;
235 } else if (sav->alg_auth != 0) {
236 csp.csp_mode = CSP_MODE_ETA;
237 if (sav->flags & SADB_X_SAFLAGS_ESN)
238 csp.csp_flags |= CSP_F_ESN;
240 csp.csp_mode = CSP_MODE_CIPHER;
242 /* Initialize crypto session. */
243 csp.csp_cipher_alg = sav->tdb_encalgxform->type;
244 if (csp.csp_cipher_alg != CRYPTO_NULL_CBC) {
245 csp.csp_cipher_key = sav->key_enc->key_data;
246 csp.csp_cipher_klen = _KEYBITS(sav->key_enc) / 8 -
247 SAV_ISCTRORGCM(sav) * 4 - SAV_ISCHACHA(sav) * 4;
249 csp.csp_ivlen = txform->ivsize;
251 error = crypto_newsession(&sav->tdb_cryptoid, &csp, V_crypto_support);
256 esp_cleanup(struct secasvar *sav)
259 crypto_freesession(sav->tdb_cryptoid);
260 sav->tdb_cryptoid = NULL;
261 sav->tdb_authalgxform = NULL;
262 sav->tdb_encalgxform = NULL;
266 * ESP input processing, called (eventually) through the protocol switch.
269 esp_input(struct mbuf *m, struct secasvar *sav, int skip, int protoff)
271 IPSEC_DEBUG_DECLARE(char buf[128]);
272 const struct auth_hash *esph;
273 const struct enc_xform *espx;
274 struct xform_data *xd;
278 crypto_session_t cryptoid;
279 int alen, error, hlen, plen;
281 const struct crypto_session_params *csp;
283 SECASVAR_RLOCK_TRACKER;
285 IPSEC_ASSERT(sav != NULL, ("null SA"));
286 IPSEC_ASSERT(sav->tdb_encalgxform != NULL, ("null encoding xform"));
289 /* Valid IP Packet length ? */
290 if ( (skip&3) || (m->m_pkthdr.len&3) ){
291 DPRINTF(("%s: misaligned packet, skip %u pkt len %u",
292 __func__, skip, m->m_pkthdr.len));
293 ESPSTAT_INC(esps_badilen);
297 if (m->m_len < skip + sizeof(*esp)) {
298 m = m_pullup(m, skip + sizeof(*esp));
300 DPRINTF(("%s: cannot pullup header\n", __func__));
301 ESPSTAT_INC(esps_hdrops); /*XXX*/
306 esp = (struct newesp *)(mtod(m, caddr_t) + skip);
308 esph = sav->tdb_authalgxform;
309 espx = sav->tdb_encalgxform;
311 /* Determine the ESP header and auth length */
312 if (sav->flags & SADB_X_EXT_OLD)
313 hlen = sizeof (struct esp) + sav->ivlen;
315 hlen = sizeof (struct newesp) + sav->ivlen;
317 alen = xform_ah_authsize(esph);
320 * Verify payload length is multiple of encryption algorithm
323 * NB: This works for the null algorithm because the blocksize
324 * is 4 and all packets must be 4-byte aligned regardless
327 plen = m->m_pkthdr.len - (skip + hlen + alen);
328 if ((plen & (espx->blocksize - 1)) || (plen <= 0)) {
329 DPRINTF(("%s: payload of %d octets not a multiple of %d octets,"
330 " SA %s/%08lx\n", __func__, plen, espx->blocksize,
331 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
332 (u_long)ntohl(sav->spi)));
333 ESPSTAT_INC(esps_badilen);
338 * Check sequence number.
341 if (esph != NULL && sav->replay != NULL && sav->replay->wsize != 0) {
342 if (ipsec_chkreplay(ntohl(esp->esp_seq), &seqh, sav) == 0) {
343 SECASVAR_RUNLOCK(sav);
344 DPRINTF(("%s: packet replay check for %s\n", __func__,
345 ipsec_sa2str(sav, buf, sizeof(buf))));
346 ESPSTAT_INC(esps_replay);
352 cryptoid = sav->tdb_cryptoid;
353 SECASVAR_RUNLOCK(sav);
355 /* Update the counters */
356 ESPSTAT_ADD(esps_ibytes, m->m_pkthdr.len - (skip + hlen + alen));
358 /* Get crypto descriptors */
359 crp = crypto_getreq(cryptoid, M_NOWAIT);
361 DPRINTF(("%s: failed to acquire crypto descriptors\n",
363 ESPSTAT_INC(esps_crypto);
368 /* Get IPsec-specific opaque pointer */
369 xd = malloc(sizeof(*xd), M_ESP, M_NOWAIT | M_ZERO);
371 DPRINTF(("%s: failed to allocate xform_data\n", __func__));
376 crp->crp_op = CRYPTO_OP_VERIFY_DIGEST;
377 if (SAV_ISGCM(sav) || SAV_ISCHACHA(sav))
378 crp->crp_aad_length = 8; /* RFC4106 5, SPI + SN */
380 crp->crp_aad_length = hlen;
382 csp = crypto_get_params(crp->crp_session);
383 if ((csp->csp_flags & CSP_F_SEPARATE_AAD) &&
384 (sav->replay != NULL) && (sav->replay->wsize != 0)) {
387 crp->crp_aad_length += sizeof(seqh);
388 crp->crp_aad = malloc(crp->crp_aad_length, M_ESP, M_NOWAIT);
389 if (crp->crp_aad == NULL) {
390 DPRINTF(("%s: failed to allocate xform_data\n",
396 m_copydata(m, skip, SPI_SIZE, crp->crp_aad);
400 bcopy(&seqh, (char *)crp->crp_aad + aad_skip, sizeof(seqh));
401 aad_skip += sizeof(seqh);
404 if (crp->crp_aad_length - aad_skip > 0)
405 m_copydata(m, skip + SPI_SIZE,
406 crp->crp_aad_length - aad_skip,
407 (char *)crp->crp_aad + aad_skip);
409 crp->crp_aad_start = skip;
411 if (csp->csp_flags & CSP_F_ESN &&
412 sav->replay != NULL && sav->replay->wsize != 0)
413 memcpy(crp->crp_esn, &seqh, sizeof(seqh));
415 crp->crp_digest_start = m->m_pkthdr.len - alen;
418 /* Crypto operation descriptor */
419 crp->crp_flags = CRYPTO_F_CBIFSYNC;
420 crypto_use_mbuf(crp, m);
421 crp->crp_callback = esp_input_cb;
422 crp->crp_opaque = xd;
424 /* These are passed as-is to the callback */
426 xd->protoff = protoff;
428 xd->cryptoid = cryptoid;
431 /* Decryption descriptor */
432 crp->crp_op |= CRYPTO_OP_DECRYPT;
433 crp->crp_payload_start = skip + hlen;
434 crp->crp_payload_length = m->m_pkthdr.len - (skip + hlen + alen);
436 /* Generate or read cipher IV. */
437 if (SAV_ISCTRORGCM(sav) || SAV_ISCHACHA(sav)) {
438 ivp = &crp->crp_iv[0];
441 * AES-GCM and AES-CTR use similar cipher IV formats
442 * defined in RFC 4106 section 4 and RFC 3686 section
445 * The first 4 bytes of the cipher IV contain an
446 * implicit salt, or nonce, obtained from the last 4
447 * bytes of the encryption key. The next 8 bytes hold
448 * an explicit IV unique to each packet. This
449 * explicit IV is used as the ESP IV for the packet.
450 * The last 4 bytes hold a big-endian block counter
451 * incremented for each block. For AES-GCM, the block
452 * counter's initial value is defined as part of the
453 * algorithm. For AES-CTR, the block counter's
454 * initial value for each packet is defined as 1 by
457 * ------------------------------------------
458 * | Salt | Explicit ESP IV | Block Counter |
459 * ------------------------------------------
460 * 4 bytes 8 bytes 4 bytes
462 memcpy(ivp, sav->key_enc->key_data +
463 _KEYLEN(sav->key_enc) - 4, 4);
464 m_copydata(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
465 if (SAV_ISCTR(sav)) {
466 be32enc(&ivp[sav->ivlen + 4], 1);
468 crp->crp_flags |= CRYPTO_F_IV_SEPARATE;
469 } else if (sav->ivlen != 0)
470 crp->crp_iv_start = skip + hlen - sav->ivlen;
473 return (crypto_dispatch_async(crp, CRYPTO_ASYNC_ORDERED));
475 return (crypto_dispatch(crp));
481 ESPSTAT_INC(esps_crypto);
490 * ESP input callback from the crypto driver.
493 esp_input_cb(struct cryptop *crp)
495 IPSEC_DEBUG_DECLARE(char buf[128]);
496 uint8_t lastthree[3];
497 const struct auth_hash *esph;
499 struct xform_data *xd;
500 struct secasvar *sav;
501 struct secasindex *saidx;
502 crypto_session_t cryptoid;
503 int hlen, skip, protoff, error, alen;
505 SECASVAR_RLOCK_TRACKER;
507 m = crp->crp_buf.cb_mbuf;
508 xd = crp->crp_opaque;
509 CURVNET_SET(xd->vnet);
512 protoff = xd->protoff;
513 cryptoid = xd->cryptoid;
514 saidx = &sav->sah->saidx;
515 esph = sav->tdb_authalgxform;
517 /* Check for crypto errors */
518 if (crp->crp_etype) {
519 if (crp->crp_etype == EAGAIN) {
520 /* Reset the session ID */
521 if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
522 crypto_freesession(cryptoid);
523 xd->cryptoid = crp->crp_session;
525 return (crypto_dispatch(crp));
528 /* EBADMSG indicates authentication failure. */
529 if (!(crp->crp_etype == EBADMSG && esph != NULL)) {
530 ESPSTAT_INC(esps_noxform);
531 DPRINTF(("%s: crypto error %d\n", __func__,
533 error = crp->crp_etype;
538 /* Shouldn't happen... */
540 ESPSTAT_INC(esps_crypto);
541 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
545 ESPSTAT_INC(esps_hist[sav->alg_enc]);
547 /* If authentication was performed, check now. */
549 alen = xform_ah_authsize(esph);
550 AHSTAT_INC(ahs_hist[sav->alg_auth]);
551 if (crp->crp_etype == EBADMSG) {
552 DPRINTF(("%s: authentication hash mismatch for "
553 "packet in SA %s/%08lx\n", __func__,
554 ipsec_address(&saidx->dst, buf, sizeof(buf)),
555 (u_long) ntohl(sav->spi)));
556 ESPSTAT_INC(esps_badauth);
560 m->m_flags |= M_AUTHIPDGM;
561 /* Remove trailing authenticator */
565 /* Release the crypto descriptors */
566 free(xd, M_ESP), xd = NULL;
567 free(crp->crp_aad, M_ESP), crp->crp_aad = NULL;
568 crypto_freereq(crp), crp = NULL;
571 * Packet is now decrypted.
573 m->m_flags |= M_DECRYPTED;
576 * Update replay sequence number, if appropriate.
581 m_copydata(m, skip + offsetof(struct newesp, esp_seq),
582 sizeof (seq), (caddr_t) &seq);
584 if (ipsec_updatereplay(ntohl(seq), sav)) {
585 SECASVAR_RUNLOCK(sav);
586 DPRINTF(("%s: packet replay check for %s\n", __func__,
587 ipsec_sa2str(sav, buf, sizeof(buf))));
588 ESPSTAT_INC(esps_replay);
592 SECASVAR_RUNLOCK(sav);
595 /* Determine the ESP header length */
596 if (sav->flags & SADB_X_EXT_OLD)
597 hlen = sizeof (struct esp) + sav->ivlen;
599 hlen = sizeof (struct newesp) + sav->ivlen;
601 /* Remove the ESP header and IV from the mbuf. */
602 error = m_striphdr(m, skip, hlen);
604 ESPSTAT_INC(esps_hdrops);
605 DPRINTF(("%s: bad mbuf chain, SA %s/%08lx\n", __func__,
606 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
607 (u_long) ntohl(sav->spi)));
611 /* Save the last three bytes of decrypted data */
612 m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
614 /* Verify pad length */
615 if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
616 ESPSTAT_INC(esps_badilen);
617 DPRINTF(("%s: invalid padding length %d for %u byte packet "
618 "in SA %s/%08lx\n", __func__, lastthree[1],
619 m->m_pkthdr.len - skip,
620 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
621 (u_long) ntohl(sav->spi)));
626 /* Verify correct decryption by checking the last padding bytes */
627 if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
628 if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
629 ESPSTAT_INC(esps_badenc);
630 DPRINTF(("%s: decryption failed for packet in "
631 "SA %s/%08lx\n", __func__, ipsec_address(
632 &sav->sah->saidx.dst, buf, sizeof(buf)),
633 (u_long) ntohl(sav->spi)));
641 * Silently drop packet if next header field is IPPROTO_NONE.
643 if (lastthree[2] == IPPROTO_NONE)
646 /* Trim the mbuf chain to remove trailing authenticator and padding */
647 m_adj(m, -(lastthree[1] + 2));
649 /* Restore the Next Protocol field */
650 m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
652 switch (saidx->dst.sa.sa_family) {
655 error = ipsec6_common_input_cb(m, sav, skip, protoff);
660 error = ipsec4_common_input_cb(m, sav, skip, protoff);
664 panic("%s: Unexpected address family: %d saidx=%p", __func__,
665 saidx->dst.sa.sa_family, saidx);
677 free(crp->crp_aad, M_ESP);
684 * ESP output routine, called by ipsec[46]_perform_request().
687 esp_output(struct mbuf *m, struct secpolicy *sp, struct secasvar *sav,
688 u_int idx, int skip, int protoff)
690 IPSEC_DEBUG_DECLARE(char buf[IPSEC_ADDRSTRLEN]);
692 const struct auth_hash *esph;
693 const struct enc_xform *espx;
694 struct mbuf *mo = NULL;
695 struct xform_data *xd;
696 struct secasindex *saidx;
700 crypto_session_t cryptoid;
701 int hlen, rlen, padding, blks, alen, i, roff;
702 int error, maxpacketsize;
705 const struct crypto_session_params *csp;
707 SECASVAR_RLOCK_TRACKER;
709 IPSEC_ASSERT(sav != NULL, ("null SA"));
710 esph = sav->tdb_authalgxform;
711 espx = sav->tdb_encalgxform;
712 IPSEC_ASSERT(espx != NULL, ("null encoding xform"));
714 if (sav->flags & SADB_X_EXT_OLD)
715 hlen = sizeof (struct esp) + sav->ivlen;
717 hlen = sizeof (struct newesp) + sav->ivlen;
719 rlen = m->m_pkthdr.len - skip; /* Raw payload length. */
721 * RFC4303 2.4 Requires 4 byte alignment.
722 * Old versions of FreeBSD can't decrypt partial blocks encrypted
723 * with AES-CTR. Align payload to native_blocksize (16 bytes)
724 * in order to preserve compatibility.
726 if (SAV_ISCTR(sav) && V_esp_ctr_compatibility)
727 blks = MAX(4, espx->native_blocksize); /* Cipher blocksize */
729 blks = MAX(4, espx->blocksize);
731 /* XXX clamp padding length a la KAME??? */
732 padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
734 alen = xform_ah_authsize(esph);
736 ESPSTAT_INC(esps_output);
738 saidx = &sav->sah->saidx;
739 /* Check for maximum packet size violations. */
740 switch (saidx->dst.sa.sa_family) {
743 maxpacketsize = IP_MAXPACKET;
748 maxpacketsize = IPV6_MAXPACKET;
752 DPRINTF(("%s: unknown/unsupported protocol "
753 "family %d, SA %s/%08lx\n", __func__,
754 saidx->dst.sa.sa_family, ipsec_address(&saidx->dst,
755 buf, sizeof(buf)), (u_long) ntohl(sav->spi)));
756 ESPSTAT_INC(esps_nopf);
757 error = EPFNOSUPPORT;
761 DPRINTF(("%s: skip %d hlen %d rlen %d padding %d alen %d blksd %d\n",
762 __func__, skip, hlen, rlen, padding, alen, blks)); */
763 if (skip + hlen + rlen + padding + alen > maxpacketsize) {
764 DPRINTF(("%s: packet in SA %s/%08lx got too big "
765 "(len %u, max len %u)\n", __func__,
766 ipsec_address(&saidx->dst, buf, sizeof(buf)),
767 (u_long) ntohl(sav->spi),
768 skip + hlen + rlen + padding + alen, maxpacketsize));
769 ESPSTAT_INC(esps_toobig);
774 /* Update the counters. */
775 ESPSTAT_ADD(esps_obytes, m->m_pkthdr.len - skip);
777 m = m_unshare(m, M_NOWAIT);
779 DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
780 ipsec_address(&saidx->dst, buf, sizeof(buf)),
781 (u_long) ntohl(sav->spi)));
782 ESPSTAT_INC(esps_hdrops);
787 /* Inject ESP header. */
788 mo = m_makespace(m, skip, hlen, &roff);
790 DPRINTF(("%s: %u byte ESP hdr inject failed for SA %s/%08lx\n",
791 __func__, hlen, ipsec_address(&saidx->dst, buf,
792 sizeof(buf)), (u_long) ntohl(sav->spi)));
793 ESPSTAT_INC(esps_hdrops); /* XXX diffs from openbsd */
798 /* Initialize ESP header. */
799 bcopy((caddr_t) &sav->spi, mtod(mo, caddr_t) + roff,
805 SECREPLAY_LOCK(sav->replay);
807 /* Emulate replay attack when ipsec_replay is TRUE. */
810 sav->replay->count++;
811 replay = htonl((uint32_t)sav->replay->count);
813 bcopy((caddr_t) &replay, mtod(mo, caddr_t) + roff +
814 sizeof(uint32_t), sizeof(uint32_t));
816 seqh = htonl((uint32_t)(sav->replay->count >> IPSEC_SEQH_SHIFT));
817 SECREPLAY_UNLOCK(sav->replay);
819 cryptoid = sav->tdb_cryptoid;
820 if (SAV_ISCTRORGCM(sav) || SAV_ISCHACHA(sav))
822 SECASVAR_RUNLOCK(sav);
825 * Add padding -- better to do it ourselves than use the crypto engine,
826 * although if/when we support compression, we'd have to do that.
828 pad = (u_char *) m_pad(m, padding + alen);
830 DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
831 ipsec_address(&saidx->dst, buf, sizeof(buf)),
832 (u_long) ntohl(sav->spi)));
833 m = NULL; /* NB: free'd by m_pad */
839 * Add padding: random, zero, or self-describing.
840 * XXX catch unexpected setting
842 switch (sav->flags & SADB_X_EXT_PMASK) {
843 case SADB_X_EXT_PRAND:
844 arc4random_buf(pad, padding - 2);
846 case SADB_X_EXT_PZERO:
847 bzero(pad, padding - 2);
849 case SADB_X_EXT_PSEQ:
850 for (i = 0; i < padding - 2; i++)
855 /* Fix padding length and Next Protocol in padding itself. */
856 pad[padding - 2] = padding - 2;
857 m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
859 /* Fix Next Protocol in IPv4/IPv6 header. */
861 m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
863 /* Get crypto descriptor. */
864 crp = crypto_getreq(cryptoid, M_NOWAIT);
866 DPRINTF(("%s: failed to acquire crypto descriptor\n",
868 ESPSTAT_INC(esps_crypto);
873 /* IPsec-specific opaque crypto info. */
874 xd = malloc(sizeof(struct xform_data), M_ESP, M_NOWAIT | M_ZERO);
876 DPRINTF(("%s: failed to allocate xform_data\n", __func__));
880 /* Encryption descriptor. */
881 crp->crp_payload_start = skip + hlen;
882 crp->crp_payload_length = m->m_pkthdr.len - (skip + hlen + alen);
883 crp->crp_op = CRYPTO_OP_ENCRYPT;
885 /* Generate cipher and ESP IVs. */
886 ivp = &crp->crp_iv[0];
887 if (SAV_ISCTRORGCM(sav) || SAV_ISCHACHA(sav)) {
889 * See comment in esp_input() for details on the
890 * cipher IV. A simple per-SA counter stored in
891 * 'cntr' is used as the explicit ESP IV.
893 memcpy(ivp, sav->key_enc->key_data +
894 _KEYLEN(sav->key_enc) - 4, 4);
895 be64enc(&ivp[4], cntr);
896 if (SAV_ISCTR(sav)) {
897 be32enc(&ivp[sav->ivlen + 4], 1);
899 m_copyback(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
900 crp->crp_flags |= CRYPTO_F_IV_SEPARATE;
901 } else if (sav->ivlen != 0) {
902 arc4rand(ivp, sav->ivlen, 0);
903 crp->crp_iv_start = skip + hlen - sav->ivlen;
904 m_copyback(m, crp->crp_iv_start, sav->ivlen, ivp);
907 /* Callback parameters */
911 xd->cryptoid = cryptoid;
914 /* Crypto operation descriptor. */
915 crp->crp_flags |= CRYPTO_F_CBIFSYNC;
916 crypto_use_mbuf(crp, m);
917 crp->crp_callback = esp_output_cb;
918 crp->crp_opaque = xd;
921 /* Authentication descriptor. */
922 crp->crp_op |= CRYPTO_OP_COMPUTE_DIGEST;
923 if (SAV_ISGCM(sav) || SAV_ISCHACHA(sav))
924 crp->crp_aad_length = 8; /* RFC4106 5, SPI + SN */
926 crp->crp_aad_length = hlen;
928 csp = crypto_get_params(crp->crp_session);
929 if (csp->csp_flags & CSP_F_SEPARATE_AAD &&
930 sav->replay != NULL) {
933 crp->crp_aad_length += sizeof(seqh);
934 crp->crp_aad = malloc(crp->crp_aad_length, M_ESP, M_NOWAIT);
935 if (crp->crp_aad == NULL) {
936 DPRINTF(("%s: failed to allocate xform_data\n",
942 m_copydata(m, skip, SPI_SIZE, crp->crp_aad);
946 bcopy(&seqh, (char *)crp->crp_aad + aad_skip, sizeof(seqh));
947 aad_skip += sizeof(seqh);
950 if (crp->crp_aad_length - aad_skip > 0)
951 m_copydata(m, skip + SPI_SIZE,
952 crp->crp_aad_length - aad_skip,
953 (char *)crp->crp_aad + aad_skip);
955 crp->crp_aad_start = skip;
957 if (csp->csp_flags & CSP_F_ESN && sav->replay != NULL)
958 memcpy(crp->crp_esn, &seqh, sizeof(seqh));
960 crp->crp_digest_start = m->m_pkthdr.len - alen;
964 return (crypto_dispatch_async(crp, CRYPTO_ASYNC_ORDERED));
966 return (crypto_dispatch(crp));
972 ESPSTAT_INC(esps_crypto);
982 * ESP output callback from the crypto driver.
985 esp_output_cb(struct cryptop *crp)
987 struct xform_data *xd;
988 struct secpolicy *sp;
989 struct secasvar *sav;
991 crypto_session_t cryptoid;
995 xd = (struct xform_data *) crp->crp_opaque;
996 CURVNET_SET(xd->vnet);
997 m = crp->crp_buf.cb_mbuf;
1001 cryptoid = xd->cryptoid;
1003 /* Check for crypto errors. */
1004 if (crp->crp_etype) {
1005 if (crp->crp_etype == EAGAIN) {
1006 /* Reset the session ID */
1007 if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
1008 crypto_freesession(cryptoid);
1009 xd->cryptoid = crp->crp_session;
1011 return (crypto_dispatch(crp));
1013 ESPSTAT_INC(esps_noxform);
1014 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
1015 error = crp->crp_etype;
1020 /* Shouldn't happen... */
1022 ESPSTAT_INC(esps_crypto);
1023 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
1028 free(crp->crp_aad, M_ESP);
1029 crypto_freereq(crp);
1030 ESPSTAT_INC(esps_hist[sav->alg_enc]);
1031 if (sav->tdb_authalgxform != NULL)
1032 AHSTAT_INC(ahs_hist[sav->alg_auth]);
1035 /* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
1036 if (V_ipsec_integrity) {
1037 static unsigned char ipseczeroes[AH_HMAC_MAXHASHLEN];
1038 const struct auth_hash *esph;
1041 * Corrupt HMAC if we want to test integrity verification of
1044 esph = sav->tdb_authalgxform;
1048 alen = xform_ah_authsize(esph);
1049 m_copyback(m, m->m_pkthdr.len - alen,
1055 /* NB: m is reclaimed by ipsec_process_done. */
1056 error = ipsec_process_done(m, sp, sav, idx);
1061 free(crp->crp_aad, M_ESP);
1062 crypto_freereq(crp);
1069 static struct xformsw esp_xformsw = {
1071 .xf_name = "IPsec ESP",
1072 .xf_init = esp_init,
1073 .xf_cleanup = esp_cleanup,
1074 .xf_input = esp_input,
1075 .xf_output = esp_output,
1078 SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
1079 xform_attach, &esp_xformsw);
1080 SYSUNINIT(esp_xform_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
1081 xform_detach, &esp_xformsw);