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