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"
41 #include <sys/param.h>
42 #include <sys/systm.h>
44 #include <sys/socket.h>
45 #include <sys/syslog.h>
46 #include <sys/kernel.h>
48 #include <sys/random.h>
49 #include <sys/mutex.h>
50 #include <sys/sysctl.h>
51 #include <sys/mutex.h>
52 #include <machine/atomic.h>
57 #include <netinet/in.h>
58 #include <netinet/in_systm.h>
59 #include <netinet/ip.h>
60 #include <netinet/ip_ecn.h>
61 #include <netinet/ip6.h>
63 #include <netipsec/ipsec.h>
64 #include <netipsec/ah.h>
65 #include <netipsec/ah_var.h>
66 #include <netipsec/esp.h>
67 #include <netipsec/esp_var.h>
68 #include <netipsec/xform.h>
71 #include <netinet6/ip6_var.h>
72 #include <netipsec/ipsec6.h>
73 #include <netinet6/ip6_ecn.h>
76 #include <netipsec/key.h>
77 #include <netipsec/key_debug.h>
79 #include <opencrypto/cryptodev.h>
80 #include <opencrypto/xform.h>
82 VNET_DEFINE(int, esp_enable) = 1;
83 VNET_PCPUSTAT_DEFINE(struct espstat, espstat);
84 VNET_PCPUSTAT_SYSINIT(espstat);
87 VNET_PCPUSTAT_SYSUNINIT(espstat);
90 SYSCTL_DECL(_net_inet_esp);
91 SYSCTL_INT(_net_inet_esp, OID_AUTO, esp_enable,
92 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(esp_enable), 0, "");
93 SYSCTL_VNET_PCPUSTAT(_net_inet_esp, IPSECCTL_STATS, stats,
94 struct espstat, espstat,
95 "ESP statistics (struct espstat, netipsec/esp_var.h");
97 static struct timeval deswarn, blfwarn, castwarn, camelliawarn;
99 static int esp_input_cb(struct cryptop *op);
100 static int esp_output_cb(struct cryptop *crp);
103 esp_hdrsiz(struct secasvar *sav)
108 /*XXX not right for null algorithm--does it matter??*/
109 IPSEC_ASSERT(sav->tdb_encalgxform != NULL,
110 ("SA with null xform"));
111 if (sav->flags & SADB_X_EXT_OLD)
112 size = sizeof (struct esp);
114 size = sizeof (struct newesp);
115 size += sav->tdb_encalgxform->blocksize + 9;
116 /*XXX need alg check???*/
117 if (sav->tdb_authalgxform != NULL && sav->replay)
118 size += ah_hdrsiz(sav);
122 * + max iv length for CBC mode
124 * + sizeof (pad length field)
125 * + sizeof (next header field)
126 * + max icv supported.
128 size = sizeof (struct newesp) + EALG_MAX_BLOCK_LEN + 9 + 16;
134 * esp_init() is called when an SPI is being set up.
137 esp_init(struct secasvar *sav, struct xformsw *xsp)
139 const struct enc_xform *txform;
140 struct cryptoini cria, crie;
144 txform = enc_algorithm_lookup(sav->alg_enc);
145 if (txform == NULL) {
146 DPRINTF(("%s: unsupported encryption algorithm %d\n",
147 __func__, sav->alg_enc));
150 if (sav->key_enc == NULL) {
151 DPRINTF(("%s: no encoding key for %s algorithm\n",
152 __func__, txform->name));
155 if ((sav->flags & (SADB_X_EXT_OLD | SADB_X_EXT_IV4B)) ==
157 DPRINTF(("%s: 4-byte IV not supported with protocol\n",
162 switch (sav->alg_enc) {
163 case SADB_EALG_DESCBC:
164 if (ratecheck(&deswarn, &ipsec_warn_interval))
165 gone_in(13, "DES cipher for IPsec");
167 case SADB_X_EALG_BLOWFISHCBC:
168 if (ratecheck(&blfwarn, &ipsec_warn_interval))
169 gone_in(13, "Blowfish cipher for IPsec");
171 case SADB_X_EALG_CAST128CBC:
172 if (ratecheck(&castwarn, &ipsec_warn_interval))
173 gone_in(13, "CAST cipher for IPsec");
175 case SADB_X_EALG_CAMELLIACBC:
176 if (ratecheck(&camelliawarn, &ipsec_warn_interval))
177 gone_in(13, "Camellia cipher for IPsec");
181 /* subtract off the salt, RFC4106, 8.1 and RFC3686, 5.1 */
182 keylen = _KEYLEN(sav->key_enc) - SAV_ISCTRORGCM(sav) * 4;
183 if (txform->minkey > keylen || keylen > txform->maxkey) {
184 DPRINTF(("%s: invalid key length %u, must be in the range "
185 "[%u..%u] for algorithm %s\n", __func__,
186 keylen, txform->minkey, txform->maxkey,
191 if (SAV_ISCTRORGCM(sav))
192 sav->ivlen = 8; /* RFC4106 3.1 and RFC3686 3.1 */
194 sav->ivlen = txform->ivsize;
197 * Setup AH-related state.
199 if (sav->alg_auth != 0) {
200 error = ah_init0(sav, xsp, &cria);
205 /* NB: override anything set in ah_init0 */
206 sav->tdb_xform = xsp;
207 sav->tdb_encalgxform = txform;
210 * Whenever AES-GCM is used for encryption, one
211 * of the AES authentication algorithms is chosen
212 * as well, based on the key size.
214 if (sav->alg_enc == SADB_X_EALG_AESGCM16) {
216 case AES_128_GMAC_KEY_LEN:
217 sav->alg_auth = SADB_X_AALG_AES128GMAC;
218 sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_128;
220 case AES_192_GMAC_KEY_LEN:
221 sav->alg_auth = SADB_X_AALG_AES192GMAC;
222 sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_192;
224 case AES_256_GMAC_KEY_LEN:
225 sav->alg_auth = SADB_X_AALG_AES256GMAC;
226 sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_256;
229 DPRINTF(("%s: invalid key length %u"
230 "for algorithm %s\n", __func__,
231 keylen, txform->name));
234 bzero(&cria, sizeof(cria));
235 cria.cri_alg = sav->tdb_authalgxform->type;
236 cria.cri_key = sav->key_enc->key_data;
237 cria.cri_klen = _KEYBITS(sav->key_enc) - SAV_ISGCM(sav) * 32;
240 /* Initialize crypto session. */
241 bzero(&crie, sizeof(crie));
242 crie.cri_alg = sav->tdb_encalgxform->type;
243 crie.cri_key = sav->key_enc->key_data;
244 crie.cri_klen = _KEYBITS(sav->key_enc) - SAV_ISCTRORGCM(sav) * 32;
246 if (sav->tdb_authalgxform && sav->tdb_encalgxform) {
247 /* init both auth & enc */
248 crie.cri_next = &cria;
249 error = crypto_newsession(&sav->tdb_cryptoid,
250 &crie, V_crypto_support);
251 } else if (sav->tdb_encalgxform) {
252 error = crypto_newsession(&sav->tdb_cryptoid,
253 &crie, V_crypto_support);
254 } else if (sav->tdb_authalgxform) {
255 error = crypto_newsession(&sav->tdb_cryptoid,
256 &cria, V_crypto_support);
258 /* XXX cannot happen? */
259 DPRINTF(("%s: no encoding OR authentication xform!\n",
270 esp_zeroize(struct secasvar *sav)
272 /* NB: ah_zerorize free's the crypto session state */
273 int error = ah_zeroize(sav);
276 bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
277 sav->tdb_encalgxform = NULL;
278 sav->tdb_xform = NULL;
283 * ESP input processing, called (eventually) through the protocol switch.
286 esp_input(struct mbuf *m, struct secasvar *sav, int skip, int protoff)
288 IPSEC_DEBUG_DECLARE(char buf[128]);
289 const struct auth_hash *esph;
290 const struct enc_xform *espx;
291 struct xform_data *xd;
292 struct cryptodesc *crde;
296 crypto_session_t cryptoid;
297 int alen, error, hlen, plen;
299 IPSEC_ASSERT(sav != NULL, ("null SA"));
300 IPSEC_ASSERT(sav->tdb_encalgxform != NULL, ("null encoding xform"));
303 /* Valid IP Packet length ? */
304 if ( (skip&3) || (m->m_pkthdr.len&3) ){
305 DPRINTF(("%s: misaligned packet, skip %u pkt len %u",
306 __func__, skip, m->m_pkthdr.len));
307 ESPSTAT_INC(esps_badilen);
310 /* XXX don't pullup, just copy header */
311 IP6_EXTHDR_GET(esp, struct newesp *, m, skip, sizeof (struct newesp));
313 esph = sav->tdb_authalgxform;
314 espx = sav->tdb_encalgxform;
316 /* Determine the ESP header and auth length */
317 if (sav->flags & SADB_X_EXT_OLD)
318 hlen = sizeof (struct esp) + sav->ivlen;
320 hlen = sizeof (struct newesp) + sav->ivlen;
322 alen = xform_ah_authsize(esph);
325 * Verify payload length is multiple of encryption algorithm
328 * NB: This works for the null algorithm because the blocksize
329 * is 4 and all packets must be 4-byte aligned regardless
332 plen = m->m_pkthdr.len - (skip + hlen + alen);
333 if ((plen & (espx->blocksize - 1)) || (plen <= 0)) {
334 DPRINTF(("%s: payload of %d octets not a multiple of %d octets,"
335 " SA %s/%08lx\n", __func__, plen, espx->blocksize,
336 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
337 (u_long)ntohl(sav->spi)));
338 ESPSTAT_INC(esps_badilen);
343 * Check sequence number.
346 if (esph != NULL && sav->replay != NULL && sav->replay->wsize != 0) {
347 if (ipsec_chkreplay(ntohl(esp->esp_seq), sav) == 0) {
348 SECASVAR_UNLOCK(sav);
349 DPRINTF(("%s: packet replay check for %s\n", __func__,
350 ipsec_sa2str(sav, buf, sizeof(buf))));
351 ESPSTAT_INC(esps_replay);
356 cryptoid = sav->tdb_cryptoid;
357 SECASVAR_UNLOCK(sav);
359 /* Update the counters */
360 ESPSTAT_ADD(esps_ibytes, m->m_pkthdr.len - (skip + hlen + alen));
362 /* Get crypto descriptors */
363 crp = crypto_getreq(esph && espx ? 2 : 1);
365 DPRINTF(("%s: failed to acquire crypto descriptors\n",
367 ESPSTAT_INC(esps_crypto);
372 /* Get IPsec-specific opaque pointer */
373 xd = malloc(sizeof(*xd) + alen, M_XDATA, M_NOWAIT | M_ZERO);
375 DPRINTF(("%s: failed to allocate xform_data\n", __func__));
376 ESPSTAT_INC(esps_crypto);
383 struct cryptodesc *crda = crp->crp_desc;
385 IPSEC_ASSERT(crda != NULL, ("null ah crypto descriptor"));
387 /* Authentication descriptor */
388 crda->crd_skip = skip;
390 crda->crd_len = 8; /* RFC4106 5, SPI + SN */
392 crda->crd_len = m->m_pkthdr.len - (skip + alen);
393 crda->crd_inject = m->m_pkthdr.len - alen;
395 crda->crd_alg = esph->type;
397 /* Copy the authenticator */
398 m_copydata(m, m->m_pkthdr.len - alen, alen,
401 /* Chain authentication request */
402 crde = crda->crd_next;
404 crde = crp->crp_desc;
407 /* Crypto operation descriptor */
408 crp->crp_ilen = m->m_pkthdr.len; /* Total input length */
409 crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
411 crp->crp_flags |= CRYPTO_F_ASYNC | CRYPTO_F_ASYNC_KEEPORDER;
412 crp->crp_buf = (caddr_t) m;
413 crp->crp_callback = esp_input_cb;
414 crp->crp_session = cryptoid;
415 crp->crp_opaque = (caddr_t) xd;
417 /* These are passed as-is to the callback */
419 xd->protoff = protoff;
421 xd->cryptoid = cryptoid;
424 /* Decryption descriptor */
425 IPSEC_ASSERT(crde != NULL, ("null esp crypto descriptor"));
426 crde->crd_skip = skip + hlen;
427 crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
428 crde->crd_inject = skip + hlen - sav->ivlen;
430 if (SAV_ISCTRORGCM(sav)) {
431 ivp = &crde->crd_iv[0];
433 /* GCM IV Format: RFC4106 4 */
434 /* CTR IV Format: RFC3686 4 */
435 /* Salt is last four bytes of key, RFC4106 8.1 */
436 /* Nonce is last four bytes of key, RFC3686 5.1 */
437 memcpy(ivp, sav->key_enc->key_data +
438 _KEYLEN(sav->key_enc) - 4, 4);
440 if (SAV_ISCTR(sav)) {
441 /* Initial block counter is 1, RFC3686 4 */
442 be32enc(&ivp[sav->ivlen + 4], 1);
445 m_copydata(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
446 crde->crd_flags |= CRD_F_IV_EXPLICIT;
449 crde->crd_alg = espx->type;
451 return (crypto_dispatch(crp));
459 * ESP input callback from the crypto driver.
462 esp_input_cb(struct cryptop *crp)
464 IPSEC_DEBUG_DECLARE(char buf[128]);
465 u_int8_t lastthree[3], aalg[AH_HMAC_MAXHASHLEN];
466 const struct auth_hash *esph;
468 struct cryptodesc *crd;
469 struct xform_data *xd;
470 struct secasvar *sav;
471 struct secasindex *saidx;
473 crypto_session_t cryptoid;
474 int hlen, skip, protoff, error, alen;
477 IPSEC_ASSERT(crd != NULL, ("null crypto descriptor!"));
479 m = (struct mbuf *) crp->crp_buf;
480 xd = (struct xform_data *) crp->crp_opaque;
481 CURVNET_SET(xd->vnet);
484 protoff = xd->protoff;
485 cryptoid = xd->cryptoid;
486 saidx = &sav->sah->saidx;
487 esph = sav->tdb_authalgxform;
489 /* Check for crypto errors */
490 if (crp->crp_etype) {
491 if (crp->crp_etype == EAGAIN) {
492 /* Reset the session ID */
493 if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
494 crypto_freesession(cryptoid);
495 xd->cryptoid = crp->crp_session;
497 return (crypto_dispatch(crp));
499 ESPSTAT_INC(esps_noxform);
500 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
501 error = crp->crp_etype;
505 /* Shouldn't happen... */
507 ESPSTAT_INC(esps_crypto);
508 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
512 ESPSTAT_INC(esps_hist[sav->alg_enc]);
514 /* If authentication was performed, check now. */
516 alen = xform_ah_authsize(esph);
517 AHSTAT_INC(ahs_hist[sav->alg_auth]);
518 /* Copy the authenticator from the packet */
519 m_copydata(m, m->m_pkthdr.len - alen, alen, aalg);
520 ptr = (caddr_t) (xd + 1);
522 /* Verify authenticator */
523 if (timingsafe_bcmp(ptr, aalg, alen) != 0) {
524 DPRINTF(("%s: authentication hash mismatch for "
525 "packet in SA %s/%08lx\n", __func__,
526 ipsec_address(&saidx->dst, buf, sizeof(buf)),
527 (u_long) ntohl(sav->spi)));
528 ESPSTAT_INC(esps_badauth);
532 m->m_flags |= M_AUTHIPDGM;
533 /* Remove trailing authenticator */
537 /* Release the crypto descriptors */
538 free(xd, M_XDATA), xd = NULL;
539 crypto_freereq(crp), crp = NULL;
542 * Packet is now decrypted.
544 m->m_flags |= M_DECRYPTED;
547 * Update replay sequence number, if appropriate.
552 m_copydata(m, skip + offsetof(struct newesp, esp_seq),
553 sizeof (seq), (caddr_t) &seq);
555 if (ipsec_updatereplay(ntohl(seq), sav)) {
556 SECASVAR_UNLOCK(sav);
557 DPRINTF(("%s: packet replay check for %s\n", __func__,
558 ipsec_sa2str(sav, buf, sizeof(buf))));
559 ESPSTAT_INC(esps_replay);
563 SECASVAR_UNLOCK(sav);
566 /* Determine the ESP header length */
567 if (sav->flags & SADB_X_EXT_OLD)
568 hlen = sizeof (struct esp) + sav->ivlen;
570 hlen = sizeof (struct newesp) + sav->ivlen;
572 /* Remove the ESP header and IV from the mbuf. */
573 error = m_striphdr(m, skip, hlen);
575 ESPSTAT_INC(esps_hdrops);
576 DPRINTF(("%s: bad mbuf chain, SA %s/%08lx\n", __func__,
577 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
578 (u_long) ntohl(sav->spi)));
582 /* Save the last three bytes of decrypted data */
583 m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
585 /* Verify pad length */
586 if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
587 ESPSTAT_INC(esps_badilen);
588 DPRINTF(("%s: invalid padding length %d for %u byte packet "
589 "in SA %s/%08lx\n", __func__, lastthree[1],
590 m->m_pkthdr.len - skip,
591 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
592 (u_long) ntohl(sav->spi)));
597 /* Verify correct decryption by checking the last padding bytes */
598 if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
599 if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
600 ESPSTAT_INC(esps_badenc);
601 DPRINTF(("%s: decryption failed for packet in "
602 "SA %s/%08lx\n", __func__, ipsec_address(
603 &sav->sah->saidx.dst, buf, sizeof(buf)),
604 (u_long) ntohl(sav->spi)));
610 /* Trim the mbuf chain to remove trailing authenticator and padding */
611 m_adj(m, -(lastthree[1] + 2));
613 /* Restore the Next Protocol field */
614 m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
616 switch (saidx->dst.sa.sa_family) {
619 error = ipsec6_common_input_cb(m, sav, skip, protoff);
624 error = ipsec4_common_input_cb(m, sav, skip, protoff);
628 panic("%s: Unexpected address family: %d saidx=%p", __func__,
629 saidx->dst.sa.sa_family, saidx);
646 * ESP output routine, called by ipsec[46]_perform_request().
649 esp_output(struct mbuf *m, struct secpolicy *sp, struct secasvar *sav,
650 u_int idx, int skip, int protoff)
652 IPSEC_DEBUG_DECLARE(char buf[IPSEC_ADDRSTRLEN]);
653 struct cryptodesc *crde = NULL, *crda = NULL;
655 const struct auth_hash *esph;
656 const struct enc_xform *espx;
657 struct mbuf *mo = NULL;
658 struct xform_data *xd;
659 struct secasindex *saidx;
663 crypto_session_t cryptoid;
664 int hlen, rlen, padding, blks, alen, i, roff;
665 int error, maxpacketsize;
668 IPSEC_ASSERT(sav != NULL, ("null SA"));
669 esph = sav->tdb_authalgxform;
670 espx = sav->tdb_encalgxform;
671 IPSEC_ASSERT(espx != NULL, ("null encoding xform"));
673 if (sav->flags & SADB_X_EXT_OLD)
674 hlen = sizeof (struct esp) + sav->ivlen;
676 hlen = sizeof (struct newesp) + sav->ivlen;
678 rlen = m->m_pkthdr.len - skip; /* Raw payload length. */
680 * RFC4303 2.4 Requires 4 byte alignment.
682 blks = MAX(4, espx->blocksize); /* Cipher blocksize */
684 /* XXX clamp padding length a la KAME??? */
685 padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
687 alen = xform_ah_authsize(esph);
689 ESPSTAT_INC(esps_output);
691 saidx = &sav->sah->saidx;
692 /* Check for maximum packet size violations. */
693 switch (saidx->dst.sa.sa_family) {
696 maxpacketsize = IP_MAXPACKET;
701 maxpacketsize = IPV6_MAXPACKET;
705 DPRINTF(("%s: unknown/unsupported protocol "
706 "family %d, SA %s/%08lx\n", __func__,
707 saidx->dst.sa.sa_family, ipsec_address(&saidx->dst,
708 buf, sizeof(buf)), (u_long) ntohl(sav->spi)));
709 ESPSTAT_INC(esps_nopf);
710 error = EPFNOSUPPORT;
714 DPRINTF(("%s: skip %d hlen %d rlen %d padding %d alen %d blksd %d\n",
715 __func__, skip, hlen, rlen, padding, alen, blks)); */
716 if (skip + hlen + rlen + padding + alen > maxpacketsize) {
717 DPRINTF(("%s: packet in SA %s/%08lx got too big "
718 "(len %u, max len %u)\n", __func__,
719 ipsec_address(&saidx->dst, buf, sizeof(buf)),
720 (u_long) ntohl(sav->spi),
721 skip + hlen + rlen + padding + alen, maxpacketsize));
722 ESPSTAT_INC(esps_toobig);
727 /* Update the counters. */
728 ESPSTAT_ADD(esps_obytes, m->m_pkthdr.len - skip);
730 m = m_unshare(m, M_NOWAIT);
732 DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
733 ipsec_address(&saidx->dst, buf, sizeof(buf)),
734 (u_long) ntohl(sav->spi)));
735 ESPSTAT_INC(esps_hdrops);
740 /* Inject ESP header. */
741 mo = m_makespace(m, skip, hlen, &roff);
743 DPRINTF(("%s: %u byte ESP hdr inject failed for SA %s/%08lx\n",
744 __func__, hlen, ipsec_address(&saidx->dst, buf,
745 sizeof(buf)), (u_long) ntohl(sav->spi)));
746 ESPSTAT_INC(esps_hdrops); /* XXX diffs from openbsd */
751 /* Initialize ESP header. */
752 bcopy((caddr_t) &sav->spi, mtod(mo, caddr_t) + roff,
759 /* Emulate replay attack when ipsec_replay is TRUE. */
762 sav->replay->count++;
763 replay = htonl(sav->replay->count);
765 bcopy((caddr_t) &replay, mtod(mo, caddr_t) + roff +
766 sizeof(uint32_t), sizeof(uint32_t));
768 cryptoid = sav->tdb_cryptoid;
769 if (SAV_ISCTRORGCM(sav))
771 SECASVAR_UNLOCK(sav);
774 * Add padding -- better to do it ourselves than use the crypto engine,
775 * although if/when we support compression, we'd have to do that.
777 pad = (u_char *) m_pad(m, padding + alen);
779 DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
780 ipsec_address(&saidx->dst, buf, sizeof(buf)),
781 (u_long) ntohl(sav->spi)));
782 m = NULL; /* NB: free'd by m_pad */
788 * Add padding: random, zero, or self-describing.
789 * XXX catch unexpected setting
791 switch (sav->flags & SADB_X_EXT_PMASK) {
792 case SADB_X_EXT_PRAND:
793 arc4random_buf(pad, padding - 2);
795 case SADB_X_EXT_PZERO:
796 bzero(pad, padding - 2);
798 case SADB_X_EXT_PSEQ:
799 for (i = 0; i < padding - 2; i++)
804 /* Fix padding length and Next Protocol in padding itself. */
805 pad[padding - 2] = padding - 2;
806 m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
808 /* Fix Next Protocol in IPv4/IPv6 header. */
810 m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
812 /* Get crypto descriptors. */
813 crp = crypto_getreq(esph != NULL ? 2 : 1);
815 DPRINTF(("%s: failed to acquire crypto descriptors\n",
817 ESPSTAT_INC(esps_crypto);
822 /* IPsec-specific opaque crypto info. */
823 xd = malloc(sizeof(struct xform_data), M_XDATA, M_NOWAIT | M_ZERO);
826 DPRINTF(("%s: failed to allocate xform_data\n", __func__));
827 ESPSTAT_INC(esps_crypto);
832 crde = crp->crp_desc;
833 crda = crde->crd_next;
835 /* Encryption descriptor. */
836 crde->crd_skip = skip + hlen;
837 crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
838 crde->crd_flags = CRD_F_ENCRYPT;
839 crde->crd_inject = skip + hlen - sav->ivlen;
841 /* Encryption operation. */
842 crde->crd_alg = espx->type;
843 if (SAV_ISCTRORGCM(sav)) {
844 ivp = &crde->crd_iv[0];
846 /* GCM IV Format: RFC4106 4 */
847 /* CTR IV Format: RFC3686 4 */
848 /* Salt is last four bytes of key, RFC4106 8.1 */
849 /* Nonce is last four bytes of key, RFC3686 5.1 */
850 memcpy(ivp, sav->key_enc->key_data +
851 _KEYLEN(sav->key_enc) - 4, 4);
852 be64enc(&ivp[4], cntr);
853 if (SAV_ISCTR(sav)) {
854 /* Initial block counter is 1, RFC3686 4 */
855 /* XXXAE: should we use this only for first packet? */
856 be32enc(&ivp[sav->ivlen + 4], 1);
859 m_copyback(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
860 crde->crd_flags |= CRD_F_IV_EXPLICIT|CRD_F_IV_PRESENT;
863 /* Callback parameters */
867 xd->cryptoid = cryptoid;
870 /* Crypto operation descriptor. */
871 crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
872 crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
874 crp->crp_flags |= CRYPTO_F_ASYNC | CRYPTO_F_ASYNC_KEEPORDER;
875 crp->crp_buf = (caddr_t) m;
876 crp->crp_callback = esp_output_cb;
877 crp->crp_opaque = (caddr_t) xd;
878 crp->crp_session = cryptoid;
881 /* Authentication descriptor. */
882 crda->crd_alg = esph->type;
883 crda->crd_skip = skip;
885 crda->crd_len = 8; /* RFC4106 5, SPI + SN */
887 crda->crd_len = m->m_pkthdr.len - (skip + alen);
888 crda->crd_inject = m->m_pkthdr.len - alen;
891 return crypto_dispatch(crp);
900 * ESP output callback from the crypto driver.
903 esp_output_cb(struct cryptop *crp)
905 struct xform_data *xd;
906 struct secpolicy *sp;
907 struct secasvar *sav;
909 crypto_session_t cryptoid;
913 xd = (struct xform_data *) crp->crp_opaque;
914 CURVNET_SET(xd->vnet);
915 m = (struct mbuf *) crp->crp_buf;
919 cryptoid = xd->cryptoid;
921 /* Check for crypto errors. */
922 if (crp->crp_etype) {
923 if (crp->crp_etype == EAGAIN) {
924 /* Reset the session ID */
925 if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
926 crypto_freesession(cryptoid);
927 xd->cryptoid = crp->crp_session;
929 return (crypto_dispatch(crp));
931 ESPSTAT_INC(esps_noxform);
932 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
933 error = crp->crp_etype;
938 /* Shouldn't happen... */
940 ESPSTAT_INC(esps_crypto);
941 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
947 ESPSTAT_INC(esps_hist[sav->alg_enc]);
948 if (sav->tdb_authalgxform != NULL)
949 AHSTAT_INC(ahs_hist[sav->alg_auth]);
952 /* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
953 if (V_ipsec_integrity) {
954 static unsigned char ipseczeroes[AH_HMAC_MAXHASHLEN];
955 const struct auth_hash *esph;
958 * Corrupt HMAC if we want to test integrity verification of
961 esph = sav->tdb_authalgxform;
965 alen = xform_ah_authsize(esph);
966 m_copyback(m, m->m_pkthdr.len - alen,
972 /* NB: m is reclaimed by ipsec_process_done. */
973 error = ipsec_process_done(m, sp, sav, idx);
985 static struct xformsw esp_xformsw = {
987 .xf_name = "IPsec ESP",
989 .xf_zeroize = esp_zeroize,
990 .xf_input = esp_input,
991 .xf_output = esp_output,
994 SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
995 xform_attach, &esp_xformsw);
996 SYSUNINIT(esp_xform_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
997 xform_detach, &esp_xformsw);