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