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