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