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