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