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