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