0d906e4b746c0faf9e2f6238187fa58e1d90592f
[dragonfly.git] / sys / dev / disk / dm / dm_target_crypt.c
1 /*
2  * Copyright (c) 2010 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Alex Hornung <ahornung@gmail.com>
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34
35 /*
36  * This file implements initial version of device-mapper crypt target.
37  */
38 #include <sys/types.h>
39 #include <sys/param.h>
40 #include <sys/endian.h>
41
42 #include <sys/bio.h>
43 #include <sys/buf.h>
44 #include <sys/malloc.h>
45 #include <sys/md5.h>
46 #include <sys/vnode.h>
47 #include <crypto/sha1.h>
48 #include <crypto/sha2/sha2.h>
49 #include <opencrypto/cryptodev.h>
50 #include <opencrypto/rmd160.h>
51 #include <machine/cpufunc.h>
52
53 #include "dm.h"
54 MALLOC_DEFINE(M_DMCRYPT, "dm_crypt", "Device Mapper Target Crypt");
55
56 struct target_crypt_config;
57
58 typedef void dispatch_t(void *);
59 typedef void ivgen_t(struct target_crypt_config *, u_int8_t *, size_t, off_t,
60     void *);
61
62 typedef int ivgen_ctor_t(struct target_crypt_config *, char *, void **);
63 typedef int ivgen_dtor_t(struct target_crypt_config *, void *);
64
65 struct iv_generator {
66         const char      *name;
67         ivgen_ctor_t    *ctor;
68         ivgen_dtor_t    *dtor;
69         ivgen_t         *gen_iv;
70 };
71
72 struct essiv_ivgen_priv {
73         struct cryptoini        crypto_session;
74         struct objcache *crp_crd_cache;
75         u_int64_t       crypto_sid;
76         size_t          keyhash_len;
77         u_int8_t        crypto_keyhash[SHA512_DIGEST_LENGTH];
78 };
79
80 typedef struct target_crypt_config {
81         size_t  params_len;
82         dm_pdev_t *pdev;
83         char    *status_str;
84         int     crypto_alg;
85         int     crypto_klen;
86         u_int8_t        crypto_key[512>>3];
87         
88         u_int64_t       crypto_sid;
89         u_int64_t       block_offset;
90         u_int64_t       iv_offset;
91         SHA512_CTX      essivsha512_ctx;
92
93         struct cryptoini        crypto_session;
94
95         struct iv_generator     *ivgen;
96         void    *ivgen_priv;
97 } dm_target_crypt_config_t;
98
99 struct dmtc_helper {
100         caddr_t free_addr;
101         caddr_t orig_buf;
102         caddr_t data_buf;
103 };
104
105 static void dmtc_crypto_dispatch(void *arg);
106 static void dmtc_crypto_read_start(dm_target_crypt_config_t *priv,
107                                 struct bio *bio);
108 static void dmtc_crypto_write_start(dm_target_crypt_config_t *priv,
109                                 struct bio *bio);
110 static void dmtc_bio_read_done(struct bio *bio);
111 static void dmtc_bio_write_done(struct bio *bio);
112 static int dmtc_crypto_cb_read_done(struct cryptop *crp);
113 static int dmtc_crypto_cb_write_done(struct cryptop *crp);
114
115 static ivgen_ctor_t     essiv_ivgen_ctor;
116 static ivgen_dtor_t     essiv_ivgen_dtor;
117 static ivgen_t          essiv_ivgen;
118 static ivgen_t          plain_ivgen;
119
120 static struct iv_generator ivgens[] = {
121         { .name = "essiv", .ctor = essiv_ivgen_ctor, .dtor = essiv_ivgen_dtor,
122             .gen_iv = essiv_ivgen },
123         { .name = "plain", .ctor = NULL, .dtor = NULL, .gen_iv = plain_ivgen },
124         { NULL, NULL, NULL, NULL }
125 };
126
127 struct objcache_malloc_args essiv_ivgen_malloc_args = {
128                 2*sizeof(void *) + (sizeof(struct cryptodesc) +
129                 sizeof(struct cryptop)), M_DMCRYPT };
130
131 /*
132  * Overwrite private information (in buf) to avoid leaking it
133  */
134 static void
135 dmtc_crypto_clear(void *buf, size_t len)
136 {
137         memset(buf, 0xFF, len);
138         bzero(buf, len);
139 }
140
141 /*
142  * ESSIV IV Generator Routines
143  */
144 static int 
145 essiv_ivgen_ctor(struct target_crypt_config *priv, char *iv_hash, void **p_ivpriv)
146 {
147         struct essiv_ivgen_priv *ivpriv;
148         u_int8_t crypto_keyhash[SHA512_DIGEST_LENGTH];
149         unsigned int klen;
150         int error;
151
152         klen = (priv->crypto_klen >> 3);
153
154         if (iv_hash == NULL)
155                 return EINVAL;
156
157         if (!strcmp(iv_hash, "sha1")) {
158                 SHA1_CTX ctx;
159
160                 if (klen != SHA1_RESULTLEN)
161                         return EINVAL;
162
163                 SHA1Init(&ctx);
164                 SHA1Update(&ctx, priv->crypto_key, priv->crypto_klen>>3);
165                 SHA1Final(crypto_keyhash, &ctx);
166         } else if (!strcmp(iv_hash, "sha256")) {
167                 SHA256_CTX ctx;
168
169                 if (klen != SHA256_DIGEST_LENGTH)
170                         return EINVAL;
171
172                 SHA256_Init(&ctx);
173                 SHA256_Update(&ctx, priv->crypto_key, priv->crypto_klen>>3);
174                 SHA256_Final(crypto_keyhash, &ctx);
175         } else if (!strcmp(iv_hash, "sha384")) {
176                 SHA384_CTX ctx;
177
178                 if (klen != SHA384_DIGEST_LENGTH)
179                         return EINVAL;
180
181                 SHA384_Init(&ctx);
182                 SHA384_Update(&ctx, priv->crypto_key, priv->crypto_klen>>3);
183                 SHA384_Final(crypto_keyhash, &ctx);
184         } else if (!strcmp(iv_hash, "sha512")) {
185                 SHA512_CTX ctx;
186
187                 if (klen != SHA512_DIGEST_LENGTH)
188                         return EINVAL;
189
190                 SHA512_Init(&ctx);
191                 SHA512_Update(&ctx, priv->crypto_key, priv->crypto_klen>>3);
192                 SHA512_Final(crypto_keyhash, &ctx);
193         } else if (!strcmp(iv_hash, "md5")) {
194                 MD5_CTX ctx;
195
196                 if (klen != MD5_DIGEST_LENGTH)
197                         return EINVAL;
198
199                 MD5Init(&ctx);
200                 MD5Update(&ctx, priv->crypto_key, priv->crypto_klen>>3);
201                 MD5Final(crypto_keyhash, &ctx);
202         } else if (!strcmp(iv_hash, "rmd160") ||
203                    !strcmp(iv_hash, "ripemd160")) {
204                 RMD160_CTX ctx;
205
206                 if (klen != (160/8))
207                         return EINVAL;
208
209                 RMD160Init(&ctx);
210                 RMD160Update(&ctx, priv->crypto_key, priv->crypto_klen>>3);
211                 RMD160Final(crypto_keyhash, &ctx);
212         } else {
213                 return EINVAL;
214         }
215
216         ivpriv = kmalloc(sizeof(struct essiv_ivgen_priv), M_DMCRYPT,
217             M_WAITOK | M_ZERO);
218         memcpy(ivpriv->crypto_keyhash, crypto_keyhash, sizeof(crypto_keyhash));
219         ivpriv->keyhash_len = sizeof(crypto_keyhash);
220         dmtc_crypto_clear(crypto_keyhash, sizeof(crypto_keyhash));
221
222         ivpriv->crypto_session.cri_alg = priv->crypto_alg;
223         ivpriv->crypto_session.cri_key = (u_int8_t *)ivpriv->crypto_keyhash;
224         ivpriv->crypto_session.cri_klen = priv->crypto_klen;
225         ivpriv->crypto_session.cri_mlen = 0;
226         ivpriv->crypto_session.cri_next = NULL;
227
228         error = crypto_newsession(&ivpriv->crypto_sid,
229                                   &ivpriv->crypto_session,
230                                   CRYPTOCAP_F_SOFTWARE | CRYPTOCAP_F_HARDWARE);
231         if (error) {
232                 kprintf("dm_target_crypt: Error during crypto_newsession "
233                         "for essiv_ivgen, error = %d\n",
234                         error);
235                 dmtc_crypto_clear(ivpriv->crypto_keyhash, ivpriv->keyhash_len);
236                 kfree(ivpriv, M_DMCRYPT);
237                 return ENOTSUP;
238         }
239
240         ivpriv->crp_crd_cache = objcache_create(
241             "dmcrypt-essiv-cache", 0, 0,
242             NULL, NULL, NULL,
243             objcache_malloc_alloc,
244             objcache_malloc_free,
245             &essiv_ivgen_malloc_args );
246
247         *p_ivpriv = ivpriv;
248         return 0;
249 }
250
251 static int 
252 essiv_ivgen_dtor(struct target_crypt_config *priv, void *arg)
253 {
254         struct essiv_ivgen_priv *ivpriv;
255
256         ivpriv = (struct essiv_ivgen_priv *)arg;
257         KKASSERT(ivpriv != NULL);
258
259         crypto_freesession(ivpriv->crypto_sid);
260
261         objcache_destroy(ivpriv->crp_crd_cache);
262
263         dmtc_crypto_clear(ivpriv->crypto_keyhash, ivpriv->keyhash_len);
264         kfree(ivpriv, M_DMCRYPT);
265
266         return 0;
267 }
268
269 static int
270 essiv_ivgen_done(struct cryptop *crp)
271 {
272         struct essiv_ivgen_priv *ivpriv;
273         void *free_addr;
274         void *opaque;
275
276         if (crp->crp_etype == EAGAIN)
277                 return crypto_dispatch(crp);
278
279         if (crp->crp_etype != 0) {
280                 kprintf("dm_target_crypt: essiv_ivgen_done, "
281                         "crp->crp_etype = %d\n", crp->crp_etype);
282         }
283
284         free_addr = crp->crp_opaque;
285         /*
286          * In-memory structure is:
287          * |  ivpriv  |  opaque  |     crp     |      crd      |
288          * | (void *) | (void *) |   (cryptop) |  (cryptodesc) |
289          */
290         ivpriv = *((struct essiv_ivgen_priv **)crp->crp_opaque);
291         crp->crp_opaque += sizeof(void *);
292         opaque = *((void **)crp->crp_opaque);
293         
294         objcache_put(ivpriv->crp_crd_cache, free_addr);
295         dmtc_crypto_dispatch(opaque);
296         return 0;
297 }
298
299 static void
300 essiv_ivgen(dm_target_crypt_config_t *priv, u_int8_t *iv,
301             size_t iv_len, off_t sector, void *opaque)
302 {
303         struct essiv_ivgen_priv *ivpriv;
304         struct cryptodesc *crd;
305         struct cryptop *crp;
306         caddr_t space, alloc_addr;
307         int error;
308
309         ivpriv = priv->ivgen_priv;
310         KKASSERT(ivpriv != NULL);
311
312         /*
313          * In-memory structure is:
314          * |  ivpriv  |  opaque  |     crp     |      crd      |
315          * | (void *) | (void *) |   (cryptop) |  (cryptodesc) |
316          */
317         alloc_addr = space = objcache_get(ivpriv->crp_crd_cache, M_WAITOK);
318         *((struct essiv_ivgen_priv **)space) = ivpriv;
319         space += sizeof(void *);
320         *((void **)space) = opaque;
321         space += sizeof(void *);
322         crp = (struct cryptop *)space;
323         space += sizeof(struct cryptop);
324         crd = (struct cryptodesc *)space;
325
326         bzero(iv, iv_len);
327         bzero(crd, sizeof(struct cryptodesc));
328         bzero(crp, sizeof(struct cryptop));
329         *((off_t *)iv) = htole64(sector + priv->iv_offset);
330         crp->crp_buf = (caddr_t)iv;
331
332         crp->crp_sid = ivpriv->crypto_sid;
333         crp->crp_ilen = crp->crp_olen = iv_len;
334
335         crp->crp_opaque = alloc_addr;
336
337         crp->crp_callback = essiv_ivgen_done;
338
339         crp->crp_desc = crd;
340         crp->crp_etype = 0;
341         crp->crp_flags = CRYPTO_F_CBIFSYNC | CRYPTO_F_REL | CRYPTO_F_BATCH;
342
343         crd->crd_alg = priv->crypto_alg;
344 #if 0
345         crd->crd_key = (caddr_t)priv->crypto_keyhash;
346         crd->crd_klen = priv->crypto_klen;
347 #endif
348
349         bzero(crd->crd_iv, sizeof(crd->crd_iv));
350
351         crd->crd_skip = 0;
352         crd->crd_len = iv_len;
353         crd->crd_flags = CRD_F_IV_EXPLICIT | CRD_F_IV_PRESENT;
354         crd->crd_flags |= CRD_F_ENCRYPT;
355         crd->crd_next = NULL;
356
357         error = crypto_dispatch(crp);
358         if (error)
359                 kprintf("dm_target_crypt: essiv_ivgen, error = %d\n", error);
360 }
361
362
363 static void
364 plain_ivgen(dm_target_crypt_config_t *priv, u_int8_t *iv,
365             size_t iv_len, off_t sector, void *opaque)
366 {
367         bzero(iv, iv_len);
368         *((uint32_t *)iv) = htole32((uint32_t)(sector + priv->iv_offset));
369         dmtc_crypto_dispatch(opaque);
370 }
371
372
373 #if 0
374 static void
375 geli_ivgen(dm_target_crypt_config_t *priv, u_int8_t *iv,
376            size_t iv_len, off_t sector, void *opaque)
377 {
378
379         SHA512_CTX      ctx512;
380         u_int8_t        md[SHA512_DIGEST_LENGTH]; /* Max. Digest Size */
381
382         memcpy(&ctx512, &priv->essivsha512_ctx, sizeof(SHA512_CTX));
383         SHA512_Update(&ctx512, (u_int8_t*)&sector, sizeof(off_t));
384         SHA512_Final(md, &ctx512);
385
386         memcpy(iv, md, iv_len);
387         dmtc_crypto_dispatch(opaque);
388 }
389 #endif
390
391 #ifdef DM_TARGET_MODULE
392 /*
393  * Every target can be compiled directly to dm driver or as a
394  * separate module this part of target is used for loading targets
395  * to dm driver.
396  * Target can be unloaded from kernel only if there are no users of
397  * it e.g. there are no devices which uses that target.
398  */
399 #include <sys/kernel.h>
400 #include <sys/module.h>
401
402 static int
403 dm_target_crypt_modcmd(modcmd_t cmd, void *arg)
404 {
405         dm_target_t *dmt;
406         int r;
407         dmt = NULL;
408
409         switch (cmd) {
410         case MODULE_CMD_INIT:
411                 if ((dmt = dm_target_lookup("crypt")) != NULL) {
412                         dm_target_unbusy(dmt);
413                         return EEXIST;
414                 }
415                 dmt = dm_target_alloc("crypt");
416
417                 dmt->version[0] = 1;
418                 dmt->version[1] = 0;
419                 dmt->version[2] = 0;
420                 strlcpy(dmt->name, "crypt", DM_MAX_TYPE_NAME);
421                 dmt->init = &dm_target_crypt_init;
422                 dmt->status = &dm_target_crypt_status;
423                 dmt->strategy = &dm_target_crypt_strategy;
424                 dmt->deps = &dm_target_crypt_deps;
425                 dmt->destroy = &dm_target_crypt_destroy;
426                 dmt->upcall = &dm_target_crypt_upcall;
427
428                 r = dm_target_insert(dmt);
429
430                 break;
431
432         case MODULE_CMD_FINI:
433                 r = dm_target_rem("crypt");
434                 break;
435
436         case MODULE_CMD_STAT:
437                 return ENOTTY;
438
439         default:
440                 return ENOTTY;
441         }
442
443         return r;
444 }
445
446 #endif
447
448 /*
449  * Init function called from dm_table_load_ioctl.
450  * cryptsetup actually passes us this:
451  * aes-cbc-essiv:sha256 7997f8af... 0 /dev/ad0s0a 8
452  */
453 static int
454 hex2key(char *hex, size_t key_len, u_int8_t *key)
455 {
456         char hex_buf[3];
457         size_t key_idx;
458
459         hex_buf[2] = 0;
460         for (key_idx = 0; key_idx < key_len; ++key_idx) {
461                 hex_buf[0] = *hex++;
462                 hex_buf[1] = *hex++;
463                 key[key_idx] = (u_int8_t)strtoul(hex_buf, NULL, 16);
464         }
465         hex_buf[0] = 0;
466         hex_buf[1] = 0;
467
468         return 0;
469 }
470
471 int
472 dm_target_crypt_init(dm_dev_t * dmv, void **target_config, char *params)
473 {
474         dm_target_crypt_config_t *priv;
475         size_t len;
476         char **ap, *args[5];
477         char *crypto_alg, *crypto_mode, *iv_mode, *iv_opt, *key, *dev;
478         char *status_str;
479         int i, argc, klen, error;
480         uint64_t iv_offset, block_offset;
481
482         if (params == NULL)
483                 return EINVAL;
484
485         len = strlen(params) + 1;
486         argc = 0;
487
488         status_str = kstrdup(params, M_DMCRYPT);
489         /*
490          * Parse a string, containing tokens delimited by white space,
491          * into an argument vector
492          */
493         for (ap = args; ap < &args[5] &&
494             (*ap = strsep(&params, " \t")) != NULL;) {
495                 if (**ap != '\0') {
496                         argc++;
497                         ap++;
498                 }
499         }
500
501         if (argc != 5) {
502                 kprintf("dm_target_crypt: not enough arguments, "
503                         "need exactly 5\n");
504                 kfree(status_str, M_DMCRYPT);
505                 return ENOMEM; /* XXX */
506         }
507
508         crypto_alg = strsep(&args[0], "-");
509         crypto_mode = strsep(&args[0], "-");
510         iv_opt = strsep(&args[0], "-");
511         iv_mode = strsep(&iv_opt, ":");
512         key = args[1];
513         iv_offset = strtouq(args[2], NULL, 0);
514         dev = args[3];
515         block_offset = strtouq(args[4], NULL, 0);
516         /* bits / 8 = bytes, 1 byte = 2 hexa chars, so << 2 */
517         klen = strlen(key) << 2;
518
519         kprintf("dm_target_crypt - new: dev=%s, crypto_alg=%s, crypto_mode=%s, "
520                 "iv_mode=%s, iv_opt=%s, key=%s, iv_offset=%ju, "
521                 "block_offset=%ju\n",
522                 dev, crypto_alg, crypto_mode, iv_mode, iv_opt, key, iv_offset,
523                 block_offset);
524
525         priv = kmalloc(sizeof(dm_target_crypt_config_t), M_DMCRYPT, M_WAITOK);
526         if (priv == NULL) {
527                 kprintf("dm_target_crypt: could not allocate memory\n");
528                 kfree(status_str, M_DMCRYPT);
529                 return ENOMEM;
530         }
531
532         /* Insert dmp to global pdev list */
533         if ((priv->pdev = dm_pdev_insert(dev)) == NULL) {
534                 kprintf("dm_target_crypt: dm_pdev_insert failed\n");
535                 kfree(status_str, M_DMCRYPT);
536                 return ENOENT;
537         }
538
539         if ((strcmp(crypto_mode, "cbc") != 0) ||
540             ((strcmp(crypto_mode, "xts") == 0) && (strcmp(crypto_alg, "aes") != 0)))
541         
542         {
543                 kprintf("dm_target_crypt: only support 'cbc' chaining mode"
544                     " and aes-xts, invalid mode '%s-%s'\n",
545                     crypto_alg, crypto_mode);
546                 goto notsup;
547         }
548
549         if (!strcmp(crypto_alg, "aes")) {
550                 if (!strcmp(crypto_mode, "xts")) {
551                         priv->crypto_alg = CRYPTO_AES_XTS;
552                         if (klen != 256 && klen != 512)
553                                 goto notsup;
554                 } else if (!strcmp(crypto_mode, "cbc")) {
555                         priv->crypto_alg = CRYPTO_AES_CBC;
556                         if (klen != 128 && klen != 192 && klen != 256)
557                                 goto notsup;
558                 } else {
559                         goto notsup;
560                 }
561                 priv->crypto_klen = klen;
562         } else if (!strcmp(crypto_alg, "blowfish")) {
563                 priv->crypto_alg = CRYPTO_BLF_CBC;
564                 if (klen < 128 || klen > 448 || (klen % 8) != 0)
565                         goto notsup;
566                 priv->crypto_klen = klen;
567         } else if (!strcmp(crypto_alg, "3des") ||
568                    !strncmp(crypto_alg, "des3", 4)) {
569                 priv->crypto_alg = CRYPTO_3DES_CBC;
570                 if (klen != 168)
571                         goto notsup;
572                 priv->crypto_klen = 168;
573         } else if (!strcmp(crypto_alg, "camellia")) {
574                 priv->crypto_alg = CRYPTO_CAMELLIA_CBC;
575                 if (klen != 128 && klen != 192 && klen != 256)
576                         goto notsup;
577                 priv->crypto_klen = klen;
578         } else if (!strcmp(crypto_alg, "skipjack")) {
579                 priv->crypto_alg = CRYPTO_SKIPJACK_CBC;
580                 if (klen != 80)
581                         goto notsup;
582                 priv->crypto_klen = 80;
583         } else if (!strcmp(crypto_alg, "cast5")) {
584                 priv->crypto_alg = CRYPTO_CAST_CBC;
585                 if (klen != 128)
586                         goto notsup;
587                 priv->crypto_klen = 128;
588         } else if (!strcmp(crypto_alg, "null")) {
589                 priv->crypto_alg = CRYPTO_NULL_CBC;
590                 if (klen != 128)
591                         goto notsup;
592                 priv->crypto_klen = 128;
593         } else {
594                 kprintf("dm_target_crypt: Unsupported crypto algorithm: %s\n",
595                         crypto_alg);
596                 goto notsup;
597         }
598
599         /* Save length of param string */
600         priv->params_len = len;
601         priv->block_offset = block_offset;
602         priv->iv_offset = iv_offset - block_offset;
603
604         *target_config = priv;
605
606         dmv->dev_type = DM_CRYPTO_DEV;
607
608         error = hex2key(key, priv->crypto_klen >> 3,
609                         (u_int8_t *)priv->crypto_key);
610
611         if (error) {
612                 kprintf("dm_target_crypt: hex2key failed, "
613                         "invalid key format\n");
614                 goto notsup;
615         }
616
617         /* Handle cmd */
618         for(i = 0; ivgens[i].name != NULL; i++) {
619                 if (!strcmp(iv_mode, ivgens[i].name))
620                         break;
621         }
622
623         if (ivgens[i].name == NULL) {
624                 kprintf("dm_target_crypt: iv_mode='%s' unsupported\n",
625                         iv_mode);       
626                 goto notsup;
627         }
628
629         /* Call our ivgen constructor */
630         if (ivgens[i].ctor != NULL) {
631                 error = ivgens[i].ctor(priv, iv_opt,
632                     &priv->ivgen_priv);
633                 if (error) {
634                         kprintf("dm_target_crypt: ctor for '%s' failed\n",
635                             ivgens[i].name);
636                         goto notsup;
637                 }
638         }
639
640         priv->ivgen = &ivgens[i];
641
642         priv->crypto_session.cri_alg = priv->crypto_alg;
643         priv->crypto_session.cri_key = (u_int8_t *)priv->crypto_key;
644         priv->crypto_session.cri_klen = priv->crypto_klen;
645         priv->crypto_session.cri_mlen = 0;
646         priv->crypto_session.cri_next = NULL;
647
648         error = crypto_newsession(&priv->crypto_sid,
649                                   &priv->crypto_session,
650                                   CRYPTOCAP_F_SOFTWARE | CRYPTOCAP_F_HARDWARE);
651         if (error) {
652                 kprintf("dm_target_crypt: Error during crypto_newsession, "
653                         "error = %d\n",
654                         error);
655                 goto notsup;
656         }
657
658         priv->status_str = status_str;
659         return 0;
660
661 notsup:
662         kprintf("dm_target_crypt: ENOTSUP\n");
663         kfree(status_str, M_DMCRYPT);
664         return ENOTSUP;
665 }
666
667 /* Status routine called to get params string. */
668 char *
669 dm_target_crypt_status(void *target_config)
670 {
671         dm_target_crypt_config_t *priv;
672         char *params;
673
674         priv = target_config;
675
676         /* caller expects use of M_DM */
677         params = kmalloc(DM_MAX_PARAMS_SIZE, M_DM, M_WAITOK);
678
679         ksnprintf(params, DM_MAX_PARAMS_SIZE, "%s",
680             priv->status_str);
681
682         return params;
683 }
684
685 int
686 dm_target_crypt_destroy(dm_table_entry_t * table_en)
687 {
688         dm_target_crypt_config_t *priv;
689
690         /*
691          * Disconnect the crypt config before unbusying the target.
692          */
693         priv = table_en->target_config;
694         if (priv == NULL)
695                 return 0;
696         table_en->target_config = NULL;
697         dm_pdev_decr(priv->pdev);
698
699         dm_target_unbusy(table_en->target);
700
701         /*
702          * Clean up the crypt config
703          *
704          * Overwrite the private information before freeing memory to
705          * avoid leaking it.
706          */
707         dmtc_crypto_clear(priv->status_str, strlen(priv->status_str));
708         kfree(priv->status_str, M_DMCRYPT);
709
710         crypto_freesession(priv->crypto_sid);
711
712         if (priv->ivgen->dtor != NULL) {
713                 priv->ivgen->dtor(priv, priv->ivgen_priv);
714         }
715
716         dmtc_crypto_clear(priv, sizeof(dm_target_crypt_config_t));
717         kfree(priv, M_DMCRYPT);
718
719         return 0;
720 }
721
722 int
723 dm_target_crypt_deps(dm_table_entry_t * table_en, prop_array_t prop_array)
724 {
725         dm_target_crypt_config_t *priv;
726         struct vattr va;
727
728         int error;
729
730         if (table_en->target_config == NULL)
731                 return ENOENT;
732
733         priv = table_en->target_config;
734
735         if ((error = VOP_GETATTR(priv->pdev->pdev_vnode, &va)) != 0)
736                 return error;
737
738         prop_array_add_uint64(prop_array,
739                               (uint64_t)makeudev(va.va_rmajor, va.va_rminor));
740
741         return 0;
742 }
743
744 /* Unsupported for this target. */
745 int
746 dm_target_crypt_upcall(dm_table_entry_t * table_en, struct buf * bp)
747 {
748         return 0;
749 }
750
751 /************************************************************************
752  *                      STRATEGY SUPPORT FUNCTIONS                      *
753  ************************************************************************
754  *
755  * READ PATH:   doio -> bio_read_done -> crypto_work -> crypto_cb_read_done
756  * WRITE PATH:  crypto_work -> crypto_cb_write_done -> doio -> bio_write_done
757  */
758
759 /*
760  * Wrapper around crypto_dispatch() to match dispatch_t type
761  */
762 static void
763 dmtc_crypto_dispatch(void *arg)
764 {
765         struct cryptop *crp;
766
767         crp = (struct cryptop *)arg;
768         KKASSERT(crp != NULL);
769         crypto_dispatch(crp);
770 }
771  
772 /*
773  * Start IO operation, called from dmstrategy routine.
774  */
775 int
776 dm_target_crypt_strategy(dm_table_entry_t *table_en, struct buf *bp)
777 {
778         struct bio *bio;
779
780         dm_target_crypt_config_t *priv;
781         priv = table_en->target_config;
782
783         /* Get rid of stuff we can't really handle */
784         if ((bp->b_cmd == BUF_CMD_READ) || (bp->b_cmd == BUF_CMD_WRITE)) {
785                 if (((bp->b_bcount % DEV_BSIZE) != 0) || (bp->b_bcount == 0)) {
786                         kprintf("dm_target_crypt_strategy: can't really "
787                                 "handle bp->b_bcount = %d\n",
788                                 bp->b_bcount);
789                         bp->b_error = EINVAL;
790                         bp->b_flags |= B_ERROR | B_INVAL;
791                         biodone(&bp->b_bio1);
792                         return 0;
793                 }
794         }
795
796         switch (bp->b_cmd) {
797         case BUF_CMD_READ:
798                 bio = push_bio(&bp->b_bio1);
799                 bio->bio_offset = bp->b_bio1.bio_offset +
800                                   priv->block_offset * DEV_BSIZE;
801                 bio->bio_caller_info1.ptr = priv;
802                 bio->bio_done = dmtc_bio_read_done;
803                 vn_strategy(priv->pdev->pdev_vnode, bio);
804                 break;
805         case BUF_CMD_WRITE:
806                 bio = push_bio(&bp->b_bio1);
807                 bio->bio_offset = bp->b_bio1.bio_offset +
808                                   priv->block_offset * DEV_BSIZE;
809                 bio->bio_caller_info1.ptr = priv;
810                 dmtc_crypto_write_start(priv, bio);
811                 break;
812         default:
813                 vn_strategy(priv->pdev->pdev_vnode, &bp->b_bio1);
814                 break;
815         }
816         return 0;
817 }
818
819 /*
820  * STRATEGY READ PATH PART 1/3 (after read BIO completes)
821  */
822 static void
823 dmtc_bio_read_done(struct bio *bio)
824 {
825         struct bio *obio;
826
827         dm_target_crypt_config_t *priv;
828
829         /*
830          * If a read error occurs we shortcut the operation, otherwise
831          * go on to stage 2.
832          */
833         if (bio->bio_buf->b_flags & B_ERROR) {
834                 obio = pop_bio(bio);
835                 biodone(obio);
836         } else {
837                 priv = bio->bio_caller_info1.ptr;
838                 dmtc_crypto_read_start(priv, bio);
839         }
840 }
841
842 /*
843  * STRATEGY READ PATH PART 2/3
844  */
845 static void
846 dmtc_crypto_read_start(dm_target_crypt_config_t *priv, struct bio *bio)
847 {
848         struct dmtc_helper *dmtc;
849         struct cryptodesc *crd;
850         struct cryptop *crp;
851         struct cryptoini *cri;
852         int i, bytes, sectors, sz;
853         off_t isector;
854         u_char *ptr, *space;
855
856         cri = &priv->crypto_session;
857
858         /*
859          * Note: b_resid no good after read I/O, it will be 0, use
860          *       b_bcount.
861          */
862         bytes = bio->bio_buf->b_bcount;
863         isector = bio->bio_offset / DEV_BSIZE;  /* ivgen salt base? */
864         sectors = bytes / DEV_BSIZE;            /* Number of sectors */
865         sz = sectors * (sizeof(*crp) + sizeof(*crd));
866
867         /*
868          * For reads with bogus page we can't decrypt in place as stuff
869          * can get ripped out from under us.
870          *
871          * XXX actually it looks like we can, and in any case the initial
872          * read already completed and threw crypted data into the buffer
873          * cache buffer.  Disable for now.
874          */
875 #if 0
876         if (bio->bio_buf->b_flags & B_HASBOGUS) {
877                 space = kmalloc(sizeof(struct dmtc_helper) + sz + bytes,
878                                 M_DMCRYPT, M_WAITOK);
879                 dmtc = (struct dmtc_helper *)space;
880                 dmtc->free_addr = space;
881                 space += sizeof(struct dmtc_helper);
882                 dmtc->orig_buf = NULL;
883                 dmtc->data_buf = space + sz;
884                 memcpy(dmtc->data_buf, bio->bio_buf->b_data, bytes);
885         } else
886 #endif
887         {
888                 space = kmalloc(sizeof(struct dmtc_helper) + sz,
889                                 M_DMCRYPT, M_WAITOK);
890                 dmtc = (struct dmtc_helper *)space;
891                 dmtc->free_addr = space;
892                 space += sizeof(struct dmtc_helper);
893                 dmtc->orig_buf = NULL;
894                 dmtc->data_buf = bio->bio_buf->b_data;
895         }
896         bio->bio_caller_info2.ptr = dmtc;
897         bio->bio_buf->b_error = 0;
898
899         /*
900          * Load crypto descriptors (crp/crd loop)
901          */
902         bzero(space, sz);
903         ptr = space;
904         bio->bio_caller_info3.value = sectors;
905         cpu_sfence();
906 #if 0
907         kprintf("Read, bytes = %d (b_bcount), "
908                 "sectors = %d (bio = %p, b_cmd = %d)\n",
909                 bytes, sectors, bio, bio->bio_buf->b_cmd);
910 #endif
911         for (i = 0; i < sectors; i++) {
912                 crp = (struct cryptop *)ptr;
913                 ptr += sizeof(*crp);
914                 crd = (struct cryptodesc *)ptr;
915                 ptr += sizeof (*crd);
916
917                 crp->crp_buf = dmtc->data_buf + i * DEV_BSIZE;
918
919                 crp->crp_sid = priv->crypto_sid;
920                 crp->crp_ilen = crp->crp_olen = DEV_BSIZE;
921
922                 crp->crp_opaque = (void *)bio;
923
924                 crp->crp_callback = dmtc_crypto_cb_read_done;
925                 crp->crp_desc = crd;
926                 crp->crp_etype = 0;
927                 crp->crp_flags = CRYPTO_F_CBIFSYNC | CRYPTO_F_REL |
928                                  CRYPTO_F_BATCH;
929
930                 crd->crd_alg = priv->crypto_alg;
931 #if 0
932                 crd->crd_key = (caddr_t)priv->crypto_key;
933                 crd->crd_klen = priv->crypto_klen;
934 #endif
935
936                 crd->crd_skip = 0;
937                 crd->crd_len = DEV_BSIZE /* XXX */;
938                 crd->crd_flags = CRD_F_IV_EXPLICIT | CRD_F_IV_PRESENT;
939                 crd->crd_next = NULL;
940
941                 crd->crd_flags &= ~CRD_F_ENCRYPT;
942
943                 /*
944                  * Note: last argument is used to generate salt(?) and is
945                  *       a 64 bit value, but the original code passed an
946                  *       int.  Changing it now will break pre-existing
947                  *       crypt volumes.
948                  */
949                 priv->ivgen->gen_iv(priv, crd->crd_iv, sizeof(crd->crd_iv),
950                                     isector + i, crp);
951         }
952 }
953
954 /*
955  * STRATEGY READ PATH PART 3/3
956  */
957 static int
958 dmtc_crypto_cb_read_done(struct cryptop *crp)
959 {
960         struct dmtc_helper *dmtc;
961         struct bio *bio, *obio;
962         int n;
963
964         if (crp->crp_etype == EAGAIN)
965                 return crypto_dispatch(crp);
966
967         bio = (struct bio *)crp->crp_opaque;
968         KKASSERT(bio != NULL);
969
970         /*
971          * Cumulative error
972          */
973         if (crp->crp_etype) {
974                 kprintf("dm_target_crypt: dmtc_crypto_cb_read_done "
975                         "crp_etype = %d\n",
976                         crp->crp_etype);
977                 bio->bio_buf->b_error = crp->crp_etype;
978         }
979
980         /*
981          * On the last chunk of the decryption we do any required copybacks
982          * and complete the I/O.
983          */
984         n = atomic_fetchadd_int(&bio->bio_caller_info3.value, -1);
985 #if 0
986         kprintf("dmtc_crypto_cb_read_done %p, n = %d\n", bio, n);
987 #endif
988
989         if (n == 1) {
990                 /*
991                  * For the B_HASBOGUS case we didn't decrypt in place,
992                  * so we need to copy stuff back into the buf.
993                  *
994                  * (disabled for now).
995                  */
996                 dmtc = bio->bio_caller_info2.ptr;
997                 if (bio->bio_buf->b_error) {
998                         bio->bio_buf->b_flags |= B_ERROR;
999                 }
1000 #if 0
1001                 else if (bio->bio_buf->b_flags & B_HASBOGUS) {
1002                         memcpy(bio->bio_buf->b_data, dmtc->data_buf,
1003                                bio->bio_buf->b_bcount);
1004                 }
1005 #endif
1006                 kfree(dmtc->free_addr, M_DMCRYPT);
1007                 obio = pop_bio(bio);
1008                 biodone(obio);
1009         }
1010         return 0;
1011 }
1012 /* END OF STRATEGY READ SECTION */
1013
1014 /*
1015  * STRATEGY WRITE PATH PART 1/3
1016  */
1017 static void
1018 dmtc_crypto_write_start(dm_target_crypt_config_t *priv, struct bio *bio)
1019 {
1020         struct dmtc_helper *dmtc;
1021         struct cryptodesc *crd;
1022         struct cryptop *crp;
1023         struct cryptoini *cri;
1024         int i, bytes, sectors, sz;
1025         off_t isector;
1026         u_char *ptr, *space;
1027
1028         cri = &priv->crypto_session;
1029
1030         /*
1031          * Use b_bcount for consistency
1032          */
1033         bytes = bio->bio_buf->b_bcount;
1034
1035         isector = bio->bio_offset / DEV_BSIZE;  /* ivgen salt base? */
1036         sectors = bytes / DEV_BSIZE;            /* Number of sectors */
1037         sz = sectors * (sizeof(*crp) + sizeof(*crd));
1038
1039         /*
1040          * For writes and reads with bogus page don't decrypt in place.
1041          */
1042         space = kmalloc(sizeof(struct dmtc_helper) + sz + bytes,
1043                         M_DMCRYPT, M_WAITOK);
1044         dmtc = (struct dmtc_helper *)space;
1045         dmtc->free_addr = space;
1046         space += sizeof(struct dmtc_helper);
1047         memcpy(space + sz, bio->bio_buf->b_data, bytes);
1048
1049         bio->bio_caller_info2.ptr = dmtc;
1050         bio->bio_buf->b_error = 0;
1051
1052         dmtc->orig_buf = bio->bio_buf->b_data;
1053         dmtc->data_buf = space + sz;
1054
1055         /*
1056          * Load crypto descriptors (crp/crd loop)
1057          */
1058         bzero(space, sz);
1059         ptr = space;
1060         bio->bio_caller_info3.value = sectors;
1061         cpu_sfence();
1062 #if 0
1063         kprintf("Write, bytes = %d (b_bcount), "
1064                 "sectors = %d (bio = %p, b_cmd = %d)\n",
1065                 bytes, sectors, bio, bio->bio_buf->b_cmd);
1066 #endif
1067         for (i = 0; i < sectors; i++) {
1068                 crp = (struct cryptop *)ptr;
1069                 ptr += sizeof(*crp);
1070                 crd = (struct cryptodesc *)ptr;
1071                 ptr += sizeof (*crd);
1072
1073                 crp->crp_buf = dmtc->data_buf + i * DEV_BSIZE;
1074
1075                 crp->crp_sid = priv->crypto_sid;
1076                 crp->crp_ilen = crp->crp_olen = DEV_BSIZE;
1077
1078                 crp->crp_opaque = (void *)bio;
1079
1080                 crp->crp_callback = dmtc_crypto_cb_write_done;
1081                 crp->crp_desc = crd;
1082                 crp->crp_etype = 0;
1083                 crp->crp_flags = CRYPTO_F_CBIFSYNC | CRYPTO_F_REL |
1084                                  CRYPTO_F_BATCH;
1085
1086                 crd->crd_alg = priv->crypto_alg;
1087 #if 0
1088                 crd->crd_key = (caddr_t)priv->crypto_key;
1089                 crd->crd_klen = priv->crypto_klen;
1090 #endif
1091
1092                 crd->crd_skip = 0;
1093                 crd->crd_len = DEV_BSIZE /* XXX */;
1094                 crd->crd_flags = CRD_F_IV_EXPLICIT | CRD_F_IV_PRESENT;
1095                 crd->crd_next = NULL;
1096
1097                 crd->crd_flags |= CRD_F_ENCRYPT;
1098
1099                 /*
1100                  * Note: last argument is used to generate salt(?) and is
1101                  *       a 64 bit value, but the original code passed an
1102                  *       int.  Changing it now will break pre-existing
1103                  *       crypt volumes.
1104                  */
1105                 priv->ivgen->gen_iv(priv, crd->crd_iv, sizeof(crd->crd_iv),
1106                                     isector + i, crp);
1107         }
1108 }
1109
1110 /*
1111  * STRATEGY WRITE PATH PART 2/3
1112  */
1113 static int
1114 dmtc_crypto_cb_write_done(struct cryptop *crp)
1115 {
1116         struct dmtc_helper *dmtc;
1117         dm_target_crypt_config_t *priv;
1118         struct bio *bio, *obio;
1119         int n;
1120
1121         if (crp->crp_etype == EAGAIN)
1122                 return crypto_dispatch(crp);
1123
1124         bio = (struct bio *)crp->crp_opaque;
1125         KKASSERT(bio != NULL);
1126
1127         /*
1128          * Cumulative error
1129          */
1130         if (crp->crp_etype != 0) {
1131                 kprintf("dm_target_crypt: dmtc_crypto_cb_write_done "
1132                         "crp_etype = %d\n",
1133                 crp->crp_etype);
1134                 bio->bio_buf->b_error = crp->crp_etype;
1135         }
1136
1137         /*
1138          * On the last chunk of the encryption we issue the write
1139          */
1140         n = atomic_fetchadd_int(&bio->bio_caller_info3.value, -1);
1141 #if 0
1142         kprintf("dmtc_crypto_cb_write_done %p, n = %d\n", bio, n);
1143 #endif
1144
1145         if (n == 1) {
1146                 dmtc = bio->bio_caller_info2.ptr;
1147                 priv = (dm_target_crypt_config_t *)bio->bio_caller_info1.ptr;
1148
1149                 if (bio->bio_buf->b_error) {
1150                         bio->bio_buf->b_flags |= B_ERROR;
1151                         kfree(dmtc->free_addr, M_DMCRYPT);
1152                         obio = pop_bio(bio);
1153                         biodone(obio);
1154                 } else {
1155                         dmtc->orig_buf = bio->bio_buf->b_data;
1156                         bio->bio_buf->b_data = dmtc->data_buf;
1157                         bio->bio_done = dmtc_bio_write_done;
1158                         vn_strategy(priv->pdev->pdev_vnode, bio);
1159                 }
1160         }
1161         return 0;
1162 }
1163
1164 /*
1165  * STRATEGY WRITE PATH PART 3/3
1166  */
1167 static void
1168 dmtc_bio_write_done(struct bio *bio)
1169 {
1170         struct dmtc_helper *dmtc;
1171         struct bio *obio;
1172
1173         dmtc = bio->bio_caller_info2.ptr;
1174         bio->bio_buf->b_data = dmtc->orig_buf;
1175         kfree(dmtc->free_addr, M_DMCRYPT);
1176         obio = pop_bio(bio);
1177         biodone(obio);
1178 }
1179 /* END OF STRATEGY WRITE SECTION */