Revert "Imported upstream version 1.6.7"
[platform/upstream/cryptsetup.git] / lib / tcrypt / tcrypt.c
1 /*
2  * TCRYPT (TrueCrypt-compatible) volume handling
3  *
4  * Copyright (C) 2012, Red Hat, Inc. All rights reserved.
5  * Copyright (C) 2012-2013, Milan Broz
6  *
7  * This file is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This file is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this file; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20  */
21
22 #include <errno.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <fcntl.h>
27 #include <assert.h>
28
29 #include "libcryptsetup.h"
30 #include "tcrypt.h"
31 #include "internal.h"
32
33 /* TCRYPT PBKDF variants */
34 static struct {
35         unsigned int legacy:1;
36         const char *name;
37         const char *hash;
38         unsigned int iterations;
39 } tcrypt_kdf[] = {
40         { 0, "pbkdf2", "ripemd160", 2000 },
41         { 0, "pbkdf2", "ripemd160", 1000 },
42         { 0, "pbkdf2", "sha512",    1000 },
43         { 0, "pbkdf2", "whirlpool", 1000 },
44         { 1, "pbkdf2", "sha1",      2000 },
45         { 0, NULL,     NULL,           0 }
46 };
47
48 struct tcrypt_alg {
49                 const char *name;
50                 unsigned int key_size;
51                 unsigned int iv_size;
52                 unsigned int key_offset;
53                 unsigned int iv_offset; /* or tweak key offset */
54 };
55
56 struct tcrypt_algs {
57         unsigned int legacy:1;
58         unsigned int chain_count;
59         unsigned int chain_key_size;
60         const char *long_name;
61         const char *mode;
62         struct tcrypt_alg cipher[3];
63 };
64
65 /* TCRYPT cipher variants */
66 static struct tcrypt_algs tcrypt_cipher[] = {
67 /* XTS mode */
68 {0,1,64,"aes","xts-plain64",
69         {{"aes",    64,16,0,32}}},
70 {0,1,64,"serpent","xts-plain64",
71         {{"serpent",64,16,0,32}}},
72 {0,1,64,"twofish","xts-plain64",
73         {{"twofish",64,16,0,32}}},
74 {0,2,128,"twofish-aes","xts-plain64",
75         {{"twofish",64,16, 0,64},
76          {"aes",    64,16,32,96}}},
77 {0,3,192,"serpent-twofish-aes","xts-plain64",
78         {{"serpent",64,16, 0, 96},
79          {"twofish",64,16,32,128},
80          {"aes",    64,16,64,160}}},
81 {0,2,128,"aes-serpent","xts-plain64",
82         {{"aes",    64,16, 0,64},
83          {"serpent",64,16,32,96}}},
84 {0,3,192,"aes-twofish-serpent","xts-plain64",
85         {{"aes",    64,16, 0, 96},
86          {"twofish",64,16,32,128},
87          {"serpent",64,16,64,160}}},
88 {0,2,128,"serpent-twofish","xts-plain64",
89         {{"serpent",64,16, 0,64},
90          {"twofish",64,16,32,96}}},
91 /* LRW mode */
92 {0,1,48,"aes","lrw-benbi",
93         {{"aes",    48,16,32,0}}},
94 {0,1,48,"serpent","lrw-benbi",
95         {{"serpent",48,16,32,0}}},
96 {0,1,48,"twofish","lrw-benbi",
97         {{"twofish",48,16,32,0}}},
98 {0,2,96,"twofish-aes","lrw-benbi",
99         {{"twofish",48,16,32,0},
100          {"aes",    48,16,64,0}}},
101 {0,3,144,"serpent-twofish-aes","lrw-benbi",
102         {{"serpent",48,16,32,0},
103          {"twofish",48,16,64,0},
104          {"aes",    48,16,96,0}}},
105 {0,2,96,"aes-serpent","lrw-benbi",
106         {{"aes",    48,16,32,0},
107          {"serpent",48,16,64,0}}},
108 {0,3,144,"aes-twofish-serpent","lrw-benbi",
109         {{"aes",    48,16,32,0},
110          {"twofish",48,16,64,0},
111          {"serpent",48,16,96,0}}},
112 {0,2,96,"serpent-twofish", "lrw-benbi",
113         {{"serpent",48,16,32,0},
114          {"twofish",48,16,64,0}}},
115 /* Kernel LRW block size is fixed to 16 bytes for GF(2^128)
116  * thus cannot be used with blowfish where block is 8 bytes.
117  * There also no GF(2^64) support.
118 {1,1,64,"blowfish_le","lrw-benbi",
119          {{"blowfish_le",64,8,32,0}}},
120 {1,2,112,"blowfish_le-aes","lrw-benbi",
121          {{"blowfish_le",64, 8,32,0},
122           {"aes",        48,16,88,0}}},
123 {1,3,160,"serpent-blowfish_le-aes","lrw-benbi",
124           {{"serpent",    48,16, 32,0},
125            {"blowfish_le",64, 8, 64,0},
126            {"aes",        48,16,120,0}}},*/
127 /* CBC + "outer" CBC (both with whitening) */
128 {1,1,32,"aes","cbc-tcrypt",
129         {{"aes",    32,16,32,0}}},
130 {1,1,32,"serpent","cbc-tcrypt",
131         {{"serpent",32,16,32,0}}},
132 {1,1,32,"twofish","cbc-tcrypt",
133         {{"twofish",32,16,32,0}}},
134 {1,2,64,"twofish-aes","cbci-tcrypt",
135         {{"twofish",32,16,32,0},
136          {"aes",    32,16,64,0}}},
137 {1,3,96,"serpent-twofish-aes","cbci-tcrypt",
138         {{"serpent",32,16,32,0},
139          {"twofish",32,16,64,0},
140          {"aes",    32,16,96,0}}},
141 {1,2,64,"aes-serpent","cbci-tcrypt",
142         {{"aes",    32,16,32,0},
143          {"serpent",32,16,64,0}}},
144 {1,3,96,"aes-twofish-serpent", "cbci-tcrypt",
145         {{"aes",    32,16,32,0},
146          {"twofish",32,16,64,0},
147          {"serpent",32,16,96,0}}},
148 {1,2,64,"serpent-twofish", "cbci-tcrypt",
149         {{"serpent",32,16,32,0},
150          {"twofish",32,16,64,0}}},
151 {1,1,16,"cast5","cbc-tcrypt",
152         {{"cast5",   16,8,32,0}}},
153 {1,1,24,"des3_ede","cbc-tcrypt",
154         {{"des3_ede",24,8,32,0}}},
155 {1,1,56,"blowfish_le","cbc-tcrypt",
156         {{"blowfish_le",56,8,32,0}}},
157 {1,2,88,"blowfish_le-aes","cbc-tcrypt",
158         {{"blowfish_le",56, 8,32,0},
159          {"aes",        32,16,88,0}}},
160 {1,3,120,"serpent-blowfish_le-aes","cbc-tcrypt",
161         {{"serpent",    32,16, 32,0},
162          {"blowfish_le",56, 8, 64,0},
163          {"aes",        32,16,120,0}}},
164 {}
165 };
166
167 static int TCRYPT_hdr_from_disk(struct tcrypt_phdr *hdr,
168                                 struct crypt_params_tcrypt *params,
169                                 int kdf_index, int cipher_index)
170 {
171         uint32_t crc32;
172         size_t size;
173
174         /* Check CRC32 of header */
175         size = TCRYPT_HDR_LEN - sizeof(hdr->d.keys) - sizeof(hdr->d.header_crc32);
176         crc32 = crypt_crc32(~0, (unsigned char*)&hdr->d, size) ^ ~0;
177         if (be16_to_cpu(hdr->d.version) > 3 &&
178             crc32 != be32_to_cpu(hdr->d.header_crc32)) {
179                 log_dbg("TCRYPT header CRC32 mismatch.");
180                 return -EINVAL;
181         }
182
183         /* Check CRC32 of keys */
184         crc32 = crypt_crc32(~0, (unsigned char*)hdr->d.keys, sizeof(hdr->d.keys)) ^ ~0;
185         if (crc32 != be32_to_cpu(hdr->d.keys_crc32)) {
186                 log_dbg("TCRYPT keys CRC32 mismatch.");
187                 return -EINVAL;
188         }
189
190         /* Convert header to cpu format */
191         hdr->d.version  =  be16_to_cpu(hdr->d.version);
192         hdr->d.version_tc = le16_to_cpu(hdr->d.version_tc);
193
194         hdr->d.keys_crc32 = be32_to_cpu(hdr->d.keys_crc32);
195
196         hdr->d.hidden_volume_size = be64_to_cpu(hdr->d.hidden_volume_size);
197         hdr->d.volume_size        = be64_to_cpu(hdr->d.volume_size);
198
199         hdr->d.mk_offset = be64_to_cpu(hdr->d.mk_offset);
200         if (!hdr->d.mk_offset)
201                 hdr->d.mk_offset = 512;
202
203         hdr->d.mk_size = be64_to_cpu(hdr->d.mk_size);
204
205         hdr->d.flags = be32_to_cpu(hdr->d.flags);
206
207         hdr->d.sector_size = be32_to_cpu(hdr->d.sector_size);
208         if (!hdr->d.sector_size)
209                 hdr->d.sector_size = 512;
210
211         hdr->d.header_crc32 = be32_to_cpu(hdr->d.header_crc32);
212
213         /* Set params */
214         params->passphrase = NULL;
215         params->passphrase_size = 0;
216         params->hash_name  = tcrypt_kdf[kdf_index].hash;
217         params->key_size = tcrypt_cipher[cipher_index].chain_key_size;
218         params->cipher = tcrypt_cipher[cipher_index].long_name;
219         params->mode = tcrypt_cipher[cipher_index].mode;
220
221         return 0;
222 }
223
224 /*
225  * Kernel implements just big-endian version of blowfish, hack it here
226  */
227 static void TCRYPT_swab_le(char *buf)
228 {
229         uint32_t *l = (uint32_t*)&buf[0];
230         uint32_t *r = (uint32_t*)&buf[4];
231         *l = swab32(*l);
232         *r = swab32(*r);
233 }
234
235 static int decrypt_blowfish_le_cbc(struct tcrypt_alg *alg,
236                                    const char *key, char *buf)
237 {
238         int bs = alg->iv_size;
239         char iv[bs], iv_old[bs];
240         struct crypt_cipher *cipher = NULL;
241         int i, j, r;
242
243         assert(bs == 2*sizeof(uint32_t));
244
245         r = crypt_cipher_init(&cipher, "blowfish", "ecb",
246                               &key[alg->key_offset], alg->key_size);
247         if (r < 0)
248                 return r;
249
250         memcpy(iv, &key[alg->iv_offset], alg->iv_size);
251         for (i = 0; i < TCRYPT_HDR_LEN; i += bs) {
252                 memcpy(iv_old, &buf[i], bs);
253                 TCRYPT_swab_le(&buf[i]);
254                 r = crypt_cipher_decrypt(cipher, &buf[i], &buf[i],
255                                           bs, NULL, 0);
256                 TCRYPT_swab_le(&buf[i]);
257                 if (r < 0)
258                         break;
259                 for (j = 0; j < bs; j++)
260                         buf[i + j] ^= iv[j];
261                 memcpy(iv, iv_old, bs);
262         }
263
264         crypt_cipher_destroy(cipher);
265         memset(iv, 0, bs);
266         memset(iv_old, 0, bs);
267         return r;
268 }
269
270 static void TCRYPT_remove_whitening(char *buf, const char *key)
271 {
272         int j;
273
274         for (j = 0; j < TCRYPT_HDR_LEN; j++)
275                 buf[j] ^= key[j % 8];
276 }
277
278 static void TCRYPT_copy_key(struct tcrypt_alg *alg, const char *mode,
279                              char *out_key, const char *key)
280 {
281         int ks2;
282         if (!strncmp(mode, "xts", 3)) {
283                 ks2 = alg->key_size / 2;
284                 memcpy(out_key, &key[alg->key_offset], ks2);
285                 memcpy(&out_key[ks2], &key[alg->iv_offset], ks2);
286         } else if (!strncmp(mode, "lrw", 3)) {
287                 ks2 = alg->key_size - TCRYPT_LRW_IKEY_LEN;
288                 memcpy(out_key, &key[alg->key_offset], ks2);
289                 memcpy(&out_key[ks2], key, TCRYPT_LRW_IKEY_LEN);
290         } else if (!strncmp(mode, "cbc", 3)) {
291                 memcpy(out_key, &key[alg->key_offset], alg->key_size);
292         }
293 }
294
295 static int TCRYPT_decrypt_hdr_one(struct tcrypt_alg *alg, const char *mode,
296                                    const char *key,struct tcrypt_phdr *hdr)
297 {
298         char backend_key[TCRYPT_HDR_KEY_LEN];
299         char iv[TCRYPT_HDR_IV_LEN] = {};
300         char mode_name[MAX_CIPHER_LEN];
301         struct crypt_cipher *cipher;
302         char *c, *buf = (char*)&hdr->e;
303         int r;
304
305         /* Remove IV if present */
306         strncpy(mode_name, mode, MAX_CIPHER_LEN);
307         c = strchr(mode_name, '-');
308         if (c)
309                 *c = '\0';
310
311         if (!strncmp(mode, "lrw", 3))
312                 iv[alg->iv_size - 1] = 1;
313         else if (!strncmp(mode, "cbc", 3)) {
314                 TCRYPT_remove_whitening(buf, &key[8]);
315                 if (!strcmp(alg->name, "blowfish_le"))
316                         return decrypt_blowfish_le_cbc(alg, key, buf);
317                 memcpy(iv, &key[alg->iv_offset], alg->iv_size);
318         }
319
320         TCRYPT_copy_key(alg, mode, backend_key, key);
321         r = crypt_cipher_init(&cipher, alg->name, mode_name,
322                               backend_key, alg->key_size);
323         if (!r) {
324                 r = crypt_cipher_decrypt(cipher, buf, buf, TCRYPT_HDR_LEN,
325                                          iv, alg->iv_size);
326                 crypt_cipher_destroy(cipher);
327         }
328
329         memset(backend_key, 0, sizeof(backend_key));
330         memset(iv, 0, TCRYPT_HDR_IV_LEN);
331         return r;
332 }
333
334 /*
335  * For chanined ciphers and CBC mode we need "outer" decryption.
336  * Backend doesn't provide this, so implement it here directly using ECB.
337  */
338 static int TCRYPT_decrypt_cbci(struct tcrypt_algs *ciphers,
339                                 const char *key, struct tcrypt_phdr *hdr)
340 {
341         struct crypt_cipher *cipher[ciphers->chain_count];
342         unsigned int bs = ciphers->cipher[0].iv_size;
343         char *buf = (char*)&hdr->e, iv[bs], iv_old[bs];
344         unsigned int i, j;
345         int r = -EINVAL;
346
347         TCRYPT_remove_whitening(buf, &key[8]);
348
349         memcpy(iv, &key[ciphers->cipher[0].iv_offset], bs);
350
351         /* Initialize all ciphers in chain in ECB mode */
352         for (j = 0; j < ciphers->chain_count; j++)
353                 cipher[j] = NULL;
354         for (j = 0; j < ciphers->chain_count; j++) {
355                 r = crypt_cipher_init(&cipher[j], ciphers->cipher[j].name, "ecb",
356                                       &key[ciphers->cipher[j].key_offset],
357                                       ciphers->cipher[j].key_size);
358                 if (r < 0)
359                         goto out;
360         }
361
362         /* Implements CBC with chained ciphers in loop inside */
363         for (i = 0; i < TCRYPT_HDR_LEN; i += bs) {
364                 memcpy(iv_old, &buf[i], bs);
365                 for (j = ciphers->chain_count; j > 0; j--) {
366                         r = crypt_cipher_decrypt(cipher[j - 1], &buf[i], &buf[i],
367                                                   bs, NULL, 0);
368                         if (r < 0)
369                                 goto out;
370                 }
371                 for (j = 0; j < bs; j++)
372                         buf[i + j] ^= iv[j];
373                 memcpy(iv, iv_old, bs);
374         }
375 out:
376         for (j = 0; j < ciphers->chain_count; j++)
377                 if (cipher[j])
378                         crypt_cipher_destroy(cipher[j]);
379
380         memset(iv, 0, bs);
381         memset(iv_old, 0, bs);
382         return r;
383 }
384
385 static int TCRYPT_decrypt_hdr(struct crypt_device *cd, struct tcrypt_phdr *hdr,
386                                const char *key, int legacy_modes)
387 {
388         struct tcrypt_phdr hdr2;
389         int i, j, r = -EINVAL;
390
391         for (i = 0; tcrypt_cipher[i].chain_count; i++) {
392                 if (!legacy_modes && tcrypt_cipher[i].legacy)
393                         continue;
394                 log_dbg("TCRYPT:  trying cipher %s-%s",
395                         tcrypt_cipher[i].long_name, tcrypt_cipher[i].mode);
396
397                 memcpy(&hdr2.e, &hdr->e, TCRYPT_HDR_LEN);
398
399                 if (!strncmp(tcrypt_cipher[i].mode, "cbci", 4))
400                         r = TCRYPT_decrypt_cbci(&tcrypt_cipher[i], key, &hdr2);
401                 else for (j = tcrypt_cipher[i].chain_count - 1; j >= 0 ; j--) {
402                         if (!tcrypt_cipher[i].cipher[j].name)
403                                 continue;
404                         r = TCRYPT_decrypt_hdr_one(&tcrypt_cipher[i].cipher[j],
405                                             tcrypt_cipher[i].mode, key, &hdr2);
406                         if (r < 0)
407                                 break;
408                 }
409
410                 if (r < 0) {
411                         log_dbg("TCRYPT:   returned error %d, skipped.", r);
412                         if (r == -ENOTSUP)
413                                 break;
414                         r = -ENOENT;
415                         continue;
416                 }
417
418                 if (!strncmp(hdr2.d.magic, TCRYPT_HDR_MAGIC, TCRYPT_HDR_MAGIC_LEN)) {
419                         log_dbg("TCRYPT: Signature magic detected.");
420                         memcpy(&hdr->e, &hdr2.e, TCRYPT_HDR_LEN);
421                         r = i;
422                         break;
423                 }
424                 r = -EPERM;
425         }
426
427         memset(&hdr2, 0, sizeof(hdr2));
428         return r;
429 }
430
431 static int TCRYPT_pool_keyfile(struct crypt_device *cd,
432                                 unsigned char pool[TCRYPT_KEY_POOL_LEN],
433                                 const char *keyfile)
434 {
435         unsigned char data[TCRYPT_KEYFILE_LEN];
436         int i, j, fd, data_size;
437         uint32_t crc;
438
439         log_dbg("TCRYPT: using keyfile %s.", keyfile);
440
441         fd = open(keyfile, O_RDONLY);
442         if (fd < 0) {
443                 log_err(cd, _("Failed to open key file.\n"));
444                 return -EIO;
445         }
446
447         /* FIXME: add while */
448         data_size = read(fd, data, TCRYPT_KEYFILE_LEN);
449         close(fd);
450         if (data_size < 0) {
451                 log_err(cd, _("Error reading keyfile %s.\n"), keyfile);
452                 return -EIO;
453         }
454
455         for (i = 0, j = 0, crc = ~0U; i < data_size; i++) {
456                 crc = crypt_crc32(crc, &data[i], 1);
457                 pool[j++] += (unsigned char)(crc >> 24);
458                 pool[j++] += (unsigned char)(crc >> 16);
459                 pool[j++] += (unsigned char)(crc >>  8);
460                 pool[j++] += (unsigned char)(crc);
461                 j %= TCRYPT_KEY_POOL_LEN;
462         }
463
464         memset(&crc, 0, sizeof(crc));
465         memset(data, 0, TCRYPT_KEYFILE_LEN);
466
467         return 0;
468 }
469
470 static int TCRYPT_init_hdr(struct crypt_device *cd,
471                            struct tcrypt_phdr *hdr,
472                            struct crypt_params_tcrypt *params)
473 {
474         unsigned char pwd[TCRYPT_KEY_POOL_LEN] = {};
475         size_t passphrase_size;
476         char *key;
477         unsigned int i, skipped = 0;
478         int r = -EINVAL, legacy_modes;
479
480         if (posix_memalign((void*)&key, crypt_getpagesize(), TCRYPT_HDR_KEY_LEN))
481                 return -ENOMEM;
482
483         if (params->keyfiles_count)
484                 passphrase_size = TCRYPT_KEY_POOL_LEN;
485         else
486                 passphrase_size = params->passphrase_size;
487
488         if (params->passphrase_size > TCRYPT_KEY_POOL_LEN) {
489                 log_err(cd, _("Maximum TCRYPT passphrase length (%d) exceeded.\n"),
490                               TCRYPT_KEY_POOL_LEN);
491                 return -EPERM;
492         }
493
494         /* Calculate pool content from keyfiles */
495         for (i = 0; i < params->keyfiles_count; i++) {
496                 r = TCRYPT_pool_keyfile(cd, pwd, params->keyfiles[i]);
497                 if (r < 0)
498                         goto out;
499         }
500
501         /* If provided password, combine it with pool */
502         for (i = 0; i < params->passphrase_size; i++)
503                 pwd[i] += params->passphrase[i];
504
505         legacy_modes = params->flags & CRYPT_TCRYPT_LEGACY_MODES ? 1 : 0;
506         for (i = 0; tcrypt_kdf[i].name; i++) {
507                 if (!legacy_modes && tcrypt_kdf[i].legacy)
508                         continue;
509                 /* Derive header key */
510                 log_dbg("TCRYPT: trying KDF: %s-%s-%d.",
511                         tcrypt_kdf[i].name, tcrypt_kdf[i].hash, tcrypt_kdf[i].iterations);
512                 r = crypt_pbkdf(tcrypt_kdf[i].name, tcrypt_kdf[i].hash,
513                                 (char*)pwd, passphrase_size,
514                                 hdr->salt, TCRYPT_HDR_SALT_LEN,
515                                 key, TCRYPT_HDR_KEY_LEN,
516                                 tcrypt_kdf[i].iterations);
517                 if (r < 0 && crypt_hash_size(tcrypt_kdf[i].hash) < 0) {
518                         log_verbose(cd, _("PBKDF2 hash algorithm %s not available, skipping.\n"),
519                                       tcrypt_kdf[i].hash);
520                         continue;
521                 }
522                 if (r < 0)
523                         break;
524
525                 /* Decrypt header */
526                 r = TCRYPT_decrypt_hdr(cd, hdr, key, legacy_modes);
527                 if (r == -ENOENT) {
528                         skipped++;
529                         continue;
530                 }
531                 if (r != -EPERM)
532                         break;
533         }
534
535         if ((skipped && skipped == i) || r == -ENOTSUP) {
536                 log_err(cd, _("Required kernel crypto interface not available.\n"));
537 #ifdef ENABLE_AF_ALG
538                 log_err(cd, _("Ensure you have algif_skcipher kernel module loaded.\n"));
539 #endif
540         }
541         if (r < 0)
542                 goto out;
543
544         r = TCRYPT_hdr_from_disk(hdr, params, i, r);
545         if (!r) {
546                 log_dbg("TCRYPT: Header version: %d, req. %d, sector %d"
547                         ", mk_offset %" PRIu64 ", hidden_size %" PRIu64
548                         ", volume size %" PRIu64, (int)hdr->d.version,
549                         (int)hdr->d.version_tc, (int)hdr->d.sector_size,
550                         hdr->d.mk_offset, hdr->d.hidden_volume_size, hdr->d.volume_size);
551                 log_dbg("TCRYPT: Header cipher %s-%s, key size %d",
552                         params->cipher, params->mode, params->key_size);
553         }
554 out:
555         memset(pwd, 0, TCRYPT_KEY_POOL_LEN);
556         if (key)
557                 memset(key, 0, TCRYPT_HDR_KEY_LEN);
558         free(key);
559         return r;
560 }
561
562 int TCRYPT_read_phdr(struct crypt_device *cd,
563                      struct tcrypt_phdr *hdr,
564                      struct crypt_params_tcrypt *params)
565 {
566         struct device *device = crypt_metadata_device(cd);
567         ssize_t hdr_size = sizeof(struct tcrypt_phdr);
568         int devfd = 0, r, bs;
569
570         assert(sizeof(struct tcrypt_phdr) == 512);
571
572         log_dbg("Reading TCRYPT header of size %d bytes from device %s.",
573                 hdr_size, device_path(device));
574
575         bs = device_block_size(device);
576         if (bs < 0)
577                 return bs;
578
579         devfd = device_open(device, O_RDONLY);
580         if (devfd == -1) {
581                 log_err(cd, _("Cannot open device %s.\n"), device_path(device));
582                 return -EINVAL;
583         }
584
585         r = -EIO;
586         if (params->flags & CRYPT_TCRYPT_SYSTEM_HEADER) {
587                 if (lseek(devfd, TCRYPT_HDR_SYSTEM_OFFSET, SEEK_SET) >= 0 &&
588                     read_blockwise(devfd, bs, hdr, hdr_size) == hdr_size) {
589                         r = TCRYPT_init_hdr(cd, hdr, params);
590                         if (r == -EPERM && crypt_dev_is_partition(device_path(device)))
591                                 log_std(cd, _("WARNING: device %s is a partition, for TCRYPT "
592                                               "system encryption you usually need to use "
593                                               "whole block device path.\n"), device_path(device));
594                 }
595         } else if (params->flags & CRYPT_TCRYPT_HIDDEN_HEADER) {
596                 if (params->flags & CRYPT_TCRYPT_BACKUP_HEADER) {
597                         if (lseek(devfd, TCRYPT_HDR_HIDDEN_OFFSET_BCK, SEEK_END) >= 0 &&
598                             read_blockwise(devfd, bs, hdr, hdr_size) == hdr_size)
599                                 r = TCRYPT_init_hdr(cd, hdr, params);
600                 } else {
601                         if (lseek(devfd, TCRYPT_HDR_HIDDEN_OFFSET, SEEK_SET) >= 0 &&
602                             read_blockwise(devfd, bs, hdr, hdr_size) == hdr_size)
603                                 r = TCRYPT_init_hdr(cd, hdr, params);
604                         if (r &&
605                             lseek(devfd, TCRYPT_HDR_HIDDEN_OFFSET_OLD, SEEK_END) >= 0 &&
606                             read_blockwise(devfd, bs, hdr, hdr_size) == hdr_size)
607                                 r = TCRYPT_init_hdr(cd, hdr, params);
608                 }
609         } else if (params->flags & CRYPT_TCRYPT_BACKUP_HEADER) {
610                 if (lseek(devfd, TCRYPT_HDR_OFFSET_BCK, SEEK_END) >= 0 &&
611                             read_blockwise(devfd, bs, hdr, hdr_size) == hdr_size)
612                         r = TCRYPT_init_hdr(cd, hdr, params);
613         } else if (read_blockwise(devfd, bs, hdr, hdr_size) == hdr_size)
614                 r = TCRYPT_init_hdr(cd, hdr, params);
615
616         close(devfd);
617         if (r < 0)
618                 memset(hdr, 0, sizeof (*hdr));
619         return r;
620 }
621
622 static struct tcrypt_algs *TCRYPT_get_algs(const char *cipher, const char *mode)
623 {
624         int i;
625
626         if (!cipher || !mode)
627                 return NULL;
628
629         for (i = 0; tcrypt_cipher[i].chain_count; i++)
630                 if (!strcmp(tcrypt_cipher[i].long_name, cipher) &&
631                     !strcmp(tcrypt_cipher[i].mode, mode))
632                     return &tcrypt_cipher[i];
633
634         return NULL;
635 }
636
637 int TCRYPT_activate(struct crypt_device *cd,
638                      const char *name,
639                      struct tcrypt_phdr *hdr,
640                      struct crypt_params_tcrypt *params,
641                      uint32_t flags)
642 {
643         char cipher[MAX_CIPHER_LEN], dm_name[PATH_MAX], dm_dev_name[PATH_MAX];
644         char *part_path;
645         struct device *device = NULL, *part_device = NULL;
646         unsigned int i;
647         int r;
648         struct tcrypt_algs *algs;
649         enum devcheck device_check;
650         struct crypt_dm_active_device dmd = {
651                 .target = DM_CRYPT,
652                 .size   = 0,
653                 .data_device = crypt_data_device(cd),
654                 .u.crypt  = {
655                         .cipher = cipher,
656                         .offset = crypt_get_data_offset(cd),
657                         .iv_offset = crypt_get_iv_offset(cd),
658                 }
659         };
660
661         if (!hdr->d.version) {
662                 log_dbg("TCRYPT: this function is not supported without encrypted header load.");
663                 return -ENOTSUP;
664         }
665
666         if (hdr->d.sector_size && hdr->d.sector_size != SECTOR_SIZE) {
667                 log_err(cd, _("Activation is not supported for %d sector size.\n"),
668                         hdr->d.sector_size);
669                 return -ENOTSUP;
670         }
671
672         if (strstr(params->mode, "-tcrypt")) {
673                 log_err(cd, _("Kernel doesn't support activation for this TCRYPT legacy mode.\n"));
674                 return -ENOTSUP;
675         }
676
677         algs = TCRYPT_get_algs(params->cipher, params->mode);
678         if (!algs)
679                 return -EINVAL;
680
681         if (params->flags & CRYPT_TCRYPT_HIDDEN_HEADER)
682                 dmd.size = hdr->d.hidden_volume_size / hdr->d.sector_size;
683         else
684                 dmd.size = hdr->d.volume_size / hdr->d.sector_size;
685
686         /*
687          * System encryption use the whole device mapping, there can
688          * be active partitions.
689          * FIXME: This will allow multiple mappings unexpectedly.
690          */
691         if ((dmd.flags & CRYPT_ACTIVATE_SHARED) ||
692             (params->flags & CRYPT_TCRYPT_SYSTEM_HEADER))
693                 device_check = DEV_SHARED;
694         else
695                 device_check = DEV_EXCL;
696
697         if ((params->flags & CRYPT_TCRYPT_SYSTEM_HEADER) &&
698                 (part_path = crypt_get_partition_device(device_path(dmd.data_device),
699                                  dmd.u.crypt.offset, dmd.size))) {
700                 if (!device_alloc(&part_device, part_path)) {
701                         log_verbose(cd, _("Activating TCRYPT system encryption for partition %s.\n"),
702                                     part_path);
703                         dmd.data_device = part_device;
704                         dmd.u.crypt.offset = 0;
705                 }
706                 free(part_path);
707         }
708
709         r = device_block_adjust(cd, dmd.data_device, device_check,
710                                 dmd.u.crypt.offset, &dmd.size, &dmd.flags);
711         if (r)
712                 return r;
713
714         /* Frome here, key size for every cipher must be the same */
715         dmd.u.crypt.vk = crypt_alloc_volume_key(algs->cipher[0].key_size, NULL);
716         if (!dmd.u.crypt.vk)
717                 return -ENOMEM;
718
719         for (i = algs->chain_count; i > 0; i--) {
720                 if (i == 1) {
721                         strncpy(dm_name, name, sizeof(dm_name));
722                         dmd.flags = flags;
723                 } else {
724                         snprintf(dm_name, sizeof(dm_name), "%s_%d", name, i-1);
725                         dmd.flags = flags | CRYPT_ACTIVATE_PRIVATE;
726                 }
727
728                 snprintf(cipher, sizeof(cipher), "%s-%s",
729                          algs->cipher[i-1].name, algs->mode);
730
731                 TCRYPT_copy_key(&algs->cipher[i-1], algs->mode,
732                                 dmd.u.crypt.vk->key, hdr->d.keys);
733
734                 if (algs->chain_count != i) {
735                         snprintf(dm_dev_name, sizeof(dm_dev_name), "%s/%s_%d",
736                                  dm_get_dir(), name, i);
737                         r = device_alloc(&device, dm_dev_name);
738                         if (r)
739                                 break;
740                         dmd.data_device = device;
741                         dmd.u.crypt.offset = 0;
742                 }
743
744                 log_dbg("Trying to activate TCRYPT device %s using cipher %s.",
745                         dm_name, dmd.u.crypt.cipher);
746                 r = dm_create_device(cd, dm_name, CRYPT_TCRYPT, &dmd, 0);
747
748                 device_free(device);
749                 device = NULL;
750
751                 if (r)
752                         break;
753         }
754
755         if (r < 0 && !(dm_flags() & DM_PLAIN64_SUPPORTED)) {
756                 log_err(cd, _("Kernel doesn't support plain64 IV.\n"));
757                 r = -ENOTSUP;
758         }
759
760         device_free(part_device);
761         crypt_free_volume_key(dmd.u.crypt.vk);
762         return r;
763 }
764
765 static int TCRYPT_remove_one(struct crypt_device *cd, const char *name,
766                       const char *base_uuid, int index)
767 {
768         struct crypt_dm_active_device dmd = {};
769         char dm_name[PATH_MAX];
770         int r;
771
772         if (snprintf(dm_name, sizeof(dm_name), "%s_%d", name, index) < 0)
773                 return -ENOMEM;
774
775         r = dm_status_device(cd, dm_name);
776         if (r < 0)
777                 return r;
778
779         r = dm_query_device(cd, dm_name, DM_ACTIVE_UUID, &dmd);
780         if (!r && !strncmp(dmd.uuid, base_uuid, strlen(base_uuid)))
781                 r = dm_remove_device(cd, dm_name, 0, 0);
782
783         free(CONST_CAST(void*)dmd.uuid);
784         return r;
785 }
786
787 int TCRYPT_deactivate(struct crypt_device *cd, const char *name)
788 {
789         struct crypt_dm_active_device dmd = {};
790         int r;
791
792         r = dm_query_device(cd, name, DM_ACTIVE_UUID, &dmd);
793         if (r < 0)
794                 return r;
795         if (!dmd.uuid)
796                 return -EINVAL;
797
798         r = dm_remove_device(cd, name, 0, 0);
799         if (r < 0)
800                 goto out;
801
802         r = TCRYPT_remove_one(cd, name, dmd.uuid, 1);
803         if (r < 0)
804                 goto out;
805
806         r = TCRYPT_remove_one(cd, name, dmd.uuid, 2);
807         if (r < 0)
808                 goto out;
809 out:
810         free(CONST_CAST(void*)dmd.uuid);
811         return (r == -ENODEV) ? 0 : r;
812 }
813
814 static int TCRYPT_status_one(struct crypt_device *cd, const char *name,
815                               const char *base_uuid, int index,
816                               size_t *key_size, char *cipher,
817                               uint64_t *data_offset, struct device **device)
818 {
819         struct crypt_dm_active_device dmd = {};
820         char dm_name[PATH_MAX], *c;
821         int r;
822
823         if (snprintf(dm_name, sizeof(dm_name), "%s_%d", name, index) < 0)
824                 return -ENOMEM;
825
826         r = dm_status_device(cd, dm_name);
827         if (r < 0)
828                 return r;
829
830         r = dm_query_device(cd, dm_name, DM_ACTIVE_DEVICE |
831                                           DM_ACTIVE_UUID |
832                                           DM_ACTIVE_CRYPT_CIPHER |
833                                           DM_ACTIVE_CRYPT_KEYSIZE, &dmd);
834         if (r > 0)
835                 r = 0;
836         if (!r && !strncmp(dmd.uuid, base_uuid, strlen(base_uuid))) {
837                 if ((c = strchr(dmd.u.crypt.cipher, '-')))
838                         *c = '\0';
839                 strcat(cipher, "-");
840                 strncat(cipher, dmd.u.crypt.cipher, MAX_CIPHER_LEN);
841                 *key_size += dmd.u.crypt.vk->keylength;
842                 *data_offset = dmd.u.crypt.offset * SECTOR_SIZE;
843                 device_free(*device);
844                 *device = dmd.data_device;
845         } else {
846                 device_free(dmd.data_device);
847                 r = -ENODEV;
848         }
849
850         free(CONST_CAST(void*)dmd.uuid);
851         free(CONST_CAST(void*)dmd.u.crypt.cipher);
852         crypt_free_volume_key(dmd.u.crypt.vk);
853         return r;
854 }
855
856 int TCRYPT_init_by_name(struct crypt_device *cd, const char *name,
857                         const struct crypt_dm_active_device *dmd,
858                         struct device **device,
859                         struct crypt_params_tcrypt *tcrypt_params,
860                         struct tcrypt_phdr *tcrypt_hdr)
861 {
862         struct tcrypt_algs *algs;
863         char cipher[MAX_CIPHER_LEN * 4], mode[MAX_CIPHER_LEN], *tmp;
864         size_t key_size;
865         int r;
866
867         memset(tcrypt_params, 0, sizeof(*tcrypt_params));
868         memset(tcrypt_hdr, 0, sizeof(*tcrypt_hdr));
869         tcrypt_hdr->d.sector_size = SECTOR_SIZE;
870         tcrypt_hdr->d.mk_offset = dmd->u.crypt.offset * SECTOR_SIZE;
871
872         strncpy(cipher, dmd->u.crypt.cipher, MAX_CIPHER_LEN);
873         tmp = strchr(cipher, '-');
874         if (!tmp)
875                 return -EINVAL;
876         *tmp = '\0';
877         strncpy(mode, ++tmp, MAX_CIPHER_LEN);
878
879         key_size = dmd->u.crypt.vk->keylength;
880         r = TCRYPT_status_one(cd, name, dmd->uuid, 1, &key_size,
881                               cipher, &tcrypt_hdr->d.mk_offset, device);
882         if (!r)
883                 r = TCRYPT_status_one(cd, name, dmd->uuid, 2, &key_size,
884                                       cipher, &tcrypt_hdr->d.mk_offset, device);
885
886         if (r < 0 && r != -ENODEV)
887                 return r;
888
889         algs = TCRYPT_get_algs(cipher, mode);
890         if (!algs || key_size != algs->chain_key_size)
891                 return -EINVAL;
892
893         tcrypt_params->key_size = algs->chain_key_size;
894         tcrypt_params->cipher = algs->long_name;
895         tcrypt_params->mode = algs->mode;
896         return 0;
897 }
898
899 uint64_t TCRYPT_get_data_offset(struct crypt_device *cd,
900                                  struct tcrypt_phdr *hdr,
901                                  struct crypt_params_tcrypt *params)
902 {
903         uint64_t size;
904
905         /* No real header loaded, initialized by active device */
906         if (!hdr->d.version)
907                 goto hdr_offset;
908
909         /* Mapping through whole device, not partition! */
910         if (params->flags & CRYPT_TCRYPT_SYSTEM_HEADER)
911                 goto hdr_offset;
912
913         if (params->mode && !strncmp(params->mode, "xts", 3)) {
914                 if (hdr->d.version < 3)
915                         return 1;
916
917                 if (params->flags & CRYPT_TCRYPT_HIDDEN_HEADER) {
918                         if (hdr->d.version > 3)
919                                 return (hdr->d.mk_offset / hdr->d.sector_size);
920                         if (device_size(crypt_metadata_device(cd), &size) < 0)
921                                 return 0;
922                         return (size - hdr->d.hidden_volume_size +
923                                 (TCRYPT_HDR_HIDDEN_OFFSET_OLD)) / hdr->d.sector_size;
924                 }
925                 goto hdr_offset;
926         }
927
928         if (params->flags & CRYPT_TCRYPT_HIDDEN_HEADER) {
929                 if (device_size(crypt_metadata_device(cd), &size) < 0)
930                         return 0;
931                 return (size - hdr->d.hidden_volume_size +
932                         (TCRYPT_HDR_HIDDEN_OFFSET_OLD)) / hdr->d.sector_size;
933         }
934
935 hdr_offset:
936         return hdr->d.mk_offset / hdr->d.sector_size;
937 }
938
939 uint64_t TCRYPT_get_iv_offset(struct crypt_device *cd,
940                               struct tcrypt_phdr *hdr,
941                               struct crypt_params_tcrypt *params
942 )
943 {
944         if (params->mode && !strncmp(params->mode, "xts", 3))
945                 return TCRYPT_get_data_offset(cd, hdr, params);
946         else if (params->mode && !strncmp(params->mode, "lrw", 3))
947                 return 0;
948
949         return hdr->d.mk_offset / hdr->d.sector_size;
950 }
951
952 int TCRYPT_get_volume_key(struct crypt_device *cd,
953                           struct tcrypt_phdr *hdr,
954                           struct crypt_params_tcrypt *params,
955                           struct volume_key **vk)
956 {
957         struct tcrypt_algs *algs;
958         unsigned int i, key_index;
959
960         if (!hdr->d.version) {
961                 log_err(cd, _("This function is not supported without TCRYPT header load."));
962                 return -ENOTSUP;
963         }
964
965         algs = TCRYPT_get_algs(params->cipher, params->mode);
966         if (!algs)
967                 return -EINVAL;
968
969         *vk = crypt_alloc_volume_key(params->key_size, NULL);
970         if (!*vk)
971                 return -ENOMEM;
972
973         for (i = 0, key_index = 0; i < algs->chain_count; i++) {
974                 TCRYPT_copy_key(&algs->cipher[i], algs->mode,
975                                 &(*vk)->key[key_index], hdr->d.keys);
976                 key_index += algs->cipher[i].key_size;
977         }
978
979         return 0;
980 }
981
982 int TCRYPT_dump(struct crypt_device *cd,
983                 struct tcrypt_phdr *hdr,
984                 struct crypt_params_tcrypt *params)
985 {
986         log_std(cd, "TCRYPT header information for %s\n",
987                 device_path(crypt_metadata_device(cd)));
988         if (hdr->d.version) {
989                 log_std(cd, "Version:       \t%d\n", hdr->d.version);
990                 log_std(cd, "Driver req.:\t%d\n", hdr->d.version_tc);
991
992                 log_std(cd, "Sector size:\t%" PRIu32 "\n", hdr->d.sector_size);
993                 log_std(cd, "MK offset:\t%" PRIu64 "\n", hdr->d.mk_offset);
994                 log_std(cd, "PBKDF2 hash:\t%s\n", params->hash_name);
995         }
996         log_std(cd, "Cipher chain:\t%s\n", params->cipher);
997         log_std(cd, "Cipher mode:\t%s\n", params->mode);
998         log_std(cd, "MK bits:       \t%d\n", params->key_size * 8);
999         return 0;
1000 }