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