Imported Upstream version 2.6.1
[platform/upstream/cryptsetup.git] / lib / luks1 / keymanage.c
1 /*
2  * LUKS - Linux Unified Key Setup
3  *
4  * Copyright (C) 2004-2006 Clemens Fruhwirth <clemens@endorphin.org>
5  * Copyright (C) 2009-2023 Red Hat, Inc. All rights reserved.
6  * Copyright (C) 2013-2023 Milan Broz
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program 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
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  */
22
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <errno.h>
26 #include <unistd.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <ctype.h>
31 #include <uuid/uuid.h>
32 #include <limits.h>
33
34 #include "luks.h"
35 #include "af.h"
36 #include "internal.h"
37
38 int LUKS_keyslot_area(const struct luks_phdr *hdr,
39         int keyslot,
40         uint64_t *offset,
41         uint64_t *length)
42 {
43         if(keyslot >= LUKS_NUMKEYS || keyslot < 0)
44                 return -EINVAL;
45
46         *offset = (uint64_t)hdr->keyblock[keyslot].keyMaterialOffset * SECTOR_SIZE;
47         *length = AF_split_sectors(hdr->keyBytes, LUKS_STRIPES) * SECTOR_SIZE;
48
49         return 0;
50 }
51
52 /* insertsort: because the array has 8 elements and it's mostly sorted. that's why */
53 static void LUKS_sort_keyslots(const struct luks_phdr *hdr, int *array)
54 {
55         int i, j, x;
56
57         for (i = 1; i < LUKS_NUMKEYS; i++) {
58                 j = i;
59                 while (j > 0 && hdr->keyblock[array[j-1]].keyMaterialOffset > hdr->keyblock[array[j]].keyMaterialOffset) {
60                         x = array[j];
61                         array[j] = array[j-1];
62                         array[j-1] = x;
63                         j--;
64                 }
65         }
66 }
67
68 static int _is_not_lower(char *str, unsigned max_len)
69 {
70         for(; *str && max_len; str++, max_len--)
71                 if (isupper(*str))
72                         return 1;
73         return 0;
74 }
75
76 static int _to_lower(char *str, unsigned max_len)
77 {
78         int r = 0;
79
80         for(; *str && max_len; str++, max_len--)
81                 if (isupper(*str)) {
82                         *str = tolower(*str);
83                         r = 1;
84                 }
85
86         return r;
87 }
88
89 size_t LUKS_device_sectors(const struct luks_phdr *hdr)
90 {
91         int sorted_areas[LUKS_NUMKEYS] = { 0, 1, 2, 3, 4, 5, 6, 7 };
92
93         LUKS_sort_keyslots(hdr, sorted_areas);
94
95         return hdr->keyblock[sorted_areas[LUKS_NUMKEYS-1]].keyMaterialOffset + AF_split_sectors(hdr->keyBytes, LUKS_STRIPES);
96 }
97
98 size_t LUKS_keyslots_offset(const struct luks_phdr *hdr)
99 {
100         int sorted_areas[LUKS_NUMKEYS] = { 0, 1, 2, 3, 4, 5, 6, 7 };
101
102         LUKS_sort_keyslots(hdr, sorted_areas);
103
104         return hdr->keyblock[sorted_areas[0]].keyMaterialOffset;
105 }
106
107 static int LUKS_check_device_size(struct crypt_device *ctx, const struct luks_phdr *hdr, int falloc)
108 {
109         struct device *device = crypt_metadata_device(ctx);
110         uint64_t dev_sectors, hdr_sectors;
111
112         if (!hdr->keyBytes)
113                 return -EINVAL;
114
115         if (device_size(device, &dev_sectors)) {
116                 log_dbg(ctx, "Cannot get device size for device %s.", device_path(device));
117                 return -EIO;
118         }
119
120         dev_sectors >>= SECTOR_SHIFT;
121         hdr_sectors = LUKS_device_sectors(hdr);
122         log_dbg(ctx, "Key length %u, device size %" PRIu64 " sectors, header size %"
123                 PRIu64 " sectors.", hdr->keyBytes, dev_sectors, hdr_sectors);
124
125         if (hdr_sectors > dev_sectors) {
126                 /* If it is header file, increase its size */
127                 if (falloc && !device_fallocate(device, hdr_sectors << SECTOR_SHIFT))
128                         return 0;
129
130                 log_err(ctx, _("Device %s is too small. (LUKS1 requires at least %" PRIu64 " bytes.)"),
131                         device_path(device), hdr_sectors * SECTOR_SIZE);
132                 return -EINVAL;
133         }
134
135         return 0;
136 }
137
138 static int LUKS_check_keyslots(struct crypt_device *ctx, const struct luks_phdr *phdr)
139 {
140         int i, prev, next, sorted_areas[LUKS_NUMKEYS] = { 0, 1, 2, 3, 4, 5, 6, 7 };
141         uint32_t secs_per_stripes = AF_split_sectors(phdr->keyBytes, LUKS_STRIPES);
142
143         LUKS_sort_keyslots(phdr, sorted_areas);
144
145         /* Check keyslot to prevent access outside of header and keyslot area */
146         for (i = 0; i < LUKS_NUMKEYS; i++) {
147                 /* enforce stripes == 4000 */
148                 if (phdr->keyblock[i].stripes != LUKS_STRIPES) {
149                         log_dbg(ctx, "Invalid stripes count %u in keyslot %u.",
150                                 phdr->keyblock[i].stripes, i);
151                         log_err(ctx, _("LUKS keyslot %u is invalid."), i);
152                         return -1;
153                 }
154
155                 /* First sectors is the header itself */
156                 if (phdr->keyblock[i].keyMaterialOffset * SECTOR_SIZE < sizeof(*phdr)) {
157                         log_dbg(ctx, "Invalid offset %u in keyslot %u.",
158                                 phdr->keyblock[i].keyMaterialOffset, i);
159                         log_err(ctx, _("LUKS keyslot %u is invalid."), i);
160                         return -1;
161                 }
162
163                 /* Ignore following check for detached header where offset can be zero. */
164                 if (phdr->payloadOffset == 0)
165                         continue;
166
167                 if (phdr->payloadOffset <= phdr->keyblock[i].keyMaterialOffset) {
168                         log_dbg(ctx, "Invalid offset %u in keyslot %u (beyond data area offset %u).",
169                                 phdr->keyblock[i].keyMaterialOffset, i,
170                                 phdr->payloadOffset);
171                         log_err(ctx, _("LUKS keyslot %u is invalid."), i);
172                         return -1;
173                 }
174
175                 if (phdr->payloadOffset < (phdr->keyblock[i].keyMaterialOffset + secs_per_stripes)) {
176                         log_dbg(ctx, "Invalid keyslot size %u (offset %u, stripes %u) in "
177                                 "keyslot %u (beyond data area offset %u).",
178                                 secs_per_stripes,
179                                 phdr->keyblock[i].keyMaterialOffset,
180                                 phdr->keyblock[i].stripes,
181                                 i, phdr->payloadOffset);
182                         log_err(ctx, _("LUKS keyslot %u is invalid."), i);
183                         return -1;
184                 }
185         }
186
187         /* check no keyslot overlaps with each other */
188         for (i = 1; i < LUKS_NUMKEYS; i++) {
189                 prev = sorted_areas[i-1];
190                 next = sorted_areas[i];
191                 if (phdr->keyblock[next].keyMaterialOffset <
192                     (phdr->keyblock[prev].keyMaterialOffset + secs_per_stripes)) {
193                         log_dbg(ctx, "Not enough space in LUKS keyslot %d.", prev);
194                         log_err(ctx, _("LUKS keyslot %u is invalid."), prev);
195                         return -1;
196                 }
197         }
198         /* do not check last keyslot on purpose, it must be tested in device size check */
199
200         return 0;
201 }
202
203 static const char *dbg_slot_state(crypt_keyslot_info ki)
204 {
205         switch(ki) {
206         case CRYPT_SLOT_INACTIVE:
207                 return "INACTIVE";
208         case CRYPT_SLOT_ACTIVE:
209                 return "ACTIVE";
210         case CRYPT_SLOT_ACTIVE_LAST:
211                 return "ACTIVE_LAST";
212         case CRYPT_SLOT_INVALID:
213         default:
214                 return "INVALID";
215         }
216 }
217
218 int LUKS_hdr_backup(const char *backup_file, struct crypt_device *ctx)
219 {
220         struct device *device = crypt_metadata_device(ctx);
221         struct luks_phdr hdr;
222         int fd, devfd, r = 0;
223         size_t hdr_size;
224         size_t buffer_size;
225         ssize_t ret;
226         char *buffer = NULL;
227
228         r = LUKS_read_phdr(&hdr, 1, 0, ctx);
229         if (r)
230                 return r;
231
232         hdr_size = LUKS_device_sectors(&hdr) << SECTOR_SHIFT;
233         buffer_size = size_round_up(hdr_size, crypt_getpagesize());
234
235         buffer = malloc(buffer_size);
236         if (!buffer || hdr_size < LUKS_ALIGN_KEYSLOTS || hdr_size > buffer_size) {
237                 r = -ENOMEM;
238                 goto out;
239         }
240         memset(buffer, 0, buffer_size);
241
242         log_dbg(ctx, "Storing backup of header (%zu bytes) and keyslot area (%zu bytes).",
243                 sizeof(hdr), hdr_size - LUKS_ALIGN_KEYSLOTS);
244
245         log_dbg(ctx, "Output backup file size: %zu bytes.", buffer_size);
246
247         devfd = device_open(ctx, device, O_RDONLY);
248         if (devfd < 0) {
249                 log_err(ctx, _("Device %s is not a valid LUKS device."), device_path(device));
250                 r = -EINVAL;
251                 goto out;
252         }
253
254         if (read_lseek_blockwise(devfd, device_block_size(ctx, device), device_alignment(device),
255                            buffer, hdr_size, 0) < (ssize_t)hdr_size) {
256                 r = -EIO;
257                 goto out;
258         }
259
260         /* Wipe unused area, so backup cannot contain old signatures */
261         if (hdr.keyblock[0].keyMaterialOffset * SECTOR_SIZE == LUKS_ALIGN_KEYSLOTS)
262                 memset(buffer + sizeof(hdr), 0, LUKS_ALIGN_KEYSLOTS - sizeof(hdr));
263
264         fd = open(backup_file, O_CREAT|O_EXCL|O_WRONLY, S_IRUSR);
265         if (fd == -1) {
266                 if (errno == EEXIST)
267                         log_err(ctx, _("Requested header backup file %s already exists."), backup_file);
268                 else
269                         log_err(ctx, _("Cannot create header backup file %s."), backup_file);
270                 r = -EINVAL;
271                 goto out;
272         }
273         ret = write_buffer(fd, buffer, buffer_size);
274         close(fd);
275         if (ret < (ssize_t)buffer_size) {
276                 log_err(ctx, _("Cannot write header backup file %s."), backup_file);
277                 r = -EIO;
278                 goto out;
279         }
280
281         r = 0;
282 out:
283         crypt_safe_memzero(&hdr, sizeof(hdr));
284         crypt_safe_memzero(buffer, buffer_size);
285         free(buffer);
286         return r;
287 }
288
289 int LUKS_hdr_restore(
290         const char *backup_file,
291         struct luks_phdr *hdr,
292         struct crypt_device *ctx)
293 {
294         struct device *device = crypt_metadata_device(ctx);
295         int fd, r = 0, devfd = -1, diff_uuid = 0;
296         ssize_t ret, buffer_size = 0;
297         char *buffer = NULL, msg[200];
298         struct luks_phdr hdr_file;
299
300         r = LUKS_read_phdr_backup(backup_file, &hdr_file, 0, ctx);
301         if (r == -ENOENT)
302                 return r;
303
304         if (!r)
305                 buffer_size = LUKS_device_sectors(&hdr_file) << SECTOR_SHIFT;
306
307         if (r || buffer_size < LUKS_ALIGN_KEYSLOTS) {
308                 log_err(ctx, _("Backup file does not contain valid LUKS header."));
309                 r = -EINVAL;
310                 goto out;
311         }
312
313         buffer = malloc(buffer_size);
314         if (!buffer) {
315                 r = -ENOMEM;
316                 goto out;
317         }
318
319         fd = open(backup_file, O_RDONLY);
320         if (fd == -1) {
321                 log_err(ctx, _("Cannot open header backup file %s."), backup_file);
322                 r = -EINVAL;
323                 goto out;
324         }
325
326         ret = read_buffer(fd, buffer, buffer_size);
327         close(fd);
328         if (ret < buffer_size) {
329                 log_err(ctx, _("Cannot read header backup file %s."), backup_file);
330                 r = -EIO;
331                 goto out;
332         }
333
334         r = LUKS_read_phdr(hdr, 0, 0, ctx);
335         if (r == 0) {
336                 log_dbg(ctx, "Device %s already contains LUKS header, checking UUID and offset.", device_path(device));
337                 if(hdr->payloadOffset != hdr_file.payloadOffset ||
338                    hdr->keyBytes != hdr_file.keyBytes) {
339                         log_err(ctx, _("Data offset or key size differs on device and backup, restore failed."));
340                         r = -EINVAL;
341                         goto out;
342                 }
343                 if (memcmp(hdr->uuid, hdr_file.uuid, UUID_STRING_L))
344                         diff_uuid = 1;
345         }
346
347         if (snprintf(msg, sizeof(msg), _("Device %s %s%s"), device_path(device),
348                  r ? _("does not contain LUKS header. Replacing header can destroy data on that device.") :
349                      _("already contains LUKS header. Replacing header will destroy existing keyslots."),
350                      diff_uuid ? _("\nWARNING: real device header has different UUID than backup!") : "") < 0) {
351                 r = -ENOMEM;
352                 goto out;
353         }
354
355         if (!crypt_confirm(ctx, msg)) {
356                 r = -EINVAL;
357                 goto out;
358         }
359
360         log_dbg(ctx, "Storing backup of header (%zu bytes) and keyslot area (%zu bytes) to device %s.",
361                 sizeof(*hdr), buffer_size - LUKS_ALIGN_KEYSLOTS, device_path(device));
362
363         devfd = device_open(ctx, device, O_RDWR);
364         if (devfd < 0) {
365                 if (errno == EACCES)
366                         log_err(ctx, _("Cannot write to device %s, permission denied."),
367                                 device_path(device));
368                 else
369                         log_err(ctx, _("Cannot open device %s."), device_path(device));
370                 r = -EINVAL;
371                 goto out;
372         }
373
374         if (write_lseek_blockwise(devfd, device_block_size(ctx, device), device_alignment(device),
375                             buffer, buffer_size, 0) < buffer_size) {
376                 r = -EIO;
377                 goto out;
378         }
379
380         /* Be sure to reload new data */
381         r = LUKS_read_phdr(hdr, 1, 0, ctx);
382 out:
383         device_sync(ctx, device);
384         crypt_safe_memzero(buffer, buffer_size);
385         free(buffer);
386         return r;
387 }
388
389 /* This routine should do some just basic recovery for known problems. */
390 static int _keyslot_repair(struct luks_phdr *phdr, struct crypt_device *ctx)
391 {
392         struct luks_phdr temp_phdr;
393         const unsigned char *sector = (const unsigned char*)phdr;
394         struct volume_key *vk;
395         int i, bad, r, need_write = 0;
396
397         if (phdr->keyBytes != 16 && phdr->keyBytes != 32 && phdr->keyBytes != 64) {
398                 log_err(ctx, _("Non standard key size, manual repair required."));
399                 return -EINVAL;
400         }
401
402         /*
403          * cryptsetup 1.0 did not align keyslots to 4k, cannot repair this one
404          * Also we cannot trust possibly broken keyslots metadata here through LUKS_keyslots_offset().
405          * Expect first keyslot is aligned, if not, then manual repair is necessary.
406          */
407         if (phdr->keyblock[0].keyMaterialOffset < (LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE)) {
408                 log_err(ctx, _("Non standard keyslots alignment, manual repair required."));
409                 return -EINVAL;
410         }
411
412         /*
413          * ECB mode does not use IV but legacy dmcrypt silently allows it.
414          * Today device cannot be activated anyway, so we need to fix it here.
415          */
416         if (!strncmp(phdr->cipherMode, "ecb-", 4)) {
417                 log_err(ctx, _("Cipher mode repaired (%s -> %s)."), phdr->cipherMode, "ecb");
418                 memset(phdr->cipherMode, 0, LUKS_CIPHERMODE_L);
419                 strcpy(phdr->cipherMode, "ecb");
420                 need_write = 1;
421         }
422
423         /*
424          * Old cryptsetup expects "sha1", gcrypt allows case insensitive names,
425          * so always convert hash to lower case in header
426          */
427         if (_to_lower(phdr->hashSpec, LUKS_HASHSPEC_L)) {
428                 log_err(ctx, _("Cipher hash repaired to lowercase (%s)."), phdr->hashSpec);
429                 if (crypt_hmac_size(phdr->hashSpec) < LUKS_DIGESTSIZE) {
430                         log_err(ctx, _("Requested LUKS hash %s is not supported."), phdr->hashSpec);
431                         return -EINVAL;
432                 }
433                 need_write = 1;
434         }
435
436         r = LUKS_check_cipher(ctx, phdr->keyBytes, phdr->cipherName, phdr->cipherMode);
437         if (r < 0)
438                 return -EINVAL;
439
440         vk = crypt_alloc_volume_key(phdr->keyBytes, NULL);
441         if (!vk)
442                 return -ENOMEM;
443
444         log_verbose(ctx, _("Repairing keyslots."));
445
446         log_dbg(ctx, "Generating second header with the same parameters for check.");
447         /* cipherName, cipherMode, hashSpec, uuid are already null terminated */
448         /* payloadOffset - cannot check */
449         r = LUKS_generate_phdr(&temp_phdr, vk, phdr->cipherName, phdr->cipherMode,
450                                phdr->hashSpec, phdr->uuid,
451                                phdr->payloadOffset * SECTOR_SIZE, 0, 0, ctx);
452         if (r < 0)
453                 goto out;
454
455         for(i = 0; i < LUKS_NUMKEYS; ++i) {
456                 if (phdr->keyblock[i].active == LUKS_KEY_ENABLED)  {
457                         log_dbg(ctx, "Skipping repair for active keyslot %i.", i);
458                         continue;
459                 }
460
461                 bad = 0;
462                 if (phdr->keyblock[i].keyMaterialOffset != temp_phdr.keyblock[i].keyMaterialOffset) {
463                         log_err(ctx, _("Keyslot %i: offset repaired (%u -> %u)."), i,
464                                 (unsigned)phdr->keyblock[i].keyMaterialOffset,
465                                 (unsigned)temp_phdr.keyblock[i].keyMaterialOffset);
466                         phdr->keyblock[i].keyMaterialOffset = temp_phdr.keyblock[i].keyMaterialOffset;
467                         bad = 1;
468                 }
469
470                 if (phdr->keyblock[i].stripes != temp_phdr.keyblock[i].stripes) {
471                         log_err(ctx, _("Keyslot %i: stripes repaired (%u -> %u)."), i,
472                                 (unsigned)phdr->keyblock[i].stripes,
473                                 (unsigned)temp_phdr.keyblock[i].stripes);
474                         phdr->keyblock[i].stripes = temp_phdr.keyblock[i].stripes;
475                         bad = 1;
476                 }
477
478                 /* Known case - MSDOS partition table signature */
479                 if (i == 6 && sector[0x1fe] == 0x55 && sector[0x1ff] == 0xaa) {
480                         log_err(ctx, _("Keyslot %i: bogus partition signature."), i);
481                         bad = 1;
482                 }
483
484                 if(bad) {
485                         log_err(ctx, _("Keyslot %i: salt wiped."), i);
486                         phdr->keyblock[i].active = LUKS_KEY_DISABLED;
487                         memset(&phdr->keyblock[i].passwordSalt, 0x00, LUKS_SALTSIZE);
488                         phdr->keyblock[i].passwordIterations = 0;
489                 }
490
491                 if (bad)
492                         need_write = 1;
493         }
494
495         /*
496          * check repair result before writing because repair can't fix out of order
497          * keyslot offsets and would corrupt header again
498          */
499         if (LUKS_check_keyslots(ctx, phdr))
500                 r = -EINVAL;
501         else if (need_write) {
502                 log_verbose(ctx, _("Writing LUKS header to disk."));
503                 r = LUKS_write_phdr(phdr, ctx);
504         }
505 out:
506         if (r)
507                 log_err(ctx, _("Repair failed."));
508         crypt_free_volume_key(vk);
509         crypt_safe_memzero(&temp_phdr, sizeof(temp_phdr));
510         return r;
511 }
512
513 static int _check_and_convert_hdr(const char *device,
514                                   struct luks_phdr *hdr,
515                                   int require_luks_device,
516                                   int repair,
517                                   struct crypt_device *ctx)
518 {
519         int r = 0;
520         unsigned int i;
521         char luksMagic[] = LUKS_MAGIC;
522
523         hdr->version = be16_to_cpu(hdr->version);
524         if (memcmp(hdr->magic, luksMagic, LUKS_MAGIC_L)) { /* Check magic */
525                 log_dbg(ctx, "LUKS header not detected.");
526                 if (require_luks_device)
527                         log_err(ctx, _("Device %s is not a valid LUKS device."), device);
528                 return -EINVAL;
529         } else if (hdr->version != 1) {
530                 log_err(ctx, _("Unsupported LUKS version %d."), hdr->version);
531                 return -EINVAL;
532         }
533
534         hdr->hashSpec[LUKS_HASHSPEC_L - 1] = '\0';
535         if (crypt_hmac_size(hdr->hashSpec) < LUKS_DIGESTSIZE) {
536                 log_err(ctx, _("Requested LUKS hash %s is not supported."), hdr->hashSpec);
537                 r = -EINVAL;
538         }
539
540         /* Header detected */
541         hdr->payloadOffset      = be32_to_cpu(hdr->payloadOffset);
542         hdr->keyBytes           = be32_to_cpu(hdr->keyBytes);
543         hdr->mkDigestIterations = be32_to_cpu(hdr->mkDigestIterations);
544
545         for (i = 0; i < LUKS_NUMKEYS; ++i) {
546                 hdr->keyblock[i].active             = be32_to_cpu(hdr->keyblock[i].active);
547                 hdr->keyblock[i].passwordIterations = be32_to_cpu(hdr->keyblock[i].passwordIterations);
548                 hdr->keyblock[i].keyMaterialOffset  = be32_to_cpu(hdr->keyblock[i].keyMaterialOffset);
549                 hdr->keyblock[i].stripes            = be32_to_cpu(hdr->keyblock[i].stripes);
550         }
551
552         if (LUKS_check_keyslots(ctx, hdr))
553                 r = -EINVAL;
554
555         /* Avoid unterminated strings */
556         hdr->cipherName[LUKS_CIPHERNAME_L - 1] = '\0';
557         hdr->cipherMode[LUKS_CIPHERMODE_L - 1] = '\0';
558         hdr->uuid[UUID_STRING_L - 1] = '\0';
559
560         if (repair) {
561                 if (!strncmp(hdr->cipherMode, "ecb-", 4)) {
562                         log_err(ctx, _("LUKS cipher mode %s is invalid."), hdr->cipherMode);
563                         r = -EINVAL;
564                 }
565
566                 if (_is_not_lower(hdr->hashSpec, LUKS_HASHSPEC_L)) {
567                         log_err(ctx, _("LUKS hash %s is invalid."), hdr->hashSpec);
568                         r = -EINVAL;
569                 }
570
571                 if (r == -EINVAL)
572                         r = _keyslot_repair(hdr, ctx);
573                 else
574                         log_verbose(ctx, _("No known problems detected for LUKS header."));
575         }
576
577         return r;
578 }
579
580 int LUKS_read_phdr_backup(const char *backup_file,
581                           struct luks_phdr *hdr,
582                           int require_luks_device,
583                           struct crypt_device *ctx)
584 {
585         ssize_t hdr_size = sizeof(struct luks_phdr);
586         int devfd = 0, r = 0;
587
588         log_dbg(ctx, "Reading LUKS header of size %d from backup file %s",
589                 (int)hdr_size, backup_file);
590
591         devfd = open(backup_file, O_RDONLY);
592         if (devfd == -1) {
593                 log_err(ctx, _("Cannot open header backup file %s."), backup_file);
594                 return -ENOENT;
595         }
596
597         if (read_buffer(devfd, hdr, hdr_size) < hdr_size)
598                 r = -EIO;
599         else
600                 r = _check_and_convert_hdr(backup_file, hdr,
601                                            require_luks_device, 0, ctx);
602
603         close(devfd);
604         return r;
605 }
606
607 int LUKS_read_phdr(struct luks_phdr *hdr,
608                    int require_luks_device,
609                    int repair,
610                    struct crypt_device *ctx)
611 {
612         int devfd, r = 0;
613         struct device *device = crypt_metadata_device(ctx);
614         ssize_t hdr_size = sizeof(struct luks_phdr);
615
616         /* LUKS header starts at offset 0, first keyslot on LUKS_ALIGN_KEYSLOTS */
617         assert(sizeof(struct luks_phdr) <= LUKS_ALIGN_KEYSLOTS);
618
619         /* Stripes count cannot be changed without additional code fixes yet */
620         assert(LUKS_STRIPES == 4000);
621
622         if (repair && !require_luks_device)
623                 return -EINVAL;
624
625         log_dbg(ctx, "Reading LUKS header of size %zu from device %s",
626                 hdr_size, device_path(device));
627
628         devfd = device_open(ctx, device, O_RDONLY);
629         if (devfd < 0) {
630                 log_err(ctx, _("Cannot open device %s."), device_path(device));
631                 return -EINVAL;
632         }
633
634         if (read_lseek_blockwise(devfd, device_block_size(ctx, device), device_alignment(device),
635                            hdr, hdr_size, 0) < hdr_size)
636                 r = -EIO;
637         else
638                 r = _check_and_convert_hdr(device_path(device), hdr, require_luks_device,
639                                            repair, ctx);
640
641         if (!r)
642                 r = LUKS_check_device_size(ctx, hdr, 0);
643
644         /*
645          * Cryptsetup 1.0.0 did not align keyslots to 4k (very rare version).
646          * Disable direct-io to avoid possible IO errors if underlying device
647          * has bigger sector size.
648          */
649         if (!r && hdr->keyblock[0].keyMaterialOffset * SECTOR_SIZE < LUKS_ALIGN_KEYSLOTS) {
650                 log_dbg(ctx, "Old unaligned LUKS keyslot detected, disabling direct-io.");
651                 device_disable_direct_io(device);
652         }
653
654         return r;
655 }
656
657 int LUKS_write_phdr(struct luks_phdr *hdr,
658                     struct crypt_device *ctx)
659 {
660         struct device *device = crypt_metadata_device(ctx);
661         ssize_t hdr_size = sizeof(struct luks_phdr);
662         int devfd = 0;
663         unsigned int i;
664         struct luks_phdr convHdr;
665         int r;
666
667         log_dbg(ctx, "Updating LUKS header of size %zu on device %s",
668                 sizeof(struct luks_phdr), device_path(device));
669
670         r = LUKS_check_device_size(ctx, hdr, 1);
671         if (r)
672                 return r;
673
674         devfd = device_open(ctx, device, O_RDWR);
675         if (devfd < 0) {
676                 if (errno == EACCES)
677                         log_err(ctx, _("Cannot write to device %s, permission denied."),
678                                 device_path(device));
679                 else
680                         log_err(ctx, _("Cannot open device %s."), device_path(device));
681                 return -EINVAL;
682         }
683
684         memcpy(&convHdr, hdr, hdr_size);
685         memset(&convHdr._padding, 0, sizeof(convHdr._padding));
686
687         /* Convert every uint16/32_t item to network byte order */
688         convHdr.version            = cpu_to_be16(hdr->version);
689         convHdr.payloadOffset      = cpu_to_be32(hdr->payloadOffset);
690         convHdr.keyBytes           = cpu_to_be32(hdr->keyBytes);
691         convHdr.mkDigestIterations = cpu_to_be32(hdr->mkDigestIterations);
692         for(i = 0; i < LUKS_NUMKEYS; ++i) {
693                 convHdr.keyblock[i].active             = cpu_to_be32(hdr->keyblock[i].active);
694                 convHdr.keyblock[i].passwordIterations = cpu_to_be32(hdr->keyblock[i].passwordIterations);
695                 convHdr.keyblock[i].keyMaterialOffset  = cpu_to_be32(hdr->keyblock[i].keyMaterialOffset);
696                 convHdr.keyblock[i].stripes            = cpu_to_be32(hdr->keyblock[i].stripes);
697         }
698
699         r = write_lseek_blockwise(devfd, device_block_size(ctx, device), device_alignment(device),
700                             &convHdr, hdr_size, 0) < hdr_size ? -EIO : 0;
701         if (r)
702                 log_err(ctx, _("Error during update of LUKS header on device %s."), device_path(device));
703
704         device_sync(ctx, device);
705
706         /* Re-read header from disk to be sure that in-memory and on-disk data are the same. */
707         if (!r) {
708                 r = LUKS_read_phdr(hdr, 1, 0, ctx);
709                 if (r)
710                         log_err(ctx, _("Error re-reading LUKS header after update on device %s."),
711                                 device_path(device));
712         }
713
714         return r;
715 }
716
717 /* Check that kernel supports requested cipher by decryption of one sector */
718 int LUKS_check_cipher(struct crypt_device *ctx, size_t keylength, const char *cipher, const char *cipher_mode)
719 {
720         int r;
721         struct volume_key *empty_key;
722         char buf[SECTOR_SIZE];
723
724         log_dbg(ctx, "Checking if cipher %s-%s is usable.", cipher, cipher_mode);
725
726         empty_key = crypt_alloc_volume_key(keylength, NULL);
727         if (!empty_key)
728                 return -ENOMEM;
729
730         /* No need to get KEY quality random but it must avoid known weak keys. */
731         r = crypt_random_get(ctx, empty_key->key, empty_key->keylength, CRYPT_RND_NORMAL);
732         if (!r)
733                 r = LUKS_decrypt_from_storage(buf, sizeof(buf), cipher, cipher_mode, empty_key, 0, ctx);
734
735         crypt_free_volume_key(empty_key);
736         crypt_safe_memzero(buf, sizeof(buf));
737         return r;
738 }
739
740 int LUKS_generate_phdr(struct luks_phdr *header,
741         const struct volume_key *vk,
742         const char *cipherName,
743         const char *cipherMode,
744         const char *hashSpec,
745         const char *uuid,
746         uint64_t data_offset,        /* in bytes */
747         uint64_t align_offset,       /* in bytes */
748         uint64_t required_alignment, /* in bytes */
749         struct crypt_device *ctx)
750 {
751         int i, r;
752         size_t keyslot_sectors, header_sectors;
753         uuid_t partitionUuid;
754         struct crypt_pbkdf_type *pbkdf;
755         double PBKDF2_temp;
756         char luksMagic[] = LUKS_MAGIC;
757
758         if (data_offset % SECTOR_SIZE || align_offset % SECTOR_SIZE ||
759             required_alignment % SECTOR_SIZE)
760                 return -EINVAL;
761
762         memset(header, 0, sizeof(struct luks_phdr));
763
764         keyslot_sectors = AF_split_sectors(vk->keylength, LUKS_STRIPES);
765         header_sectors = LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE;
766
767         for (i = 0; i < LUKS_NUMKEYS; i++) {
768                 header->keyblock[i].active = LUKS_KEY_DISABLED;
769                 header->keyblock[i].keyMaterialOffset = header_sectors;
770                 header->keyblock[i].stripes = LUKS_STRIPES;
771                 header_sectors = size_round_up(header_sectors + keyslot_sectors,
772                                                LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);
773         }
774         /* In sector is now size of all keyslot material space */
775
776         /* Data offset has priority */
777         if (data_offset)
778                 header->payloadOffset = data_offset / SECTOR_SIZE;
779         else if (required_alignment) {
780                 header->payloadOffset = size_round_up(header_sectors, (required_alignment / SECTOR_SIZE));
781                 header->payloadOffset += (align_offset / SECTOR_SIZE);
782         } else
783                 header->payloadOffset = 0;
784
785         if (header->payloadOffset && header->payloadOffset < header_sectors) {
786                 log_err(ctx, _("Data offset for LUKS header must be "
787                                "either 0 or higher than header size."));
788                 return -EINVAL;
789         }
790
791         if (crypt_hmac_size(hashSpec) < LUKS_DIGESTSIZE) {
792                 log_err(ctx, _("Requested LUKS hash %s is not supported."), hashSpec);
793                 return -EINVAL;
794         }
795
796         if (uuid && uuid_parse(uuid, partitionUuid) == -1) {
797                 log_err(ctx, _("Wrong LUKS UUID format provided."));
798                 return -EINVAL;
799         }
800         if (!uuid)
801                 uuid_generate(partitionUuid);
802
803         /* Set Magic */
804         memcpy(header->magic,luksMagic,LUKS_MAGIC_L);
805         header->version=1;
806         strncpy(header->cipherName,cipherName,LUKS_CIPHERNAME_L-1);
807         strncpy(header->cipherMode,cipherMode,LUKS_CIPHERMODE_L-1);
808         strncpy(header->hashSpec,hashSpec,LUKS_HASHSPEC_L-1);
809         _to_lower(header->hashSpec, LUKS_HASHSPEC_L);
810
811         header->keyBytes=vk->keylength;
812
813         log_dbg(ctx, "Generating LUKS header version %d using hash %s, %s, %s, MK %d bytes",
814                 header->version, header->hashSpec ,header->cipherName, header->cipherMode,
815                 header->keyBytes);
816
817         r = crypt_random_get(ctx, header->mkDigestSalt, LUKS_SALTSIZE, CRYPT_RND_SALT);
818         if(r < 0) {
819                 log_err(ctx, _("Cannot create LUKS header: reading random salt failed."));
820                 return r;
821         }
822
823         /* Compute volume key digest */
824         pbkdf = crypt_get_pbkdf(ctx);
825         r = crypt_benchmark_pbkdf_internal(ctx, pbkdf, vk->keylength);
826         if (r < 0)
827                 return r;
828         assert(pbkdf->iterations);
829
830         if (pbkdf->flags & CRYPT_PBKDF_NO_BENCHMARK && pbkdf->time_ms == 0)
831                 PBKDF2_temp = LUKS_MKD_ITERATIONS_MIN;
832         else    /* iterations per ms * LUKS_MKD_ITERATIONS_MS */
833                 PBKDF2_temp = (double)pbkdf->iterations * LUKS_MKD_ITERATIONS_MS / pbkdf->time_ms;
834
835         if (PBKDF2_temp > (double)UINT32_MAX)
836                 return -EINVAL;
837         header->mkDigestIterations = AT_LEAST((uint32_t)PBKDF2_temp, LUKS_MKD_ITERATIONS_MIN);
838         assert(header->mkDigestIterations);
839
840         r = crypt_pbkdf(CRYPT_KDF_PBKDF2, header->hashSpec, vk->key,vk->keylength,
841                         header->mkDigestSalt, LUKS_SALTSIZE,
842                         header->mkDigest,LUKS_DIGESTSIZE,
843                         header->mkDigestIterations, 0, 0);
844         if (r < 0) {
845                 log_err(ctx, _("Cannot create LUKS header: header digest failed (using hash %s)."),
846                         header->hashSpec);
847                 return r;
848         }
849
850         uuid_unparse(partitionUuid, header->uuid);
851
852         log_dbg(ctx, "Data offset %d, UUID %s, digest iterations %" PRIu32,
853                 header->payloadOffset, header->uuid, header->mkDigestIterations);
854
855         return 0;
856 }
857
858 int LUKS_hdr_uuid_set(
859         struct luks_phdr *hdr,
860         const char *uuid,
861         struct crypt_device *ctx)
862 {
863         uuid_t partitionUuid;
864
865         if (uuid && uuid_parse(uuid, partitionUuid) == -1) {
866                 log_err(ctx, _("Wrong LUKS UUID format provided."));
867                 return -EINVAL;
868         }
869         if (!uuid)
870                 uuid_generate(partitionUuid);
871
872         uuid_unparse(partitionUuid, hdr->uuid);
873
874         return LUKS_write_phdr(hdr, ctx);
875 }
876
877 int LUKS_set_key(unsigned int keyIndex,
878                  const char *password, size_t passwordLen,
879                  struct luks_phdr *hdr, struct volume_key *vk,
880                  struct crypt_device *ctx)
881 {
882         struct volume_key *derived_key;
883         char *AfKey = NULL;
884         size_t AFEKSize;
885         struct crypt_pbkdf_type *pbkdf;
886         int r;
887
888         if(hdr->keyblock[keyIndex].active != LUKS_KEY_DISABLED) {
889                 log_err(ctx, _("Key slot %d active, purge first."), keyIndex);
890                 return -EINVAL;
891         }
892
893         /* LUKS keyslot has always at least 4000 stripes according to specification */
894         if(hdr->keyblock[keyIndex].stripes < 4000) {
895                 log_err(ctx, _("Key slot %d material includes too few stripes. Header manipulation?"),
896                         keyIndex);
897                  return -EINVAL;
898         }
899
900         log_dbg(ctx, "Calculating data for key slot %d", keyIndex);
901         pbkdf = crypt_get_pbkdf(ctx);
902         r = crypt_benchmark_pbkdf_internal(ctx, pbkdf, vk->keylength);
903         if (r < 0)
904                 return r;
905         assert(pbkdf->iterations);
906
907         /*
908          * Final iteration count is at least LUKS_SLOT_ITERATIONS_MIN
909          */
910         hdr->keyblock[keyIndex].passwordIterations =
911                 AT_LEAST(pbkdf->iterations, LUKS_SLOT_ITERATIONS_MIN);
912         log_dbg(ctx, "Key slot %d use %" PRIu32 " password iterations.", keyIndex,
913                 hdr->keyblock[keyIndex].passwordIterations);
914
915         derived_key = crypt_alloc_volume_key(hdr->keyBytes, NULL);
916         if (!derived_key)
917                 return -ENOMEM;
918
919         r = crypt_random_get(ctx, hdr->keyblock[keyIndex].passwordSalt,
920                        LUKS_SALTSIZE, CRYPT_RND_SALT);
921         if (r < 0)
922                 goto out;
923
924         r = crypt_pbkdf(CRYPT_KDF_PBKDF2, hdr->hashSpec, password, passwordLen,
925                         hdr->keyblock[keyIndex].passwordSalt, LUKS_SALTSIZE,
926                         derived_key->key, hdr->keyBytes,
927                         hdr->keyblock[keyIndex].passwordIterations, 0, 0);
928         if (r < 0) {
929                 if ((crypt_backend_flags() & CRYPT_BACKEND_PBKDF2_INT) &&
930                      hdr->keyblock[keyIndex].passwordIterations > INT_MAX)
931                         log_err(ctx, _("PBKDF2 iteration value overflow."));
932                 goto out;
933         }
934
935         /*
936          * AF splitting, the volume key stored in vk->key is split to AfKey
937          */
938         assert(vk->keylength == hdr->keyBytes);
939         AFEKSize = AF_split_sectors(vk->keylength, hdr->keyblock[keyIndex].stripes) * SECTOR_SIZE;
940         AfKey = crypt_safe_alloc(AFEKSize);
941         if (!AfKey) {
942                 r = -ENOMEM;
943                 goto out;
944         }
945
946         log_dbg(ctx, "Using hash %s for AF in key slot %d, %d stripes",
947                 hdr->hashSpec, keyIndex, hdr->keyblock[keyIndex].stripes);
948         r = AF_split(ctx, vk->key, AfKey, vk->keylength, hdr->keyblock[keyIndex].stripes, hdr->hashSpec);
949         if (r < 0)
950                 goto out;
951
952         log_dbg(ctx, "Updating key slot %d [0x%04x] area.", keyIndex,
953                 hdr->keyblock[keyIndex].keyMaterialOffset << 9);
954         /* Encryption via dm */
955         r = LUKS_encrypt_to_storage(AfKey,
956                                     AFEKSize,
957                                     hdr->cipherName, hdr->cipherMode,
958                                     derived_key,
959                                     hdr->keyblock[keyIndex].keyMaterialOffset,
960                                     ctx);
961         if (r < 0)
962                 goto out;
963
964         /* Mark the key as active in phdr */
965         r = LUKS_keyslot_set(hdr, (int)keyIndex, 1, ctx);
966         if (r < 0)
967                 goto out;
968
969         r = LUKS_write_phdr(hdr, ctx);
970         if (r < 0)
971                 goto out;
972
973         r = 0;
974 out:
975         crypt_safe_free(AfKey);
976         crypt_free_volume_key(derived_key);
977         return r;
978 }
979
980 /* Check whether a volume key is invalid. */
981 int LUKS_verify_volume_key(const struct luks_phdr *hdr,
982                            const struct volume_key *vk)
983 {
984         char checkHashBuf[LUKS_DIGESTSIZE];
985
986         if (crypt_pbkdf(CRYPT_KDF_PBKDF2, hdr->hashSpec, vk->key, vk->keylength,
987                         hdr->mkDigestSalt, LUKS_SALTSIZE,
988                         checkHashBuf, LUKS_DIGESTSIZE,
989                         hdr->mkDigestIterations, 0, 0) < 0)
990                 return -EINVAL;
991
992         if (crypt_backend_memeq(checkHashBuf, hdr->mkDigest, LUKS_DIGESTSIZE))
993                 return -EPERM;
994
995         return 0;
996 }
997
998 /* Try to open a particular key slot */
999 static int LUKS_open_key(unsigned int keyIndex,
1000                   const char *password,
1001                   size_t passwordLen,
1002                   struct luks_phdr *hdr,
1003                   struct volume_key **vk,
1004                   struct crypt_device *ctx)
1005 {
1006         crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyIndex);
1007         struct volume_key *derived_key;
1008         char *AfKey = NULL;
1009         size_t AFEKSize;
1010         int r;
1011
1012         log_dbg(ctx, "Trying to open key slot %d [%s].", keyIndex,
1013                 dbg_slot_state(ki));
1014
1015         if (ki < CRYPT_SLOT_ACTIVE)
1016                 return -ENOENT;
1017
1018         derived_key = crypt_alloc_volume_key(hdr->keyBytes, NULL);
1019         if (!derived_key)
1020                 return -ENOMEM;
1021
1022         *vk = crypt_alloc_volume_key(hdr->keyBytes, NULL);
1023         if (!*vk) {
1024                 r = -ENOMEM;
1025                 goto out;
1026         }
1027
1028         AFEKSize = AF_split_sectors(hdr->keyBytes, hdr->keyblock[keyIndex].stripes) * SECTOR_SIZE;
1029         AfKey = crypt_safe_alloc(AFEKSize);
1030         if (!AfKey) {
1031                 r = -ENOMEM;
1032                 goto out;
1033         }
1034
1035         r = crypt_pbkdf(CRYPT_KDF_PBKDF2, hdr->hashSpec, password, passwordLen,
1036                         hdr->keyblock[keyIndex].passwordSalt, LUKS_SALTSIZE,
1037                         derived_key->key, hdr->keyBytes,
1038                         hdr->keyblock[keyIndex].passwordIterations, 0, 0);
1039         if (r < 0) {
1040                 log_err(ctx, _("Cannot open keyslot (using hash %s)."), hdr->hashSpec);
1041                 goto out;
1042         }
1043
1044         log_dbg(ctx, "Reading key slot %d area.", keyIndex);
1045         r = LUKS_decrypt_from_storage(AfKey,
1046                                       AFEKSize,
1047                                       hdr->cipherName, hdr->cipherMode,
1048                                       derived_key,
1049                                       hdr->keyblock[keyIndex].keyMaterialOffset,
1050                                       ctx);
1051         if (r < 0)
1052                 goto out;
1053
1054         r = AF_merge(AfKey, (*vk)->key, (*vk)->keylength, hdr->keyblock[keyIndex].stripes, hdr->hashSpec);
1055         if (r < 0)
1056                 goto out;
1057
1058         r = LUKS_verify_volume_key(hdr, *vk);
1059
1060         /* Allow only empty passphrase with null cipher */
1061         if (!r && crypt_is_cipher_null(hdr->cipherName) && passwordLen)
1062                 r = -EPERM;
1063 out:
1064         if (r < 0) {
1065                 crypt_free_volume_key(*vk);
1066                 *vk = NULL;
1067         }
1068         crypt_safe_free(AfKey);
1069         crypt_free_volume_key(derived_key);
1070         return r;
1071 }
1072
1073 int LUKS_open_key_with_hdr(int keyIndex,
1074                            const char *password,
1075                            size_t passwordLen,
1076                            struct luks_phdr *hdr,
1077                            struct volume_key **vk,
1078                            struct crypt_device *ctx)
1079 {
1080         unsigned int i, tried = 0;
1081         int r;
1082
1083         if (keyIndex >= 0) {
1084                 r = LUKS_open_key(keyIndex, password, passwordLen, hdr, vk, ctx);
1085                 return (r < 0) ? r : keyIndex;
1086         }
1087
1088         for (i = 0; i < LUKS_NUMKEYS; i++) {
1089                 r = LUKS_open_key(i, password, passwordLen, hdr, vk, ctx);
1090                 if (r == 0)
1091                         return i;
1092
1093                 /* Do not retry for errors that are no -EPERM or -ENOENT,
1094                    former meaning password wrong, latter key slot inactive */
1095                 if ((r != -EPERM) && (r != -ENOENT))
1096                         return r;
1097                 if (r == -EPERM)
1098                         tried++;
1099         }
1100         /* Warning, early returns above */
1101         return tried ? -EPERM : -ENOENT;
1102 }
1103
1104 int LUKS_del_key(unsigned int keyIndex,
1105                  struct luks_phdr *hdr,
1106                  struct crypt_device *ctx)
1107 {
1108         struct device *device = crypt_metadata_device(ctx);
1109         unsigned int startOffset, endOffset;
1110         int r;
1111
1112         r = LUKS_read_phdr(hdr, 1, 0, ctx);
1113         if (r)
1114                 return r;
1115
1116         r = LUKS_keyslot_set(hdr, keyIndex, 0, ctx);
1117         if (r) {
1118                 log_err(ctx, _("Key slot %d is invalid, please select keyslot between 0 and %d."),
1119                         keyIndex, LUKS_NUMKEYS - 1);
1120                 return r;
1121         }
1122
1123         /* secure deletion of key material */
1124         startOffset = hdr->keyblock[keyIndex].keyMaterialOffset;
1125         endOffset = startOffset + AF_split_sectors(hdr->keyBytes, hdr->keyblock[keyIndex].stripes);
1126
1127         r = crypt_wipe_device(ctx, device, CRYPT_WIPE_SPECIAL, startOffset * SECTOR_SIZE,
1128                               (endOffset - startOffset) * SECTOR_SIZE,
1129                               (endOffset - startOffset) * SECTOR_SIZE, NULL, NULL);
1130         if (r) {
1131                 if (r == -EACCES) {
1132                         log_err(ctx, _("Cannot write to device %s, permission denied."),
1133                                 device_path(device));
1134                         r = -EINVAL;
1135                 } else
1136                         log_err(ctx, _("Cannot wipe device %s."),
1137                                 device_path(device));
1138                 return r;
1139         }
1140
1141         /* Wipe keyslot info */
1142         memset(&hdr->keyblock[keyIndex].passwordSalt, 0, LUKS_SALTSIZE);
1143         hdr->keyblock[keyIndex].passwordIterations = 0;
1144
1145         r = LUKS_write_phdr(hdr, ctx);
1146
1147         return r;
1148 }
1149
1150 crypt_keyslot_info LUKS_keyslot_info(struct luks_phdr *hdr, int keyslot)
1151 {
1152         int i;
1153
1154         if(keyslot >= LUKS_NUMKEYS || keyslot < 0)
1155                 return CRYPT_SLOT_INVALID;
1156
1157         if (hdr->keyblock[keyslot].active == LUKS_KEY_DISABLED)
1158                 return CRYPT_SLOT_INACTIVE;
1159
1160         if (hdr->keyblock[keyslot].active != LUKS_KEY_ENABLED)
1161                 return CRYPT_SLOT_INVALID;
1162
1163         for(i = 0; i < LUKS_NUMKEYS; i++)
1164                 if(i != keyslot && hdr->keyblock[i].active == LUKS_KEY_ENABLED)
1165                         return CRYPT_SLOT_ACTIVE;
1166
1167         return CRYPT_SLOT_ACTIVE_LAST;
1168 }
1169
1170 int LUKS_keyslot_find_empty(struct luks_phdr *hdr)
1171 {
1172         int i;
1173
1174         for (i = 0; i < LUKS_NUMKEYS; i++)
1175                 if(hdr->keyblock[i].active == LUKS_KEY_DISABLED)
1176                         break;
1177
1178         if (i == LUKS_NUMKEYS)
1179                 return -EINVAL;
1180
1181         return i;
1182 }
1183
1184 int LUKS_keyslot_active_count(struct luks_phdr *hdr)
1185 {
1186         int i, num = 0;
1187
1188         for (i = 0; i < LUKS_NUMKEYS; i++)
1189                 if(hdr->keyblock[i].active == LUKS_KEY_ENABLED)
1190                         num++;
1191
1192         return num;
1193 }
1194
1195 int LUKS_keyslot_set(struct luks_phdr *hdr, int keyslot, int enable, struct crypt_device *ctx)
1196 {
1197         crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyslot);
1198
1199         if (ki == CRYPT_SLOT_INVALID)
1200                 return -EINVAL;
1201
1202         hdr->keyblock[keyslot].active = enable ? LUKS_KEY_ENABLED : LUKS_KEY_DISABLED;
1203         log_dbg(ctx, "Key slot %d was %s in LUKS header.", keyslot, enable ? "enabled" : "disabled");
1204         return 0;
1205 }
1206
1207 int LUKS1_activate(struct crypt_device *cd,
1208                    const char *name,
1209                    struct volume_key *vk,
1210                    uint32_t flags)
1211 {
1212         int r;
1213         struct crypt_dm_active_device dmd = {
1214                 .flags = flags,
1215                 .uuid = crypt_get_uuid(cd),
1216         };
1217
1218         r = dm_crypt_target_set(&dmd.segment, 0, dmd.size, crypt_data_device(cd),
1219                         vk, crypt_get_cipher_spec(cd), crypt_get_iv_offset(cd),
1220                         crypt_get_data_offset(cd), crypt_get_integrity(cd),
1221                         crypt_get_integrity_tag_size(cd), crypt_get_sector_size(cd));
1222         if (!r)
1223                 r = create_or_reload_device(cd, name, CRYPT_LUKS1, &dmd);
1224
1225         dm_targets_free(cd, &dmd);
1226
1227         return r;
1228 }
1229
1230 int LUKS_wipe_header_areas(struct luks_phdr *hdr,
1231         struct crypt_device *ctx)
1232 {
1233         int i, r;
1234         uint64_t offset, length;
1235         size_t wipe_block;
1236
1237         r = LUKS_check_device_size(ctx, hdr, 1);
1238         if (r)
1239                 return r;
1240
1241         /* Wipe complete header, keyslots and padding areas with zeroes. */
1242         offset = 0;
1243         length = (uint64_t)hdr->payloadOffset * SECTOR_SIZE;
1244         wipe_block = 1024 * 1024;
1245
1246         /* On detached header or bogus header, wipe at least the first 4k */
1247         if (length == 0 || length > (LUKS_MAX_KEYSLOT_SIZE * LUKS_NUMKEYS)) {
1248                 length = 4096;
1249                 wipe_block = 4096;
1250         }
1251
1252         log_dbg(ctx, "Wiping LUKS areas (0x%06" PRIx64 " - 0x%06" PRIx64") with zeroes.",
1253                 offset, length + offset);
1254
1255         r = crypt_wipe_device(ctx, crypt_metadata_device(ctx), CRYPT_WIPE_ZERO,
1256                               offset, length, wipe_block, NULL, NULL);
1257         if (r < 0)
1258                 return r;
1259
1260         /* Wipe keyslots areas */
1261         wipe_block = 1024 * 1024;
1262         for (i = 0; i < LUKS_NUMKEYS; i++) {
1263                 r = LUKS_keyslot_area(hdr, i, &offset, &length);
1264                 if (r < 0)
1265                         return r;
1266
1267                 /* Ignore too big LUKS1 keyslots here */
1268                 if (length > LUKS_MAX_KEYSLOT_SIZE ||
1269                     offset > (LUKS_MAX_KEYSLOT_SIZE - length))
1270                         continue;
1271
1272                 if (length == 0 || offset < 4096)
1273                         return -EINVAL;
1274
1275                 log_dbg(ctx, "Wiping keyslot %i area (0x%06" PRIx64 " - 0x%06" PRIx64") with random data.",
1276                         i, offset, length + offset);
1277
1278                 r = crypt_wipe_device(ctx, crypt_metadata_device(ctx), CRYPT_WIPE_RANDOM,
1279                                 offset, length, wipe_block, NULL, NULL);
1280                 if (r < 0)
1281                         return r;
1282         }
1283
1284         return r;
1285 }
1286
1287 int LUKS_keyslot_pbkdf(struct luks_phdr *hdr, int keyslot, struct crypt_pbkdf_type *pbkdf)
1288 {
1289         if (LUKS_keyslot_info(hdr, keyslot) < CRYPT_SLOT_ACTIVE)
1290                 return -EINVAL;
1291
1292         pbkdf->type = CRYPT_KDF_PBKDF2;
1293         pbkdf->hash = hdr->hashSpec;
1294         pbkdf->iterations = hdr->keyblock[keyslot].passwordIterations;
1295         pbkdf->max_memory_kb = 0;
1296         pbkdf->parallel_threads = 0;
1297         pbkdf->time_ms = 0;
1298         pbkdf->flags = 0;
1299         return 0;
1300 }