TCRYPT: add backup header option.
[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                 unsigned int key_offset;
52                 unsigned int iv_offset; /* or tweak key offset */
53 };
54
55 struct tcrypt_algs {
56         unsigned int legacy:1;
57         unsigned int chain_count;
58         unsigned int chain_key_size;
59         const char *long_name;
60         const char *mode;
61         struct tcrypt_alg cipher[3];
62 };
63
64 /* TCRYPT cipher variants */
65 static struct tcrypt_algs tcrypt_cipher[] = {
66 /* XTS mode */
67 {0,1,64,"aes","xts-plain64",
68         {{"aes",    64,16,0,32}}},
69 {0,1,64,"serpent","xts-plain64",
70         {{"serpent",64,16,0,32}}},
71 {0,1,64,"twofish","xts-plain64",
72         {{"twofish",64,16,0,32}}},
73 {0,2,128,"twofish-aes","xts-plain64",
74         {{"twofish",64,16, 0,64},
75          {"aes",    64,16,32,96}}},
76 {0,3,192,"serpent-twofish-aes","xts-plain64",
77         {{"serpent",64,16, 0, 96},
78          {"twofish",64,16,32,128},
79          {"aes",    64,16,64,160}}},
80 {0,2,128,"aes-serpent","xts-plain64",
81         {{"aes",    64,16, 0,64},
82          {"serpent",64,16,32,96}}},
83 {0,3,192,"aes-twofish-serpent","xts-plain64",
84         {{"aes",    64,16, 0, 96},
85          {"twofish",64,16,32,128},
86          {"serpent",64,16,64,160}}},
87 {0,2,128,"serpent-twofish","xts-plain64",
88         {{"serpent",64,16, 0,64},
89          {"twofish",64,16,32,96}}},
90 /* LRW mode */
91 {0,1,48,"aes","lrw-benbi",
92         {{"aes",    48,16,32,0}}},
93 {0,1,48,"serpent","lrw-benbi",
94         {{"serpent",48,16,32,0}}},
95 {0,1,48,"twofish","lrw-benbi",
96         {{"twofish",48,16,32,0}}},
97 {0,2,96,"twofish-aes","lrw-benbi",
98         {{"twofish",48,16,32,0},
99          {"aes",    48,16,64,0}}},
100 {0,3,144,"serpent-twofish-aes","lrw-benbi",
101         {{"serpent",48,16,32,0},
102          {"twofish",48,16,64,0},
103          {"aes",    48,16,96,0}}},
104 {0,2,96,"aes-serpent","lrw-benbi",
105         {{"aes",    48,16,32,0},
106          {"serpent",48,16,64,0}}},
107 {0,3,144,"aes-twofish-serpent","lrw-benbi",
108         {{"aes",    48,16,32,0},
109          {"twofish",48,16,64,0},
110          {"serpent",48,16,96,0}}},
111 {0,2,96,"serpent-twofish", "lrw-benbi",
112         {{"serpent",48,16,32,0},
113          {"twofish",48,16,64,0}}},
114 /* Kernel LRW block size is fixed to 16 bytes for GF(2^128)
115  * thus cannot be used with blowfish where block is 8 bytes.
116  * There also no GF(2^64) support.
117 {1,1,64,"blowfish_le","lrw-benbi",
118          {{"blowfish_le",64,8,32,0}}},
119 {1,2,112,"blowfish_le-aes","lrw-benbi",
120          {{"blowfish_le",64, 8,32,0},
121           {"aes",        48,16,88,0}}},
122 {1,3,160,"serpent-blowfish_le-aes","lrw-benbi",
123           {{"serpent",    48,16, 32,0},
124            {"blowfish_le",64, 8, 64,0},
125            {"aes",        48,16,120,0}}},*/
126 /* CBC + "outer" CBC (both with whitening) */
127 {1,1,32,"aes","cbc-tcrypt",
128         {{"aes",    32,16,32,0}}},
129 {1,1,32,"serpent","cbc-tcrypt",
130         {{"serpent",32,16,32,0}}},
131 {1,1,32,"twofish","cbc-tcrypt",
132         {{"twofish",32,16,32,0}}},
133 {1,2,64,"twofish-aes","cbci-tcrypt",
134         {{"twofish",32,16,32,0},
135          {"aes",    32,16,64,0}}},
136 {1,3,96,"serpent-twofish-aes","cbci-tcrypt",
137         {{"serpent",32,16,32,0},
138          {"twofish",32,16,64,0},
139          {"aes",    32,16,96,0}}},
140 {1,2,64,"aes-serpent","cbci-tcrypt",
141         {{"aes",    32,16,32,0},
142          {"serpent",32,16,64,0}}},
143 {1,3,96,"aes-twofish-serpent", "cbci-tcrypt",
144         {{"aes",    32,16,32,0},
145          {"twofish",32,16,64,0},
146          {"serpent",32,16,96,0}}},
147 {1,2,64,"serpent-twofish", "cbci-tcrypt",
148         {{"serpent",32,16,32,0},
149          {"twofish",32,16,64,0}}},
150 {1,1,16,"cast5","cbc-tcrypt",
151         {{"cast5",   16,8,32,0}}},
152 {1,1,24,"des3_ede","cbc-tcrypt",
153         {{"des3_ede",24,8,32,0}}},
154 {1,1,56,"blowfish_le","cbc-tcrypt",
155         {{"blowfish_le",56,8,32,0}}},
156 {1,2,88,"blowfish_le-aes","cbc-tcrypt",
157         {{"blowfish_le",56, 8,32,0},
158          {"aes",        32,16,88,0}}},
159 {1,3,120,"serpent-blowfish_le-aes","cbc-tcrypt",
160         {{"serpent",    32,16, 32,0},
161          {"blowfish_le",56, 8, 64,0},
162          {"aes",        32,16,120,0}}},
163 {}
164 };
165
166 static int hdr_from_disk(struct tcrypt_phdr *hdr,
167                          struct crypt_params_tcrypt *params,
168                          int kdf_index, int cipher_index)
169 {
170         uint32_t crc32;
171         size_t size;
172
173         /* Check CRC32 of header */
174         size = TCRYPT_HDR_LEN - sizeof(hdr->d.keys) - sizeof(hdr->d.header_crc32);
175         crc32 = crypt_crc32(~0, (unsigned char*)&hdr->d, size) ^ ~0;
176         if (be16_to_cpu(hdr->d.version) > 3 &&
177             crc32 != be32_to_cpu(hdr->d.header_crc32)) {
178                 log_dbg("TCRYPT header CRC32 mismatch.");
179                 return -EINVAL;
180         }
181
182         /* Check CRC32 of keys */
183         crc32 = crypt_crc32(~0, (unsigned char*)hdr->d.keys, sizeof(hdr->d.keys)) ^ ~0;
184         if (crc32 != be32_to_cpu(hdr->d.keys_crc32)) {
185                 log_dbg("TCRYPT keys CRC32 mismatch.");
186                 return -EINVAL;
187         }
188
189         /* Convert header to cpu format */
190         hdr->d.version  =  be16_to_cpu(hdr->d.version);
191         hdr->d.version_tc = le16_to_cpu(hdr->d.version_tc);
192
193         hdr->d.keys_crc32 = be32_to_cpu(hdr->d.keys_crc32);
194
195         hdr->d.hidden_volume_size = be64_to_cpu(hdr->d.hidden_volume_size);
196         hdr->d.volume_size        = be64_to_cpu(hdr->d.volume_size);
197
198         hdr->d.mk_offset = be64_to_cpu(hdr->d.mk_offset);
199         if (!hdr->d.mk_offset)
200                 hdr->d.mk_offset = 512;
201
202         hdr->d.mk_size = be64_to_cpu(hdr->d.mk_size);
203
204         hdr->d.flags = be32_to_cpu(hdr->d.flags);
205
206         hdr->d.sector_size = be32_to_cpu(hdr->d.sector_size);
207         if (!hdr->d.sector_size)
208                 hdr->d.sector_size = 512;
209
210         hdr->d.header_crc32 = be32_to_cpu(hdr->d.header_crc32);
211
212         /* Set params */
213         params->passphrase = NULL;
214         params->passphrase_size = 0;
215         params->hash_name  = tcrypt_kdf[kdf_index].hash;
216         params->key_size = tcrypt_cipher[cipher_index].chain_key_size;
217         params->cipher = tcrypt_cipher[cipher_index].long_name;
218         params->mode = tcrypt_cipher[cipher_index].mode;
219
220         return 0;
221 }
222
223 /*
224  * Kernel implements just big-endian version of blowfish, hack it here
225  */
226 static void blowfish_le(char *buf)
227 {
228         uint32_t *l = (uint32_t*)&buf[0];
229         uint32_t *r = (uint32_t*)&buf[4];
230         *l = swab32(*l);
231         *r = swab32(*r);
232 }
233
234 static int decrypt_blowfish_le_cbc(struct tcrypt_alg *alg,
235                                    const char *key, char *buf)
236 {
237         char iv[alg->iv_size], iv_old[alg->iv_size];
238         struct crypt_cipher *cipher = NULL;
239         int bs = alg->iv_size;
240         int i, j, r;
241
242         assert(bs == 2*sizeof(uint32_t));
243
244         r = crypt_cipher_init(&cipher, "blowfish", "ecb",
245                               &key[alg->key_offset], alg->key_size);
246         if (r < 0)
247                 goto out;
248
249         memcpy(iv, &key[alg->iv_offset], alg->iv_size);
250         for (i = 0; i < TCRYPT_HDR_LEN; i += bs) {
251                 memcpy(iv_old, &buf[i], bs);
252                 blowfish_le(&buf[i]);
253                 r = crypt_cipher_decrypt(cipher, &buf[i], &buf[i],
254                                           bs, NULL, 0);
255                 blowfish_le(&buf[i]);
256                 if (r < 0)
257                         goto out;
258                 for (j = 0; j < bs; j++)
259                         buf[i + j] ^= iv[j];
260                 memcpy(iv, iv_old, bs);
261         }
262 out:
263         crypt_cipher_destroy(cipher);
264         return r;
265 }
266
267 static void remove_whitening(char *buf, const char *key)
268 {
269         int j;
270
271         for (j = 0; j < TCRYPT_HDR_LEN; j++)
272                 buf[j] ^= key[j % 8];
273 }
274
275 static void copy_key(struct tcrypt_alg *alg, const char *mode,
276                      char *out_key, const char *key)
277 {
278         int ks2;
279         if (!strncmp(mode, "xts", 3)) {
280                 ks2 = alg->key_size / 2;
281                 memcpy(out_key, &key[alg->key_offset], ks2);
282                 memcpy(&out_key[ks2], &key[alg->iv_offset], ks2);
283         } else if (!strncmp(mode, "lrw", 3)) {
284                 ks2 = alg->key_size - TCRYPT_LRW_IKEY_LEN;
285                 memcpy(out_key, &key[alg->key_offset], ks2);
286                 memcpy(&out_key[ks2], key, TCRYPT_LRW_IKEY_LEN);
287         } else if (!strncmp(mode, "cbc", 3)) {
288                 memcpy(out_key, &key[alg->key_offset], alg->key_size);
289         }
290 }
291
292 static int decrypt_hdr_one(struct tcrypt_alg *alg, const char *mode,
293                            const char *key,struct tcrypt_phdr *hdr)
294 {
295         char backend_key[TCRYPT_HDR_KEY_LEN];
296         char iv[TCRYPT_HDR_IV_LEN] = {};
297         char mode_name[MAX_CIPHER_LEN];
298         struct crypt_cipher *cipher;
299         char *c, *buf = (char*)&hdr->e;
300         int r;
301
302         /* Remove IV if present */
303         strncpy(mode_name, mode, MAX_CIPHER_LEN);
304         c = strchr(mode_name, '-');
305         if (c)
306                 *c = '\0';
307
308         if (!strncmp(mode, "lrw", 3))
309                 iv[alg->iv_size - 1] = 1;
310         else if (!strncmp(mode, "cbc", 3)) {
311                 remove_whitening(buf, &key[8]);
312                 if (!strcmp(alg->name, "blowfish_le"))
313                         return decrypt_blowfish_le_cbc(alg, key, buf);
314                 memcpy(iv, &key[alg->iv_offset], alg->iv_size);
315         }
316
317         copy_key(alg, mode, backend_key, key);
318         r = crypt_cipher_init(&cipher, alg->name, mode_name,
319                               backend_key, alg->key_size);
320         memset(backend_key, 0, sizeof(backend_key));
321         if (r < 0)
322                 return r;
323
324         r = crypt_cipher_decrypt(cipher, buf, buf, TCRYPT_HDR_LEN, iv, alg->iv_size);
325         crypt_cipher_destroy(cipher);
326
327         return r;
328 }
329
330 /*
331  * For chanined ciphers and CBC mode we need "outer" decryption.
332  * Backend doesn't provide this, so implement it here directly using ECB.
333  */
334 static int decrypt_hdr_cbci(struct tcrypt_algs *ciphers,
335                              const char *key, struct tcrypt_phdr *hdr)
336 {
337         struct crypt_cipher *cipher[ciphers->chain_count];
338         int bs = ciphers->cipher[0].iv_size;
339         char *buf = (char*)&hdr->e, iv[bs], iv_old[bs];
340         int i, j, r = -EINVAL;
341
342         remove_whitening(buf, &key[8]);
343
344         memcpy(iv, &key[ciphers->cipher[0].iv_offset], bs);
345
346         /* Initialize all ciphers in chain in ECB mode */
347         for (j = 0; j < ciphers->chain_count; j++) {
348                 r = crypt_cipher_init(&cipher[j], ciphers->cipher[j].name, "ecb",
349                                       &key[ciphers->cipher[j].key_offset],
350                                       ciphers->cipher[j].key_size);
351                 if (r < 0)
352                         goto out;
353         }
354
355         /* Implements CBC with chained ciphers in loop inside */
356         for (i = 0; i < TCRYPT_HDR_LEN; i += bs) {
357                 memcpy(iv_old, &buf[i], bs);
358                 for (j = ciphers->chain_count - 1; j >= 0; j--) {
359                         r = crypt_cipher_decrypt(cipher[j], &buf[i], &buf[i],
360                                                   bs, NULL, 0);
361                         if (r < 0)
362                                 goto out;
363                 }
364                 for (j = 0; j < bs; j++)
365                         buf[i + j] ^= iv[j];
366                 memcpy(iv, iv_old, bs);
367         }
368 out:
369         for (j = 0; j < ciphers->chain_count; j++)
370                 if (cipher[j])
371                         crypt_cipher_destroy(cipher[j]);
372
373         return r;
374 }
375
376 static int decrypt_hdr(struct crypt_device *cd, struct tcrypt_phdr *hdr,
377                         const char *key, int legacy_modes)
378 {
379         struct tcrypt_phdr hdr2;
380         int i, j, r;
381
382         for (i = 0; tcrypt_cipher[i].chain_count; i++) {
383                 if (!legacy_modes && tcrypt_cipher[i].legacy)
384                         continue;
385                 log_dbg("TCRYPT:  trying cipher %s-%s",
386                         tcrypt_cipher[i].long_name, tcrypt_cipher[i].mode);
387
388                 memcpy(&hdr2.e, &hdr->e, TCRYPT_HDR_LEN);
389
390                 if (!strncmp(tcrypt_cipher[i].mode, "cbci", 4))
391                         r = decrypt_hdr_cbci(&tcrypt_cipher[i], key, &hdr2);
392                 else for (j = tcrypt_cipher[i].chain_count - 1; j >= 0 ; j--) {
393                         if (!tcrypt_cipher[i].cipher[j].name)
394                                 continue;
395                         r = decrypt_hdr_one(&tcrypt_cipher[i].cipher[j],
396                                             tcrypt_cipher[i].mode, key, &hdr2);
397                         if (r < 0) {
398                                 log_dbg("Error %s.", tcrypt_cipher[i].cipher[j].name);
399                                 break;
400                         }
401                 }
402
403                 if (!strncmp(hdr2.d.magic, TCRYPT_HDR_MAGIC, TCRYPT_HDR_MAGIC_LEN)) {
404                         log_dbg("TCRYPT: Signature magic detected.");
405                         memcpy(&hdr->e, &hdr2.e, TCRYPT_HDR_LEN);
406                         memset(&hdr2.e, 0, TCRYPT_HDR_LEN);
407                         r = i;
408                         break;
409                 }
410                 r = -EPERM;
411         }
412
413         return r;
414 }
415
416 static int pool_keyfile(struct crypt_device *cd,
417                         unsigned char pool[TCRYPT_KEY_POOL_LEN],
418                         const char *keyfile)
419 {
420         unsigned char data[TCRYPT_KEYFILE_LEN];
421         int i, j, fd, data_size;
422         uint32_t crc;
423         unsigned char *crc_c = (unsigned char*)&crc;
424
425         log_dbg("TCRYPT: using keyfile %s.", keyfile);
426
427         fd = open(keyfile, O_RDONLY);
428         if (fd < 0) {
429                 log_err(cd, _("Failed to open key file.\n"));
430                 return -EIO;
431         }
432
433         /* FIXME: add while */
434         data_size = read(fd, data, TCRYPT_KEYFILE_LEN);
435         close(fd);
436         if (data_size < 0) {
437                 log_err(cd, _("Error reading keyfile %s.\n"), keyfile);
438                 return -EIO;
439         }
440
441         for (i = 0, j = 0, crc = ~0U; i < data_size; i++) {
442                 crc = crypt_crc32(crc, &data[i], 1);
443                 pool[j++] += crc_c[3];
444                 pool[j++] += crc_c[2];
445                 pool[j++] += crc_c[1];
446                 pool[j++] += crc_c[0];
447                 j %= TCRYPT_KEY_POOL_LEN;
448         }
449
450         crc = 0;
451         memset(data, 0, TCRYPT_KEYFILE_LEN);
452
453         return 0;
454 }
455
456 static int TCRYPT_init_hdr(struct crypt_device *cd,
457                            struct tcrypt_phdr *hdr,
458                            struct crypt_params_tcrypt *params)
459 {
460         unsigned char pwd[TCRYPT_KEY_POOL_LEN] = {};
461         size_t passphrase_size;
462         char *key;
463         int r = -EINVAL, i, legacy_modes;
464
465         if (posix_memalign((void*)&key, crypt_getpagesize(), TCRYPT_HDR_KEY_LEN))
466                 return -ENOMEM;
467
468         if (params->keyfiles_count)
469                 passphrase_size = TCRYPT_KEY_POOL_LEN;
470         else
471                 passphrase_size = params->passphrase_size;
472
473         /* Calculate pool content from keyfiles */
474         for (i = 0; i < params->keyfiles_count; i++) {
475                 r = pool_keyfile(cd, pwd, params->keyfiles[i]);
476                 if (r < 0)
477                         goto out;
478         }
479
480         /* If provided password, combine it with pool */
481         for (i = 0; i < params->passphrase_size; i++)
482                 pwd[i] += params->passphrase[i];
483
484         legacy_modes = params->flags & CRYPT_TCRYPT_LEGACY_MODES ? 1 : 0;
485         for (i = 0; tcrypt_kdf[i].name; i++) {
486                 if (!legacy_modes && tcrypt_kdf[i].legacy)
487                         continue;
488                 /* Derive header key */
489                 log_dbg("TCRYPT: trying KDF: %s-%s-%d.",
490                         tcrypt_kdf[i].name, tcrypt_kdf[i].hash, tcrypt_kdf[i].iterations);
491                 r = crypt_pbkdf(tcrypt_kdf[i].name, tcrypt_kdf[i].hash,
492                                 (char*)pwd, passphrase_size,
493                                 hdr->salt, TCRYPT_HDR_SALT_LEN,
494                                 key, TCRYPT_HDR_KEY_LEN,
495                                 tcrypt_kdf[i].iterations);
496                 if (r < 0)
497                         break;
498
499                 /* Decrypt header */
500                 r = decrypt_hdr(cd, hdr, key, legacy_modes);
501                 if (r != -EPERM)
502                         break;
503         }
504
505         if (r < 0)
506                 goto out;
507
508         r = hdr_from_disk(hdr, params, i, r);
509         if (!r) {
510                 log_dbg("TCRYPT: Header version: %d, req. %d, sector %d"
511                         ", PBKDF2 hash %s", (int)hdr->d.version,
512                         (int)hdr->d.version_tc, (int)hdr->d.sector_size,
513                         params->hash_name);
514                 log_dbg("TCRYPT: Header cipher %s-%s, key size %d",
515                         params->cipher, params->mode, params->key_size);
516         }
517 out:
518         memset(pwd, 0, TCRYPT_KEY_POOL_LEN);
519         if (key)
520                 memset(key, 0, TCRYPT_HDR_KEY_LEN);
521         free(key);
522         return r;
523 }
524
525 int TCRYPT_read_phdr(struct crypt_device *cd,
526                      struct tcrypt_phdr *hdr,
527                      struct crypt_params_tcrypt *params)
528 {
529         struct device *device = crypt_metadata_device(cd);
530         ssize_t hdr_size = sizeof(struct tcrypt_phdr);
531         int devfd = 0, r, bs;
532
533         assert(sizeof(struct tcrypt_phdr) == 512);
534
535         log_dbg("Reading TCRYPT header of size %d bytes from device %s.",
536                 hdr_size, device_path(device));
537
538         bs = device_block_size(device);
539         if (bs < 0)
540                 return bs;
541
542         devfd = open(device_path(device), O_RDONLY | O_DIRECT);
543         if (devfd == -1) {
544                 log_err(cd, _("Cannot open device %s.\n"), device_path(device));
545                 return -EINVAL;
546         }
547
548         r = -EIO;
549         if (params->flags & CRYPT_TCRYPT_HIDDEN_HEADER) {
550                 if (params->flags & CRYPT_TCRYPT_BACKUP_HEADER) {
551                         if (lseek(devfd, TCRYPT_HDR_HIDDEN_OFFSET_BCK, SEEK_END) >= 0 &&
552                             read_blockwise(devfd, bs, hdr, hdr_size) == hdr_size)
553                                 r = TCRYPT_init_hdr(cd, hdr, params);
554                 } else {
555                         if (lseek(devfd, TCRYPT_HDR_HIDDEN_OFFSET, SEEK_SET) >= 0 &&
556                             read_blockwise(devfd, bs, hdr, hdr_size) == hdr_size)
557                                 r = TCRYPT_init_hdr(cd, hdr, params);
558                         if (r &&
559                             lseek(devfd, TCRYPT_HDR_HIDDEN_OFFSET_OLD, SEEK_END) >= 0 &&
560                             read_blockwise(devfd, bs, hdr, hdr_size) == hdr_size)
561                                 r = TCRYPT_init_hdr(cd, hdr, params);
562                 }
563         } else if (params->flags & CRYPT_TCRYPT_BACKUP_HEADER) {
564                 if (lseek(devfd, TCRYPT_HDR_OFFSET_BCK, SEEK_END) >= 0 &&
565                             read_blockwise(devfd, bs, hdr, hdr_size) == hdr_size)
566                         r = TCRYPT_init_hdr(cd, hdr, params);
567         } else if (read_blockwise(devfd, bs, hdr, hdr_size) == hdr_size)
568                 r = TCRYPT_init_hdr(cd, hdr, params);
569
570         close(devfd);
571         return r;
572 }
573
574 static struct tcrypt_algs *get_algs(struct crypt_params_tcrypt *params)
575 {
576         int i;
577
578         if (!params->cipher || !params->mode)
579                 return NULL;
580
581         for (i = 0; tcrypt_cipher[i].chain_count; i++)
582                 if (!strcmp(tcrypt_cipher[i].long_name, params->cipher) &&
583                     !strcmp(tcrypt_cipher[i].mode, params->mode))
584                     return &tcrypt_cipher[i];
585
586         return NULL;
587 }
588
589 int TCRYPT_activate(struct crypt_device *cd,
590                      const char *name,
591                      struct tcrypt_phdr *hdr,
592                      struct crypt_params_tcrypt *params,
593                      uint32_t flags)
594 {
595         char cipher[MAX_CIPHER_LEN], dm_name[PATH_MAX], dm_dev_name[PATH_MAX];
596         struct device *device = NULL;
597         int i, r;
598         struct tcrypt_algs *algs;
599         struct crypt_dm_active_device dmd = {
600                 .target = DM_CRYPT,
601                 .size   = 0,
602                 .data_device = crypt_data_device(cd),
603                 .u.crypt  = {
604                         .cipher = cipher,
605                         .offset = crypt_get_data_offset(cd),
606                         .iv_offset = crypt_get_iv_offset(cd),
607                 }
608         };
609
610         if (!hdr->d.version) {
611                 log_dbg("TCRYPT: this function is not supported without encrypted header load.");
612                 return -ENOTSUP;
613         }
614
615         if (hdr->d.sector_size && hdr->d.sector_size != SECTOR_SIZE) {
616                 log_err(cd, _("Activation is not supported for %d sector size.\n"),
617                         hdr->d.sector_size);
618                 return -ENOTSUP;
619         }
620
621         if (strstr(params->mode, "-tcrypt")) {
622                 log_err(cd, _("Kernel doesn't support activation for this TCRYPT legacy mode.\n"));
623                 return -ENOTSUP;
624         }
625
626         algs = get_algs(params);
627         if (!algs)
628                 return -EINVAL;
629
630         r = device_block_adjust(cd, dmd.data_device, DEV_EXCL,
631                                 dmd.u.crypt.offset, &dmd.size, &dmd.flags);
632         if (r)
633                 return r;
634
635         /* Frome here, key size for every cipher must be the same */
636         dmd.u.crypt.vk = crypt_alloc_volume_key(algs->cipher[0].key_size, NULL);
637         if (!dmd.u.crypt.vk)
638                 return -ENOMEM;
639
640         for (i = algs->chain_count - 1; i >= 0; i--) {
641                 if (i == 0) {
642                         strncpy(dm_name, name, sizeof(dm_name));
643                         dmd.flags = flags;
644                 } else {
645                         snprintf(dm_name, sizeof(dm_name), "%s_%d", name, i);
646                         dmd.flags = flags | CRYPT_ACTIVATE_PRIVATE;
647                 }
648
649                 snprintf(cipher, sizeof(cipher), "%s-%s",
650                          algs->cipher[i].name, algs->mode);
651
652                 copy_key(&algs->cipher[i], algs->mode, dmd.u.crypt.vk->key, hdr->d.keys);
653
654                 if ((algs->chain_count - 1) != i) {
655                         snprintf(dm_dev_name, sizeof(dm_dev_name), "%s/%s_%d",
656                                  dm_get_dir(), name, i + 1);
657                         r = device_alloc(&device, dm_dev_name);
658                         if (r)
659                                 break;
660                         dmd.data_device = device;
661                         dmd.u.crypt.offset = 0;
662                 }
663
664                 log_dbg("Trying to activate TCRYPT device %s using cipher %s.",
665                         dm_name, dmd.u.crypt.cipher);
666                 r = dm_create_device(cd, dm_name, CRYPT_TCRYPT, &dmd, 0);
667
668                 device_free(device);
669                 device = NULL;
670
671                 if (r)
672                         break;
673         }
674
675         if (!r && !(dm_flags() & DM_PLAIN64_SUPPORTED)) {
676                 log_err(cd, _("Kernel doesn't support plain64 IV.\n"));
677                 r = -ENOTSUP;
678         }
679
680         crypt_free_volume_key(dmd.u.crypt.vk);
681         return r;
682 }
683
684 static int remove_one(struct crypt_device *cd, const char *name,
685                       const char *base_uuid, int index)
686 {
687         struct crypt_dm_active_device dmd = {};
688         char dm_name[PATH_MAX];
689         int r;
690
691         if (snprintf(dm_name, sizeof(dm_name), "%s_%d", name, index) < 0)
692                 return -ENOMEM;
693
694         r = dm_status_device(cd, dm_name);
695         if (r < 0)
696                 return r;
697
698         r = dm_query_device(cd, dm_name, DM_ACTIVE_UUID, &dmd);
699         if (!r && !strncmp(dmd.uuid, base_uuid, strlen(base_uuid)))
700                 r = dm_remove_device(cd, dm_name, 0, 0);
701
702         free(CONST_CAST(void*)dmd.uuid);
703         return r;
704 }
705
706 int TCRYPT_deactivate(struct crypt_device *cd, const char *name)
707 {
708         struct crypt_dm_active_device dmd = {};
709         int r;
710
711         r = dm_query_device(cd, name, DM_ACTIVE_UUID, &dmd);
712         if (r < 0)
713                 return r;
714         if (!dmd.uuid)
715                 return -EINVAL;
716
717         r = dm_remove_device(cd, name, 0, 0);
718         if (r < 0)
719                 goto out;
720
721         r = remove_one(cd, name, dmd.uuid, 1);
722         if (r < 0)
723                 goto out;
724
725         r = remove_one(cd, name, dmd.uuid, 2);
726         if (r < 0)
727                 goto out;
728 out:
729         free(CONST_CAST(void*)dmd.uuid);
730         return (r == -ENODEV) ? 0 : r;
731 }
732
733 static int status_one(struct crypt_device *cd, const char *name,
734                       const char *base_uuid, int index,
735                       size_t *key_size, char *cipher, uint64_t *data_offset,
736                       struct device **device)
737 {
738         struct crypt_dm_active_device dmd = {};
739         char dm_name[PATH_MAX], *c;
740         int r;
741
742         if (snprintf(dm_name, sizeof(dm_name), "%s_%d", name, index) < 0)
743                 return -ENOMEM;
744
745         r = dm_status_device(cd, dm_name);
746         if (r < 0)
747                 return r;
748
749         r = dm_query_device(cd, dm_name, DM_ACTIVE_DEVICE |
750                                           DM_ACTIVE_UUID |
751                                           DM_ACTIVE_CRYPT_CIPHER |
752                                           DM_ACTIVE_CRYPT_KEYSIZE, &dmd);
753         if (r > 0)
754                 r = 0;
755         if (!r && !strncmp(dmd.uuid, base_uuid, strlen(base_uuid))) {
756                 if ((c = strchr(dmd.u.crypt.cipher, '-')))
757                         *c = '\0';
758                 strcat(cipher, "-");
759                 strncat(cipher, dmd.u.crypt.cipher, MAX_CIPHER_LEN);
760                 *key_size += dmd.u.crypt.vk->keylength;
761                 *data_offset = dmd.u.crypt.offset * SECTOR_SIZE;
762                 device_free(*device);
763                 *device = dmd.data_device;
764         } else {
765                 device_free(dmd.data_device);
766                 r = -ENODEV;
767         }
768
769         free(CONST_CAST(void*)dmd.uuid);
770         free(CONST_CAST(void*)dmd.u.crypt.cipher);
771         crypt_free_volume_key(dmd.u.crypt.vk);
772         return r;
773 }
774
775 int TCRYPT_init_by_name(struct crypt_device *cd, const char *name,
776                         const struct crypt_dm_active_device *dmd,
777                         struct device **device,
778                         struct crypt_params_tcrypt *tcrypt_params,
779                         struct tcrypt_phdr *tcrypt_hdr)
780 {
781         char cipher[MAX_CIPHER_LEN * 4], *mode;
782
783         memset(tcrypt_params, 0, sizeof(*tcrypt_params));
784         memset(tcrypt_hdr, 0, sizeof(*tcrypt_hdr));
785         tcrypt_hdr->d.sector_size = SECTOR_SIZE;
786         tcrypt_hdr->d.mk_offset = dmd->u.crypt.offset * SECTOR_SIZE;
787
788         strncpy(cipher, dmd->u.crypt.cipher, MAX_CIPHER_LEN);
789
790         if ((mode = strchr(cipher, '-'))) {
791                 *mode = '\0';
792                 tcrypt_params->mode = strdup(++mode);
793         }
794         tcrypt_params->key_size = dmd->u.crypt.vk->keylength;
795
796         if (!status_one(cd, name, dmd->uuid, 1, &tcrypt_params->key_size,
797                         cipher, &tcrypt_hdr->d.mk_offset, device))
798                 status_one(cd, name, dmd->uuid, 2, &tcrypt_params->key_size,
799                            cipher, &tcrypt_hdr->d.mk_offset, device);
800
801         tcrypt_params->cipher = strdup(cipher);
802         return 0;
803 }
804
805 uint64_t TCRYPT_get_data_offset(struct tcrypt_phdr *hdr)
806 {
807         // FIXME: system vol.
808         if (!hdr->d.mk_offset)
809                 return 1;
810         return (hdr->d.mk_offset / hdr->d.sector_size);
811 }
812
813 uint64_t TCRYPT_get_iv_offset(struct tcrypt_phdr *hdr)
814 {
815         if (!hdr->d.mk_offset)
816                 return 0;
817         return (hdr->d.mk_offset / hdr->d.sector_size);
818 }
819
820 int TCRYPT_get_volume_key(struct crypt_device *cd,
821                           struct tcrypt_phdr *hdr,
822                           struct crypt_params_tcrypt *params,
823                           struct volume_key **vk)
824 {
825         struct tcrypt_algs *algs;
826         int i, key_index;
827
828         if (!hdr->d.version) {
829                 log_dbg("TCRYPT: this function is not supported without encrypted header load.");
830                 return -ENOTSUP;
831         }
832
833         algs = get_algs(params);
834         if (!algs)
835                 return -EINVAL;
836
837         *vk = crypt_alloc_volume_key(params->key_size, NULL);
838         if (!*vk)
839                 return -ENOMEM;
840
841         for (i = 0, key_index = 0; i < algs->chain_count; i++) {
842                 copy_key(&algs->cipher[i], algs->mode,
843                          &(*vk)->key[key_index], hdr->d.keys);
844                 key_index += algs->cipher[i].key_size;
845         }
846
847         return 0;
848 }
849
850 int TCRYPT_dump(struct crypt_device *cd,
851                 struct tcrypt_phdr *hdr,
852                 struct crypt_params_tcrypt *params)
853 {
854         log_std(cd, "TCRYPT header information for %s\n",
855                 device_path(crypt_metadata_device(cd)));
856         if (hdr->d.version) {
857                 log_std(cd, "Version:       \t%d\n", hdr->d.version);
858                 log_std(cd, "Driver req.:\t%d\n", hdr->d.version_tc);
859
860                 log_std(cd, "Sector size:\t%" PRIu32 "\n", hdr->d.sector_size);
861                 log_std(cd, "MK offset:\t%" PRIu64 "\n", hdr->d.mk_offset);
862                 log_std(cd, "PBKDF2 hash:\t%s\n", params->hash_name);
863         }
864         log_std(cd, "Cipher chain:\t%s\n", params->cipher);
865         log_std(cd, "Cipher mode:\t%s\n", params->mode);
866         log_std(cd, "MK bits:       \t%d\n", params->key_size * 8);
867         return 0;
868 }