]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netipsec/xform_esp.c
Update to Zstandard 1.4.4
[FreeBSD/FreeBSD.git] / sys / netipsec / xform_esp.c
1 /*      $FreeBSD$       */
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 struct timeval deswarn, blfwarn, castwarn, camelliawarn;
98
99 static int esp_input_cb(struct cryptop *op);
100 static int esp_output_cb(struct cryptop *crp);
101
102 size_t
103 esp_hdrsiz(struct secasvar *sav)
104 {
105         size_t size;
106
107         if (sav != NULL) {
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);
113                 else
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);
119         } else {
120                 /*
121                  *   base header size
122                  * + max iv length for CBC mode
123                  * + max pad length
124                  * + sizeof (pad length field)
125                  * + sizeof (next header field)
126                  * + max icv supported.
127                  */
128                 size = sizeof (struct newesp) + EALG_MAX_BLOCK_LEN + 9 + 16;
129         }
130         return size;
131 }
132
133 /*
134  * esp_init() is called when an SPI is being set up.
135  */
136 static int
137 esp_init(struct secasvar *sav, struct xformsw *xsp)
138 {
139         const struct enc_xform *txform;
140         struct cryptoini cria, crie;
141         int keylen;
142         int error;
143
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));
148                 return EINVAL;
149         }
150         if (sav->key_enc == NULL) {
151                 DPRINTF(("%s: no encoding key for %s algorithm\n",
152                          __func__, txform->name));
153                 return EINVAL;
154         }
155         if ((sav->flags & (SADB_X_EXT_OLD | SADB_X_EXT_IV4B)) ==
156             SADB_X_EXT_IV4B) {
157                 DPRINTF(("%s: 4-byte IV not supported with protocol\n",
158                         __func__));
159                 return EINVAL;
160         }
161
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");
166                 break;
167         case SADB_X_EALG_BLOWFISHCBC:
168                 if (ratecheck(&blfwarn, &ipsec_warn_interval))
169                         gone_in(13, "Blowfish cipher for IPsec");
170                 break;
171         case SADB_X_EALG_CAST128CBC:
172                 if (ratecheck(&castwarn, &ipsec_warn_interval))
173                         gone_in(13, "CAST cipher for IPsec");
174                 break;
175         case SADB_X_EALG_CAMELLIACBC:
176                 if (ratecheck(&camelliawarn, &ipsec_warn_interval))
177                         gone_in(13, "Camellia cipher for IPsec");
178                 break;
179         }
180
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,
187                         txform->name));
188                 return EINVAL;
189         }
190
191         if (SAV_ISCTRORGCM(sav))
192                 sav->ivlen = 8; /* RFC4106 3.1 and RFC3686 3.1 */
193         else
194                 sav->ivlen = txform->ivsize;
195
196         /*
197          * Setup AH-related state.
198          */
199         if (sav->alg_auth != 0) {
200                 error = ah_init0(sav, xsp, &cria);
201                 if (error)
202                         return error;
203         }
204
205         /* NB: override anything set in ah_init0 */
206         sav->tdb_xform = xsp;
207         sav->tdb_encalgxform = txform;
208
209         /*
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.
213          */
214         if (sav->alg_enc == SADB_X_EALG_AESGCM16) {
215                 switch (keylen) {
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;
219                         break;
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;
223                         break;
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;
227                         break;
228                 default:
229                         DPRINTF(("%s: invalid key length %u"
230                                  "for algorithm %s\n", __func__,
231                                  keylen, txform->name));
232                         return EINVAL;
233                 }
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;
238         }
239
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;
245
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);
257         } else {
258                 /* XXX cannot happen? */
259                 DPRINTF(("%s: no encoding OR authentication xform!\n",
260                         __func__));
261                 error = EINVAL;
262         }
263         return error;
264 }
265
266 /*
267  * Paranoia.
268  */
269 static int
270 esp_zeroize(struct secasvar *sav)
271 {
272         /* NB: ah_zerorize free's the crypto session state */
273         int error = ah_zeroize(sav);
274
275         if (sav->key_enc)
276                 bzero(sav->key_enc->key_data, _KEYLEN(sav->key_enc));
277         sav->tdb_encalgxform = NULL;
278         sav->tdb_xform = NULL;
279         return error;
280 }
281
282 /*
283  * ESP input processing, called (eventually) through the protocol switch.
284  */
285 static int
286 esp_input(struct mbuf *m, struct secasvar *sav, int skip, int protoff)
287 {
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;
293         struct cryptop *crp;
294         struct newesp *esp;
295         uint8_t *ivp;
296         crypto_session_t cryptoid;
297         int alen, error, hlen, plen;
298
299         IPSEC_ASSERT(sav != NULL, ("null SA"));
300         IPSEC_ASSERT(sav->tdb_encalgxform != NULL, ("null encoding xform"));
301
302         error = EINVAL;
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);
308                 goto bad;
309         }
310
311         m = m_pullup(m, skip + sizeof(*esp));
312         if (m == NULL) {
313                 DPRINTF(("%s: cannot pullup header\n", __func__));
314                 ESPSTAT_INC(esps_hdrops);       /*XXX*/
315                 error = ENOBUFS;
316                 goto bad;
317         }
318         esp = (struct newesp *)(mtod(m, caddr_t) + skip);
319
320         esph = sav->tdb_authalgxform;
321         espx = sav->tdb_encalgxform;
322
323         /* Determine the ESP header and auth length */
324         if (sav->flags & SADB_X_EXT_OLD)
325                 hlen = sizeof (struct esp) + sav->ivlen;
326         else
327                 hlen = sizeof (struct newesp) + sav->ivlen;
328
329         alen = xform_ah_authsize(esph);
330
331         /*
332          * Verify payload length is multiple of encryption algorithm
333          * block size.
334          *
335          * NB: This works for the null algorithm because the blocksize
336          *     is 4 and all packets must be 4-byte aligned regardless
337          *     of the algorithm.
338          */
339         plen = m->m_pkthdr.len - (skip + hlen + alen);
340         if ((plen & (espx->blocksize - 1)) || (plen <= 0)) {
341                 DPRINTF(("%s: payload of %d octets not a multiple of %d octets,"
342                     "  SA %s/%08lx\n", __func__, plen, espx->blocksize,
343                     ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
344                     (u_long)ntohl(sav->spi)));
345                 ESPSTAT_INC(esps_badilen);
346                 goto bad;
347         }
348
349         /*
350          * Check sequence number.
351          */
352         SECASVAR_LOCK(sav);
353         if (esph != NULL && sav->replay != NULL && sav->replay->wsize != 0) {
354                 if (ipsec_chkreplay(ntohl(esp->esp_seq), sav) == 0) {
355                         SECASVAR_UNLOCK(sav);
356                         DPRINTF(("%s: packet replay check for %s\n", __func__,
357                             ipsec_sa2str(sav, buf, sizeof(buf))));
358                         ESPSTAT_INC(esps_replay);
359                         error = EACCES;
360                         goto bad;
361                 }
362         }
363         cryptoid = sav->tdb_cryptoid;
364         SECASVAR_UNLOCK(sav);
365
366         /* Update the counters */
367         ESPSTAT_ADD(esps_ibytes, m->m_pkthdr.len - (skip + hlen + alen));
368
369         /* Get crypto descriptors */
370         crp = crypto_getreq(esph && espx ? 2 : 1);
371         if (crp == NULL) {
372                 DPRINTF(("%s: failed to acquire crypto descriptors\n",
373                         __func__));
374                 ESPSTAT_INC(esps_crypto);
375                 error = ENOBUFS;
376                 goto bad;
377         }
378
379         /* Get IPsec-specific opaque pointer */
380         xd = malloc(sizeof(*xd) + alen, M_XDATA, M_NOWAIT | M_ZERO);
381         if (xd == NULL) {
382                 DPRINTF(("%s: failed to allocate xform_data\n", __func__));
383                 ESPSTAT_INC(esps_crypto);
384                 crypto_freereq(crp);
385                 error = ENOBUFS;
386                 goto bad;
387         }
388
389         if (esph != NULL) {
390                 struct cryptodesc *crda = crp->crp_desc;
391
392                 IPSEC_ASSERT(crda != NULL, ("null ah crypto descriptor"));
393
394                 /* Authentication descriptor */
395                 crda->crd_skip = skip;
396                 if (SAV_ISGCM(sav))
397                         crda->crd_len = 8;      /* RFC4106 5, SPI + SN */
398                 else
399                         crda->crd_len = m->m_pkthdr.len - (skip + alen);
400                 crda->crd_inject = m->m_pkthdr.len - alen;
401
402                 crda->crd_alg = esph->type;
403
404                 /* Copy the authenticator */
405                 m_copydata(m, m->m_pkthdr.len - alen, alen,
406                     (caddr_t) (xd + 1));
407
408                 /* Chain authentication request */
409                 crde = crda->crd_next;
410         } else {
411                 crde = crp->crp_desc;
412         }
413
414         /* Crypto operation descriptor */
415         crp->crp_ilen = m->m_pkthdr.len; /* Total input length */
416         crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
417         if (V_async_crypto)
418                 crp->crp_flags |= CRYPTO_F_ASYNC | CRYPTO_F_ASYNC_KEEPORDER;
419         crp->crp_buf = (caddr_t) m;
420         crp->crp_callback = esp_input_cb;
421         crp->crp_session = cryptoid;
422         crp->crp_opaque = (caddr_t) xd;
423
424         /* These are passed as-is to the callback */
425         xd->sav = sav;
426         xd->protoff = protoff;
427         xd->skip = skip;
428         xd->cryptoid = cryptoid;
429         xd->vnet = curvnet;
430
431         /* Decryption descriptor */
432         IPSEC_ASSERT(crde != NULL, ("null esp crypto descriptor"));
433         crde->crd_skip = skip + hlen;
434         crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
435         crde->crd_inject = skip + hlen - sav->ivlen;
436
437         if (SAV_ISCTRORGCM(sav)) {
438                 ivp = &crde->crd_iv[0];
439
440                 /* GCM IV Format: RFC4106 4 */
441                 /* CTR IV Format: RFC3686 4 */
442                 /* Salt is last four bytes of key, RFC4106 8.1 */
443                 /* Nonce is last four bytes of key, RFC3686 5.1 */
444                 memcpy(ivp, sav->key_enc->key_data +
445                     _KEYLEN(sav->key_enc) - 4, 4);
446
447                 if (SAV_ISCTR(sav)) {
448                         /* Initial block counter is 1, RFC3686 4 */
449                         be32enc(&ivp[sav->ivlen + 4], 1);
450                 }
451
452                 m_copydata(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
453                 crde->crd_flags |= CRD_F_IV_EXPLICIT;
454         }
455
456         crde->crd_alg = espx->type;
457
458         return (crypto_dispatch(crp));
459 bad:
460         m_freem(m);
461         key_freesav(&sav);
462         return (error);
463 }
464
465 /*
466  * ESP input callback from the crypto driver.
467  */
468 static int
469 esp_input_cb(struct cryptop *crp)
470 {
471         IPSEC_DEBUG_DECLARE(char buf[128]);
472         u_int8_t lastthree[3], aalg[AH_HMAC_MAXHASHLEN];
473         const struct auth_hash *esph;
474         struct mbuf *m;
475         struct cryptodesc *crd;
476         struct xform_data *xd;
477         struct secasvar *sav;
478         struct secasindex *saidx;
479         caddr_t ptr;
480         crypto_session_t cryptoid;
481         int hlen, skip, protoff, error, alen;
482
483         crd = crp->crp_desc;
484         IPSEC_ASSERT(crd != NULL, ("null crypto descriptor!"));
485
486         m = (struct mbuf *) crp->crp_buf;
487         xd = (struct xform_data *) crp->crp_opaque;
488         CURVNET_SET(xd->vnet);
489         sav = xd->sav;
490         skip = xd->skip;
491         protoff = xd->protoff;
492         cryptoid = xd->cryptoid;
493         saidx = &sav->sah->saidx;
494         esph = sav->tdb_authalgxform;
495
496         /* Check for crypto errors */
497         if (crp->crp_etype) {
498                 if (crp->crp_etype == EAGAIN) {
499                         /* Reset the session ID */
500                         if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
501                                 crypto_freesession(cryptoid);
502                         xd->cryptoid = crp->crp_session;
503                         CURVNET_RESTORE();
504                         return (crypto_dispatch(crp));
505                 }
506                 ESPSTAT_INC(esps_noxform);
507                 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
508                 error = crp->crp_etype;
509                 goto bad;
510         }
511
512         /* Shouldn't happen... */
513         if (m == NULL) {
514                 ESPSTAT_INC(esps_crypto);
515                 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
516                 error = EINVAL;
517                 goto bad;
518         }
519         ESPSTAT_INC(esps_hist[sav->alg_enc]);
520
521         /* If authentication was performed, check now. */
522         if (esph != NULL) {
523                 alen = xform_ah_authsize(esph);
524                 AHSTAT_INC(ahs_hist[sav->alg_auth]);
525                 /* Copy the authenticator from the packet */
526                 m_copydata(m, m->m_pkthdr.len - alen, alen, aalg);
527                 ptr = (caddr_t) (xd + 1);
528
529                 /* Verify authenticator */
530                 if (timingsafe_bcmp(ptr, aalg, alen) != 0) {
531                         DPRINTF(("%s: authentication hash mismatch for "
532                             "packet in SA %s/%08lx\n", __func__,
533                             ipsec_address(&saidx->dst, buf, sizeof(buf)),
534                             (u_long) ntohl(sav->spi)));
535                         ESPSTAT_INC(esps_badauth);
536                         error = EACCES;
537                         goto bad;
538                 }
539                 m->m_flags |= M_AUTHIPDGM;
540                 /* Remove trailing authenticator */
541                 m_adj(m, -alen);
542         }
543
544         /* Release the crypto descriptors */
545         free(xd, M_XDATA), xd = NULL;
546         crypto_freereq(crp), crp = NULL;
547
548         /*
549          * Packet is now decrypted.
550          */
551         m->m_flags |= M_DECRYPTED;
552
553         /*
554          * Update replay sequence number, if appropriate.
555          */
556         if (sav->replay) {
557                 u_int32_t seq;
558
559                 m_copydata(m, skip + offsetof(struct newesp, esp_seq),
560                            sizeof (seq), (caddr_t) &seq);
561                 SECASVAR_LOCK(sav);
562                 if (ipsec_updatereplay(ntohl(seq), sav)) {
563                         SECASVAR_UNLOCK(sav);
564                         DPRINTF(("%s: packet replay check for %s\n", __func__,
565                             ipsec_sa2str(sav, buf, sizeof(buf))));
566                         ESPSTAT_INC(esps_replay);
567                         error = EACCES;
568                         goto bad;
569                 }
570                 SECASVAR_UNLOCK(sav);
571         }
572
573         /* Determine the ESP header length */
574         if (sav->flags & SADB_X_EXT_OLD)
575                 hlen = sizeof (struct esp) + sav->ivlen;
576         else
577                 hlen = sizeof (struct newesp) + sav->ivlen;
578
579         /* Remove the ESP header and IV from the mbuf. */
580         error = m_striphdr(m, skip, hlen);
581         if (error) {
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)));
586                 goto bad;
587         }
588
589         /* Save the last three bytes of decrypted data */
590         m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
591
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)));
600                 error = EINVAL;
601                 goto bad;
602         }
603
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)));
612                         error = EINVAL;
613                         goto bad;
614                 }
615         }
616
617         /* Trim the mbuf chain to remove trailing authenticator and padding */
618         m_adj(m, -(lastthree[1] + 2));
619
620         /* Restore the Next Protocol field */
621         m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
622
623         switch (saidx->dst.sa.sa_family) {
624 #ifdef INET6
625         case AF_INET6:
626                 error = ipsec6_common_input_cb(m, sav, skip, protoff);
627                 break;
628 #endif
629 #ifdef INET
630         case AF_INET:
631                 error = ipsec4_common_input_cb(m, sav, skip, protoff);
632                 break;
633 #endif
634         default:
635                 panic("%s: Unexpected address family: %d saidx=%p", __func__,
636                     saidx->dst.sa.sa_family, saidx);
637         }
638         CURVNET_RESTORE();
639         return error;
640 bad:
641         CURVNET_RESTORE();
642         if (sav != NULL)
643                 key_freesav(&sav);
644         if (m != NULL)
645                 m_freem(m);
646         if (xd != NULL)
647                 free(xd, M_XDATA);
648         if (crp != NULL)
649                 crypto_freereq(crp);
650         return error;
651 }
652 /*
653  * ESP output routine, called by ipsec[46]_perform_request().
654  */
655 static int
656 esp_output(struct mbuf *m, struct secpolicy *sp, struct secasvar *sav,
657     u_int idx, int skip, int protoff)
658 {
659         IPSEC_DEBUG_DECLARE(char buf[IPSEC_ADDRSTRLEN]);
660         struct cryptodesc *crde = NULL, *crda = NULL;
661         struct cryptop *crp;
662         const struct auth_hash *esph;
663         const struct enc_xform *espx;
664         struct mbuf *mo = NULL;
665         struct xform_data *xd;
666         struct secasindex *saidx;
667         unsigned char *pad;
668         uint8_t *ivp;
669         uint64_t cntr;
670         crypto_session_t cryptoid;
671         int hlen, rlen, padding, blks, alen, i, roff;
672         int error, maxpacketsize;
673         uint8_t prot;
674
675         IPSEC_ASSERT(sav != NULL, ("null SA"));
676         esph = sav->tdb_authalgxform;
677         espx = sav->tdb_encalgxform;
678         IPSEC_ASSERT(espx != NULL, ("null encoding xform"));
679
680         if (sav->flags & SADB_X_EXT_OLD)
681                 hlen = sizeof (struct esp) + sav->ivlen;
682         else
683                 hlen = sizeof (struct newesp) + sav->ivlen;
684
685         rlen = m->m_pkthdr.len - skip;  /* Raw payload length. */
686         /*
687          * RFC4303 2.4 Requires 4 byte alignment.
688          */
689         blks = MAX(4, espx->blocksize);         /* Cipher blocksize */
690
691         /* XXX clamp padding length a la KAME??? */
692         padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
693
694         alen = xform_ah_authsize(esph);
695
696         ESPSTAT_INC(esps_output);
697
698         saidx = &sav->sah->saidx;
699         /* Check for maximum packet size violations. */
700         switch (saidx->dst.sa.sa_family) {
701 #ifdef INET
702         case AF_INET:
703                 maxpacketsize = IP_MAXPACKET;
704                 break;
705 #endif /* INET */
706 #ifdef INET6
707         case AF_INET6:
708                 maxpacketsize = IPV6_MAXPACKET;
709                 break;
710 #endif /* INET6 */
711         default:
712                 DPRINTF(("%s: unknown/unsupported protocol "
713                     "family %d, SA %s/%08lx\n", __func__,
714                     saidx->dst.sa.sa_family, ipsec_address(&saidx->dst,
715                         buf, sizeof(buf)), (u_long) ntohl(sav->spi)));
716                 ESPSTAT_INC(esps_nopf);
717                 error = EPFNOSUPPORT;
718                 goto bad;
719         }
720         /*
721         DPRINTF(("%s: skip %d hlen %d rlen %d padding %d alen %d blksd %d\n",
722                 __func__, skip, hlen, rlen, padding, alen, blks)); */
723         if (skip + hlen + rlen + padding + alen > maxpacketsize) {
724                 DPRINTF(("%s: packet in SA %s/%08lx got too big "
725                     "(len %u, max len %u)\n", __func__,
726                     ipsec_address(&saidx->dst, buf, sizeof(buf)),
727                     (u_long) ntohl(sav->spi),
728                     skip + hlen + rlen + padding + alen, maxpacketsize));
729                 ESPSTAT_INC(esps_toobig);
730                 error = EMSGSIZE;
731                 goto bad;
732         }
733
734         /* Update the counters. */
735         ESPSTAT_ADD(esps_obytes, m->m_pkthdr.len - skip);
736
737         m = m_unshare(m, M_NOWAIT);
738         if (m == NULL) {
739                 DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
740                     ipsec_address(&saidx->dst, buf, sizeof(buf)),
741                     (u_long) ntohl(sav->spi)));
742                 ESPSTAT_INC(esps_hdrops);
743                 error = ENOBUFS;
744                 goto bad;
745         }
746
747         /* Inject ESP header. */
748         mo = m_makespace(m, skip, hlen, &roff);
749         if (mo == NULL) {
750                 DPRINTF(("%s: %u byte ESP hdr inject failed for SA %s/%08lx\n",
751                     __func__, hlen, ipsec_address(&saidx->dst, buf,
752                     sizeof(buf)), (u_long) ntohl(sav->spi)));
753                 ESPSTAT_INC(esps_hdrops);       /* XXX diffs from openbsd */
754                 error = ENOBUFS;
755                 goto bad;
756         }
757
758         /* Initialize ESP header. */
759         bcopy((caddr_t) &sav->spi, mtod(mo, caddr_t) + roff,
760             sizeof(uint32_t));
761         SECASVAR_LOCK(sav);
762         if (sav->replay) {
763                 uint32_t replay;
764
765 #ifdef REGRESSION
766                 /* Emulate replay attack when ipsec_replay is TRUE. */
767                 if (!V_ipsec_replay)
768 #endif
769                         sav->replay->count++;
770                 replay = htonl(sav->replay->count);
771
772                 bcopy((caddr_t) &replay, mtod(mo, caddr_t) + roff +
773                     sizeof(uint32_t), sizeof(uint32_t));
774         }
775         cryptoid = sav->tdb_cryptoid;
776         if (SAV_ISCTRORGCM(sav))
777                 cntr = sav->cntr++;
778         SECASVAR_UNLOCK(sav);
779
780         /*
781          * Add padding -- better to do it ourselves than use the crypto engine,
782          * although if/when we support compression, we'd have to do that.
783          */
784         pad = (u_char *) m_pad(m, padding + alen);
785         if (pad == NULL) {
786                 DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
787                     ipsec_address(&saidx->dst, buf, sizeof(buf)),
788                     (u_long) ntohl(sav->spi)));
789                 m = NULL;               /* NB: free'd by m_pad */
790                 error = ENOBUFS;
791                 goto bad;
792         }
793
794         /*
795          * Add padding: random, zero, or self-describing.
796          * XXX catch unexpected setting
797          */
798         switch (sav->flags & SADB_X_EXT_PMASK) {
799         case SADB_X_EXT_PRAND:
800                 arc4random_buf(pad, padding - 2);
801                 break;
802         case SADB_X_EXT_PZERO:
803                 bzero(pad, padding - 2);
804                 break;
805         case SADB_X_EXT_PSEQ:
806                 for (i = 0; i < padding - 2; i++)
807                         pad[i] = i+1;
808                 break;
809         }
810
811         /* Fix padding length and Next Protocol in padding itself. */
812         pad[padding - 2] = padding - 2;
813         m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
814
815         /* Fix Next Protocol in IPv4/IPv6 header. */
816         prot = IPPROTO_ESP;
817         m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
818
819         /* Get crypto descriptors. */
820         crp = crypto_getreq(esph != NULL ? 2 : 1);
821         if (crp == NULL) {
822                 DPRINTF(("%s: failed to acquire crypto descriptors\n",
823                         __func__));
824                 ESPSTAT_INC(esps_crypto);
825                 error = ENOBUFS;
826                 goto bad;
827         }
828
829         /* IPsec-specific opaque crypto info. */
830         xd =  malloc(sizeof(struct xform_data), M_XDATA, M_NOWAIT | M_ZERO);
831         if (xd == NULL) {
832                 crypto_freereq(crp);
833                 DPRINTF(("%s: failed to allocate xform_data\n", __func__));
834                 ESPSTAT_INC(esps_crypto);
835                 error = ENOBUFS;
836                 goto bad;
837         }
838
839         crde = crp->crp_desc;
840         crda = crde->crd_next;
841
842         /* Encryption descriptor. */
843         crde->crd_skip = skip + hlen;
844         crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
845         crde->crd_flags = CRD_F_ENCRYPT;
846         crde->crd_inject = skip + hlen - sav->ivlen;
847
848         /* Encryption operation. */
849         crde->crd_alg = espx->type;
850         if (SAV_ISCTRORGCM(sav)) {
851                 ivp = &crde->crd_iv[0];
852
853                 /* GCM IV Format: RFC4106 4 */
854                 /* CTR IV Format: RFC3686 4 */
855                 /* Salt is last four bytes of key, RFC4106 8.1 */
856                 /* Nonce is last four bytes of key, RFC3686 5.1 */
857                 memcpy(ivp, sav->key_enc->key_data +
858                     _KEYLEN(sav->key_enc) - 4, 4);
859                 be64enc(&ivp[4], cntr);
860                 if (SAV_ISCTR(sav)) {
861                         /* Initial block counter is 1, RFC3686 4 */
862                         /* XXXAE: should we use this only for first packet? */
863                         be32enc(&ivp[sav->ivlen + 4], 1);
864                 }
865
866                 m_copyback(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
867                 crde->crd_flags |= CRD_F_IV_EXPLICIT|CRD_F_IV_PRESENT;
868         }
869
870         /* Callback parameters */
871         xd->sp = sp;
872         xd->sav = sav;
873         xd->idx = idx;
874         xd->cryptoid = cryptoid;
875         xd->vnet = curvnet;
876
877         /* Crypto operation descriptor. */
878         crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
879         crp->crp_flags = CRYPTO_F_IMBUF | CRYPTO_F_CBIFSYNC;
880         if (V_async_crypto)
881                 crp->crp_flags |= CRYPTO_F_ASYNC | CRYPTO_F_ASYNC_KEEPORDER;
882         crp->crp_buf = (caddr_t) m;
883         crp->crp_callback = esp_output_cb;
884         crp->crp_opaque = (caddr_t) xd;
885         crp->crp_session = cryptoid;
886
887         if (esph) {
888                 /* Authentication descriptor. */
889                 crda->crd_alg = esph->type;
890                 crda->crd_skip = skip;
891                 if (SAV_ISGCM(sav))
892                         crda->crd_len = 8;      /* RFC4106 5, SPI + SN */
893                 else
894                         crda->crd_len = m->m_pkthdr.len - (skip + alen);
895                 crda->crd_inject = m->m_pkthdr.len - alen;
896         }
897
898         return crypto_dispatch(crp);
899 bad:
900         if (m)
901                 m_freem(m);
902         key_freesav(&sav);
903         key_freesp(&sp);
904         return (error);
905 }
906 /*
907  * ESP output callback from the crypto driver.
908  */
909 static int
910 esp_output_cb(struct cryptop *crp)
911 {
912         struct xform_data *xd;
913         struct secpolicy *sp;
914         struct secasvar *sav;
915         struct mbuf *m;
916         crypto_session_t cryptoid;
917         u_int idx;
918         int error;
919
920         xd = (struct xform_data *) crp->crp_opaque;
921         CURVNET_SET(xd->vnet);
922         m = (struct mbuf *) crp->crp_buf;
923         sp = xd->sp;
924         sav = xd->sav;
925         idx = xd->idx;
926         cryptoid = xd->cryptoid;
927
928         /* Check for crypto errors. */
929         if (crp->crp_etype) {
930                 if (crp->crp_etype == EAGAIN) {
931                         /* Reset the session ID */
932                         if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
933                                 crypto_freesession(cryptoid);
934                         xd->cryptoid = crp->crp_session;
935                         CURVNET_RESTORE();
936                         return (crypto_dispatch(crp));
937                 }
938                 ESPSTAT_INC(esps_noxform);
939                 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
940                 error = crp->crp_etype;
941                 m_freem(m);
942                 goto bad;
943         }
944
945         /* Shouldn't happen... */
946         if (m == NULL) {
947                 ESPSTAT_INC(esps_crypto);
948                 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
949                 error = EINVAL;
950                 goto bad;
951         }
952         free(xd, M_XDATA);
953         crypto_freereq(crp);
954         ESPSTAT_INC(esps_hist[sav->alg_enc]);
955         if (sav->tdb_authalgxform != NULL)
956                 AHSTAT_INC(ahs_hist[sav->alg_auth]);
957
958 #ifdef REGRESSION
959         /* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
960         if (V_ipsec_integrity) {
961                 static unsigned char ipseczeroes[AH_HMAC_MAXHASHLEN];
962                 const struct auth_hash *esph;
963
964                 /*
965                  * Corrupt HMAC if we want to test integrity verification of
966                  * the other side.
967                  */
968                 esph = sav->tdb_authalgxform;
969                 if (esph !=  NULL) {
970                         int alen;
971
972                         alen = xform_ah_authsize(esph);
973                         m_copyback(m, m->m_pkthdr.len - alen,
974                             alen, ipseczeroes);
975                 }
976         }
977 #endif
978
979         /* NB: m is reclaimed by ipsec_process_done. */
980         error = ipsec_process_done(m, sp, sav, idx);
981         CURVNET_RESTORE();
982         return (error);
983 bad:
984         CURVNET_RESTORE();
985         free(xd, M_XDATA);
986         crypto_freereq(crp);
987         key_freesav(&sav);
988         key_freesp(&sp);
989         return (error);
990 }
991
992 static struct xformsw esp_xformsw = {
993         .xf_type =      XF_ESP,
994         .xf_name =      "IPsec ESP",
995         .xf_init =      esp_init,
996         .xf_zeroize =   esp_zeroize,
997         .xf_input =     esp_input,
998         .xf_output =    esp_output,
999 };
1000
1001 SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
1002     xform_attach, &esp_xformsw);
1003 SYSUNINIT(esp_xform_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
1004     xform_detach, &esp_xformsw);