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