The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/netipsec/xform_esp.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

    1 /*      $FreeBSD: releng/11.2/sys/netipsec/xform_esp.c 331693 2018-03-28 17:49:31Z jhb $        */
    2 /*      $OpenBSD: ip_esp.c,v 1.69 2001/06/26 06:18:59 angelos Exp $ */
    3 /*-
    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).
    7  *
    8  * The original version of this code was written by John Ioannidis
    9  * for BSD/OS in Athens, Greece, in November 1995.
   10  *
   11  * Ported to OpenBSD and NetBSD, with additional transforms, in December 1996,
   12  * by Angelos D. Keromytis.
   13  *
   14  * Additional transforms and features in 1997 and 1998 by Angelos D. Keromytis
   15  * and Niels Provos.
   16  *
   17  * Additional features in 1999 by Angelos D. Keromytis.
   18  *
   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.
   22  *
   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
   30  * all.
   31  *
   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
   36  * PURPOSE.
   37  */
   38 #include "opt_inet.h"
   39 #include "opt_inet6.h"
   40 
   41 #include <sys/param.h>
   42 #include <sys/systm.h>
   43 #include <sys/mbuf.h>
   44 #include <sys/socket.h>
   45 #include <sys/syslog.h>
   46 #include <sys/kernel.h>
   47 #include <sys/lock.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>
   53 
   54 #include <net/if.h>
   55 #include <net/vnet.h>
   56 
   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>
   62 
   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>
   69 
   70 #ifdef INET6
   71 #include <netinet6/ip6_var.h>
   72 #include <netipsec/ipsec6.h>
   73 #include <netinet6/ip6_ecn.h>
   74 #endif
   75 
   76 #include <netipsec/key.h>
   77 #include <netipsec/key_debug.h>
   78 
   79 #include <opencrypto/cryptodev.h>
   80 #include <opencrypto/xform.h>
   81 
   82 VNET_DEFINE(int, esp_enable) = 1;
   83 VNET_PCPUSTAT_DEFINE(struct espstat, espstat);
   84 VNET_PCPUSTAT_SYSINIT(espstat);
   85 
   86 #ifdef VIMAGE
   87 VNET_PCPUSTAT_SYSUNINIT(espstat);
   88 #endif /* VIMAGE */
   89 
   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");
   96 
   97 static int esp_input_cb(struct cryptop *op);
   98 static int esp_output_cb(struct cryptop *crp);
   99 
  100 size_t
  101 esp_hdrsiz(struct secasvar *sav)
  102 {
  103         size_t size;
  104 
  105         if (sav != NULL) {
  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);
  111                 else
  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);
  117         } else {
  118                 /*
  119                  *   base header size
  120                  * + max iv length for CBC mode
  121                  * + max pad length
  122                  * + sizeof (pad length field)
  123                  * + sizeof (next header field)
  124                  * + max icv supported.
  125                  */
  126                 size = sizeof (struct newesp) + EALG_MAX_BLOCK_LEN + 9 + 16;
  127         }
  128         return size;
  129 }
  130 
  131 /*
  132  * esp_init() is called when an SPI is being set up.
  133  */
  134 static int
  135 esp_init(struct secasvar *sav, struct xformsw *xsp)
  136 {
  137         const struct enc_xform *txform;
  138         struct cryptoini cria, crie;
  139         int keylen;
  140         int error;
  141 
  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));
  146                 return EINVAL;
  147         }
  148         if (sav->key_enc == NULL) {
  149                 DPRINTF(("%s: no encoding key for %s algorithm\n",
  150                          __func__, txform->name));
  151                 return EINVAL;
  152         }
  153         if ((sav->flags & (SADB_X_EXT_OLD | SADB_X_EXT_IV4B)) ==
  154             SADB_X_EXT_IV4B) {
  155                 DPRINTF(("%s: 4-byte IV not supported with protocol\n",
  156                         __func__));
  157                 return EINVAL;
  158         }
  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,
  165                         txform->name));
  166                 return EINVAL;
  167         }
  168 
  169         if (SAV_ISCTRORGCM(sav))
  170                 sav->ivlen = 8; /* RFC4106 3.1 and RFC3686 3.1 */
  171         else
  172                 sav->ivlen = txform->ivsize;
  173 
  174         /*
  175          * Setup AH-related state.
  176          */
  177         if (sav->alg_auth != 0) {
  178                 error = ah_init0(sav, xsp, &cria);
  179                 if (error)
  180                         return error;
  181         }
  182 
  183         /* NB: override anything set in ah_init0 */
  184         sav->tdb_xform = xsp;
  185         sav->tdb_encalgxform = txform;
  186 
  187         /*
  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.
  191          */
  192         if (sav->alg_enc == SADB_X_EALG_AESGCM16) {
  193                 switch (keylen) {
  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;
  197                         break;
  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;
  201                         break;
  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;
  205                         break;
  206                 default:
  207                         DPRINTF(("%s: invalid key length %u"
  208                                  "for algorithm %s\n", __func__,
  209                                  keylen, txform->name));
  210                         return EINVAL;
  211                 }
  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;
  216         }
  217 
  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;
  223 
  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);
  235         } else {
  236                 /* XXX cannot happen? */
  237                 DPRINTF(("%s: no encoding OR authentication xform!\n",
  238                         __func__));
  239                 error = EINVAL;
  240         }
  241         return error;
  242 }
  243 
  244 /*
  245  * Paranoia.
  246  */
  247 static int
  248 esp_zeroize(struct secasvar *sav)
  249 {
  250         /* NB: ah_zerorize free's the crypto session state */
  251         int error = ah_zeroize(sav);
  252 
  253         if (sav->key_enc)
  254                 bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
  255         sav->tdb_encalgxform = NULL;
  256         sav->tdb_xform = NULL;
  257         return error;
  258 }
  259 
  260 /*
  261  * ESP input processing, called (eventually) through the protocol switch.
  262  */
  263 static int
  264 esp_input(struct mbuf *m, struct secasvar *sav, int skip, int protoff)
  265 {
  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;
  271         struct cryptop *crp;
  272         struct newesp *esp;
  273         uint8_t *ivp;
  274         uint64_t cryptoid;
  275         int alen, error, hlen, plen;
  276 
  277         IPSEC_ASSERT(sav != NULL, ("null SA"));
  278         IPSEC_ASSERT(sav->tdb_encalgxform != NULL, ("null encoding xform"));
  279 
  280         error = EINVAL;
  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);
  286                 goto bad;
  287         }
  288         /* XXX don't pullup, just copy header */
  289         IP6_EXTHDR_GET(esp, struct newesp *, m, skip, sizeof (struct newesp));
  290 
  291         esph = sav->tdb_authalgxform;
  292         espx = sav->tdb_encalgxform;
  293 
  294         /* Determine the ESP header and auth length */
  295         if (sav->flags & SADB_X_EXT_OLD)
  296                 hlen = sizeof (struct esp) + sav->ivlen;
  297         else
  298                 hlen = sizeof (struct newesp) + sav->ivlen;
  299 
  300         alen = xform_ah_authsize(esph);
  301 
  302         /*
  303          * Verify payload length is multiple of encryption algorithm
  304          * block size.
  305          *
  306          * NB: This works for the null algorithm because the blocksize
  307          *     is 4 and all packets must be 4-byte aligned regardless
  308          *     of the algorithm.
  309          */
  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);
  317                 goto bad;
  318         }
  319 
  320         /*
  321          * Check sequence number.
  322          */
  323         SECASVAR_LOCK(sav);
  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);
  330                         error = EACCES;
  331                         goto bad;
  332                 }
  333         }
  334         cryptoid = sav->tdb_cryptoid;
  335         SECASVAR_UNLOCK(sav);
  336 
  337         /* Update the counters */
  338         ESPSTAT_ADD(esps_ibytes, m->m_pkthdr.len - (skip + hlen + alen));
  339 
  340         /* Get crypto descriptors */
  341         crp = crypto_getreq(esph && espx ? 2 : 1);
  342         if (crp == NULL) {
  343                 DPRINTF(("%s: failed to acquire crypto descriptors\n",
  344                         __func__));
  345                 ESPSTAT_INC(esps_crypto);
  346                 error = ENOBUFS;
  347                 goto bad;
  348         }
  349 
  350         /* Get IPsec-specific opaque pointer */
  351         xd = malloc(sizeof(*xd) + alen, M_XDATA, M_NOWAIT | M_ZERO);
  352         if (xd == NULL) {
  353                 DPRINTF(("%s: failed to allocate xform_data\n", __func__));
  354                 ESPSTAT_INC(esps_crypto);
  355                 crypto_freereq(crp);
  356                 error = ENOBUFS;
  357                 goto bad;
  358         }
  359 
  360         if (esph != NULL) {
  361                 struct cryptodesc *crda = crp->crp_desc;
  362 
  363                 IPSEC_ASSERT(crda != NULL, ("null ah crypto descriptor"));
  364 
  365                 /* Authentication descriptor */
  366                 crda->crd_skip = skip;
  367                 if (SAV_ISGCM(sav))
  368                         crda->crd_len = 8;      /* RFC4106 5, SPI + SN */
  369                 else
  370                         crda->crd_len = m->m_pkthdr.len - (skip + alen);
  371                 crda->crd_inject = m->m_pkthdr.len - alen;
  372 
  373                 crda->crd_alg = esph->type;
  374 
  375                 /* Copy the authenticator */
  376                 m_copydata(m, m->m_pkthdr.len - alen, alen,
  377                     (caddr_t) (xd + 1));
  378 
  379                 /* Chain authentication request */
  380                 crde = crda->crd_next;
  381         } else {
  382                 crde = crp->crp_desc;
  383         }
  384 
  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;
  388         crp->crp_buf = (caddr_t) m;
  389         crp->crp_callback = esp_input_cb;
  390         crp->crp_sid = cryptoid;
  391         crp->crp_opaque = (caddr_t) xd;
  392 
  393         /* These are passed as-is to the callback */
  394         xd->sav = sav;
  395         xd->protoff = protoff;
  396         xd->skip = skip;
  397         xd->cryptoid = cryptoid;
  398         xd->vnet = curvnet;
  399 
  400         /* Decryption descriptor */
  401         IPSEC_ASSERT(crde != NULL, ("null esp crypto descriptor"));
  402         crde->crd_skip = skip + hlen;
  403         crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
  404         crde->crd_inject = skip + hlen - sav->ivlen;
  405 
  406         if (SAV_ISCTRORGCM(sav)) {
  407                 ivp = &crde->crd_iv[0];
  408 
  409                 /* GCM IV Format: RFC4106 4 */
  410                 /* CTR IV Format: RFC3686 4 */
  411                 /* Salt is last four bytes of key, RFC4106 8.1 */
  412                 /* Nonce is last four bytes of key, RFC3686 5.1 */
  413                 memcpy(ivp, sav->key_enc->key_data +
  414                     _KEYLEN(sav->key_enc) - 4, 4);
  415 
  416                 if (SAV_ISCTR(sav)) {
  417                         /* Initial block counter is 1, RFC3686 4 */
  418                         be32enc(&ivp[sav->ivlen + 4], 1);
  419                 }
  420 
  421                 m_copydata(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
  422                 crde->crd_flags |= CRD_F_IV_EXPLICIT;
  423         }
  424 
  425         crde->crd_alg = espx->type;
  426 
  427         return (crypto_dispatch(crp));
  428 bad:
  429         m_freem(m);
  430         key_freesav(&sav);
  431         return (error);
  432 }
  433 
  434 /*
  435  * ESP input callback from the crypto driver.
  436  */
  437 static int
  438 esp_input_cb(struct cryptop *crp)
  439 {
  440         IPSEC_DEBUG_DECLARE(char buf[128]);
  441         u_int8_t lastthree[3], aalg[AH_HMAC_MAXHASHLEN];
  442         const struct auth_hash *esph;
  443         const struct enc_xform *espx;
  444         struct mbuf *m;
  445         struct cryptodesc *crd;
  446         struct xform_data *xd;
  447         struct secasvar *sav;
  448         struct secasindex *saidx;
  449         caddr_t ptr;
  450         uint64_t cryptoid;
  451         int hlen, skip, protoff, error, alen;
  452 
  453         crd = crp->crp_desc;
  454         IPSEC_ASSERT(crd != NULL, ("null crypto descriptor!"));
  455 
  456         m = (struct mbuf *) crp->crp_buf;
  457         xd = (struct xform_data *) crp->crp_opaque;
  458         CURVNET_SET(xd->vnet);
  459         sav = xd->sav;
  460         skip = xd->skip;
  461         protoff = xd->protoff;
  462         cryptoid = xd->cryptoid;
  463         saidx = &sav->sah->saidx;
  464         esph = sav->tdb_authalgxform;
  465         espx = sav->tdb_encalgxform;
  466 
  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_sid, &cryptoid) != 0)
  472                                 crypto_freesession(cryptoid);
  473                         xd->cryptoid = crp->crp_sid;
  474                         CURVNET_RESTORE();
  475                         return (crypto_dispatch(crp));
  476                 }
  477                 ESPSTAT_INC(esps_noxform);
  478                 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
  479                 error = crp->crp_etype;
  480                 goto bad;
  481         }
  482 
  483         /* Shouldn't happen... */
  484         if (m == NULL) {
  485                 ESPSTAT_INC(esps_crypto);
  486                 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
  487                 error = EINVAL;
  488                 goto bad;
  489         }
  490         ESPSTAT_INC(esps_hist[sav->alg_enc]);
  491 
  492         /* If authentication was performed, check now. */
  493         if (esph != NULL) {
  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);
  499 
  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);
  507                         error = EACCES;
  508                         goto bad;
  509                 }
  510                 m->m_flags |= M_AUTHIPDGM;
  511                 /* Remove trailing authenticator */
  512                 m_adj(m, -alen);
  513         }
  514 
  515         /* Release the crypto descriptors */
  516         free(xd, M_XDATA), xd = NULL;
  517         crypto_freereq(crp), crp = NULL;
  518 
  519         /*
  520          * Packet is now decrypted.
  521          */
  522         m->m_flags |= M_DECRYPTED;
  523 
  524         /*
  525          * Update replay sequence number, if appropriate.
  526          */
  527         if (sav->replay) {
  528                 u_int32_t seq;
  529 
  530                 m_copydata(m, skip + offsetof(struct newesp, esp_seq),
  531                            sizeof (seq), (caddr_t) &seq);
  532                 SECASVAR_LOCK(sav);
  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);
  538                         error = EACCES;
  539                         goto bad;
  540                 }
  541                 SECASVAR_UNLOCK(sav);
  542         }
  543 
  544         /* Determine the ESP header length */
  545         if (sav->flags & SADB_X_EXT_OLD)
  546                 hlen = sizeof (struct esp) + sav->ivlen;
  547         else
  548                 hlen = sizeof (struct newesp) + sav->ivlen;
  549 
  550         /* Remove the ESP header and IV from the mbuf. */
  551         error = m_striphdr(m, skip, hlen);
  552         if (error) {
  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)));
  557                 goto bad;
  558         }
  559 
  560         /* Save the last three bytes of decrypted data */
  561         m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
  562 
  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)));
  571                 error = EINVAL;
  572                 goto bad;
  573         }
  574 
  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)));
  583                         error = EINVAL;
  584                         goto bad;
  585                 }
  586         }
  587 
  588         /* Trim the mbuf chain to remove trailing authenticator and padding */
  589         m_adj(m, -(lastthree[1] + 2));
  590 
  591         /* Restore the Next Protocol field */
  592         m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
  593 
  594         switch (saidx->dst.sa.sa_family) {
  595 #ifdef INET6
  596         case AF_INET6:
  597                 error = ipsec6_common_input_cb(m, sav, skip, protoff);
  598                 break;
  599 #endif
  600 #ifdef INET
  601         case AF_INET:
  602                 error = ipsec4_common_input_cb(m, sav, skip, protoff);
  603                 break;
  604 #endif
  605         default:
  606                 panic("%s: Unexpected address family: %d saidx=%p", __func__,
  607                     saidx->dst.sa.sa_family, saidx);
  608         }
  609         CURVNET_RESTORE();
  610         return error;
  611 bad:
  612         CURVNET_RESTORE();
  613         if (sav != NULL)
  614                 key_freesav(&sav);
  615         if (m != NULL)
  616                 m_freem(m);
  617         if (xd != NULL)
  618                 free(xd, M_XDATA);
  619         if (crp != NULL)
  620                 crypto_freereq(crp);
  621         return error;
  622 }
  623 /*
  624  * ESP output routine, called by ipsec[46]_perform_request().
  625  */
  626 static int
  627 esp_output(struct mbuf *m, struct secpolicy *sp, struct secasvar *sav,
  628     u_int idx, int skip, int protoff)
  629 {
  630         IPSEC_DEBUG_DECLARE(char buf[IPSEC_ADDRSTRLEN]);
  631         struct cryptodesc *crde = NULL, *crda = NULL;
  632         struct cryptop *crp;
  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;
  638         unsigned char *pad;
  639         uint8_t *ivp;
  640         uint64_t cntr, cryptoid;
  641         int hlen, rlen, padding, blks, alen, i, roff;
  642         int error, maxpacketsize;
  643         uint8_t prot;
  644 
  645         IPSEC_ASSERT(sav != NULL, ("null SA"));
  646         esph = sav->tdb_authalgxform;
  647         espx = sav->tdb_encalgxform;
  648         IPSEC_ASSERT(espx != NULL, ("null encoding xform"));
  649 
  650         if (sav->flags & SADB_X_EXT_OLD)
  651                 hlen = sizeof (struct esp) + sav->ivlen;
  652         else
  653                 hlen = sizeof (struct newesp) + sav->ivlen;
  654 
  655         rlen = m->m_pkthdr.len - skip;  /* Raw payload length. */
  656         /*
  657          * RFC4303 2.4 Requires 4 byte alignment.
  658          */
  659         blks = MAX(4, espx->blocksize);         /* Cipher blocksize */
  660 
  661         /* XXX clamp padding length a la KAME??? */
  662         padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
  663 
  664         alen = xform_ah_authsize(esph);
  665 
  666         ESPSTAT_INC(esps_output);
  667 
  668         saidx = &sav->sah->saidx;
  669         /* Check for maximum packet size violations. */
  670         switch (saidx->dst.sa.sa_family) {
  671 #ifdef INET
  672         case AF_INET:
  673                 maxpacketsize = IP_MAXPACKET;
  674                 break;
  675 #endif /* INET */
  676 #ifdef INET6
  677         case AF_INET6:
  678                 maxpacketsize = IPV6_MAXPACKET;
  679                 break;
  680 #endif /* INET6 */
  681         default:
  682                 DPRINTF(("%s: unknown/unsupported protocol "
  683                     "family %d, SA %s/%08lx\n", __func__,
  684                     saidx->dst.sa.sa_family, ipsec_address(&saidx->dst,
  685                         buf, sizeof(buf)), (u_long) ntohl(sav->spi)));
  686                 ESPSTAT_INC(esps_nopf);
  687                 error = EPFNOSUPPORT;
  688                 goto bad;
  689         }
  690         /*
  691         DPRINTF(("%s: skip %d hlen %d rlen %d padding %d alen %d blksd %d\n",
  692                 __func__, skip, hlen, rlen, padding, alen, blks)); */
  693         if (skip + hlen + rlen + padding + alen > maxpacketsize) {
  694                 DPRINTF(("%s: packet in SA %s/%08lx got too big "
  695                     "(len %u, max len %u)\n", __func__,
  696                     ipsec_address(&saidx->dst, buf, sizeof(buf)),
  697                     (u_long) ntohl(sav->spi),
  698                     skip + hlen + rlen + padding + alen, maxpacketsize));
  699                 ESPSTAT_INC(esps_toobig);
  700                 error = EMSGSIZE;
  701                 goto bad;
  702         }
  703 
  704         /* Update the counters. */
  705         ESPSTAT_ADD(esps_obytes, m->m_pkthdr.len - skip);
  706 
  707         m = m_unshare(m, M_NOWAIT);
  708         if (m == NULL) {
  709                 DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
  710                     ipsec_address(&saidx->dst, buf, sizeof(buf)),
  711                     (u_long) ntohl(sav->spi)));
  712                 ESPSTAT_INC(esps_hdrops);
  713                 error = ENOBUFS;
  714                 goto bad;
  715         }
  716 
  717         /* Inject ESP header. */
  718         mo = m_makespace(m, skip, hlen, &roff);
  719         if (mo == NULL) {
  720                 DPRINTF(("%s: %u byte ESP hdr inject failed for SA %s/%08lx\n",
  721                     __func__, hlen, ipsec_address(&saidx->dst, buf,
  722                     sizeof(buf)), (u_long) ntohl(sav->spi)));
  723                 ESPSTAT_INC(esps_hdrops);       /* XXX diffs from openbsd */
  724                 error = ENOBUFS;
  725                 goto bad;
  726         }
  727 
  728         /* Initialize ESP header. */
  729         bcopy((caddr_t) &sav->spi, mtod(mo, caddr_t) + roff,
  730             sizeof(uint32_t));
  731         SECASVAR_LOCK(sav);
  732         if (sav->replay) {
  733                 uint32_t replay;
  734 
  735 #ifdef REGRESSION
  736                 /* Emulate replay attack when ipsec_replay is TRUE. */
  737                 if (!V_ipsec_replay)
  738 #endif
  739                         sav->replay->count++;
  740                 replay = htonl(sav->replay->count);
  741 
  742                 bcopy((caddr_t) &replay, mtod(mo, caddr_t) + roff +
  743                     sizeof(uint32_t), sizeof(uint32_t));
  744         }
  745         cryptoid = sav->tdb_cryptoid;
  746         if (SAV_ISCTRORGCM(sav))
  747                 cntr = sav->cntr++;
  748         SECASVAR_UNLOCK(sav);
  749 
  750         /*
  751          * Add padding -- better to do it ourselves than use the crypto engine,
  752          * although if/when we support compression, we'd have to do that.
  753          */
  754         pad = (u_char *) m_pad(m, padding + alen);
  755         if (pad == NULL) {
  756                 DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
  757                     ipsec_address(&saidx->dst, buf, sizeof(buf)),
  758                     (u_long) ntohl(sav->spi)));
  759                 m = NULL;               /* NB: free'd by m_pad */
  760                 error = ENOBUFS;
  761                 goto bad;
  762         }
  763 
  764         /*
  765          * Add padding: random, zero, or self-describing.
  766          * XXX catch unexpected setting
  767          */
  768         switch (sav->flags & SADB_X_EXT_PMASK) {
  769         case SADB_X_EXT_PRAND:
  770                 (void) read_random(pad, padding - 2);
  771                 break;
  772         case SADB_X_EXT_PZERO:
  773                 bzero(pad, padding - 2);
  774                 break;
  775         case SADB_X_EXT_PSEQ:
  776                 for (i = 0; i < padding - 2; i++)
  777                         pad[i] = i+1;
  778                 break;
  779         }
  780 
  781         /* Fix padding length and Next Protocol in padding itself. */
  782         pad[padding - 2] = padding - 2;
  783         m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
  784 
  785         /* Fix Next Protocol in IPv4/IPv6 header. */
  786         prot = IPPROTO_ESP;
  787         m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
  788 
  789         /* Get crypto descriptors. */
  790         crp = crypto_getreq(esph != NULL ? 2 : 1);
  791         if (crp == NULL) {
  792                 DPRINTF(("%s: failed to acquire crypto descriptors\n",
  793                         __func__));
  794                 ESPSTAT_INC(esps_crypto);
  795                 error = ENOBUFS;
  796                 goto bad;
  797         }
  798 
  799         /* IPsec-specific opaque crypto info. */
  800         xd =  malloc(sizeof(struct xform_data), M_XDATA, M_NOWAIT | M_ZERO);
  801         if (xd == NULL) {
  802                 crypto_freereq(crp);
  803                 DPRINTF(("%s: failed to allocate xform_data\n", __func__));
  804                 ESPSTAT_INC(esps_crypto);
  805                 error = ENOBUFS;
  806                 goto bad;
  807         }
  808 
  809         crde = crp->crp_desc;
  810         crda = crde->crd_next;
  811 
  812         /* Encryption descriptor. */
  813         crde->crd_skip = skip + hlen;
  814         crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
  815         crde->crd_flags = CRD_F_ENCRYPT;
  816         crde->crd_inject = skip + hlen - sav->ivlen;
  817 
  818         /* Encryption operation. */
  819         crde->crd_alg = espx->type;
  820         if (SAV_ISCTRORGCM(sav)) {
  821                 ivp = &crde->crd_iv[0];
  822 
  823                 /* GCM IV Format: RFC4106 4 */
  824                 /* CTR IV Format: RFC3686 4 */
  825                 /* Salt is last four bytes of key, RFC4106 8.1 */
  826                 /* Nonce is last four bytes of key, RFC3686 5.1 */
  827                 memcpy(ivp, sav->key_enc->key_data +
  828                     _KEYLEN(sav->key_enc) - 4, 4);
  829                 be64enc(&ivp[4], cntr);
  830                 if (SAV_ISCTR(sav)) {
  831                         /* Initial block counter is 1, RFC3686 4 */
  832                         /* XXXAE: should we use this only for first packet? */
  833                         be32enc(&ivp[sav->ivlen + 4], 1);
  834                 }
  835 
  836                 m_copyback(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
  837                 crde->crd_flags |= CRD_F_IV_EXPLICIT|CRD_F_IV_PRESENT;
  838         }
  839 
  840         /* Callback parameters */
  841         xd->sp = sp;
  842         xd->sav = sav;
  843         xd->idx = idx;
  844         xd->cryptoid = cryptoid;
  845         xd->vnet = curvnet;
  846 
  847         /* Crypto operation descriptor. */
  848         crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
  849         crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
  850         crp->crp_buf = (caddr_t) m;
  851         crp->crp_callback = esp_output_cb;
  852         crp->crp_opaque = (caddr_t) xd;
  853         crp->crp_sid = cryptoid;
  854 
  855         if (esph) {
  856                 /* Authentication descriptor. */
  857                 crda->crd_alg = esph->type;
  858                 crda->crd_skip = skip;
  859                 if (SAV_ISGCM(sav))
  860                         crda->crd_len = 8;      /* RFC4106 5, SPI + SN */
  861                 else
  862                         crda->crd_len = m->m_pkthdr.len - (skip + alen);
  863                 crda->crd_inject = m->m_pkthdr.len - alen;
  864         }
  865 
  866         return crypto_dispatch(crp);
  867 bad:
  868         if (m)
  869                 m_freem(m);
  870         key_freesav(&sav);
  871         key_freesp(&sp);
  872         return (error);
  873 }
  874 /*
  875  * ESP output callback from the crypto driver.
  876  */
  877 static int
  878 esp_output_cb(struct cryptop *crp)
  879 {
  880         struct xform_data *xd;
  881         struct secpolicy *sp;
  882         struct secasvar *sav;
  883         struct mbuf *m;
  884         uint64_t cryptoid;
  885         u_int idx;
  886         int error;
  887 
  888         xd = (struct xform_data *) crp->crp_opaque;
  889         CURVNET_SET(xd->vnet);
  890         m = (struct mbuf *) crp->crp_buf;
  891         sp = xd->sp;
  892         sav = xd->sav;
  893         idx = xd->idx;
  894         cryptoid = xd->cryptoid;
  895 
  896         /* Check for crypto errors. */
  897         if (crp->crp_etype) {
  898                 if (crp->crp_etype == EAGAIN) {
  899                         /* Reset the session ID */
  900                         if (ipsec_updateid(sav, &crp->crp_sid, &cryptoid) != 0)
  901                                 crypto_freesession(cryptoid);
  902                         xd->cryptoid = crp->crp_sid;
  903                         CURVNET_RESTORE();
  904                         return (crypto_dispatch(crp));
  905                 }
  906                 ESPSTAT_INC(esps_noxform);
  907                 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
  908                 error = crp->crp_etype;
  909                 m_freem(m);
  910                 goto bad;
  911         }
  912 
  913         /* Shouldn't happen... */
  914         if (m == NULL) {
  915                 ESPSTAT_INC(esps_crypto);
  916                 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
  917                 error = EINVAL;
  918                 goto bad;
  919         }
  920         free(xd, M_XDATA);
  921         crypto_freereq(crp);
  922         ESPSTAT_INC(esps_hist[sav->alg_enc]);
  923         if (sav->tdb_authalgxform != NULL)
  924                 AHSTAT_INC(ahs_hist[sav->alg_auth]);
  925 
  926 #ifdef REGRESSION
  927         /* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
  928         if (V_ipsec_integrity) {
  929                 static unsigned char ipseczeroes[AH_HMAC_MAXHASHLEN];
  930                 const struct auth_hash *esph;
  931 
  932                 /*
  933                  * Corrupt HMAC if we want to test integrity verification of
  934                  * the other side.
  935                  */
  936                 esph = sav->tdb_authalgxform;
  937                 if (esph !=  NULL) {
  938                         int alen;
  939 
  940                         alen = xform_ah_authsize(esph);
  941                         m_copyback(m, m->m_pkthdr.len - alen,
  942                             alen, ipseczeroes);
  943                 }
  944         }
  945 #endif
  946 
  947         /* NB: m is reclaimed by ipsec_process_done. */
  948         error = ipsec_process_done(m, sp, sav, idx);
  949         CURVNET_RESTORE();
  950         return (error);
  951 bad:
  952         CURVNET_RESTORE();
  953         free(xd, M_XDATA);
  954         crypto_freereq(crp);
  955         key_freesav(&sav);
  956         key_freesp(&sp);
  957         return (error);
  958 }
  959 
  960 static struct xformsw esp_xformsw = {
  961         .xf_type =      XF_ESP,
  962         .xf_name =      "IPsec ESP",
  963         .xf_init =      esp_init,
  964         .xf_zeroize =   esp_zeroize,
  965         .xf_input =     esp_input,
  966         .xf_output =    esp_output,
  967 };
  968 
  969 SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
  970     xform_attach, &esp_xformsw);
  971 SYSUNINIT(esp_xform_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
  972     xform_detach, &esp_xformsw);

Cache object: fdc02507d57951e0d28299904a32cccf


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.