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 int esp_input_cb(struct cryptop *op);
98 static int esp_output_cb(struct cryptop *crp);
101 esp_hdrsiz(struct secasvar *sav)
106 /*XXX not right for null algorithm--does it matter??*/
107 IPSEC_ASSERT(sav->tdb_encalgxform != NULL,
108 ("SA with null xform"));
109 if (sav->flags & SADB_X_EXT_OLD)
110 size = sizeof (struct esp);
112 size = sizeof (struct newesp);
113 size += sav->tdb_encalgxform->blocksize + 9;
114 /*XXX need alg check???*/
115 if (sav->tdb_authalgxform != NULL && sav->replay)
116 size += ah_hdrsiz(sav);
120 * + max iv length for CBC mode
122 * + sizeof (pad length field)
123 * + sizeof (next header field)
124 * + max icv supported.
126 size = sizeof (struct newesp) + EALG_MAX_BLOCK_LEN + 9 + 16;
132 * esp_init() is called when an SPI is being set up.
135 esp_init(struct secasvar *sav, struct xformsw *xsp)
137 const struct enc_xform *txform;
138 struct cryptoini cria, crie;
142 txform = enc_algorithm_lookup(sav->alg_enc);
143 if (txform == NULL) {
144 DPRINTF(("%s: unsupported encryption algorithm %d\n",
145 __func__, sav->alg_enc));
148 if (sav->key_enc == NULL) {
149 DPRINTF(("%s: no encoding key for %s algorithm\n",
150 __func__, txform->name));
153 if ((sav->flags & (SADB_X_EXT_OLD | SADB_X_EXT_IV4B)) ==
155 DPRINTF(("%s: 4-byte IV not supported with protocol\n",
159 /* subtract off the salt, RFC4106, 8.1 and RFC3686, 5.1 */
160 keylen = _KEYLEN(sav->key_enc) - SAV_ISCTRORGCM(sav) * 4;
161 if (txform->minkey > keylen || keylen > txform->maxkey) {
162 DPRINTF(("%s: invalid key length %u, must be in the range "
163 "[%u..%u] for algorithm %s\n", __func__,
164 keylen, txform->minkey, txform->maxkey,
169 if (SAV_ISCTRORGCM(sav))
170 sav->ivlen = 8; /* RFC4106 3.1 and RFC3686 3.1 */
172 sav->ivlen = txform->ivsize;
175 * Setup AH-related state.
177 if (sav->alg_auth != 0) {
178 error = ah_init0(sav, xsp, &cria);
183 /* NB: override anything set in ah_init0 */
184 sav->tdb_xform = xsp;
185 sav->tdb_encalgxform = txform;
188 * Whenever AES-GCM is used for encryption, one
189 * of the AES authentication algorithms is chosen
190 * as well, based on the key size.
192 if (sav->alg_enc == SADB_X_EALG_AESGCM16) {
194 case AES_128_GMAC_KEY_LEN:
195 sav->alg_auth = SADB_X_AALG_AES128GMAC;
196 sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_128;
198 case AES_192_GMAC_KEY_LEN:
199 sav->alg_auth = SADB_X_AALG_AES192GMAC;
200 sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_192;
202 case AES_256_GMAC_KEY_LEN:
203 sav->alg_auth = SADB_X_AALG_AES256GMAC;
204 sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_256;
207 DPRINTF(("%s: invalid key length %u"
208 "for algorithm %s\n", __func__,
209 keylen, txform->name));
212 bzero(&cria, sizeof(cria));
213 cria.cri_alg = sav->tdb_authalgxform->type;
214 cria.cri_key = sav->key_enc->key_data;
215 cria.cri_klen = _KEYBITS(sav->key_enc) - SAV_ISGCM(sav) * 32;
218 /* Initialize crypto session. */
219 bzero(&crie, sizeof(crie));
220 crie.cri_alg = sav->tdb_encalgxform->type;
221 crie.cri_key = sav->key_enc->key_data;
222 crie.cri_klen = _KEYBITS(sav->key_enc) - SAV_ISCTRORGCM(sav) * 32;
224 if (sav->tdb_authalgxform && sav->tdb_encalgxform) {
225 /* init both auth & enc */
226 crie.cri_next = &cria;
227 error = crypto_newsession(&sav->tdb_cryptoid,
228 &crie, V_crypto_support);
229 } else if (sav->tdb_encalgxform) {
230 error = crypto_newsession(&sav->tdb_cryptoid,
231 &crie, V_crypto_support);
232 } else if (sav->tdb_authalgxform) {
233 error = crypto_newsession(&sav->tdb_cryptoid,
234 &cria, V_crypto_support);
236 /* XXX cannot happen? */
237 DPRINTF(("%s: no encoding OR authentication xform!\n",
248 esp_zeroize(struct secasvar *sav)
250 /* NB: ah_zerorize free's the crypto session state */
251 int error = ah_zeroize(sav);
254 bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
255 sav->tdb_encalgxform = NULL;
256 sav->tdb_xform = NULL;
261 * ESP input processing, called (eventually) through the protocol switch.
264 esp_input(struct mbuf *m, struct secasvar *sav, int skip, int protoff)
266 IPSEC_DEBUG_DECLARE(char buf[128]);
267 const struct auth_hash *esph;
268 const struct enc_xform *espx;
269 struct xform_data *xd;
270 struct cryptodesc *crde;
274 crypto_session_t cryptoid;
275 int alen, error, hlen, plen;
277 IPSEC_ASSERT(sav != NULL, ("null SA"));
278 IPSEC_ASSERT(sav->tdb_encalgxform != NULL, ("null encoding xform"));
281 /* Valid IP Packet length ? */
282 if ( (skip&3) || (m->m_pkthdr.len&3) ){
283 DPRINTF(("%s: misaligned packet, skip %u pkt len %u",
284 __func__, skip, m->m_pkthdr.len));
285 ESPSTAT_INC(esps_badilen);
288 /* XXX don't pullup, just copy header */
289 IP6_EXTHDR_GET(esp, struct newesp *, m, skip, sizeof (struct newesp));
291 esph = sav->tdb_authalgxform;
292 espx = sav->tdb_encalgxform;
294 /* Determine the ESP header and auth length */
295 if (sav->flags & SADB_X_EXT_OLD)
296 hlen = sizeof (struct esp) + sav->ivlen;
298 hlen = sizeof (struct newesp) + sav->ivlen;
300 alen = xform_ah_authsize(esph);
303 * Verify payload length is multiple of encryption algorithm
306 * NB: This works for the null algorithm because the blocksize
307 * is 4 and all packets must be 4-byte aligned regardless
310 plen = m->m_pkthdr.len - (skip + hlen + alen);
311 if ((plen & (espx->blocksize - 1)) || (plen <= 0)) {
312 DPRINTF(("%s: payload of %d octets not a multiple of %d octets,"
313 " SA %s/%08lx\n", __func__, plen, espx->blocksize,
314 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
315 (u_long)ntohl(sav->spi)));
316 ESPSTAT_INC(esps_badilen);
321 * Check sequence number.
324 if (esph != NULL && sav->replay != NULL && sav->replay->wsize != 0) {
325 if (ipsec_chkreplay(ntohl(esp->esp_seq), sav) == 0) {
326 SECASVAR_UNLOCK(sav);
327 DPRINTF(("%s: packet replay check for %s\n", __func__,
328 ipsec_sa2str(sav, buf, sizeof(buf))));
329 ESPSTAT_INC(esps_replay);
334 cryptoid = sav->tdb_cryptoid;
335 SECASVAR_UNLOCK(sav);
337 /* Update the counters */
338 ESPSTAT_ADD(esps_ibytes, m->m_pkthdr.len - (skip + hlen + alen));
340 /* Get crypto descriptors */
341 crp = crypto_getreq(esph && espx ? 2 : 1);
343 DPRINTF(("%s: failed to acquire crypto descriptors\n",
345 ESPSTAT_INC(esps_crypto);
350 /* Get IPsec-specific opaque pointer */
351 xd = malloc(sizeof(*xd) + alen, M_XDATA, M_NOWAIT | M_ZERO);
353 DPRINTF(("%s: failed to allocate xform_data\n", __func__));
354 ESPSTAT_INC(esps_crypto);
361 struct cryptodesc *crda = crp->crp_desc;
363 IPSEC_ASSERT(crda != NULL, ("null ah crypto descriptor"));
365 /* Authentication descriptor */
366 crda->crd_skip = skip;
368 crda->crd_len = 8; /* RFC4106 5, SPI + SN */
370 crda->crd_len = m->m_pkthdr.len - (skip + alen);
371 crda->crd_inject = m->m_pkthdr.len - alen;
373 crda->crd_alg = esph->type;
375 /* Copy the authenticator */
376 m_copydata(m, m->m_pkthdr.len - alen, alen,
379 /* Chain authentication request */
380 crde = crda->crd_next;
382 crde = crp->crp_desc;
385 /* Crypto operation descriptor */
386 crp->crp_ilen = m->m_pkthdr.len; /* Total input length */
387 crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
389 crp->crp_flags |= CRYPTO_F_ASYNC | CRYPTO_F_ASYNC_KEEPORDER;
390 crp->crp_buf = (caddr_t) m;
391 crp->crp_callback = esp_input_cb;
392 crp->crp_session = cryptoid;
393 crp->crp_opaque = (caddr_t) xd;
395 /* These are passed as-is to the callback */
397 xd->protoff = protoff;
399 xd->cryptoid = cryptoid;
402 /* Decryption descriptor */
403 IPSEC_ASSERT(crde != NULL, ("null esp crypto descriptor"));
404 crde->crd_skip = skip + hlen;
405 crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
406 crde->crd_inject = skip + hlen - sav->ivlen;
408 if (SAV_ISCTRORGCM(sav)) {
409 ivp = &crde->crd_iv[0];
411 /* GCM IV Format: RFC4106 4 */
412 /* CTR IV Format: RFC3686 4 */
413 /* Salt is last four bytes of key, RFC4106 8.1 */
414 /* Nonce is last four bytes of key, RFC3686 5.1 */
415 memcpy(ivp, sav->key_enc->key_data +
416 _KEYLEN(sav->key_enc) - 4, 4);
418 if (SAV_ISCTR(sav)) {
419 /* Initial block counter is 1, RFC3686 4 */
420 be32enc(&ivp[sav->ivlen + 4], 1);
423 m_copydata(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
424 crde->crd_flags |= CRD_F_IV_EXPLICIT;
427 crde->crd_alg = espx->type;
429 return (crypto_dispatch(crp));
437 * ESP input callback from the crypto driver.
440 esp_input_cb(struct cryptop *crp)
442 IPSEC_DEBUG_DECLARE(char buf[128]);
443 u_int8_t lastthree[3], aalg[AH_HMAC_MAXHASHLEN];
444 const struct auth_hash *esph;
446 struct cryptodesc *crd;
447 struct xform_data *xd;
448 struct secasvar *sav;
449 struct secasindex *saidx;
451 crypto_session_t cryptoid;
452 int hlen, skip, protoff, error, alen;
455 IPSEC_ASSERT(crd != NULL, ("null crypto descriptor!"));
457 m = (struct mbuf *) crp->crp_buf;
458 xd = (struct xform_data *) crp->crp_opaque;
459 CURVNET_SET(xd->vnet);
462 protoff = xd->protoff;
463 cryptoid = xd->cryptoid;
464 saidx = &sav->sah->saidx;
465 esph = sav->tdb_authalgxform;
467 /* Check for crypto errors */
468 if (crp->crp_etype) {
469 if (crp->crp_etype == EAGAIN) {
470 /* Reset the session ID */
471 if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
472 crypto_freesession(cryptoid);
473 xd->cryptoid = crp->crp_session;
475 return (crypto_dispatch(crp));
477 ESPSTAT_INC(esps_noxform);
478 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
479 error = crp->crp_etype;
483 /* Shouldn't happen... */
485 ESPSTAT_INC(esps_crypto);
486 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
490 ESPSTAT_INC(esps_hist[sav->alg_enc]);
492 /* If authentication was performed, check now. */
494 alen = xform_ah_authsize(esph);
495 AHSTAT_INC(ahs_hist[sav->alg_auth]);
496 /* Copy the authenticator from the packet */
497 m_copydata(m, m->m_pkthdr.len - alen, alen, aalg);
498 ptr = (caddr_t) (xd + 1);
500 /* Verify authenticator */
501 if (timingsafe_bcmp(ptr, aalg, alen) != 0) {
502 DPRINTF(("%s: authentication hash mismatch for "
503 "packet in SA %s/%08lx\n", __func__,
504 ipsec_address(&saidx->dst, buf, sizeof(buf)),
505 (u_long) ntohl(sav->spi)));
506 ESPSTAT_INC(esps_badauth);
510 m->m_flags |= M_AUTHIPDGM;
511 /* Remove trailing authenticator */
515 /* Release the crypto descriptors */
516 free(xd, M_XDATA), xd = NULL;
517 crypto_freereq(crp), crp = NULL;
520 * Packet is now decrypted.
522 m->m_flags |= M_DECRYPTED;
525 * Update replay sequence number, if appropriate.
530 m_copydata(m, skip + offsetof(struct newesp, esp_seq),
531 sizeof (seq), (caddr_t) &seq);
533 if (ipsec_updatereplay(ntohl(seq), sav)) {
534 SECASVAR_UNLOCK(sav);
535 DPRINTF(("%s: packet replay check for %s\n", __func__,
536 ipsec_sa2str(sav, buf, sizeof(buf))));
537 ESPSTAT_INC(esps_replay);
541 SECASVAR_UNLOCK(sav);
544 /* Determine the ESP header length */
545 if (sav->flags & SADB_X_EXT_OLD)
546 hlen = sizeof (struct esp) + sav->ivlen;
548 hlen = sizeof (struct newesp) + sav->ivlen;
550 /* Remove the ESP header and IV from the mbuf. */
551 error = m_striphdr(m, skip, hlen);
553 ESPSTAT_INC(esps_hdrops);
554 DPRINTF(("%s: bad mbuf chain, SA %s/%08lx\n", __func__,
555 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
556 (u_long) ntohl(sav->spi)));
560 /* Save the last three bytes of decrypted data */
561 m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
563 /* Verify pad length */
564 if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
565 ESPSTAT_INC(esps_badilen);
566 DPRINTF(("%s: invalid padding length %d for %u byte packet "
567 "in SA %s/%08lx\n", __func__, lastthree[1],
568 m->m_pkthdr.len - skip,
569 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
570 (u_long) ntohl(sav->spi)));
575 /* Verify correct decryption by checking the last padding bytes */
576 if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
577 if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
578 ESPSTAT_INC(esps_badenc);
579 DPRINTF(("%s: decryption failed for packet in "
580 "SA %s/%08lx\n", __func__, ipsec_address(
581 &sav->sah->saidx.dst, buf, sizeof(buf)),
582 (u_long) ntohl(sav->spi)));
588 /* Trim the mbuf chain to remove trailing authenticator and padding */
589 m_adj(m, -(lastthree[1] + 2));
591 /* Restore the Next Protocol field */
592 m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
594 switch (saidx->dst.sa.sa_family) {
597 error = ipsec6_common_input_cb(m, sav, skip, protoff);
602 error = ipsec4_common_input_cb(m, sav, skip, protoff);
606 panic("%s: Unexpected address family: %d saidx=%p", __func__,
607 saidx->dst.sa.sa_family, saidx);
624 * ESP output routine, called by ipsec[46]_perform_request().
627 esp_output(struct mbuf *m, struct secpolicy *sp, struct secasvar *sav,
628 u_int idx, int skip, int protoff)
630 IPSEC_DEBUG_DECLARE(char buf[IPSEC_ADDRSTRLEN]);
631 struct cryptodesc *crde = NULL, *crda = NULL;
633 const struct auth_hash *esph;
634 const struct enc_xform *espx;
635 struct mbuf *mo = NULL;
636 struct xform_data *xd;
637 struct secasindex *saidx;
641 crypto_session_t cryptoid;
642 int hlen, rlen, padding, blks, alen, i, roff;
643 int error, maxpacketsize;
646 IPSEC_ASSERT(sav != NULL, ("null SA"));
647 esph = sav->tdb_authalgxform;
648 espx = sav->tdb_encalgxform;
649 IPSEC_ASSERT(espx != NULL, ("null encoding xform"));
651 if (sav->flags & SADB_X_EXT_OLD)
652 hlen = sizeof (struct esp) + sav->ivlen;
654 hlen = sizeof (struct newesp) + sav->ivlen;
656 rlen = m->m_pkthdr.len - skip; /* Raw payload length. */
658 * RFC4303 2.4 Requires 4 byte alignment.
660 blks = MAX(4, espx->blocksize); /* Cipher blocksize */
662 /* XXX clamp padding length a la KAME??? */
663 padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
665 alen = xform_ah_authsize(esph);
667 ESPSTAT_INC(esps_output);
669 saidx = &sav->sah->saidx;
670 /* Check for maximum packet size violations. */
671 switch (saidx->dst.sa.sa_family) {
674 maxpacketsize = IP_MAXPACKET;
679 maxpacketsize = IPV6_MAXPACKET;
683 DPRINTF(("%s: unknown/unsupported protocol "
684 "family %d, SA %s/%08lx\n", __func__,
685 saidx->dst.sa.sa_family, ipsec_address(&saidx->dst,
686 buf, sizeof(buf)), (u_long) ntohl(sav->spi)));
687 ESPSTAT_INC(esps_nopf);
688 error = EPFNOSUPPORT;
692 DPRINTF(("%s: skip %d hlen %d rlen %d padding %d alen %d blksd %d\n",
693 __func__, skip, hlen, rlen, padding, alen, blks)); */
694 if (skip + hlen + rlen + padding + alen > maxpacketsize) {
695 DPRINTF(("%s: packet in SA %s/%08lx got too big "
696 "(len %u, max len %u)\n", __func__,
697 ipsec_address(&saidx->dst, buf, sizeof(buf)),
698 (u_long) ntohl(sav->spi),
699 skip + hlen + rlen + padding + alen, maxpacketsize));
700 ESPSTAT_INC(esps_toobig);
705 /* Update the counters. */
706 ESPSTAT_ADD(esps_obytes, m->m_pkthdr.len - skip);
708 m = m_unshare(m, M_NOWAIT);
710 DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
711 ipsec_address(&saidx->dst, buf, sizeof(buf)),
712 (u_long) ntohl(sav->spi)));
713 ESPSTAT_INC(esps_hdrops);
718 /* Inject ESP header. */
719 mo = m_makespace(m, skip, hlen, &roff);
721 DPRINTF(("%s: %u byte ESP hdr inject failed for SA %s/%08lx\n",
722 __func__, hlen, ipsec_address(&saidx->dst, buf,
723 sizeof(buf)), (u_long) ntohl(sav->spi)));
724 ESPSTAT_INC(esps_hdrops); /* XXX diffs from openbsd */
729 /* Initialize ESP header. */
730 bcopy((caddr_t) &sav->spi, mtod(mo, caddr_t) + roff,
737 /* Emulate replay attack when ipsec_replay is TRUE. */
740 sav->replay->count++;
741 replay = htonl(sav->replay->count);
743 bcopy((caddr_t) &replay, mtod(mo, caddr_t) + roff +
744 sizeof(uint32_t), sizeof(uint32_t));
746 cryptoid = sav->tdb_cryptoid;
747 if (SAV_ISCTRORGCM(sav))
749 SECASVAR_UNLOCK(sav);
752 * Add padding -- better to do it ourselves than use the crypto engine,
753 * although if/when we support compression, we'd have to do that.
755 pad = (u_char *) m_pad(m, padding + alen);
757 DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
758 ipsec_address(&saidx->dst, buf, sizeof(buf)),
759 (u_long) ntohl(sav->spi)));
760 m = NULL; /* NB: free'd by m_pad */
766 * Add padding: random, zero, or self-describing.
767 * XXX catch unexpected setting
769 switch (sav->flags & SADB_X_EXT_PMASK) {
770 case SADB_X_EXT_PRAND:
771 (void) read_random(pad, padding - 2);
773 case SADB_X_EXT_PZERO:
774 bzero(pad, padding - 2);
776 case SADB_X_EXT_PSEQ:
777 for (i = 0; i < padding - 2; i++)
782 /* Fix padding length and Next Protocol in padding itself. */
783 pad[padding - 2] = padding - 2;
784 m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
786 /* Fix Next Protocol in IPv4/IPv6 header. */
788 m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
790 /* Get crypto descriptors. */
791 crp = crypto_getreq(esph != NULL ? 2 : 1);
793 DPRINTF(("%s: failed to acquire crypto descriptors\n",
795 ESPSTAT_INC(esps_crypto);
800 /* IPsec-specific opaque crypto info. */
801 xd = malloc(sizeof(struct xform_data), M_XDATA, M_NOWAIT | M_ZERO);
804 DPRINTF(("%s: failed to allocate xform_data\n", __func__));
805 ESPSTAT_INC(esps_crypto);
810 crde = crp->crp_desc;
811 crda = crde->crd_next;
813 /* Encryption descriptor. */
814 crde->crd_skip = skip + hlen;
815 crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
816 crde->crd_flags = CRD_F_ENCRYPT;
817 crde->crd_inject = skip + hlen - sav->ivlen;
819 /* Encryption operation. */
820 crde->crd_alg = espx->type;
821 if (SAV_ISCTRORGCM(sav)) {
822 ivp = &crde->crd_iv[0];
824 /* GCM IV Format: RFC4106 4 */
825 /* CTR IV Format: RFC3686 4 */
826 /* Salt is last four bytes of key, RFC4106 8.1 */
827 /* Nonce is last four bytes of key, RFC3686 5.1 */
828 memcpy(ivp, sav->key_enc->key_data +
829 _KEYLEN(sav->key_enc) - 4, 4);
830 be64enc(&ivp[4], cntr);
831 if (SAV_ISCTR(sav)) {
832 /* Initial block counter is 1, RFC3686 4 */
833 /* XXXAE: should we use this only for first packet? */
834 be32enc(&ivp[sav->ivlen + 4], 1);
837 m_copyback(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
838 crde->crd_flags |= CRD_F_IV_EXPLICIT|CRD_F_IV_PRESENT;
841 /* Callback parameters */
845 xd->cryptoid = cryptoid;
848 /* Crypto operation descriptor. */
849 crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
850 crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
852 crp->crp_flags |= CRYPTO_F_ASYNC | CRYPTO_F_ASYNC_KEEPORDER;
853 crp->crp_buf = (caddr_t) m;
854 crp->crp_callback = esp_output_cb;
855 crp->crp_opaque = (caddr_t) xd;
856 crp->crp_session = cryptoid;
859 /* Authentication descriptor. */
860 crda->crd_alg = esph->type;
861 crda->crd_skip = skip;
863 crda->crd_len = 8; /* RFC4106 5, SPI + SN */
865 crda->crd_len = m->m_pkthdr.len - (skip + alen);
866 crda->crd_inject = m->m_pkthdr.len - alen;
869 return crypto_dispatch(crp);
878 * ESP output callback from the crypto driver.
881 esp_output_cb(struct cryptop *crp)
883 struct xform_data *xd;
884 struct secpolicy *sp;
885 struct secasvar *sav;
887 crypto_session_t cryptoid;
891 xd = (struct xform_data *) crp->crp_opaque;
892 CURVNET_SET(xd->vnet);
893 m = (struct mbuf *) crp->crp_buf;
897 cryptoid = xd->cryptoid;
899 /* Check for crypto errors. */
900 if (crp->crp_etype) {
901 if (crp->crp_etype == EAGAIN) {
902 /* Reset the session ID */
903 if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
904 crypto_freesession(cryptoid);
905 xd->cryptoid = crp->crp_session;
907 return (crypto_dispatch(crp));
909 ESPSTAT_INC(esps_noxform);
910 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
911 error = crp->crp_etype;
916 /* Shouldn't happen... */
918 ESPSTAT_INC(esps_crypto);
919 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
925 ESPSTAT_INC(esps_hist[sav->alg_enc]);
926 if (sav->tdb_authalgxform != NULL)
927 AHSTAT_INC(ahs_hist[sav->alg_auth]);
930 /* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
931 if (V_ipsec_integrity) {
932 static unsigned char ipseczeroes[AH_HMAC_MAXHASHLEN];
933 const struct auth_hash *esph;
936 * Corrupt HMAC if we want to test integrity verification of
939 esph = sav->tdb_authalgxform;
943 alen = xform_ah_authsize(esph);
944 m_copyback(m, m->m_pkthdr.len - alen,
950 /* NB: m is reclaimed by ipsec_process_done. */
951 error = ipsec_process_done(m, sp, sav, idx);
963 static struct xformsw esp_xformsw = {
965 .xf_name = "IPsec ESP",
967 .xf_zeroize = esp_zeroize,
968 .xf_input = esp_input,
969 .xf_output = esp_output,
972 SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
973 xform_attach, &esp_xformsw);
974 SYSUNINIT(esp_xform_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
975 xform_detach, &esp_xformsw);