diff options
author | Milan Broz <gmazyland@gmail.com> | 2010-11-14 20:06:35 +0000 |
---|---|---|
committer | Milan Broz <gmazyland@gmail.com> | 2010-11-14 20:06:35 +0000 |
commit | 014206399ae0a6bd4499595c2f6527dc30d3cae5 (patch) | |
tree | 06673909c6270d4d5f3987ce3dbb58ca86a22378 /lib | |
parent | 312d8eca7342fb7de37f9124fb73119018a94523 (diff) | |
download | cryptsetup-014206399ae0a6bd4499595c2f6527dc30d3cae5.tar.gz cryptsetup-014206399ae0a6bd4499595c2f6527dc30d3cae5.tar.bz2 cryptsetup-014206399ae0a6bd4499595c2f6527dc30d3cae5.zip |
Move LUKS library to lib subdir.
git-svn-id: https://cryptsetup.googlecode.com/svn/trunk@366 36d66b0a-2a48-0410-832c-cd162a569da5
Diffstat (limited to 'lib')
-rw-r--r-- | lib/Makefile.am | 6 | ||||
-rw-r--r-- | lib/luks1/Makefile.am | 20 | ||||
-rw-r--r-- | lib/luks1/af.c | 140 | ||||
-rw-r--r-- | lib/luks1/af.h | 25 | ||||
-rw-r--r-- | lib/luks1/keyencryption.c | 210 | ||||
-rw-r--r-- | lib/luks1/keymanage.c | 863 | ||||
-rw-r--r-- | lib/luks1/luks.h | 176 | ||||
-rw-r--r-- | lib/luks1/pbkdf.c | 276 | ||||
-rw-r--r-- | lib/luks1/pbkdf.h | 15 |
9 files changed, 1729 insertions, 2 deletions
diff --git a/lib/Makefile.am b/lib/Makefile.am index dc78b3c..a624e5b 100644 --- a/lib/Makefile.am +++ b/lib/Makefile.am @@ -1,3 +1,5 @@ +SUBDIRS = luks1 + moduledir = $(libdir)/cryptsetup pkgconfigdir = $(libdir)/pkgconfig @@ -5,7 +7,7 @@ pkgconfig_DATA = libcryptsetup.pc INCLUDES = \ -I$(top_srcdir) \ - -I$(top_srcdir)/luks \ + -I$(top_srcdir)/lib/luks1 \ -DDATADIR=\""$(datadir)"\" \ -DLIBDIR=\""$(libdir)"\" \ -DPREFIX=\""$(prefix)"\" \ @@ -29,7 +31,7 @@ libcryptsetup_la_LIBADD = \ @UUID_LIBS@ \ @DEVMAPPER_LIBS@ \ @LIBGCRYPT_LIBS@ \ - ../luks/libluks.la + luks1/libluks1.la libcryptsetup_la_SOURCES = \ setup.c \ diff --git a/lib/luks1/Makefile.am b/lib/luks1/Makefile.am new file mode 100644 index 0000000..18292c3 --- /dev/null +++ b/lib/luks1/Makefile.am @@ -0,0 +1,20 @@ +moduledir = $(libdir)/cryptsetup + +noinst_LTLIBRARIES = libluks1.la + +libluks1_la_CFLAGS = -Wall @LIBGCRYPT_CFLAGS@ + +libluks1_la_SOURCES = \ + af.c \ + pbkdf.c \ + keymanage.c \ + keyencryption.c \ + pbkdf.h \ + af.h \ + luks.h + +INCLUDES = -D_GNU_SOURCE \ + -D_LARGEFILE64_SOURCE \ + -D_FILE_OFFSET_BITS=64 \ + -I$(top_srcdir)/lib + diff --git a/lib/luks1/af.c b/lib/luks1/af.c new file mode 100644 index 0000000..aad6691 --- /dev/null +++ b/lib/luks1/af.c @@ -0,0 +1,140 @@ +/* + * AFsplitter - Anti forensic information splitter + * Copyright 2004, Clemens Fruhwirth <clemens@endorphin.org> + * Copyright (C) 2009 Red Hat, Inc. All rights reserved. + * + * AFsplitter diffuses information over a large stripe of data, + * therefor supporting secure data destruction. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Library General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#include <stddef.h> +#include <stdlib.h> +#include <string.h> +#include <netinet/in.h> +#include <errno.h> +#include <gcrypt.h> +#include "internal.h" + +static void XORblock(char const *src1, char const *src2, char *dst, size_t n) +{ + size_t j; + + for(j = 0; j < n; ++j) + dst[j] = src1[j] ^ src2[j]; +} + +static int hash_buf(char *src, char *dst, uint32_t iv, int len, int hash_id) +{ + gcry_md_hd_t hd; + unsigned char *digest; + + iv = htonl(iv); + if (gcry_md_open(&hd, hash_id, 0)) + return 1; + gcry_md_write(hd, (unsigned char *)&iv, sizeof(iv)); + gcry_md_write(hd, src, len); + digest = gcry_md_read(hd, hash_id); + memcpy(dst, digest, len); + gcry_md_close(hd); + return 0; +} + +/* diffuse: Information spreading over the whole dataset with + * the help of hash function. + */ + +static int diffuse(char *src, char *dst, size_t size, int hash_id) +{ + unsigned int digest_size = gcry_md_get_algo_dlen(hash_id); + unsigned int i, blocks, padding; + + blocks = size / digest_size; + padding = size % digest_size; + + for (i = 0; i < blocks; i++) + if(hash_buf(src + digest_size * i, + dst + digest_size * i, + i, digest_size, hash_id)) + return 1; + + if(padding) + if(hash_buf(src + digest_size * i, + dst + digest_size * i, + i, padding, hash_id)) + return 1; + + return 0; +} + +/* + * Information splitting. The amount of data is multiplied by + * blocknumbers. The same blocksize and blocknumbers values + * must be supplied to AF_merge to recover information. + */ + +int AF_split(char *src, char *dst, size_t blocksize, unsigned int blocknumbers, const char *hash) +{ + unsigned int i; + char *bufblock; + int r = -EINVAL; + int hash_id; + + if (!(hash_id = gcry_md_map_name(hash))) + return -EINVAL; + + if((bufblock = calloc(blocksize, 1)) == NULL) return -ENOMEM; + + /* process everything except the last block */ + for(i=0; i<blocknumbers-1; i++) { + r = crypt_random_get(NULL, dst+(blocksize*i), blocksize, CRYPT_RND_NORMAL); + if(r < 0) goto out; + + XORblock(dst+(blocksize*i),bufblock,bufblock,blocksize); + if(diffuse(bufblock, bufblock, blocksize, hash_id)) + goto out; + } + /* the last block is computed */ + XORblock(src,bufblock,dst+(i*blocksize),blocksize); + r = 0; +out: + free(bufblock); + return r; +} + +int AF_merge(char *src, char *dst, size_t blocksize, unsigned int blocknumbers, const char *hash) +{ + unsigned int i; + char *bufblock; + int r = -EINVAL; + int hash_id; + + if (!(hash_id = gcry_md_map_name(hash))) + return -EINVAL; + + if((bufblock = calloc(blocksize, 1)) == NULL) return -ENOMEM; + + memset(bufblock,0,blocksize); + for(i=0; i<blocknumbers-1; i++) { + XORblock(src+(blocksize*i),bufblock,bufblock,blocksize); + if(diffuse(bufblock, bufblock, blocksize, hash_id)) + goto out; + } + XORblock(src + blocksize * i, bufblock, dst, blocksize); + r = 0; +out: + free(bufblock); + return 0; +} diff --git a/lib/luks1/af.h b/lib/luks1/af.h new file mode 100644 index 0000000..78f978c --- /dev/null +++ b/lib/luks1/af.h @@ -0,0 +1,25 @@ +#ifndef INCLUDED_CRYPTSETUP_LUKS_AF_H +#define INCLUDED_CRYPTSETUP_LUKS_AF_H + +/* + * AFsplitter - Anti forensic information splitter + * Copyright 2004, Clemens Fruhwirth <clemens@endorphin.org> + */ + +/* + * AF_split operates on src and produces information splitted data in + * dst. src is assumed to be of the length blocksize. The data stripe + * dst points to must be captable of storing blocksize*blocknumbers. + * blocknumbers is the data multiplication factor. + * + * AF_merge does just the opposite: reproduces the information stored in + * src of the length blocksize*blocknumbers into dst of the length + * blocksize. + * + * On error, both functions return -1, 0 otherwise. + */ + +int AF_split(char *src, char *dst, size_t blocksize, unsigned int blocknumbers, const char *hash); +int AF_merge(char *src, char *dst, size_t blocksize, unsigned int blocknumbers, const char *hash); + +#endif diff --git a/lib/luks1/keyencryption.c b/lib/luks1/keyencryption.c new file mode 100644 index 0000000..ed18025 --- /dev/null +++ b/lib/luks1/keyencryption.c @@ -0,0 +1,210 @@ +/* + * LUKS - Linux Unified Key Setup + * + * Copyright (C) 2004-2006, Clemens Fruhwirth <clemens@endorphin.org> + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include <string.h> +#include <stdio.h> +#include <stdlib.h> +#include <ctype.h> +#include <inttypes.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <sys/ioctl.h> +#include <sys/mman.h> +#include <sys/utsname.h> +#include <fcntl.h> +#include <unistd.h> +#include <errno.h> +#include <signal.h> + +#include "luks.h" +#include "internal.h" + +#define div_round_up(a,b) ({ \ + typeof(a) __a = (a); \ + typeof(b) __b = (b); \ + (__a - 1) / __b + 1; \ +}) + +static inline int round_up_modulo(int x, int m) { + return div_round_up(x, m) * m; +} + +static const char *cleaner_name=NULL; +static uint64_t cleaner_size = 0; +static int devfd=-1; + +static int setup_mapping(const char *cipher, const char *name, + const char *device, unsigned int payloadOffset, + const char *key, size_t keyLength, + unsigned int sector, size_t srcLength, + int mode, struct crypt_device *ctx) +{ + int device_sector_size = sector_size_for_device(device); + uint64_t size; + + /* + * we need to round this to nearest multiple of the underlying + * device's sector size, otherwise the mapping will be refused. + */ + if(device_sector_size < 0) { + log_err(ctx, _("Unable to obtain sector size for %s"), device); + return -EINVAL; + } + size = round_up_modulo(srcLength,device_sector_size)/SECTOR_SIZE; + cleaner_size = size; + + return dm_create_device(name, device, cipher, "TEMP", NULL, size, 0, sector, + keyLength, key, (mode == O_RDONLY), 0); +} + +static void sigint_handler(int sig) +{ + if(devfd >= 0) + close(devfd); + devfd = -1; + if(cleaner_name) + dm_remove_device(cleaner_name, 1, cleaner_size); + + signal(SIGINT, SIG_DFL); + kill(getpid(), SIGINT); +} + +static char *_error_hint(char *cipherName, char *cipherMode, size_t keyLength) +{ + char *hint = ""; +#ifdef __linux__ + char c, tmp[4] = {0}; + struct utsname uts; + int i = 0, kernel_minor; + + /* Nothing to suggest here */ + if (uname(&uts) || strncmp(uts.release, "2.6.", 4)) + return hint; + + /* Get kernel minor without suffixes */ + while (i < 3 && (c = uts.release[i + 4])) + tmp[i++] = isdigit(c) ? c : '\0'; + kernel_minor = atoi(tmp); + + if (!strncmp(cipherMode, "xts", 3) && (keyLength != 256 && keyLength != 512)) + hint = _("Key size in XTS mode must be 256 or 512 bits.\n"); + else if (!strncmp(cipherMode, "xts", 3) && kernel_minor < 24) + hint = _("Block mode XTS is available since kernel 2.6.24.\n"); + if (!strncmp(cipherMode, "lrw", 3) && (keyLength != 256 && keyLength != 512)) + hint = _("Key size in LRW mode must be 256 or 512 bits.\n"); + else if (!strncmp(cipherMode, "lrw", 3) && kernel_minor < 20) + hint = _("Block mode LRW is available since kernel 2.6.20.\n"); +#endif + return hint; +} + +/* This function is not reentrant safe, as it installs a signal + handler and global vars for cleaning */ +static int LUKS_endec_template(char *src, size_t srcLength, + struct luks_phdr *hdr, + char *key, size_t keyLength, + const char *device, + unsigned int sector, + ssize_t (*func)(int, void *, size_t), + int mode, + struct crypt_device *ctx) +{ + char *name = NULL; + char *fullpath = NULL; + char *dmCipherSpec = NULL; + const char *dmDir = dm_get_dir(); + int r = -1; + + if(dmDir == NULL) { + log_err(ctx, _("Failed to obtain device mapper directory.")); + return -1; + } + if(asprintf(&name,"temporary-cryptsetup-%d",getpid()) == -1 || + asprintf(&fullpath,"%s/%s",dmDir,name) == -1 || + asprintf(&dmCipherSpec,"%s-%s",hdr->cipherName, hdr->cipherMode) == -1) { + r = -ENOMEM; + goto out1; + } + + signal(SIGINT, sigint_handler); + cleaner_name = name; + + r = setup_mapping(dmCipherSpec, name, device, hdr->payloadOffset, + key, keyLength, sector, srcLength, mode, ctx); + if(r < 0) { + log_err(ctx, _("Failed to setup dm-crypt key mapping for device %s.\n" + "Check that kernel supports %s cipher (check syslog for more info).\n%s"), + device, dmCipherSpec, + _error_hint(hdr->cipherName, hdr->cipherMode, keyLength * 8)); + r = -EIO; + goto out1; + } + + devfd = open(fullpath, mode | O_DIRECT | O_SYNC); /* devfd is a global var */ + if(devfd == -1) { + log_err(ctx, _("Failed to open temporary keystore device.\n")); + r = -EIO; + goto out2; + } + + r = func(devfd,src,srcLength); + if(r < 0) { + log_err(ctx, _("Failed to access temporary keystore device.\n")); + r = -EIO; + goto out3; + } + + r = 0; + out3: + close(devfd); + devfd = -1; + out2: + dm_remove_device(cleaner_name, 1, cleaner_size); + out1: + signal(SIGINT, SIG_DFL); + cleaner_name = NULL; + cleaner_size = 0; + free(dmCipherSpec); + free(fullpath); + free(name); + return r; +} + +int LUKS_encrypt_to_storage(char *src, size_t srcLength, + struct luks_phdr *hdr, + char *key, size_t keyLength, + const char *device, + unsigned int sector, + struct crypt_device *ctx) +{ + return LUKS_endec_template(src,srcLength,hdr,key,keyLength, device, sector, + (ssize_t (*)(int, void *, size_t)) write_blockwise, + O_RDWR, ctx); +} + +int LUKS_decrypt_from_storage(char *dst, size_t dstLength, + struct luks_phdr *hdr, + char *key, size_t keyLength, + const char *device, + unsigned int sector, + struct crypt_device *ctx) +{ + return LUKS_endec_template(dst,dstLength,hdr,key,keyLength, device, + sector, read_blockwise, O_RDONLY, ctx); +} diff --git a/lib/luks1/keymanage.c b/lib/luks1/keymanage.c new file mode 100644 index 0000000..b75e645 --- /dev/null +++ b/lib/luks1/keymanage.c @@ -0,0 +1,863 @@ +/* + * LUKS - Linux Unified Key Setup + * + * Copyright (C) 2004-2006, Clemens Fruhwirth <clemens@endorphin.org> + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include <sys/types.h> +#include <sys/stat.h> +#include <sys/ioctl.h> +#include <linux/fs.h> +#include <netinet/in.h> +#include <fcntl.h> +#include <errno.h> +#include <unistd.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <ctype.h> +#include <uuid/uuid.h> + +#include "luks.h" +#include "af.h" +#include "pbkdf.h" +#include "internal.h" + +#define div_round_up(a,b) ({ \ + typeof(a) __a = (a); \ + typeof(b) __b = (b); \ + (__a - 1) / __b + 1; \ +}) + +static inline int round_up_modulo(int x, int m) { + return div_round_up(x, m) * m; +} + +int LUKS_hdr_backup( + const char *backup_file, + const char *device, + struct luks_phdr *hdr, + struct crypt_device *ctx) +{ + int r = 0, devfd = -1; + size_t buffer_size; + char *buffer = NULL; + struct stat st; + + if(stat(backup_file, &st) == 0) { + log_err(ctx, _("Requested file %s already exist.\n"), backup_file); + return -EINVAL; + } + + r = LUKS_read_phdr(device, hdr, 1, ctx); + if (r) + return r; + + buffer_size = hdr->payloadOffset << SECTOR_SHIFT; + buffer = crypt_safe_alloc(buffer_size); + if (!buffer || buffer_size < LUKS_ALIGN_KEYSLOTS) { + r = -ENOMEM; + goto out; + } + + log_dbg("Storing backup of header (%u bytes) and keyslot area (%u bytes).", + sizeof(*hdr), buffer_size - LUKS_ALIGN_KEYSLOTS); + + devfd = open(device, O_RDONLY | O_DIRECT | O_SYNC); + if(devfd == -1) { + log_err(ctx, _("Device %s is not a valid LUKS device.\n"), device); + r = -EINVAL; + goto out; + } + + if(read_blockwise(devfd, buffer, buffer_size) < buffer_size) { + r = -EIO; + goto out; + } + close(devfd); + + /* Wipe unused area, so backup cannot contain old signatures */ + memset(buffer + sizeof(*hdr), 0, LUKS_ALIGN_KEYSLOTS - sizeof(*hdr)); + + devfd = creat(backup_file, S_IRUSR); + if(devfd == -1) { + r = -EINVAL; + goto out; + } + if(write(devfd, buffer, buffer_size) < buffer_size) { + log_err(ctx, _("Cannot write header backup file %s.\n"), backup_file); + r = -EIO; + goto out; + } + close(devfd); + + r = 0; +out: + if (devfd != -1) + close(devfd); + crypt_safe_free(buffer); + return r; +} + +int LUKS_hdr_restore( + const char *backup_file, + const char *device, + struct luks_phdr *hdr, + struct crypt_device *ctx) +{ + int r = 0, devfd = -1, diff_uuid = 0; + size_t buffer_size; + char *buffer = NULL, msg[200]; + struct stat st; + struct luks_phdr hdr_file; + + if(stat(backup_file, &st) < 0) { + log_err(ctx, _("Backup file %s doesn't exist.\n"), backup_file); + return -EINVAL; + } + + r = LUKS_read_phdr_backup(backup_file, device, &hdr_file, 0, ctx); + buffer_size = hdr_file.payloadOffset << SECTOR_SHIFT; + + if (r || buffer_size < LUKS_ALIGN_KEYSLOTS) { + log_err(ctx, _("Backup file do not contain valid LUKS header.\n")); + r = -EINVAL; + goto out; + } + + buffer = crypt_safe_alloc(buffer_size); + if (!buffer) { + r = -ENOMEM; + goto out; + } + + devfd = open(backup_file, O_RDONLY); + if(devfd == -1) { + log_err(ctx, _("Cannot open header backup file %s.\n"), backup_file); + r = -EINVAL; + goto out; + } + + if(read(devfd, buffer, buffer_size) < buffer_size) { + log_err(ctx, _("Cannot read header backup file %s.\n"), backup_file); + r = -EIO; + goto out; + } + close(devfd); + + r = LUKS_read_phdr(device, hdr, 0, ctx); + if (r == 0) { + log_dbg("Device %s already contains LUKS header, checking UUID and offset.", device); + if(hdr->payloadOffset != hdr_file.payloadOffset || + hdr->keyBytes != hdr_file.keyBytes) { + log_err(ctx, _("Data offset or key size differs on device and backup, restore failed.\n")); + r = -EINVAL; + goto out; + } + if (memcmp(hdr->uuid, hdr_file.uuid, UUID_STRING_L)) + diff_uuid = 1; + } + + if (snprintf(msg, sizeof(msg), _("Device %s %s%s"), device, + r ? _("does not contain LUKS header. Replacing header can destroy data on that device.") : + _("already contains LUKS header. Replacing header will destroy existing keyslots."), + diff_uuid ? _("\nWARNING: real device header has different UUID than backup!") : "") < 0) { + r = -ENOMEM; + goto out; + } + + if (!crypt_confirm(ctx, msg)) { + r = -EINVAL; + goto out; + } + + log_dbg("Storing backup of header (%u bytes) and keyslot area (%u bytes) to device %s.", + sizeof(*hdr), buffer_size - LUKS_ALIGN_KEYSLOTS, device); + + devfd = open(device, O_WRONLY | O_DIRECT | O_SYNC); + if(devfd == -1) { + log_err(ctx, _("Cannot open device %s.\n"), device); + r = -EINVAL; + goto out; + } + + if(write_blockwise(devfd, buffer, buffer_size) < buffer_size) { + r = -EIO; + goto out; + } + close(devfd); + + /* Be sure to reload new data */ + r = LUKS_read_phdr(device, hdr, 0, ctx); +out: + if (devfd != -1) + close(devfd); + crypt_safe_free(buffer); + return r; +} + +static int _check_and_convert_hdr(const char *device, + struct luks_phdr *hdr, + int require_luks_device, + struct crypt_device *ctx) +{ + int r = 0; + unsigned int i; + char luksMagic[] = LUKS_MAGIC; + + if(memcmp(hdr->magic, luksMagic, LUKS_MAGIC_L)) { /* Check magic */ + log_dbg("LUKS header not detected."); + if (require_luks_device) + log_err(ctx, _("Device %s is not a valid LUKS device.\n"), device); + else + set_error(_("Device %s is not a valid LUKS device."), device); + r = -EINVAL; + } else if((hdr->version = ntohs(hdr->version)) != 1) { /* Convert every uint16/32_t item from network byte order */ + log_err(ctx, _("Unsupported LUKS version %d.\n"), hdr->version); + r = -EINVAL; + } else if (PBKDF2_HMAC_ready(hdr->hashSpec) < 0) { + log_err(ctx, _("Requested LUKS hash %s is not supported.\n"), hdr->hashSpec); + r = -EINVAL; + } else { + hdr->payloadOffset = ntohl(hdr->payloadOffset); + hdr->keyBytes = ntohl(hdr->keyBytes); + hdr->mkDigestIterations = ntohl(hdr->mkDigestIterations); + + for(i = 0; i < LUKS_NUMKEYS; ++i) { + hdr->keyblock[i].active = ntohl(hdr->keyblock[i].active); + hdr->keyblock[i].passwordIterations = ntohl(hdr->keyblock[i].passwordIterations); + hdr->keyblock[i].keyMaterialOffset = ntohl(hdr->keyblock[i].keyMaterialOffset); + hdr->keyblock[i].stripes = ntohl(hdr->keyblock[i].stripes); + } + } + + return r; +} + +static void _to_lower(char *str, unsigned max_len) +{ + for(; *str && max_len; str++, max_len--) + if (isupper(*str)) + *str = tolower(*str); +} + +static void LUKS_fix_header_compatible(struct luks_phdr *header) +{ + /* Old cryptsetup expects "sha1", gcrypt allows case insensistive names, + * so always convert hash to lower case in header */ + _to_lower(header->hashSpec, LUKS_HASHSPEC_L); +} + +int LUKS_read_phdr_backup(const char *backup_file, + const char *device, + struct luks_phdr *hdr, + int require_luks_device, + struct crypt_device *ctx) +{ + int devfd = 0, r = 0; + + log_dbg("Reading LUKS header of size %d from backup file %s", + sizeof(struct luks_phdr), backup_file); + + devfd = open(backup_file, O_RDONLY); + if(-1 == devfd) { + log_err(ctx, _("Cannot open file %s.\n"), device); + return -EINVAL; + } + + if(read(devfd, hdr, sizeof(struct luks_phdr)) < sizeof(struct luks_phdr)) + r = -EIO; + else { + LUKS_fix_header_compatible(hdr); + r = _check_and_convert_hdr(backup_file, hdr, require_luks_device, ctx); + } + + close(devfd); + return r; +} + +int LUKS_read_phdr(const char *device, + struct luks_phdr *hdr, + int require_luks_device, + struct crypt_device *ctx) +{ + int devfd = 0, r = 0; + uint64_t size; + + log_dbg("Reading LUKS header of size %d from device %s", + sizeof(struct luks_phdr), device); + + devfd = open(device,O_RDONLY | O_DIRECT | O_SYNC); + if(-1 == devfd) { + log_err(ctx, _("Cannot open device %s.\n"), device); + return -EINVAL; + } + + if(read_blockwise(devfd, hdr, sizeof(struct luks_phdr)) < sizeof(struct luks_phdr)) + r = -EIO; + else + r = _check_and_convert_hdr(device, hdr, require_luks_device, ctx); + +#ifdef BLKGETSIZE64 + if (r == 0 && (ioctl(devfd, BLKGETSIZE64, &size) < 0 || + size < (uint64_t)hdr->payloadOffset)) { + log_err(ctx, _("LUKS header detected but device %s is too small.\n"), device); + r = -EINVAL; + } +#endif + close(devfd); + + return r; +} + +int LUKS_write_phdr(const char *device, + struct luks_phdr *hdr, + struct crypt_device *ctx) +{ + int devfd = 0; + unsigned int i; + struct luks_phdr convHdr; + int r; + + log_dbg("Updating LUKS header of size %d on device %s", + sizeof(struct luks_phdr), device); + + devfd = open(device,O_RDWR | O_DIRECT | O_SYNC); + if(-1 == devfd) { + log_err(ctx, _("Cannot open device %s.\n"), device); + return -EINVAL; + } + + memcpy(&convHdr, hdr, sizeof(struct luks_phdr)); + memset(&convHdr._padding, 0, sizeof(convHdr._padding)); + + /* Convert every uint16/32_t item to network byte order */ + convHdr.version = htons(hdr->version); + convHdr.payloadOffset = htonl(hdr->payloadOffset); + convHdr.keyBytes = htonl(hdr->keyBytes); + convHdr.mkDigestIterations = htonl(hdr->mkDigestIterations); + for(i = 0; i < LUKS_NUMKEYS; ++i) { + convHdr.keyblock[i].active = htonl(hdr->keyblock[i].active); + convHdr.keyblock[i].passwordIterations = htonl(hdr->keyblock[i].passwordIterations); + convHdr.keyblock[i].keyMaterialOffset = htonl(hdr->keyblock[i].keyMaterialOffset); + convHdr.keyblock[i].stripes = htonl(hdr->keyblock[i].stripes); + } + + r = write_blockwise(devfd, &convHdr, sizeof(struct luks_phdr)) < sizeof(struct luks_phdr) ? -EIO : 0; + if (r) + log_err(ctx, _("Error during update of LUKS header on device %s.\n"), device); + close(devfd); + + /* Re-read header from disk to be sure that in-memory and on-disk data are the same. */ + if (!r) { + r = LUKS_read_phdr(device, hdr, 1, ctx); + if (r) + log_err(ctx, _("Error re-reading LUKS header after update on device %s.\n"), device); + } + + return r; +} + +static int LUKS_PBKDF2_performance_check(const char *hashSpec, + uint64_t *PBKDF2_per_sec, + struct crypt_device *ctx) +{ + if (!*PBKDF2_per_sec) { + if (PBKDF2_performance_check(hashSpec, PBKDF2_per_sec) < 0) { + log_err(ctx, _("Not compatible PBKDF2 options (using hash algorithm %s).\n"), hashSpec); + return -EINVAL; + } + log_dbg("PBKDF2: %" PRIu64 " iterations per second using hash %s.", *PBKDF2_per_sec, hashSpec); + } + + return 0; +} + +int LUKS_generate_phdr(struct luks_phdr *header, + const struct volume_key *vk, + const char *cipherName, const char *cipherMode, const char *hashSpec, + const char *uuid, unsigned int stripes, + unsigned int alignPayload, + unsigned int alignOffset, + uint32_t iteration_time_ms, + uint64_t *PBKDF2_per_sec, + struct crypt_device *ctx) +{ + unsigned int i=0; + unsigned int blocksPerStripeSet = div_round_up(vk->keylength*stripes,SECTOR_SIZE); + int r; + char luksMagic[] = LUKS_MAGIC; + uuid_t partitionUuid; + int currentSector; + + if (alignPayload == 0) + alignPayload = DEFAULT_DISK_ALIGNMENT / SECTOR_SIZE; + + if (PBKDF2_HMAC_ready(hashSpec) < 0) { + log_err(ctx, _("Requested LUKS hash %s is not supported.\n"), hashSpec); + return -EINVAL; + } + + if (uuid && uuid_parse(uuid, partitionUuid) == -1) { + log_err(ctx, _("Wrong LUKS UUID format provided.\n")); + return -EINVAL; + } + if (!uuid) + uuid_generate(partitionUuid); + + memset(header,0,sizeof(struct luks_phdr)); + + /* Set Magic */ + memcpy(header->magic,luksMagic,LUKS_MAGIC_L); + header->version=1; + strncpy(header->cipherName,cipherName,LUKS_CIPHERNAME_L); + strncpy(header->cipherMode,cipherMode,LUKS_CIPHERMODE_L); + strncpy(header->hashSpec,hashSpec,LUKS_HASHSPEC_L); + + header->keyBytes=vk->keylength; + + LUKS_fix_header_compatible(header); + + log_dbg("Generating LUKS header version %d using hash %s, %s, %s, MK %d bytes", + header->version, header->hashSpec ,header->cipherName, header->cipherMode, + header->keyBytes); + + r = crypt_random_get(ctx, header->mkDigestSalt, LUKS_SALTSIZE, CRYPT_RND_NORMAL); + if(r < 0) { + log_err(ctx, _("Cannot create LUKS header: reading random salt failed.\n")); + return r; + } + + if ((r = LUKS_PBKDF2_performance_check(header->hashSpec, PBKDF2_per_sec, ctx))) + return r; + + /* Compute master key digest */ + iteration_time_ms /= 8; + header->mkDigestIterations = at_least((uint32_t)(*PBKDF2_per_sec/1024) * iteration_time_ms, + LUKS_MKD_ITERATIONS_MIN); + + r = PBKDF2_HMAC(header->hashSpec,vk->key,vk->keylength, + header->mkDigestSalt,LUKS_SALTSIZE, + header->mkDigestIterations, + header->mkDigest,LUKS_DIGESTSIZE); + if(r < 0) { + log_err(ctx, _("Cannot create LUKS header: header digest failed (using hash %s).\n"), + header->hashSpec); + return r; + } + + currentSector = round_up_modulo(LUKS_PHDR_SIZE, LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE); + for(i = 0; i < LUKS_NUMKEYS; ++i) { + header->keyblock[i].active = LUKS_KEY_DISABLED; + header->keyblock[i].keyMaterialOffset = currentSector; + header->keyblock[i].stripes = stripes; + currentSector = round_up_modulo(currentSector + blocksPerStripeSet, + LUKS_ALIGN_KEYSLOTS / SECTOR_SIZE); + } + currentSector = round_up_modulo(currentSector, alignPayload); + + /* alignOffset - offset from natural device alignment provided by topology info */ + header->payloadOffset = currentSector + alignOffset; + + uuid_unparse(partitionUuid, header->uuid); + + log_dbg("Data offset %d, UUID %s, digest iterations %" PRIu32, + header->payloadOffset, header->uuid, header->mkDigestIterations); + + return 0; +} + +int LUKS_hdr_uuid_set( + const char *device, + struct luks_phdr *hdr, + const char *uuid, + struct crypt_device *ctx) +{ + uuid_t partitionUuid; + + if (uuid && uuid_parse(uuid, partitionUuid) == -1) { + log_err(ctx, _("Wrong LUKS UUID format provided.\n")); + return -EINVAL; + } + if (!uuid) + uuid_generate(partitionUuid); + + uuid_unparse(partitionUuid, hdr->uuid); + + return LUKS_write_phdr(device, hdr, ctx); +} + +int LUKS_set_key(const char *device, unsigned int keyIndex, + const char *password, size_t passwordLen, + struct luks_phdr *hdr, struct volume_key *vk, + uint32_t iteration_time_ms, + uint64_t *PBKDF2_per_sec, + struct crypt_device *ctx) +{ + char derivedKey[hdr->keyBytes]; + char *AfKey; + unsigned int AFEKSize; + uint64_t PBKDF2_temp; + int r; + + if(hdr->keyblock[keyIndex].active != LUKS_KEY_DISABLED) { + log_err(ctx, _("Key slot %d active, purge first.\n"), keyIndex); + return -EINVAL; + } + + if(hdr->keyblock[keyIndex].stripes < LUKS_STRIPES) { + log_err(ctx, _("Key slot %d material includes too few stripes. Header manipulation?\n"), + keyIndex); + return -EINVAL; + } + + log_dbg("Calculating data for key slot %d", keyIndex); + + if ((r = LUKS_PBKDF2_performance_check(hdr->hashSpec, PBKDF2_per_sec, ctx))) + return r; + + /* + * Avoid floating point operation + * Final iteration count is at least LUKS_SLOT_ITERATIONS_MIN + */ + PBKDF2_temp = (*PBKDF2_per_sec / 2) * (uint64_t)iteration_time_ms; + PBKDF2_temp /= 1024; + if (PBKDF2_temp > UINT32_MAX) + PBKDF2_temp = UINT32_MAX; + hdr->keyblock[keyIndex].passwordIterations = at_least((uint32_t)PBKDF2_temp, + LUKS_SLOT_ITERATIONS_MIN); + + log_dbg("Key slot %d use %d password iterations.", keyIndex, hdr->keyblock[keyIndex].passwordIterations); + + r = crypt_random_get(ctx, hdr->keyblock[keyIndex].passwordSalt, + LUKS_SALTSIZE, CRYPT_RND_NORMAL); + if(r < 0) return r; + +// assert((vk->keylength % TWOFISH_BLOCKSIZE) == 0); FIXME + + r = PBKDF2_HMAC(hdr->hashSpec, password,passwordLen, + hdr->keyblock[keyIndex].passwordSalt,LUKS_SALTSIZE, + hdr->keyblock[keyIndex].passwordIterations, + derivedKey, hdr->keyBytes); + if(r < 0) return r; + + /* + * AF splitting, the masterkey stored in vk->key is splitted to AfMK + */ + AFEKSize = hdr->keyblock[keyIndex].stripes*vk->keylength; + AfKey = (char *)malloc(AFEKSize); + if(AfKey == NULL) return -ENOMEM; + + log_dbg("Using hash %s for AF in key slot %d, %d stripes", + hdr->hashSpec, keyIndex, hdr->keyblock[keyIndex].stripes); + r = AF_split(vk->key,AfKey,vk->keylength,hdr->keyblock[keyIndex].stripes,hdr->hashSpec); + if(r < 0) goto out; + + log_dbg("Updating key slot %d [0x%04x] area on device %s.", keyIndex, + hdr->keyblock[keyIndex].keyMaterialOffset << 9, device); + /* Encryption via dm */ + r = LUKS_encrypt_to_storage(AfKey, + AFEKSize, + hdr, + derivedKey, + hdr->keyBytes, + device, + hdr->keyblock[keyIndex].keyMaterialOffset, + ctx); + if(r < 0) { + if(!get_error()) + log_err(ctx, _("Failed to write to key storage.\n")); + goto out; + } + + /* Mark the key as active in phdr */ + r = LUKS_keyslot_set(hdr, (int)keyIndex, 1); + if(r < 0) goto out; + + r = LUKS_write_phdr(device, hdr, ctx); + if(r < 0) goto out; + + r = 0; +out: + free(AfKey); + return r; +} + +/* Check whether a volume key is invalid. */ +int LUKS_verify_volume_key(const struct luks_phdr *hdr, + const struct volume_key *vk) +{ + char checkHashBuf[LUKS_DIGESTSIZE]; + + if (PBKDF2_HMAC(hdr->hashSpec, vk->key, vk->keylength, + hdr->mkDigestSalt, LUKS_SALTSIZE, + hdr->mkDigestIterations, checkHashBuf, + LUKS_DIGESTSIZE) < 0) + return -EINVAL; + + if (memcmp(checkHashBuf, hdr->mkDigest, LUKS_DIGESTSIZE)) + return -EPERM; + + return 0; +} + +/* Try to open a particular key slot */ +static int LUKS_open_key(const char *device, + unsigned int keyIndex, + const char *password, + size_t passwordLen, + struct luks_phdr *hdr, + struct volume_key *vk, + struct crypt_device *ctx) +{ + crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyIndex); + char derivedKey[hdr->keyBytes]; + char *AfKey; + size_t AFEKSize; + int r; + + log_dbg("Trying to open key slot %d [%d].", keyIndex, (int)ki); + + if (ki < CRYPT_SLOT_ACTIVE) + return -ENOENT; + + // assert((vk->keylength % TWOFISH_BLOCKSIZE) == 0); FIXME + + AFEKSize = hdr->keyblock[keyIndex].stripes*vk->keylength; + AfKey = (char *)malloc(AFEKSize); + if(AfKey == NULL) return -ENOMEM; + + r = PBKDF2_HMAC(hdr->hashSpec, password,passwordLen, + hdr->keyblock[keyIndex].passwordSalt,LUKS_SALTSIZE, + hdr->keyblock[keyIndex].passwordIterations, + derivedKey, hdr->keyBytes); + if(r < 0) goto out; + + log_dbg("Reading key slot %d area.", keyIndex); + r = LUKS_decrypt_from_storage(AfKey, + AFEKSize, + hdr, + derivedKey, + hdr->keyBytes, + device, + hdr->keyblock[keyIndex].keyMaterialOffset, + ctx); + if(r < 0) { + log_err(ctx, _("Failed to read from key storage.\n")); + goto out; + } + + r = AF_merge(AfKey,vk->key,vk->keylength,hdr->keyblock[keyIndex].stripes,hdr->hashSpec); + if(r < 0) goto out; + + r = LUKS_verify_volume_key(hdr, vk); + if (!r) + log_verbose(ctx, _("Key slot %d unlocked.\n"), keyIndex); +out: + free(AfKey); + return r; +} + +int LUKS_open_key_with_hdr(const char *device, + int keyIndex, + const char *password, + size_t passwordLen, + struct luks_phdr *hdr, + struct volume_key **vk, + struct crypt_device *ctx) +{ + unsigned int i; + int r; + + *vk = crypt_alloc_volume_key(hdr->keyBytes, NULL); + + if (keyIndex >= 0) { + r = LUKS_open_key(device, keyIndex, password, passwordLen, hdr, *vk, ctx); + return (r < 0) ? r : keyIndex; + } + + for(i = 0; i < LUKS_NUMKEYS; i++) { + r = LUKS_open_key(device, i, password, passwordLen, hdr, *vk, ctx); + if(r == 0) + return i; + + /* Do not retry for errors that are no -EPERM or -ENOENT, + former meaning password wrong, latter key slot inactive */ + if ((r != -EPERM) && (r != -ENOENT)) + return r; + } + /* Warning, early returns above */ + log_err(ctx, _("No key available with this passphrase.\n")); + return -EPERM; +} + +/* + * Wipe patterns according to Gutmann's Paper + */ + +static void wipeSpecial(char *buffer, size_t buffer_size, unsigned int turn) +{ + unsigned int i; + + unsigned char write_modes[][3] = { + {"\x55\x55\x55"}, {"\xaa\xaa\xaa"}, {"\x92\x49\x24"}, + {"\x49\x24\x92"}, {"\x24\x92\x49"}, {"\x00\x00\x00"}, + {"\x11\x11\x11"}, {"\x22\x22\x22"}, {"\x33\x33\x33"}, + {"\x44\x44\x44"}, {"\x55\x55\x55"}, {"\x66\x66\x66"}, + {"\x77\x77\x77"}, {"\x88\x88\x88"}, {"\x99\x99\x99"}, + {"\xaa\xaa\xaa"}, {"\xbb\xbb\xbb"}, {"\xcc\xcc\xcc"}, + {"\xdd\xdd\xdd"}, {"\xee\xee\xee"}, {"\xff\xff\xff"}, + {"\x92\x49\x24"}, {"\x49\x24\x92"}, {"\x24\x92\x49"}, + {"\x6d\xb6\xdb"}, {"\xb6\xdb\x6d"}, {"\xdb\x6d\xb6"} + }; + + for(i = 0; i < buffer_size / 3; ++i) { + memcpy(buffer, write_modes[turn], 3); + buffer += 3; + } +} + +static int wipe(const char *device, unsigned int from, unsigned int to) +{ + int devfd; + char *buffer; + unsigned int i; + unsigned int bufLen = (to - from) * SECTOR_SIZE; + int r = 0; + + devfd = open(device, O_RDWR | O_DIRECT | O_SYNC); + if(devfd == -1) + return -EINVAL; + + buffer = (char *) malloc(bufLen); + if(!buffer) { + close(devfd); + return -ENOMEM; + } + + for(i = 0; i < 39; ++i) { + if (i >= 0 && i < 5) crypt_random_get(NULL, buffer, bufLen, CRYPT_RND_NORMAL); + else if(i >= 5 && i < 32) wipeSpecial(buffer, bufLen, i - 5); + else if(i >= 32 && i < 38) crypt_random_get(NULL, buffer, bufLen, CRYPT_RND_NORMAL); + else if(i >= 38 && i < 39) memset(buffer, 0xFF, bufLen); + + if(write_lseek_blockwise(devfd, buffer, bufLen, from * SECTOR_SIZE) < 0) { + r = -EIO; + break; + } + } + + free(buffer); + close(devfd); + + return r; +} + +int LUKS_del_key(const char *device, + unsigned int keyIndex, + struct luks_phdr *hdr, + struct crypt_device *ctx) +{ + unsigned int startOffset, endOffset, stripesLen; + int r; + + r = LUKS_read_phdr(device, hdr, 1, ctx); + if (r) + return r; + + r = LUKS_keyslot_set(hdr, keyIndex, 0); + if (r) { + log_err(ctx, _("Key slot %d is invalid, please select keyslot between 0 and %d.\n"), + keyIndex, LUKS_NUMKEYS - 1); + return r; + } + + /* secure deletion of key material */ + startOffset = hdr->keyblock[keyIndex].keyMaterialOffset; + stripesLen = hdr->keyBytes * hdr->keyblock[keyIndex].stripes; + endOffset = startOffset + div_round_up(stripesLen, SECTOR_SIZE); + + r = wipe(device, startOffset, endOffset); + if (r) { + log_err(ctx, _("Cannot wipe device %s.\n"), device); + return r; + } + + /* Wipe keyslot info */ + memset(&hdr->keyblock[keyIndex].passwordSalt, 0, LUKS_SALTSIZE); + hdr->keyblock[keyIndex].passwordIterations = 0; + + r = LUKS_write_phdr(device, hdr, ctx); + + return r; +} + +crypt_keyslot_info LUKS_keyslot_info(struct luks_phdr *hdr, int keyslot) +{ + int i; + + if(keyslot >= LUKS_NUMKEYS || keyslot < 0) + return CRYPT_SLOT_INVALID; + + if (hdr->keyblock[keyslot].active == LUKS_KEY_DISABLED) + return CRYPT_SLOT_INACTIVE; + + if (hdr->keyblock[keyslot].active != LUKS_KEY_ENABLED) + return CRYPT_SLOT_INVALID; + + for(i = 0; i < LUKS_NUMKEYS; i++) + if(i != keyslot && hdr->keyblock[i].active == LUKS_KEY_ENABLED) + return CRYPT_SLOT_ACTIVE; + + return CRYPT_SLOT_ACTIVE_LAST; +} + +int LUKS_keyslot_find_empty(struct luks_phdr *hdr) +{ + int i; + + for (i = 0; i < LUKS_NUMKEYS; i++) + if(hdr->keyblock[i].active == LUKS_KEY_DISABLED) + break; + + if (i == LUKS_NUMKEYS) + return -EINVAL; + + return i; +} + +int LUKS_keyslot_active_count(struct luks_phdr *hdr) +{ + int i, num = 0; + + for (i = 0; i < LUKS_NUMKEYS; i++) + if(hdr->keyblock[i].active == LUKS_KEY_ENABLED) + num++; + + return num; +} + +int LUKS_keyslot_set(struct luks_phdr *hdr, int keyslot, int enable) +{ + crypt_keyslot_info ki = LUKS_keyslot_info(hdr, keyslot); + + if (ki == CRYPT_SLOT_INVALID) + return -EINVAL; + + hdr->keyblock[keyslot].active = enable ? LUKS_KEY_ENABLED : LUKS_KEY_DISABLED; + log_dbg("Key slot %d was %s in LUKS header.", keyslot, enable ? "enabled" : "disabled"); + return 0; +} diff --git a/lib/luks1/luks.h b/lib/luks1/luks.h new file mode 100644 index 0000000..d188438 --- /dev/null +++ b/lib/luks1/luks.h @@ -0,0 +1,176 @@ +#ifndef INCLUDED_CRYPTSETUP_LUKS_LUKS_H +#define INCLUDED_CRYPTSETUP_LUKS_LUKS_H + +/* + * LUKS partition header + */ + +#include "libcryptsetup.h" + +#define LUKS_CIPHERNAME_L 32 +#define LUKS_CIPHERMODE_L 32 +#define LUKS_HASHSPEC_L 32 +#define LUKS_DIGESTSIZE 20 // since SHA1 +#define LUKS_HMACSIZE 32 +#define LUKS_SALTSIZE 32 +#define LUKS_NUMKEYS 8 + +// Minimal number of iterations +#define LUKS_MKD_ITERATIONS_MIN 1000 +#define LUKS_SLOT_ITERATIONS_MIN 1000 + +#define LUKS_KEY_DISABLED_OLD 0 +#define LUKS_KEY_ENABLED_OLD 0xCAFE + +#define LUKS_KEY_DISABLED 0x0000DEAD +#define LUKS_KEY_ENABLED 0x00AC71F3 + +#define LUKS_STRIPES 4000 + +// partition header starts with magic +#define LUKS_MAGIC {'L','U','K','S', 0xba, 0xbe}; +#define LUKS_MAGIC_L 6 + +#define LUKS_PHDR_SIZE (sizeof(struct luks_phdr)/SECTOR_SIZE+1) + +/* Actually we need only 37, but we don't want struct autoaligning to kick in */ +#define UUID_STRING_L 40 + +/* Offset to keyslot area [in bytes] */ +#define LUKS_ALIGN_KEYSLOTS 4096 + +/* Any integer values are stored in network byte order on disk and must be +converted */ + +struct volume_key; + +struct luks_phdr { + char magic[LUKS_MAGIC_L]; + uint16_t version; + char cipherName[LUKS_CIPHERNAME_L]; + char cipherMode[LUKS_CIPHERMODE_L]; + char hashSpec[LUKS_HASHSPEC_L]; + uint32_t payloadOffset; + uint32_t keyBytes; + char mkDigest[LUKS_DIGESTSIZE]; + char mkDigestSalt[LUKS_SALTSIZE]; + uint32_t mkDigestIterations; + char uuid[UUID_STRING_L]; + + struct { + uint32_t active; + + /* parameters used for password processing */ + uint32_t passwordIterations; + char passwordSalt[LUKS_SALTSIZE]; + + /* parameters used for AF store/load */ + uint32_t keyMaterialOffset; + uint32_t stripes; + } keyblock[LUKS_NUMKEYS]; + + /* Align it to 512 sector size */ + char _padding[432]; +}; + +int LUKS_verify_volume_key(const struct luks_phdr *hdr, + const struct volume_key *vk); + +int LUKS_generate_phdr( + struct luks_phdr *header, + const struct volume_key *vk, + const char *cipherName, + const char *cipherMode, + const char *hashSpec, + const char *uuid, + unsigned int stripes, + unsigned int alignPayload, + unsigned int alignOffset, + uint32_t iteration_time_ms, + uint64_t *PBKDF2_per_sec, + struct crypt_device *ctx); + +int LUKS_read_phdr( + const char *device, + struct luks_phdr *hdr, + int require_luks_device, + struct crypt_device *ctx); + +int LUKS_read_phdr_backup( + const char *backup_file, + const char *device, + struct luks_phdr *hdr, + int require_luks_device, + struct crypt_device *ctx); + +int LUKS_hdr_uuid_set( + const char *device, + struct luks_phdr *hdr, + const char *uuid, + struct crypt_device *ctx); + +int LUKS_hdr_backup( + const char *backup_file, + const char *device, + struct luks_phdr *hdr, + struct crypt_device *ctx); + +int LUKS_hdr_restore( + const char *backup_file, + const char *device, + struct luks_phdr *hdr, + struct crypt_device *ctx); + +int LUKS_write_phdr( + const char *device, + struct luks_phdr *hdr, + struct crypt_device *ctx); + +int LUKS_set_key( + const char *device, + unsigned int keyIndex, + const char *password, + size_t passwordLen, + struct luks_phdr *hdr, + struct volume_key *vk, + uint32_t iteration_time_ms, + uint64_t *PBKDF2_per_sec, + struct crypt_device *ctx); + +int LUKS_open_key_with_hdr( + const char *device, + int keyIndex, + const char *password, + size_t passwordLen, + struct luks_phdr *hdr, + struct volume_key **vk, + struct crypt_device *ctx); + +int LUKS_del_key( + const char *device, + unsigned int keyIndex, + struct luks_phdr *hdr, + struct crypt_device *ctx); + +crypt_keyslot_info LUKS_keyslot_info(struct luks_phdr *hdr, int keyslot); +int LUKS_keyslot_find_empty(struct luks_phdr *hdr); +int LUKS_keyslot_active_count(struct luks_phdr *hdr); +int LUKS_keyslot_set(struct luks_phdr *hdr, int keyslot, int enable); + +int LUKS_encrypt_to_storage( + char *src, size_t srcLength, + struct luks_phdr *hdr, + char *key, size_t keyLength, + const char *device, + unsigned int sector, + struct crypt_device *ctx); + +int LUKS_decrypt_from_storage( + char *dst, size_t dstLength, + struct luks_phdr *hdr, + char *key, size_t keyLength, + const char *device, + unsigned int sector, + struct crypt_device *ctx); + +#endif diff --git a/lib/luks1/pbkdf.c b/lib/luks1/pbkdf.c new file mode 100644 index 0000000..fa1f720 --- /dev/null +++ b/lib/luks1/pbkdf.c @@ -0,0 +1,276 @@ +/* Implementation of Password-Based Cryptography as per PKCS#5 + * Copyright (C) 2002,2003 Simon Josefsson + * Copyright (C) 2004 Free Software Foundation + * + * LUKS code + * Copyright (C) 2004 Clemens Fruhwirth <clemens@endorphin.org> + * Copyright (C) 2009 Red Hat, Inc. All rights reserved. + * + * This file is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This file is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this file; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +#include <netinet/in.h> +#include <errno.h> +#include <signal.h> +#include <alloca.h> +#include <sys/time.h> +#include <gcrypt.h> + +static volatile uint64_t __PBKDF2_global_j = 0; +static volatile uint64_t __PBKDF2_performance = 0; + +int init_crypto(void); + +/* + * 5.2 PBKDF2 + * + * PBKDF2 applies a pseudorandom function (see Appendix B.1 for an + * example) to derive keys. The length of the derived key is essentially + * unbounded. (However, the maximum effective search space for the + * derived key may be limited by the structure of the underlying + * pseudorandom function. See Appendix B.1 for further discussion.) + * PBKDF2 is recommended for new applications. + * + * PBKDF2 (P, S, c, dkLen) + * + * Options: PRF underlying pseudorandom function (hLen + * denotes the length in octets of the + * pseudorandom function output) + * + * Input: P password, an octet string (ASCII or UTF-8) + * S salt, an octet string + * c iteration count, a positive integer + * dkLen intended length in octets of the derived + * key, a positive integer, at most + * (2^32 - 1) * hLen + * + * Output: DK derived key, a dkLen-octet string + */ + +#define MAX_PRF_BLOCK_LEN 80 + +static int pkcs5_pbkdf2(const char *hash, + const char *P, size_t Plen, + const char *S, size_t Slen, + unsigned int c, unsigned int dkLen, + char *DK, int perfcheck) +{ + gcry_md_hd_t prf; + char U[MAX_PRF_BLOCK_LEN]; + char T[MAX_PRF_BLOCK_LEN]; + int PRF, i, k, rc = -EINVAL; + unsigned int u, hLen, l, r; + unsigned char *p; + size_t tmplen = Slen + 4; + char *tmp; + + tmp = alloca(tmplen); + if (tmp == NULL) + return -ENOMEM; + + if (init_crypto()) + return -ENOSYS; + + PRF = gcry_md_map_name(hash); + if (PRF == 0) + return -EINVAL; + + hLen = gcry_md_get_algo_dlen(PRF); + if (hLen == 0 || hLen > MAX_PRF_BLOCK_LEN) + return -EINVAL; + + if (c == 0) + return -EINVAL; + + if (dkLen == 0) + return -EINVAL; + + /* + * + * Steps: + * + * 1. If dkLen > (2^32 - 1) * hLen, output "derived key too long" and + * stop. + */ + + if (dkLen > 4294967295U) + return -EINVAL; + + /* + * 2. Let l be the number of hLen-octet blocks in the derived key, + * rounding up, and let r be the number of octets in the last + * block: + * + * l = CEIL (dkLen / hLen) , + * r = dkLen - (l - 1) * hLen . + * + * Here, CEIL (x) is the "ceiling" function, i.e. the smallest + * integer greater than, or equal to, x. + */ + + l = dkLen / hLen; + if (dkLen % hLen) + l++; + r = dkLen - (l - 1) * hLen; + + /* + * 3. For each block of the derived key apply the function F defined + * below to the password P, the salt S, the iteration count c, and + * the block index to compute the block: + * + * T_1 = F (P, S, c, 1) , + * T_2 = F (P, S, c, 2) , + * ... + * T_l = F (P, S, c, l) , + * + * where the function F is defined as the exclusive-or sum of the + * first c iterates of the underlying pseudorandom function PRF + * applied to the password P and the concatenation of the salt S + * and the block index i: + * + * F (P, S, c, i) = U_1 \xor U_2 \xor ... \xor U_c + * + * where + * + * U_1 = PRF (P, S || INT (i)) , + * U_2 = PRF (P, U_1) , + * ... + * U_c = PRF (P, U_{c-1}) . + * + * Here, INT (i) is a four-octet encoding of the integer i, most + * significant octet first. + * + * 4. Concatenate the blocks and extract the first dkLen octets to + * produce a derived key DK: + * + * DK = T_1 || T_2 || ... || T_l<0..r-1> + * + * 5. Output the derived key DK. + * + * Note. The construction of the function F follows a "belt-and- + * suspenders" approach. The iterates U_i are computed recursively to + * remove a degree of parallelism from an opponent; they are exclusive- + * ored together to reduce concerns about the recursion degenerating + * into a small set of values. + * + */ + + if(gcry_md_open(&prf, PRF, GCRY_MD_FLAG_HMAC)) + return -EINVAL; + + if (gcry_md_setkey(prf, P, Plen)) + goto out; + + for (i = 1; (uint) i <= l; i++) { + memset(T, 0, hLen); + + for (u = 1; u <= c ; u++) { + gcry_md_reset(prf); + + if (u == 1) { + memcpy(tmp, S, Slen); + tmp[Slen + 0] = (i & 0xff000000) >> 24; + tmp[Slen + 1] = (i & 0x00ff0000) >> 16; + tmp[Slen + 2] = (i & 0x0000ff00) >> 8; + tmp[Slen + 3] = (i & 0x000000ff) >> 0; + + gcry_md_write(prf, tmp, tmplen); + } else { + gcry_md_write(prf, U, hLen); + } + + p = gcry_md_read(prf, PRF); + if (p == NULL) + goto out; + + memcpy(U, p, hLen); + + for (k = 0; (uint) k < hLen; k++) + T[k] ^= U[k]; + + if (perfcheck && __PBKDF2_performance) { + rc = 0; + goto out; + } + + if (perfcheck) + __PBKDF2_global_j++; + } + + memcpy(DK + (i - 1) * hLen, T, (uint) i == l ? r : hLen); + } + rc = 0; +out: + gcry_md_close(prf); + return rc; +} + +int PBKDF2_HMAC(const char *hash, + const char *password, size_t passwordLen, + const char *salt, size_t saltLen, unsigned int iterations, + char *dKey, size_t dKeyLen) +{ + return pkcs5_pbkdf2(hash, password, passwordLen, salt, saltLen, + iterations, (unsigned int)dKeyLen, dKey, 0); +} + +int PBKDF2_HMAC_ready(const char *hash) +{ + int hash_id = gcry_md_map_name(hash); + + if (!hash_id) + return -EINVAL; + + /* Used hash must have at least 160 bits */ + if (gcry_md_get_algo_dlen(hash_id) < 20) + return -EINVAL; + + return 1; +} + +static void sigvtalarm(int foo) +{ + __PBKDF2_performance = __PBKDF2_global_j; +} + +/* This code benchmarks PBKDF2 and returns iterations/second using wth specified hash */ +int PBKDF2_performance_check(const char *hash, uint64_t *iter) +{ + int r; + char buf; + struct itimerval it; + + if (__PBKDF2_global_j) + return -EBUSY; + + if (!PBKDF2_HMAC_ready(hash)) + return -EINVAL; + + signal(SIGVTALRM,sigvtalarm); + it.it_interval.tv_usec = 0; + it.it_interval.tv_sec = 0; + it.it_value.tv_usec = 0; + it.it_value.tv_sec = 1; + if (setitimer (ITIMER_VIRTUAL, &it, NULL) < 0) + return -EINVAL; + + r = pkcs5_pbkdf2(hash, "foo", 3, "bar", 3, ~(0U), 1, &buf, 1); + + *iter = __PBKDF2_performance; + __PBKDF2_global_j = 0; + __PBKDF2_performance = 0; + return r; +} diff --git a/lib/luks1/pbkdf.h b/lib/luks1/pbkdf.h new file mode 100644 index 0000000..9bbd8f3 --- /dev/null +++ b/lib/luks1/pbkdf.h @@ -0,0 +1,15 @@ +#ifndef INCLUDED_CRYPTSETUP_LUKS_PBKDF_H +#define INCLUDED_CRYPTSETUP_LUKS_PBKDF_H + +#include <stddef.h> + +int PBKDF2_HMAC(const char *hash, + const char *password, size_t passwordLen, + const char *salt, size_t saltLen, unsigned int iterations, + char *dKey, size_t dKeyLen); + + +int PBKDF2_performance_check(const char *hash, uint64_t *iter); +int PBKDF2_HMAC_ready(const char *hash); + +#endif |