8ae2af8f408a48f7e6881993c3cbe10dc6921525
[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-2012, Red Hat, Inc. All rights reserved.
6  * Copyright (C) 2013-2014, 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 <netinet/in.h>
26 #include <fcntl.h>
27 #include <errno.h>
28 #include <unistd.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <ctype.h>
33 #include <assert.h>
34 #include <uuid/uuid.h>
35
36 #include "luks.h"
37 #include "af.h"
38 #include "internal.h"
39
40 /* Get size of struct luks_phdr with all keyslots material space */
41 static size_t LUKS_device_sectors(size_t keyLen)
42 {
43         size_t keyslot_sectors, sector;
44         int i;
45
46         keyslot_sectors = AF_split_sectors(keyLen, LUKS_STRIPES);
47         sector = LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE;
48
49         for (i = 0; i < LUKS_NUMKEYS; i++) {
50                 sector = size_round_up(sector, LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);
51                 sector += keyslot_sectors;
52         }
53
54         return sector;
55 }
56
57 int LUKS_keyslot_area(struct luks_phdr *hdr,
58         int keyslot,
59         uint64_t *offset,
60         uint64_t *length)
61 {
62         if(keyslot >= LUKS_NUMKEYS || keyslot < 0)
63                 return -EINVAL;
64
65         *offset = hdr->keyblock[keyslot].keyMaterialOffset * SECTOR_SIZE;
66         *length = AF_split_sectors(hdr->keyBytes, LUKS_STRIPES) * SECTOR_SIZE;
67
68         return 0;
69 }
70
71 static int LUKS_check_device_size(struct crypt_device *ctx, size_t keyLength)
72 {
73         struct device *device = crypt_metadata_device(ctx);
74         uint64_t dev_sectors, hdr_sectors;
75
76         if (!keyLength)
77                 return -EINVAL;
78
79         if(device_size(device, &dev_sectors)) {
80                 log_dbg("Cannot get device size for device %s.", device_path(device));
81                 return -EIO;
82         }
83
84         dev_sectors >>= SECTOR_SHIFT;
85         hdr_sectors = LUKS_device_sectors(keyLength);
86         log_dbg("Key length %zu, device size %" PRIu64 " sectors, header size %"
87                 PRIu64 " sectors.",keyLength, dev_sectors, hdr_sectors);
88
89         if (hdr_sectors > dev_sectors) {
90                 log_err(ctx, _("Device %s is too small. (LUKS requires at least %" PRIu64 " bytes.)\n"),
91                         device_path(device), hdr_sectors * SECTOR_SIZE);
92                 return -EINVAL;
93         }
94
95         return 0;
96 }
97
98 /* Check keyslot to prevent access outside of header and keyslot area */
99 static int LUKS_check_keyslot_size(const struct luks_phdr *phdr, unsigned int keyIndex)
100 {
101         uint32_t secs_per_stripes;
102
103         /* First sectors is the header itself */
104         if (phdr->keyblock[keyIndex].keyMaterialOffset * SECTOR_SIZE < sizeof(*phdr)) {
105                 log_dbg("Invalid offset %u in keyslot %u.",
106                         phdr->keyblock[keyIndex].keyMaterialOffset, keyIndex);
107                 return 1;
108         }
109
110         /* Ignore following check for detached header where offset can be zero. */
111         if (phdr->payloadOffset == 0)
112                 return 0;
113
114         if (phdr->payloadOffset <= phdr->keyblock[keyIndex].keyMaterialOffset) {
115                 log_dbg("Invalid offset %u in keyslot %u (beyond data area offset %u).",
116                         phdr->keyblock[keyIndex].keyMaterialOffset, keyIndex,
117                         phdr->payloadOffset);
118                 return 1;
119         }
120
121         secs_per_stripes = AF_split_sectors(phdr->keyBytes, phdr->keyblock[keyIndex].stripes);
122
123         if (phdr->payloadOffset < (phdr->keyblock[keyIndex].keyMaterialOffset + secs_per_stripes)) {
124                 log_dbg("Invalid keyslot size %u (offset %u, stripes %u) in "
125                         "keyslot %u (beyond data area offset %u).",
126                         secs_per_stripes,
127                         phdr->keyblock[keyIndex].keyMaterialOffset,
128                         phdr->keyblock[keyIndex].stripes,
129                         keyIndex, phdr->payloadOffset);
130                 return 1;
131         }
132
133         return 0;
134 }
135
136 static const char *dbg_slot_state(crypt_keyslot_info ki)
137 {
138         switch(ki) {
139         case CRYPT_SLOT_INACTIVE:
140                 return "INACTIVE";
141         case CRYPT_SLOT_ACTIVE:
142                 return "ACTIVE";
143         case CRYPT_SLOT_ACTIVE_LAST:
144                 return "ACTIVE_LAST";
145         case CRYPT_SLOT_INVALID:
146         default:
147                 return "INVALID";
148         }
149 }
150
151 int LUKS_hdr_backup(const char *backup_file, struct crypt_device *ctx)
152 {
153         struct device *device = crypt_metadata_device(ctx);
154         struct luks_phdr hdr;
155         int r = 0, devfd = -1;
156         ssize_t hdr_size;
157         ssize_t buffer_size;
158         char *buffer = NULL;
159
160         r = LUKS_read_phdr(&hdr, 1, 0, ctx);
161         if (r)
162                 return r;
163
164         hdr_size = LUKS_device_sectors(hdr.keyBytes) << SECTOR_SHIFT;
165         buffer_size = size_round_up(hdr_size, crypt_getpagesize());
166
167         buffer = crypt_safe_alloc(buffer_size);
168         if (!buffer || hdr_size < LUKS_ALIGN_KEYSLOTS || hdr_size > buffer_size) {
169                 r = -ENOMEM;
170                 goto out;
171         }
172
173         log_dbg("Storing backup of header (%zu bytes) and keyslot area (%zu bytes).",
174                 sizeof(hdr), hdr_size - LUKS_ALIGN_KEYSLOTS);
175
176         log_dbg("Output backup file size: %zu bytes.", buffer_size);
177
178         devfd = device_open(device, O_RDONLY);
179         if(devfd == -1) {
180                 log_err(ctx, _("Device %s is not a valid LUKS device.\n"), device_path(device));
181                 r = -EINVAL;
182                 goto out;
183         }
184
185         if (read_blockwise(devfd, device_block_size(device), buffer, hdr_size) < hdr_size) {
186                 r = -EIO;
187                 goto out;
188         }
189         close(devfd);
190
191         /* Wipe unused area, so backup cannot contain old signatures */
192         if (hdr.keyblock[0].keyMaterialOffset * SECTOR_SIZE == LUKS_ALIGN_KEYSLOTS)
193                 memset(buffer + sizeof(hdr), 0, LUKS_ALIGN_KEYSLOTS - sizeof(hdr));
194
195         devfd = open(backup_file, O_CREAT|O_EXCL|O_WRONLY, S_IRUSR);
196         if (devfd == -1) {
197                 if (errno == EEXIST)
198                         log_err(ctx, _("Requested header backup file %s already exists.\n"), backup_file);
199                 else
200                         log_err(ctx, _("Cannot create header backup file %s.\n"), backup_file);
201                 r = -EINVAL;
202                 goto out;
203         }
204         if (write(devfd, buffer, buffer_size) < buffer_size) {
205                 log_err(ctx, _("Cannot write header backup file %s.\n"), backup_file);
206                 r = -EIO;
207                 goto out;
208         }
209         close(devfd);
210
211         r = 0;
212 out:
213         if (devfd != -1)
214                 close(devfd);
215         crypt_memzero(&hdr, sizeof(hdr));
216         crypt_safe_free(buffer);
217         return r;
218 }
219
220 int LUKS_hdr_restore(
221         const char *backup_file,
222         struct luks_phdr *hdr,
223         struct crypt_device *ctx)
224 {
225         struct device *device = crypt_metadata_device(ctx);
226         int r = 0, devfd = -1, diff_uuid = 0;
227         ssize_t buffer_size = 0;
228         char *buffer = NULL, msg[200];
229         struct luks_phdr hdr_file;
230
231         r = LUKS_read_phdr_backup(backup_file, &hdr_file, 0, ctx);
232         if (r == -ENOENT)
233                 return r;
234
235         if (!r)
236                 buffer_size = LUKS_device_sectors(hdr_file.keyBytes) << SECTOR_SHIFT;
237
238         if (r || buffer_size < LUKS_ALIGN_KEYSLOTS) {
239                 log_err(ctx, _("Backup file doesn't contain valid LUKS header.\n"));
240                 r = -EINVAL;
241                 goto out;
242         }
243
244         buffer = crypt_safe_alloc(buffer_size);
245         if (!buffer) {
246                 r = -ENOMEM;
247                 goto out;
248         }
249
250         devfd = open(backup_file, O_RDONLY);
251         if (devfd == -1) {
252                 log_err(ctx, _("Cannot open header backup file %s.\n"), backup_file);
253                 r = -EINVAL;
254                 goto out;
255         }
256
257         if (read(devfd, buffer, buffer_size) < buffer_size) {
258                 log_err(ctx, _("Cannot read header backup file %s.\n"), backup_file);
259                 r = -EIO;
260                 goto out;
261         }
262         close(devfd);
263
264         r = LUKS_read_phdr(hdr, 0, 0, ctx);
265         if (r == 0) {
266                 log_dbg("Device %s already contains LUKS header, checking UUID and offset.", device_path(device));
267                 if(hdr->payloadOffset != hdr_file.payloadOffset ||
268                    hdr->keyBytes != hdr_file.keyBytes) {
269                         log_err(ctx, _("Data offset or key size differs on device and backup, restore failed.\n"));
270                         r = -EINVAL;
271                         goto out;
272                 }
273                 if (memcmp(hdr->uuid, hdr_file.uuid, UUID_STRING_L))
274                         diff_uuid = 1;
275         }
276
277         if (snprintf(msg, sizeof(msg), _("Device %s %s%s"), device_path(device),
278                  r ? _("does not contain LUKS header. Replacing header can destroy data on that device.") :
279                      _("already contains LUKS header. Replacing header will destroy existing keyslots."),
280                      diff_uuid ? _("\nWARNING: real device header has different UUID than backup!") : "") < 0) {
281                 r = -ENOMEM;
282                 goto out;
283         }
284
285         if (!crypt_confirm(ctx, msg)) {
286                 r = -EINVAL;
287                 goto out;
288         }
289
290         log_dbg("Storing backup of header (%zu bytes) and keyslot area (%zu bytes) to device %s.",
291                 sizeof(*hdr), buffer_size - LUKS_ALIGN_KEYSLOTS, device_path(device));
292
293         devfd = device_open(device, O_RDWR);
294         if (devfd == -1) {
295                 if (errno == EACCES)
296                         log_err(ctx, _("Cannot write to device %s, permission denied.\n"),
297                                 device_path(device));
298                 else
299                         log_err(ctx, _("Cannot open device %s.\n"), device_path(device));
300                 r = -EINVAL;
301                 goto out;
302         }
303
304         if (write_blockwise(devfd, device_block_size(device), buffer, buffer_size) < buffer_size) {
305                 r = -EIO;
306                 goto out;
307         }
308         close(devfd);
309
310         /* Be sure to reload new data */
311         r = LUKS_read_phdr(hdr, 1, 0, ctx);
312 out:
313         if (devfd != -1)
314                 close(devfd);
315         crypt_safe_free(buffer);
316         return r;
317 }
318
319 /* This routine should do some just basic recovery for known problems. */
320 static int _keyslot_repair(struct luks_phdr *phdr, struct crypt_device *ctx)
321 {
322         struct luks_phdr temp_phdr;
323         const unsigned char *sector = (const unsigned char*)phdr;
324         struct volume_key *vk;
325         uint64_t PBKDF2_per_sec = 1;
326         int i, bad, r, need_write = 0;
327
328         if (phdr->keyBytes != 16 && phdr->keyBytes != 32 && phdr->keyBytes != 64) {
329                 log_err(ctx, _("Non standard key size, manual repair required.\n"));
330                 return -EINVAL;
331         }
332         /* cryptsetup 1.0 did not align to 4k, cannot repair this one */
333         if (phdr->keyblock[0].keyMaterialOffset < (LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE)) {
334                 log_err(ctx, _("Non standard keyslots alignment, manual repair required.\n"));
335                 return -EINVAL;
336         }
337
338         vk = crypt_alloc_volume_key(phdr->keyBytes, NULL);
339
340         log_verbose(ctx, _("Repairing keyslots.\n"));
341
342         log_dbg("Generating second header with the same parameters for check.");
343         /* cipherName, cipherMode, hashSpec, uuid are already null terminated */
344         /* payloadOffset - cannot check */
345         r = LUKS_generate_phdr(&temp_phdr, vk, phdr->cipherName, phdr->cipherMode,
346                                phdr->hashSpec,phdr->uuid, LUKS_STRIPES,
347                                phdr->payloadOffset, 0,
348                                1, &PBKDF2_per_sec,
349                                1, ctx);
350         if (r < 0) {
351                 log_err(ctx, _("Repair failed."));
352                 goto out;
353         }
354
355         for(i = 0; i < LUKS_NUMKEYS; ++i) {
356                 if (phdr->keyblock[i].active == LUKS_KEY_ENABLED)  {
357                         log_dbg("Skipping repair for active keyslot %i.", i);
358                         continue;
359                 }
360
361                 bad = 0;
362                 if (phdr->keyblock[i].keyMaterialOffset != temp_phdr.keyblock[i].keyMaterialOffset) {
363                         log_err(ctx, _("Keyslot %i: offset repaired (%u -> %u).\n"), i,
364                                 (unsigned)phdr->keyblock[i].keyMaterialOffset,
365                                 (unsigned)temp_phdr.keyblock[i].keyMaterialOffset);
366                         phdr->keyblock[i].keyMaterialOffset = temp_phdr.keyblock[i].keyMaterialOffset;
367                         bad = 1;
368                 }
369
370                 if (phdr->keyblock[i].stripes != temp_phdr.keyblock[i].stripes) {
371                         log_err(ctx, _("Keyslot %i: stripes repaired (%u -> %u).\n"), i,
372                                 (unsigned)phdr->keyblock[i].stripes,
373                                 (unsigned)temp_phdr.keyblock[i].stripes);
374                         phdr->keyblock[i].stripes = temp_phdr.keyblock[i].stripes;
375                         bad = 1;
376                 }
377
378                 /* Known case - MSDOS partition table signature */
379                 if (i == 6 && sector[0x1fe] == 0x55 && sector[0x1ff] == 0xaa) {
380                         log_err(ctx, _("Keyslot %i: bogus partition signature.\n"), i);
381                         bad = 1;
382                 }
383
384                 if(bad) {
385                         log_err(ctx, _("Keyslot %i: salt wiped.\n"), i);
386                         phdr->keyblock[i].active = LUKS_KEY_DISABLED;
387                         memset(&phdr->keyblock[i].passwordSalt, 0x00, LUKS_SALTSIZE);
388                         phdr->keyblock[i].passwordIterations = 0;
389                 }
390
391                 if (bad)
392                         need_write = 1;
393         }
394
395         if (need_write) {
396                 log_verbose(ctx, _("Writing LUKS header to disk.\n"));
397                 r = LUKS_write_phdr(phdr, ctx);
398         }
399 out:
400         crypt_free_volume_key(vk);
401         crypt_memzero(&temp_phdr, sizeof(temp_phdr));
402         return r;
403 }
404
405 static int _check_and_convert_hdr(const char *device,
406                                   struct luks_phdr *hdr,
407                                   int require_luks_device,
408                                   int repair,
409                                   struct crypt_device *ctx)
410 {
411         int r = 0;
412         unsigned int i;
413         char luksMagic[] = LUKS_MAGIC;
414
415         if(memcmp(hdr->magic, luksMagic, LUKS_MAGIC_L)) { /* Check magic */
416                 log_dbg("LUKS header not detected.");
417                 if (require_luks_device)
418                         log_err(ctx, _("Device %s is not a valid LUKS device.\n"), device);
419                 return -EINVAL;
420         } else if((hdr->version = ntohs(hdr->version)) != 1) {  /* Convert every uint16/32_t item from network byte order */
421                 log_err(ctx, _("Unsupported LUKS version %d.\n"), hdr->version);
422                 return -EINVAL;
423         }
424
425         hdr->hashSpec[LUKS_HASHSPEC_L - 1] = '\0';
426         if (crypt_hmac_size(hdr->hashSpec) < LUKS_DIGESTSIZE) {
427                 log_err(ctx, _("Requested LUKS hash %s is not supported.\n"), hdr->hashSpec);
428                 return -EINVAL;
429         }
430
431         /* Header detected */
432         hdr->payloadOffset      = ntohl(hdr->payloadOffset);
433         hdr->keyBytes           = ntohl(hdr->keyBytes);
434         hdr->mkDigestIterations = ntohl(hdr->mkDigestIterations);
435
436         for(i = 0; i < LUKS_NUMKEYS; ++i) {
437                 hdr->keyblock[i].active             = ntohl(hdr->keyblock[i].active);
438                 hdr->keyblock[i].passwordIterations = ntohl(hdr->keyblock[i].passwordIterations);
439                 hdr->keyblock[i].keyMaterialOffset  = ntohl(hdr->keyblock[i].keyMaterialOffset);
440                 hdr->keyblock[i].stripes            = ntohl(hdr->keyblock[i].stripes);
441                 if (LUKS_check_keyslot_size(hdr, i)) {
442                         log_err(ctx, _("LUKS keyslot %u is invalid.\n"), i);
443                         r = -EINVAL;
444                 }
445         }
446
447         /* Avoid unterminated strings */
448         hdr->cipherName[LUKS_CIPHERNAME_L - 1] = '\0';
449         hdr->cipherMode[LUKS_CIPHERMODE_L - 1] = '\0';
450         hdr->uuid[UUID_STRING_L - 1] = '\0';
451
452         if (repair) {
453                 if (r == -EINVAL)
454                         r = _keyslot_repair(hdr, ctx);
455                 else
456                         log_verbose(ctx, _("No known problems detected for LUKS header.\n"));
457         }
458
459         return r;
460 }
461
462 static void _to_lower(char *str, unsigned max_len)
463 {
464         for(; *str && max_len; str++, max_len--)
465                 if (isupper(*str))
466                         *str = tolower(*str);
467 }
468
469 static void LUKS_fix_header_compatible(struct luks_phdr *header)
470 {
471         /* Old cryptsetup expects "sha1", gcrypt allows case insensistive names,
472          * so always convert hash to lower case in header */
473         _to_lower(header->hashSpec, LUKS_HASHSPEC_L);
474
475         /* ECB mode does not use IV but dmcrypt silently allows it.
476          * Drop any IV here if ECB is used (that is not secure anyway).*/
477         if (!strncmp(header->cipherMode, "ecb-", 4)) {
478                 memset(header->cipherMode, 0, LUKS_CIPHERMODE_L);
479                 strcpy(header->cipherMode, "ecb");
480         }
481 }
482
483 int LUKS_read_phdr_backup(const char *backup_file,
484                           struct luks_phdr *hdr,
485                           int require_luks_device,
486                           struct crypt_device *ctx)
487 {
488         ssize_t hdr_size = sizeof(struct luks_phdr);
489         int devfd = 0, r = 0;
490
491         log_dbg("Reading LUKS header of size %d from backup file %s",
492                 (int)hdr_size, backup_file);
493
494         devfd = open(backup_file, O_RDONLY);
495         if(-1 == devfd) {
496                 log_err(ctx, _("Cannot open header backup file %s.\n"), backup_file);
497                 return -ENOENT;
498         }
499
500         if (read(devfd, hdr, hdr_size) < hdr_size)
501                 r = -EIO;
502         else {
503                 LUKS_fix_header_compatible(hdr);
504                 r = _check_and_convert_hdr(backup_file, hdr,
505                                            require_luks_device, 0, ctx);
506         }
507
508         close(devfd);
509         return r;
510 }
511
512 int LUKS_read_phdr(struct luks_phdr *hdr,
513                    int require_luks_device,
514                    int repair,
515                    struct crypt_device *ctx)
516 {
517         struct device *device = crypt_metadata_device(ctx);
518         ssize_t hdr_size = sizeof(struct luks_phdr);
519         int devfd = 0, r = 0;
520
521         /* LUKS header starts at offset 0, first keyslot on LUKS_ALIGN_KEYSLOTS */
522         assert(sizeof(struct luks_phdr) <= LUKS_ALIGN_KEYSLOTS);
523
524         /* Stripes count cannot be changed without additional code fixes yet */
525         assert(LUKS_STRIPES == 4000);
526
527         if (repair && !require_luks_device)
528                 return -EINVAL;
529
530         log_dbg("Reading LUKS header of size %zu from device %s",
531                 hdr_size, device_path(device));
532
533         devfd = device_open(device, O_RDONLY);
534         if (devfd == -1) {
535                 log_err(ctx, _("Cannot open device %s.\n"), device_path(device));
536                 return -EINVAL;
537         }
538
539         if (read_blockwise(devfd, device_block_size(device), hdr, hdr_size) < hdr_size)
540                 r = -EIO;
541         else
542                 r = _check_and_convert_hdr(device_path(device), hdr, require_luks_device,
543                                            repair, ctx);
544
545         if (!r)
546                 r = LUKS_check_device_size(ctx, hdr->keyBytes);
547
548         close(devfd);
549         return r;
550 }
551
552 int LUKS_write_phdr(struct luks_phdr *hdr,
553                     struct crypt_device *ctx)
554 {
555         struct device *device = crypt_metadata_device(ctx);
556         ssize_t hdr_size = sizeof(struct luks_phdr);
557         int devfd = 0;
558         unsigned int i;
559         struct luks_phdr convHdr;
560         int r;
561
562         log_dbg("Updating LUKS header of size %zu on device %s",
563                 sizeof(struct luks_phdr), device_path(device));
564
565         r = LUKS_check_device_size(ctx, hdr->keyBytes);
566         if (r)
567                 return r;
568
569         devfd = device_open(device, O_RDWR);
570         if(-1 == devfd) {
571                 if (errno == EACCES)
572                         log_err(ctx, _("Cannot write to device %s, permission denied.\n"),
573                                 device_path(device));
574                 else
575                         log_err(ctx, _("Cannot open device %s.\n"), device_path(device));
576                 return -EINVAL;
577         }
578
579         memcpy(&convHdr, hdr, hdr_size);
580         memset(&convHdr._padding, 0, sizeof(convHdr._padding));
581
582         /* Convert every uint16/32_t item to network byte order */
583         convHdr.version            = htons(hdr->version);
584         convHdr.payloadOffset      = htonl(hdr->payloadOffset);
585         convHdr.keyBytes           = htonl(hdr->keyBytes);
586         convHdr.mkDigestIterations = htonl(hdr->mkDigestIterations);
587         for(i = 0; i < LUKS_NUMKEYS; ++i) {
588                 convHdr.keyblock[i].active             = htonl(hdr->keyblock[i].active);
589                 convHdr.keyblock[i].passwordIterations = htonl(hdr->keyblock[i].passwordIterations);
590                 convHdr.keyblock[i].keyMaterialOffset  = htonl(hdr->keyblock[i].keyMaterialOffset);
591                 convHdr.keyblock[i].stripes            = htonl(hdr->keyblock[i].stripes);
592         }
593
594         r = write_blockwise(devfd, device_block_size(device), &convHdr, hdr_size) < hdr_size ? -EIO : 0;
595         if (r)
596                 log_err(ctx, _("Error during update of LUKS header on device %s.\n"), device_path(device));
597         close(devfd);
598
599         /* Re-read header from disk to be sure that in-memory and on-disk data are the same. */
600         if (!r) {
601                 r = LUKS_read_phdr(hdr, 1, 0, ctx);
602                 if (r)
603                         log_err(ctx, _("Error re-reading LUKS header after update on device %s.\n"),
604                                 device_path(device));
605         }
606
607         return r;
608 }
609
610 /* Check that kernel supports requested cipher by decryption of one sector */
611 static int LUKS_check_cipher(struct luks_phdr *hdr, struct crypt_device *ctx)
612 {
613         int r;
614         struct volume_key *empty_key;
615         char buf[SECTOR_SIZE];
616
617         log_dbg("Checking if cipher %s-%s is usable.", hdr->cipherName, hdr->cipherMode);
618
619         empty_key = crypt_alloc_volume_key(hdr->keyBytes, NULL);
620         if (!empty_key)
621                 return -ENOMEM;
622
623         r = LUKS_decrypt_from_storage(buf, sizeof(buf),
624                                       hdr->cipherName, hdr->cipherMode,
625                                       empty_key, 0, ctx);
626
627         crypt_free_volume_key(empty_key);
628         crypt_memzero(buf, sizeof(buf));
629         return r;
630 }
631
632 int LUKS_generate_phdr(struct luks_phdr *header,
633                        const struct volume_key *vk,
634                        const char *cipherName, const char *cipherMode, const char *hashSpec,
635                        const char *uuid, unsigned int stripes,
636                        unsigned int alignPayload,
637                        unsigned int alignOffset,
638                        uint32_t iteration_time_ms,
639                        uint64_t *PBKDF2_per_sec,
640                        int detached_metadata_device,
641                        struct crypt_device *ctx)
642 {
643         unsigned int i = 0, hdr_sectors = LUKS_device_sectors(vk->keylength);
644         size_t blocksPerStripeSet, currentSector;
645         int r;
646         uuid_t partitionUuid;
647         char luksMagic[] = LUKS_MAGIC;
648
649         /* For separate metadata device allow zero alignment */
650         if (alignPayload == 0 && !detached_metadata_device)
651                 alignPayload = DEFAULT_DISK_ALIGNMENT / SECTOR_SIZE;
652
653         if (alignPayload && detached_metadata_device && alignPayload < hdr_sectors) {
654                 log_err(ctx, _("Data offset for detached LUKS header must be "
655                                "either 0 or higher than header size (%d sectors).\n"),
656                                hdr_sectors);
657                 return -EINVAL;
658         }
659
660         if (crypt_hmac_size(hashSpec) < LUKS_DIGESTSIZE) {
661                 log_err(ctx, _("Requested LUKS hash %s is not supported.\n"), hashSpec);
662                 return -EINVAL;
663         }
664
665         if (uuid && uuid_parse(uuid, partitionUuid) == -1) {
666                 log_err(ctx, _("Wrong LUKS UUID format provided.\n"));
667                 return -EINVAL;
668         }
669         if (!uuid)
670                 uuid_generate(partitionUuid);
671
672         memset(header,0,sizeof(struct luks_phdr));
673
674         /* Set Magic */
675         memcpy(header->magic,luksMagic,LUKS_MAGIC_L);
676         header->version=1;
677         strncpy(header->cipherName,cipherName,LUKS_CIPHERNAME_L);
678         strncpy(header->cipherMode,cipherMode,LUKS_CIPHERMODE_L);
679         strncpy(header->hashSpec,hashSpec,LUKS_HASHSPEC_L);
680
681         header->keyBytes=vk->keylength;
682
683         LUKS_fix_header_compatible(header);
684
685         r = LUKS_check_cipher(header, ctx);
686         if (r < 0)
687                 return r;
688
689         log_dbg("Generating LUKS header version %d using hash %s, %s, %s, MK %d bytes",
690                 header->version, header->hashSpec ,header->cipherName, header->cipherMode,
691                 header->keyBytes);
692
693         r = crypt_random_get(ctx, header->mkDigestSalt, LUKS_SALTSIZE, CRYPT_RND_SALT);
694         if(r < 0) {
695                 log_err(ctx, _("Cannot create LUKS header: reading random salt failed.\n"));
696                 return r;
697         }
698
699         r = crypt_benchmark_kdf(ctx, "pbkdf2", header->hashSpec,
700                                 "foo", 3, "bar", 3, PBKDF2_per_sec);
701         if (r < 0) {
702                 log_err(ctx, _("Not compatible PBKDF2 options (using hash algorithm %s).\n"),
703                         header->hashSpec);
704                 return r;
705         }
706
707         /* Compute master key digest */
708         iteration_time_ms /= 8;
709         header->mkDigestIterations = at_least((uint32_t)(*PBKDF2_per_sec/1024) * iteration_time_ms,
710                                               LUKS_MKD_ITERATIONS_MIN);
711
712         r = crypt_pbkdf("pbkdf2", header->hashSpec, vk->key,vk->keylength,
713                         header->mkDigestSalt, LUKS_SALTSIZE,
714                         header->mkDigest,LUKS_DIGESTSIZE,
715                         header->mkDigestIterations);
716         if(r < 0) {
717                 log_err(ctx, _("Cannot create LUKS header: header digest failed (using hash %s).\n"),
718                         header->hashSpec);
719                 return r;
720         }
721
722         currentSector = LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE;
723         blocksPerStripeSet = AF_split_sectors(vk->keylength, stripes);
724         for(i = 0; i < LUKS_NUMKEYS; ++i) {
725                 header->keyblock[i].active = LUKS_KEY_DISABLED;
726                 header->keyblock[i].keyMaterialOffset = currentSector;
727                 header->keyblock[i].stripes = stripes;
728                 currentSector = size_round_up(currentSector + blocksPerStripeSet,
729                                                 LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE);
730         }
731
732         if (detached_metadata_device) {
733                 /* for separate metadata device use alignPayload directly */
734                 header->payloadOffset = alignPayload;
735         } else {
736                 /* alignOffset - offset from natural device alignment provided by topology info */
737                 currentSector = size_round_up(currentSector, alignPayload);
738                 header->payloadOffset = currentSector + alignOffset;
739         }
740
741         uuid_unparse(partitionUuid, header->uuid);
742
743         log_dbg("Data offset %d, UUID %s, digest iterations %" PRIu32,
744                 header->payloadOffset, header->uuid, header->mkDigestIterations);
745
746         return 0;
747 }
748
749 int LUKS_hdr_uuid_set(
750         struct luks_phdr *hdr,
751         const char *uuid,
752         struct crypt_device *ctx)
753 {
754         uuid_t partitionUuid;
755
756         if (uuid && uuid_parse(uuid, partitionUuid) == -1) {
757                 log_err(ctx, _("Wrong LUKS UUID format provided.\n"));
758                 return -EINVAL;
759         }
760         if (!uuid)
761                 uuid_generate(partitionUuid);
762
763         uuid_unparse(partitionUuid, hdr->uuid);
764
765         return LUKS_write_phdr(hdr, ctx);
766 }
767
768 int LUKS_set_key(unsigned int keyIndex,
769                  const char *password, size_t passwordLen,
770                  struct luks_phdr *hdr, struct volume_key *vk,
771                  uint32_t iteration_time_ms,
772                  uint64_t *PBKDF2_per_sec,
773                  struct crypt_device *ctx)
774 {
775         struct volume_key *derived_key;
776         char *AfKey = NULL;
777         size_t AFEKSize;
778         uint64_t PBKDF2_temp;
779         int r;
780
781         if(hdr->keyblock[keyIndex].active != LUKS_KEY_DISABLED) {
782                 log_err(ctx, _("Key slot %d active, purge first.\n"), keyIndex);
783                 return -EINVAL;
784         }
785
786         /* LUKS keyslot has always at least 4000 stripes accoding to specification */
787         if(hdr->keyblock[keyIndex].stripes < 4000) {
788                 log_err(ctx, _("Key slot %d material includes too few stripes. Header manipulation?\n"),
789                         keyIndex);
790                  return -EINVAL;
791         }
792
793         log_dbg("Calculating data for key slot %d", keyIndex);
794
795         r = crypt_benchmark_kdf(ctx, "pbkdf2", hdr->hashSpec,
796                                 "foo", 3, "bar", 3, PBKDF2_per_sec);
797         if (r < 0) {
798                 log_err(ctx, _("Not compatible PBKDF2 options (using hash algorithm %s).\n"),
799                         hdr->hashSpec);
800                 return r;
801         }
802
803         /*
804          * Avoid floating point operation
805          * Final iteration count is at least LUKS_SLOT_ITERATIONS_MIN
806          */
807         PBKDF2_temp = (*PBKDF2_per_sec / 2) * (uint64_t)iteration_time_ms;
808         PBKDF2_temp /= 1024;
809         if (PBKDF2_temp > UINT32_MAX)
810                 PBKDF2_temp = UINT32_MAX;
811         hdr->keyblock[keyIndex].passwordIterations = at_least((uint32_t)PBKDF2_temp,
812                                                               LUKS_SLOT_ITERATIONS_MIN);
813
814         log_dbg("Key slot %d use %" PRIu32 " password iterations.", keyIndex, hdr->keyblock[keyIndex].passwordIterations);
815
816         derived_key = crypt_alloc_volume_key(hdr->keyBytes, NULL);
817         if (!derived_key)
818                 return -ENOMEM;
819
820         r = crypt_random_get(ctx, hdr->keyblock[keyIndex].passwordSalt,
821                        LUKS_SALTSIZE, CRYPT_RND_SALT);
822         if (r < 0)
823                 goto out;
824
825         r = crypt_pbkdf("pbkdf2", hdr->hashSpec, password, passwordLen,
826                         hdr->keyblock[keyIndex].passwordSalt, LUKS_SALTSIZE,
827                         derived_key->key, hdr->keyBytes,
828                         hdr->keyblock[keyIndex].passwordIterations);
829         if (r < 0)
830                 goto out;
831
832         /*
833          * AF splitting, the masterkey stored in vk->key is split to AfKey
834          */
835         assert(vk->keylength == hdr->keyBytes);
836         AFEKSize = AF_split_sectors(vk->keylength, hdr->keyblock[keyIndex].stripes) * SECTOR_SIZE;
837         AfKey = crypt_safe_alloc(AFEKSize);
838         if (!AfKey) {
839                 r = -ENOMEM;
840                 goto out;
841         }
842
843         log_dbg("Using hash %s for AF in key slot %d, %d stripes",
844                 hdr->hashSpec, keyIndex, hdr->keyblock[keyIndex].stripes);
845         r = AF_split(vk->key,AfKey,vk->keylength,hdr->keyblock[keyIndex].stripes,hdr->hashSpec);
846         if (r < 0)
847                 goto out;
848
849         log_dbg("Updating key slot %d [0x%04x] area.", keyIndex,
850                 hdr->keyblock[keyIndex].keyMaterialOffset << 9);
851         /* Encryption via dm */
852         r = LUKS_encrypt_to_storage(AfKey,
853                                     AFEKSize,
854                                     hdr->cipherName, hdr->cipherMode,
855                                     derived_key,
856                                     hdr->keyblock[keyIndex].keyMaterialOffset,
857                                     ctx);
858         if (r < 0)
859                 goto out;
860
861         /* Mark the key as active in phdr */
862         r = LUKS_keyslot_set(hdr, (int)keyIndex, 1);
863         if (r < 0)
864                 goto out;
865
866         r = LUKS_write_phdr(hdr, ctx);
867         if (r < 0)
868                 goto out;
869
870         r = 0;
871 out:
872         crypt_safe_free(AfKey);
873         crypt_free_volume_key(derived_key);
874         return r;
875 }
876
877 /* Check whether a volume key is invalid. */
878 int LUKS_verify_volume_key(const struct luks_phdr *hdr,
879                            const struct volume_key *vk)
880 {
881         char checkHashBuf[LUKS_DIGESTSIZE];
882
883         if (crypt_pbkdf("pbkdf2", hdr->hashSpec, vk->key, vk->keylength,
884                         hdr->mkDigestSalt, LUKS_SALTSIZE,
885                         checkHashBuf, LUKS_DIGESTSIZE,
886                         hdr->mkDigestIterations) < 0)
887                 return -EINVAL;
888
889         if (memcmp(checkHashBuf, hdr->mkDigest, LUKS_DIGESTSIZE))
890                 return -EPERM;
891
892         return 0;
893 }
894
895 /* Try to open a particular key slot */
896 static int LUKS_open_key(unsigned int keyIndex,
897                   const char *password,
898                   size_t passwordLen,
899                   struct luks_phdr *hdr,
900                   struct volume_key *vk,
901                   struct crypt_device *ctx)
902 {
903         crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyIndex);
904         struct volume_key *derived_key;
905         char *AfKey;
906         size_t AFEKSize;
907         int r;
908
909         log_dbg("Trying to open key slot %d [%s].", keyIndex,
910                 dbg_slot_state(ki));
911
912         if (ki < CRYPT_SLOT_ACTIVE)
913                 return -ENOENT;
914
915         derived_key = crypt_alloc_volume_key(hdr->keyBytes, NULL);
916         if (!derived_key)
917                 return -ENOMEM;
918
919         assert(vk->keylength == hdr->keyBytes);
920         AFEKSize = AF_split_sectors(vk->keylength, hdr->keyblock[keyIndex].stripes) * SECTOR_SIZE;
921         AfKey = crypt_safe_alloc(AFEKSize);
922         if (!AfKey) {
923                 r = -ENOMEM;
924                 goto out;
925         }
926
927         r = crypt_pbkdf("pbkdf2", hdr->hashSpec, password, passwordLen,
928                         hdr->keyblock[keyIndex].passwordSalt, LUKS_SALTSIZE,
929                         derived_key->key, hdr->keyBytes,
930                         hdr->keyblock[keyIndex].passwordIterations);
931         if (r < 0)
932                 goto out;
933
934         log_dbg("Reading key slot %d area.", keyIndex);
935         r = LUKS_decrypt_from_storage(AfKey,
936                                       AFEKSize,
937                                       hdr->cipherName, hdr->cipherMode,
938                                       derived_key,
939                                       hdr->keyblock[keyIndex].keyMaterialOffset,
940                                       ctx);
941         if (r < 0)
942                 goto out;
943
944         r = AF_merge(AfKey,vk->key,vk->keylength,hdr->keyblock[keyIndex].stripes,hdr->hashSpec);
945         if (r < 0)
946                 goto out;
947
948         r = LUKS_verify_volume_key(hdr, vk);
949         if (!r)
950                 log_verbose(ctx, _("Key slot %d unlocked.\n"), keyIndex);
951 out:
952         crypt_safe_free(AfKey);
953         crypt_free_volume_key(derived_key);
954         return r;
955 }
956
957 int LUKS_open_key_with_hdr(int keyIndex,
958                            const char *password,
959                            size_t passwordLen,
960                            struct luks_phdr *hdr,
961                            struct volume_key **vk,
962                            struct crypt_device *ctx)
963 {
964         unsigned int i;
965         int r;
966
967         *vk = crypt_alloc_volume_key(hdr->keyBytes, NULL);
968
969         if (keyIndex >= 0) {
970                 r = LUKS_open_key(keyIndex, password, passwordLen, hdr, *vk, ctx);
971                 return (r < 0) ? r : keyIndex;
972         }
973
974         for(i = 0; i < LUKS_NUMKEYS; i++) {
975                 r = LUKS_open_key(i, password, passwordLen, hdr, *vk, ctx);
976                 if(r == 0)
977                         return i;
978
979                 /* Do not retry for errors that are no -EPERM or -ENOENT,
980                    former meaning password wrong, latter key slot inactive */
981                 if ((r != -EPERM) && (r != -ENOENT))
982                         return r;
983         }
984         /* Warning, early returns above */
985         log_err(ctx, _("No key available with this passphrase.\n"));
986         return -EPERM;
987 }
988
989 int LUKS_del_key(unsigned int keyIndex,
990                  struct luks_phdr *hdr,
991                  struct crypt_device *ctx)
992 {
993         struct device *device = crypt_metadata_device(ctx);
994         unsigned int startOffset, endOffset;
995         int r;
996
997         r = LUKS_read_phdr(hdr, 1, 0, ctx);
998         if (r)
999                 return r;
1000
1001         r = LUKS_keyslot_set(hdr, keyIndex, 0);
1002         if (r) {
1003                 log_err(ctx, _("Key slot %d is invalid, please select keyslot between 0 and %d.\n"),
1004                         keyIndex, LUKS_NUMKEYS - 1);
1005                 return r;
1006         }
1007
1008         /* secure deletion of key material */
1009         startOffset = hdr->keyblock[keyIndex].keyMaterialOffset;
1010         endOffset = startOffset + AF_split_sectors(hdr->keyBytes, hdr->keyblock[keyIndex].stripes);
1011
1012         r = crypt_wipe(device, startOffset * SECTOR_SIZE,
1013                        (endOffset - startOffset) * SECTOR_SIZE,
1014                        CRYPT_WIPE_DISK, 0);
1015         if (r) {
1016                 if (r == -EACCES) {
1017                         log_err(ctx, _("Cannot write to device %s, permission denied.\n"),
1018                                 device_path(device));
1019                         r = -EINVAL;
1020                 } else
1021                         log_err(ctx, _("Cannot wipe device %s.\n"),
1022                                 device_path(device));
1023                 return r;
1024         }
1025
1026         /* Wipe keyslot info */
1027         memset(&hdr->keyblock[keyIndex].passwordSalt, 0, LUKS_SALTSIZE);
1028         hdr->keyblock[keyIndex].passwordIterations = 0;
1029
1030         r = LUKS_write_phdr(hdr, ctx);
1031
1032         return r;
1033 }
1034
1035 crypt_keyslot_info LUKS_keyslot_info(struct luks_phdr *hdr, int keyslot)
1036 {
1037         int i;
1038
1039         if(keyslot >= LUKS_NUMKEYS || keyslot < 0)
1040                 return CRYPT_SLOT_INVALID;
1041
1042         if (hdr->keyblock[keyslot].active == LUKS_KEY_DISABLED)
1043                 return CRYPT_SLOT_INACTIVE;
1044
1045         if (hdr->keyblock[keyslot].active != LUKS_KEY_ENABLED)
1046                 return CRYPT_SLOT_INVALID;
1047
1048         for(i = 0; i < LUKS_NUMKEYS; i++)
1049                 if(i != keyslot && hdr->keyblock[i].active == LUKS_KEY_ENABLED)
1050                         return CRYPT_SLOT_ACTIVE;
1051
1052         return CRYPT_SLOT_ACTIVE_LAST;
1053 }
1054
1055 int LUKS_keyslot_find_empty(struct luks_phdr *hdr)
1056 {
1057         int i;
1058
1059         for (i = 0; i < LUKS_NUMKEYS; i++)
1060                 if(hdr->keyblock[i].active == LUKS_KEY_DISABLED)
1061                         break;
1062
1063         if (i == LUKS_NUMKEYS)
1064                 return -EINVAL;
1065
1066         return i;
1067 }
1068
1069 int LUKS_keyslot_active_count(struct luks_phdr *hdr)
1070 {
1071         int i, num = 0;
1072
1073         for (i = 0; i < LUKS_NUMKEYS; i++)
1074                 if(hdr->keyblock[i].active == LUKS_KEY_ENABLED)
1075                         num++;
1076
1077         return num;
1078 }
1079
1080 int LUKS_keyslot_set(struct luks_phdr *hdr, int keyslot, int enable)
1081 {
1082         crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyslot);
1083
1084         if (ki == CRYPT_SLOT_INVALID)
1085                 return -EINVAL;
1086
1087         hdr->keyblock[keyslot].active = enable ? LUKS_KEY_ENABLED : LUKS_KEY_DISABLED;
1088         log_dbg("Key slot %d was %s in LUKS header.", keyslot, enable ? "enabled" : "disabled");
1089         return 0;
1090 }
1091
1092 int LUKS1_activate(struct crypt_device *cd,
1093                    const char *name,
1094                    struct volume_key *vk,
1095                    uint32_t flags)
1096 {
1097         int r;
1098         char *dm_cipher = NULL;
1099         enum devcheck device_check;
1100         struct crypt_dm_active_device dmd = {
1101                 .target = DM_CRYPT,
1102                 .uuid   = crypt_get_uuid(cd),
1103                 .flags  = flags,
1104                 .size   = 0,
1105                 .data_device = crypt_data_device(cd),
1106                 .u.crypt = {
1107                         .cipher = NULL,
1108                         .vk     = vk,
1109                         .offset = crypt_get_data_offset(cd),
1110                         .iv_offset = 0,
1111                 }
1112         };
1113
1114         if (dmd.flags & CRYPT_ACTIVATE_SHARED)
1115                 device_check = DEV_SHARED;
1116         else
1117                 device_check = DEV_EXCL;
1118
1119         r = device_block_adjust(cd, dmd.data_device, device_check,
1120                                  dmd.u.crypt.offset, &dmd.size, &dmd.flags);
1121         if (r)
1122                 return r;
1123
1124         r = asprintf(&dm_cipher, "%s-%s", crypt_get_cipher(cd), crypt_get_cipher_mode(cd));
1125         if (r < 0)
1126                 return -ENOMEM;
1127
1128         dmd.u.crypt.cipher = dm_cipher;
1129         r = dm_create_device(cd, name, CRYPT_LUKS1, &dmd, 0);
1130
1131         free(dm_cipher);
1132         return r;
1133 }