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/rwlock.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 int esp_input_cb(struct cryptop *op);
98 static int esp_output_cb(struct cryptop *crp);
101 * NB: this is public for use by the PF_KEY support.
102 * NB: if you add support here; be sure to add code to esp_attach below!
105 esp_algorithm_lookup(int alg)
107 if (alg >= ESP_ALG_MAX)
110 case SADB_EALG_DESCBC:
111 return &enc_xform_des;
112 case SADB_EALG_3DESCBC:
113 return &enc_xform_3des;
114 case SADB_X_EALG_AES:
115 return &enc_xform_rijndael128;
116 case SADB_X_EALG_BLOWFISHCBC:
117 return &enc_xform_blf;
118 case SADB_X_EALG_CAST128CBC:
119 return &enc_xform_cast5;
121 return &enc_xform_null;
122 case SADB_X_EALG_CAMELLIACBC:
123 return &enc_xform_camellia;
124 case SADB_X_EALG_AESCTR:
125 return &enc_xform_aes_icm;
126 case SADB_X_EALG_AESGCM16:
127 return &enc_xform_aes_nist_gcm;
128 case SADB_X_EALG_AESGMAC:
129 return &enc_xform_aes_nist_gmac;
135 esp_hdrsiz(struct secasvar *sav)
140 /*XXX not right for null algorithm--does it matter??*/
141 IPSEC_ASSERT(sav->tdb_encalgxform != NULL,
142 ("SA with null xform"));
143 if (sav->flags & SADB_X_EXT_OLD)
144 size = sizeof (struct esp);
146 size = sizeof (struct newesp);
147 size += sav->tdb_encalgxform->blocksize + 9;
148 /*XXX need alg check???*/
149 if (sav->tdb_authalgxform != NULL && sav->replay)
150 size += ah_hdrsiz(sav);
154 * + max iv length for CBC mode
156 * + sizeof (pad length field)
157 * + sizeof (next header field)
158 * + max icv supported.
160 size = sizeof (struct newesp) + EALG_MAX_BLOCK_LEN + 9 + 16;
166 * esp_init() is called when an SPI is being set up.
169 esp_init(struct secasvar *sav, struct xformsw *xsp)
171 struct enc_xform *txform;
172 struct cryptoini cria, crie;
176 txform = esp_algorithm_lookup(sav->alg_enc);
177 if (txform == NULL) {
178 DPRINTF(("%s: unsupported encryption algorithm %d\n",
179 __func__, sav->alg_enc));
182 if (sav->key_enc == NULL) {
183 DPRINTF(("%s: no encoding key for %s algorithm\n",
184 __func__, txform->name));
187 if ((sav->flags & (SADB_X_EXT_OLD | SADB_X_EXT_IV4B)) ==
189 DPRINTF(("%s: 4-byte IV not supported with protocol\n",
193 /* subtract off the salt, RFC4106, 8.1 and RFC3686, 5.1 */
194 keylen = _KEYLEN(sav->key_enc) - SAV_ISCTRORGCM(sav) * 4;
195 if (txform->minkey > keylen || keylen > txform->maxkey) {
196 DPRINTF(("%s: invalid key length %u, must be in the range "
197 "[%u..%u] for algorithm %s\n", __func__,
198 keylen, txform->minkey, txform->maxkey,
203 if (SAV_ISCTRORGCM(sav))
204 sav->ivlen = 8; /* RFC4106 3.1 and RFC3686 3.1 */
206 sav->ivlen = txform->ivsize;
209 * Setup AH-related state.
211 if (sav->alg_auth != 0) {
212 error = ah_init0(sav, xsp, &cria);
217 /* NB: override anything set in ah_init0 */
218 sav->tdb_xform = xsp;
219 sav->tdb_encalgxform = txform;
222 * Whenever AES-GCM is used for encryption, one
223 * of the AES authentication algorithms is chosen
224 * as well, based on the key size.
226 if (sav->alg_enc == SADB_X_EALG_AESGCM16) {
228 case AES_128_GMAC_KEY_LEN:
229 sav->alg_auth = SADB_X_AALG_AES128GMAC;
230 sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_128;
232 case AES_192_GMAC_KEY_LEN:
233 sav->alg_auth = SADB_X_AALG_AES192GMAC;
234 sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_192;
236 case AES_256_GMAC_KEY_LEN:
237 sav->alg_auth = SADB_X_AALG_AES256GMAC;
238 sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_256;
241 DPRINTF(("%s: invalid key length %u"
242 "for algorithm %s\n", __func__,
243 keylen, txform->name));
246 bzero(&cria, sizeof(cria));
247 cria.cri_alg = sav->tdb_authalgxform->type;
248 cria.cri_key = sav->key_enc->key_data;
249 cria.cri_klen = _KEYBITS(sav->key_enc) - SAV_ISGCM(sav) * 32;
252 /* Initialize crypto session. */
253 bzero(&crie, sizeof(crie));
254 crie.cri_alg = sav->tdb_encalgxform->type;
255 crie.cri_key = sav->key_enc->key_data;
256 crie.cri_klen = _KEYBITS(sav->key_enc) - SAV_ISCTRORGCM(sav) * 32;
258 if (sav->tdb_authalgxform && sav->tdb_encalgxform) {
259 /* init both auth & enc */
260 crie.cri_next = &cria;
261 error = crypto_newsession(&sav->tdb_cryptoid,
262 &crie, V_crypto_support);
263 } else if (sav->tdb_encalgxform) {
264 error = crypto_newsession(&sav->tdb_cryptoid,
265 &crie, V_crypto_support);
266 } else if (sav->tdb_authalgxform) {
267 error = crypto_newsession(&sav->tdb_cryptoid,
268 &cria, V_crypto_support);
270 /* XXX cannot happen? */
271 DPRINTF(("%s: no encoding OR authentication xform!\n",
282 esp_zeroize(struct secasvar *sav)
284 /* NB: ah_zerorize free's the crypto session state */
285 int error = ah_zeroize(sav);
288 bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
289 sav->tdb_encalgxform = NULL;
290 sav->tdb_xform = NULL;
295 * ESP input processing, called (eventually) through the protocol switch.
298 esp_input(struct mbuf *m, struct secasvar *sav, int skip, int protoff)
301 struct auth_hash *esph;
302 struct enc_xform *espx;
303 struct tdb_crypto *tc;
305 int plen, alen, hlen;
307 struct cryptodesc *crde;
310 IPSEC_ASSERT(sav != NULL, ("null SA"));
311 IPSEC_ASSERT(sav->tdb_encalgxform != NULL, ("null encoding xform"));
313 /* Valid IP Packet length ? */
314 if ( (skip&3) || (m->m_pkthdr.len&3) ){
315 DPRINTF(("%s: misaligned packet, skip %u pkt len %u",
316 __func__, skip, m->m_pkthdr.len));
317 ESPSTAT_INC(esps_badilen);
321 /* XXX don't pullup, just copy header */
322 IP6_EXTHDR_GET(esp, struct newesp *, m, skip, sizeof (struct newesp));
324 esph = sav->tdb_authalgxform;
325 espx = sav->tdb_encalgxform;
327 /* Determine the ESP header and auth length */
328 if (sav->flags & SADB_X_EXT_OLD)
329 hlen = sizeof (struct esp) + sav->ivlen;
331 hlen = sizeof (struct newesp) + sav->ivlen;
333 alen = xform_ah_authsize(esph);
336 * Verify payload length is multiple of encryption algorithm
339 * NB: This works for the null algorithm because the blocksize
340 * is 4 and all packets must be 4-byte aligned regardless
343 plen = m->m_pkthdr.len - (skip + hlen + alen);
344 if ((plen & (espx->blocksize - 1)) || (plen <= 0)) {
345 DPRINTF(("%s: payload of %d octets not a multiple of %d octets,"
346 " SA %s/%08lx\n", __func__, plen, espx->blocksize,
347 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
348 (u_long)ntohl(sav->spi)));
349 ESPSTAT_INC(esps_badilen);
355 * Check sequence number.
357 if (esph != NULL && sav->replay != NULL &&
358 !ipsec_chkreplay(ntohl(esp->esp_seq), sav)) {
359 DPRINTF(("%s: packet replay check for %s\n", __func__,
360 ipsec_logsastr(sav, buf, sizeof(buf)))); /*XXX*/
361 ESPSTAT_INC(esps_replay);
363 return ENOBUFS; /*XXX*/
366 /* Update the counters */
367 ESPSTAT_ADD(esps_ibytes, m->m_pkthdr.len - (skip + hlen + alen));
369 /* Get crypto descriptors */
370 crp = crypto_getreq(esph && espx ? 2 : 1);
372 DPRINTF(("%s: failed to acquire crypto descriptors\n",
374 ESPSTAT_INC(esps_crypto);
379 /* Get IPsec-specific opaque pointer */
380 tc = (struct tdb_crypto *) malloc(sizeof(struct tdb_crypto) + alen,
381 M_XDATA, M_NOWAIT | M_ZERO);
384 DPRINTF(("%s: failed to allocate tdb_crypto\n", __func__));
385 ESPSTAT_INC(esps_crypto);
391 struct cryptodesc *crda = crp->crp_desc;
393 IPSEC_ASSERT(crda != NULL, ("null ah crypto descriptor"));
395 /* Authentication descriptor */
396 crda->crd_skip = skip;
398 crda->crd_len = 8; /* RFC4106 5, SPI + SN */
400 crda->crd_len = m->m_pkthdr.len - (skip + alen);
401 crda->crd_inject = m->m_pkthdr.len - alen;
403 crda->crd_alg = esph->type;
405 /* Copy the authenticator */
406 m_copydata(m, m->m_pkthdr.len - alen, alen,
409 /* Chain authentication request */
410 crde = crda->crd_next;
412 crde = crp->crp_desc;
415 /* Crypto operation descriptor */
416 crp->crp_ilen = m->m_pkthdr.len; /* Total input length */
417 crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
418 crp->crp_buf = (caddr_t) m;
419 crp->crp_callback = esp_input_cb;
420 crp->crp_sid = sav->tdb_cryptoid;
421 crp->crp_opaque = (caddr_t) tc;
423 /* These are passed as-is to the callback */
424 tc->tc_spi = sav->spi;
425 tc->tc_dst = sav->sah->saidx.dst;
426 tc->tc_proto = sav->sah->saidx.proto;
427 tc->tc_protoff = protoff;
432 /* Decryption descriptor */
433 IPSEC_ASSERT(crde != NULL, ("null esp crypto descriptor"));
434 crde->crd_skip = skip + hlen;
435 crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
436 crde->crd_inject = skip + hlen - sav->ivlen;
438 if (SAV_ISCTRORGCM(sav)) {
439 ivp = &crde->crd_iv[0];
441 /* GCM IV Format: RFC4106 4 */
442 /* CTR IV Format: RFC3686 4 */
443 /* Salt is last four bytes of key, RFC4106 8.1 */
444 /* Nonce is last four bytes of key, RFC3686 5.1 */
445 memcpy(ivp, sav->key_enc->key_data +
446 _KEYLEN(sav->key_enc) - 4, 4);
448 if (SAV_ISCTR(sav)) {
449 /* Initial block counter is 1, RFC3686 4 */
450 be32enc(&ivp[sav->ivlen + 4], 1);
453 m_copydata(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
454 crde->crd_flags |= CRD_F_IV_EXPLICIT;
457 crde->crd_alg = espx->type;
459 return (crypto_dispatch(crp));
463 * ESP input callback from the crypto driver.
466 esp_input_cb(struct cryptop *crp)
469 u_int8_t lastthree[3], aalg[AH_HMAC_MAXHASHLEN];
470 int hlen, skip, protoff, error, alen;
472 struct cryptodesc *crd;
473 struct auth_hash *esph;
474 struct enc_xform *espx;
475 struct tdb_crypto *tc;
476 struct secasvar *sav;
477 struct secasindex *saidx;
481 IPSEC_ASSERT(crd != NULL, ("null crypto descriptor!"));
483 tc = (struct tdb_crypto *) crp->crp_opaque;
484 IPSEC_ASSERT(tc != NULL, ("null opaque crypto data area!"));
486 protoff = tc->tc_protoff;
487 m = (struct mbuf *) crp->crp_buf;
490 IPSEC_ASSERT(sav != NULL, ("null SA!"));
492 saidx = &sav->sah->saidx;
493 IPSEC_ASSERT(saidx->dst.sa.sa_family == AF_INET ||
494 saidx->dst.sa.sa_family == AF_INET6,
495 ("unexpected protocol family %u", saidx->dst.sa.sa_family));
497 esph = sav->tdb_authalgxform;
498 espx = sav->tdb_encalgxform;
500 /* Check for crypto errors */
501 if (crp->crp_etype) {
502 /* Reset the session ID */
503 if (sav->tdb_cryptoid != 0)
504 sav->tdb_cryptoid = crp->crp_sid;
506 if (crp->crp_etype == EAGAIN)
507 return (crypto_dispatch(crp));
509 ESPSTAT_INC(esps_noxform);
510 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
511 error = crp->crp_etype;
515 /* Shouldn't happen... */
517 ESPSTAT_INC(esps_crypto);
518 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
522 ESPSTAT_INC(esps_hist[sav->alg_enc]);
524 /* If authentication was performed, check now. */
526 alen = xform_ah_authsize(esph);
527 AHSTAT_INC(ahs_hist[sav->alg_auth]);
528 /* Copy the authenticator from the packet */
529 m_copydata(m, m->m_pkthdr.len - alen, alen, aalg);
530 ptr = (caddr_t) (tc + 1);
532 /* Verify authenticator */
533 if (timingsafe_bcmp(ptr, aalg, alen) != 0) {
534 DPRINTF(("%s: authentication hash mismatch for "
535 "packet in SA %s/%08lx\n", __func__,
536 ipsec_address(&saidx->dst, buf, sizeof(buf)),
537 (u_long) ntohl(sav->spi)));
538 ESPSTAT_INC(esps_badauth);
543 /* Remove trailing authenticator */
547 /* Release the crypto descriptors */
548 free(tc, M_XDATA), tc = NULL;
549 crypto_freereq(crp), crp = NULL;
552 * Packet is now decrypted.
554 m->m_flags |= M_DECRYPTED;
557 * Update replay sequence number, if appropriate.
562 m_copydata(m, skip + offsetof(struct newesp, esp_seq),
563 sizeof (seq), (caddr_t) &seq);
564 if (ipsec_updatereplay(ntohl(seq), sav)) {
565 DPRINTF(("%s: packet replay check for %s\n", __func__,
566 ipsec_logsastr(sav, buf, sizeof(buf))));
567 ESPSTAT_INC(esps_replay);
573 /* Determine the ESP header length */
574 if (sav->flags & SADB_X_EXT_OLD)
575 hlen = sizeof (struct esp) + sav->ivlen;
577 hlen = sizeof (struct newesp) + sav->ivlen;
579 /* Remove the ESP header and IV from the mbuf. */
580 error = m_striphdr(m, skip, hlen);
582 ESPSTAT_INC(esps_hdrops);
583 DPRINTF(("%s: bad mbuf chain, SA %s/%08lx\n", __func__,
584 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
585 (u_long) ntohl(sav->spi)));
589 /* Save the last three bytes of decrypted data */
590 m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
592 /* Verify pad length */
593 if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
594 ESPSTAT_INC(esps_badilen);
595 DPRINTF(("%s: invalid padding length %d for %u byte packet "
596 "in SA %s/%08lx\n", __func__, lastthree[1],
597 m->m_pkthdr.len - skip,
598 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
599 (u_long) ntohl(sav->spi)));
604 /* Verify correct decryption by checking the last padding bytes */
605 if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
606 if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
607 ESPSTAT_INC(esps_badenc);
608 DPRINTF(("%s: decryption failed for packet in "
609 "SA %s/%08lx\n", __func__, ipsec_address(
610 &sav->sah->saidx.dst, buf, sizeof(buf)),
611 (u_long) ntohl(sav->spi)));
617 /* Trim the mbuf chain to remove trailing authenticator and padding */
618 m_adj(m, -(lastthree[1] + 2));
620 /* Restore the Next Protocol field */
621 m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
623 switch (saidx->dst.sa.sa_family) {
626 error = ipsec6_common_input_cb(m, sav, skip, protoff);
631 error = ipsec4_common_input_cb(m, sav, skip, protoff);
635 panic("%s: Unexpected address family: %d saidx=%p", __func__,
636 saidx->dst.sa.sa_family, saidx);
654 * ESP output routine, called by ipsec[46]_process_packet().
657 esp_output(struct mbuf *m, struct ipsecrequest *isr, struct mbuf **mp,
658 int skip, int protoff)
660 char buf[INET6_ADDRSTRLEN];
661 struct enc_xform *espx;
662 struct auth_hash *esph;
665 int hlen, rlen, padding, blks, alen, i, roff;
666 struct mbuf *mo = (struct mbuf *) NULL;
667 struct tdb_crypto *tc;
668 struct secasvar *sav;
669 struct secasindex *saidx;
672 int error, maxpacketsize;
674 struct cryptodesc *crde = NULL, *crda = NULL;
678 IPSEC_ASSERT(sav != NULL, ("null SA"));
679 esph = sav->tdb_authalgxform;
680 espx = sav->tdb_encalgxform;
681 IPSEC_ASSERT(espx != NULL, ("null encoding xform"));
683 if (sav->flags & SADB_X_EXT_OLD)
684 hlen = sizeof (struct esp) + sav->ivlen;
686 hlen = sizeof (struct newesp) + sav->ivlen;
688 rlen = m->m_pkthdr.len - skip; /* Raw payload length. */
690 * RFC4303 2.4 Requires 4 byte alignment.
692 blks = MAX(4, espx->blocksize); /* Cipher blocksize */
694 /* XXX clamp padding length a la KAME??? */
695 padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
697 alen = xform_ah_authsize(esph);
699 ESPSTAT_INC(esps_output);
701 saidx = &sav->sah->saidx;
702 /* Check for maximum packet size violations. */
703 switch (saidx->dst.sa.sa_family) {
706 maxpacketsize = IP_MAXPACKET;
711 maxpacketsize = IPV6_MAXPACKET;
715 DPRINTF(("%s: unknown/unsupported protocol "
716 "family %d, SA %s/%08lx\n", __func__,
717 saidx->dst.sa.sa_family, ipsec_address(&saidx->dst,
718 buf, sizeof(buf)), (u_long) ntohl(sav->spi)));
719 ESPSTAT_INC(esps_nopf);
720 error = EPFNOSUPPORT;
723 DPRINTF(("%s: skip %d hlen %d rlen %d padding %d alen %d blksd %d\n",
724 __func__, skip, hlen, rlen, padding, alen, blks));
725 if (skip + hlen + rlen + padding + alen > maxpacketsize) {
726 DPRINTF(("%s: packet in SA %s/%08lx got too big "
727 "(len %u, max len %u)\n", __func__,
728 ipsec_address(&saidx->dst, buf, sizeof(buf)),
729 (u_long) ntohl(sav->spi),
730 skip + hlen + rlen + padding + alen, maxpacketsize));
731 ESPSTAT_INC(esps_toobig);
736 /* Update the counters. */
737 ESPSTAT_ADD(esps_obytes, m->m_pkthdr.len - skip);
739 m = m_unshare(m, M_NOWAIT);
741 DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
742 ipsec_address(&saidx->dst, buf, sizeof(buf)),
743 (u_long) ntohl(sav->spi)));
744 ESPSTAT_INC(esps_hdrops);
749 /* Inject ESP header. */
750 mo = m_makespace(m, skip, hlen, &roff);
752 DPRINTF(("%s: %u byte ESP hdr inject failed for SA %s/%08lx\n",
753 __func__, hlen, ipsec_address(&saidx->dst, buf,
754 sizeof(buf)), (u_long) ntohl(sav->spi)));
755 ESPSTAT_INC(esps_hdrops); /* XXX diffs from openbsd */
760 /* Initialize ESP header. */
761 bcopy((caddr_t) &sav->spi, mtod(mo, caddr_t) + roff, sizeof(u_int32_t));
767 /* Emulate replay attack when ipsec_replay is TRUE. */
770 sav->replay->count++;
771 replay = htonl(sav->replay->count);
772 SECASVAR_UNLOCK(sav);
773 bcopy((caddr_t) &replay,
774 mtod(mo, caddr_t) + roff + sizeof(u_int32_t),
779 * Add padding -- better to do it ourselves than use the crypto engine,
780 * although if/when we support compression, we'd have to do that.
782 pad = (u_char *) m_pad(m, padding + alen);
784 DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
785 ipsec_address(&saidx->dst, buf, sizeof(buf)),
786 (u_long) ntohl(sav->spi)));
787 m = NULL; /* NB: free'd by m_pad */
793 * Add padding: random, zero, or self-describing.
794 * XXX catch unexpected setting
796 switch (sav->flags & SADB_X_EXT_PMASK) {
797 case SADB_X_EXT_PRAND:
798 (void) read_random(pad, padding - 2);
800 case SADB_X_EXT_PZERO:
801 bzero(pad, padding - 2);
803 case SADB_X_EXT_PSEQ:
804 for (i = 0; i < padding - 2; i++)
809 /* Fix padding length and Next Protocol in padding itself. */
810 pad[padding - 2] = padding - 2;
811 m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
813 /* Fix Next Protocol in IPv4/IPv6 header. */
815 m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
817 /* Get crypto descriptors. */
818 crp = crypto_getreq(esph != NULL ? 2 : 1);
820 DPRINTF(("%s: failed to acquire crypto descriptors\n",
822 ESPSTAT_INC(esps_crypto);
827 /* IPsec-specific opaque crypto info. */
828 tc = (struct tdb_crypto *) malloc(sizeof(struct tdb_crypto),
829 M_XDATA, M_NOWAIT|M_ZERO);
832 DPRINTF(("%s: failed to allocate tdb_crypto\n", __func__));
833 ESPSTAT_INC(esps_crypto);
838 crde = crp->crp_desc;
839 crda = crde->crd_next;
841 /* Encryption descriptor. */
842 crde->crd_skip = skip + hlen;
843 crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
844 crde->crd_flags = CRD_F_ENCRYPT;
845 crde->crd_inject = skip + hlen - sav->ivlen;
847 /* Encryption operation. */
848 crde->crd_alg = espx->type;
849 if (SAV_ISCTRORGCM(sav)) {
850 ivp = &crde->crd_iv[0];
852 /* GCM IV Format: RFC4106 4 */
853 /* CTR IV Format: RFC3686 4 */
854 /* Salt is last four bytes of key, RFC4106 8.1 */
855 /* Nonce is last four bytes of key, RFC3686 5.1 */
856 memcpy(ivp, sav->key_enc->key_data +
857 _KEYLEN(sav->key_enc) - 4, 4);
860 SECASVAR_UNLOCK(sav);
861 be64enc(&ivp[4], cntr);
863 if (SAV_ISCTR(sav)) {
864 /* Initial block counter is 1, RFC3686 4 */
865 be32enc(&ivp[sav->ivlen + 4], 1);
868 m_copyback(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
869 crde->crd_flags |= CRD_F_IV_EXPLICIT|CRD_F_IV_PRESENT;
872 /* Callback parameters */
877 tc->tc_spi = sav->spi;
878 tc->tc_dst = saidx->dst;
879 tc->tc_proto = saidx->proto;
881 /* Crypto operation descriptor. */
882 crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
883 crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
884 crp->crp_buf = (caddr_t) m;
885 crp->crp_callback = esp_output_cb;
886 crp->crp_opaque = (caddr_t) tc;
887 crp->crp_sid = sav->tdb_cryptoid;
890 /* Authentication descriptor. */
891 crda->crd_alg = esph->type;
892 crda->crd_skip = skip;
894 crda->crd_len = 8; /* RFC4106 5, SPI + SN */
896 crda->crd_len = m->m_pkthdr.len - (skip + alen);
897 crda->crd_inject = m->m_pkthdr.len - alen;
900 return crypto_dispatch(crp);
908 * ESP output callback from the crypto driver.
911 esp_output_cb(struct cryptop *crp)
913 char buf[INET6_ADDRSTRLEN];
914 struct tdb_crypto *tc;
915 struct ipsecrequest *isr;
916 struct secasvar *sav;
920 tc = (struct tdb_crypto *) crp->crp_opaque;
921 IPSEC_ASSERT(tc != NULL, ("null opaque data area!"));
922 m = (struct mbuf *) crp->crp_buf;
925 IPSEC_ASSERT(isr->sp != NULL, ("NULL isr->sp"));
926 IPSECREQUEST_LOCK(isr);
929 /* With the isr lock released, SA pointer may have changed. */
930 if (sav != isr->sav) {
931 ESPSTAT_INC(esps_notdb);
932 DPRINTF(("%s: SA gone during crypto (SA %s/%08lx proto %u)\n",
933 __func__, ipsec_address(&tc->tc_dst, buf, sizeof(buf)),
934 (u_long) ntohl(tc->tc_spi), tc->tc_proto));
935 error = ENOBUFS; /*XXX*/
939 /* Check for crypto errors. */
940 if (crp->crp_etype) {
941 /* Reset session ID. */
942 if (sav->tdb_cryptoid != 0)
943 sav->tdb_cryptoid = crp->crp_sid;
945 if (crp->crp_etype == EAGAIN) {
946 IPSECREQUEST_UNLOCK(isr);
947 return (crypto_dispatch(crp));
950 ESPSTAT_INC(esps_noxform);
951 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
952 error = crp->crp_etype;
956 /* Shouldn't happen... */
958 ESPSTAT_INC(esps_crypto);
959 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
963 ESPSTAT_INC(esps_hist[sav->alg_enc]);
964 if (sav->tdb_authalgxform != NULL)
965 AHSTAT_INC(ahs_hist[sav->alg_auth]);
967 /* Release crypto descriptors. */
972 /* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
973 if (V_ipsec_integrity) {
974 static unsigned char ipseczeroes[AH_HMAC_MAXHASHLEN];
975 struct auth_hash *esph;
978 * Corrupt HMAC if we want to test integrity verification of
981 esph = sav->tdb_authalgxform;
985 alen = xform_ah_authsize(esph);
986 m_copyback(m, m->m_pkthdr.len - alen,
992 /* NB: m is reclaimed by ipsec_process_done. */
993 error = ipsec_process_done(m, isr);
995 IPSECREQUEST_UNLOCK(isr);
996 KEY_FREESP(&isr->sp);
1001 IPSECREQUEST_UNLOCK(isr);
1002 KEY_FREESP(&isr->sp);
1006 crypto_freereq(crp);
1010 static struct xformsw esp_xformsw = {
1011 XF_ESP, XFT_CONF|XFT_AUTH, "IPsec ESP",
1012 esp_init, esp_zeroize, esp_input,
1020 xform_register(&esp_xformsw);
1022 SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE, esp_attach, NULL);