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