2ce3a94588edec69dbf210720ace2cd425f3a8bb
[platform/upstream/cryptsetup.git] / lib / bitlk / bitlk.c
1 /*
2  * BITLK (BitLocker-compatible) volume handling
3  *
4  * Copyright (C) 2019-2020 Red Hat, Inc. All rights reserved.
5  * Copyright (C) 2019-2020 Milan Broz
6  * Copyright (C) 2019-2020 Vojtech Trefny
7  *
8  * This file is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This file is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this file; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  */
22
23 #include <errno.h>
24 #include <string.h>
25 #include <uuid/uuid.h>
26 #include <time.h>
27 #include <iconv.h>
28 #include <limits.h>
29
30 #include "bitlk.h"
31 #include "internal.h"
32
33 #define BITLK_BOOTCODE_V1 "\xeb\x52\x90"
34 #define BITLK_BOOTCODE_V2 "\xeb\x58\x90"
35 #define BITLK_SIGNATURE "-FVE-FS-"
36 #define BITLK_SIGNATURE_TOGO "MSWIN4.1"
37 #define BITLK_HEADER_METADATA_OFFSET 160
38 #define BITLK_HEADER_METADATA_OFFSET_TOGO 424
39
40 /* FVE metadata header is split into two parts */
41 #define BITLK_FVE_METADATA_BLOCK_HEADER_LEN 64
42 #define BITLK_FVE_METADATA_HEADER_LEN 48
43 #define BITLK_FVE_METADATA_HEADERS_LEN BITLK_FVE_METADATA_BLOCK_HEADER_LEN + BITLK_FVE_METADATA_HEADER_LEN
44
45 /* total size of the FVE area (64 KiB) */
46 #define BITLK_FVE_METADATA_SIZE 64 * 1024
47
48 #define BITLK_ENTRY_HEADER_LEN 8
49 #define BITLK_VMK_HEADER_LEN 28
50
51 #define BITLK_OPEN_KEY_METADATA_LEN 12
52
53 #define BITLK_RECOVERY_KEY_LEN 55
54 #define BITLK_RECOVERY_PARTS 8
55 #define BITLK_RECOVERY_PART_LEN 6
56
57 #define BITLK_KDF_HASH "sha256"
58 #define BITLK_KDF_ITERATION_COUNT 0x100000
59
60 /* maximum number of segments for the DM device */
61 #define MAX_BITLK_SEGMENTS 10
62
63 /* January 1, 1970 as MS file time */
64 #define EPOCH_AS_FILETIME 116444736000000000
65 #define HUNDREDS_OF_NANOSECONDS 10000000
66
67 /* not available in older version of libuuid */
68 #ifndef UUID_STR_LEN
69 #define UUID_STR_LEN    37
70 #endif
71
72 /* known types of GUIDs from the BITLK superblock */
73 const uint8_t BITLK_GUID_NORMAL[16] = { 0x3b, 0xd6, 0x67, 0x49, 0x29, 0x2e, 0xd8, 0x4a,
74                                         0x83, 0x99, 0xf6, 0xa3, 0x39, 0xe3, 0xd0, 0x01 };
75 const uint8_t BITLK_GUID_EOW[16] = { 0x3b, 0x4d, 0xa8, 0x92, 0x80, 0xdd, 0x0e, 0x4d,
76                                      0x9e, 0x4e, 0xb1, 0xe3, 0x28, 0x4e, 0xae, 0xd8 };
77
78 /* taken from libfdisk gpt.c -- TODO: this is a good candidate for adding to libuuid */
79 struct bitlk_guid {
80         uint32_t   time_low;
81         uint16_t   time_mid;
82         uint16_t   time_hi_and_version;
83         uint8_t    clock_seq_hi;
84         uint8_t    clock_seq_low;
85         uint8_t    node[6];
86 } __attribute__ ((packed));
87
88 static void swap_guid(struct bitlk_guid *guid) {
89         guid->time_low = swab32(guid->time_low);
90         guid->time_mid = swab16(guid->time_mid);
91         guid->time_hi_and_version = swab16(guid->time_hi_and_version);
92 }
93
94 static void guid_to_string(struct bitlk_guid *guid, char *out) {
95         swap_guid(guid);
96         uuid_unparse((unsigned char *) guid, out);
97 }
98
99 typedef enum {
100         BITLK_SEGTYPE_CRYPT,
101         BITLK_SEGTYPE_ZERO,
102 } BitlkSegmentType;
103
104 struct segment {
105         uint64_t offset;
106         uint64_t length;
107         uint64_t iv_offset;
108         BitlkSegmentType type;
109 };
110
111 struct bitlk_signature {
112         uint8_t boot_code[3];
113         uint8_t signature[8];
114         uint16_t sector_size;
115 } __attribute__ ((packed));
116
117 struct bitlk_superblock {
118         struct bitlk_guid guid;
119         uint64_t fve_offset[3];
120 } __attribute__ ((packed));
121
122 struct bitlk_fve_metadata {
123         /* FVE metadata block header */
124         uint8_t signature[8];
125         uint16_t fve_size;
126         uint16_t fve_version;
127         uint16_t curr_state;
128         uint16_t next_state;
129         uint64_t volume_size;
130         uint32_t unknown2;
131         uint32_t volume_header_size;
132         uint64_t fve_offset[3];
133         uint64_t volume_header_offset;
134         /* FVE metadata header */
135         uint32_t metadata_size;
136         uint32_t metadata_version;
137         uint32_t metadata_header_size;
138         uint32_t metada_size_copy;
139         struct bitlk_guid guid;
140         uint32_t next_nonce;
141         uint16_t encryption;
142         uint16_t unknown3;
143         uint64_t creation_time;
144 } __attribute__ ((packed));
145
146 struct bitlk_entry_header_block {
147         uint64_t offset;
148         uint64_t size;
149 } __attribute__ ((packed));
150
151 struct bitlk_entry_vmk {
152         struct bitlk_guid guid;
153         uint8_t modified[8];
154         uint16_t _unknown;
155         uint16_t protection;
156 } __attribute__ ((packed));
157
158 struct bitlk_kdf_data {
159         char last_sha256[32];
160         char initial_sha256[32];
161         char salt[16];
162         uint64_t count;
163 };
164
165 static BITLKVMKProtection get_vmk_protection(uint16_t protection)
166 {
167         switch (protection) {
168         case 0x0000:
169                 return BITLK_PROTECTION_CLEAR_KEY;
170         case 0x0100:
171                 return BITLK_PROTECTION_TPM;
172         case 0x0200:
173                 return BITLK_PROTECTION_STARTUP_KEY;
174         case 0x0500:
175                 return BITLK_PROTECTION_TPM_PIN;
176         case 0x0800:
177                 return BITLK_PROTECTION_RECOVERY_PASSPHRASE;
178         case 0x1000:
179                 return BITLK_PROTECTION_SMART_CARD;
180         case 0x2000:
181                 return BITLK_PROTECTION_PASSPHRASE;
182         default:
183                 return BITLK_PROTECTION_UNKNOWN;
184         }
185 }
186
187 static const char* get_vmk_protection_string(BITLKVMKProtection protection)
188 {
189         switch (protection) {
190         case BITLK_PROTECTION_CLEAR_KEY:
191                 return "VMK protected with clear key";
192         case BITLK_PROTECTION_TPM:
193                 return "VMK protected with TPM";
194         case BITLK_PROTECTION_STARTUP_KEY:
195                 return "VMK protected with startup key";
196         case BITLK_PROTECTION_TPM_PIN:
197                 return "VMK protected with TPM and PIN";
198         case BITLK_PROTECTION_PASSPHRASE:
199                 return "VMK protected with passphrase";
200         case BITLK_PROTECTION_RECOVERY_PASSPHRASE:
201                 return "VMK protected with recovery passphrase";
202         case BITLK_PROTECTION_SMART_CARD:
203                 return "VMK protected with smart card";
204         default:
205                 return "VMK with unknown protection";
206         }
207 }
208
209 static const char* get_bitlk_type_string(BITLKEncryptionType type)
210 {
211         switch (type)
212         {
213         case BITLK_ENCRYPTION_TYPE_NORMAL:
214                 return "normal";
215         case BITLK_ENCRYPTION_TYPE_EOW:
216                 return "encrypt-on-write";
217         default:
218                 return "unknown";
219         }
220 }
221
222 /* TODO -- move to some utils file */
223 static void hexprint(struct crypt_device *cd, const char *d, int n, const char *sep)
224 {
225         int i;
226         for(i = 0; i < n; i++)
227                 log_std(cd, "%02hhx%s", (const char)d[i], sep);
228 }
229
230 static uint64_t filetime_to_unixtime(uint64_t time)
231 {
232         return (time - EPOCH_AS_FILETIME) / HUNDREDS_OF_NANOSECONDS;
233 }
234
235 static int convert_to_utf8(struct crypt_device *cd, uint8_t *input, size_t inlen, char **out)
236 {
237         char *outbuf = NULL;
238         iconv_t ic;
239         size_t ic_inlen = inlen;
240         size_t ic_outlen = inlen;
241         char *ic_outbuf = NULL;
242         size_t r = 0;
243
244         outbuf = malloc(inlen);
245         if (outbuf == NULL)
246                 return -ENOMEM;
247
248         memset(outbuf, 0, inlen);
249         ic_outbuf = outbuf;
250
251         ic = iconv_open("UTF-8", "UTF-16LE");
252         r = iconv(ic, (char **) &input, &ic_inlen, &ic_outbuf, &ic_outlen);
253         iconv_close(ic);
254
255         if (r == 0)
256                 *out = strdup(outbuf);
257         else {
258                 *out = NULL;
259                 log_dbg(cd, "Failed to convert volume description: %s", strerror(errno));
260                 r = 0;
261         }
262
263         free(outbuf);
264         return r;
265 }
266
267 static int passphrase_to_utf16(struct crypt_device *cd, char *input, size_t inlen, char **out)
268 {
269         char *outbuf = NULL;
270         iconv_t ic;
271         size_t ic_inlen = inlen;
272         size_t ic_outlen = inlen * 2;
273         char *ic_outbuf = NULL;
274         size_t r = 0;
275
276         if (inlen == 0)
277                 return r;
278
279         outbuf = crypt_safe_alloc(inlen * 2);
280         if (outbuf == NULL)
281                 return -ENOMEM;
282
283         memset(outbuf, 0, inlen * 2);
284         ic_outbuf = outbuf;
285
286         ic = iconv_open("UTF-16LE", "UTF-8");
287         r = iconv(ic, &input, &ic_inlen, &ic_outbuf, &ic_outlen);
288         iconv_close(ic);
289
290         if (r == 0) {
291                 *out = outbuf;
292         } else {
293                 *out = NULL;
294                 crypt_safe_free(outbuf);
295                 log_dbg(cd, "Failed to convert passphrase: %s", strerror(errno));
296                 r = -errno;
297         }
298
299         return r;
300 }
301
302 static int parse_vmk_entry(struct crypt_device *cd, uint8_t *data, int start, int end, struct bitlk_vmk **vmk)
303 {
304         uint16_t key_entry_size = 0;
305         uint16_t key_entry_type = 0;
306         uint16_t key_entry_value = 0;
307         size_t key_size = 0;
308         char *string = NULL;
309         const char *key = NULL;
310         struct volume_key *vk = NULL;
311         bool supported = false;
312
313         /* only passphrase or recovery passphrase vmks are supported (can be used to activate) */
314         supported = (*vmk)->protection == BITLK_PROTECTION_PASSPHRASE || (*vmk)->protection == BITLK_PROTECTION_RECOVERY_PASSPHRASE;
315
316         while (end - start > 2) {
317                 /* size of this entry */
318                 memcpy(&key_entry_size, data + start, sizeof(key_entry_size));
319                 key_entry_size = le16_to_cpu(key_entry_size);
320                 if (key_entry_size == 0)
321                         break;
322
323                 /* type and value of this entry */
324                 memcpy(&key_entry_type, data + start + sizeof(key_entry_size), sizeof(key_entry_type));
325                 memcpy(&key_entry_value,
326                        data + start + sizeof(key_entry_size) + sizeof(key_entry_type),
327                        sizeof(key_entry_value));
328                 key_entry_type = le16_to_cpu(key_entry_type);
329                 key_entry_value = le16_to_cpu(key_entry_value);
330
331                 if (key_entry_type != BITLK_ENTRY_TYPE_PROPERTY) {
332                         if (supported) {
333                                 log_err(cd, _("Unexpected metadata entry type '%u' found when parsing supported Volume Master Key."), key_entry_type);
334                                 return -EINVAL;
335                         } else {
336                                 log_dbg(cd, "Unexpected metadata entry type '%u' found when parsing unsupported VMK.", key_entry_type);
337                         }
338                 }
339
340                 /* stretch key with salt, skip 4 B (encryption method of the stretch key) */
341                 if (key_entry_value == BITLK_ENTRY_VALUE_STRETCH_KEY)
342                         memcpy((*vmk)->salt,
343                                data + start + BITLK_ENTRY_HEADER_LEN + 4,
344                                sizeof((*vmk)->salt));
345                 /* AES-CCM encrypted key */
346                 else if (key_entry_value == BITLK_ENTRY_VALUE_ENCRYPTED_KEY) {
347                         /* nonce */
348                         memcpy((*vmk)->nonce,
349                                data + start + BITLK_ENTRY_HEADER_LEN,
350                                sizeof((*vmk)->nonce));
351                         /* MAC tag */
352                         memcpy((*vmk)->mac_tag,
353                                data + start + BITLK_ENTRY_HEADER_LEN + BITLK_NONCE_SIZE,
354                                sizeof((*vmk)->mac_tag));
355                         /* AES-CCM encrypted key */
356                         key_size = key_entry_size - (BITLK_ENTRY_HEADER_LEN + BITLK_NONCE_SIZE + BITLK_VMK_MAC_TAG_SIZE);
357                         key = (const char *) data + start + BITLK_ENTRY_HEADER_LEN + BITLK_NONCE_SIZE + BITLK_VMK_MAC_TAG_SIZE;
358                         vk = crypt_alloc_volume_key(key_size, key);
359                         if (vk == NULL)
360                                 return -ENOMEM;
361                         crypt_volume_key_add_next(&((*vmk)->vk), vk);
362                 /* clear key for a partially decrypted volume */
363                 } else if (key_entry_value == BITLK_ENTRY_VALUE_KEY) {
364                         /* We currently don't want to support opening a partially decrypted
365                          * device so we don't need to store this key.
366                          *
367                          * key_size = key_entry_size - (BITLK_ENTRY_HEADER_LEN + 4);
368                          * key = (const char *) data + start + BITLK_ENTRY_HEADER_LEN + 4;
369                          * vk = crypt_alloc_volume_key(key_size, key);
370                          * if (vk == NULL)
371                          *      return -ENOMEM;
372                          * crypt_volume_key_add_next(&((*vmk)->vk), vk);
373                          */
374                         log_dbg(cd, "Skipping clear key metadata entry.");
375                 /* unknown timestamps in recovery protected VMK */
376                 } else if (key_entry_value == BITLK_ENTRY_VALUE_RECOVERY_TIME) {
377                         ;
378                 } else if (key_entry_value == BITLK_ENTRY_VALUE_STRING) {
379                         if (convert_to_utf8(cd, data + start + BITLK_ENTRY_HEADER_LEN, key_entry_size - BITLK_ENTRY_HEADER_LEN, &string) < 0) {
380                                 log_err(cd, _("Invalid string found when parsing Volume Master Key."));
381                                 free(string);
382                                 return -EINVAL;
383                         } else if ((*vmk)->name != NULL) {
384                                 if (supported) {
385                                         log_err(cd, _("Unexpected string ('%s') found when parsing supported Volume Master Key."), string);
386                                         free(string);
387                                         return -EINVAL;
388                                 }
389                                 log_dbg(cd, "Unexpected string ('%s') found when parsing unsupported VMK.", string);
390                                 free(string);
391                                 string = NULL;
392                         } else {
393                                 /* Assume that strings in VMK are the name of the VMK */
394                                 (*vmk)->name = string;
395                                 string = NULL;
396                         }
397                 } else {
398                         if (supported) {
399                                 log_err(cd, _("Unexpected metadata entry value '%u' found when parsing supported Volume Master Key."), key_entry_value);
400                                 return -EINVAL;
401                         } else {
402                                 log_dbg(cd, "Unexpected metadata entry value '%u' found when parsing unsupported VMK.", key_entry_value);
403                         }
404                 }
405
406                 start += key_entry_size;
407         }
408
409         return 0;
410 }
411
412 void BITLK_bitlk_fvek_free(struct bitlk_fvek *fvek)
413 {
414         if (!fvek)
415                 return;
416
417         crypt_free_volume_key(fvek->vk);
418         free(fvek);
419 }
420
421 void BITLK_bitlk_vmk_free(struct bitlk_vmk *vmk)
422 {
423         struct bitlk_vmk *vmk_next = NULL;
424
425         while (vmk) {
426                 if (vmk->guid)
427                         free(vmk->guid);
428                 if (vmk->name)
429                         free(vmk->name);
430                 crypt_free_volume_key(vmk->vk);
431                 vmk_next = vmk->next;
432                 free(vmk);
433                 vmk = vmk_next;
434         }
435 }
436
437 void BITLK_bitlk_metadata_free(struct bitlk_metadata *metadata)
438 {
439         free(metadata->guid);
440         if (metadata->description)
441                 free(metadata->description);
442         BITLK_bitlk_vmk_free(metadata->vmks);
443         BITLK_bitlk_fvek_free(metadata->fvek);
444 }
445
446 int BITLK_read_sb(struct crypt_device *cd, struct bitlk_metadata *params)
447 {
448         int devfd;
449         struct device *device = crypt_metadata_device(cd);
450         struct bitlk_signature sig = {};
451         struct bitlk_superblock sb = {};
452         struct bitlk_fve_metadata fve = {};
453         struct bitlk_entry_vmk entry_vmk = {};
454         uint8_t *fve_entries = NULL;
455         uint32_t fve_metadata_size = 0;
456         int fve_offset = 0;
457         char guid_buf[UUID_STR_LEN] = {0};
458         uint16_t entry_size = 0;
459         uint16_t entry_type = 0;
460         int i = 0;
461         int r = 0;
462         int start = 0;
463         int end = 0;
464         size_t key_size = 0;
465         const char *key = NULL;
466
467         struct bitlk_vmk *vmk = NULL;
468         struct bitlk_vmk *vmk_p = params->vmks;
469
470         devfd = device_open(cd, crypt_data_device(cd), O_RDONLY);
471         if (devfd < 0) {
472                 r = -EINVAL;
473                 goto out;
474         }
475
476         /* read and check the signature */
477         if (read_lseek_blockwise(devfd, device_block_size(cd, device),
478                 device_alignment(device), &sig, sizeof(sig), 0) != sizeof(sig)) {
479                 log_err(cd, _("Failed to read BITLK signature from %s."), device_path(device));
480                 r = -EINVAL;
481                 goto out;
482         }
483
484         if (memcmp(sig.boot_code, BITLK_BOOTCODE_V1, sizeof(sig.boot_code)) == 0) {
485                 log_err(cd, _("BITLK version 1 is currently not supported."));
486                 r = -ENOTSUP;
487                 goto out;
488         } else if (memcmp(sig.boot_code, BITLK_BOOTCODE_V2, sizeof(sig.boot_code)) == 0)
489                 ;
490         else {
491                 log_err(cd, _("Invalid or unknown boot signature for BITLK device."));
492                 r = -EINVAL;
493                 goto out;
494         }
495
496         if (memcmp(sig.signature, BITLK_SIGNATURE, sizeof(sig.signature)) == 0) {
497                 params->togo = false;
498                 fve_offset = BITLK_HEADER_METADATA_OFFSET;
499         } else if (memcmp(sig.signature, BITLK_SIGNATURE_TOGO, sizeof(sig.signature)) == 0) {
500                 params->togo = true;
501                 fve_offset = BITLK_HEADER_METADATA_OFFSET_TOGO;
502         } else {
503                 log_err(cd, _("Invalid or unknown signature for BITLK device."));
504                 r = -EINVAL;
505                 goto out;
506         }
507
508         params->sector_size = le16_to_cpu(sig.sector_size);
509         if (!(params->sector_size == 512 || params->sector_size == 4096)) {
510                 log_err(cd, _("Unsupported sector size %" PRIu16 "."), params->sector_size);
511                 r = -EINVAL;
512                 goto out;
513         }
514
515         /* read GUID and FVE metadata offsets */
516         if (read_lseek_blockwise(devfd, device_block_size(cd, device),
517                 device_alignment(device), &sb, sizeof(sb), fve_offset) != sizeof(sb)) {
518                 log_err(cd, _("Failed to read BITLK header from %s."), device_path(device));
519                 r = -EINVAL;
520                 goto out;
521         }
522
523         /* get encryption "type" based on the GUID from BITLK superblock */
524         if (memcmp(&sb.guid, BITLK_GUID_NORMAL, 16) == 0)
525                 params->type = BITLK_ENCRYPTION_TYPE_NORMAL;
526         else if (memcmp(&sb.guid, BITLK_GUID_EOW, 16) == 0)
527                 params->type = BITLK_ENCRYPTION_TYPE_EOW;
528         else
529                 params->type = BITLK_ENCRYPTION_TYPE_UNKNOWN;
530         log_dbg(cd, "BITLK type from GUID: %s.", get_bitlk_type_string(params->type));
531
532         for (i = 0; i < 3; i++)
533                 params->metadata_offset[i] = le64_to_cpu(sb.fve_offset[i]);
534
535         log_dbg(cd, "Reading BITLK FVE metadata of size %zu on device %s, offset %" PRIu64 ".",
536                 sizeof(fve), device_path(device), params->metadata_offset[0]);
537
538         /* read FVE metadata from the first metadata area */
539         if (read_lseek_blockwise(devfd, device_block_size(cd, device),
540                 device_alignment(device), &fve, sizeof(fve), params->metadata_offset[0]) != sizeof(fve) ||
541                 memcmp(fve.signature, BITLK_SIGNATURE, sizeof(fve.signature)) ||
542                 le16_to_cpu(fve.fve_version) != 2) {
543                 log_err(cd, _("Failed to read BITLK FVE metadata from %s."), device_path(device));
544                 r = -EINVAL;
545                 goto out;
546         }
547
548         /* check encryption state for the device */
549         params->state = true;
550         if (le16_to_cpu(fve.curr_state) != BITLK_STATE_NORMAL || le16_to_cpu(fve.next_state) != BITLK_STATE_NORMAL) {
551                 params->state = false;
552                 log_dbg(cd, "Unknown/unsupported state detected. Current state: %"PRIu16", next state: %"PRIu16".",
553                         le16_to_cpu(fve.curr_state), le16_to_cpu(fve.next_state));
554         }
555
556         params->metadata_version = le16_to_cpu(fve.fve_version);
557         fve_metadata_size = le32_to_cpu(fve.metadata_size);
558
559         switch (le16_to_cpu(fve.encryption)) {
560         /* AES-CBC with Elephant difuser */
561         case 0x8000:
562                 params->key_size = 128;
563                 params->cipher = "aes";
564                 params->cipher_mode = "cbc-elephant";
565                 break;
566         case 0x8001:
567                 params->key_size = 256;
568                 params->cipher = "aes";
569                 params->cipher_mode = "cbc-elephant";
570                 break;
571         /* AES-CBC */
572         case 0x8002:
573                 params->key_size = 128;
574                 params->cipher = "aes";
575                 params->cipher_mode = "cbc-eboiv";
576                 break;
577         case 0x8003:
578                 params->key_size = 256;
579                 params->cipher = "aes";
580                 params->cipher_mode = "cbc-eboiv";
581                 break;
582         /* AES-XTS */
583         case 0x8004:
584                 params->key_size = 128;
585                 params->cipher = "aes";
586                 params->cipher_mode = "xts-plain64";
587                 break;
588         case 0x8005:
589                 params->key_size = 256;
590                 params->cipher = "aes";
591                 params->cipher_mode = "xts-plain64";
592                 break;
593         default:
594                 log_err(cd, _("Unknown or unsupported encryption type."));
595                 params->key_size = 0;
596                 params->cipher = NULL;
597                 params->cipher_mode = NULL;
598                 r = -ENOTSUP;
599                 goto out;
600         };
601
602         /* device GUID */
603         guid_to_string(&fve.guid, guid_buf);
604         params->guid = strdup(guid_buf);
605         if (!params->guid) {
606                 r = -ENOMEM;
607                 goto out;
608         }
609
610         params->creation_time = filetime_to_unixtime(le64_to_cpu(fve.creation_time));
611
612         /* read and parse all FVE metadata entries */
613         fve_entries = malloc(fve_metadata_size - BITLK_FVE_METADATA_HEADER_LEN);
614         if (!fve_entries) {
615                 r = -ENOMEM;
616                 goto out;
617         }
618         memset(fve_entries, 0, (fve_metadata_size - BITLK_FVE_METADATA_HEADER_LEN));
619
620         log_dbg(cd, "Reading BITLK FVE metadata entries of size %" PRIu32 " on device %s, offset %" PRIu64 ".",
621                 fve_metadata_size - BITLK_FVE_METADATA_HEADER_LEN, device_path(device),
622                 params->metadata_offset[0] + BITLK_FVE_METADATA_HEADERS_LEN);
623
624         if (read_lseek_blockwise(devfd, device_block_size(cd, device),
625                 device_alignment(device), fve_entries, fve_metadata_size - BITLK_FVE_METADATA_HEADER_LEN,
626                 params->metadata_offset[0] + BITLK_FVE_METADATA_HEADERS_LEN) != fve_metadata_size - BITLK_FVE_METADATA_HEADER_LEN) {
627                 log_err(cd, _("Failed to read BITLK metadata entries from %s."), device_path(device));
628                 r = -EINVAL;
629                 goto out;
630         }
631
632         end = fve_metadata_size - BITLK_FVE_METADATA_HEADER_LEN;
633         while (end - start > 2) {
634                 /* size of this entry */
635                 memcpy(&entry_size, fve_entries + start, sizeof(entry_size));
636                 entry_size = le16_to_cpu(entry_size);
637                 if (entry_size == 0)
638                         break;
639
640                 /* type of this entry */
641                 memcpy(&entry_type, fve_entries + start + sizeof(entry_size), sizeof(entry_type));
642                 entry_type = le16_to_cpu(entry_type);
643
644                 /* VMK */
645                 if (entry_type == BITLK_ENTRY_TYPE_VMK) {
646                         /* skip first four variables in the entry (entry size, type, value and version) */
647                         memcpy(&entry_vmk,
648                                fve_entries + start + BITLK_ENTRY_HEADER_LEN,
649                                sizeof(entry_vmk));
650
651                         vmk = malloc(sizeof(struct bitlk_vmk));
652                         memset(vmk, 0, sizeof(struct bitlk_vmk));
653
654                         guid_to_string(&entry_vmk.guid, guid_buf);
655                         vmk->guid = strdup (guid_buf);
656
657                         vmk->name = NULL;
658
659                         vmk->protection = get_vmk_protection(le16_to_cpu(entry_vmk.protection));
660
661                         /* more data in another entry list */
662                         r = parse_vmk_entry(cd, fve_entries,
663                                               start + BITLK_ENTRY_HEADER_LEN + BITLK_VMK_HEADER_LEN,
664                                               start + entry_size, &vmk);
665                         if (r < 0) {
666                                 BITLK_bitlk_vmk_free(vmk);
667                                 goto out;
668                         }
669
670                         if (params->vmks == NULL)
671                                 params->vmks = vmk;
672                         else
673                                 vmk_p->next = vmk;
674
675                         vmk_p = vmk;
676                         vmk = vmk->next;
677                 /* FVEK */
678                 } else if (entry_type == BITLK_ENTRY_TYPE_FVEK) {
679                         params->fvek = malloc(sizeof(struct bitlk_fvek));
680                         memcpy(params->fvek->nonce,
681                                fve_entries + start + BITLK_ENTRY_HEADER_LEN,
682                                sizeof(params->fvek->nonce));
683                         /* MAC tag */
684                         memcpy(params->fvek->mac_tag,
685                                fve_entries + start + BITLK_ENTRY_HEADER_LEN + BITLK_NONCE_SIZE,
686                                sizeof(params->fvek->mac_tag));
687                         /* AES-CCM encrypted key */
688                         key_size = entry_size - (BITLK_ENTRY_HEADER_LEN + BITLK_NONCE_SIZE + BITLK_VMK_MAC_TAG_SIZE);
689                         key = (const char *) fve_entries + start + BITLK_ENTRY_HEADER_LEN + BITLK_NONCE_SIZE + BITLK_VMK_MAC_TAG_SIZE;
690                         params->fvek->vk = crypt_alloc_volume_key(key_size, key);
691                         if (params->fvek->vk == NULL) {
692                                 r = -ENOMEM;
693                                 goto out;
694                         }
695                 /* volume header info (location and size) */
696                 } else if (entry_type == BITLK_ENTRY_TYPE_VOLUME_HEADER) {
697                         struct bitlk_entry_header_block entry_header;
698                         memcpy(&entry_header,
699                                fve_entries + start + BITLK_ENTRY_HEADER_LEN,
700                                sizeof(entry_header));
701                         params->volume_header_offset = le64_to_cpu(entry_header.offset);
702                         params->volume_header_size = le64_to_cpu(entry_header.size);
703                 /* volume description (utf-16 string) */
704                 } else if (entry_type == BITLK_ENTRY_TYPE_DESCRIPTION) {
705                         r = convert_to_utf8(cd, fve_entries + start + BITLK_ENTRY_HEADER_LEN,
706                                             entry_size - BITLK_ENTRY_HEADER_LEN,
707                                             &(params->description));
708                         if (r < 0) {
709                                 BITLK_bitlk_vmk_free(vmk);
710                                 goto out;
711                         }
712                 }
713
714                 start += entry_size;
715         }
716
717 out:
718         if (fve_entries)
719                 free(fve_entries);
720         return r;
721 }
722
723 int BITLK_dump(struct crypt_device *cd, struct device *device, struct bitlk_metadata *params)
724 {
725         struct volume_key *vk_p;
726         struct bitlk_vmk *vmk_p;
727         int next_id = 0;
728         int i = 0;
729
730         log_std(cd, "Info for BITLK%s device %s.\n", params->togo ? " To Go" : "", device_path(device));
731         log_std(cd, "Version:      \t%u\n", params->metadata_version);
732         log_std(cd, "GUID:         \t%s\n", params->guid);
733         log_std(cd, "Sector size:  \t%u [bytes]\n", params->sector_size);
734         log_std(cd, "Created:      \t%s", ctime((time_t *)&(params->creation_time)));
735         log_std(cd, "Description:  \t%s\n", params->description);
736         log_std(cd, "Cipher name:  \t%s\n", params->cipher);
737         log_std(cd, "Cipher mode:  \t%s\n", params->cipher_mode);
738         log_std(cd, "Cipher key:   \t%u bits\n", params->key_size);
739
740         log_std(cd, "\n");
741
742         log_std(cd, "Keyslots:\n");
743         vmk_p = params->vmks;
744         while (vmk_p) {
745                 log_std(cd, " %d: VMK\n", next_id);
746                 if (vmk_p->name != NULL) {
747                         log_std(cd, "\tName:       \t%s\n", vmk_p->name);
748                 }
749                 log_std(cd, "\tGUID:       \t%s\n", vmk_p->guid);
750                 log_std(cd, "\tProtection: \t%s\n", get_vmk_protection_string (vmk_p->protection));
751                 log_std(cd, "\tSalt:       \t");
752                 hexprint(cd, (const char *) vmk_p->salt, 16, "");
753                 log_std(cd, "\n");
754
755                 vk_p = vmk_p->vk;
756                 while (vk_p) {
757                         log_std(cd, "\tKey data size:\t%zu [bytes]\n", vk_p->keylength);
758                         vk_p = vk_p->next;
759                 }
760                 vmk_p = vmk_p->next;
761                 next_id++;
762         }
763
764         log_std(cd, " %d: FVEK\n", next_id);
765         log_std(cd, "\tKey data size:\t%zu [bytes]\n", params->fvek->vk->keylength);
766
767         log_std(cd, "\n");
768
769         log_std(cd, "Metadata segments:\n");
770
771         for (i = 0; i < 3; i++) {
772                 log_std(cd, " %d: FVE metadata area\n", i);
773                 log_std(cd, "\tOffset: \t%" PRIu64 " [bytes]\n", params->metadata_offset[i]);
774                 log_std(cd, "\tSize:   \t%d [bytes]\n", BITLK_FVE_METADATA_SIZE);
775         }
776
777         log_std(cd, " %d: Volume header\n", i);
778         log_std(cd, "\tOffset: \t%" PRIu64 " [bytes]\n", params->volume_header_offset);
779         log_std(cd, "\tSize:   \t%" PRIu64 " [bytes]\n", params->volume_header_size);
780         log_std(cd, "\tCipher: \t%s-%s\n", params->cipher, params->cipher_mode);
781
782         return 0;
783 }
784
785 /* check if given passphrase can be a recovery key (has right format) and convert it */
786 static int get_recovery_key(struct crypt_device *cd,
787                             const char *password,
788                             size_t passwordLen,
789                             struct volume_key **rc_key)
790 {
791         unsigned int i, j = 0;
792         uint16_t parts[BITLK_RECOVERY_PARTS] = {0};
793         char part_str[BITLK_RECOVERY_PART_LEN + 1] = {0};
794         long part_num = 0;
795
796         /* check the passphrase it should be:
797             - 55 characters
798             - 8 groups of 6 divided by '-'
799             - each part is a number dividable by 11
800         */
801         if (passwordLen != BITLK_RECOVERY_KEY_LEN) {
802                 if (passwordLen == BITLK_RECOVERY_KEY_LEN + 1 && password[passwordLen - 1] == '\n') {
803                         /* looks like a recovery key with an extra newline, possibly from a key file */
804                         passwordLen--;
805                         log_dbg(cd, "Possible extra EOL stripped from the recovery key.");
806                 } else
807                         return 0;
808         }
809
810         for (i = BITLK_RECOVERY_PART_LEN; i < passwordLen; i += BITLK_RECOVERY_PART_LEN + 1) {
811                 if (password[i] != '-')
812                         return 0;
813         }
814
815         for (i = 0, j = 0; i < passwordLen; i += BITLK_RECOVERY_PART_LEN + 1, j++) {
816                 strncpy(part_str, password + i, BITLK_RECOVERY_PART_LEN);
817
818                 errno = 0;
819                 part_num = strtol(part_str, NULL, 10);
820                 if ((errno == ERANGE && (part_num == LONG_MAX || part_num == LONG_MIN)) ||
821                     (errno != 0 && part_num == 0))
822                         return -errno;
823
824                 if (part_num % 11 != 0)
825                         return 0;
826                 parts[j] = cpu_to_le16(part_num / 11);
827         }
828
829         *rc_key = crypt_alloc_volume_key(16, (const char*) parts);
830         if (*rc_key == NULL)
831                 return -ENOMEM;
832
833         return 0;
834 }
835
836 static int bitlk_kdf(struct crypt_device *cd,
837                      const char *password,
838                      size_t passwordLen,
839                      bool recovery,
840                      const uint8_t *salt,
841                      struct volume_key **vk)
842 {
843         struct bitlk_kdf_data kdf = {};
844         struct crypt_hash *hd = NULL;
845         int len = 0;
846         char *utf16Password = NULL;
847         int i = 0;
848         int r = 0;
849
850         memcpy(kdf.salt, salt, 16);
851
852         r = crypt_hash_init(&hd, BITLK_KDF_HASH);
853         if (r < 0)
854                 return r;
855         len = crypt_hash_size(BITLK_KDF_HASH);
856         if (len < 0) {
857                 crypt_hash_destroy(hd);
858                 return len;
859         }
860
861         if (!recovery) {
862                 /* passphrase: convert to UTF-16 first, then sha256(sha256(pw)) */
863                 r = passphrase_to_utf16(cd, CONST_CAST(char*)password, passwordLen, &utf16Password);
864                 if (r < 0)
865                         goto out;
866
867                 crypt_hash_write(hd, utf16Password, passwordLen * 2);
868                 r = crypt_hash_final(hd, kdf.initial_sha256, len);
869                 if (r < 0)
870                         goto out;
871
872                 crypt_hash_write(hd, kdf.initial_sha256, len);
873                 r = crypt_hash_final(hd, kdf.initial_sha256, len);
874                 if (r < 0)
875                         goto out;
876         } else {
877                 /* recovery passphrase: already converted in #get_recovery_key, now just sha256(rpw) */
878                 crypt_hash_write(hd, password, passwordLen);
879                 r = crypt_hash_final(hd, kdf.initial_sha256, len);
880                 if (r < 0)
881                         goto out;
882         }
883
884         for (i = 0; i < BITLK_KDF_ITERATION_COUNT; i++) {
885                 crypt_hash_write(hd, (const char*) &kdf, sizeof(kdf));
886                 r = crypt_hash_final(hd, kdf.last_sha256, len);
887                 if (r < 0)
888                         goto out;
889                 kdf.count = cpu_to_le64(le64_to_cpu(kdf.count) + 1);
890         }
891
892         *vk = crypt_alloc_volume_key(len, kdf.last_sha256);
893
894 out:
895         crypt_safe_free(utf16Password);
896         if (hd)
897                 crypt_hash_destroy(hd);
898         return r;
899 }
900
901 static int decrypt_key(struct crypt_device *cd,
902                        struct volume_key **vk,
903                        struct volume_key *enc_key,
904                        struct volume_key *key,
905                        const uint8_t *tag, size_t tag_size,
906                        const uint8_t *iv, size_t iv_size,
907                        bool is_fvek)
908 {
909         char *outbuf;
910         int r;
911         uint32_t key_size = 0;
912
913         outbuf = crypt_safe_alloc(enc_key->keylength);
914         if (!outbuf)
915                 return -ENOMEM;
916
917         r = crypt_bitlk_decrypt_key(key->key, key->keylength, enc_key->key, outbuf, enc_key->keylength,
918                                 (const char*)iv, iv_size, (const char*)tag, tag_size);
919         if (r < 0) {
920                 if (r == -ENOTSUP)
921                         log_err(cd, _("This operation is not supported."));
922                 goto out;
923         }
924
925         /* key_data has it's size as part of the metadata */
926         memcpy(&key_size, outbuf, 4);
927         key_size = le32_to_cpu(key_size);
928         if (enc_key->keylength != key_size) {
929                 log_err(cd, _("Wrong key size."));
930                 r = -EINVAL;
931                 goto out;
932         }
933
934         if (is_fvek && strcmp(crypt_get_cipher_mode(cd), "cbc-elephant") == 0 &&
935                 crypt_get_volume_key_size(cd) == 16) {
936                 /* 128bit AES-CBC with Elephant -- key size is 256 bit (2 keys) but key data is 512 bits,
937                    data: 16B CBC key, 16B empty, 16B elephant key, 16B empty */
938                 memcpy(outbuf + 16 + BITLK_OPEN_KEY_METADATA_LEN,
939                         outbuf + 2 * 16 + BITLK_OPEN_KEY_METADATA_LEN, 16);
940                 key_size = 32 + BITLK_OPEN_KEY_METADATA_LEN;
941         }
942
943
944         *vk = crypt_alloc_volume_key(key_size - BITLK_OPEN_KEY_METADATA_LEN,
945                                         (const char *)(outbuf + BITLK_OPEN_KEY_METADATA_LEN));
946         r = *vk ? 0 : -ENOMEM;
947 out:
948         crypt_safe_free(outbuf);
949         return r;
950 }
951
952 int BITLK_activate(struct crypt_device *cd,
953                    const char *name,
954                    const char *password,
955                    size_t passwordLen,
956                    const struct bitlk_metadata *params,
957                    uint32_t flags)
958 {
959         int r = 0;
960         int i = 0;
961         int j = 0;
962         int min = 0;
963         int num_segments = 0;
964         struct crypt_dm_active_device dmd = {
965                 .flags = flags,
966         };
967         struct dm_target *next_segment = NULL;
968         struct volume_key *open_vmk_key = NULL;
969         struct volume_key *open_fvek_key = NULL;
970         struct volume_key *vmk_dec_key = NULL;
971         struct volume_key *recovery_key = NULL;
972         const struct bitlk_vmk *next_vmk = NULL;
973         struct segment segments[MAX_BITLK_SEGMENTS] = {};
974         struct segment temp;
975         uint64_t next_start = 0;
976         uint64_t next_end = 0;
977         uint64_t last_segment = 0;
978         uint32_t dmt_flags;
979
980         if (!params->state) {
981                 log_err(cd, _("This BITLK device is in an unsupported state and cannot be activated."));
982                 r = -ENOTSUP;
983                 goto out;
984         }
985
986         if (params->type != BITLK_ENCRYPTION_TYPE_NORMAL) {
987                 log_err(cd, _("BITLK devices with type '%s' cannot be activated."), get_bitlk_type_string(params->type));
988                 r = -ENOTSUP;
989                 goto out;
990         }
991
992         next_vmk = params->vmks;
993         while (next_vmk) {
994                 if (next_vmk->protection == BITLK_PROTECTION_PASSPHRASE) {
995                         r = bitlk_kdf(cd, password, passwordLen, false, next_vmk->salt, &vmk_dec_key);
996                         if (r)
997                                 return r;
998                 } else if (next_vmk->protection == BITLK_PROTECTION_RECOVERY_PASSPHRASE) {
999                         r = get_recovery_key(cd, password, passwordLen, &recovery_key);
1000                         if (r)
1001                                 return r;
1002                         if (recovery_key == NULL) {
1003                                 /* r = 0 but no key -> given passphrase is not a recovery passphrase */
1004                                 r = -EPERM;
1005                                 next_vmk = next_vmk->next;
1006                                 continue;
1007                         }
1008                         log_dbg(cd, "Trying to use given password as a recovery key.");
1009                         r = bitlk_kdf(cd, recovery_key->key, recovery_key->keylength,
1010                                       true, next_vmk->salt, &vmk_dec_key);
1011                         crypt_free_volume_key(recovery_key);
1012                         if (r)
1013                                 return r;
1014                 } else {
1015                         /* only passphrase and recovery passphrase VMKs supported right now */
1016                         log_dbg(cd, "Skipping %s", get_vmk_protection_string(next_vmk->protection));
1017                         next_vmk = next_vmk->next;
1018                         if (r == 0)
1019                                 /* we need to set error code in case we have only unsupported VMKs */
1020                                 r = -ENOTSUP;
1021                         continue;
1022                 }
1023
1024                 log_dbg(cd, "Trying to decrypt %s.", get_vmk_protection_string(next_vmk->protection));
1025                 r = decrypt_key(cd, &open_vmk_key, next_vmk->vk, vmk_dec_key,
1026                                 next_vmk->mac_tag, BITLK_VMK_MAC_TAG_SIZE,
1027                                 next_vmk->nonce, BITLK_NONCE_SIZE, false);
1028                 if (r < 0) {
1029                         log_dbg(cd, "Failed to decrypt VMK using provided passphrase.");
1030                         crypt_free_volume_key(vmk_dec_key);
1031                         if (r == -ENOTSUP)
1032                                 return r;
1033                         next_vmk = next_vmk->next;
1034                         continue;
1035                 }
1036                 crypt_free_volume_key(vmk_dec_key);
1037
1038                 r = decrypt_key(cd, &open_fvek_key, params->fvek->vk, open_vmk_key,
1039                                 params->fvek->mac_tag, BITLK_VMK_MAC_TAG_SIZE,
1040                                 params->fvek->nonce, BITLK_NONCE_SIZE, true);
1041                 if (r < 0) {
1042                         log_dbg(cd, "Failed to decrypt FVEK using VMK.");
1043                         crypt_free_volume_key(open_vmk_key);
1044                         if (r == -ENOTSUP)
1045                                 return r;
1046                 } else {
1047                         crypt_free_volume_key(open_vmk_key);
1048                         break;
1049                 }
1050
1051                 next_vmk = next_vmk->next;
1052         }
1053
1054         if (r) {
1055                 log_dbg(cd, "No more VMKs to try.");
1056                 return r;
1057         }
1058
1059         /* Password verify only */
1060         if (!name) {
1061                 crypt_free_volume_key(open_fvek_key);
1062                 return r;
1063         }
1064
1065         next_vmk = params->vmks;
1066         while (next_vmk) {
1067                 if (next_vmk->protection == BITLK_PROTECTION_CLEAR_KEY) {
1068                         crypt_free_volume_key(open_fvek_key);
1069                         log_err(cd, _("Activation of partially decrypted BITLK device is not supported."));
1070                         return -ENOTSUP;
1071                 }
1072                 next_vmk = next_vmk->next;
1073         }
1074
1075         r = device_block_adjust(cd, crypt_data_device(cd), DEV_EXCL,
1076                                 0, &dmd.size, &dmd.flags);
1077         if (r) {
1078                 crypt_free_volume_key(open_fvek_key);
1079                 return r;
1080         }
1081
1082         /* there will be always 4 dm-zero segments: 3x metadata, 1x FS header */
1083         for (i = 0; i < 3; i++) {
1084                 segments[num_segments].offset = params->metadata_offset[i] / SECTOR_SIZE;
1085                 segments[num_segments].length = BITLK_FVE_METADATA_SIZE / SECTOR_SIZE;
1086                 segments[num_segments].iv_offset = 0;
1087                 segments[num_segments].type = BITLK_SEGTYPE_ZERO;
1088                 num_segments++;
1089         }
1090         segments[num_segments].offset = params->volume_header_offset / SECTOR_SIZE;
1091         segments[num_segments].length = params->volume_header_size / SECTOR_SIZE;
1092         segments[num_segments].iv_offset = 0;
1093         segments[num_segments].type = BITLK_SEGTYPE_ZERO;
1094         num_segments++;
1095
1096         /* filesystem header (moved from the special location) */
1097         segments[num_segments].offset = 0;
1098         segments[num_segments].length = params->volume_header_size / SECTOR_SIZE;
1099         segments[num_segments].iv_offset = params->volume_header_offset / SECTOR_SIZE;
1100         segments[num_segments].type = BITLK_SEGTYPE_CRYPT;
1101         num_segments++;
1102
1103         /* now fill gaps between the dm-zero segments with dm-crypt */
1104         last_segment = params->volume_header_size / SECTOR_SIZE;
1105         while (true) {
1106                 next_start = dmd.size;
1107                 next_end = dmd.size;
1108
1109                 /* start of the next segment: end of the first existing segment after the last added */
1110                 for (i = 0; i < num_segments; i++)
1111                         if (segments[i].offset + segments[i].length < next_start && segments[i].offset + segments[i].length >= last_segment)
1112                                 next_start = segments[i].offset + segments[i].length;
1113
1114                 /* end of the next segment: start of the next segment after start we found above */
1115                 for (i = 0; i < num_segments; i++)
1116                         if (segments[i].offset < next_end && segments[i].offset >= next_start)
1117                                 next_end = segments[i].offset;
1118
1119                 /* two zero segments next to each other, just bump the last_segment
1120                    so the algorithm moves */
1121                 if (next_end - next_start == 0) {
1122                         last_segment = next_end + 1;
1123                         continue;
1124                 }
1125
1126                 segments[num_segments].offset = next_start;
1127                 segments[num_segments].length = next_end - next_start;
1128                 segments[num_segments].iv_offset = next_start;
1129                 segments[num_segments].type = BITLK_SEGTYPE_CRYPT;
1130                 last_segment = next_end;
1131                 num_segments++;
1132
1133                 if (next_end == dmd.size)
1134                         break;
1135
1136                 if (num_segments == 10) {
1137                         log_dbg(cd, "Failed to calculate number of dm-crypt segments for open.");
1138                         r = -EINVAL;
1139                         goto out;
1140                 }
1141         }
1142
1143         /* device mapper needs the segment sorted */
1144         for (i = 0; i < num_segments - 1; i++) {
1145                 min = i;
1146                 for (j = i + 1; j < num_segments; j++)
1147                         if (segments[j].offset < segments[min].offset)
1148                                 min = j;
1149
1150                 if (min != i) {
1151                         temp.offset = segments[min].offset;
1152                         temp.length = segments[min].length;
1153                         temp.iv_offset = segments[min].iv_offset;
1154                         temp.type = segments[min].type;
1155
1156                         segments[min].offset = segments[i].offset;
1157                         segments[min].length = segments[i].length;
1158                         segments[min].iv_offset = segments[i].iv_offset;
1159                         segments[min].type = segments[i].type;
1160
1161                         segments[i].offset = temp.offset;
1162                         segments[i].length = temp.length;
1163                         segments[i].iv_offset = temp.iv_offset;
1164                         segments[i].type = temp.type;
1165                 }
1166         }
1167
1168         if (params->sector_size != SECTOR_SIZE)
1169                 dmd.flags |= CRYPT_ACTIVATE_IV_LARGE_SECTORS;
1170
1171         r = dm_targets_allocate(&dmd.segment, num_segments);
1172         if (r)
1173                 goto out;
1174         next_segment = &dmd.segment;
1175
1176         for (i = 0; i < num_segments; i++) {
1177                 if (segments[i].type == BITLK_SEGTYPE_ZERO)
1178                         r = dm_zero_target_set(next_segment,
1179                                                segments[i].offset,
1180                                                segments[i].length);
1181                 else if (segments[i].type == BITLK_SEGTYPE_CRYPT)
1182                         r = dm_crypt_target_set(next_segment,
1183                                                 segments[i].offset,
1184                                                 segments[i].length,
1185                                                 crypt_data_device(cd),
1186                                                 open_fvek_key,
1187                                                 crypt_get_cipher_spec(cd),
1188                                                 segments[i].iv_offset,
1189                                                 segments[i].iv_offset,
1190                                                 NULL, 0,
1191                                                 params->sector_size);
1192                 if (r)
1193                         goto out;
1194
1195                 next_segment = next_segment->next;
1196         }
1197
1198         log_dbg(cd, "Trying to activate BITLK on device %s%s%s.",
1199                 device_path(crypt_data_device(cd)), name ? " with name " :"", name ?: "");
1200
1201         r = dm_create_device(cd, name, CRYPT_BITLK, &dmd);
1202         if (r < 0) {
1203                 dm_flags(cd, DM_CRYPT, &dmt_flags);
1204                 if (!strcmp(params->cipher_mode, "cbc-eboiv") && !(dmt_flags & DM_BITLK_EBOIV_SUPPORTED)) {
1205                         log_err(cd, _("Cannot activate device, kernel dm-crypt is missing support for BITLK IV."));
1206                         r = -ENOTSUP;
1207                 }
1208                 if (!strcmp(params->cipher_mode, "cbc-elephant") && !(dmt_flags & DM_BITLK_ELEPHANT_SUPPORTED)) {
1209                         log_err(cd, _("Cannot activate device, kernel dm-crypt is missing support for BITLK Elephant diffuser."));
1210                         r = -ENOTSUP;
1211                 }
1212         }
1213 out:
1214         dm_targets_free(cd, &dmd);
1215         crypt_free_volume_key(open_fvek_key);
1216         return r;
1217 }