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