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