]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netipsec/xform_esp.c
sound: Remove leftover references to snd_clone
[FreeBSD/FreeBSD.git] / sys / netipsec / xform_esp.c
1 /*      $OpenBSD: ip_esp.c,v 1.69 2001/06/26 06:18:59 angelos Exp $ */
2 /*-
3  * The authors of this code are John Ioannidis (ji@tla.org),
4  * Angelos D. Keromytis (kermit@csd.uch.gr) and
5  * Niels Provos (provos@physnet.uni-hamburg.de).
6  *
7  * The original version of this code was written by John Ioannidis
8  * for BSD/OS in Athens, Greece, in November 1995.
9  *
10  * Ported to OpenBSD and NetBSD, with additional transforms, in December 1996,
11  * by Angelos D. Keromytis.
12  *
13  * Additional transforms and features in 1997 and 1998 by Angelos D. Keromytis
14  * and Niels Provos.
15  *
16  * Additional features in 1999 by Angelos D. Keromytis.
17  *
18  * Copyright (C) 1995, 1996, 1997, 1998, 1999 by John Ioannidis,
19  * Angelos D. Keromytis and Niels Provos.
20  * Copyright (c) 2001 Angelos D. Keromytis.
21  *
22  * Permission to use, copy, and modify this software with or without fee
23  * is hereby granted, provided that this entire notice is included in
24  * all copies of any software which is or includes a copy or
25  * modification of this software.
26  * You may use this code under the GNU public license if you so wish. Please
27  * contribute changes back to the authors under this freer than GPL license
28  * so that we may further the use of strong encryption without limitations to
29  * all.
30  *
31  * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
32  * IMPLIED WARRANTY. IN PARTICULAR, NONE OF THE AUTHORS MAKES ANY
33  * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
34  * MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
35  * PURPOSE.
36  */
37 #include "opt_inet.h"
38 #include "opt_inet6.h"
39 #include "opt_ipsec.h"
40
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/malloc.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 #define SPI_SIZE        4
84
85 VNET_DEFINE(int, esp_enable) = 1;
86 VNET_DEFINE_STATIC(int, esp_ctr_compatibility) = 1;
87 #define V_esp_ctr_compatibility VNET(esp_ctr_compatibility)
88 VNET_PCPUSTAT_DEFINE(struct espstat, espstat);
89 VNET_PCPUSTAT_SYSINIT(espstat);
90
91 #ifdef VIMAGE
92 VNET_PCPUSTAT_SYSUNINIT(espstat);
93 #endif /* VIMAGE */
94
95 SYSCTL_DECL(_net_inet_esp);
96 SYSCTL_INT(_net_inet_esp, OID_AUTO, esp_enable,
97         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(esp_enable), 0, "");
98 SYSCTL_INT(_net_inet_esp, OID_AUTO, ctr_compatibility,
99     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(esp_ctr_compatibility), 0,
100     "Align AES-CTR encrypted transmitted frames to blocksize");
101 SYSCTL_VNET_PCPUSTAT(_net_inet_esp, IPSECCTL_STATS, stats,
102     struct espstat, espstat,
103     "ESP statistics (struct espstat, netipsec/esp_var.h");
104
105 static MALLOC_DEFINE(M_ESP, "esp", "IPsec ESP");
106
107 static int esp_input_cb(struct cryptop *op);
108 static int esp_output_cb(struct cryptop *crp);
109
110 size_t
111 esp_hdrsiz(struct secasvar *sav)
112 {
113         size_t size;
114
115         if (sav != NULL) {
116                 /*XXX not right for null algorithm--does it matter??*/
117                 IPSEC_ASSERT(sav->tdb_encalgxform != NULL,
118                         ("SA with null xform"));
119                 if (sav->flags & SADB_X_EXT_OLD)
120                         size = sizeof (struct esp);
121                 else
122                         size = sizeof (struct newesp);
123                 size += sav->tdb_encalgxform->blocksize + 9;
124                 /*XXX need alg check???*/
125                 if (sav->tdb_authalgxform != NULL && sav->replay)
126                         size += ah_hdrsiz(sav);
127         } else {
128                 /*
129                  *   base header size
130                  * + max iv length for CBC mode
131                  * + max pad length
132                  * + sizeof (pad length field)
133                  * + sizeof (next header field)
134                  * + max icv supported.
135                  */
136                 size = sizeof (struct newesp) + EALG_MAX_BLOCK_LEN + 9 + 16;
137         }
138         return size;
139 }
140
141 /*
142  * esp_init() is called when an SPI is being set up.
143  */
144 static int
145 esp_init(struct secasvar *sav, struct xformsw *xsp)
146 {
147         const struct enc_xform *txform;
148         struct crypto_session_params csp;
149         int keylen;
150         int error;
151
152         txform = enc_algorithm_lookup(sav->alg_enc);
153         if (txform == NULL) {
154                 DPRINTF(("%s: unsupported encryption algorithm %d\n",
155                         __func__, sav->alg_enc));
156                 return EINVAL;
157         }
158         if (sav->key_enc == NULL) {
159                 DPRINTF(("%s: no encoding key for %s algorithm\n",
160                          __func__, txform->name));
161                 return EINVAL;
162         }
163         if ((sav->flags & (SADB_X_EXT_OLD | SADB_X_EXT_IV4B)) ==
164             SADB_X_EXT_IV4B) {
165                 DPRINTF(("%s: 4-byte IV not supported with protocol\n",
166                         __func__));
167                 return EINVAL;
168         }
169
170         /* subtract off the salt, RFC4106, 8.1 and RFC3686, 5.1 */
171         keylen = _KEYLEN(sav->key_enc) - SAV_ISCTRORGCM(sav) * 4 -
172             SAV_ISCHACHA(sav) * 4;
173         if (txform->minkey > keylen || keylen > txform->maxkey) {
174                 DPRINTF(("%s: invalid key length %u, must be in the range "
175                         "[%u..%u] for algorithm %s\n", __func__,
176                         keylen, txform->minkey, txform->maxkey,
177                         txform->name));
178                 return EINVAL;
179         }
180
181         if (SAV_ISCTRORGCM(sav) || SAV_ISCHACHA(sav))
182                 sav->ivlen = 8; /* RFC4106 3.1 and RFC3686 3.1 */
183         else
184                 sav->ivlen = txform->ivsize;
185
186         memset(&csp, 0, sizeof(csp));
187
188         /*
189          * Setup AH-related state.
190          */
191         if (sav->alg_auth != 0) {
192                 error = ah_init0(sav, xsp, &csp);
193                 if (error)
194                         return error;
195         }
196
197         /* NB: override anything set in ah_init0 */
198         sav->tdb_xform = xsp;
199         sav->tdb_encalgxform = txform;
200
201         /*
202          * Whenever AES-GCM is used for encryption, one
203          * of the AES authentication algorithms is chosen
204          * as well, based on the key size.
205          */
206         if (sav->alg_enc == SADB_X_EALG_AESGCM16) {
207                 switch (keylen) {
208                 case AES_128_GMAC_KEY_LEN:
209                         sav->alg_auth = SADB_X_AALG_AES128GMAC;
210                         sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_128;
211                         break;
212                 case AES_192_GMAC_KEY_LEN:
213                         sav->alg_auth = SADB_X_AALG_AES192GMAC;
214                         sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_192;
215                         break;
216                 case AES_256_GMAC_KEY_LEN:
217                         sav->alg_auth = SADB_X_AALG_AES256GMAC;
218                         sav->tdb_authalgxform = &auth_hash_nist_gmac_aes_256;
219                         break;
220                 default:
221                         DPRINTF(("%s: invalid key length %u"
222                                  "for algorithm %s\n", __func__,
223                                  keylen, txform->name));
224                         return EINVAL;
225                 }
226                 csp.csp_mode = CSP_MODE_AEAD;
227                 if (sav->flags & SADB_X_SAFLAGS_ESN)
228                         csp.csp_flags |= CSP_F_SEPARATE_AAD;
229         } else if (sav->alg_enc == SADB_X_EALG_CHACHA20POLY1305) {
230                 sav->alg_auth = SADB_X_AALG_CHACHA20POLY1305;
231                 sav->tdb_authalgxform = &auth_hash_poly1305;
232                 csp.csp_mode = CSP_MODE_AEAD;
233                 if (sav->flags & SADB_X_SAFLAGS_ESN)
234                         csp.csp_flags |= CSP_F_SEPARATE_AAD;
235         } else if (sav->alg_auth != 0) {
236                 csp.csp_mode = CSP_MODE_ETA;
237                 if (sav->flags & SADB_X_SAFLAGS_ESN)
238                         csp.csp_flags |= CSP_F_ESN;
239         } else
240                 csp.csp_mode = CSP_MODE_CIPHER;
241
242         /* Initialize crypto session. */
243         csp.csp_cipher_alg = sav->tdb_encalgxform->type;
244         if (csp.csp_cipher_alg != CRYPTO_NULL_CBC) {
245                 csp.csp_cipher_key = sav->key_enc->key_data;
246                 csp.csp_cipher_klen = _KEYBITS(sav->key_enc) / 8 -
247                     SAV_ISCTRORGCM(sav) * 4 - SAV_ISCHACHA(sav) * 4;
248         };
249         csp.csp_ivlen = txform->ivsize;
250
251         error = crypto_newsession(&sav->tdb_cryptoid, &csp, V_crypto_support);
252         return error;
253 }
254
255 static void
256 esp_cleanup(struct secasvar *sav)
257 {
258
259         crypto_freesession(sav->tdb_cryptoid);
260         sav->tdb_cryptoid = NULL;
261         sav->tdb_authalgxform = NULL;
262         sav->tdb_encalgxform = NULL;
263 }
264
265 /*
266  * ESP input processing, called (eventually) through the protocol switch.
267  */
268 static int
269 esp_input(struct mbuf *m, struct secasvar *sav, int skip, int protoff)
270 {
271         IPSEC_DEBUG_DECLARE(char buf[128]);
272         const struct auth_hash *esph;
273         const struct enc_xform *espx;
274         struct xform_data *xd;
275         struct cryptop *crp;
276         struct newesp *esp;
277         uint8_t *ivp;
278         crypto_session_t cryptoid;
279         int alen, error, hlen, plen;
280         uint32_t seqh;
281         const struct crypto_session_params *csp;
282
283         SECASVAR_RLOCK_TRACKER;
284
285         IPSEC_ASSERT(sav != NULL, ("null SA"));
286         IPSEC_ASSERT(sav->tdb_encalgxform != NULL, ("null encoding xform"));
287
288         error = EINVAL;
289         /* Valid IP Packet length ? */
290         if ( (skip&3) || (m->m_pkthdr.len&3) ){
291                 DPRINTF(("%s: misaligned packet, skip %u pkt len %u",
292                                 __func__, skip, m->m_pkthdr.len));
293                 ESPSTAT_INC(esps_badilen);
294                 goto bad;
295         }
296
297         if (m->m_len < skip + sizeof(*esp)) {
298                 m = m_pullup(m, skip + sizeof(*esp));
299                 if (m == NULL) {
300                         DPRINTF(("%s: cannot pullup header\n", __func__));
301                         ESPSTAT_INC(esps_hdrops);       /*XXX*/
302                         error = ENOBUFS;
303                         goto bad;
304                 }
305         }
306         esp = (struct newesp *)(mtod(m, caddr_t) + skip);
307
308         esph = sav->tdb_authalgxform;
309         espx = sav->tdb_encalgxform;
310
311         /* Determine the ESP header and auth length */
312         if (sav->flags & SADB_X_EXT_OLD)
313                 hlen = sizeof (struct esp) + sav->ivlen;
314         else
315                 hlen = sizeof (struct newesp) + sav->ivlen;
316
317         alen = xform_ah_authsize(esph);
318
319         /*
320          * Verify payload length is multiple of encryption algorithm
321          * block size.
322          *
323          * NB: This works for the null algorithm because the blocksize
324          *     is 4 and all packets must be 4-byte aligned regardless
325          *     of the algorithm.
326          */
327         plen = m->m_pkthdr.len - (skip + hlen + alen);
328         if ((plen & (espx->blocksize - 1)) || (plen <= 0)) {
329                 DPRINTF(("%s: payload of %d octets not a multiple of %d octets,"
330                     "  SA %s/%08lx\n", __func__, plen, espx->blocksize,
331                     ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
332                     (u_long)ntohl(sav->spi)));
333                 ESPSTAT_INC(esps_badilen);
334                 goto bad;
335         }
336
337         /*
338          * Check sequence number.
339          */
340         SECASVAR_RLOCK(sav);
341         if (esph != NULL && sav->replay != NULL && sav->replay->wsize != 0) {
342                 if (ipsec_chkreplay(ntohl(esp->esp_seq), &seqh, sav) == 0) {
343                         SECASVAR_RUNLOCK(sav);
344                         DPRINTF(("%s: packet replay check for %s\n", __func__,
345                             ipsec_sa2str(sav, buf, sizeof(buf))));
346                         ESPSTAT_INC(esps_replay);
347                         error = EACCES;
348                         goto bad;
349                 }
350                 seqh = htonl(seqh);
351         }
352         cryptoid = sav->tdb_cryptoid;
353         SECASVAR_RUNLOCK(sav);
354
355         /* Update the counters */
356         ESPSTAT_ADD(esps_ibytes, m->m_pkthdr.len - (skip + hlen + alen));
357
358         /* Get crypto descriptors */
359         crp = crypto_getreq(cryptoid, M_NOWAIT);
360         if (crp == NULL) {
361                 DPRINTF(("%s: failed to acquire crypto descriptors\n",
362                         __func__));
363                 ESPSTAT_INC(esps_crypto);
364                 error = ENOBUFS;
365                 goto bad;
366         }
367
368         /* Get IPsec-specific opaque pointer */
369         xd = malloc(sizeof(*xd), M_ESP, M_NOWAIT | M_ZERO);
370         if (xd == NULL) {
371                 DPRINTF(("%s: failed to allocate xform_data\n", __func__));
372                 goto xd_fail;
373         }
374
375         if (esph != NULL) {
376                 crp->crp_op = CRYPTO_OP_VERIFY_DIGEST;
377                 if (SAV_ISGCM(sav) || SAV_ISCHACHA(sav))
378                         crp->crp_aad_length = 8; /* RFC4106 5, SPI + SN */
379                 else
380                         crp->crp_aad_length = hlen;
381
382                 csp = crypto_get_params(crp->crp_session);
383                 if ((csp->csp_flags & CSP_F_SEPARATE_AAD) &&
384                     (sav->replay != NULL) && (sav->replay->wsize != 0)) {
385                         int aad_skip;
386
387                         crp->crp_aad_length += sizeof(seqh);
388                         crp->crp_aad = malloc(crp->crp_aad_length, M_ESP, M_NOWAIT);
389                         if (crp->crp_aad == NULL) {
390                                 DPRINTF(("%s: failed to allocate xform_data\n",
391                                          __func__));
392                                 goto crp_aad_fail;
393                         }
394
395                         /* SPI */
396                         m_copydata(m, skip, SPI_SIZE, crp->crp_aad);
397                         aad_skip = SPI_SIZE;
398
399                         /* ESN */
400                         bcopy(&seqh, (char *)crp->crp_aad + aad_skip, sizeof(seqh));
401                         aad_skip += sizeof(seqh);
402
403                         /* Rest of aad */
404                         if (crp->crp_aad_length - aad_skip > 0)
405                                 m_copydata(m, skip + SPI_SIZE,
406                                            crp->crp_aad_length - aad_skip,
407                                            (char *)crp->crp_aad + aad_skip);
408                 } else
409                         crp->crp_aad_start = skip;
410
411                 if (csp->csp_flags & CSP_F_ESN &&
412                            sav->replay != NULL && sav->replay->wsize != 0)
413                         memcpy(crp->crp_esn, &seqh, sizeof(seqh));
414
415                 crp->crp_digest_start = m->m_pkthdr.len - alen;
416         }
417
418         /* Crypto operation descriptor */
419         crp->crp_flags = CRYPTO_F_CBIFSYNC;
420         crypto_use_mbuf(crp, m);
421         crp->crp_callback = esp_input_cb;
422         crp->crp_opaque = 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         crp->crp_op |= CRYPTO_OP_DECRYPT;
433         crp->crp_payload_start = skip + hlen;
434         crp->crp_payload_length = m->m_pkthdr.len - (skip + hlen + alen);
435
436         /* Generate or read cipher IV. */
437         if (SAV_ISCTRORGCM(sav) || SAV_ISCHACHA(sav)) {
438                 ivp = &crp->crp_iv[0];
439
440                 /*
441                  * AES-GCM and AES-CTR use similar cipher IV formats
442                  * defined in RFC 4106 section 4 and RFC 3686 section
443                  * 4, respectively.
444                  *
445                  * The first 4 bytes of the cipher IV contain an
446                  * implicit salt, or nonce, obtained from the last 4
447                  * bytes of the encryption key.  The next 8 bytes hold
448                  * an explicit IV unique to each packet.  This
449                  * explicit IV is used as the ESP IV for the packet.
450                  * The last 4 bytes hold a big-endian block counter
451                  * incremented for each block.  For AES-GCM, the block
452                  * counter's initial value is defined as part of the
453                  * algorithm.  For AES-CTR, the block counter's
454                  * initial value for each packet is defined as 1 by
455                  * RFC 3686.
456                  *
457                  * ------------------------------------------
458                  * | Salt | Explicit ESP IV | Block Counter |
459                  * ------------------------------------------
460                  *  4 bytes     8 bytes          4 bytes
461                  */
462                 memcpy(ivp, sav->key_enc->key_data +
463                     _KEYLEN(sav->key_enc) - 4, 4);
464                 m_copydata(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
465                 if (SAV_ISCTR(sav)) {
466                         be32enc(&ivp[sav->ivlen + 4], 1);
467                 }
468                 crp->crp_flags |= CRYPTO_F_IV_SEPARATE;
469         } else if (sav->ivlen != 0)
470                 crp->crp_iv_start = skip + hlen - sav->ivlen;
471
472         if (V_async_crypto)
473                 return (crypto_dispatch_async(crp, CRYPTO_ASYNC_ORDERED));
474         else
475                 return (crypto_dispatch(crp));
476
477 crp_aad_fail:
478         free(xd, M_ESP);
479 xd_fail:
480         crypto_freereq(crp);
481         ESPSTAT_INC(esps_crypto);
482         error = ENOBUFS;
483 bad:
484         m_freem(m);
485         key_freesav(&sav);
486         return (error);
487 }
488
489 /*
490  * ESP input callback from the crypto driver.
491  */
492 static int
493 esp_input_cb(struct cryptop *crp)
494 {
495         IPSEC_DEBUG_DECLARE(char buf[128]);
496         uint8_t lastthree[3];
497         const struct auth_hash *esph;
498         struct mbuf *m;
499         struct xform_data *xd;
500         struct secasvar *sav;
501         struct secasindex *saidx;
502         crypto_session_t cryptoid;
503         int hlen, skip, protoff, error, alen;
504
505         SECASVAR_RLOCK_TRACKER;
506
507         m = crp->crp_buf.cb_mbuf;
508         xd = crp->crp_opaque;
509         CURVNET_SET(xd->vnet);
510         sav = xd->sav;
511         if (sav->state >= SADB_SASTATE_DEAD) {
512                 /* saidx is freed */
513                 DPRINTF(("%s: dead SA %p spi %#x\n", __func__, sav, sav->spi));
514                 ESPSTAT_INC(esps_notdb);
515                 error = ESRCH;
516                 goto bad;
517         }
518         skip = xd->skip;
519         protoff = xd->protoff;
520         cryptoid = xd->cryptoid;
521         saidx = &sav->sah->saidx;
522         esph = sav->tdb_authalgxform;
523
524         /* Check for crypto errors */
525         if (crp->crp_etype) {
526                 if (crp->crp_etype == EAGAIN) {
527                         /* Reset the session ID */
528                         if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
529                                 crypto_freesession(cryptoid);
530                         xd->cryptoid = crp->crp_session;
531                         CURVNET_RESTORE();
532                         return (crypto_dispatch(crp));
533                 }
534
535                 /* EBADMSG indicates authentication failure. */
536                 if (!(crp->crp_etype == EBADMSG && esph != NULL)) {
537                         ESPSTAT_INC(esps_noxform);
538                         DPRINTF(("%s: crypto error %d\n", __func__,
539                                 crp->crp_etype));
540                         error = crp->crp_etype;
541                         goto bad;
542                 }
543         }
544
545         /* Shouldn't happen... */
546         if (m == NULL) {
547                 ESPSTAT_INC(esps_crypto);
548                 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
549                 error = EINVAL;
550                 goto bad;
551         }
552         ESPSTAT_INC(esps_hist[sav->alg_enc]);
553
554         /* If authentication was performed, check now. */
555         if (esph != NULL) {
556                 alen = xform_ah_authsize(esph);
557                 AHSTAT_INC(ahs_hist[sav->alg_auth]);
558                 if (crp->crp_etype == EBADMSG) {
559                         DPRINTF(("%s: authentication hash mismatch for "
560                             "packet in SA %s/%08lx\n", __func__,
561                             ipsec_address(&saidx->dst, buf, sizeof(buf)),
562                             (u_long) ntohl(sav->spi)));
563                         ESPSTAT_INC(esps_badauth);
564                         error = EACCES;
565                         goto bad;
566                 }
567                 m->m_flags |= M_AUTHIPDGM;
568                 /* Remove trailing authenticator */
569                 m_adj(m, -alen);
570         }
571
572         /* Release the crypto descriptors */
573         free(xd, M_ESP), xd = NULL;
574         free(crp->crp_aad, M_ESP), crp->crp_aad = NULL;
575         crypto_freereq(crp), crp = NULL;
576
577         /*
578          * Packet is now decrypted.
579          */
580         m->m_flags |= M_DECRYPTED;
581
582         /*
583          * Update replay sequence number, if appropriate.
584          */
585         if (sav->replay) {
586                 u_int32_t seq;
587
588                 m_copydata(m, skip + offsetof(struct newesp, esp_seq),
589                            sizeof (seq), (caddr_t) &seq);
590                 SECASVAR_RLOCK(sav);
591                 if (ipsec_updatereplay(ntohl(seq), sav)) {
592                         SECASVAR_RUNLOCK(sav);
593                         DPRINTF(("%s: packet replay check for %s\n", __func__,
594                             ipsec_sa2str(sav, buf, sizeof(buf))));
595                         ESPSTAT_INC(esps_replay);
596                         error = EACCES;
597                         goto bad;
598                 }
599                 SECASVAR_RUNLOCK(sav);
600         }
601
602         /* Determine the ESP header length */
603         if (sav->flags & SADB_X_EXT_OLD)
604                 hlen = sizeof (struct esp) + sav->ivlen;
605         else
606                 hlen = sizeof (struct newesp) + sav->ivlen;
607
608         /* Remove the ESP header and IV from the mbuf. */
609         error = m_striphdr(m, skip, hlen);
610         if (error) {
611                 ESPSTAT_INC(esps_hdrops);
612                 DPRINTF(("%s: bad mbuf chain, SA %s/%08lx\n", __func__,
613                     ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
614                     (u_long) ntohl(sav->spi)));
615                 goto bad;
616         }
617
618         /* Save the last three bytes of decrypted data */
619         m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
620
621         /* Verify pad length */
622         if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
623                 ESPSTAT_INC(esps_badilen);
624                 DPRINTF(("%s: invalid padding length %d for %u byte packet "
625                     "in SA %s/%08lx\n", __func__, lastthree[1],
626                     m->m_pkthdr.len - skip,
627                     ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
628                     (u_long) ntohl(sav->spi)));
629                 error = EINVAL;
630                 goto bad;
631         }
632
633         /* Verify correct decryption by checking the last padding bytes */
634         if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
635                 if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
636                         ESPSTAT_INC(esps_badenc);
637                         DPRINTF(("%s: decryption failed for packet in "
638                             "SA %s/%08lx\n", __func__, ipsec_address(
639                             &sav->sah->saidx.dst, buf, sizeof(buf)),
640                             (u_long) ntohl(sav->spi)));
641                         error = EINVAL;
642                         goto bad;
643                 }
644         }
645
646         /*
647          * RFC4303 2.6:
648          * Silently drop packet if next header field is IPPROTO_NONE.
649          */
650         if (lastthree[2] == IPPROTO_NONE)
651                 goto bad;
652
653         /* Trim the mbuf chain to remove trailing authenticator and padding */
654         m_adj(m, -(lastthree[1] + 2));
655
656         /* Restore the Next Protocol field */
657         m_copyback(m, protoff, sizeof (u_int8_t), lastthree + 2);
658
659         switch (saidx->dst.sa.sa_family) {
660 #ifdef INET6
661         case AF_INET6:
662                 error = ipsec6_common_input_cb(m, sav, skip, protoff);
663                 break;
664 #endif
665 #ifdef INET
666         case AF_INET:
667                 error = ipsec4_common_input_cb(m, sav, skip, protoff);
668                 break;
669 #endif
670         default:
671                 panic("%s: Unexpected address family: %d saidx=%p", __func__,
672                     saidx->dst.sa.sa_family, saidx);
673         }
674         CURVNET_RESTORE();
675         return error;
676 bad:
677         if (sav != NULL)
678                 key_freesav(&sav);
679         if (m != NULL)
680                 m_freem(m);
681         if (xd != NULL)
682                 free(xd, M_ESP);
683         if (crp != NULL) {
684                 free(crp->crp_aad, M_ESP);
685                 crypto_freereq(crp);
686         }
687         CURVNET_RESTORE();
688         return error;
689 }
690 /*
691  * ESP output routine, called by ipsec[46]_perform_request().
692  */
693 static int
694 esp_output(struct mbuf *m, struct secpolicy *sp, struct secasvar *sav,
695     u_int idx, int skip, int protoff)
696 {
697         IPSEC_DEBUG_DECLARE(char buf[IPSEC_ADDRSTRLEN]);
698         struct cryptop *crp;
699         const struct auth_hash *esph;
700         const struct enc_xform *espx;
701         struct mbuf *mo = NULL;
702         struct xform_data *xd;
703         struct secasindex *saidx;
704         unsigned char *pad;
705         uint8_t *ivp;
706         uint64_t cntr;
707         crypto_session_t cryptoid;
708         int hlen, rlen, padding, blks, alen, i, roff;
709         int error, maxpacketsize;
710         uint8_t prot;
711         uint32_t seqh;
712         const struct crypto_session_params *csp;
713
714         SECASVAR_RLOCK_TRACKER;
715
716         IPSEC_ASSERT(sav != NULL, ("null SA"));
717         esph = sav->tdb_authalgxform;
718         espx = sav->tdb_encalgxform;
719         IPSEC_ASSERT(espx != NULL, ("null encoding xform"));
720
721         if (sav->flags & SADB_X_EXT_OLD)
722                 hlen = sizeof (struct esp) + sav->ivlen;
723         else
724                 hlen = sizeof (struct newesp) + sav->ivlen;
725
726         rlen = m->m_pkthdr.len - skip;  /* Raw payload length. */
727         /*
728          * RFC4303 2.4 Requires 4 byte alignment.
729          * Old versions of FreeBSD can't decrypt partial blocks encrypted
730          * with AES-CTR. Align payload to native_blocksize (16 bytes)
731          * in order to preserve compatibility.
732          */
733         if (SAV_ISCTR(sav) && V_esp_ctr_compatibility)
734                 blks = MAX(4, espx->native_blocksize);  /* Cipher blocksize */
735         else
736                 blks = MAX(4, espx->blocksize);
737
738         /* XXX clamp padding length a la KAME??? */
739         padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
740
741         alen = xform_ah_authsize(esph);
742
743         ESPSTAT_INC(esps_output);
744
745         saidx = &sav->sah->saidx;
746         /* Check for maximum packet size violations. */
747         switch (saidx->dst.sa.sa_family) {
748 #ifdef INET
749         case AF_INET:
750                 maxpacketsize = IP_MAXPACKET;
751                 break;
752 #endif /* INET */
753 #ifdef INET6
754         case AF_INET6:
755                 maxpacketsize = IPV6_MAXPACKET;
756                 break;
757 #endif /* INET6 */
758         default:
759                 DPRINTF(("%s: unknown/unsupported protocol "
760                     "family %d, SA %s/%08lx\n", __func__,
761                     saidx->dst.sa.sa_family, ipsec_address(&saidx->dst,
762                         buf, sizeof(buf)), (u_long) ntohl(sav->spi)));
763                 ESPSTAT_INC(esps_nopf);
764                 error = EPFNOSUPPORT;
765                 goto bad;
766         }
767         /*
768         DPRINTF(("%s: skip %d hlen %d rlen %d padding %d alen %d blksd %d\n",
769                 __func__, skip, hlen, rlen, padding, alen, blks)); */
770         if (skip + hlen + rlen + padding + alen > maxpacketsize) {
771                 DPRINTF(("%s: packet in SA %s/%08lx got too big "
772                     "(len %u, max len %u)\n", __func__,
773                     ipsec_address(&saidx->dst, buf, sizeof(buf)),
774                     (u_long) ntohl(sav->spi),
775                     skip + hlen + rlen + padding + alen, maxpacketsize));
776                 ESPSTAT_INC(esps_toobig);
777                 error = EMSGSIZE;
778                 goto bad;
779         }
780
781         /* Update the counters. */
782         ESPSTAT_ADD(esps_obytes, m->m_pkthdr.len - skip);
783
784         m = m_unshare(m, M_NOWAIT);
785         if (m == NULL) {
786                 DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
787                     ipsec_address(&saidx->dst, buf, sizeof(buf)),
788                     (u_long) ntohl(sav->spi)));
789                 ESPSTAT_INC(esps_hdrops);
790                 error = ENOBUFS;
791                 goto bad;
792         }
793
794         /* Inject ESP header. */
795         mo = m_makespace(m, skip, hlen, &roff);
796         if (mo == NULL) {
797                 DPRINTF(("%s: %u byte ESP hdr inject failed for SA %s/%08lx\n",
798                     __func__, hlen, ipsec_address(&saidx->dst, buf,
799                     sizeof(buf)), (u_long) ntohl(sav->spi)));
800                 ESPSTAT_INC(esps_hdrops);       /* XXX diffs from openbsd */
801                 error = ENOBUFS;
802                 goto bad;
803         }
804
805         /* Initialize ESP header. */
806         bcopy((caddr_t) &sav->spi, mtod(mo, caddr_t) + roff,
807             sizeof(uint32_t));
808         SECASVAR_RLOCK(sav);
809         if (sav->replay) {
810                 uint32_t replay;
811
812                 SECREPLAY_LOCK(sav->replay);
813 #ifdef REGRESSION
814                 /* Emulate replay attack when ipsec_replay is TRUE. */
815                 if (!V_ipsec_replay)
816 #endif
817                         sav->replay->count++;
818                 replay = htonl((uint32_t)sav->replay->count);
819
820                 bcopy((caddr_t) &replay, mtod(mo, caddr_t) + roff +
821                     sizeof(uint32_t), sizeof(uint32_t));
822
823                 seqh = htonl((uint32_t)(sav->replay->count >> IPSEC_SEQH_SHIFT));
824                 SECREPLAY_UNLOCK(sav->replay);
825         }
826         cryptoid = sav->tdb_cryptoid;
827         if (SAV_ISCTRORGCM(sav) || SAV_ISCHACHA(sav))
828                 cntr = sav->cntr++;
829         SECASVAR_RUNLOCK(sav);
830
831         /*
832          * Add padding -- better to do it ourselves than use the crypto engine,
833          * although if/when we support compression, we'd have to do that.
834          */
835         pad = (u_char *) m_pad(m, padding + alen);
836         if (pad == NULL) {
837                 DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
838                     ipsec_address(&saidx->dst, buf, sizeof(buf)),
839                     (u_long) ntohl(sav->spi)));
840                 m = NULL;               /* NB: free'd by m_pad */
841                 error = ENOBUFS;
842                 goto bad;
843         }
844
845         /*
846          * Add padding: random, zero, or self-describing.
847          * XXX catch unexpected setting
848          */
849         switch (sav->flags & SADB_X_EXT_PMASK) {
850         case SADB_X_EXT_PRAND:
851                 arc4random_buf(pad, padding - 2);
852                 break;
853         case SADB_X_EXT_PZERO:
854                 bzero(pad, padding - 2);
855                 break;
856         case SADB_X_EXT_PSEQ:
857                 for (i = 0; i < padding - 2; i++)
858                         pad[i] = i+1;
859                 break;
860         }
861
862         /* Fix padding length and Next Protocol in padding itself. */
863         pad[padding - 2] = padding - 2;
864         m_copydata(m, protoff, sizeof(u_int8_t), pad + padding - 1);
865
866         /* Fix Next Protocol in IPv4/IPv6 header. */
867         prot = IPPROTO_ESP;
868         m_copyback(m, protoff, sizeof(u_int8_t), (u_char *) &prot);
869
870         /* Get crypto descriptor. */
871         crp = crypto_getreq(cryptoid, M_NOWAIT);
872         if (crp == NULL) {
873                 DPRINTF(("%s: failed to acquire crypto descriptor\n",
874                         __func__));
875                 ESPSTAT_INC(esps_crypto);
876                 error = ENOBUFS;
877                 goto bad;
878         }
879
880         /* IPsec-specific opaque crypto info. */
881         xd = malloc(sizeof(struct xform_data), M_ESP, M_NOWAIT | M_ZERO);
882         if (xd == NULL) {
883                 DPRINTF(("%s: failed to allocate xform_data\n", __func__));
884                 goto xd_fail;
885         }
886
887         /* Encryption descriptor. */
888         crp->crp_payload_start = skip + hlen;
889         crp->crp_payload_length = m->m_pkthdr.len - (skip + hlen + alen);
890         crp->crp_op = CRYPTO_OP_ENCRYPT;
891
892         /* Generate cipher and ESP IVs. */
893         ivp = &crp->crp_iv[0];
894         if (SAV_ISCTRORGCM(sav) || SAV_ISCHACHA(sav)) {
895                 /*
896                  * See comment in esp_input() for details on the
897                  * cipher IV.  A simple per-SA counter stored in
898                  * 'cntr' is used as the explicit ESP IV.
899                  */
900                 memcpy(ivp, sav->key_enc->key_data +
901                     _KEYLEN(sav->key_enc) - 4, 4);
902                 be64enc(&ivp[4], cntr);
903                 if (SAV_ISCTR(sav)) {
904                         be32enc(&ivp[sav->ivlen + 4], 1);
905                 }
906                 m_copyback(m, skip + hlen - sav->ivlen, sav->ivlen, &ivp[4]);
907                 crp->crp_flags |= CRYPTO_F_IV_SEPARATE;
908         } else if (sav->ivlen != 0) {
909                 arc4rand(ivp, sav->ivlen, 0);
910                 crp->crp_iv_start = skip + hlen - sav->ivlen;
911                 m_copyback(m, crp->crp_iv_start, sav->ivlen, ivp);
912         }
913
914         /* Callback parameters */
915         xd->sp = sp;
916         xd->sav = sav;
917         xd->idx = idx;
918         xd->cryptoid = cryptoid;
919         xd->vnet = curvnet;
920
921         /* Crypto operation descriptor. */
922         crp->crp_flags |= CRYPTO_F_CBIFSYNC;
923         crypto_use_mbuf(crp, m);
924         crp->crp_callback = esp_output_cb;
925         crp->crp_opaque = xd;
926
927         if (esph) {
928                 /* Authentication descriptor. */
929                 crp->crp_op |= CRYPTO_OP_COMPUTE_DIGEST;
930                 if (SAV_ISGCM(sav) || SAV_ISCHACHA(sav))
931                         crp->crp_aad_length = 8; /* RFC4106 5, SPI + SN */
932                 else
933                         crp->crp_aad_length = hlen;
934
935                 csp = crypto_get_params(crp->crp_session);
936                 if (csp->csp_flags & CSP_F_SEPARATE_AAD &&
937                     sav->replay != NULL) {
938                         int aad_skip;
939
940                         crp->crp_aad_length += sizeof(seqh);
941                         crp->crp_aad = malloc(crp->crp_aad_length, M_ESP, M_NOWAIT);
942                         if (crp->crp_aad == NULL) {
943                                 DPRINTF(("%s: failed to allocate xform_data\n",
944                                          __func__));
945                                 goto crp_aad_fail;
946                         }
947
948                         /* SPI */
949                         m_copydata(m, skip, SPI_SIZE, crp->crp_aad);
950                         aad_skip = SPI_SIZE;
951
952                         /* ESN */
953                         bcopy(&seqh, (char *)crp->crp_aad + aad_skip, sizeof(seqh));
954                         aad_skip += sizeof(seqh);
955
956                         /* Rest of aad */
957                         if (crp->crp_aad_length - aad_skip > 0)
958                                 m_copydata(m, skip + SPI_SIZE,
959                                            crp->crp_aad_length - aad_skip,
960                                            (char *)crp->crp_aad + aad_skip);
961                 } else
962                         crp->crp_aad_start = skip;
963
964                 if (csp->csp_flags & CSP_F_ESN && sav->replay != NULL)
965                         memcpy(crp->crp_esn, &seqh, sizeof(seqh));
966
967                 crp->crp_digest_start = m->m_pkthdr.len - alen;
968         }
969
970         if (V_async_crypto)
971                 return (crypto_dispatch_async(crp, CRYPTO_ASYNC_ORDERED));
972         else
973                 return (crypto_dispatch(crp));
974
975 crp_aad_fail:
976         free(xd, M_ESP);
977 xd_fail:
978         crypto_freereq(crp);
979         ESPSTAT_INC(esps_crypto);
980         error = ENOBUFS;
981 bad:
982         if (m)
983                 m_freem(m);
984         key_freesav(&sav);
985         key_freesp(&sp);
986         return (error);
987 }
988 /*
989  * ESP output callback from the crypto driver.
990  */
991 static int
992 esp_output_cb(struct cryptop *crp)
993 {
994         struct xform_data *xd;
995         struct secpolicy *sp;
996         struct secasvar *sav;
997         struct mbuf *m;
998         crypto_session_t cryptoid;
999         u_int idx;
1000         int error;
1001
1002         xd = (struct xform_data *) crp->crp_opaque;
1003         CURVNET_SET(xd->vnet);
1004         m = crp->crp_buf.cb_mbuf;
1005         sp = xd->sp;
1006         sav = xd->sav;
1007         idx = xd->idx;
1008         cryptoid = xd->cryptoid;
1009
1010         /* Check for crypto errors. */
1011         if (crp->crp_etype) {
1012                 if (crp->crp_etype == EAGAIN) {
1013                         /* Reset the session ID */
1014                         if (ipsec_updateid(sav, &crp->crp_session, &cryptoid) != 0)
1015                                 crypto_freesession(cryptoid);
1016                         xd->cryptoid = crp->crp_session;
1017                         CURVNET_RESTORE();
1018                         return (crypto_dispatch(crp));
1019                 }
1020                 ESPSTAT_INC(esps_noxform);
1021                 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
1022                 error = crp->crp_etype;
1023                 m_freem(m);
1024                 goto bad;
1025         }
1026
1027         /* Shouldn't happen... */
1028         if (m == NULL) {
1029                 ESPSTAT_INC(esps_crypto);
1030                 DPRINTF(("%s: bogus returned buffer from crypto\n", __func__));
1031                 error = EINVAL;
1032                 goto bad;
1033         }
1034         free(xd, M_ESP);
1035         free(crp->crp_aad, M_ESP);
1036         crypto_freereq(crp);
1037         ESPSTAT_INC(esps_hist[sav->alg_enc]);
1038         if (sav->tdb_authalgxform != NULL)
1039                 AHSTAT_INC(ahs_hist[sav->alg_auth]);
1040
1041 #ifdef REGRESSION
1042         /* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
1043         if (V_ipsec_integrity) {
1044                 static unsigned char ipseczeroes[AH_HMAC_MAXHASHLEN];
1045                 const struct auth_hash *esph;
1046
1047                 /*
1048                  * Corrupt HMAC if we want to test integrity verification of
1049                  * the other side.
1050                  */
1051                 esph = sav->tdb_authalgxform;
1052                 if (esph !=  NULL) {
1053                         int alen;
1054
1055                         alen = xform_ah_authsize(esph);
1056                         m_copyback(m, m->m_pkthdr.len - alen,
1057                             alen, ipseczeroes);
1058                 }
1059         }
1060 #endif
1061
1062         /* NB: m is reclaimed by ipsec_process_done. */
1063         error = ipsec_process_done(m, sp, sav, idx);
1064         CURVNET_RESTORE();
1065         return (error);
1066 bad:
1067         free(xd, M_ESP);
1068         free(crp->crp_aad, M_ESP);
1069         crypto_freereq(crp);
1070         key_freesav(&sav);
1071         key_freesp(&sp);
1072         CURVNET_RESTORE();
1073         return (error);
1074 }
1075
1076 static struct xformsw esp_xformsw = {
1077         .xf_type =      XF_ESP,
1078         .xf_name =      "IPsec ESP",
1079         .xf_init =      esp_init,
1080         .xf_cleanup =   esp_cleanup,
1081         .xf_input =     esp_input,
1082         .xf_output =    esp_output,
1083 };
1084
1085 SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
1086     xform_attach, &esp_xformsw);
1087 SYSUNINIT(esp_xform_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
1088     xform_detach, &esp_xformsw);