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