xform_esp.c revision 1.89 1 /* $NetBSD: xform_esp.c,v 1.89 2018/05/18 19:02:49 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.89 2018/05/18 19:02:49 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, padding, blks, alen, i, roff;
691 struct mbuf *mo = NULL;
692 struct tdb_crypto *tc;
693 struct secasindex *saidx;
694 unsigned char *pad;
695 uint8_t prot;
696 int error, maxpacketsize;
697
698 struct cryptodesc *crde = NULL, *crda = NULL;
699 struct cryptop *crp;
700
701 esph = sav->tdb_authalgxform;
702 KASSERT(sav->tdb_encalgxform != NULL);
703 espx = sav->tdb_encalgxform;
704
705 if (sav->flags & SADB_X_EXT_OLD)
706 hlen = sizeof(struct esp) + sav->ivlen;
707 else
708 hlen = sizeof(struct newesp) + sav->ivlen;
709
710 rlen = m->m_pkthdr.len - skip; /* Raw payload length. */
711 /*
712 * NB: The null encoding transform has a blocksize of 4
713 * so that headers are properly aligned.
714 */
715 blks = espx->blocksize; /* IV blocksize */
716
717 /* XXX clamp padding length a la KAME??? */
718 padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
719
720 if (esph)
721 alen = esph->authsize;
722 else
723 alen = 0;
724
725 ESP_STATINC(ESP_STAT_OUTPUT);
726
727 saidx = &sav->sah->saidx;
728 /* Check for maximum packet size violations. */
729 switch (saidx->dst.sa.sa_family) {
730 #ifdef INET
731 case AF_INET:
732 maxpacketsize = IP_MAXPACKET;
733 break;
734 #endif
735 #ifdef INET6
736 case AF_INET6:
737 maxpacketsize = IPV6_MAXPACKET;
738 break;
739 #endif
740 default:
741 DPRINTF(("%s: unknown/unsupported protocol family %d, "
742 "SA %s/%08lx\n", __func__, saidx->dst.sa.sa_family,
743 ipsec_address(&saidx->dst, buf, sizeof(buf)),
744 (u_long)ntohl(sav->spi)));
745 ESP_STATINC(ESP_STAT_NOPF);
746 error = EPFNOSUPPORT;
747 goto bad;
748 }
749 if (skip + hlen + rlen + padding + alen > maxpacketsize) {
750 DPRINTF(("%s: packet in SA %s/%08lx got too big (len %u, "
751 "max len %u)\n", __func__,
752 ipsec_address(&saidx->dst, buf, sizeof(buf)),
753 (u_long) ntohl(sav->spi),
754 skip + hlen + rlen + padding + alen, maxpacketsize));
755 ESP_STATINC(ESP_STAT_TOOBIG);
756 error = EMSGSIZE;
757 goto bad;
758 }
759
760 /* Update the counters. */
761 ESP_STATADD(ESP_STAT_OBYTES, m->m_pkthdr.len - skip);
762
763 m = m_clone(m);
764 if (m == NULL) {
765 DPRINTF(("%s: cannot clone mbuf chain, SA %s/%08lx\n", __func__,
766 ipsec_address(&saidx->dst, buf, sizeof(buf)),
767 (u_long) ntohl(sav->spi)));
768 ESP_STATINC(ESP_STAT_HDROPS);
769 error = ENOBUFS;
770 goto bad;
771 }
772
773 /* Inject ESP header. */
774 mo = m_makespace(m, skip, hlen, &roff);
775 if (mo == NULL) {
776 DPRINTF(("%s: failed to inject %u byte ESP hdr for SA "
777 "%s/%08lx\n", __func__, hlen,
778 ipsec_address(&saidx->dst, buf, sizeof(buf)),
779 (u_long) ntohl(sav->spi)));
780 ESP_STATINC(ESP_STAT_HDROPS);
781 error = ENOBUFS;
782 goto bad;
783 }
784
785 /* Initialize ESP header. */
786 memcpy(mtod(mo, char *) + roff, &sav->spi, sizeof(uint32_t));
787 if (sav->replay) {
788 uint32_t replay;
789
790 #ifdef IPSEC_DEBUG
791 /* Emulate replay attack when ipsec_replay is TRUE. */
792 if (!ipsec_replay)
793 #endif
794 sav->replay->count++;
795
796 replay = htonl(sav->replay->count);
797 memcpy(mtod(mo,char *) + roff + sizeof(uint32_t), &replay,
798 sizeof(uint32_t));
799 }
800
801 /*
802 * Add padding -- better to do it ourselves than use the crypto engine,
803 * although if/when we support compression, we'd have to do that.
804 */
805 pad = m_pad(m, padding + alen);
806 if (pad == NULL) {
807 DPRINTF(("%s: m_pad failed for SA %s/%08lx\n", __func__,
808 ipsec_address(&saidx->dst, buf, sizeof(buf)),
809 (u_long) ntohl(sav->spi)));
810 m = NULL; /* NB: free'd by m_pad */
811 error = ENOBUFS;
812 goto bad;
813 }
814
815 /*
816 * Add padding: random, zero, or self-describing.
817 */
818 switch (sav->flags & SADB_X_EXT_PMASK) {
819 case SADB_X_EXT_PSEQ:
820 for (i = 0; i < padding - 2; i++)
821 pad[i] = i+1;
822 break;
823 case SADB_X_EXT_PRAND:
824 (void)cprng_fast(pad, padding - 2);
825 break;
826 case SADB_X_EXT_PZERO:
827 default:
828 memset(pad, 0, padding - 2);
829 break;
830 }
831
832 /* Fix padding length and Next Protocol in padding itself. */
833 pad[padding - 2] = padding - 2;
834 m_copydata(m, protoff, sizeof(uint8_t), pad + padding - 1);
835
836 /* Fix Next Protocol in IPv4/IPv6 header. */
837 prot = IPPROTO_ESP;
838 m_copyback(m, protoff, sizeof(uint8_t), &prot);
839
840 /* Get crypto descriptors. */
841 crp = crypto_getreq(esph && espx ? 2 : 1);
842 if (crp == NULL) {
843 DPRINTF(("%s: failed to acquire crypto descriptors\n",
844 __func__));
845 ESP_STATINC(ESP_STAT_CRYPTO);
846 error = ENOBUFS;
847 goto bad;
848 }
849
850 if (espx) {
851 crde = crp->crp_desc;
852 crda = crde->crd_next;
853
854 /* Encryption descriptor. */
855 crde->crd_skip = skip + hlen;
856 if (espx->type == CRYPTO_AES_GMAC)
857 crde->crd_len = 0;
858 else
859 crde->crd_len = m->m_pkthdr.len - (skip + hlen + alen);
860 crde->crd_flags = CRD_F_ENCRYPT;
861 crde->crd_inject = skip + hlen - sav->ivlen;
862
863 /* Encryption operation. */
864 crde->crd_alg = espx->type;
865 crde->crd_key = _KEYBUF(sav->key_enc);
866 crde->crd_klen = _KEYBITS(sav->key_enc);
867 /* XXX Rounds ? */
868 } else
869 crda = crp->crp_desc;
870
871 /* IPsec-specific opaque crypto info. */
872 tc = pool_cache_get(esp_tdb_crypto_pool_cache, PR_NOWAIT);
873 if (tc == NULL) {
874 crypto_freereq(crp);
875 DPRINTF(("%s: failed to allocate tdb_crypto\n", __func__));
876 ESP_STATINC(ESP_STAT_CRYPTO);
877 error = ENOBUFS;
878 goto bad;
879 }
880
881 {
882 int s = pserialize_read_enter();
883
884 /*
885 * Take another reference to the SP and the SA for opencrypto callback.
886 */
887 if (__predict_false(isr->sp->state == IPSEC_SPSTATE_DEAD ||
888 sav->state == SADB_SASTATE_DEAD)) {
889 pserialize_read_exit(s);
890 pool_cache_put(esp_tdb_crypto_pool_cache, tc);
891 crypto_freereq(crp);
892 ESP_STATINC(ESP_STAT_NOTDB);
893 error = ENOENT;
894 goto bad;
895 }
896 KEY_SP_REF(isr->sp);
897 KEY_SA_REF(sav);
898 pserialize_read_exit(s);
899 }
900
901 /* Callback parameters */
902 tc->tc_isr = isr;
903 tc->tc_spi = sav->spi;
904 tc->tc_dst = saidx->dst;
905 tc->tc_proto = saidx->proto;
906 tc->tc_sav = sav;
907
908 /* Crypto operation descriptor. */
909 crp->crp_ilen = m->m_pkthdr.len; /* Total input length. */
910 crp->crp_flags = CRYPTO_F_IMBUF;
911 crp->crp_buf = m;
912 crp->crp_callback = esp_output_cb;
913 crp->crp_opaque = tc;
914 crp->crp_sid = sav->tdb_cryptoid;
915
916 if (esph) {
917 /* Authentication descriptor. */
918 crda->crd_skip = skip;
919 if (espx && espx->type == CRYPTO_AES_GCM_16)
920 crda->crd_len = hlen - sav->ivlen;
921 else
922 crda->crd_len = m->m_pkthdr.len - (skip + alen);
923 crda->crd_inject = m->m_pkthdr.len - alen;
924
925 /* Authentication operation. */
926 crda->crd_alg = esph->type;
927 if (espx && (espx->type == CRYPTO_AES_GCM_16 ||
928 espx->type == CRYPTO_AES_GMAC)) {
929 crda->crd_key = _KEYBUF(sav->key_enc);
930 crda->crd_klen = _KEYBITS(sav->key_enc);
931 } else {
932 crda->crd_key = _KEYBUF(sav->key_auth);
933 crda->crd_klen = _KEYBITS(sav->key_auth);
934 }
935 }
936
937 return crypto_dispatch(crp);
938
939 bad:
940 if (m)
941 m_freem(m);
942 return error;
943 }
944
945 /*
946 * ESP output callback from the crypto driver.
947 */
948 static int
949 esp_output_cb(struct cryptop *crp)
950 {
951 struct tdb_crypto *tc;
952 const struct ipsecrequest *isr;
953 struct secasvar *sav;
954 struct mbuf *m;
955 int err, error;
956 IPSEC_DECLARE_LOCK_VARIABLE;
957
958 KASSERT(crp->crp_opaque != NULL);
959 tc = crp->crp_opaque;
960 m = crp->crp_buf;
961
962 IPSEC_ACQUIRE_GLOBAL_LOCKS();
963
964 isr = tc->tc_isr;
965 sav = tc->tc_sav;
966
967 /* Check for crypto errors. */
968 if (crp->crp_etype) {
969 /* Reset session ID. */
970 if (sav->tdb_cryptoid != 0)
971 sav->tdb_cryptoid = crp->crp_sid;
972
973 if (crp->crp_etype == EAGAIN) {
974 IPSEC_RELEASE_GLOBAL_LOCKS();
975 return crypto_dispatch(crp);
976 }
977
978 ESP_STATINC(ESP_STAT_NOXFORM);
979 DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
980 error = crp->crp_etype;
981 goto bad;
982 }
983
984 ESP_STATINC(ESP_STAT_HIST + esp_stats[sav->alg_enc]);
985 if (sav->tdb_authalgxform != NULL)
986 AH_STATINC(AH_STAT_HIST + ah_stats[sav->alg_auth]);
987
988 /* Release crypto descriptors. */
989 pool_cache_put(esp_tdb_crypto_pool_cache, tc);
990 crypto_freereq(crp);
991
992 #ifdef IPSEC_DEBUG
993 /* Emulate man-in-the-middle attack when ipsec_integrity is TRUE. */
994 if (ipsec_integrity) {
995 static unsigned char ipseczeroes[AH_ALEN_MAX];
996 const struct auth_hash *esph;
997
998 /*
999 * Corrupt HMAC if we want to test integrity verification of
1000 * the other side.
1001 */
1002 esph = sav->tdb_authalgxform;
1003 if (esph != NULL) {
1004 m_copyback(m, m->m_pkthdr.len - esph->authsize,
1005 esph->authsize, ipseczeroes);
1006 }
1007 }
1008 #endif
1009
1010 /* NB: m is reclaimed by ipsec_process_done. */
1011 err = ipsec_process_done(m, isr, sav);
1012 KEY_SA_UNREF(&sav);
1013 KEY_SP_UNREF(&isr->sp);
1014 IPSEC_RELEASE_GLOBAL_LOCKS();
1015 return err;
1016
1017 bad:
1018 if (sav)
1019 KEY_SA_UNREF(&sav);
1020 KEY_SP_UNREF(&isr->sp);
1021 IPSEC_RELEASE_GLOBAL_LOCKS();
1022 if (m)
1023 m_freem(m);
1024 pool_cache_put(esp_tdb_crypto_pool_cache, tc);
1025 crypto_freereq(crp);
1026 return error;
1027 }
1028
1029 static struct xformsw esp_xformsw = {
1030 .xf_type = XF_ESP,
1031 .xf_flags = XFT_CONF|XFT_AUTH,
1032 .xf_name = "IPsec ESP",
1033 .xf_init = esp_init,
1034 .xf_zeroize = esp_zeroize,
1035 .xf_input = esp_input,
1036 .xf_output = esp_output,
1037 .xf_next = NULL,
1038 };
1039
1040 void
1041 esp_attach(void)
1042 {
1043
1044 espstat_percpu = percpu_alloc(sizeof(uint64_t) * ESP_NSTATS);
1045
1046 extern int ah_max_authsize;
1047 KASSERT(ah_max_authsize != 0);
1048 esp_pool_item_size = sizeof(struct tdb_crypto) + ah_max_authsize;
1049 esp_tdb_crypto_pool_cache = pool_cache_init(esp_pool_item_size,
1050 coherency_unit, 0, 0, "esp_tdb_crypto", NULL, IPL_SOFTNET,
1051 NULL, NULL, NULL);
1052
1053 #define MAXIV(xform) \
1054 if (xform.ivsize > esp_max_ivlen) \
1055 esp_max_ivlen = xform.ivsize \
1056
1057 esp_max_ivlen = 0;
1058 MAXIV(enc_xform_des); /* SADB_EALG_DESCBC */
1059 MAXIV(enc_xform_3des); /* SADB_EALG_3DESCBC */
1060 MAXIV(enc_xform_rijndael128); /* SADB_X_EALG_AES */
1061 MAXIV(enc_xform_blf); /* SADB_X_EALG_BLOWFISHCBC */
1062 MAXIV(enc_xform_cast5); /* SADB_X_EALG_CAST128CBC */
1063 MAXIV(enc_xform_skipjack); /* SADB_X_EALG_SKIPJACK */
1064 MAXIV(enc_xform_camellia); /* SADB_X_EALG_CAMELLIACBC */
1065 MAXIV(enc_xform_aes_ctr); /* SADB_X_EALG_AESCTR */
1066 MAXIV(enc_xform_null); /* SADB_EALG_NULL */
1067
1068 xform_register(&esp_xformsw);
1069 #undef MAXIV
1070 }
1071