diff options
author | Dina K Nimeh <Dina.Nimeh@Sun.Com> | 2008-12-08 16:24:12 -0800 |
---|---|---|
committer | Dina K Nimeh <Dina.Nimeh@Sun.Com> | 2008-12-08 16:24:12 -0800 |
commit | 7d82f0f819f2fde1c321b8ac4ff15e494c5eb4b1 (patch) | |
tree | b85f9a1b9e0465449f9183491c944bf63ba3e8fa /usr/src | |
parent | 14cd9973e77e9bfa1eca7f8e24ff5786853576c5 (diff) | |
download | illumos-gate-7d82f0f819f2fde1c321b8ac4ff15e494c5eb4b1.tar.gz |
PSARC 2007/001 lofi(7d) crypto support
4926125 lofi(7d) should support encrypted block devices
6236948 need userland interface to list crypto algorithms available to kernel consumers
Diffstat (limited to 'usr/src')
-rw-r--r-- | usr/src/cmd/lofiadm/Makefile | 7 | ||||
-rw-r--r-- | usr/src/cmd/lofiadm/main.c | 1212 | ||||
-rw-r--r-- | usr/src/cmd/lofiadm/utils.c | 7 | ||||
-rw-r--r-- | usr/src/cmd/lofiadm/utils.h | 7 | ||||
-rw-r--r-- | usr/src/uts/common/crypto/api/kcf_miscapi.c | 15 | ||||
-rw-r--r-- | usr/src/uts/common/crypto/io/crypto.c | 191 | ||||
-rw-r--r-- | usr/src/uts/common/io/lofi.c | 797 | ||||
-rw-r--r-- | usr/src/uts/common/sys/crypto/api.h | 22 | ||||
-rw-r--r-- | usr/src/uts/common/sys/crypto/ioctl.h | 44 | ||||
-rw-r--r-- | usr/src/uts/common/sys/lofi.h | 54 |
10 files changed, 2061 insertions, 295 deletions
diff --git a/usr/src/cmd/lofiadm/Makefile b/usr/src/cmd/lofiadm/Makefile index a8a4a2b4a1..1899f85fb3 100644 --- a/usr/src/cmd/lofiadm/Makefile +++ b/usr/src/cmd/lofiadm/Makefile @@ -20,11 +20,9 @@ # # # -# Copyright 2007 Sun Microsystems, Inc. All rights reserved. +# Copyright 2008 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # -#pragma ident "%Z%%M% %I% %E% SMI" -# PROG= lofiadm OBJS= main.o utils.o @@ -33,7 +31,8 @@ POFILES= $(OBJS:%.o=%.po) include ../Makefile.cmd -LDLIBS += -ldevinfo +CPPFLAGS += -I $(SRC)/common/crypto +LDLIBS += -ldevinfo -lpkcs11 -lcryptoutil .KEEP_STATE: diff --git a/usr/src/cmd/lofiadm/main.c b/usr/src/cmd/lofiadm/main.c index a73d123221..b01ef37706 100644 --- a/usr/src/cmd/lofiadm/main.c +++ b/usr/src/cmd/lofiadm/main.c @@ -48,21 +48,75 @@ #include <libgen.h> #include <ctype.h> #include <dlfcn.h> +#include <limits.h> +#include <security/cryptoki.h> +#include <cryptoutil.h> +#include <sys/crypto/ioctl.h> +#include <sys/crypto/ioctladmin.h> #include "utils.h" +/* Only need the IV len #defines out of these files, nothing else. */ +#include <aes/aes_impl.h> +#include <des/des_impl.h> +#include <blowfish/blowfish_impl.h> + static const char USAGE[] = - "Usage: %s -a file [ device ]\n" + "Usage: %s -a file [ device ] " + " [-c aes-128-cbc|aes-192-cbc|aes-256-cbc|des3-cbc|blowfish-cbc]" + " [-e] [-k keyfile] [-T [token]:[manuf]:[serial]:key]\n" " %s -d file | device\n" " %s -C [algorithm] [-s segment_size] file\n" " %s -U file\n" " %s [ file | device ]\n"; -static const char *pname; -static int addflag = 0; -static int deleteflag = 0; -static int errflag = 0; -static int compressflag = 0; -static int uncompressflag = 0; +typedef struct token_spec { + char *name; + char *mfr; + char *serno; + char *key; +} token_spec_t; + +typedef struct mech_alias { + char *alias; + CK_MECHANISM_TYPE type; + char *name; /* for ioctl */ + char *iv_name; /* for ioctl */ + size_t iv_len; /* for ioctl */ + iv_method_t iv_type; /* for ioctl */ + size_t min_keysize; /* in bytes */ + size_t max_keysize; /* in bytes */ + token_spec_t *token; + CK_SLOT_ID slot; +} mech_alias_t; + +static mech_alias_t mech_aliases[] = { + /* Preferred one should always be listed first. */ + { "aes-256-cbc", CKM_AES_CBC, "CKM_AES_CBC", "CKM_AES_ECB", AES_IV_LEN, + IVM_ENC_BLKNO, ULONG_MAX, 0L, NULL, (CK_SLOT_ID) -1 }, + { "aes-192-cbc", CKM_AES_CBC, "CKM_AES_CBC", "CKM_AES_ECB", AES_IV_LEN, + IVM_ENC_BLKNO, ULONG_MAX, 0L, NULL, (CK_SLOT_ID) -1 }, + { "aes-128-cbc", CKM_AES_CBC, "CKM_AES_CBC", "CKM_AES_ECB", AES_IV_LEN, + IVM_ENC_BLKNO, ULONG_MAX, 0L, NULL, (CK_SLOT_ID) -1 }, + { "des3-cbc", CKM_DES3_CBC, "CKM_DES3_CBC", "CKM_DES3_ECB", DES_IV_LEN, + IVM_ENC_BLKNO, ULONG_MAX, 0L, NULL, (CK_SLOT_ID)-1 }, + { "blowfish-cbc", CKM_BLOWFISH_CBC, "CKM_BLOWFISH_CBC", + "CKM_BLOWFISH_ECB", BLOWFISH_IV_LEN, IVM_ENC_BLKNO, ULONG_MAX, + 0L, NULL, (CK_SLOT_ID)-1 } + /* + * A cipher without an iv requirement would look like this: + * { "aes-xex", CKM_AES_XEX, "CKM_AES_XEX", NULL, 0, + * IVM_NONE, ULONG_MAX, 0L, NULL, (CK_SLOT_ID)-1 } + */ +}; + +int mech_aliases_count = (sizeof (mech_aliases) / sizeof (mech_alias_t)); + +/* Preferred cipher, if one isn't specified on command line. */ +#define DEFAULT_CIPHER (&mech_aliases[0]) + +#define DEFAULT_CIPHER_NUM 64 /* guess # kernel ciphers available */ +#define DEFAULT_MECHINFO_NUM 16 /* guess # kernel mechs available */ +#define MIN_PASSLEN 8 /* min acceptable passphrase size */ static int gzip_compress(void *src, size_t srclen, void *dst, size_t *destlen, int level); @@ -73,9 +127,9 @@ lofi_compress_info_t lofi_compress_table[LOFI_COMPRESS_FUNCTIONS] = { {NULL, gzip_compress, 9, "gzip-9"} }; +/* For displaying lofi mappings */ #define FORMAT "%-20s %-30s %s\n" -#define NONE "-" -#define COMPRESS "Compressed" + #define COMPRESS_ALGORITHM "gzip" #define COMPRESS_THRESHOLD 2048 #define SEGSIZE 131072 @@ -115,52 +169,11 @@ static int gzip_compress(void *src, size_t srclen, void *dst, return (0); } -/* - * Print the list of all the mappings. Including a header. - */ -static void -print_mappings(int fd) -{ - struct lofi_ioctl li; - int minor; - int maxminor; - char path[MAXPATHLEN]; - char options[MAXPATHLEN]; - - li.li_minor = 0; - if (ioctl(fd, LOFI_GET_MAXMINOR, &li) == -1) { - perror("ioctl"); - exit(E_ERROR); - } - - maxminor = li.li_minor; - - (void) printf(FORMAT, "Block Device", "File", "Options"); - for (minor = 1; minor <= maxminor; minor++) { - li.li_minor = minor; - if (ioctl(fd, LOFI_GET_FILENAME, &li) == -1) { - if (errno == ENXIO) - continue; - perror("ioctl"); - break; - } - (void) snprintf(path, sizeof (path), "/dev/%s/%d", - LOFI_BLOCK_NAME, minor); - if (li.li_algorithm[0] == '\0') - (void) snprintf(options, sizeof (options), "%s", NONE); - else - (void) snprintf(options, sizeof (options), - COMPRESS "(%s)", li.li_algorithm); - - (void) printf(FORMAT, path, li.li_filename, options); - } -} - static void -usage(void) +usage(const char *pname) { - (void) fprintf(stderr, gettext(USAGE), pname, pname, - pname, pname, pname); + (void) fprintf(stderr, gettext(USAGE), pname, pname, pname, + pname, pname); exit(E_USAGE); } @@ -203,7 +216,6 @@ wait_until_dev_complete(int minor) char charpath[MAXPATHLEN]; di_devlink_handle_t hdl; - (void) snprintf(blkpath, sizeof (blkpath), "/dev/%s/%d", LOFI_BLOCK_NAME, minor); (void) snprintf(charpath, sizeof (charpath), "/dev/%s/%d", @@ -224,19 +236,13 @@ wait_until_dev_complete(int minor) * only fail if the caller is non-root. In that case, wait for * link creation via sysevents. */ - cursleep = 0; - while (cursleep < maxsleep) { - if ((stat64(blkpath, &buf) == -1) || - (stat64(charpath, &buf) == -1)) { - (void) sleep(sleeptime); - cursleep += sleeptime; - continue; - } - return; + for (cursleep = 0; cursleep < maxsleep; cursleep += sleeptime) { + if (stat64(blkpath, &buf) == 0 && stat64(charpath, &buf) == 0) + return; + (void) sleep(sleeptime); } /* one last try */ - out: if (stat64(blkpath, &buf) == -1) { die(gettext("%s was not created"), blkpath); @@ -247,48 +253,89 @@ out: } /* + * Map the file and return the minor number the driver picked for the file + * DO NOT use this function if the filename is actually the device name. + */ +static int +lofi_map_file(int lfd, struct lofi_ioctl li, const char *filename) +{ + int minor; + + li.li_minor = 0; + (void) strlcpy(li.li_filename, filename, sizeof (li.li_filename)); + minor = ioctl(lfd, LOFI_MAP_FILE, &li); + if (minor == -1) { + if (errno == ENOTSUP) + warn(gettext("encrypting compressed files is " + "unsupported")); + die(gettext("could not map file %s"), filename); + } + wait_until_dev_complete(minor); + return (minor); +} + +/* * Add a device association. If devicename is NULL, let the driver * pick a device. */ static void add_mapping(int lfd, const char *devicename, const char *filename, - int *minor_created, int suppress) + mech_alias_t *cipher, const char *rkey, size_t rksz) { struct lofi_ioctl li; - int minor; - if (devicename == NULL) { - /* pick one */ - li.li_minor = 0; - (void) strlcpy(li.li_filename, filename, - sizeof (li.li_filename)); - minor = ioctl(lfd, LOFI_MAP_FILE, &li); - if (minor == -1) { - die(gettext("could not map file %s"), filename); + li.li_crypto_enabled = B_FALSE; + if (cipher != NULL) { + /* set up encryption for mapped file */ + li.li_crypto_enabled = B_TRUE; + (void) strlcpy(li.li_cipher, cipher->name, + sizeof (li.li_cipher)); + if (rksz > sizeof (li.li_key)) { + die(gettext("key too large")); } - wait_until_dev_complete(minor); - /* print one picked */ - if (!suppress) - (void) printf("/dev/%s/%d\n", LOFI_BLOCK_NAME, minor); - - /* fill in the minor if needed */ - if (minor_created != NULL) { - *minor_created = minor; + bcopy(rkey, li.li_key, rksz); + li.li_key_len = rksz << 3; /* convert to bits */ + + li.li_iv_type = cipher->iv_type; + li.li_iv_len = cipher->iv_len; /* 0 when no iv needed */ + switch (cipher->iv_type) { + case IVM_ENC_BLKNO: + (void) strlcpy(li.li_iv_cipher, cipher->iv_name, + sizeof (li.li_iv_cipher)); + break; + case IVM_NONE: + /* FALLTHROUGH */ + default: + break; } + } + + if (devicename == NULL) { + int minor; + + /* pick one via the driver */ + minor = lofi_map_file(lfd, li, filename); + /* if mapping succeeds, print the one picked */ + (void) printf("/dev/%s/%d\n", LOFI_BLOCK_NAME, minor); return; } + /* use device we were given */ - minor = name_to_minor(devicename); - if (minor == 0) { + li.li_minor = name_to_minor(devicename); + if (li.li_minor == 0) { die(gettext("malformed device name %s\n"), devicename); } (void) strlcpy(li.li_filename, filename, sizeof (li.li_filename)); - li.li_minor = minor; + + /* if device is already in use li.li_minor won't change */ if (ioctl(lfd, LOFI_MAP_FILE_MINOR, &li) == -1) { + if (errno == ENOTSUP) + warn(gettext("encrypting compressed files is " + "unsupported")); die(gettext("could not map file %s to %s"), filename, devicename); } - wait_until_dev_complete(minor); + wait_until_dev_complete(li.li_minor); } /* @@ -325,6 +372,9 @@ delete_mapping(int lfd, const char *devicename, const char *filename, } } +/* + * Show filename given devicename, or devicename given filename. + */ static void print_one_mapping(int lfd, const char *devicename, const char *filename) { @@ -354,6 +404,762 @@ print_one_mapping(int lfd, const char *devicename, const char *filename) } /* + * Print the list of all the mappings, including a header. + */ +static void +print_mappings(int fd) +{ + struct lofi_ioctl li; + int minor; + int maxminor; + char path[MAXPATHLEN]; + char options[MAXPATHLEN]; + + li.li_minor = 0; + if (ioctl(fd, LOFI_GET_MAXMINOR, &li) == -1) { + die("ioctl"); + } + maxminor = li.li_minor; + + (void) printf(FORMAT, gettext("Block Device"), gettext("File"), + gettext("Options")); + for (minor = 1; minor <= maxminor; minor++) { + li.li_minor = minor; + if (ioctl(fd, LOFI_GET_FILENAME, &li) == -1) { + if (errno == ENXIO) + continue; + warn("ioctl"); + break; + } + (void) snprintf(path, sizeof (path), "/dev/%s/%d", + LOFI_BLOCK_NAME, minor); + /* + * Encrypted lofi and compressed lofi are mutually exclusive. + */ + if (li.li_crypto_enabled) + (void) snprintf(options, sizeof (options), + gettext("Encrypted")); + else if (li.li_algorithm[0] != '\0') + (void) snprintf(options, sizeof (options), + gettext("Compressed(%s)"), li.li_algorithm); + else + (void) snprintf(options, sizeof (options), "-"); + + (void) printf(FORMAT, path, li.li_filename, options); + } +} + +/* + * Verify the cipher selected by user. + */ +static mech_alias_t * +ciph2mech(const char *alias) +{ + int i; + + for (i = 0; i < mech_aliases_count; i++) { + if (strcasecmp(alias, mech_aliases[i].alias) == 0) + return (&mech_aliases[i]); + } + return (NULL); +} + +/* + * Verify user selected cipher is also available in kernel. + * + * While traversing kernel list of mechs, if the cipher is supported in the + * kernel for both encryption and decryption, it also picks up the min/max + * key size. + */ +static boolean_t +kernel_cipher_check(mech_alias_t *cipher) +{ + boolean_t ciph_ok = B_FALSE; + boolean_t iv_ok = B_FALSE; + int i; + int count; + crypto_get_mechanism_list_t *kciphers = NULL; + crypto_get_all_mechanism_info_t *kinfo = NULL; + int fd = -1; + size_t keymin; + size_t keymax; + + /* if cipher doesn't need iv generating mech, bypass that check now */ + if (cipher->iv_name == NULL) + iv_ok = B_TRUE; + + /* allocate some space for the list of kernel ciphers */ + count = DEFAULT_CIPHER_NUM; + kciphers = malloc(sizeof (crypto_get_mechanism_list_t) + + sizeof (crypto_mech_name_t) * (count - 1)); + if (kciphers == NULL) + die(gettext("failed to allocate memory for list of " + "kernel mechanisms")); + kciphers->ml_count = count; + + /* query crypto device to get list of kernel ciphers */ + if ((fd = open("/dev/crypto", O_RDWR)) == -1) { + warn(gettext("failed to open %s"), "/dev/crypto"); + goto kcc_out; + } + + if (ioctl(fd, CRYPTO_GET_MECHANISM_LIST, kciphers) == -1) { + warn(gettext("CRYPTO_GET_MECHANISM_LIST ioctl failed")); + goto kcc_out; + } + + if (kciphers->ml_return_value == CRYPTO_BUFFER_TOO_SMALL) { + count = kciphers->ml_count; + free(kciphers); + kciphers = malloc(sizeof (crypto_get_mechanism_list_t) + + sizeof (crypto_mech_name_t) * (count - 1)); + if (kciphers == NULL) { + warn(gettext("failed to allocate memory for list of " + "kernel mechanisms")); + goto kcc_out; + } + kciphers->ml_count = count; + + if (ioctl(fd, CRYPTO_GET_MECHANISM_LIST, kciphers) == -1) { + warn(gettext("CRYPTO_GET_MECHANISM_LIST ioctl failed")); + goto kcc_out; + } + } + + if (kciphers->ml_return_value != CRYPTO_SUCCESS) { + warn(gettext( + "CRYPTO_GET_MECHANISM_LIST ioctl return value = %d\n"), + kciphers->ml_return_value); + goto kcc_out; + } + + /* + * scan list of kernel ciphers looking for the selected one and if + * it needs an iv generated using another cipher, also look for that + * additional cipher to be used for generating the iv + */ + count = kciphers->ml_count; + for (i = 0; i < count && !(ciph_ok && iv_ok); i++) { + if (!ciph_ok && + strcasecmp(cipher->name, kciphers->ml_list[i]) == 0) + ciph_ok = B_TRUE; + if (!iv_ok && + strcasecmp(cipher->iv_name, kciphers->ml_list[i]) == 0) + iv_ok = B_TRUE; + } + free(kciphers); + kciphers = NULL; + + if (!ciph_ok) + warn(gettext("%s mechanism not supported in kernel\n"), + cipher->name); + if (!iv_ok) + warn(gettext("%s mechanism not supported in kernel\n"), + cipher->iv_name); + + if (ciph_ok) { + /* Get the details about the user selected cipher */ + count = DEFAULT_MECHINFO_NUM; + kinfo = malloc(sizeof (crypto_get_all_mechanism_info_t) + + sizeof (crypto_mechanism_info_t) * (count - 1)); + if (kinfo == NULL) { + warn(gettext("failed to allocate memory for " + "kernel mechanism info")); + goto kcc_out; + } + kinfo->mi_count = count; + (void) strlcpy(kinfo->mi_mechanism_name, cipher->name, + CRYPTO_MAX_MECH_NAME); + + if (ioctl(fd, CRYPTO_GET_ALL_MECHANISM_INFO, kinfo) == -1) { + warn(gettext( + "CRYPTO_GET_ALL_MECHANISM_INFO ioctl failed")); + goto kcc_out; + } + + if (kinfo->mi_return_value == CRYPTO_BUFFER_TOO_SMALL) { + count = kinfo->mi_count; + free(kinfo); + kinfo = malloc( + sizeof (crypto_get_all_mechanism_info_t) + + sizeof (crypto_mechanism_info_t) * (count - 1)); + if (kinfo == NULL) { + warn(gettext("failed to allocate memory for " + "kernel mechanism info")); + goto kcc_out; + } + kinfo->mi_count = count; + (void) strlcpy(kinfo->mi_mechanism_name, cipher->name, + CRYPTO_MAX_MECH_NAME); + + if (ioctl(fd, CRYPTO_GET_ALL_MECHANISM_INFO, kinfo) == + -1) { + warn(gettext("CRYPTO_GET_ALL_MECHANISM_INFO " + "ioctl failed")); + goto kcc_out; + } + } + + if (kinfo->mi_return_value != CRYPTO_SUCCESS) { + warn(gettext("CRYPTO_GET_ALL_MECHANISM_INFO ioctl " + "return value = %d\n"), kinfo->mi_return_value); + goto kcc_out; + } + + /* Set key min and max size */ + count = kinfo->mi_count; + i = 0; + if (i < count) { + keymin = kinfo->mi_list[i].mi_min_key_size; + keymax = kinfo->mi_list[i].mi_max_key_size; + if (kinfo->mi_list[i].mi_keysize_unit & + CRYPTO_KEYSIZE_UNIT_IN_BITS) { + keymin = CRYPTO_BITS2BYTES(keymin); + keymax = CRYPTO_BITS2BYTES(keymax); + + } + cipher->min_keysize = keymin; + cipher->max_keysize = keymax; + } + free(kinfo); + kinfo = NULL; + + if (i == count) { + (void) close(fd); + die(gettext( + "failed to find usable %s kernel mechanism, " + "use \"cryptoadm list -m\" to find available " + "mechanisms\n"), + cipher->name); + } + } + + /* Note: key min/max, unit size, usage for iv cipher are not checked. */ + + return (ciph_ok && iv_ok); + +kcc_out: + if (kinfo != NULL) + free(kinfo); + if (kciphers != NULL) + free(kciphers); + if (fd != -1) + (void) close(fd); + return (B_FALSE); +} + +/* + * Break up token spec into its components (non-destructive) + */ +static token_spec_t * +parsetoken(char *spec) +{ +#define FLD_NAME 0 +#define FLD_MANUF 1 +#define FLD_SERIAL 2 +#define FLD_LABEL 3 +#define NFIELDS 4 +#define nullfield(i) ((field[(i)+1] - field[(i)]) <= 1) +#define copyfield(fld, i) \ + { \ + int n; \ + (fld) = NULL; \ + if ((n = (field[(i)+1] - field[(i)])) > 1) { \ + if (((fld) = malloc(n)) != NULL) { \ + (void) strncpy((fld), field[(i)], n); \ + ((fld))[n - 1] = '\0'; \ + } \ + } \ + } + + int i; + char *field[NFIELDS + 1]; /* +1 to catch extra delimiters */ + token_spec_t *ti = NULL; + + if (spec == NULL) + return (NULL); + + /* + * Correct format is "[name]:[manuf]:[serial]:key". Can't use + * strtok because it treats ":::key" and "key:::" and "key" all + * as the same thing, and we can't have the :s compressed away. + */ + field[0] = spec; + for (i = 1; i < NFIELDS + 1; i++) { + field[i] = strchr(field[i-1], ':'); + if (field[i] == NULL) + break; + field[i]++; + } + if (i < NFIELDS) /* not enough fields */ + return (NULL); + if (field[NFIELDS] != NULL) /* too many fields */ + return (NULL); + field[NFIELDS] = strchr(field[NFIELDS-1], '\0') + 1; + + /* key label can't be empty */ + if (nullfield(FLD_LABEL)) + return (NULL); + + ti = malloc(sizeof (token_spec_t)); + if (ti == NULL) + return (NULL); + + copyfield(ti->name, FLD_NAME); + copyfield(ti->mfr, FLD_MANUF); + copyfield(ti->serno, FLD_SERIAL); + copyfield(ti->key, FLD_LABEL); + + /* + * If token specified and it only contains a key label, then + * search all tokens for the key, otherwise only those with + * matching name, mfr, and serno are used. + */ + /* + * That's how we'd like it to be, however, if only the key label + * is specified, default to using softtoken. It's easier. + */ + if (ti->name == NULL && ti->mfr == NULL && ti->serno == NULL) + ti->name = strdup(pkcs11_default_token()); + return (ti); +} + +/* + * PBE the passphrase into a raw key + */ +static void +getkeyfromuser(mech_alias_t *cipher, char **raw_key, size_t *raw_key_sz) +{ + CK_SESSION_HANDLE sess; + CK_RV rv; + char *pass = NULL; + size_t passlen = 0; + void *salt = NULL; /* don't use NULL, see note on salt below */ + size_t saltlen = 0; + CK_KEY_TYPE ktype; + void *kvalue; + size_t klen; + + /* did init_crypto find a slot that supports this cipher? */ + if (cipher->slot == (CK_SLOT_ID)-1 || cipher->max_keysize == 0) { + rv = CKR_MECHANISM_INVALID; + goto cleanup; + } + + rv = pkcs11_mech2keytype(cipher->type, &ktype); + if (rv != CKR_OK) + goto cleanup; + + /* + * use the passphrase to generate a PBE PKCS#5 secret key and + * retrieve the raw key data to eventually pass it to the kernel; + */ + rv = C_OpenSession(cipher->slot, CKF_SERIAL_SESSION, NULL, NULL, &sess); + if (rv != CKR_OK) + goto cleanup; + + /* get user passphrase with 8 byte minimum */ + if (pkcs11_get_pass(NULL, &pass, &passlen, MIN_PASSLEN, B_TRUE) < 0) { + die(gettext("passphrases do not match\n")); + } + + /* + * salt should not be NULL, or else pkcs11_PasswdToKey() will + * complain about CKR_MECHANISM_PARAM_INVALID; the following is + * to make up for not having a salt until a proper one is used + */ + salt = pass; + saltlen = passlen; + + klen = cipher->max_keysize; + rv = pkcs11_PasswdToKey(sess, pass, passlen, salt, saltlen, ktype, + cipher->max_keysize, &kvalue, &klen); + + (void) C_CloseSession(sess); + + if (rv != CKR_OK) { + goto cleanup; + } + + /* assert(klen == cipher->max_keysize); */ + *raw_key_sz = klen; + *raw_key = (char *)kvalue; + return; + +cleanup: + die(gettext("failed to generate %s key from passphrase: %s"), + cipher->alias, pkcs11_strerror(rv)); +} + +/* + * Read raw key from file; also handles ephemeral keys. + */ +void +getkeyfromfile(const char *pathname, mech_alias_t *cipher, char **key, + size_t *ksz) +{ + int fd; + struct stat sbuf; + boolean_t notplain = B_FALSE; + ssize_t cursz; + ssize_t nread; + + /* ephemeral keys are just random data */ + if (pathname == NULL) { + *ksz = cipher->max_keysize; + *key = malloc(*ksz); + if (*key == NULL) + die(gettext("failed to allocate memory for" + " ephemeral key")); + if (pkcs11_random_data(*key, *ksz) < 0) { + free(*key); + die(gettext("failed to get enough random data")); + } + return; + } + + /* + * If the remaining section of code didn't also check for secure keyfile + * permissions and whether the key is within cipher min and max lengths, + * (or, if those things moved out of this block), we could have had: + * if (pkcs11_read_data(pathname, key, ksz) < 0) + * handle_error(); + */ + + if ((fd = open(pathname, O_RDONLY, 0)) == -1) + die(gettext("open of keyfile (%s) failed"), pathname); + + if (fstat(fd, &sbuf) == -1) + die(gettext("fstat of keyfile (%s) failed"), pathname); + + if (S_ISREG(sbuf.st_mode)) { + if ((sbuf.st_mode & (S_IWGRP | S_IWOTH)) != 0) + die(gettext("insecure permissions on keyfile %s\n"), + pathname); + + *ksz = sbuf.st_size; + if (*ksz < cipher->min_keysize || cipher->max_keysize < *ksz) { + warn(gettext("%s: invalid keysize: %d\n"), + pathname, (int)*ksz); + die(gettext("\t%d <= keysize <= %d\n"), + cipher->min_keysize, cipher->max_keysize); + } + } else { + *ksz = cipher->max_keysize; + notplain = B_TRUE; + } + + *key = malloc(*ksz); + if (*key == NULL) + die(gettext("failed to allocate memory for key from file")); + + for (cursz = 0, nread = 0; cursz < *ksz; cursz += nread) { + nread = read(fd, *key, *ksz); + if (nread > 0) + continue; + /* + * nread == 0. If it's not a regular file we were trying to + * get the maximum keysize of data possible for this cipher. + * But if we've got at least the minimum keysize of data, + * round down to the nearest keysize unit and call it good. + * If we haven't met the minimum keysize, that's an error. + * If it's a regular file, nread = 0 is also an error. + */ + if (nread == 0 && notplain && cursz >= cipher->min_keysize) { + *ksz = (cursz / cipher->min_keysize) * + cipher->min_keysize; + break; + } + die(gettext("%s: can't read all keybytes"), pathname); + } + (void) close(fd); +} + +/* + * Read the raw key from token, or from a file that was wrapped with a + * key from token + */ +void +getkeyfromtoken(CK_SESSION_HANDLE sess, + token_spec_t *token, const char *keyfile, mech_alias_t *cipher, + char **raw_key, size_t *raw_key_sz) +{ + CK_RV rv = CKR_OK; + CK_BBOOL trueval = B_TRUE; + CK_OBJECT_CLASS kclass; /* secret key or RSA private key */ + CK_KEY_TYPE ktype; /* from selected cipher or CKK_RSA */ + CK_KEY_TYPE raw_ktype; /* from selected cipher */ + CK_ATTRIBUTE key_tmpl[] = { + { CKA_CLASS, NULL, 0 }, /* re-used for token key and unwrap */ + { CKA_KEY_TYPE, NULL, 0 }, /* ditto */ + { CKA_LABEL, NULL, 0 }, + { CKA_TOKEN, NULL, 0 }, + { CKA_PRIVATE, NULL, 0 } + }; + CK_ULONG attrs = sizeof (key_tmpl) / sizeof (CK_ATTRIBUTE); + int i; + char *pass = NULL; + size_t passlen = 0; + CK_OBJECT_HANDLE obj, rawobj; + CK_ULONG num_objs = 1; /* just want to find 1 token key */ + CK_MECHANISM unwrap = { CKM_RSA_PKCS, NULL, 0 }; + char *rkey; + size_t rksz; + + if (token == NULL || token->key == NULL) + return; + + /* did init_crypto find a slot that supports this cipher? */ + if (cipher->slot == (CK_SLOT_ID)-1 || cipher->max_keysize == 0) { + die(gettext("failed to find any cryptographic provider, " + "use \"cryptoadm list -p\" to find providers: %s\n"), + pkcs11_strerror(CKR_MECHANISM_INVALID)); + } + + if (pkcs11_get_pass(token->name, &pass, &passlen, 0, B_FALSE) < 0) + die(gettext("unable to get passphrase")); + + /* use passphrase to login to token */ + if (pass != NULL && passlen > 0) { + rv = C_Login(sess, CKU_USER, (CK_UTF8CHAR_PTR)pass, passlen); + if (rv != CKR_OK) { + die(gettext("cannot login to the token %s: %s\n"), + token->name, pkcs11_strerror(rv)); + } + } + + rv = pkcs11_mech2keytype(cipher->type, &raw_ktype); + if (rv != CKR_OK) { + die(gettext("failed to get key type for cipher %s: %s\n"), + cipher->name, pkcs11_strerror(rv)); + } + + /* + * If no keyfile was given, then the token key is secret key to + * be used for encryption/decryption. Otherwise, the keyfile + * contains a wrapped secret key, and the token is actually the + * unwrapping RSA private key. + */ + if (keyfile == NULL) { + kclass = CKO_SECRET_KEY; + ktype = raw_ktype; + } else { + kclass = CKO_PRIVATE_KEY; + ktype = CKK_RSA; + } + + /* Find the key in the token first */ + for (i = 0; i < attrs; i++) { + switch (key_tmpl[i].type) { + case CKA_CLASS: + key_tmpl[i].pValue = &kclass; + key_tmpl[i].ulValueLen = sizeof (kclass); + break; + case CKA_KEY_TYPE: + key_tmpl[i].pValue = &ktype; + key_tmpl[i].ulValueLen = sizeof (ktype); + break; + case CKA_LABEL: + key_tmpl[i].pValue = token->key; + key_tmpl[i].ulValueLen = strlen(token->key); + break; + case CKA_TOKEN: + key_tmpl[i].pValue = &trueval; + key_tmpl[i].ulValueLen = sizeof (trueval); + break; + case CKA_PRIVATE: + key_tmpl[i].pValue = &trueval; + key_tmpl[i].ulValueLen = sizeof (trueval); + break; + default: + break; + } + } + rv = C_FindObjectsInit(sess, key_tmpl, attrs); + if (rv != CKR_OK) + die(gettext("cannot find key %s: %s\n"), token->key, + pkcs11_strerror(rv)); + rv = C_FindObjects(sess, &obj, 1, &num_objs); + (void) C_FindObjectsFinal(sess); + + if (num_objs == 0) { + die(gettext("cannot find key %s\n"), token->key); + } else if (rv != CKR_OK) { + die(gettext("cannot find key %s: %s\n"), token->key, + pkcs11_strerror(rv)); + } + + /* + * No keyfile means when token key is found, convert it to raw key, + * and done. Otherwise still need do an unwrap to create yet another + * obj and that needs to be converted to raw key before we're done. + */ + if (keyfile == NULL) { + /* obj contains raw key, extract it */ + rv = pkcs11_ObjectToKey(sess, obj, (void **)&rkey, &rksz, + B_FALSE); + if (rv != CKR_OK) { + die(gettext("failed to get key value for %s" + " from token %s, %s\n"), token->key, + token->name, pkcs11_strerror(rv)); + } + } else { + getkeyfromfile(keyfile, cipher, &rkey, &rksz); + + /* + * Got the wrapping RSA obj and the wrapped key from file. + * Unwrap the key from file with RSA obj to get rawkey obj. + */ + + /* re-use the first two attributes of key_tmpl */ + kclass = CKO_SECRET_KEY; + ktype = raw_ktype; + + rv = C_UnwrapKey(sess, &unwrap, obj, (CK_BYTE_PTR)rkey, + rksz, key_tmpl, 2, &rawobj); + if (rv != CKR_OK) { + die(gettext("failed to unwrap key in keyfile %s," + " %s\n"), keyfile, pkcs11_strerror(rv)); + } + /* rawobj contains raw key, extract it */ + rv = pkcs11_ObjectToKey(sess, rawobj, (void **)&rkey, &rksz, + B_TRUE); + if (rv != CKR_OK) { + die(gettext("failed to get unwrapped key value for" + " key in keyfile %s, %s\n"), keyfile, + pkcs11_strerror(rv)); + } + } + + /* validate raw key size */ + if (rksz < cipher->min_keysize || cipher->max_keysize < rksz) { + warn(gettext("%s: invalid keysize: %d\n"), keyfile, (int)rksz); + die(gettext("\t%d <= keysize <= %d\n"), cipher->min_keysize, + cipher->max_keysize); + } + + *raw_key_sz = rksz; + *raw_key = (char *)rkey; +} + +/* + * Set up cipher key limits and verify PKCS#11 can be done + * match_token_cipher is the function pointer used by + * pkcs11_GetCriteriaSession() init_crypto. + */ +boolean_t +match_token_cipher(CK_SLOT_ID slot_id, void *args, CK_RV *rv) +{ + token_spec_t *token; + mech_alias_t *cipher; + CK_TOKEN_INFO tokinfo; + CK_MECHANISM_INFO mechinfo; + boolean_t token_match; + + /* + * While traversing slot list, pick up the following info per slot: + * - if token specified, whether it matches this slot's token info + * - if the slot supports the PKCS#5 PBKD2 cipher + * + * If the user said on the command line + * -T tok:mfr:ser:lab -k keyfile + * -c cipher -T tok:mfr:ser:lab -k keyfile + * the given cipher or the default cipher apply to keyfile, + * If the user said instead + * -T tok:mfr:ser:lab + * -c cipher -T tok:mfr:ser:lab + * the key named "lab" may or may not agree with the given + * cipher or the default cipher. In those cases, cipher will + * be overridden with the actual cipher type of the key "lab". + */ + *rv = CKR_FUNCTION_FAILED; + + if (args == NULL) { + return (B_FALSE); + } + + cipher = (mech_alias_t *)args; + token = cipher->token; + + if (C_GetMechanismInfo(slot_id, cipher->type, &mechinfo) != CKR_OK) { + return (B_FALSE); + } + + if (token == NULL) { + if (C_GetMechanismInfo(slot_id, CKM_PKCS5_PBKD2, &mechinfo) != + CKR_OK) { + return (B_FALSE); + } + goto foundit; + } + + /* does the token match the token spec? */ + if (token->key == NULL || (C_GetTokenInfo(slot_id, &tokinfo) != CKR_OK)) + return (B_FALSE); + + token_match = B_TRUE; + + if (token->name != NULL && (token->name)[0] != '\0' && + strncmp((char *)token->name, (char *)tokinfo.label, + TOKEN_LABEL_SIZE) != 0) + token_match = B_FALSE; + if (token->mfr != NULL && (token->mfr)[0] != '\0' && + strncmp((char *)token->mfr, (char *)tokinfo.manufacturerID, + TOKEN_MANUFACTURER_SIZE) != 0) + token_match = B_FALSE; + if (token->serno != NULL && (token->serno)[0] != '\0' && + strncmp((char *)token->serno, (char *)tokinfo.serialNumber, + TOKEN_SERIAL_SIZE) != 0) + token_match = B_FALSE; + + if (!token_match) + return (B_FALSE); + +foundit: + cipher->slot = slot_id; + return (B_TRUE); +} + +/* + * Clean up crypto loose ends + */ +static void +end_crypto(CK_SESSION_HANDLE sess) +{ + (void) C_CloseSession(sess); + (void) C_Finalize(NULL); +} + +/* + * Set up crypto, opening session on slot that matches token and cipher + */ +static void +init_crypto(token_spec_t *token, mech_alias_t *cipher, + CK_SESSION_HANDLE_PTR sess) +{ + CK_RV rv; + + cipher->token = token; + + /* Turn off Metaslot so that we can see actual tokens */ + if (setenv("METASLOT_ENABLED", "false", 1) < 0) { + die(gettext("could not disable Metaslot")); + } + + rv = pkcs11_GetCriteriaSession(match_token_cipher, (void *)cipher, + sess); + if (rv != CKR_OK) { + end_crypto(*sess); + if (rv == CKR_HOST_MEMORY) { + die("malloc"); + } + die(gettext("failed to find any cryptographic provider, " + "use \"cryptoadm list -p\" to find providers: %s\n"), + pkcs11_strerror(rv)); + } +} + +/* * Uncompress a file. * * First map the file in to establish a device @@ -372,6 +1178,7 @@ lofi_uncompress(int lfd, const char *filename) char buf[MAXBSIZE]; char devicename[32]; char tmpfilename[MAXPATHLEN]; + char *x; char *dir = NULL; char *file = NULL; int minor = 0; @@ -396,7 +1203,7 @@ lofi_uncompress(int lfd, const char *filename) if (statbuf.st_size == 0) return; - add_mapping(lfd, NULL, filename, &minor, 1); + minor = lofi_map_file(lfd, li, filename); (void) snprintf(devicename, sizeof (devicename), "/dev/%s/%d", LOFI_BLOCK_NAME, minor); @@ -412,18 +1219,20 @@ lofi_uncompress(int lfd, const char *filename) die(gettext("open: %s"), filename); } /* Create a temp file in the same directory */ - dir = strdup(filename); - dir = dirname(dir); - file = strdup(filename); - file = basename(file); + x = strdup(filename); + dir = strdup(dirname(x)); + free(x); + x = strdup(filename); + file = strdup(basename(x)); + free(x); (void) snprintf(tmpfilename, sizeof (tmpfilename), "%s/.%sXXXXXX", dir, file); + free(dir); + free(file); if ((uncompfd = mkstemp64(tmpfilename)) == -1) { (void) close(compfd); delete_mapping(lfd, devicename, filename, B_TRUE); - free(dir); - free(file); die("%s could not be uncompressed\n", filename); } @@ -437,8 +1246,6 @@ lofi_uncompress(int lfd, const char *filename) (void) close(compfd); (void) close(uncompfd); delete_mapping(lfd, devicename, filename, B_TRUE); - free(dir); - free(file); die("%s could not be uncompressed\n", filename); } @@ -457,8 +1264,6 @@ lofi_uncompress(int lfd, const char *filename) (void) close(compfd); (void) close(uncompfd); - free(dir); - free(file); /* Delete the mapping */ delete_mapping(lfd, devicename, filename, B_TRUE); @@ -490,6 +1295,7 @@ lofi_compress(int *lfd, const char *filename, int compress_index, char tmpfilename[MAXPATHLEN]; char comp_filename[MAXPATHLEN]; char algorithm[MAXALGLEN]; + char *x; char *dir = NULL, *file = NULL; uchar_t *uncompressed_seg = NULL; uchar_t *compressed_seg = NULL; @@ -573,14 +1379,18 @@ lofi_compress(int *lfd, const char *filename, int compress_index, * Create temporary files in the same directory that * will hold the intermediate data */ - dir = strdup(filename); - dir = dirname(dir); - file = strdup(filename); - file = basename(file); + x = strdup(filename); + dir = strdup(dirname(x)); + free(x); + x = strdup(filename); + file = strdup(basename(x)); + free(x); (void) snprintf(tmpfilename, sizeof (tmpfilename), "%s/.%sXXXXXX", dir, file); (void) snprintf(comp_filename, sizeof (comp_filename), "%s/.%sXXXXXX", dir, file); + free(dir); + free(file); if ((tfd = mkstemp64(tmpfilename)) == -1) goto cleanup; @@ -781,10 +1591,6 @@ cleanup: free(compressed_seg); if (uncompressed_seg != NULL) free(uncompressed_seg); - if (dir != NULL) - free(dir); - if (file != NULL) - free(file); if (index != NULL) free(index); if (compfd != -1) @@ -820,7 +1626,7 @@ check_file_validity(const char *filename) { struct stat64 buf; int error; - int fd = -1; + int fd; fd = open64(filename, O_RDONLY); if (fd == -1) { @@ -894,21 +1700,34 @@ main(int argc, char *argv[]) uint32_t segsize = SEGSIZE; static char *lofictl = "/dev/" LOFI_CTL_NAME; boolean_t force = B_FALSE; - char realfilename[MAXPATHLEN]; + const char *pname; + boolean_t errflag = B_FALSE; + boolean_t addflag = B_FALSE; + boolean_t deleteflag = B_FALSE; + boolean_t ephflag = B_FALSE; + boolean_t compressflag = B_FALSE; + boolean_t uncompressflag = B_FALSE; + /* the next two work together for -c, -k, -T, -e options only */ + boolean_t need_crypto = B_FALSE; /* if any -c, -k, -T, -e */ + boolean_t cipher_only = B_TRUE; /* if -c only */ + const char *keyfile = NULL; + mech_alias_t *cipher = NULL; + token_spec_t *token = NULL; + char *rkey = NULL; + size_t rksz = 0; + char realfilename[MAXPATHLEN]; pname = getpname(argv[0]); (void) setlocale(LC_ALL, ""); (void) textdomain(TEXT_DOMAIN); - while ((c = getopt(argc, argv, "a:C:d:s:U:f")) != EOF) { + while ((c = getopt(argc, argv, "a:c:Cd:efk:o:s:T:U")) != EOF) { switch (c) { case 'a': - addflag = 1; + addflag = B_TRUE; if ((filename = realpath(optarg, realfilename)) == NULL) die("%s", optarg); - check_file_validity(filename); - if (((argc - optind) > 0) && (*argv[optind] != '-')) { /* optional device */ devicename = argv[optind]; @@ -916,39 +1735,26 @@ main(int argc, char *argv[]) } break; case 'C': - compressflag = 1; - - if (((argc - optind) > 0) && - (*optarg == '-')) { - check_algorithm_validity(algname, - &compress_index); - optind--; - break; - } else if (((argc - optind) == 1) && - (*argv[optind] != '-')) { - algname = optarg; - if ((filename = realpath(argv[optind], - realfilename)) == NULL) - die("%s", argv[optind]); + compressflag = B_TRUE; + if (((argc - optind) > 1) && (*argv[optind] != '-')) { + /* optional algorithm */ + algname = argv[optind]; optind++; - } else if (((argc - optind) > 1) && - (*argv[optind] == '-')) { - algname = optarg; - check_algorithm_validity(algname, - &compress_index); - break; - } else { - if ((filename = realpath(optarg, - realfilename)) == NULL) - die("%s", optarg); } - - check_file_validity(filename); check_algorithm_validity(algname, &compress_index); break; + case 'c': + /* is the chosen cipher allowed? */ + if ((cipher = ciph2mech(optarg)) == NULL) { + errflag = B_TRUE; + warn(gettext("cipher %s not allowed\n"), + optarg); + } + need_crypto = B_TRUE; + /* cipher_only is already set */ + break; case 'd': - deleteflag = 1; - + deleteflag = B_TRUE; minor = name_to_minor(optarg); if (minor != 0) devicename = optarg; @@ -958,62 +1764,97 @@ main(int argc, char *argv[]) die("%s", optarg); } break; + case 'e': + ephflag = B_TRUE; + need_crypto = B_TRUE; + cipher_only = B_FALSE; /* need to unset cipher_only */ + break; case 'f': force = B_TRUE; break; + case 'k': + keyfile = optarg; + need_crypto = B_TRUE; + cipher_only = B_FALSE; /* need to unset cipher_only */ + break; case 's': segsize = convert_to_num(optarg); - if (segsize == 0 || segsize % DEV_BSIZE) die(gettext("segment size %s is invalid " "or not a multiple of minimum block " "size %ld\n"), optarg, DEV_BSIZE); - - if ((filename = realpath(argv[optind], - realfilename)) == NULL) - die("%s", argv[optind]); - check_file_validity(filename); - optind++; + break; + case 'T': + if ((token = parsetoken(optarg)) == NULL) { + errflag = B_TRUE; + warn( + gettext("invalid token key specifier %s\n"), + optarg); + } + need_crypto = B_TRUE; + cipher_only = B_FALSE; /* need to unset cipher_only */ break; case 'U': - uncompressflag = 1; - if ((filename = realpath(optarg, realfilename)) == NULL) - die("%s", optarg); - check_file_validity(filename); + uncompressflag = B_TRUE; break; case '?': default: - errflag = 1; + errflag = B_TRUE; break; } } + + /* Check for mutually exclusive combinations of options */ if (errflag || (addflag && deleteflag) || + (!addflag && need_crypto) || ((compressflag || uncompressflag) && (addflag || deleteflag))) - usage(); + usage(pname); + + /* ephemeral key, and key from either file or token are incompatible */ + if (ephflag && (keyfile != NULL || token != NULL)) { + die(gettext("ephemeral key cannot be used with keyfile" + " or token key\n")); + } + + /* + * "-c" but no "-k", "-T", "-e", or "-T -k" means derive key from + * command line passphrase + */ switch (argc - optind) { case 0: /* no more args */ + if (compressflag || uncompressflag) /* needs filename */ + usage(pname); break; - case 1: /* one arg without options means print the association */ + case 1: if (addflag || deleteflag) - usage(); - if (compressflag || uncompressflag) - usage(); - minor = name_to_minor(argv[optind]); - if (minor != 0) - devicename = argv[optind]; - else { + usage(pname); + /* one arg means compress/uncompress the file ... */ + if (compressflag || uncompressflag) { if ((filename = realpath(argv[optind], realfilename)) == NULL) die("%s", argv[optind]); + /* ... or without options means print the association */ + } else { + minor = name_to_minor(argv[optind]); + if (minor != 0) + devicename = argv[optind]; + else { + if ((filename = realpath(argv[optind], + realfilename)) == NULL) + die("%s", argv[optind]); + } } break; default: - usage(); + usage(pname); break; } + if (addflag || compressflag || uncompressflag) + check_file_validity(filename); + if (filename && !valid_abspath(filename)) exit(E_ERROR); @@ -1022,9 +1863,7 @@ main(int argc, char *argv[]) * absolute path, it exists and is a regular file. We don't yet * know that the device name is ok or not. */ - /* - * Now to the real work. - */ + openflag = O_EXCL; if (addflag || deleteflag || compressflag || uncompressflag) openflag |= O_RDWR; @@ -1040,8 +1879,51 @@ main(int argc, char *argv[]) } /*NOTREACHED*/ } + + /* + * No passphrase is needed for ephemeral key, or when key is + * in a file and not wrapped by another key from a token. + * However, a passphrase is needed in these cases: + * 1. cipher with no ephemeral key, key file, or token, + * in which case the passphrase is used to build the key + * 2. token with an optional cipher or optional key file, + * in which case the passphrase unlocks the token + * If only the cipher is specified, reconfirm the passphrase + * to ensure the user hasn't mis-entered it. Otherwise, the + * token will enforce the token passphrase. + */ + if (need_crypto) { + CK_SESSION_HANDLE sess; + + /* pick a cipher if none specified */ + if (cipher == NULL) + cipher = DEFAULT_CIPHER; + + if (!kernel_cipher_check(cipher)) + die(gettext( + "use \"cryptoadm list -m\" to find available " + "mechanisms\n")); + + init_crypto(token, cipher, &sess); + + if (cipher_only) { + getkeyfromuser(cipher, &rkey, &rksz); + } else if (token != NULL) { + getkeyfromtoken(sess, token, keyfile, cipher, + &rkey, &rksz); + } else { + /* this also handles ephemeral keys */ + getkeyfromfile(keyfile, cipher, &rkey, &rksz); + } + + end_crypto(sess); + } + + /* + * Now to the real work. + */ if (addflag) - add_mapping(lfd, devicename, filename, NULL, 0); + add_mapping(lfd, devicename, filename, cipher, rkey, rksz); else if (compressflag) lofi_compress(&lfd, filename, compress_index, segsize); else if (uncompressflag) diff --git a/usr/src/cmd/lofiadm/utils.c b/usr/src/cmd/lofiadm/utils.c index 349fab1c2b..6b94155ab0 100644 --- a/usr/src/cmd/lofiadm/utils.c +++ b/usr/src/cmd/lofiadm/utils.c @@ -19,12 +19,10 @@ * CDDL HEADER END */ /* - * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ -#pragma ident "%Z%%M% %I% %E% SMI" - #include <sys/types.h> #include <sys/param.h> #include <sys/stat.h> @@ -49,7 +47,7 @@ static const char ERRNO_FMT[] = ": %s\n"; static const char *pname; /*PRINTFLIKE1*/ -static void +void warn(const char *format, ...) { int err = errno; @@ -82,7 +80,6 @@ die(const char *format, ...) if (strchr(format, '\n') == NULL) (void) fprintf(stderr, gettext(ERRNO_FMT), strerror(err)); - exit(E_ERROR); } diff --git a/usr/src/cmd/lofiadm/utils.h b/usr/src/cmd/lofiadm/utils.h index 627ac3b264..59f32c7989 100644 --- a/usr/src/cmd/lofiadm/utils.h +++ b/usr/src/cmd/lofiadm/utils.h @@ -19,15 +19,13 @@ * CDDL HEADER END */ /* - * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _UTILS_H #define _UTILS_H -#pragma ident "%Z%%M% %I% %E% SMI" - #include <libintl.h> #ifdef __cplusplus @@ -38,9 +36,12 @@ extern "C" { #define E_ERROR 1 /* Exit status for error */ #define E_USAGE 2 /* Exit status for usage error */ +extern void warn(const char *, ...); extern void die(const char *, ...); + extern const char *getpname(const char *); extern int valid_abspath(const char *); + extern void *openlib(const char *); extern void closelib(); diff --git a/usr/src/uts/common/crypto/api/kcf_miscapi.c b/usr/src/uts/common/crypto/api/kcf_miscapi.c index 335d30df62..600a144779 100644 --- a/usr/src/uts/common/crypto/api/kcf_miscapi.c +++ b/usr/src/uts/common/crypto/api/kcf_miscapi.c @@ -19,12 +19,10 @@ * CDDL HEADER END */ /* - * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ -#pragma ident "%Z%%M% %I% %E% SMI" - #include <sys/types.h> #include <sys/sunddi.h> #include <sys/disp.h> @@ -697,6 +695,17 @@ bail: } /* + * Frees the array of mechanism infos previously allocated by + * crypto_get_all_mech_info(). + */ +void +crypto_free_all_mech_info(crypto_mechanism_info_t *mech_infos, uint_t count) +{ + if ((mech_infos != NULL) && (count > 0)) + kmem_free(mech_infos, count * sizeof (crypto_mechanism_info_t)); +} + +/* * memcmp_pad_max() is a specialized version of memcmp() which * compares two pieces of data up to a maximum length. If the * the two data match up the maximum length, they are considered diff --git a/usr/src/uts/common/crypto/io/crypto.c b/usr/src/uts/common/crypto/io/crypto.c index c948007b91..4481d804eb 100644 --- a/usr/src/uts/common/crypto/io/crypto.c +++ b/usr/src/uts/common/crypto/io/crypto.c @@ -921,6 +921,191 @@ out: } /* + * This ioctl returns an array of crypto_mech_name_t entries. + * It lists all the PKCS#11 mechanisms available in the kernel. + */ +/* ARGSUSED */ +static int +get_mechanism_list(dev_t dev, caddr_t arg, int mode, int *rval) +{ + STRUCT_DECL(crypto_get_mechanism_list, get_list); + crypto_mech_name_t *entries; + size_t copyout_size; + uint_t req_count; + uint_t count; + ulong_t offset; + int error = 0; + + STRUCT_INIT(get_list, mode); + + if (copyin(arg, STRUCT_BUF(get_list), STRUCT_SIZE(get_list)) != 0) { + return (EFAULT); + } + + entries = crypto_get_mech_list(&count, KM_SLEEP); + + /* Number of entries caller thinks we have */ + req_count = STRUCT_FGET(get_list, ml_count); + + STRUCT_FSET(get_list, ml_count, count); + STRUCT_FSET(get_list, ml_return_value, CRYPTO_SUCCESS); + + /* check if buffer is too small */ + if (count > req_count) { + STRUCT_FSET(get_list, ml_return_value, CRYPTO_BUFFER_TOO_SMALL); + } + + /* copyout the first stuff */ + if (copyout(STRUCT_BUF(get_list), arg, STRUCT_SIZE(get_list)) != 0) { + error = EFAULT; + } + + /* + * If only requesting number of entries or buffer too small or an + * error occurred, stop here + */ + if (req_count == 0 || count > req_count || error != 0) { + goto out; + } + + copyout_size = count * sizeof (crypto_mech_name_t); + + /* copyout entries */ + offset = (ulong_t)STRUCT_FADDR(get_list, ml_list); + offset -= (ulong_t)STRUCT_BUF(get_list); + if (copyout(entries, arg + offset, copyout_size) != 0) { + error = EFAULT; + } + +out: + crypto_free_mech_list(entries, count); + return (error); +} + +/* + * Copyout kernel array of mech_infos to user space. + */ +/* ARGSUSED */ +static int +copyout_mechinfos(int mode, caddr_t out, uint_t count, + crypto_mechanism_info_t *k_minfos, caddr_t u_minfos) +{ + STRUCT_DECL(crypto_mechanism_info, mi); + caddr_t p; + size_t len; + int i; + + if (count == 0) + return (0); + + STRUCT_INIT(mi, mode); + + len = count * STRUCT_SIZE(mi); + + ASSERT(u_minfos != NULL); + p = u_minfos; + for (i = 0; i < count; i++) { + STRUCT_FSET(mi, mi_min_key_size, k_minfos[i].mi_min_key_size); + STRUCT_FSET(mi, mi_max_key_size, k_minfos[i].mi_max_key_size); + STRUCT_FSET(mi, mi_keysize_unit, k_minfos[i].mi_keysize_unit); + STRUCT_FSET(mi, mi_usage, k_minfos[i].mi_usage); + bcopy(STRUCT_BUF(mi), p, STRUCT_SIZE(mi)); + p += STRUCT_SIZE(mi); + } + + if (copyout(u_minfos, out, len) != 0) + return (EFAULT); + + return (0); +} + +/* + * This ioctl returns information for the specified mechanism. + */ +/* ARGSUSED */ +static int +get_all_mechanism_info(dev_t dev, caddr_t arg, int mode, int *rval) +{ + STRUCT_DECL(crypto_get_all_mechanism_info, get_all_mech); + STRUCT_DECL(crypto_mechanism_info, mi); + crypto_mech_name_t mech_name; + crypto_mech_type_t mech_type; + crypto_mechanism_info_t *mech_infos = NULL; + uint_t num_mech_infos = 0; + uint_t req_count; + caddr_t u_minfos; + ulong_t offset; + int error = 0; + int rv; + + STRUCT_INIT(get_all_mech, mode); + STRUCT_INIT(mi, mode); + + if (copyin(arg, STRUCT_BUF(get_all_mech), + STRUCT_SIZE(get_all_mech)) != 0) { + return (EFAULT); + } + + (void) strncpy(mech_name, STRUCT_FGET(get_all_mech, mi_mechanism_name), + CRYPTO_MAX_MECH_NAME); + mech_type = crypto_mech2id(mech_name); + + if (mech_type == CRYPTO_MECH_INVALID) { + rv = CRYPTO_ARGUMENTS_BAD; + goto out1; + } + + rv = crypto_get_all_mech_info(mech_type, &mech_infos, &num_mech_infos, + KM_SLEEP); + if (rv != CRYPTO_SUCCESS) { + goto out1; + } + /* rv is CRYPTO_SUCCESS at this point */ + + /* Number of entries caller thinks we have */ + req_count = STRUCT_FGET(get_all_mech, mi_count); + + STRUCT_FSET(get_all_mech, mi_count, num_mech_infos); + + /* check if buffer is too small */ + if (num_mech_infos > req_count) { + rv = CRYPTO_BUFFER_TOO_SMALL; + } + +out1: + STRUCT_FSET(get_all_mech, mi_return_value, rv); + + /* copy the first part */ + if (copyout(STRUCT_BUF(get_all_mech), arg, + STRUCT_SIZE(get_all_mech)) != 0) { + error = EFAULT; + } + + /* + * If only requesting number of entries, or there are no entries, + * or rv is not CRYPTO_SUCCESS due to buffer too small or some other + * crypto error, or an error occurred with copyout, stop here + */ + if (req_count == 0 || num_mech_infos == 0 || rv != CRYPTO_SUCCESS || + error != 0) { + goto out2; + } + + /* copyout mech_infos */ + offset = (ulong_t)STRUCT_FADDR(get_all_mech, mi_list); + offset -= (ulong_t)STRUCT_BUF(get_all_mech); + + u_minfos = kmem_alloc(num_mech_infos * STRUCT_SIZE(mi), KM_SLEEP); + error = copyout_mechinfos(mode, arg + offset, num_mech_infos, + mech_infos, u_minfos); + kmem_free(u_minfos, num_mech_infos * STRUCT_SIZE(mi)); +out2: + if (mech_infos != NULL) + crypto_free_all_mech_info(mech_infos, num_mech_infos); + return (error); +} + +/* * Side-effects: * 1. This routine stores provider descriptor pointers in an array * and increments each descriptor's reference count. The array @@ -6276,6 +6461,12 @@ crypto_ioctl(dev_t dev, int cmd, intptr_t arg, int mode, cred_t *c, case CRYPTO_GET_MECHANISM_NUMBER: return (get_mechanism_number(dev, ARG, mode, rval)); + case CRYPTO_GET_MECHANISM_LIST: + return (get_mechanism_list(dev, ARG, mode, rval)); + + case CRYPTO_GET_ALL_MECHANISM_INFO: + return (get_all_mechanism_info(dev, ARG, mode, rval)); + case CRYPTO_GET_PROVIDER_LIST: return (get_provider_list(dev, ARG, mode, rval)); diff --git a/usr/src/uts/common/io/lofi.c b/usr/src/uts/common/io/lofi.c index 8ad6f4f9e7..ceee2576f0 100644 --- a/usr/src/uts/common/io/lofi.c +++ b/usr/src/uts/common/io/lofi.c @@ -23,7 +23,6 @@ * Use is subject to license terms. */ - /* * lofi (loopback file) driver - allows you to attach a file to a device, * which can then be accessed through that device. The simple model is that @@ -90,11 +89,19 @@ * * Pass-through ioctls on block devices. You can (though it's not * documented), give lofi a block device as a file name. Then we shouldn't - * need to fake a geometry. But this is also silly unless you're replacing - * metadisk. + * need to fake a geometry, however, it may be relevant if you're replacing + * metadisk, or using lofi to get crypto. + * It makes sense to do lofiadm -c aes -a /dev/dsk/c0t0d0s4 /dev/lofi/1 + * and then in /etc/vfstab have an entry for /dev/lofi/1 as /export/home. + * In fact this even makes sense if you have lofi "above" metadisk. + * + * Encryption: + * Each lofi device can have its own symmetric key and cipher. + * They are passed to us by lofiadm(1m) in the correct format for use + * with the misc/kcf crypto_* routines. * - * Encryption. tpm would like this. Apparently Windows 2000 has it, and - * so does Linux. + * Each block has its own IV, that is calculated in lofi_blk_mech(), based + * on the "master" key held in the lsp and the block number of the buffer. */ #include <sys/types.h> @@ -123,12 +130,37 @@ #include <sys/ddi.h> #include <sys/sunddi.h> #include <sys/zmod.h> +#include <sys/crypto/common.h> +#include <sys/crypto/api.h> + +/* + * The basis for CRYOFF is derived from usr/src/uts/common/sys/fs/ufs_fs.h. + * Crypto metadata, if it exists, is located at the end of the boot block + * (BBOFF + BBSIZE, which is SBOFF). The super block and everything after + * is offset by the size of the crypto metadata which is handled by + * lsp->ls_crypto_offset. + */ +#define CRYOFF ((off_t)8192) #define NBLOCKS_PROP_NAME "Nblocks" #define SIZE_PROP_NAME "Size" -static dev_info_t *lofi_dip; -static void *lofi_statep; +#define SETUP_C_DATA(cd, buf, len) \ + (cd).cd_format = CRYPTO_DATA_RAW; \ + (cd).cd_offset = 0; \ + (cd).cd_miscdata = NULL; \ + (cd).cd_length = (len); \ + (cd).cd_raw.iov_base = (buf); \ + (cd).cd_raw.iov_len = (len); + +#define UIO_CHECK(uio) \ + if (((uio)->uio_loffset % DEV_BSIZE) != 0 || \ + ((uio)->uio_resid % DEV_BSIZE) != 0) { \ + return (EINVAL); \ + } + +static dev_info_t *lofi_dip = NULL; +static void *lofi_statep = NULL; static kmutex_t lofi_lock; /* state lock */ /* @@ -147,6 +179,7 @@ static int lofi_taskq_maxalloc = 104857600 / DEV_BSIZE; static int lofi_taskq_nthreads = 4; /* # of taskq threads per device */ uint32_t lofi_max_files = LOFI_MAX_FILES; +const char lofi_crypto_magic[6] = LOFI_CRYPTO_MAGIC; static int gzip_decompress(void *src, size_t srclen, void *dst, size_t *destlen, int level); @@ -224,12 +257,51 @@ mark_closed(struct lofi_state *lsp, int otyp) } static void +lofi_free_crypto(struct lofi_state *lsp) +{ + ASSERT(mutex_owned(&lofi_lock)); + + if (lsp->ls_crypto_enabled) { + /* + * Clean up the crypto state so that it doesn't hang around + * in memory after we are done with it. + */ + bzero(lsp->ls_key.ck_data, + CRYPTO_BITS2BYTES(lsp->ls_key.ck_length)); + kmem_free(lsp->ls_key.ck_data, + CRYPTO_BITS2BYTES(lsp->ls_key.ck_length)); + lsp->ls_key.ck_data = NULL; + lsp->ls_key.ck_length = 0; + + if (lsp->ls_mech.cm_param != NULL) { + kmem_free(lsp->ls_mech.cm_param, + lsp->ls_mech.cm_param_len); + lsp->ls_mech.cm_param = NULL; + lsp->ls_mech.cm_param_len = 0; + } + + if (lsp->ls_iv_mech.cm_param != NULL) { + kmem_free(lsp->ls_iv_mech.cm_param, + lsp->ls_iv_mech.cm_param_len); + lsp->ls_iv_mech.cm_param = NULL; + lsp->ls_iv_mech.cm_param_len = 0; + } + + mutex_destroy(&lsp->ls_crypto_lock); + } +} + +static void lofi_free_handle(dev_t dev, minor_t minor, struct lofi_state *lsp, cred_t *credp) { dev_t newdev; char namebuf[50]; + ASSERT(mutex_owned(&lofi_lock)); + + lofi_free_crypto(lsp); + if (lsp->ls_vp) { (void) VOP_CLOSE(lsp->ls_vp, lsp->ls_openflag, 1, 0, credp, NULL); @@ -340,18 +412,243 @@ lofi_close(dev_t dev, int flag, int otyp, struct cred *credp) return (0); } +/* + * Sets the mechanism's initialization vector (IV) if one is needed. + * The IV is computed from the data block number. lsp->ls_mech is + * altered so that: + * lsp->ls_mech.cm_param_len is set to the IV len. + * lsp->ls_mech.cm_param is set to the IV. + */ +static int +lofi_blk_mech(struct lofi_state *lsp, longlong_t lblkno) +{ + int ret; + crypto_data_t cdata; + char *iv; + size_t iv_len; + size_t min; + void *data; + size_t datasz; + + ASSERT(mutex_owned(&lsp->ls_crypto_lock)); + + if (lsp == NULL) + return (CRYPTO_DEVICE_ERROR); + + /* lsp->ls_mech.cm_param{_len} has already been set for static iv */ + if (lsp->ls_iv_type == IVM_NONE) { + return (CRYPTO_SUCCESS); + } + + /* + * if kmem already alloced from previous call and it's the same size + * we need now, just recycle it; allocate new kmem only if we have to + */ + if (lsp->ls_mech.cm_param == NULL || + lsp->ls_mech.cm_param_len != lsp->ls_iv_len) { + iv_len = lsp->ls_iv_len; + iv = kmem_zalloc(iv_len, KM_SLEEP); + } else { + iv_len = lsp->ls_mech.cm_param_len; + iv = lsp->ls_mech.cm_param; + bzero(iv, iv_len); + } + + switch (lsp->ls_iv_type) { + case IVM_ENC_BLKNO: + /* iv is not static, lblkno changes each time */ + data = &lblkno; + datasz = sizeof (lblkno); + break; + default: + data = 0; + datasz = 0; + break; + } + + /* + * write blkno into the iv buffer padded on the left in case + * blkno ever grows bigger than its current longlong_t size + * or a variation other than blkno is used for the iv data + */ + min = MIN(datasz, iv_len); + bcopy(data, iv + (iv_len - min), min); + + /* encrypt the data in-place to get the IV */ + SETUP_C_DATA(cdata, iv, iv_len); + + ret = crypto_encrypt(&lsp->ls_iv_mech, &cdata, &lsp->ls_key, + NULL, NULL, NULL); + if (ret != CRYPTO_SUCCESS) { + cmn_err(CE_WARN, "failed to create iv for block %lld: (0x%x)", + lblkno, ret); + if (lsp->ls_mech.cm_param != iv) + kmem_free(iv, iv_len); + return (ret); + } + + /* clean up the iv from the last computation */ + if (lsp->ls_mech.cm_param != NULL && lsp->ls_mech.cm_param != iv) + kmem_free(lsp->ls_mech.cm_param, lsp->ls_mech.cm_param_len); + lsp->ls_mech.cm_param_len = iv_len; + lsp->ls_mech.cm_param = iv; + + return (CRYPTO_SUCCESS); +} + +/* + * Performs encryption and decryption of a chunk of data of size "len", + * one DEV_BSIZE block at a time. "len" is assumed to be a multiple of + * DEV_BSIZE. + */ +static int +lofi_crypto(struct lofi_state *lsp, struct buf *bp, caddr_t plaintext, + caddr_t ciphertext, size_t len, boolean_t op_encrypt) +{ + crypto_data_t cdata; + crypto_data_t wdata; + int ret; + longlong_t lblkno = bp->b_lblkno; + + mutex_enter(&lsp->ls_crypto_lock); + + /* + * though we could encrypt/decrypt entire "len" chunk of data, we need + * to break it into DEV_BSIZE pieces to capture blkno incrementing + */ + SETUP_C_DATA(cdata, plaintext, len); + cdata.cd_length = DEV_BSIZE; + if (ciphertext != NULL) { /* not in-place crypto */ + SETUP_C_DATA(wdata, ciphertext, len); + wdata.cd_length = DEV_BSIZE; + } + + do { + ret = lofi_blk_mech(lsp, lblkno); + if (ret != CRYPTO_SUCCESS) + continue; + + if (op_encrypt) { + ret = crypto_encrypt(&lsp->ls_mech, &cdata, + &lsp->ls_key, NULL, + ((ciphertext != NULL) ? &wdata : NULL), NULL); + } else { + ret = crypto_decrypt(&lsp->ls_mech, &cdata, + &lsp->ls_key, NULL, + ((ciphertext != NULL) ? &wdata : NULL), NULL); + } + + cdata.cd_offset += DEV_BSIZE; + if (ciphertext != NULL) + wdata.cd_offset += DEV_BSIZE; + lblkno++; + } while (ret == CRYPTO_SUCCESS && cdata.cd_offset < len); + + mutex_exit(&lsp->ls_crypto_lock); + + if (ret != CRYPTO_SUCCESS) { + cmn_err(CE_WARN, "%s failed for block %lld: (0x%x)", + op_encrypt ? "crypto_encrypt()" : "crypto_decrypt()", + lblkno, ret); + } + + return (ret); +} + +#define RDWR_RAW 1 +#define RDWR_BCOPY 2 + +static int +lofi_rdwr(caddr_t bufaddr, offset_t offset, struct buf *bp, + struct lofi_state *lsp, size_t len, int method, caddr_t bcopy_locn) +{ + ssize_t resid; + int isread; + int error; + + /* + * Handles reads/writes for both plain and encrypted lofi + * Note: offset is already shifted by lsp->ls_crypto_offset + * when it gets here. + */ + + isread = bp->b_flags & B_READ; + if (isread) { + if (method == RDWR_BCOPY) { + /* DO NOT update bp->b_resid for bcopy */ + bcopy(bcopy_locn, bufaddr, len); + error = 0; + } else { /* RDWR_RAW */ + error = vn_rdwr(UIO_READ, lsp->ls_vp, bufaddr, len, + offset, UIO_SYSSPACE, 0, RLIM64_INFINITY, kcred, + &resid); + bp->b_resid = resid; + } + if (lsp->ls_crypto_enabled && error == 0) { + if (lofi_crypto(lsp, bp, bufaddr, NULL, len, + B_FALSE) != CRYPTO_SUCCESS) { + /* + * XXX: original code didn't set residual + * back to len because no error was expected + * from bcopy() if encryption is not enabled + */ + if (method != RDWR_BCOPY) + bp->b_resid = len; + error = EIO; + } + } + return (error); + } else { + void *iobuf = bufaddr; + + if (lsp->ls_crypto_enabled) { + /* don't do in-place crypto to keep bufaddr intact */ + iobuf = kmem_alloc(len, KM_SLEEP); + if (lofi_crypto(lsp, bp, bufaddr, iobuf, len, + B_TRUE) != CRYPTO_SUCCESS) { + kmem_free(iobuf, len); + if (method != RDWR_BCOPY) + bp->b_resid = len; + return (EIO); + } + } + if (method == RDWR_BCOPY) { + /* DO NOT update bp->b_resid for bcopy */ + bcopy(iobuf, bcopy_locn, len); + error = 0; + } else { /* RDWR_RAW */ + error = vn_rdwr(UIO_WRITE, lsp->ls_vp, iobuf, len, + offset, UIO_SYSSPACE, 0, RLIM64_INFINITY, kcred, + &resid); + bp->b_resid = resid; + } + if (lsp->ls_crypto_enabled) { + kmem_free(iobuf, len); + } + return (error); + } +} + static int lofi_mapped_rdwr(caddr_t bufaddr, offset_t offset, struct buf *bp, - struct lofi_state *lsp) + struct lofi_state *lsp) { int error; offset_t alignedoffset, mapoffset; size_t xfersize; int isread; - int smflags; + int smflags; caddr_t mapaddr; size_t len; enum seg_rw srw; + int save_error; + + /* + * Note: offset is already shifted by lsp->ls_crypto_offset + * when it gets here. + */ + if (lsp->ls_crypto_enabled) + ASSERT(lsp->ls_vp_comp_size == lsp->ls_vp_size); /* * segmap always gives us an 8K (MAXBSIZE) chunk, aligned on @@ -362,6 +659,25 @@ lofi_mapped_rdwr(caddr_t bufaddr, offset_t offset, struct buf *bp, * segmap'd chunk. So we have to compensate for that with * 'mapoffset'. Subsequent chunks always start off at the * beginning, and the last is capped by b_resid + * + * Visually, where "|" represents page map boundaries: + * alignedoffset (mapaddr begins at this segmap boundary) + * | offset (from beginning of file) + * | | len + * v v v + * ===|====X========|====...======|========X====|==== + * /-------------...---------------/ + * ^ bp->b_bcount/bp->b_resid at start + * /----/--------/----...------/--------/ + * ^ ^ ^ ^ ^ + * | | | | nth xfersize (<= MAXBSIZE) + * | | 2nd thru n-1st xfersize (= MAXBSIZE) + * | 1st xfersize (<= MAXBSIZE) + * mapoffset (offset into 1st segmap, non-0 1st time, 0 thereafter) + * + * Notes: "alignedoffset" is "offset" rounded down to nearest + * MAXBSIZE boundary. "len" is next page boundary of size + * MAXBSIZE after "alignedoffset". */ mapoffset = offset & MAXBOFFSET; alignedoffset = offset - mapoffset; @@ -371,7 +687,7 @@ lofi_mapped_rdwr(caddr_t bufaddr, offset_t offset, struct buf *bp, do { xfersize = MIN(lsp->ls_vp_comp_size - offset, MIN(MAXBSIZE - mapoffset, bp->b_resid)); - len = roundup(mapoffset + xfersize, PAGESIZE); + len = roundup(mapoffset + xfersize, MAXBSIZE); mapaddr = segmap_getmapflt(segkmap, lsp->ls_vp, alignedoffset, MAXBSIZE, 1, srw); /* @@ -392,6 +708,14 @@ lofi_mapped_rdwr(caddr_t bufaddr, offset_t offset, struct buf *bp, error = EIO; break; } + /* error may be non-zero for encrypted lofi */ + error = lofi_rdwr(bufaddr, 0, bp, lsp, xfersize, + RDWR_BCOPY, mapaddr + mapoffset); + if (error == 0) { + bp->b_resid -= xfersize; + bufaddr += xfersize; + offset += xfersize; + } smflags = 0; if (isread) { smflags |= SM_FREE; @@ -403,17 +727,15 @@ lofi_mapped_rdwr(caddr_t bufaddr, offset_t offset, struct buf *bp, */ if (mapoffset == 0 && xfersize == MAXBSIZE) smflags |= SM_DONTNEED; - bcopy(mapaddr + mapoffset, bufaddr, xfersize); } else { - smflags |= SM_WRITE; - bcopy(bufaddr, mapaddr + mapoffset, xfersize); + if (error == 0) /* write back good pages */ + smflags |= SM_WRITE; } - bp->b_resid -= xfersize; - bufaddr += xfersize; - offset += xfersize; (void) segmap_fault(kas.a_hat, segkmap, mapaddr, len, F_SOFTUNLOCK, srw); - error = segmap_release(segkmap, mapaddr, smflags); + save_error = segmap_release(segkmap, mapaddr, smflags); + if (error == 0) + error = save_error; /* only the first map may start partial */ mapoffset = 0; alignedoffset += MAXBSIZE; @@ -444,19 +766,17 @@ lofi_strategy_task(void *arg) struct buf *bp = (struct buf *)arg; int error; struct lofi_state *lsp; - uint64_t sblkno, eblkno, cmpbytes; - offset_t offset, sblkoff, eblkoff; - u_offset_t salign, ealign; - u_offset_t sdiff; - uint32_t comp_data_sz; - caddr_t bufaddr; - unsigned char *compressed_seg = NULL, *cmpbuf; - unsigned char *uncompressed_seg = NULL; - lofi_compress_info_t *li; - size_t oblkcount, xfersize; - unsigned long seglen; + offset_t offset; + caddr_t bufaddr; + size_t len; + size_t xfersize; + boolean_t bufinited = B_FALSE; lsp = ddi_get_soft_state(lofi_statep, getminor(bp->b_edev)); + if (lsp == NULL) { + error = ENXIO; + goto errout; + } if (lsp->ls_kstat) { mutex_enter(lsp->ls_kstat->ks_lock); kstat_waitq_to_runq(KSTAT_IO_PTR(lsp->ls_kstat)); @@ -464,32 +784,53 @@ lofi_strategy_task(void *arg) } bp_mapin(bp); bufaddr = bp->b_un.b_addr; +#ifdef _LP64 offset = bp->b_lblkno * DEV_BSIZE; /* offset within file */ +#else + offset = bp->b_blkno * DEV_BSIZE; /* offset within file */ +#endif /* _LP64 */ + if (lsp->ls_crypto_enabled) { + /* encrypted data really begins after crypto header */ + offset += lsp->ls_crypto_offset; + } + len = bp->b_bcount; + bufinited = B_TRUE; + + if (lsp->ls_vp == NULL || lsp->ls_vp_closereq) { + error = EIO; + goto errout; + } /* * We used to always use vn_rdwr here, but we cannot do that because * we might decide to read or write from the the underlying * file during this call, which would be a deadlock because * we have the rw_lock. So instead we page, unless it's not - * mapable or it's a character device. + * mapable or it's a character device or it's an encrypted lofi. */ - if (lsp->ls_vp == NULL || lsp->ls_vp_closereq) { - error = EIO; - } else if (((lsp->ls_vp->v_flag & VNOMAP) == 0) && - (lsp->ls_vp->v_type != VCHR)) { + if ((lsp->ls_vp->v_flag & VNOMAP) || (lsp->ls_vp->v_type == VCHR) || + lsp->ls_crypto_enabled) { + error = lofi_rdwr(bufaddr, offset, bp, lsp, len, RDWR_RAW, + NULL); + } else if (lsp->ls_uncomp_seg_sz == 0) { + error = lofi_mapped_rdwr(bufaddr, offset, bp, lsp); + } else { + unsigned char *compressed_seg = NULL, *cmpbuf; + unsigned char *uncompressed_seg = NULL; + lofi_compress_info_t *li; + size_t oblkcount; + unsigned long seglen; + uint64_t sblkno, eblkno, cmpbytes; + offset_t sblkoff, eblkoff; + u_offset_t salign, ealign; + u_offset_t sdiff; + uint32_t comp_data_sz; uint64_t i; /* - * Handle uncompressed files with a regular read - */ - if (lsp->ls_uncomp_seg_sz == 0) { - error = lofi_mapped_rdwr(bufaddr, offset, bp, lsp); - goto done; - } - - /* * From here on we're dealing primarily with compressed files */ + ASSERT(!lsp->ls_crypto_enabled); /* * Compressed files can only be read from and @@ -629,26 +970,15 @@ lofi_strategy_task(void *arg) if (bp->b_resid == 0) break; } - } else { - ssize_t resid; - enum uio_rw rw; - - if (bp->b_flags & B_READ) - rw = UIO_READ; - else - rw = UIO_WRITE; - error = vn_rdwr(rw, lsp->ls_vp, bufaddr, bp->b_bcount, - offset, UIO_SYSSPACE, 0, RLIM64_INFINITY, kcred, &resid); - bp->b_resid = resid; - } - done: - if (compressed_seg != NULL) - kmem_free(compressed_seg, comp_data_sz); - if (uncompressed_seg != NULL) - kmem_free(uncompressed_seg, lsp->ls_uncomp_seg_sz); - - if (lsp->ls_kstat) { + if (compressed_seg != NULL) + kmem_free(compressed_seg, comp_data_sz); + if (uncompressed_seg != NULL) + kmem_free(uncompressed_seg, lsp->ls_uncomp_seg_sz); + } /* end of handling compressed files */ + +errout: + if (bufinited && lsp->ls_kstat) { size_t n_done = bp->b_bcount - bp->b_resid; kstat_io_t *kioptr; @@ -692,6 +1022,12 @@ lofi_strategy(struct buf *bp) * queues were incredibly easy so they win. */ lsp = ddi_get_soft_state(lofi_statep, getminor(bp->b_edev)); + if (lsp == NULL) { + bioerror(bp, ENXIO); + biodone(bp); + return (0); + } + mutex_enter(&lsp->ls_vp_lock); if (lsp->ls_vp == NULL || lsp->ls_vp_closereq) { bioerror(bp, EIO); @@ -700,7 +1036,15 @@ lofi_strategy(struct buf *bp) return (0); } +#ifdef _LP64 offset = bp->b_lblkno * DEV_BSIZE; /* offset within file */ +#else + offset = bp->b_blkno * DEV_BSIZE; /* offset within file */ +#endif /* _LP64 */ + if (lsp->ls_crypto_enabled) { + /* encrypted data really begins after crypto header */ + offset += lsp->ls_crypto_offset; + } if (offset == lsp->ls_vp_size) { /* EOF */ if ((bp->b_flags & B_READ) != 0) { @@ -738,6 +1082,7 @@ lofi_read(dev_t dev, struct uio *uio, struct cred *credp) { if (getminor(dev) == 0) return (EINVAL); + UIO_CHECK(uio); return (physio(lofi_strategy, NULL, dev, B_READ, minphys, uio)); } @@ -747,6 +1092,7 @@ lofi_write(dev_t dev, struct uio *uio, struct cred *credp) { if (getminor(dev) == 0) return (EINVAL); + UIO_CHECK(uio); return (physio(lofi_strategy, NULL, dev, B_WRITE, minphys, uio)); } @@ -756,6 +1102,7 @@ lofi_aread(dev_t dev, struct aio_req *aio, struct cred *credp) { if (getminor(dev) == 0) return (EINVAL); + UIO_CHECK(aio->aio_uio); return (aphysio(lofi_strategy, anocancel, dev, B_READ, minphys, aio)); } @@ -765,6 +1112,7 @@ lofi_awrite(dev_t dev, struct aio_req *aio, struct cred *credp) { if (getminor(dev) == 0) return (EINVAL); + UIO_CHECK(aio->aio_uio); return (aphysio(lofi_strategy, anocancel, dev, B_WRITE, minphys, aio)); } @@ -827,6 +1175,19 @@ lofi_detach(dev_info_t *dip, ddi_detach_cmd_t cmd) } /* + * With addition of encryption, be careful that encryption key is wiped before + * kernel memory structures are freed, and also that key is not accidentally + * passed out into userland structures. + */ +static void +free_lofi_ioctl(struct lofi_ioctl *klip) +{ + /* Make sure this encryption key doesn't stick around */ + bzero(klip->li_key, sizeof (klip->li_key)); + kmem_free(klip, sizeof (struct lofi_ioctl)); +} + +/* * These two just simplify the rest of the ioctls that need to copyin/out * the lofi_ioctl structure. */ @@ -839,16 +1200,18 @@ copy_in_lofi_ioctl(const struct lofi_ioctl *ulip, int flag) klip = kmem_alloc(sizeof (struct lofi_ioctl), KM_SLEEP); error = ddi_copyin(ulip, klip, sizeof (struct lofi_ioctl), flag); if (error) { - kmem_free(klip, sizeof (struct lofi_ioctl)); + free_lofi_ioctl(klip); return (NULL); } /* make sure filename is always null-terminated */ - klip->li_filename[MAXPATHLEN - 1] = '\0'; + klip->li_filename[MAXPATHLEN-1] = '\0'; /* validate minor number */ if (klip->li_minor > lofi_max_files) { - kmem_free(klip, sizeof (struct lofi_ioctl)); + free_lofi_ioctl(klip); + cmn_err(CE_WARN, "attempt to map more than lofi_max_files (%d)", + lofi_max_files); return (NULL); } return (klip); @@ -860,18 +1223,25 @@ copy_out_lofi_ioctl(const struct lofi_ioctl *klip, struct lofi_ioctl *ulip, { int error; + /* + * NOTE: Do NOT copy the crypto_key_t "back" to userland. + * This ensures that an attacker can't trivially find the + * key for a mapping just by issuing the ioctl. + * + * It can still be found by poking around in kmem with mdb(1), + * but there is no point in making it easy when the info isn't + * of any use in this direction anyway. + * + * Either way we don't actually have the raw key stored in + * a form that we can get it anyway, since we just used it + * to create a ctx template and didn't keep "the original". + */ error = ddi_copyout(klip, ulip, sizeof (struct lofi_ioctl), flag); if (error) return (EFAULT); return (0); } -void -free_lofi_ioctl(struct lofi_ioctl *klip) -{ - kmem_free(klip, sizeof (struct lofi_ioctl)); -} - /* * Return the minor number 'filename' is mapped to, if it is. */ @@ -924,6 +1294,8 @@ valid_filename(const char *filename) static void fake_disk_geometry(struct lofi_state *lsp) { + u_offset_t dsize = lsp->ls_vp_size - lsp->ls_crypto_offset; + /* dk_geom - see dkio(7I) */ /* * dkg_ncyl _could_ be set to one here (one big cylinder with gobs @@ -936,10 +1308,10 @@ fake_disk_geometry(struct lofi_state *lsp) * for a small file, or so many on a big file that you waste space * for backup superblocks or cylinder group structures. */ - if (lsp->ls_vp_size < (2 * 1024 * 1024)) /* floppy? */ - lsp->ls_dkg.dkg_ncyl = lsp->ls_vp_size / (100 * 1024); + if (dsize < (2 * 1024 * 1024)) /* floppy? */ + lsp->ls_dkg.dkg_ncyl = dsize / (100 * 1024); else - lsp->ls_dkg.dkg_ncyl = lsp->ls_vp_size / (300 * 1024); + lsp->ls_dkg.dkg_ncyl = dsize / (300 * 1024); /* in case file file is < 100k */ if (lsp->ls_dkg.dkg_ncyl == 0) lsp->ls_dkg.dkg_ncyl = 1; @@ -953,8 +1325,7 @@ fake_disk_geometry(struct lofi_state *lsp) lsp->ls_dkg.dkg_apc = 0; lsp->ls_dkg.dkg_rpm = 7200; lsp->ls_dkg.dkg_pcyl = lsp->ls_dkg.dkg_ncyl + lsp->ls_dkg.dkg_acyl; - lsp->ls_dkg.dkg_nsect = lsp->ls_vp_size / - (DEV_BSIZE * lsp->ls_dkg.dkg_ncyl); + lsp->ls_dkg.dkg_nsect = dsize / (DEV_BSIZE * lsp->ls_dkg.dkg_ncyl); lsp->ls_dkg.dkg_write_reinstruct = 0; lsp->ls_dkg.dkg_read_reinstruct = 0; @@ -1116,7 +1487,7 @@ lofi_map_compressed_file(struct lofi_state *lsp, char *buf) /* * Check to see if the passed in signature is a valid - * one. If it is valid, return the index into + * one. If it is valid, return the index into * lofi_compress_table. * * Return -1 if it is invalid @@ -1154,10 +1525,12 @@ lofi_map_file(dev_t dev, struct lofi_ioctl *ulip, int pickminor, int zalloced = 0; dev_t newdev; char namebuf[50]; - char buf[DEV_BSIZE]; - char *tbuf; + char buf[DEV_BSIZE]; + char crybuf[DEV_BSIZE]; ssize_t resid; - enum uio_rw rw; + boolean_t need_vn_close = B_FALSE; + boolean_t keycopied = B_FALSE; + boolean_t need_size_update = B_FALSE; klip = copy_in_lofi_ioctl(ulip, ioctl_flag); if (klip == NULL) @@ -1215,22 +1588,24 @@ lofi_map_file(dev_t dev, struct lofi_ioctl *ulip, int pickminor, goto out; } } + need_vn_close = B_TRUE; + vattr.va_mask = AT_SIZE; error = VOP_GETATTR(vp, &vattr, 0, credp, NULL); if (error) { - goto closeout; + goto out; } /* the file needs to be a multiple of the block size */ if ((vattr.va_size % DEV_BSIZE) != 0) { error = EINVAL; - goto closeout; + goto out; } newdev = makedevice(getmajor(dev), newminor); Size_prop_val = vattr.va_size; if ((ddi_prop_update_int64(newdev, lofi_dip, SIZE_PROP_NAME, Size_prop_val)) != DDI_PROP_SUCCESS) { error = EINVAL; - goto closeout; + goto out; } Nblocks_prop_val = vattr.va_size / DEV_BSIZE; if ((ddi_prop_update_int64(newdev, lofi_dip, @@ -1314,41 +1689,224 @@ lofi_map_file(dev_t dev, struct lofi_ioctl *ulip, int pickminor, klip->li_minor = newminor; /* - * Read the file signature to check if it is compressed. - * 'rw' is set to read since only reads are allowed to - * a compressed file. + * Initialize crypto details for encrypted lofi */ - rw = UIO_READ; - error = vn_rdwr(rw, lsp->ls_vp, buf, DEV_BSIZE, 0, UIO_SYSSPACE, - 0, RLIM64_INFINITY, kcred, &resid); + if (klip->li_crypto_enabled) { + int ret; + + mutex_init(&lsp->ls_crypto_lock, NULL, MUTEX_DRIVER, NULL); + lsp->ls_mech.cm_type = crypto_mech2id(klip->li_cipher); + if (lsp->ls_mech.cm_type == CRYPTO_MECH_INVALID) { + cmn_err(CE_WARN, "invalid cipher %s requested for %s", + klip->li_cipher, lsp->ls_filename); + error = EINVAL; + goto propout; + } + + /* this is just initialization here */ + lsp->ls_mech.cm_param = NULL; + lsp->ls_mech.cm_param_len = 0; + + lsp->ls_iv_type = klip->li_iv_type; + lsp->ls_iv_mech.cm_type = crypto_mech2id(klip->li_iv_cipher); + if (lsp->ls_iv_mech.cm_type == CRYPTO_MECH_INVALID) { + cmn_err(CE_WARN, "invalid iv cipher %s requested" + " for %s", klip->li_iv_cipher, lsp->ls_filename); + error = EINVAL; + goto propout; + } + + /* iv mech must itself take a null iv */ + lsp->ls_iv_mech.cm_param = NULL; + lsp->ls_iv_mech.cm_param_len = 0; + lsp->ls_iv_len = klip->li_iv_len; + + /* + * Create ctx using li_cipher & the raw li_key after checking + * that it isn't a weak key. + */ + lsp->ls_key.ck_format = CRYPTO_KEY_RAW; + lsp->ls_key.ck_length = klip->li_key_len; + lsp->ls_key.ck_data = kmem_alloc( + CRYPTO_BITS2BYTES(lsp->ls_key.ck_length), KM_SLEEP); + bcopy(klip->li_key, lsp->ls_key.ck_data, + CRYPTO_BITS2BYTES(lsp->ls_key.ck_length)); + keycopied = B_TRUE; + + ret = crypto_key_check(&lsp->ls_mech, &lsp->ls_key); + if (ret != CRYPTO_SUCCESS) { + error = EINVAL; + cmn_err(CE_WARN, "weak key check failed for cipher " + "%s on file %s (0x%x)", klip->li_cipher, + lsp->ls_filename, ret); + goto propout; + } + } + lsp->ls_crypto_enabled = klip->li_crypto_enabled; + + /* + * Read the file signature to check if it is compressed or encrypted. + * Crypto signature is in a different location; both areas should + * read to keep compression and encryption mutually exclusive. + */ + if (lsp->ls_crypto_enabled) { + error = vn_rdwr(UIO_READ, lsp->ls_vp, crybuf, DEV_BSIZE, + CRYOFF, UIO_SYSSPACE, 0, RLIM64_INFINITY, kcred, &resid); + if (error != 0) + goto propout; + } + error = vn_rdwr(UIO_READ, lsp->ls_vp, buf, DEV_BSIZE, 0, UIO_SYSSPACE, + 0, RLIM64_INFINITY, kcred, &resid); if (error != 0) goto propout; - tbuf = buf; + /* initialize these variables for all lofi files */ lsp->ls_uncomp_seg_sz = 0; lsp->ls_vp_comp_size = lsp->ls_vp_size; lsp->ls_comp_algorithm[0] = '\0'; - compress_index = lofi_compress_select(tbuf); - if (compress_index != -1) { + /* encrypted lofi reads/writes shifted by crypto metadata size */ + lsp->ls_crypto_offset = 0; + + /* this is a compressed lofi */ + if ((compress_index = lofi_compress_select(buf)) != -1) { + + /* compression and encryption are mutually exclusive */ + if (klip->li_crypto_enabled) { + error = ENOTSUP; + goto propout; + } + + /* initialize compression info for compressed lofi */ lsp->ls_comp_algorithm_index = compress_index; (void) strlcpy(lsp->ls_comp_algorithm, lofi_compress_table[compress_index].l_name, sizeof (lsp->ls_comp_algorithm)); + error = lofi_map_compressed_file(lsp, buf); if (error != 0) goto propout; + need_size_update = B_TRUE; + + /* this is an encrypted lofi */ + } else if (strncmp(crybuf, lofi_crypto_magic, + sizeof (lofi_crypto_magic)) == 0) { + + char *marker = crybuf; + + /* + * This is the case where the header in the lofi image is + * already initialized to indicate it is encrypted. + * There is another case (see below) where encryption is + * requested but the lofi image has never been used yet, + * so the header needs to be written with encryption magic. + */ + + /* indicate this must be an encrypted lofi due to magic */ + klip->li_crypto_enabled = B_TRUE; + + /* + * The encryption header information is laid out this way: + * 6 bytes: hex "CFLOFI" + * 2 bytes: version = 0 ... for now + * 96 bytes: reserved1 (not implemented yet) + * 4 bytes: data_sector = 2 ... for now + * more... not implemented yet + */ + + /* copy the magic */ + bcopy(marker, lsp->ls_crypto.magic, + sizeof (lsp->ls_crypto.magic)); + marker += sizeof (lsp->ls_crypto.magic); + /* read the encryption version number */ + bcopy(marker, &(lsp->ls_crypto.version), + sizeof (lsp->ls_crypto.version)); + lsp->ls_crypto.version = ntohs(lsp->ls_crypto.version); + marker += sizeof (lsp->ls_crypto.version); + + /* read a chunk of reserved data */ + bcopy(marker, lsp->ls_crypto.reserved1, + sizeof (lsp->ls_crypto.reserved1)); + marker += sizeof (lsp->ls_crypto.reserved1); + + /* read block number where encrypted data begins */ + bcopy(marker, &(lsp->ls_crypto.data_sector), + sizeof (lsp->ls_crypto.data_sector)); + lsp->ls_crypto.data_sector = ntohl(lsp->ls_crypto.data_sector); + marker += sizeof (lsp->ls_crypto.data_sector); + + /* and ignore the rest until it is implemented */ + + lsp->ls_crypto_offset = lsp->ls_crypto.data_sector * DEV_BSIZE; + need_size_update = B_TRUE; + + /* neither compressed nor encrypted, BUT could be new encrypted lofi */ + } else if (klip->li_crypto_enabled) { + + /* + * This is the case where encryption was requested but the + * appears to be entirely blank where the encryption header + * would have been in the lofi image. If it is blank, + * assume it is a brand new lofi image and initialize the + * header area with encryption magic and current version + * header data. If it is not blank, that's an error. + */ + int i; + char *marker; + struct crypto_meta chead; + + for (i = 0; i < sizeof (struct crypto_meta); i++) + if (crybuf[i] != '\0') + break; + if (i != sizeof (struct crypto_meta)) { + error = EINVAL; + goto propout; + } + + /* nothing there, initialize as encrypted lofi */ + marker = crybuf; + bcopy(lofi_crypto_magic, marker, sizeof (lofi_crypto_magic)); + marker += sizeof (lofi_crypto_magic); + chead.version = htons(LOFI_CRYPTO_VERSION); + bcopy(&(chead.version), marker, sizeof (chead.version)); + marker += sizeof (chead.version); + marker += sizeof (chead.reserved1); + chead.data_sector = htonl(LOFI_CRYPTO_DATA_SECTOR); + bcopy(&(chead.data_sector), marker, sizeof (chead.data_sector)); + + /* write the header */ + error = vn_rdwr(UIO_WRITE, lsp->ls_vp, crybuf, DEV_BSIZE, + CRYOFF, UIO_SYSSPACE, 0, RLIM64_INFINITY, kcred, &resid); + if (error != 0) + goto propout; + + /* fix things up so it looks like we read this info */ + bcopy(lofi_crypto_magic, lsp->ls_crypto.magic, + sizeof (lofi_crypto_magic)); + lsp->ls_crypto.version = LOFI_CRYPTO_VERSION; + lsp->ls_crypto.data_sector = LOFI_CRYPTO_DATA_SECTOR; + + lsp->ls_crypto_offset = lsp->ls_crypto.data_sector * DEV_BSIZE; + need_size_update = B_TRUE; + } + + /* + * Either lsp->ls_vp_size or lsp->ls_crypto_offset changed; + * for encrypted lofi, advertise that it is somewhat shorter + * due to embedded crypto metadata section + */ + if (need_size_update) { /* update DDI properties */ - Size_prop_val = lsp->ls_vp_size; + Size_prop_val = lsp->ls_vp_size - lsp->ls_crypto_offset; if ((ddi_prop_update_int64(newdev, lofi_dip, SIZE_PROP_NAME, Size_prop_val)) != DDI_PROP_SUCCESS) { error = EINVAL; goto propout; } - - Nblocks_prop_val = lsp->ls_vp_size / DEV_BSIZE; + Nblocks_prop_val = + (lsp->ls_vp_size - lsp->ls_crypto_offset) / DEV_BSIZE; if ((ddi_prop_update_int64(newdev, lofi_dip, NBLOCKS_PROP_NAME, Nblocks_prop_val)) != DDI_PROP_SUCCESS) { error = EINVAL; @@ -1363,14 +1921,27 @@ lofi_map_file(dev_t dev, struct lofi_ioctl *ulip, int pickminor, return (0); propout: + if (keycopied) { + bzero(lsp->ls_key.ck_data, + CRYPTO_BITS2BYTES(lsp->ls_key.ck_length)); + kmem_free(lsp->ls_key.ck_data, + CRYPTO_BITS2BYTES(lsp->ls_key.ck_length)); + lsp->ls_key.ck_data = NULL; + lsp->ls_key.ck_length = 0; + } + + if (zalloced) + ddi_soft_state_free(lofi_statep, newminor); + (void) ddi_prop_remove(newdev, lofi_dip, SIZE_PROP_NAME); (void) ddi_prop_remove(newdev, lofi_dip, NBLOCKS_PROP_NAME); -closeout: - (void) VOP_CLOSE(vp, flag, 1, 0, credp, NULL); - VN_RELE(vp); + out: - if (zalloced) - ddi_soft_state_free(lofi_statep, newminor); + if (need_vn_close) { + (void) VOP_CLOSE(vp, flag, 1, 0, credp, NULL); + VN_RELE(vp); + } + mutex_exit(&lofi_lock); free_lofi_ioctl(klip); return (error); @@ -1424,14 +1995,24 @@ lofi_unmap_file(dev_t dev, struct lofi_ioctl *ulip, int byfilename, * * This is complicated by the fact that we may have outstanding * dispatched I/Os. Rather than having a single mutex to serialize all - * I/O, we keep a count of the number of outstanding I/O requests, as - * well as a flag to indicate that no new I/Os should be dispatched. + * I/O, we keep a count of the number of outstanding I/O requests + * (ls_vp_iocount), as well as a flag to indicate that no new I/Os + * should be dispatched (ls_vp_closereq). + * * We set the flag, wait for the number of outstanding I/Os to reach 0, * and then close the underlying vnode. */ - if (is_opened(lsp)) { if (klip->li_force) { + /* + * XXX: the section marked here should probably be + * carefully incorporated into lofi_free_handle(); + * afterward just replace this section with: + * lofi_free_handle(dev, minor, lsp, credp); + * and clean up lofi_unmap_file() a bit more + */ + lofi_free_crypto(lsp); + mutex_enter(&lsp->ls_vp_lock); lsp->ls_vp_closereq = B_TRUE; while (lsp->ls_vp_iocount > 0) @@ -1442,8 +2023,12 @@ lofi_unmap_file(dev_t dev, struct lofi_ioctl *ulip, int byfilename, lsp->ls_vp = NULL; cv_broadcast(&lsp->ls_vp_cv); mutex_exit(&lsp->ls_vp_lock); - mutex_exit(&lofi_lock); + /* + * XXX: to here + */ + klip->li_minor = minor; + mutex_exit(&lofi_lock); (void) copy_out_lofi_ioctl(klip, ulip, ioctl_flag); free_lofi_ioctl(klip); return (0); @@ -1504,6 +2089,7 @@ lofi_get_info(dev_t dev, struct lofi_ioctl *ulip, int which, (void) strcpy(klip->li_filename, lsp->ls_filename); (void) strlcpy(klip->li_algorithm, lsp->ls_comp_algorithm, sizeof (klip->li_algorithm)); + klip->li_crypto_enabled = lsp->ls_crypto_enabled; mutex_exit(&lofi_lock); error = copy_out_lofi_ioctl(klip, ulip, ioctl_flag); free_lofi_ioctl(klip); @@ -1511,6 +2097,7 @@ lofi_get_info(dev_t dev, struct lofi_ioctl *ulip, int which, case LOFI_GET_MINOR: mutex_enter(&lofi_lock); klip->li_minor = file_to_minor(klip->li_filename); + /* caller should not depend on klip->li_crypto_enabled here */ mutex_exit(&lofi_lock); if (klip->li_minor == 0) { free_lofi_ioctl(klip); @@ -1558,10 +2145,6 @@ lofi_ioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *credp, struct lofi_state *lsp; minor_t minor; -#ifdef lint - credp = credp; -#endif - minor = getminor(dev); /* lofi ioctls only apply to the master device */ if (minor == 0) { @@ -1724,7 +2307,7 @@ static struct dev_ops lofi_ops = { &lofi_cb_ops, /* driver operations */ NULL, /* no bus operations */ NULL, /* power */ - ddi_quiesce_not_needed, /* quiesce */ + ddi_quiesce_not_needed, /* quiesce */ }; static struct modldrv modldrv = { diff --git a/usr/src/uts/common/sys/crypto/api.h b/usr/src/uts/common/sys/crypto/api.h index af551fec31..ca789230f4 100644 --- a/usr/src/uts/common/sys/crypto/api.h +++ b/usr/src/uts/common/sys/crypto/api.h @@ -19,15 +19,13 @@ * CDDL HEADER END */ /* - * Copyright 2006 Sun Microsystems, Inc. All rights reserved. + * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _SYS_CRYPTO_API_H #define _SYS_CRYPTO_API_H -#pragma ident "%Z%%M% %I% %E% SMI" - #ifdef __cplusplus extern "C" { #endif @@ -391,6 +389,8 @@ extern int crypto_bufcall_free(crypto_bc_t bc); extern int crypto_bufcall(crypto_bc_t bc, void (*func)(void *arg), void *arg); extern int crypto_unbufcall(crypto_bc_t bc); +#endif /* _KERNEL */ + /* * To obtain the list of key size ranges supported by a mechanism. */ @@ -408,11 +408,23 @@ typedef struct crypto_mechanism_info { crypto_mech_usage_t mi_usage; } crypto_mechanism_info_t; -extern int crypto_get_all_mech_info(crypto_mech_type_t, - crypto_mechanism_info_t **, uint_t *, int); +#ifdef _KERNEL +#ifdef _SYSCALL32 +typedef struct crypto_mechanism_info32 { + size32_t mi_min_key_size; + size32_t mi_max_key_size; + crypto_keysize_unit_t mi_keysize_unit; /* for mi_xxx_key_size */ + crypto_mech_usage_t mi_usage; +} crypto_mechanism_info32_t; + +#endif /* _SYSCALL32 */ #endif /* _KERNEL */ +extern int crypto_get_all_mech_info(crypto_mech_type_t, + crypto_mechanism_info_t **, uint_t *, int); +extern void crypto_free_all_mech_info(crypto_mechanism_info_t *, uint_t); + #ifdef __cplusplus } #endif diff --git a/usr/src/uts/common/sys/crypto/ioctl.h b/usr/src/uts/common/sys/crypto/ioctl.h index 894e0b430b..ca5d748a99 100644 --- a/usr/src/uts/common/sys/crypto/ioctl.h +++ b/usr/src/uts/common/sys/crypto/ioctl.h @@ -20,20 +20,19 @@ */ /* - * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _SYS_CRYPTO_IOCTL_H #define _SYS_CRYPTO_IOCTL_H -#pragma ident "%Z%%M% %I% %E% SMI" - #ifdef __cplusplus extern "C" { #endif #include <sys/types.h> +#include <sys/crypto/api.h> #include <sys/crypto/spi.h> #include <sys/crypto/common.h> @@ -1438,6 +1437,45 @@ typedef struct crypto_nostore_derive_key32 { #define CRYPTO_NOSTORE_GENERATE_KEY_PAIR CRYPTO(128) #define CRYPTO_NOSTORE_DERIVE_KEY CRYPTO(129) +/* + * Mechanism Ioctls + */ + +typedef struct crypto_get_mechanism_list { + uint_t ml_return_value; + uint_t ml_count; + crypto_mech_name_t ml_list[1]; +} crypto_get_mechanism_list_t; + +typedef struct crypto_get_all_mechanism_info { + uint_t mi_return_value; + crypto_mech_name_t mi_mechanism_name; + uint_t mi_count; + crypto_mechanism_info_t mi_list[1]; +} crypto_get_all_mechanism_info_t; + +#ifdef _KERNEL +#ifdef _SYSCALL32 + +typedef struct crypto_get_mechanism_list32 { + uint32_t ml_return_value; + uint32_t ml_count; + crypto_mech_name_t ml_list[1]; +} crypto_get_mechanism_list32_t; + +typedef struct crypto_get_all_mechanism_info32 { + uint32_t mi_return_value; + crypto_mech_name_t mi_mechanism_name; + uint32_t mi_count; + crypto_mechanism_info32_t mi_list[1]; +} crypto_get_all_mechanism_info32_t; + +#endif /* _SYSCALL32 */ +#endif /* _KERNEL */ + +#define CRYPTO_GET_MECHANISM_LIST CRYPTO(140) +#define CRYPTO_GET_ALL_MECHANISM_INFO CRYPTO(141) + #ifdef __cplusplus } #endif diff --git a/usr/src/uts/common/sys/lofi.h b/usr/src/uts/common/sys/lofi.h index 2973b0d096..88de981361 100644 --- a/usr/src/uts/common/sys/lofi.h +++ b/usr/src/uts/common/sys/lofi.h @@ -33,6 +33,7 @@ #include <sys/vtoc.h> #include <sys/dkio.h> #include <sys/vnode.h> +#include <sys/crypto/api.h> #ifdef __cplusplus extern "C" { @@ -86,9 +87,12 @@ extern "C" { * * li.li_minor = minor_number; * ioctl(ld, LOFI_GET_FILENAME, &li); + * filename = li.li_filename; + * encrypted = li.li_crypto_enabled; * * strcpy(li.li_filename, "somefilename"); * ioctl(ld, LOFI_GET_MINOR, &li); + * minor = li.li_minor; * * li.li_minor = 0; * ioctl(ld, LOFI_GET_MAXMINOR, &li); @@ -114,12 +118,28 @@ extern "C" { * */ +typedef enum iv_method { + IVM_NONE, /* no iv needed, iv is null */ + IVM_ENC_BLKNO /* iv is logical block no. encrypted */ +} iv_method_t; + struct lofi_ioctl { uint32_t li_minor; boolean_t li_force; boolean_t li_cleanup; char li_filename[MAXPATHLEN]; + + /* the following fields are required for compression support */ char li_algorithm[MAXALGLEN]; + + /* the following fields are required for encryption support */ + boolean_t li_crypto_enabled; + crypto_mech_name_t li_cipher; /* for data */ + uint32_t li_key_len; /* for data */ + char li_key[56]; /* for data: max 448-bit Blowfish key */ + crypto_mech_name_t li_iv_cipher; /* for iv derivation */ + uint32_t li_iv_len; /* for iv derivation */ + iv_method_t li_iv_type; /* for iv derivation */ }; #define LOFI_IOC_BASE (('L' << 16) | ('F' << 8)) @@ -154,6 +174,27 @@ extern uint32_t lofi_max_files; #define V_ISLOFIABLE(vtype) \ ((vtype == VREG) || (vtype == VBLK) || (vtype == VCHR)) +/* + * Need exactly 6 bytes to identify encrypted lofi image + */ +extern const char lofi_crypto_magic[6]; +#define LOFI_CRYPTO_MAGIC { 'C', 'F', 'L', 'O', 'F', 'I' } +#define LOFI_CRYPTO_VERSION ((uint16_t)0) +#define LOFI_CRYPTO_DATA_SECTOR ((uint32_t)16) /* for version 0 */ + +/* + * Crypto metadata for encrypted lofi images + * The fields here only satisfy initial implementation requirements. + */ +struct crypto_meta { + char magic[6]; /* LOFI_CRYPTO_MAGIC */ + uint16_t version; /* version of encrypted lofi */ + char reserved1[96]; /* future use */ + uint32_t data_sector; /* start of data area */ + char pad[404]; /* end on DEV_BSIZE bdry */ + /* second header block is not defined at this time */ +}; + struct lofi_state { char *ls_filename; /* filename to open */ size_t ls_filename_sz; @@ -187,6 +228,19 @@ struct lofi_state { caddr_t ls_comp_index_data; /* index pages loaded from file */ uint32_t ls_comp_index_data_sz; u_offset_t ls_vp_comp_size; /* actual compressed file size */ + + /* the following fields are required for encryption support */ + boolean_t ls_crypto_enabled; + u_offset_t ls_crypto_offset; /* crypto meta size */ + struct crypto_meta ls_crypto; + crypto_mechanism_t ls_mech; /* for data encr/decr */ + crypto_key_t ls_key; /* for data encr/decr */ + crypto_mechanism_t ls_iv_mech; /* for iv derivation */ + size_t ls_iv_len; /* for iv derivation */ + iv_method_t ls_iv_type; /* for iv derivation */ + kmutex_t ls_crypto_lock; + crypto_ctx_template_t ls_ctx_tmpl; + }; #endif /* _KERNEL */ |