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);
511 if (sav->state >= SADB_SASTATE_DEAD) {
513 DPRINTF(("%s: dead SA %p spi %#x\n", __func__, sav, sav->spi));
514 ESPSTAT_INC(esps_notdb);
519 protoff = xd->protoff;
520 cryptoid = xd->cryptoid;
521 saidx = &sav->sah->saidx;
522 esph = sav->tdb_authalgxform;
524 /* Check for crypto errors */
525 if (crp->crp_etype) {
526 if (crp->crp_etype == EAGAIN) {
527 /* Reset the session ID */
528 if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
529 crypto_freesession(cryptoid);
530 xd->cryptoid = crp->crp_session;
532 return (crypto_dispatch(crp));
535 /* EBADMSG indicates authentication failure. */
536 if (!(crp->crp_etype == EBADMSG && esph != NULL)) {
537 ESPSTAT_INC(esps_noxform);
538 DPRINTF(("%s: crypto error %d\n", __func__,
540 error = crp->crp_etype;
545 /* Shouldn't happen... */
547 ESPSTAT_INC(esps_crypto);
548 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
552 ESPSTAT_INC(esps_hist[sav->alg_enc]);
554 /* If authentication was performed, check now. */
556 alen = xform_ah_authsize(esph);
557 AHSTAT_INC(ahs_hist[sav->alg_auth]);
558 if (crp->crp_etype == EBADMSG) {
559 DPRINTF(("%s: authentication hash mismatch for "
560 "packet in SA %s/%08lx\n", __func__,
561 ipsec_address(&saidx->dst, buf, sizeof(buf)),
562 (u_long) ntohl(sav->spi)));
563 ESPSTAT_INC(esps_badauth);
567 m->m_flags |= M_AUTHIPDGM;
568 /* Remove trailing authenticator */
572 /* Release the crypto descriptors */
573 free(xd, M_ESP), xd = NULL;
574 free(crp->crp_aad, M_ESP), crp->crp_aad = NULL;
575 crypto_freereq(crp), crp = NULL;
578 * Packet is now decrypted.
580 m->m_flags |= M_DECRYPTED;
583 * Update replay sequence number, if appropriate.
588 m_copydata(m, skip + offsetof(struct newesp, esp_seq),
589 sizeof (seq), (caddr_t) &seq);
591 if (ipsec_updatereplay(ntohl(seq), sav)) {
592 SECASVAR_RUNLOCK(sav);
593 DPRINTF(("%s: packet replay check for %s\n", __func__,
594 ipsec_sa2str(sav, buf, sizeof(buf))));
595 ESPSTAT_INC(esps_replay);
599 SECASVAR_RUNLOCK(sav);
602 /* Determine the ESP header length */
603 if (sav->flags & SADB_X_EXT_OLD)
604 hlen = sizeof (struct esp) + sav->ivlen;
606 hlen = sizeof (struct newesp) + sav->ivlen;
608 /* Remove the ESP header and IV from the mbuf. */
609 error = m_striphdr(m, skip, hlen);
611 ESPSTAT_INC(esps_hdrops);
612 DPRINTF(("%s: bad mbuf chain, SA %s/%08lx\n", __func__,
613 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
614 (u_long) ntohl(sav->spi)));
618 /* Save the last three bytes of decrypted data */
619 m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
621 /* Verify pad length */
622 if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
623 ESPSTAT_INC(esps_badilen);
624 DPRINTF(("%s: invalid padding length %d for %u byte packet "
625 "in SA %s/%08lx\n", __func__, lastthree[1],
626 m->m_pkthdr.len - skip,
627 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
628 (u_long) ntohl(sav->spi)));
633 /* Verify correct decryption by checking the last padding bytes */
634 if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
635 if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
636 ESPSTAT_INC(esps_badenc);
637 DPRINTF(("%s: decryption failed for packet in "
638 "SA %s/%08lx\n", __func__, ipsec_address(
639 &sav->sah->saidx.dst, buf, sizeof(buf)),
640 (u_long) ntohl(sav->spi)));
648 * Silently drop packet if next header field is IPPROTO_NONE.
650 if (lastthree[2] == IPPROTO_NONE)
653 /* Trim the mbuf chain to remove trailing authenticator and padding */
654 m_adj(m, -(lastthree[1] + 2));
656 /* Restore the Next Protocol field */
657 m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
659 switch (saidx->dst.sa.sa_family) {
662 error = ipsec6_common_input_cb(m, sav, skip, protoff);
667 error = ipsec4_common_input_cb(m, sav, skip, protoff);
671 panic("%s: Unexpected address family: %d saidx=%p", __func__,
672 saidx->dst.sa.sa_family, saidx);
684 free(crp->crp_aad, M_ESP);
691 * ESP output routine, called by ipsec[46]_perform_request().
694 esp_output(struct mbuf *m, struct secpolicy *sp, struct secasvar *sav,
695 u_int idx, int skip, int protoff)
697 IPSEC_DEBUG_DECLARE(char buf[IPSEC_ADDRSTRLEN]);
699 const struct auth_hash *esph;
700 const struct enc_xform *espx;
701 struct mbuf *mo = NULL;
702 struct xform_data *xd;
703 struct secasindex *saidx;
707 crypto_session_t cryptoid;
708 int hlen, rlen, padding, blks, alen, i, roff;
709 int error, maxpacketsize;
712 const struct crypto_session_params *csp;
714 SECASVAR_RLOCK_TRACKER;
716 IPSEC_ASSERT(sav != NULL, ("null SA"));
717 esph = sav->tdb_authalgxform;
718 espx = sav->tdb_encalgxform;
719 IPSEC_ASSERT(espx != NULL, ("null encoding xform"));
721 if (sav->flags & SADB_X_EXT_OLD)
722 hlen = sizeof (struct esp) + sav->ivlen;
724 hlen = sizeof (struct newesp) + sav->ivlen;
726 rlen = m->m_pkthdr.len - skip; /* Raw payload length. */
728 * RFC4303 2.4 Requires 4 byte alignment.
729 * Old versions of FreeBSD can't decrypt partial blocks encrypted
730 * with AES-CTR. Align payload to native_blocksize (16 bytes)
731 * in order to preserve compatibility.
733 if (SAV_ISCTR(sav) && V_esp_ctr_compatibility)
734 blks = MAX(4, espx->native_blocksize); /* Cipher blocksize */
736 blks = MAX(4, espx->blocksize);
738 /* XXX clamp padding length a la KAME??? */
739 padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
741 alen = xform_ah_authsize(esph);
743 ESPSTAT_INC(esps_output);
745 saidx = &sav->sah->saidx;
746 /* Check for maximum packet size violations. */
747 switch (saidx->dst.sa.sa_family) {
750 maxpacketsize = IP_MAXPACKET;
755 maxpacketsize = IPV6_MAXPACKET;
759 DPRINTF(("%s: unknown/unsupported protocol "
760 "family %d, SA %s/%08lx\n", __func__,
761 saidx->dst.sa.sa_family, ipsec_address(&saidx->dst,
762 buf, sizeof(buf)), (u_long) ntohl(sav->spi)));
763 ESPSTAT_INC(esps_nopf);
764 error = EPFNOSUPPORT;
768 DPRINTF(("%s: skip %d hlen %d rlen %d padding %d alen %d blksd %d\n",
769 __func__, skip, hlen, rlen, padding, alen, blks)); */
770 if (skip + hlen + rlen + padding + alen > maxpacketsize) {
771 DPRINTF(("%s: packet in SA %s/%08lx got too big "
772 "(len %u, max len %u)\n", __func__,
773 ipsec_address(&saidx->dst, buf, sizeof(buf)),
774 (u_long) ntohl(sav->spi),
775 skip + hlen + rlen + padding + alen, maxpacketsize));
776 ESPSTAT_INC(esps_toobig);
781 /* Update the counters. */
782 ESPSTAT_ADD(esps_obytes, m->m_pkthdr.len - skip);
784 m = m_unshare(m, M_NOWAIT);
786 DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
787 ipsec_address(&saidx->dst, buf, sizeof(buf)),
788 (u_long) ntohl(sav->spi)));
789 ESPSTAT_INC(esps_hdrops);
794 /* Inject ESP header. */
795 mo = m_makespace(m, skip, hlen, &roff);
797 DPRINTF(("%s: %u byte ESP hdr inject failed for SA %s/%08lx\n",
798 __func__, hlen, ipsec_address(&saidx->dst, buf,
799 sizeof(buf)), (u_long) ntohl(sav->spi)));
800 ESPSTAT_INC(esps_hdrops); /* XXX diffs from openbsd */
805 /* Initialize ESP header. */
806 bcopy((caddr_t) &sav->spi, mtod(mo, caddr_t) + roff,
812 SECREPLAY_LOCK(sav->replay);
814 /* Emulate replay attack when ipsec_replay is TRUE. */
817 sav->replay->count++;
818 replay = htonl((uint32_t)sav->replay->count);
820 bcopy((caddr_t) &replay, mtod(mo, caddr_t) + roff +
821 sizeof(uint32_t), sizeof(uint32_t));
823 seqh = htonl((uint32_t)(sav->replay->count >> IPSEC_SEQH_SHIFT));
824 SECREPLAY_UNLOCK(sav->replay);
826 cryptoid = sav->tdb_cryptoid;
827 if (SAV_ISCTRORGCM(sav) || SAV_ISCHACHA(sav))
829 SECASVAR_RUNLOCK(sav);
832 * Add padding -- better to do it ourselves than use the crypto engine,
833 * although if/when we support compression, we'd have to do that.
835 pad = (u_char *) m_pad(m, padding + alen);
837 DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
838 ipsec_address(&saidx->dst, buf, sizeof(buf)),
839 (u_long) ntohl(sav->spi)));
840 m = NULL; /* NB: free'd by m_pad */
846 * Add padding: random, zero, or self-describing.
847 * XXX catch unexpected setting
849 switch (sav->flags & SADB_X_EXT_PMASK) {
850 case SADB_X_EXT_PRAND:
851 arc4random_buf(pad, padding - 2);
853 case SADB_X_EXT_PZERO:
854 bzero(pad, padding - 2);
856 case SADB_X_EXT_PSEQ:
857 for (i = 0; i < padding - 2; i++)
862 /* Fix padding length and Next Protocol in padding itself. */
863 pad[padding - 2] = padding - 2;
864 m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
866 /* Fix Next Protocol in IPv4/IPv6 header. */
868 m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
870 /* Get crypto descriptor. */
871 crp = crypto_getreq(cryptoid, M_NOWAIT);
873 DPRINTF(("%s: failed to acquire crypto descriptor\n",
875 ESPSTAT_INC(esps_crypto);
880 /* IPsec-specific opaque crypto info. */
881 xd = malloc(sizeof(struct xform_data), M_ESP, M_NOWAIT | M_ZERO);
883 DPRINTF(("%s: failed to allocate xform_data\n", __func__));
887 /* Encryption descriptor. */
888 crp->crp_payload_start = skip + hlen;
889 crp->crp_payload_length = m->m_pkthdr.len - (skip + hlen + alen);
890 crp->crp_op = CRYPTO_OP_ENCRYPT;
892 /* Generate cipher and ESP IVs. */
893 ivp = &crp->crp_iv[0];
894 if (SAV_ISCTRORGCM(sav) || SAV_ISCHACHA(sav)) {
896 * See comment in esp_input() for details on the
897 * cipher IV. A simple per-SA counter stored in
898 * 'cntr' is used as the explicit ESP IV.
900 memcpy(ivp, sav->key_enc->key_data +
901 _KEYLEN(sav->key_enc) - 4, 4);
902 be64enc(&ivp[4], cntr);
903 if (SAV_ISCTR(sav)) {
904 be32enc(&ivp[sav->ivlen + 4], 1);
906 m_copyback(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
907 crp->crp_flags |= CRYPTO_F_IV_SEPARATE;
908 } else if (sav->ivlen != 0) {
909 arc4rand(ivp, sav->ivlen, 0);
910 crp->crp_iv_start = skip + hlen - sav->ivlen;
911 m_copyback(m, crp->crp_iv_start, sav->ivlen, ivp);
914 /* Callback parameters */
918 xd->cryptoid = cryptoid;
921 /* Crypto operation descriptor. */
922 crp->crp_flags |= CRYPTO_F_CBIFSYNC;
923 crypto_use_mbuf(crp, m);
924 crp->crp_callback = esp_output_cb;
925 crp->crp_opaque = xd;
928 /* Authentication descriptor. */
929 crp->crp_op |= CRYPTO_OP_COMPUTE_DIGEST;
930 if (SAV_ISGCM(sav) || SAV_ISCHACHA(sav))
931 crp->crp_aad_length = 8; /* RFC4106 5, SPI + SN */
933 crp->crp_aad_length = hlen;
935 csp = crypto_get_params(crp->crp_session);
936 if (csp->csp_flags & CSP_F_SEPARATE_AAD &&
937 sav->replay != NULL) {
940 crp->crp_aad_length += sizeof(seqh);
941 crp->crp_aad = malloc(crp->crp_aad_length, M_ESP, M_NOWAIT);
942 if (crp->crp_aad == NULL) {
943 DPRINTF(("%s: failed to allocate xform_data\n",
949 m_copydata(m, skip, SPI_SIZE, crp->crp_aad);
953 bcopy(&seqh, (char *)crp->crp_aad + aad_skip, sizeof(seqh));
954 aad_skip += sizeof(seqh);
957 if (crp->crp_aad_length - aad_skip > 0)
958 m_copydata(m, skip + SPI_SIZE,
959 crp->crp_aad_length - aad_skip,
960 (char *)crp->crp_aad + aad_skip);
962 crp->crp_aad_start = skip;
964 if (csp->csp_flags & CSP_F_ESN && sav->replay != NULL)
965 memcpy(crp->crp_esn, &seqh, sizeof(seqh));
967 crp->crp_digest_start = m->m_pkthdr.len - alen;
971 return (crypto_dispatch_async(crp, CRYPTO_ASYNC_ORDERED));
973 return (crypto_dispatch(crp));
979 ESPSTAT_INC(esps_crypto);
989 * ESP output callback from the crypto driver.
992 esp_output_cb(struct cryptop *crp)
994 struct xform_data *xd;
995 struct secpolicy *sp;
996 struct secasvar *sav;
998 crypto_session_t cryptoid;
1002 xd = (struct xform_data *) crp->crp_opaque;
1003 CURVNET_SET(xd->vnet);
1004 m = crp->crp_buf.cb_mbuf;
1008 cryptoid = xd->cryptoid;
1010 /* Check for crypto errors. */
1011 if (crp->crp_etype) {
1012 if (crp->crp_etype == EAGAIN) {
1013 /* Reset the session ID */
1014 if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
1015 crypto_freesession(cryptoid);
1016 xd->cryptoid = crp->crp_session;
1018 return (crypto_dispatch(crp));
1020 ESPSTAT_INC(esps_noxform);
1021 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
1022 error = crp->crp_etype;
1027 /* Shouldn't happen... */
1029 ESPSTAT_INC(esps_crypto);
1030 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
1035 free(crp->crp_aad, M_ESP);
1036 crypto_freereq(crp);
1037 ESPSTAT_INC(esps_hist[sav->alg_enc]);
1038 if (sav->tdb_authalgxform != NULL)
1039 AHSTAT_INC(ahs_hist[sav->alg_auth]);
1042 /* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
1043 if (V_ipsec_integrity) {
1044 static unsigned char ipseczeroes[AH_HMAC_MAXHASHLEN];
1045 const struct auth_hash *esph;
1048 * Corrupt HMAC if we want to test integrity verification of
1051 esph = sav->tdb_authalgxform;
1055 alen = xform_ah_authsize(esph);
1056 m_copyback(m, m->m_pkthdr.len - alen,
1062 /* NB: m is reclaimed by ipsec_process_done. */
1063 error = ipsec_process_done(m, sp, sav, idx);
1068 free(crp->crp_aad, M_ESP);
1069 crypto_freereq(crp);
1076 static struct xformsw esp_xformsw = {
1078 .xf_name = "IPsec ESP",
1079 .xf_init = esp_init,
1080 .xf_cleanup = esp_cleanup,
1081 .xf_input = esp_input,
1082 .xf_output = esp_output,
1085 SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
1086 xform_attach, &esp_xformsw);
1087 SYSUNINIT(esp_xform_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
1088 xform_detach, &esp_xformsw);