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