xform_esp.c revision 1.91 1 /* $NetBSD: xform_esp.c,v 1.91 2018/05/30 16:32:26 maxv Exp $ */
2 /* $FreeBSD: xform_esp.c,v 1.2.2.1 2003/01/24 05:11:36 sam Exp $ */
3 /* $OpenBSD: ip_esp.c,v 1.69 2001/06/26 06:18:59 angelos Exp $ */
4
5 /*
6 * The authors of this code are John Ioannidis (ji (at) tla.org),
7 * Angelos D. Keromytis (kermit (at) csd.uch.gr) and
8 * Niels Provos (provos (at) physnet.uni-hamburg.de).
9 *
10 * The original version of this code was written by John Ioannidis
11 * for BSD/OS in Athens, Greece, in November 1995.
12 *
13 * Ported to OpenBSD and NetBSD, with additional transforms, in December 1996,
14 * by Angelos D. Keromytis.
15 *
16 * Additional transforms and features in 1997 and 1998 by Angelos D. Keromytis
17 * and Niels Provos.
18 *
19 * Additional features in 1999 by Angelos D. Keromytis.
20 *
21 * Copyright (C) 1995, 1996, 1997, 1998, 1999 by John Ioannidis,
22 * Angelos D. Keromytis and Niels Provos.
23 * Copyright (c) 2001 Angelos D. Keromytis.
24 *
25 * Permission to use, copy, and modify this software with or without fee
26 * is hereby granted, provided that this entire notice is included in
27 * all copies of any software which is or includes a copy or
28 * modification of this software.
29 * You may use this code under the GNU public license if you so wish. Please
30 * contribute changes back to the authors under this freer than GPL license
31 * so that we may further the use of strong encryption without limitations to
32 * all.
33 *
34 * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
35 * IMPLIED WARRANTY. IN PARTICULAR, NONE OF THE AUTHORS MAKES ANY
36 * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
37 * MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
38 * PURPOSE.
39 */
40
41 #include <sys/cdefs.h>
42 __KERNEL_RCSID(0, "$NetBSD: xform_esp.c,v 1.91 2018/05/30 16:32:26 maxv Exp $");
43
44 #if defined(_KERNEL_OPT)
45 #include "opt_inet.h"
46 #include "opt_ipsec.h"
47 #endif
48
49 #include <sys/param.h>
50 #include <sys/systm.h>
51 #include <sys/mbuf.h>
52 #include <sys/socket.h>
53 #include <sys/syslog.h>
54 #include <sys/kernel.h>
55 #include <sys/sysctl.h>
56 #include <sys/cprng.h>
57 #include <sys/pool.h>
58 #include <sys/pserialize.h>
59
60 #include <net/if.h>
61
62 #include <netinet/in.h>
63 #include <netinet/in_systm.h>
64 #include <netinet/ip.h>
65 #include <netinet/ip_ecn.h>
66 #include <netinet/ip6.h>
67
68 #include <net/route.h>
69 #include <netipsec/ipsec.h>
70 #include <netipsec/ipsec_private.h>
71 #include <netipsec/ah.h>
72 #include <netipsec/ah_var.h>
73 #include <netipsec/esp.h>
74 #include <netipsec/esp_var.h>
75 #include <netipsec/xform.h>
76
77 #ifdef INET6
78 #include <netinet6/ip6_var.h>
79 #include <netipsec/ipsec6.h>
80 #endif
81
82 #include <netipsec/key.h>
83 #include <netipsec/key_debug.h>
84
85 #include <opencrypto/cryptodev.h>
86
87 percpu_t *espstat_percpu;
88
89 int esp_enable = 1;
90
91 static int esp_max_ivlen; /* max iv length over all algorithms */
92
93 static int esp_input_cb(struct cryptop *op);
94 static int esp_output_cb(struct cryptop *crp);
95
96 const uint8_t esp_stats[256] = { SADB_EALG_STATS_INIT };
97
98 static pool_cache_t esp_tdb_crypto_pool_cache;
99 static size_t esp_pool_item_size;
100
101 /*
102 * NB: this is public for use by the PF_KEY support.
103 * NB: if you add support here; be sure to add code to esp_attach below!
104 */
105 const struct enc_xform *
106 esp_algorithm_lookup(int alg)
107 {
108
109 switch (alg) {
110 case SADB_EALG_DESCBC:
111 return &enc_xform_des;
112 case SADB_EALG_3DESCBC:
113 return &enc_xform_3des;
114 case SADB_X_EALG_AES:
115 return &enc_xform_rijndael128;
116 case SADB_X_EALG_BLOWFISHCBC:
117 return &enc_xform_blf;
118 case SADB_X_EALG_CAST128CBC:
119 return &enc_xform_cast5;
120 case SADB_X_EALG_SKIPJACK:
121 return &enc_xform_skipjack;
122 case SADB_X_EALG_CAMELLIACBC:
123 return &enc_xform_camellia;
124 case SADB_X_EALG_AESCTR:
125 return &enc_xform_aes_ctr;
126 case SADB_X_EALG_AESGCM16:
127 return &enc_xform_aes_gcm;
128 case SADB_X_EALG_AESGMAC:
129 return &enc_xform_aes_gmac;
130 case SADB_EALG_NULL:
131 return &enc_xform_null;
132 }
133 return NULL;
134 }
135
136 size_t
137 esp_hdrsiz(const struct secasvar *sav)
138 {
139 size_t size;
140
141 if (sav != NULL) {
142 /*XXX not right for null algorithm--does it matter??*/
143 KASSERT(sav->tdb_encalgxform != NULL);
144 if (sav->flags & SADB_X_EXT_OLD)
145 size = sizeof(struct esp);
146 else
147 size = sizeof(struct newesp);
148 size += sav->tdb_encalgxform->ivsize + 9;
149 /*XXX need alg check???*/
150 if (sav->tdb_authalgxform != NULL && sav->replay)
151 size += ah_hdrsiz(sav);
152 } else {
153 /*
154 * base header size
155 * + max iv length for CBC mode
156 * + max pad length
157 * + sizeof(pad length field)
158 * + sizeof(next header field)
159 * + max icv supported.
160 */
161 size = sizeof(struct newesp) + esp_max_ivlen + 9 +
162 ah_hdrsiz(NULL);
163 }
164 return size;
165 }
166
167 /*
168 * esp_init() is called when an SPI is being set up.
169 */
170 static int
171 esp_init(struct secasvar *sav, const struct xformsw *xsp)
172 {
173 const struct enc_xform *txform;
174 struct cryptoini cria, crie, *cr;
175 int keylen;
176 int error;
177
178 txform = esp_algorithm_lookup(sav->alg_enc);
179 if (txform == NULL) {
180 DPRINTF(("%s: unsupported encryption algorithm %d\n", __func__,
181 sav->alg_enc));
182 return EINVAL;
183 }
184 if (sav->key_enc == NULL) {
185 DPRINTF(("%s: no encoding key for %s algorithm\n", __func__,
186 txform->name));
187 return EINVAL;
188 }
189 if ((sav->flags&(SADB_X_EXT_OLD|SADB_X_EXT_IV4B)) == SADB_X_EXT_IV4B) {
190 DPRINTF(("%s: 4-byte IV not supported with protocol\n",
191 __func__));
192 return EINVAL;
193 }
194 keylen = _KEYLEN(sav->key_enc);
195 if (txform->minkey > keylen || keylen > txform->maxkey) {
196 DPRINTF(("%s: invalid key length %u, must be in "
197 "the range [%u..%u] for algorithm %s\n", __func__,
198 keylen, txform->minkey, txform->maxkey, txform->name));
199 return EINVAL;
200 }
201
202 sav->ivlen = txform->ivsize;
203
204 /*
205 * Setup AH-related state.
206 */
207 if (sav->alg_auth != 0) {
208 error = ah_init0(sav, xsp, &cria);
209 if (error)
210 return error;
211 }
212
213 /* NB: override anything set in ah_init0 */
214 sav->tdb_xform = xsp;
215 sav->tdb_encalgxform = txform;
216
217 switch (sav->alg_enc) {
218 case SADB_X_EALG_AESGCM16:
219 case SADB_X_EALG_AESGMAC:
220 switch (keylen) {
221 case 20:
222 sav->alg_auth = SADB_X_AALG_AES128GMAC;
223 sav->tdb_authalgxform = &auth_hash_gmac_aes_128;
224 break;
225 case 28:
226 sav->alg_auth = SADB_X_AALG_AES192GMAC;
227 sav->tdb_authalgxform = &auth_hash_gmac_aes_192;
228 break;
229 case 36:
230 sav->alg_auth = SADB_X_AALG_AES256GMAC;
231 sav->tdb_authalgxform = &auth_hash_gmac_aes_256;
232 break;
233 default:
234 DPRINTF(("%s: invalid key length %u, must be either of "
235 "20, 28 or 36\n", __func__, keylen));
236 return EINVAL;
237 }
238
239 memset(&cria, 0, sizeof(cria));
240 cria.cri_alg = sav->tdb_authalgxform->type;
241 cria.cri_klen = _KEYBITS(sav->key_enc);
242 cria.cri_key = _KEYBUF(sav->key_enc);
243 break;
244 default:
245 break;
246 }
247
248 /* Initialize crypto session. */
249 memset(&crie, 0, sizeof(crie));
250 crie.cri_alg = sav->tdb_encalgxform->type;
251 crie.cri_klen = _KEYBITS(sav->key_enc);
252 crie.cri_key = _KEYBUF(sav->key_enc);
253 /* XXX Rounds ? */
254
255 if (sav->tdb_authalgxform && sav->tdb_encalgxform) {
256 /* init both auth & enc */
257 crie.cri_next = &cria;
258 cr = &crie;
259 } else if (sav->tdb_encalgxform) {
260 cr = &crie;
261 } else if (sav->tdb_authalgxform) {
262 cr = &cria;
263 } else {
264 /* XXX cannot happen? */
265 DPRINTF(("%s: no encoding OR authentication xform!\n",
266 __func__));
267 return EINVAL;
268 }
269
270 return crypto_newsession(&sav->tdb_cryptoid, cr, crypto_support);
271 }
272
273 /*
274 * Paranoia.
275 */
276 static int
277 esp_zeroize(struct secasvar *sav)
278 {
279 /* NB: ah_zerorize free's the crypto session state */
280 int error = ah_zeroize(sav);
281
282 if (sav->key_enc) {
283 explicit_memset(_KEYBUF(sav->key_enc), 0,
284 _KEYLEN(sav->key_enc));
285 }
286 sav->tdb_encalgxform = NULL;
287 sav->tdb_xform = NULL;
288 return error;
289 }
290
291 /*
292 * ESP input processing, called (eventually) through the protocol switch.
293 */
294 static int
295 esp_input(struct mbuf *m, struct secasvar *sav, int skip, int protoff)
296 {
297 const struct auth_hash *esph;
298 const struct enc_xform *espx;
299 struct tdb_crypto *tc;
300 int plen, alen, hlen, error, stat = ESP_STAT_CRYPTO;
301 struct newesp *esp;
302 struct cryptodesc *crde;
303 struct cryptop *crp;
304
305 KASSERT(sav != NULL);
306 KASSERT(sav->tdb_encalgxform != NULL);
307 KASSERTMSG((skip&3) == 0 && (m->m_pkthdr.len&3) == 0,
308 "misaligned packet, skip %u pkt len %u",
309 skip, m->m_pkthdr.len);
310
311 /* XXX don't pullup, just copy header */
312 M_REGION_GET(esp, struct newesp *, m, skip, sizeof(struct newesp));
313 if (esp == NULL) {
314 /* m already freed */
315 return ENOBUFS;
316 }
317
318 esph = sav->tdb_authalgxform;
319 espx = sav->tdb_encalgxform;
320
321 /* Determine the ESP header length */
322 if (sav->flags & SADB_X_EXT_OLD)
323 hlen = sizeof(struct esp) + sav->ivlen;
324 else
325 hlen = sizeof(struct newesp) + sav->ivlen;
326 /* Authenticator hash size */
327 alen = esph ? esph->authsize : 0;
328
329 /*
330 * Verify payload length is multiple of encryption algorithm
331 * block size.
332 *
333 * NB: This works for the null algorithm because the blocksize
334 * is 4 and all packets must be 4-byte aligned regardless
335 * of the algorithm.
336 */
337 plen = m->m_pkthdr.len - (skip + hlen + alen);
338 if ((plen & (espx->blocksize - 1)) || (plen <= 0)) {
339 char buf[IPSEC_ADDRSTRLEN];
340 DPRINTF(("%s: payload of %d octets not a multiple of %d octets,"
341 " SA %s/%08lx\n", __func__, plen, espx->blocksize,
342 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
343 (u_long) ntohl(sav->spi)));
344 stat = ESP_STAT_BADILEN;
345 error = EINVAL;
346 goto out;
347 }
348
349 /*
350 * Check sequence number.
351 */
352 if (esph && sav->replay && !ipsec_chkreplay(ntohl(esp->esp_seq), sav)) {
353 char logbuf[IPSEC_LOGSASTRLEN];
354 DPRINTF(("%s: packet replay check for %s\n", __func__,
355 ipsec_logsastr(sav, logbuf, sizeof(logbuf))));
356 stat = ESP_STAT_REPLAY;
357 error = EACCES;
358 goto out;
359 }
360
361 /* Update the counters */
362 ESP_STATADD(ESP_STAT_IBYTES, m->m_pkthdr.len - skip - hlen - alen);
363
364 /* Get crypto descriptors */
365 crp = crypto_getreq(esph && espx ? 2 : 1);
366 if (crp == NULL) {
367 DPRINTF(("%s: failed to acquire crypto descriptors\n",
368 __func__));
369 error = ENOBUFS;
370 goto out;
371 }
372
373 /* Get IPsec-specific opaque pointer */
374 size_t extra __diagused = esph == NULL ? 0 : alen;
375 KASSERTMSG(sizeof(*tc) + extra <= esp_pool_item_size,
376 "sizeof(*tc) + extra=%zu > esp_pool_item_size=%zu\n",
377 sizeof(*tc) + extra, esp_pool_item_size);
378 tc = pool_cache_get(esp_tdb_crypto_pool_cache, PR_NOWAIT);
379 if (tc == NULL) {
380 DPRINTF(("%s: failed to allocate tdb_crypto\n", __func__));
381 error = ENOBUFS;
382 goto out1;
383 }
384
385 error = m_makewritable(&m, 0, m->m_pkthdr.len, M_NOWAIT);
386 if (error) {
387 DPRINTF(("%s: m_makewritable failed\n", __func__));
388 goto out2;
389 }
390
391 if (esph) {
392 struct cryptodesc *crda;
393
394 KASSERT(crp->crp_desc != NULL);
395 crda = crp->crp_desc;
396
397 /* Authentication descriptor */
398 crda->crd_skip = skip;
399 if (espx && espx->type == CRYPTO_AES_GCM_16)
400 crda->crd_len = hlen - sav->ivlen;
401 else
402 crda->crd_len = m->m_pkthdr.len - (skip + alen);
403 crda->crd_inject = m->m_pkthdr.len - alen;
404
405 crda->crd_alg = esph->type;
406 if (espx && (espx->type == CRYPTO_AES_GCM_16 ||
407 espx->type == CRYPTO_AES_GMAC)) {
408 crda->crd_key = _KEYBUF(sav->key_enc);
409 crda->crd_klen = _KEYBITS(sav->key_enc);
410 } else {
411 crda->crd_key = _KEYBUF(sav->key_auth);
412 crda->crd_klen = _KEYBITS(sav->key_auth);
413 }
414
415 /* Copy the authenticator */
416 m_copydata(m, m->m_pkthdr.len - alen, alen, (tc + 1));
417
418 /* Chain authentication request */
419 crde = crda->crd_next;
420 } else {
421 crde = crp->crp_desc;
422 }
423
424 {
425 int s = pserialize_read_enter();
426
427 /*
428 * Take another reference to the SA for opencrypto callback.
429 */
430 if (__predict_false(sav->state == SADB_SASTATE_DEAD)) {
431 pserialize_read_exit(s);
432 stat = ESP_STAT_NOTDB;
433 error = ENOENT;
434 goto out2;
435 }
436 KEY_SA_REF(sav);
437 pserialize_read_exit(s);
438 }
439
440 /* Crypto operation descriptor */
441 crp->crp_ilen = m->m_pkthdr.len; /* Total input length */
442 crp->crp_flags = CRYPTO_F_IMBUF;
443 crp->crp_buf = m;
444 crp->crp_callback = esp_input_cb;
445 crp->crp_sid = sav->tdb_cryptoid;
446 crp->crp_opaque = tc;
447
448 /* These are passed as-is to the callback */
449 tc->tc_spi = sav->spi;
450 tc->tc_dst = sav->sah->saidx.dst;
451 tc->tc_proto = sav->sah->saidx.proto;
452 tc->tc_protoff = protoff;
453 tc->tc_skip = skip;
454 tc->tc_sav = sav;
455
456 /* Decryption descriptor */
457 if (espx) {
458 KASSERTMSG(crde != NULL, "null esp crypto descriptor");
459 crde->crd_skip = skip + hlen;
460 if (espx->type == CRYPTO_AES_GMAC)
461 crde->crd_len = 0;
462 else
463 crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
464 crde->crd_inject = skip + hlen - sav->ivlen;
465
466 crde->crd_alg = espx->type;
467 crde->crd_key = _KEYBUF(sav->key_enc);
468 crde->crd_klen = _KEYBITS(sav->key_enc);
469 /* XXX Rounds ? */
470 }
471
472 return crypto_dispatch(crp);
473
474 out2:
475 pool_cache_put(esp_tdb_crypto_pool_cache, tc);
476 out1:
477 crypto_freereq(crp);
478 out:
479 ESP_STATINC(stat);
480 m_freem(m);
481 return error;
482 }
483
484 #ifdef INET6
485 #define IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff) do { \
486 if (saidx->dst.sa.sa_family == AF_INET6) { \
487 error = ipsec6_common_input_cb(m, sav, skip, protoff); \
488 } else { \
489 error = ipsec4_common_input_cb(m, sav, skip, protoff); \
490 } \
491 } while (0)
492 #else
493 #define IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff) \
494 (error = ipsec4_common_input_cb(m, sav, skip, protoff))
495 #endif
496
497 /*
498 * ESP input callback from the crypto driver.
499 */
500 static int
501 esp_input_cb(struct cryptop *crp)
502 {
503 char buf[IPSEC_ADDRSTRLEN];
504 uint8_t lastthree[3], aalg[AH_ALEN_MAX];
505 int hlen, skip, protoff, error;
506 struct mbuf *m;
507 const struct auth_hash *esph;
508 struct tdb_crypto *tc;
509 struct secasvar *sav;
510 struct secasindex *saidx;
511 void *ptr;
512 IPSEC_DECLARE_LOCK_VARIABLE;
513
514 KASSERT(crp->crp_desc != NULL);
515 KASSERT(crp->crp_opaque != NULL);
516
517 tc = crp->crp_opaque;
518 skip = tc->tc_skip;
519 protoff = tc->tc_protoff;
520 m = crp->crp_buf;
521
522 IPSEC_ACQUIRE_GLOBAL_LOCKS();
523
524 sav = tc->tc_sav;
525 saidx = &sav->sah->saidx;
526 KASSERTMSG(saidx->dst.sa.sa_family == AF_INET ||
527 saidx->dst.sa.sa_family == AF_INET6,
528 "unexpected protocol family %u", saidx->dst.sa.sa_family);
529
530 esph = sav->tdb_authalgxform;
531
532 /* Check for crypto errors */
533 if (crp->crp_etype) {
534 /* Reset the session ID */
535 if (sav->tdb_cryptoid != 0)
536 sav->tdb_cryptoid = crp->crp_sid;
537
538 if (crp->crp_etype == EAGAIN) {
539 KEY_SA_UNREF(&sav);
540 IPSEC_RELEASE_GLOBAL_LOCKS();
541 return crypto_dispatch(crp);
542 }
543
544 ESP_STATINC(ESP_STAT_NOXFORM);
545 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
546 error = crp->crp_etype;
547 goto bad;
548 }
549
550 ESP_STATINC(ESP_STAT_HIST + esp_stats[sav->alg_enc]);
551
552 /* If authentication was performed, check now. */
553 if (esph != NULL) {
554 /*
555 * If we have a tag, it means an IPsec-aware NIC did
556 * the verification for us. Otherwise we need to
557 * check the authentication calculation.
558 */
559 AH_STATINC(AH_STAT_HIST + ah_stats[sav->alg_auth]);
560 /* Copy the authenticator from the packet */
561 m_copydata(m, m->m_pkthdr.len - esph->authsize,
562 esph->authsize, aalg);
563
564 ptr = (tc + 1);
565
566 /* Verify authenticator */
567 if (!consttime_memequal(ptr, aalg, esph->authsize)) {
568 DPRINTF(("%s: authentication hash mismatch "
569 "for packet in SA %s/%08lx\n", __func__,
570 ipsec_address(&saidx->dst, buf,
571 sizeof(buf)), (u_long) ntohl(sav->spi)));
572 ESP_STATINC(ESP_STAT_BADAUTH);
573 error = EACCES;
574 goto bad;
575 }
576
577 /* Remove trailing authenticator */
578 m_adj(m, -(esph->authsize));
579 }
580
581 /* Release the crypto descriptors */
582 pool_cache_put(esp_tdb_crypto_pool_cache, tc);
583 tc = NULL;
584 crypto_freereq(crp);
585 crp = NULL;
586
587 /*
588 * Packet is now decrypted.
589 */
590 m->m_flags |= M_DECRYPTED;
591
592 /*
593 * Update replay sequence number, if appropriate.
594 */
595 if (sav->replay) {
596 uint32_t seq;
597
598 m_copydata(m, skip + offsetof(struct newesp, esp_seq),
599 sizeof(seq), &seq);
600 if (ipsec_updatereplay(ntohl(seq), sav)) {
601 char logbuf[IPSEC_LOGSASTRLEN];
602 DPRINTF(("%s: packet replay check for %s\n", __func__,
603 ipsec_logsastr(sav, logbuf, sizeof(logbuf))));
604 ESP_STATINC(ESP_STAT_REPLAY);
605 error = EACCES;
606 goto bad;
607 }
608 }
609
610 /* Determine the ESP header length */
611 if (sav->flags & SADB_X_EXT_OLD)
612 hlen = sizeof(struct esp) + sav->ivlen;
613 else
614 hlen = sizeof(struct newesp) + sav->ivlen;
615
616 /* Remove the ESP header and IV from the mbuf. */
617 error = m_striphdr(m, skip, hlen);
618 if (error) {
619 ESP_STATINC(ESP_STAT_HDROPS);
620 DPRINTF(("%s: bad mbuf chain, SA %s/%08lx\n", __func__,
621 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
622 (u_long) ntohl(sav->spi)));
623 goto bad;
624 }
625
626 /* Save the last three bytes of decrypted data */
627 m_copydata(m, m->m_pkthdr.len - 3, 3, lastthree);
628
629 /* Verify pad length */
630 if (lastthree[1] + 2 > m->m_pkthdr.len - skip) {
631 ESP_STATINC(ESP_STAT_BADILEN);
632 DPRINTF(("%s: invalid padding length %d "
633 "for %u byte packet in SA %s/%08lx\n", __func__,
634 lastthree[1], m->m_pkthdr.len - skip,
635 ipsec_address(&sav->sah->saidx.dst, buf, sizeof(buf)),
636 (u_long) ntohl(sav->spi)));
637 error = EINVAL;
638 goto bad;
639 }
640
641 /* Verify correct decryption by checking the last padding bytes */
642 if ((sav->flags & SADB_X_EXT_PMASK) != SADB_X_EXT_PRAND) {
643 if (lastthree[1] != lastthree[0] && lastthree[1] != 0) {
644 ESP_STATINC(ESP_STAT_BADENC);
645 DPRINTF(("%s: decryption failed for packet in SA "
646 "%s/%08lx\n", __func__,
647 ipsec_address(&sav->sah->saidx.dst, buf,
648 sizeof(buf)), (u_long) ntohl(sav->spi)));
649 DPRINTF(("%s: %x %x\n", __func__, lastthree[0],
650 lastthree[1]));
651 error = EINVAL;
652 goto bad;
653 }
654 }
655
656 /* Trim the mbuf chain to remove trailing authenticator and padding */
657 m_adj(m, -(lastthree[1] + 2));
658
659 /* Restore the Next Protocol field */
660 m_copyback(m, protoff, sizeof(uint8_t), lastthree + 2);
661
662 IPSEC_COMMON_INPUT_CB(m, sav, skip, protoff);
663
664 KEY_SA_UNREF(&sav);
665 IPSEC_RELEASE_GLOBAL_LOCKS();
666 return error;
667 bad:
668 if (sav)
669 KEY_SA_UNREF(&sav);
670 IPSEC_RELEASE_GLOBAL_LOCKS();
671 if (m != NULL)
672 m_freem(m);
673 if (tc != NULL)
674 pool_cache_put(esp_tdb_crypto_pool_cache, tc);
675 if (crp != NULL)
676 crypto_freereq(crp);
677 return error;
678 }
679
680 /*
681 * ESP output routine, called by ipsec[46]_process_packet().
682 */
683 static int
684 esp_output(struct mbuf *m, const struct ipsecrequest *isr, struct secasvar *sav,
685 int skip, int protoff)
686 {
687 char buf[IPSEC_ADDRSTRLEN];
688 const struct enc_xform *espx;
689 const struct auth_hash *esph;
690 int hlen, rlen, tlen, padlen, blks, alen, i, roff;
691 struct mbuf *mo = NULL;
692 struct tdb_crypto *tc;
693 struct secasindex *saidx;
694 unsigned char *tail;
695 uint8_t prot;
696 int error, maxpacketsize;
697 struct esptail *esptail;
698
699 struct cryptodesc *crde = NULL, *crda = NULL;
700 struct cryptop *crp;
701
702 esph = sav->tdb_authalgxform;
703 espx = sav->tdb_encalgxform;
704 KASSERT(espx != NULL);
705
706 if (sav->flags & SADB_X_EXT_OLD)
707 hlen = sizeof(struct esp) + sav->ivlen;
708 else
709 hlen = sizeof(struct newesp) + sav->ivlen;
710
711 if (esph)
712 alen = esph->authsize;
713 else
714 alen = 0;
715
716 /*
717 * NB: The null encoding transform has a blocksize of 4
718 * so that headers are properly aligned.
719 */
720 blks = espx->blocksize; /* IV blocksize */
721
722 /* Raw payload length. */
723 rlen = m->m_pkthdr.len - skip;
724
725 /* Encryption padding. */
726 padlen = ((blks - ((rlen + sizeof(struct esptail)) % blks)) % blks);
727
728 /* Length of what we append (tail). */
729 tlen = padlen + sizeof(struct esptail) + alen;
730
731 ESP_STATINC(ESP_STAT_OUTPUT);
732
733 saidx = &sav->sah->saidx;
734 /* Check for maximum packet size violations. */
735 switch (saidx->dst.sa.sa_family) {
736 #ifdef INET
737 case AF_INET:
738 maxpacketsize = IP_MAXPACKET;
739 break;
740 #endif
741 #ifdef INET6
742 case AF_INET6:
743 maxpacketsize = IPV6_MAXPACKET;
744 break;
745 #endif
746 default:
747 DPRINTF(("%s: unknown/unsupported protocol family %d, "
748 "SA %s/%08lx\n", __func__, saidx->dst.sa.sa_family,
749 ipsec_address(&saidx->dst, buf, sizeof(buf)),
750 (u_long)ntohl(sav->spi)));
751 ESP_STATINC(ESP_STAT_NOPF);
752 error = EPFNOSUPPORT;
753 goto bad;
754 }
755 if (skip + hlen + rlen + tlen > maxpacketsize) {
756 DPRINTF(("%s: packet in SA %s/%08lx got too big (len %u, "
757 "max len %u)\n", __func__,
758 ipsec_address(&saidx->dst, buf, sizeof(buf)),
759 (u_long) ntohl(sav->spi),
760 skip + hlen + rlen + tlen, maxpacketsize));
761 ESP_STATINC(ESP_STAT_TOOBIG);
762 error = EMSGSIZE;
763 goto bad;
764 }
765
766 /* Update the counters. */
767 ESP_STATADD(ESP_STAT_OBYTES, m->m_pkthdr.len - skip);
768
769 m = m_clone(m);
770 if (m == NULL) {
771 DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
772 ipsec_address(&saidx->dst, buf, sizeof(buf)),
773 (u_long) ntohl(sav->spi)));
774 ESP_STATINC(ESP_STAT_HDROPS);
775 error = ENOBUFS;
776 goto bad;
777 }
778
779 /* Inject ESP header. */
780 mo = m_makespace(m, skip, hlen, &roff);
781 if (mo == NULL) {
782 DPRINTF(("%s: failed to inject %u byte ESP hdr for SA "
783 "%s/%08lx\n", __func__, hlen,
784 ipsec_address(&saidx->dst, buf, sizeof(buf)),
785 (u_long) ntohl(sav->spi)));
786 ESP_STATINC(ESP_STAT_HDROPS);
787 error = ENOBUFS;
788 goto bad;
789 }
790
791 /* Initialize ESP header. */
792 memcpy(mtod(mo, char *) + roff, &sav->spi, sizeof(uint32_t));
793 if (sav->replay) {
794 uint32_t replay;
795
796 #ifdef IPSEC_DEBUG
797 /* Emulate replay attack when ipsec_replay is TRUE. */
798 if (!ipsec_replay)
799 #endif
800 sav->replay->count++;
801
802 replay = htonl(sav->replay->count);
803 memcpy(mtod(mo,char *) + roff + sizeof(uint32_t), &replay,
804 sizeof(uint32_t));
805 }
806
807 /*
808 * Grow the mbuf, we will append data at the tail.
809 */
810 tail = m_pad(m, tlen);
811 if (tail == NULL) {
812 DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
813 ipsec_address(&saidx->dst, buf, sizeof(buf)),
814 (u_long) ntohl(sav->spi)));
815 m = NULL;
816 error = ENOBUFS;
817 goto bad;
818 }
819
820 /*
821 * Add padding: random, zero, or self-describing.
822 */
823 switch (sav->flags & SADB_X_EXT_PMASK) {
824 case SADB_X_EXT_PSEQ:
825 for (i = 0; i < padlen; i++)
826 tail[i] = i + 1;
827 break;
828 case SADB_X_EXT_PRAND:
829 (void)cprng_fast(tail, padlen);
830 break;
831 case SADB_X_EXT_PZERO:
832 default:
833 memset(tail, 0, padlen);
834 break;
835 }
836
837 /* Build the ESP Trailer. */
838 esptail = (struct esptail *)&tail[padlen];
839 esptail->esp_padlen = padlen;
840 m_copydata(m, protoff, sizeof(uint8_t), &esptail->esp_nxt);
841
842 /* Fix Next Protocol in IPv4/IPv6 header. */
843 prot = IPPROTO_ESP;
844 m_copyback(m, protoff, sizeof(uint8_t), &prot);
845
846 /* Get crypto descriptors. */
847 crp = crypto_getreq(esph && espx ? 2 : 1);
848 if (crp == NULL) {
849 DPRINTF(("%s: failed to acquire crypto descriptors\n",
850 __func__));
851 ESP_STATINC(ESP_STAT_CRYPTO);
852 error = ENOBUFS;
853 goto bad;
854 }
855
856 if (espx) {
857 crde = crp->crp_desc;
858 crda = crde->crd_next;
859
860 /* Encryption descriptor. */
861 crde->crd_skip = skip + hlen;
862 if (espx->type == CRYPTO_AES_GMAC)
863 crde->crd_len = 0;
864 else
865 crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
866 crde->crd_flags = CRD_F_ENCRYPT;
867 crde->crd_inject = skip + hlen - sav->ivlen;
868
869 /* Encryption operation. */
870 crde->crd_alg = espx->type;
871 crde->crd_key = _KEYBUF(sav->key_enc);
872 crde->crd_klen = _KEYBITS(sav->key_enc);
873 /* XXX Rounds ? */
874 } else
875 crda = crp->crp_desc;
876
877 /* IPsec-specific opaque crypto info. */
878 tc = pool_cache_get(esp_tdb_crypto_pool_cache, PR_NOWAIT);
879 if (tc == NULL) {
880 crypto_freereq(crp);
881 DPRINTF(("%s: failed to allocate tdb_crypto\n", __func__));
882 ESP_STATINC(ESP_STAT_CRYPTO);
883 error = ENOBUFS;
884 goto bad;
885 }
886
887 {
888 int s = pserialize_read_enter();
889
890 /*
891 * Take another reference to the SP and the SA for opencrypto callback.
892 */
893 if (__predict_false(isr->sp->state == IPSEC_SPSTATE_DEAD ||
894 sav->state == SADB_SASTATE_DEAD)) {
895 pserialize_read_exit(s);
896 pool_cache_put(esp_tdb_crypto_pool_cache, tc);
897 crypto_freereq(crp);
898 ESP_STATINC(ESP_STAT_NOTDB);
899 error = ENOENT;
900 goto bad;
901 }
902 KEY_SP_REF(isr->sp);
903 KEY_SA_REF(sav);
904 pserialize_read_exit(s);
905 }
906
907 /* Callback parameters */
908 tc->tc_isr = isr;
909 tc->tc_spi = sav->spi;
910 tc->tc_dst = saidx->dst;
911 tc->tc_proto = saidx->proto;
912 tc->tc_sav = sav;
913
914 /* Crypto operation descriptor. */
915 crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
916 crp->crp_flags = CRYPTO_F_IMBUF;
917 crp->crp_buf = m;
918 crp->crp_callback = esp_output_cb;
919 crp->crp_opaque = tc;
920 crp->crp_sid = sav->tdb_cryptoid;
921
922 if (esph) {
923 /* Authentication descriptor. */
924 crda->crd_skip = skip;
925 if (espx && espx->type == CRYPTO_AES_GCM_16)
926 crda->crd_len = hlen - sav->ivlen;
927 else
928 crda->crd_len = m->m_pkthdr.len - (skip + alen);
929 crda->crd_inject = m->m_pkthdr.len - alen;
930
931 /* Authentication operation. */
932 crda->crd_alg = esph->type;
933 if (espx && (espx->type == CRYPTO_AES_GCM_16 ||
934 espx->type == CRYPTO_AES_GMAC)) {
935 crda->crd_key = _KEYBUF(sav->key_enc);
936 crda->crd_klen = _KEYBITS(sav->key_enc);
937 } else {
938 crda->crd_key = _KEYBUF(sav->key_auth);
939 crda->crd_klen = _KEYBITS(sav->key_auth);
940 }
941 }
942
943 return crypto_dispatch(crp);
944
945 bad:
946 if (m)
947 m_freem(m);
948 return error;
949 }
950
951 /*
952 * ESP output callback from the crypto driver.
953 */
954 static int
955 esp_output_cb(struct cryptop *crp)
956 {
957 struct tdb_crypto *tc;
958 const struct ipsecrequest *isr;
959 struct secasvar *sav;
960 struct mbuf *m;
961 int err, error;
962 IPSEC_DECLARE_LOCK_VARIABLE;
963
964 KASSERT(crp->crp_opaque != NULL);
965 tc = crp->crp_opaque;
966 m = crp->crp_buf;
967
968 IPSEC_ACQUIRE_GLOBAL_LOCKS();
969
970 isr = tc->tc_isr;
971 sav = tc->tc_sav;
972
973 /* Check for crypto errors. */
974 if (crp->crp_etype) {
975 /* Reset session ID. */
976 if (sav->tdb_cryptoid != 0)
977 sav->tdb_cryptoid = crp->crp_sid;
978
979 if (crp->crp_etype == EAGAIN) {
980 IPSEC_RELEASE_GLOBAL_LOCKS();
981 return crypto_dispatch(crp);
982 }
983
984 ESP_STATINC(ESP_STAT_NOXFORM);
985 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
986 error = crp->crp_etype;
987 goto bad;
988 }
989
990 ESP_STATINC(ESP_STAT_HIST + esp_stats[sav->alg_enc]);
991 if (sav->tdb_authalgxform != NULL)
992 AH_STATINC(AH_STAT_HIST + ah_stats[sav->alg_auth]);
993
994 /* Release crypto descriptors. */
995 pool_cache_put(esp_tdb_crypto_pool_cache, tc);
996 crypto_freereq(crp);
997
998 #ifdef IPSEC_DEBUG
999 /* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
1000 if (ipsec_integrity) {
1001 static unsigned char ipseczeroes[AH_ALEN_MAX];
1002 const struct auth_hash *esph;
1003
1004 /*
1005 * Corrupt HMAC if we want to test integrity verification of
1006 * the other side.
1007 */
1008 esph = sav->tdb_authalgxform;
1009 if (esph != NULL) {
1010 m_copyback(m, m->m_pkthdr.len - esph->authsize,
1011 esph->authsize, ipseczeroes);
1012 }
1013 }
1014 #endif
1015
1016 /* NB: m is reclaimed by ipsec_process_done. */
1017 err = ipsec_process_done(m, isr, sav);
1018 KEY_SA_UNREF(&sav);
1019 KEY_SP_UNREF(&isr->sp);
1020 IPSEC_RELEASE_GLOBAL_LOCKS();
1021 return err;
1022
1023 bad:
1024 if (sav)
1025 KEY_SA_UNREF(&sav);
1026 KEY_SP_UNREF(&isr->sp);
1027 IPSEC_RELEASE_GLOBAL_LOCKS();
1028 if (m)
1029 m_freem(m);
1030 pool_cache_put(esp_tdb_crypto_pool_cache, tc);
1031 crypto_freereq(crp);
1032 return error;
1033 }
1034
1035 static struct xformsw esp_xformsw = {
1036 .xf_type = XF_ESP,
1037 .xf_flags = XFT_CONF|XFT_AUTH,
1038 .xf_name = "IPsec ESP",
1039 .xf_init = esp_init,
1040 .xf_zeroize = esp_zeroize,
1041 .xf_input = esp_input,
1042 .xf_output = esp_output,
1043 .xf_next = NULL,
1044 };
1045
1046 void
1047 esp_attach(void)
1048 {
1049
1050 espstat_percpu = percpu_alloc(sizeof(uint64_t) * ESP_NSTATS);
1051
1052 extern int ah_max_authsize;
1053 KASSERT(ah_max_authsize != 0);
1054 esp_pool_item_size = sizeof(struct tdb_crypto) + ah_max_authsize;
1055 esp_tdb_crypto_pool_cache = pool_cache_init(esp_pool_item_size,
1056 coherency_unit, 0, 0, "esp_tdb_crypto", NULL, IPL_SOFTNET,
1057 NULL, NULL, NULL);
1058
1059 #define MAXIV(xform) \
1060 if (xform.ivsize > esp_max_ivlen) \
1061 esp_max_ivlen = xform.ivsize \
1062
1063 esp_max_ivlen = 0;
1064 MAXIV(enc_xform_des); /* SADB_EALG_DESCBC */
1065 MAXIV(enc_xform_3des); /* SADB_EALG_3DESCBC */
1066 MAXIV(enc_xform_rijndael128); /* SADB_X_EALG_AES */
1067 MAXIV(enc_xform_blf); /* SADB_X_EALG_BLOWFISHCBC */
1068 MAXIV(enc_xform_cast5); /* SADB_X_EALG_CAST128CBC */
1069 MAXIV(enc_xform_skipjack); /* SADB_X_EALG_SKIPJACK */
1070 MAXIV(enc_xform_camellia); /* SADB_X_EALG_CAMELLIACBC */
1071 MAXIV(enc_xform_aes_ctr); /* SADB_X_EALG_AESCTR */
1072 MAXIV(enc_xform_null); /* SADB_EALG_NULL */
1073
1074 xform_register(&esp_xformsw);
1075 #undef MAXIV
1076 }
1077