TCRYPT: parse cipher chain on init.
[platform/upstream/cryptsetup.git] / lib / tcrypt / tcrypt.c
1 /*
2  * TCRYPT compatible volume handling
3  *
4  * Copyright (C) 2012, Red Hat, Inc. All rights reserved.
5  * Copyright (C) 2012, Milan Broz
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * version 2 as published by the Free Software Foundation.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19  */
20
21 #include <errno.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <fcntl.h>
26 #include <assert.h>
27
28 #include "libcryptsetup.h"
29 #include "tcrypt.h"
30 #include "internal.h"
31
32 /* TCRYPT PBKDF variants */
33 static struct {
34         unsigned int legacy:1;
35         char *name;
36         char *hash;
37         unsigned int iterations;
38 } tcrypt_kdf[] = {
39         { 0, "pbkdf2", "ripemd160", 2000 },
40         { 0, "pbkdf2", "ripemd160", 1000 },
41         { 0, "pbkdf2", "sha512",    1000 },
42         { 0, "pbkdf2", "whirlpool", 1000 },
43         { 1, "pbkdf2", "sha1",      2000 },
44         { 0, NULL,     NULL,           0 }
45 };
46
47 struct tcrypt_alg {
48                 const char *name;
49                 unsigned int key_size;
50                 unsigned int iv_size;
51 };
52
53 /* TCRYPT cipher variants */
54 static struct {
55         unsigned int legacy:1;
56         const char *mode;
57         struct tcrypt_alg cipher[3];
58 } tcrypt_cipher[] = {
59         { 0, "xts-plain64",{{"aes",    64,16}}},
60         { 0, "xts-plain64",{{"serpent",64,16}}},
61         { 0, "xts-plain64",{{"twofish",64,16}}},
62         { 0, "xts-plain64",{{"twofish",64,16},{"aes",    64,16}}},
63         { 0, "xts-plain64",{{"serpent",64,16},{"twofish",64,16},{"aes",    64,16}}},
64         { 0, "xts-plain64",{{"aes",    64,16},{"serpent",64,16}}},
65         { 0, "xts-plain64",{{"aes",    64,16},{"twofish",64,16},{"serpent",64,16}}},
66         { 0, "xts-plain64",{{"serpent",64,16},{"twofish",64,16}}},
67
68         { 0, "lrw-benbi",  {{"aes",    48,16}}},
69         { 0, "lrw-benbi",  {{"serpent",48,16}}},
70         { 0, "lrw-benbi",  {{"twofish",48,16}}},
71         { 0, "lrw-benbi",  {{"twofish",48,16},{"aes",    48,16}}},
72         { 0, "lrw-benbi",  {{"serpent",48,16},{"twofish",48,16},{"aes",    48,16}}},
73         { 0, "lrw-benbi",  {{"aes",    48,16},{"serpent",48,16}}},
74         { 0, "lrw-benbi",  {{"aes",    48,16},{"twofish",48,16},{"serpent",48,16}}},
75         { 0, "lrw-benbi",  {{"serpent",48,16},{"twofish",48,16}}},
76
77         { 1, "cbc-tcrypt", {{"aes",    32,16}}},
78         { 1, "cbc-tcrypt", {{"serpent",32,16}}},
79         { 1, "cbc-tcrypt", {{"twofish",32,16}}},
80         { 1, "cbci-tcrypt",{{"twofish",32,16},{"aes",    32,16}}},
81         { 1, "cbci-tcrypt",{{"serpent",32,16},{"twofish",32,16},{"aes",    32,16}}},
82         { 1, "cbci-tcrypt",{{"aes",    32,16},{"serpent",32,16}}},
83         { 1, "cbci-tcrypt",{{"aes",    32,16},{"twofish",32,16},{"serpent",32,16}}},
84         { 1, "cbci-tcrypt",{{"serpent",32,16},{"twofish",32,16}}},
85
86         { 1, "cbc-tcrypt", {{"cast5",   16,8}}},
87         { 1, "cbc-tcrypt", {{"des3_ede",24,8}}},
88
89         // kernel LRW block size is fixed to 16 bytes
90         // thus cannot be used with blowfish where block is 8 bytes
91         //{ 1,"lrw-benbi",{{"blowfish",64,8}}},
92         //{ 1,"lrw-benbi",{{"blowfish",64,8},{"aes",48,16}}},
93         //{ 1,"lrw-benbi",{{"serpent",48,16},{"blowfish",64,8},{"aes",48,16}}},
94
95         // FIXME: why this doesn't work (blowfish key wrong)?
96         //{ 1,"cbc-tcrypt",{{"blowfish",56,8}}},
97         //{ 1,"cbc-tcrypt",{{"blowfish",56,8},{"aes",32,16}}},
98         //{ 1,"cbc-tcrypt",{{"serpent",32,16},{"blowfish",56,8},{"aes",32,16}}},
99         {}
100 };
101
102 static void hdr_info(struct crypt_device *cd, struct tcrypt_phdr *hdr,
103                      struct crypt_params_tcrypt *params)
104 {
105         log_dbg("Version: %d, required %d", (int)hdr->d.version, (int)hdr->d.version_tc);
106
107         log_dbg("Hidden size: %" PRIu64, hdr->d.hidden_volume_size);
108         log_dbg("Volume size: %" PRIu64, hdr->d.volume_size);
109
110         log_dbg("Sector size: %" PRIu64, hdr->d.sector_size);
111         log_dbg("Flags: %d", (int)hdr->d.flags);
112         log_dbg("MK: offset %d, size %d", (int)hdr->d.mk_offset, (int)hdr->d.mk_size);
113         log_dbg("KDF: PBKDF2, hash %s", params->hash_name);
114         log_dbg("Cipher: %s-%s", params->cipher, params->mode);
115 }
116
117 static int hdr_from_disk(struct tcrypt_phdr *hdr,
118                          struct crypt_params_tcrypt *params,
119                          int kdf_index, int cipher_index)
120 {
121         char cipher_name[MAX_CIPHER_LEN * 4];
122         uint32_t crc32;
123         size_t size;
124
125         /* Check CRC32 of header */
126         size = TCRYPT_HDR_LEN - sizeof(hdr->d.keys) - sizeof(hdr->d.header_crc32);
127         crc32 = crypt_crc32(~0, (unsigned char*)&hdr->d, size) ^ ~0;
128         if (be16_to_cpu(hdr->d.version) > 3 &&
129             crc32 != be32_to_cpu(hdr->d.header_crc32)) {
130                 log_dbg("TCRYPT header CRC32 mismatch.");
131                 return -EINVAL;
132         }
133
134         /* Check CRC32 of keys */
135         crc32 = crypt_crc32(~0, (unsigned char*)hdr->d.keys, sizeof(hdr->d.keys)) ^ ~0;
136         if (crc32 != be32_to_cpu(hdr->d.keys_crc32)) {
137                 log_dbg("TCRYPT keys CRC32 mismatch.");
138                 return -EINVAL;
139         }
140
141         /* Convert header to cpu format */
142         hdr->d.version  =  be16_to_cpu(hdr->d.version);
143         hdr->d.version_tc = le16_to_cpu(hdr->d.version_tc); // ???
144
145         hdr->d.keys_crc32 = be32_to_cpu(hdr->d.keys_crc32);
146
147         hdr->d.hidden_volume_size = be64_to_cpu(hdr->d.hidden_volume_size);
148         hdr->d.volume_size        = be64_to_cpu(hdr->d.volume_size);
149
150         hdr->d.mk_offset = be64_to_cpu(hdr->d.mk_offset);
151         if (!hdr->d.mk_offset)
152                 hdr->d.mk_offset = 512;
153
154         hdr->d.mk_size = be64_to_cpu(hdr->d.mk_size);
155
156         hdr->d.flags = be32_to_cpu(hdr->d.flags);
157
158         hdr->d.sector_size = be32_to_cpu(hdr->d.sector_size);
159         if (!hdr->d.sector_size)
160                 hdr->d.sector_size = 512;
161
162         hdr->d.header_crc32 = be32_to_cpu(hdr->d.header_crc32);
163
164         /* Set params */
165         params->passphrase = NULL;
166         params->passphrase_size = 0;
167
168         params->hash_name  = tcrypt_kdf[kdf_index].hash;
169
170         params->key_size = tcrypt_cipher[cipher_index].cipher[0].key_size;
171         strncpy(cipher_name, tcrypt_cipher[cipher_index].cipher[0].name,
172                 sizeof(cipher_name));
173
174         if (tcrypt_cipher[cipher_index].cipher[1].name) {
175                 strcat(cipher_name, "-");
176                 strncat(cipher_name, tcrypt_cipher[cipher_index].cipher[1].name,
177                         MAX_CIPHER_LEN);
178                 params->key_size += tcrypt_cipher[cipher_index].cipher[1].key_size;
179         }
180
181         if (tcrypt_cipher[cipher_index].cipher[2].name) {
182                 strcat(cipher_name, "-");
183                 strncat(cipher_name, tcrypt_cipher[cipher_index].cipher[2].name,
184                         MAX_CIPHER_LEN);
185                 params->key_size += tcrypt_cipher[cipher_index].cipher[2].key_size;
186         }
187
188         params->cipher = strdup(cipher_name);
189         params->mode   = strdup(tcrypt_cipher[cipher_index].mode);
190
191         return 0;
192 }
193
194 static int decrypt_hdr_one(const char *name, const char *mode,
195                            const char *key, size_t key_size,
196                            size_t iv_size, struct tcrypt_phdr *hdr)
197 {
198         char iv[TCRYPT_HDR_IV_LEN] = {};
199         char mode_name[MAX_CIPHER_LEN];
200         struct crypt_cipher *cipher;
201         char *c, *buf = (char*)&hdr->e;
202         int r;
203
204         /* Remove IV if present */
205         strncpy(mode_name, mode, MAX_CIPHER_LEN);
206         c = strchr(mode_name, '-');
207         if (c)
208                 *c = '\0';
209
210         if (!strncmp(mode, "lrw", 3))
211                 iv[iv_size - 1] = 1;
212         else if (!strncmp(mode, "cbc", 3))
213                 memcpy(iv, &key[key_size], iv_size);
214
215         r = crypt_cipher_init(&cipher, name, mode_name, key, key_size);
216         if (r < 0)
217                 return r;
218
219         r = crypt_cipher_decrypt(cipher, buf, buf, TCRYPT_HDR_LEN, iv, iv_size);
220         crypt_cipher_destroy(cipher);
221
222         return r;
223 }
224
225 static void copy_key(char *out_key, const char *key, int key_num,
226                      int ks, int ki, const char *mode)
227 {
228         if (!strncmp(mode, "xts", 3)) {
229                 int ks2 = ks / 2;
230                 memcpy(out_key, &key[ks2 * ki], ks2);
231                 memcpy(&out_key[ks2], &key[ks2 * (++key_num + ki)], ks2);
232         } else if (!strncmp(mode, "lrw", 3)) {
233                 /* First is LRW index key */
234                 ki++;
235                 ks -= TCRYPT_LRW_IKEY_LEN;
236                 memcpy(out_key, &key[ks * ki], ks);
237                 memcpy(&out_key[ks * ki], key, TCRYPT_LRW_IKEY_LEN);
238         } else if (!strncmp(mode, "cbc", 3)) {
239                 ki++;
240                 memcpy(out_key, &key[ki * 32], ks);
241                 memcpy(&out_key[ks], key, 32);
242         }
243 }
244
245 /*
246  * For chanined ciphers and CBC mode we need "inner" decryption.
247  * Backend doesn't provide this, so implement it here directly using ECB.
248  */
249 static int decrypt_hdr_cbci(struct tcrypt_alg ciphers[3],
250                              const char *key, struct tcrypt_phdr *hdr)
251 {
252         struct crypt_cipher *cipher[3] = {};
253         int bs = ciphers[0].iv_size;
254         char *buf = (char*)&hdr->e, iv[bs], iv_old[bs];
255         int i, j, r;
256
257         memcpy(iv, key, bs);
258
259         /* Initialize all ciphers in chain in ECB mode */
260         for (j = 0; j < 3; j++) {
261                 if (!ciphers[j].name)
262                         continue;
263                 r = crypt_cipher_init(&cipher[j], ciphers[j].name, "ecb",
264                                       &key[(j+1)*32], ciphers[j].key_size);
265                 if (r < 0)
266                         goto out;
267         }
268
269         /* Implements CBC with chained ciphers in inner loop */
270         for (i = 0; i < TCRYPT_HDR_LEN; i += bs) {
271                 memcpy(iv_old, &buf[i], bs);
272                 for (j = 2; j >= 0; j--) {
273                         if (!cipher[j])
274                                 continue;
275                         r = crypt_cipher_decrypt(cipher[j], &buf[i], &buf[i],
276                                                   bs, NULL, 0);
277                         if (r < 0)
278                                 goto out;
279                 }
280                 for (j = 0; j < bs; j++)
281                         buf[i + j] ^= iv[j];
282                 memcpy(iv, iv_old, bs);
283         }
284 out:
285         for (j = 0; j < 3; j++)
286                 if (cipher[j])
287                         crypt_cipher_destroy(cipher[j]);
288
289         return r;
290 }
291
292 static int top_cipher(struct tcrypt_alg cipher[3])
293 {
294         if (cipher[2].name)
295                 return 2;
296
297         if (cipher[1].name)
298                 return 1;
299
300         return 0;
301 }
302
303 static int decrypt_hdr(struct crypt_device *cd, struct tcrypt_phdr *hdr,
304                         const char *key, int legacy_modes)
305 {
306         char one_key[TCRYPT_HDR_KEY_LEN];
307         struct tcrypt_phdr hdr2;
308         int i, j, r;
309
310         for (i = 0; tcrypt_cipher[i].cipher[0].name; i++) {
311                 if (!legacy_modes && tcrypt_cipher[i].legacy)
312                         continue;
313                 log_dbg("TCRYPT:  trying cipher: %s%s%s%s%s-%s.",
314                         tcrypt_cipher[i].cipher[0].name,
315                         tcrypt_cipher[i].cipher[1].name ? "-" : "", tcrypt_cipher[i].cipher[1].name ?: "",
316                         tcrypt_cipher[i].cipher[2].name ? "-" : "", tcrypt_cipher[i].cipher[2].name ?: "",
317                         tcrypt_cipher[i].mode);
318
319                 memcpy(&hdr2.e, &hdr->e, TCRYPT_HDR_LEN);
320
321                 /* Remove CBC whitening */
322                 if (!strncmp(tcrypt_cipher[i].mode, "cbc", 3)) {
323                         char *buf = (char*)&hdr2.e;
324                         for (j = 0; j < TCRYPT_HDR_LEN; j++)
325                                 buf[j] ^= key[8 + j % 8];
326                 }
327
328                 /* For chained (inner) CBC we do not have API support */
329                 if (!strncmp(tcrypt_cipher[i].mode, "cbci", 4))
330                         r = decrypt_hdr_cbci(tcrypt_cipher[i].cipher, key, &hdr2);
331                 else for (j = 2; j >= 0 ; j--) {
332                         if (!tcrypt_cipher[i].cipher[j].name)
333                                 continue;
334                         copy_key(one_key, key, top_cipher(tcrypt_cipher[i].cipher),
335                                  tcrypt_cipher[i].cipher[j].key_size,
336                                  j, tcrypt_cipher[i].mode);
337                         r = decrypt_hdr_one(tcrypt_cipher[i].cipher[j].name,
338                                             tcrypt_cipher[i].mode, one_key,
339                                             tcrypt_cipher[i].cipher[j].key_size,
340                                             tcrypt_cipher[i].cipher[j].iv_size, &hdr2);
341                         if (r < 0) {
342                                 log_dbg("Error %s.", tcrypt_cipher[i].cipher[j].name);
343                                 break;
344                         }
345                 }
346
347                 if (!strncmp(hdr2.d.magic, TCRYPT_HDR_MAGIC, TCRYPT_HDR_MAGIC_LEN)) {
348                         log_dbg("TCRYPT: Signature magic detected.");
349                         memcpy(&hdr->e, &hdr2.e, TCRYPT_HDR_LEN);
350                         memset(&hdr2.e, 0, TCRYPT_HDR_LEN);
351                         r = i;
352                         break;
353                 }
354                 r = -EPERM;
355         }
356
357         memset(one_key, 0, sizeof(*one_key));
358         return r;
359 }
360
361 static int pool_keyfile(struct crypt_device *cd,
362                         unsigned char pool[TCRYPT_KEY_POOL_LEN],
363                         const char *keyfile)
364 {
365         unsigned char data[TCRYPT_KEYFILE_LEN];
366         int i, j, fd, data_size;
367         uint32_t crc;
368         unsigned char *crc_c = (unsigned char*)&crc;
369
370         log_dbg("TCRYPT: using keyfile %s.", keyfile);
371
372         fd = open(keyfile, O_RDONLY);
373         if (fd < 0) {
374                 log_err(cd, _("Failed to open key file.\n"));
375                 return -EIO;
376         }
377
378         /* FIXME: add while */
379         data_size = read(fd, data, TCRYPT_KEYFILE_LEN);
380         close(fd);
381         if (data_size < 0) {
382                 log_err(cd, _("Error reading keyfile %s.\n"), keyfile);
383                 return -EIO;
384         }
385
386         for (i = 0, j = 0, crc = ~0U; i < data_size; i++) {
387                 crc = crypt_crc32(crc, &data[i], 1);
388                 pool[j++] += crc_c[3];
389                 pool[j++] += crc_c[2];
390                 pool[j++] += crc_c[1];
391                 pool[j++] += crc_c[0];
392                 j %= TCRYPT_KEY_POOL_LEN;
393         }
394
395         crc = 0;
396         memset(data, 0, TCRYPT_KEYFILE_LEN);
397
398         return 0;
399 }
400
401 static int TCRYPT_init_hdr(struct crypt_device *cd,
402                            struct tcrypt_phdr *hdr,
403                            struct crypt_params_tcrypt *params)
404 {
405         unsigned char pwd[TCRYPT_KEY_POOL_LEN] = {};
406         size_t passphrase_size;
407         char *key;
408         int r, i, legacy_modes;
409
410         if (posix_memalign((void*)&key, crypt_getpagesize(), TCRYPT_HDR_KEY_LEN))
411                 return -ENOMEM;
412
413         if (params->keyfiles_count)
414                 passphrase_size = TCRYPT_KEY_POOL_LEN;
415         else
416                 passphrase_size = params->passphrase_size;
417
418         /* Calculate pool content from keyfiles */
419         for (i = 0; i < params->keyfiles_count; i++) {
420                 r = pool_keyfile(cd, pwd, params->keyfiles[i]);
421                 if (r < 0)
422                         goto out;
423         }
424
425         /* If provided password, combine it with pool */
426         for (i = 0; i < params->passphrase_size; i++)
427                 pwd[i] += params->passphrase[i];
428
429         legacy_modes = params->flags & CRYPT_TCRYPT_LEGACY_MODES ? 1 : 0;
430         for (i = 0; tcrypt_kdf[i].name; i++) {
431                 if (!legacy_modes && tcrypt_kdf[i].legacy)
432                         continue;
433                 /* Derive header key */
434                 log_dbg("TCRYPT: trying KDF: %s-%s-%d.",
435                         tcrypt_kdf[i].name, tcrypt_kdf[i].hash, tcrypt_kdf[i].iterations);
436                 r = crypt_pbkdf(tcrypt_kdf[i].name, tcrypt_kdf[i].hash,
437                                 (char*)pwd, passphrase_size,
438                                 hdr->salt, TCRYPT_HDR_SALT_LEN,
439                                 key, TCRYPT_HDR_KEY_LEN,
440                                 tcrypt_kdf[i].iterations);
441                 if (r < 0)
442                         break;
443
444                 /* Decrypt header */
445                 r = decrypt_hdr(cd, hdr, key, legacy_modes);
446                 if (r != -EPERM)
447                         break;
448         }
449
450         if (r < 0)
451                 goto out;
452
453         r = hdr_from_disk(hdr, params, i, r);
454         if (r < 0)
455                 goto out;
456
457         hdr_info(cd, hdr, params);
458 out:
459         memset(pwd, 0, TCRYPT_KEY_POOL_LEN);
460         if (key)
461                 memset(key, 0, TCRYPT_HDR_KEY_LEN);
462         free(key);
463         return r;
464 }
465
466 int TCRYPT_read_phdr(struct crypt_device *cd,
467                      struct tcrypt_phdr *hdr,
468                      struct crypt_params_tcrypt *params)
469 {
470         struct device *device = crypt_metadata_device(cd);
471         ssize_t hdr_size = sizeof(struct tcrypt_phdr);
472         int devfd = 0, r;
473
474         assert(sizeof(struct tcrypt_phdr) == 512);
475
476         log_dbg("Reading TCRYPT header of size %d bytes from device %s.",
477                 hdr_size, device_path(device));
478
479         devfd = open(device_path(device), O_RDONLY | O_DIRECT);
480         if (devfd == -1) {
481                 log_err(cd, _("Cannot open device %s.\n"), device_path(device));
482                 return -EINVAL;
483         }
484
485         if ((params->flags & CRYPT_TCRYPT_HIDDEN_HEADER) &&
486             lseek(devfd, TCRYPT_HDR_HIDDEN_OFFSET, SEEK_SET) < 0) {
487                 log_err(cd, _("Cannot seek to hidden header for %s.\n"), device_path(device));
488                 close(devfd);
489                 return -EIO;
490         }
491
492         if (read_blockwise(devfd, device_block_size(device), hdr, hdr_size) == hdr_size)
493                 r = TCRYPT_init_hdr(cd, hdr, params);
494         else
495                 r = -EIO;
496
497         close(devfd);
498         return r;
499 }
500
501 int TCRYPT_activate(struct crypt_device *cd,
502                      const char *name,
503                      struct tcrypt_phdr *hdr,
504                      struct crypt_params_tcrypt *params,
505                      uint32_t flags)
506 {
507         char cipher[MAX_CIPHER_LEN], dm_name[PATH_MAX], dm_dev_name[PATH_MAX];
508         struct device *device = NULL;
509         int i, r, num_ciphers;
510         char cname[3][MAX_CIPHER_LEN];
511         struct crypt_dm_active_device dmd = {
512                 .target = DM_CRYPT,
513                 .size   = 0,
514                 .data_device = crypt_data_device(cd),
515                 .u.crypt  = {
516                         .cipher = cipher,
517                         .offset = crypt_get_data_offset(cd),
518                         .iv_offset = crypt_get_iv_offset(cd),
519                 }
520         };
521
522         if (strstr(params->mode, "-tcrypt")) {
523                 log_err(cd, _("Kernel doesn't support activation for this TCRYPT legacy mode.\n"));
524                 return -ENOTSUP;
525         }
526
527         r = device_block_adjust(cd, dmd.data_device, DEV_EXCL,
528                                 dmd.u.crypt.offset, &dmd.size, &dmd.flags);
529         if (r)
530                 return r;
531
532         /* Parse cipher chain from c1[-c2[-c3]] */
533         cname[0][0] = cname[1][0] = cname[2][0] = '\0';
534         num_ciphers = sscanf(params->cipher, "%" MAX_CIPHER_LEN_STR "[^-]-%"
535                                                   MAX_CIPHER_LEN_STR "[^-]-%"
536                                                   MAX_CIPHER_LEN_STR "s",
537                       cname[0], cname[1], cname[2]);
538         if (num_ciphers < 1)
539                 return -EINVAL;
540
541         /* Frome here, key size for every cipher must be the same */
542         dmd.u.crypt.vk = crypt_alloc_volume_key(params->key_size / num_ciphers, NULL);
543         if (!dmd.u.crypt.vk)
544                 return -ENOMEM;
545
546         for (i = 2; i >= 0; i--) {
547
548                 if (!cname[i][0])
549                         continue;
550
551                 if (i == 0) {
552                         strncpy(dm_name, name, sizeof(dm_name));
553                         dmd.flags = flags;
554                 } else {
555                         snprintf(dm_name, sizeof(dm_name), "%s_%d", name, i);
556                         dmd.flags = flags | CRYPT_ACTIVATE_PRIVATE;
557                 }
558
559                 snprintf(cipher, sizeof(cipher), "%s-%s",
560                          cname[i], params->mode);
561                 copy_key(dmd.u.crypt.vk->key, hdr->d.keys, num_ciphers - 1,
562                          params->key_size / num_ciphers, i, params->mode);
563
564                 if ((num_ciphers -1) != i) {
565                         snprintf(dm_dev_name, sizeof(dm_dev_name), "%s/%s_%d",
566                                  dm_get_dir(), name, i + 1);
567                         r = device_alloc(&device, dm_dev_name);
568                         if (r)
569                                 break;
570                         dmd.data_device = device;
571                         dmd.u.crypt.offset = 0;
572                 }
573
574                 log_dbg("Trying to activate TCRYPT device %s using cipher %s.",
575                         dm_name, dmd.u.crypt.cipher);
576                 r = dm_create_device(cd, dm_name, CRYPT_TCRYPT, &dmd, 0);
577
578                 device_free(device);
579                 device = NULL;
580
581                 if (r)
582                         break;
583         }
584
585         if (!r && !(dm_flags() & DM_PLAIN64_SUPPORTED)) {
586                 log_err(cd, _("Kernel doesn't support plain64 IV.\n"));
587                 r = -ENOTSUP;
588         }
589
590         crypt_free_volume_key(dmd.u.crypt.vk);
591         return r;
592 }
593
594 static int remove_one(struct crypt_device *cd, const char *name,
595                       const char *base_uuid, int index)
596 {
597         struct crypt_dm_active_device dmd = {};
598         char dm_name[PATH_MAX];
599         int r;
600
601         if (snprintf(dm_name, sizeof(dm_name), "%s_%d", name, index) < 0)
602                 return -ENOMEM;
603
604         r = dm_status_device(cd, dm_name);
605         if (r < 0)
606                 return r;
607
608         r = dm_query_device(cd, dm_name, DM_ACTIVE_UUID, &dmd);
609         if (!r && !strncmp(dmd.uuid, base_uuid, strlen(base_uuid)))
610                 r = dm_remove_device(cd, dm_name, 0, 0);
611
612         free(CONST_CAST(void*)dmd.uuid);
613         return r;
614 }
615
616 int TCRYPT_deactivate(struct crypt_device *cd, const char *name)
617 {
618         struct crypt_dm_active_device dmd = {};
619         int r;
620
621         r = dm_query_device(cd, name, DM_ACTIVE_UUID, &dmd);
622         if (r < 0)
623                 return r;
624         if (!dmd.uuid)
625                 return -EINVAL;
626
627         r = dm_remove_device(cd, name, 0, 0);
628         if (r < 0)
629                 goto out;
630
631         r = remove_one(cd, name, dmd.uuid, 1);
632         if (r < 0)
633                 goto out;
634
635         r = remove_one(cd, name, dmd.uuid, 2);
636         if (r < 0)
637                 goto out;
638 out:
639         free(CONST_CAST(void*)dmd.uuid);
640         return (r == -ENODEV) ? 0 : r;
641 }
642
643 static int status_one(struct crypt_device *cd, const char *name,
644                       const char *base_uuid, int index,
645                       size_t *key_size, char *cipher)
646 {
647         struct crypt_dm_active_device dmd = {};
648         char dm_name[PATH_MAX], *c;
649         int r;
650
651         if (snprintf(dm_name, sizeof(dm_name), "%s_%d", name, index) < 0)
652                 return -ENOMEM;
653
654         r = dm_status_device(cd, dm_name);
655         if (r < 0)
656                 return r;
657
658         r = dm_query_device(cd, dm_name, DM_ACTIVE_UUID |
659                                           DM_ACTIVE_CRYPT_CIPHER |
660                                           DM_ACTIVE_CRYPT_KEYSIZE, &dmd);
661         if (r > 0)
662                 r = 0;
663         if (!r && !strncmp(dmd.uuid, base_uuid, strlen(base_uuid))) {
664                 if ((c = strchr(dmd.u.crypt.cipher, '-')))
665                         *c = '\0';
666                 strcat(cipher, "-");
667                 strncat(cipher, dmd.u.crypt.cipher, MAX_CIPHER_LEN);
668                 *key_size += dmd.u.crypt.vk->keylength;
669         } else
670                 r = -ENODEV;
671
672         free(CONST_CAST(void*)dmd.uuid);
673         free(CONST_CAST(void*)dmd.u.crypt.cipher);
674         crypt_free_volume_key(dmd.u.crypt.vk);
675         return r;
676 }
677
678 int TCRYPT_init_by_name(struct crypt_device *cd, const char *name,
679                         const struct crypt_dm_active_device *dmd,
680                         struct crypt_params_tcrypt *tcrypt_params,
681                         struct tcrypt_phdr *tcrypt_hdr)
682 {
683         char cipher[MAX_CIPHER_LEN * 4], *mode;
684
685         memset(tcrypt_params, 0, sizeof(*tcrypt_params));
686         memset(tcrypt_hdr, 0, sizeof(*tcrypt_hdr));
687         strncpy(cipher, dmd->u.crypt.cipher, MAX_CIPHER_LEN);
688
689         if ((mode = strchr(cipher, '-'))) {
690                 *mode = '\0';
691                 tcrypt_params->mode = strdup(++mode);
692         }
693         tcrypt_params->key_size = dmd->u.crypt.vk->keylength;
694
695         if (!status_one(cd, name, dmd->uuid, 1, &tcrypt_params->key_size, cipher))
696                 status_one(cd, name, dmd->uuid, 2, &tcrypt_params->key_size, cipher);
697
698         tcrypt_params->cipher = strdup(cipher);
699         return 0;
700 }