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