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