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