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