/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2009 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
* Copyright 2012 Joyent, Inc. All rights reserved.
*
* Copyright 2013 Nexenta Systems, Inc. All rights reserved.
* Copyright (c) 2014 Gary Mills
* Copyright (c) 2016 Andrey Sokolov
*/
/*
* lofiadm - administer lofi(7d). Very simple, add and remove file<->device
* associations, and display status. All the ioctls are private between
* lofi and lofiadm, and so are very simple - device information is
* communicated via a minor number.
*/
#include <sys/sysmacros.h>
#include <stdio.h>
#include <fcntl.h>
#include <locale.h>
#include <string.h>
#include <strings.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <stropts.h>
#include <libdevinfo.h>
#include <libgen.h>
#include <ctype.h>
#include <dlfcn.h>
#include <limits.h>
#include <security/cryptoki.h>
#include <cryptoutil.h>
#include "utils.h"
#include <LzmaEnc.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 [-r] [-l] -a file [ device ]\n"
" %s [-r] -c crypto_algorithm -a file [device]\n"
" %s [-r] -c crypto_algorithm -k raw_key_file -a file [device]\n"
" %s [-r] -c crypto_algorithm -T [token]:[manuf]:[serial]:key "
"-a file [device]\n"
" %s [-r] -c crypto_algorithm -T [token]:[manuf]:[serial]:key "
"-k wrapped_key_file -a file [device]\n"
" %s [-r] -c crypto_algorithm -e -a file [device]\n"
" %s -d file | device\n"
" %s -C [gzip|gzip-6|gzip-9|lzma] [-s segment_size] file\n"
" %s -U file\n"
" %s [ file | device ]\n";
typedef struct token_spec {
char *name;
char *mfr;
char *serno;
char *key;
} token_spec_t;
typedef struct mech_alias {
char *alias;
} mech_alias_t;
/* Preferred one should always be listed first. */
/*
* 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 }
*/
};
/* Preferred cipher, if one isn't specified on command line. */
};
/* For displaying lofi mappings */
static void
{
}
static int
{
/*
* The first time we are called, attempt to dlopen()
* libz.so.1 and get a pointer to the compress2() function
*/
if (compress2p == NULL) {
"gzip compression unavailable\n"), LIBZ);
if ((compress2p =
closelib();
"gzip compression unavailable\n"), LIBZ);
}
}
return (-1);
return (0);
}
/*ARGSUSED*/
static void
{
}
/*ARGSUSED*/
static void
{
}
};
/*ARGSUSED*/
static int
{
uint64_t t = 0;
int i;
/*
* The LZMA compressed file format is as follows -
*
* Offset Size(bytes) Description
* 0 1 LZMA properties (lc, lp, lp (encoded))
* 1 4 Dictionary size (little endian)
* 5 8 Uncompressed size (little endian)
* 13 Compressed data
*/
/* set the dictionary size to be 8MB */
if (*dstlen < LZMA_HEADER_SIZE)
return (SZ_ERROR_OUTPUT_EOF);
t = srclen;
/*
* Set the uncompressed size in the LZMA header
* The LZMA properties (specified in 'props')
* will be set by the call to LzmaEncode()
*/
for (i = 0; i < LZMA_UNCOMPRESSED_SIZE; i++, t >>= 8) {
}
if (res != 0)
return (-1);
return (0);
}
/*
* Translate a lofi device name to a minor number. We might be asked
* to do this when there is no association (such as when the user specifies
* a particular device), so we can only look at the string.
*/
static int
{
/*
* If devicename does not exist, then devicename contains
* the name of the device to be created.
* Note we only allow non-labeled devices here.
*/
if (rv == 1)
return (minor);
if (rv == 1)
return (minor);
return (0);
}
}
return (0);
}
/*
* This might be the first time we've used this minor number. If so,
* it might also be that the /dev links are in the process of being created
* by devfsadmd (or that they'll be created "soon"). We cannot return
* until they're there or the invoker of lofiadm might try to use them
* and not find them. This can happen if a shell script is running on
* an MP.
*/
static void
{
if (li->li_labeled)
else
return;
}
if (li->li_labeled) {
}
}
static void
{
int cursleep;
if (li->li_labeled) {
}
/* Check if links already present */
return;
/* First use di_devlink_init() */
(void) di_devlink_fini(&hdl);
goto out;
}
/*
* Under normal conditions, di_devlink_init(DI_MAKE_LINK) above will
* only fail if the caller is non-root. In that case, wait for
* link creation via sysevents.
*/
return;
}
/* one last try */
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
{
int minor;
if (minor == -1) {
"unsupported"));
}
return (minor);
}
/*
* Add a device association. If devicename is NULL, let the driver
* pick a device.
*/
static void
{
/* set up encryption for mapped file */
}
case IVM_ENC_BLKNO:
sizeof (li.li_iv_cipher));
break;
case IVM_NONE:
/* FALLTHROUGH */
default:
break;
}
}
if (devicename == NULL) {
int minor;
/* pick one via the driver */
if (minor > 0) {
/* if mapping succeeds, print the one picked */
}
return;
}
/* use device we were given */
}
/* if device is already in use li.li_minor won't change */
"unsupported"));
}
}
/*
* Remove an association. Delete by device name if non-NULL, or by
* filename otherwise.
*/
static void
{
if (devicename == NULL) {
/* delete by filename */
sizeof (li.li_filename));
}
return;
}
/* delete by device */
}
}
}
/*
* Show filename given devicename, or devicename given filename.
*/
static void
{
if (devicename == NULL) {
/* given filename, print devicename */
sizeof (li.li_filename));
}
return;
}
/* given devicename, print filename */
}
}
}
/*
* Print the list of all the mappings, including a header.
*/
static void
{
int minor;
int maxminor;
die("ioctl");
}
gettext("Options"));
continue;
warn("ioctl");
break;
}
options[0] = '\0';
/*
* Encrypted lofi and compressed lofi are mutually exclusive.
*/
if (li.li_crypto_enabled)
gettext("Encrypted"));
if (li.li_readonly) {
sizeof (options));
} else {
gettext("Readonly"));
}
}
if (li.li_labeled) {
sizeof (options));
} else {
gettext("Labeled"));
}
}
}
}
/*
* Verify the cipher selected by user.
*/
static mech_alias_t *
{
int i;
for (i = 0; i < mech_aliases_count; i++) {
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
* key size.
*/
static boolean_t
{
int i;
int count;
/* if cipher doesn't need iv generating mech, bypass that check now */
/* allocate some space for the list of kernel ciphers */
"kernel mechanisms"));
/* query crypto device to get list of kernel ciphers */
goto kcc_out;
}
goto kcc_out;
}
"kernel mechanisms"));
goto kcc_out;
}
goto kcc_out;
}
}
"CRYPTO_GET_MECHANISM_LIST ioctl return value = %d\n"),
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
*/
if (!ciph_ok &&
if (!iv_ok &&
}
if (!ciph_ok)
if (!iv_ok)
if (ciph_ok) {
/* Get the details about the user selected cipher */
"kernel mechanism info"));
goto kcc_out;
}
"CRYPTO_GET_ALL_MECHANISM_INFO ioctl failed"));
goto kcc_out;
}
sizeof (crypto_get_all_mechanism_info_t) +
"kernel mechanism info"));
goto kcc_out;
}
-1) {
"ioctl failed"));
goto kcc_out;
}
}
goto kcc_out;
}
/* Set key min and max size */
i = 0;
if (i < count) {
}
}
if (i == count) {
"failed to find usable %s kernel mechanism, "
"use \"cryptoadm list -m\" to find available "
"mechanisms\n"),
}
}
if (fd != -1)
return (B_FALSE);
}
/*
* Break up token spec into its components (non-destructive)
*/
static token_spec_t *
{
#define FLD_NAME 0
{ \
int n; \
} \
} \
}
int i;
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.
*/
break;
field[i]++;
}
if (i < NFIELDS) /* not enough fields */
return (NULL);
return (NULL);
/* key label can't be empty */
return (NULL);
return (NULL);
/*
* 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.
*/
return (ti);
}
/*
* PBE the passphrase into a raw key
*/
static void
{
void *kvalue;
/* did init_crypto find a slot that supports this cipher? */
goto cleanup;
}
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;
*/
goto cleanup;
/* get user passphrase with 8 byte minimum */
with_confirmation) < 0) {
}
/*
* 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
*/
(void) C_CloseSession(sess);
goto cleanup;
}
/* assert(klen == cipher->max_keysize); */
*raw_key_sz = klen;
return;
}
/*
* Read raw key from file; also handles ephemeral keys.
*/
void
{
int fd;
/* ephemeral keys are just random data */
" ephemeral key"));
}
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();
*/
pathname);
}
} else {
}
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.
*/
break;
}
}
}
/*
* Read the raw key from token, or from a file that was wrapped with a
* key from token
*/
void
{
{ CKA_PRIVATE, NULL, 0 }
};
int i;
char *rkey;
return;
/* did init_crypto find a slot that supports this cipher? */
"use \"cryptoadm list -p\" to find providers: %s\n"),
}
/* use passphrase to login to token */
}
}
}
/*
* 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.
*/
} else {
}
/* Find the key in the token first */
for (i = 0; i < attrs; i++) {
case CKA_CLASS:
break;
case CKA_KEY_TYPE:
break;
case CKA_LABEL:
break;
case CKA_TOKEN:
break;
case CKA_PRIVATE:
break;
default:
break;
}
}
(void) C_FindObjectsFinal(sess);
if (num_objs == 0) {
}
/*
* 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.
*/
/* obj contains raw key, extract it */
B_FALSE);
}
} else {
/*
* 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 */
}
/* rawobj contains raw key, extract it */
B_TRUE);
" key in keyfile %s, %s\n"), keyfile,
}
}
/* validate raw key size */
}
*raw_key_sz = rksz;
}
/*
* 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.
*/
{
/*
* 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".
*/
return (B_FALSE);
}
return (B_FALSE);
}
CKR_OK) {
return (B_FALSE);
}
goto foundit;
}
/* does the token match the token spec? */
return (B_FALSE);
TOKEN_LABEL_SIZE) != 0)
TOKEN_MANUFACTURER_SIZE) != 0)
TOKEN_SERIAL_SIZE) != 0)
if (!token_match)
return (B_FALSE);
return (B_TRUE);
}
/*
* Clean up crypto loose ends
*/
static void
{
(void) C_CloseSession(sess);
(void) C_Finalize(NULL);
}
/*
* Set up crypto, opening session on slot that matches token and cipher
*/
static void
{
/* Turn off Metaslot so that we can see actual tokens */
}
sess);
end_crypto(*sess);
if (rv == CKR_HOST_MEMORY) {
die("malloc");
}
"use \"cryptoadm list -p\" to find providers: %s\n"),
}
}
/*
* Uncompress a file.
*
* First map the file in to establish a device
* association, then read from it. On-the-fly
* decompression will automatically uncompress
* the file if it's compressed
*
* If the file is mapped and a device association
* has been established, disallow uncompressing
* the file until it is unmapped.
*/
static void
{
char *x;
int minor = 0;
/*
* Disallow uncompressing the file if it is
* already mapped.
*/
filename);
/* Zero length files don't need to be uncompressed */
return;
/* If the file isn't compressed, we just return */
}
}
/* Create a temp file in the same directory */
free(x);
free(x);
}
/*
* Set the mode bits and the owner of this temporary
* file to be that of the original uncompressed file
*/
}
/* Now read from the device in MAXBSIZE-sized chunks */
for (;;) {
if (rbytes <= 0)
break;
rbytes = -1;
break;
}
}
/* Delete the mapping */
/*
* If an error occured while reading or writing, rbytes will
* be negative
*/
if (rbytes < 0) {
(void) unlink(tmpfilename);
}
/* Rename the temp file to the actual file */
(void) unlink(tmpfilename);
}
/*
* Compress a file
*/
static void
{
char *x;
int i, type;
/*
* Disallow compressing the file if it is
* already mapped
*/
filename);
/*
* Close the control device so other operations
* can use it
*/
*lfd = -1;
/*
* The size of the buffer to hold compressed data must
* be slightly larger than the compressed segment size.
*
* The compress functions use part of the buffer as
* scratch space to do calculations.
* Ref: http://www.zlib.net/manual.html#compress2
*/
/*
* Use an advisory lock to ensure that only a
* single lofiadm process compresses a given
* file at any given time
*
* A close on the file descriptor automatically
* closes all lock state on the file
*/
}
/* Zero length files don't need to be compressed */
return;
}
/*
* Create temporary files in the same directory that
* will hold the intermediate data
*/
free(x);
free(x);
goto cleanup;
goto cleanup;
/*
* Set the mode bits and owner of the compressed
* file to be that of the original uncompressed file
*/
goto cleanup;
/*
* Calculate the number of index entries required.
* index entries are stored as an array. adding
* a '2' here accounts for the fact that the last
* segment may not be a multiple of the segment size
*/
goto cleanup;
offset = 0;
count = 0;
/*
* Now read from the uncompressed file in 'segsize'
* sized chunks, compress what was read in and
* write it out to a temporary file
*/
for (;;) {
if (rbytes <= 0)
break;
goto cleanup;
/*
* Account for the first byte that
* indicates whether a segment is
* compressed or not
*/
/*
* If the length of the compressed data is more
* than a threshold then there isn't any benefit
* to be had from compressing this segment - leave
* it uncompressed.
*
* NB. In case an error occurs during compression (above)
* the 'real_segsize' isn't changed. The logic below
* ensures that that segment is left uncompressed.
*/
if (segsize <= COMPRESS_THRESHOLD ||
rbytes);
type = UNCOMPRESSED;
} else {
type = COMPRESSED;
}
/*
* Set the first byte or the SEGHDR to
* indicate if it's compressed or not
*/
*compressed_seg = type;
rbytes = -1;
break;
}
count++;
}
if (rbytes < 0)
goto cleanup;
/*
* The last index entry is a sentinel entry. It does not point to
* an actual compressed segment but helps in computing the size of
* the compressed segment. The size of each compressed segment is
* computed by subtracting the current index value from the next
* one (the compressed blocks are stored sequentially)
*/
/*
* Now write the compressed data along with the
* header information to this file which will
* later be renamed to the original uncompressed
* file name
*
* The header is as follows -
*
* Signature (name of the compression algorithm)
* Compression segment size (a multiple of 512)
* Number of index entries
* Size of the last block
* The array containing the index entries
*
* the header is always stored in network byte
* order
*/
!= sizeof (algorithm))
goto cleanup;
goto cleanup;
sizeof (index_entries))
goto cleanup;
goto cleanup;
for (i = 0; i < count; i++) {
sizeof (*index))
goto cleanup;
}
/* Header is written, now write the compressed data */
goto cleanup;
for (;;) {
if (rbytes <= 0)
break;
goto cleanup;
}
goto cleanup;
/*
* Round up the compressed file size to be a multiple of
* DEV_BSIZE. lofi(7D) likes it that way.
*/
for (i = 0; i < offset; i++)
uncompressed_seg[i] = '\0';
goto cleanup;
}
(void) unlink(tmpfilename);
if (rbytes < 0) {
if (tfd != -1)
(void) unlink(tmpfilename);
if (compfd != -1)
(void) unlink(comp_filename);
} else {
/* Rename the compressed file to the actual file */
(void) unlink(comp_filename);
}
}
if (compressed_seg != NULL)
if (uncompressed_seg != NULL)
if (compfd != -1)
if (uncompfd != -1)
if (tfd != -1)
}
static int
{
int i;
for (i = 0; i < LOFI_COMPRESS_FUNCTIONS; i++) {
return (i);
}
return (-1);
}
static void
{
if (*compress_index < 0)
}
static void
{
int error;
int fd;
if (fd == -1) {
}
if (error == -1) {
"block, or character device\n"),
filename);
}
if (name_to_minor(filename) != 0) {
}
}
static boolean_t
{
int fd;
int got;
if (fd == -1)
do {
if (got > 0)
} while (rest > 0);
}
sizeof (lofi_crypto_magic)) == 0);
}
static uint32_t
{
int len;
case 'k':
case 'K':
break;
case 'b':
case 'B':
mult = BLOCK_SIZE;
break;
case 'm':
case 'M':
break;
case 'g':
case 'G':
break;
default:
}
}
return (segsize);
}
int
{
int lfd;
int c;
int openflag;
int minor;
int compress_index;
const char *pname;
/* the next two work together for -c, -k, -T, -e options only */
(void) textdomain(TEXT_DOMAIN);
switch (c) {
case 'a':
/* optional device */
optind++;
}
break;
case 'C':
/* optional algorithm */
optind++;
}
break;
case 'c':
/* is the chosen cipher allowed? */
optarg);
}
/* cipher_only is already set */
break;
case 'd':
deleteflag = B_TRUE;
if (minor != 0)
devicename = optarg;
else {
realfilename)) == NULL)
}
break;
case 'e':
break;
case 'f':
break;
case 'k':
break;
case 'l':
break;
case 'r':
break;
case 's':
"or not a multiple of minimum block "
break;
case 'T':
warn(
gettext("invalid token key specifier %s\n"),
optarg);
}
break;
case 'U':
break;
case '?':
default:
break;
}
}
/* Check for mutually exclusive combinations of options */
if (errflag ||
(addflag && deleteflag) ||
(!addflag && need_crypto) ||
(need_crypto && labelflag) ||
((compressflag || uncompressflag) &&
/* ephemeral key, and key from either file or token are incompatible */
" or token key\n"));
}
/*
* "-c" but no "-k", "-T", "-e", or "-T -k" means derive key from
* command line passphrase
*/
case 0: /* no more args */
break;
case 1:
if (addflag || deleteflag)
/* one arg means compress/uncompress the file ... */
if (compressflag || uncompressflag) {
realfilename)) == NULL)
/* ... or without options means print the association */
} else {
if (minor != 0)
else {
realfilename)) == NULL)
}
}
break;
default:
break;
}
/*
* Here, we know the arguments are correct, the filename is an
* absolute path, it exists and is a regular file. We don't yet
* know that the device name is ok or not.
*/
else
if (lfd == -1) {
"that operation.\n"));
} else {
}
/*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) {
/* pick a cipher if none specified */
if (!kernel_cipher_check(cipher))
"use \"cryptoadm list -m\" to find available "
"mechanisms\n"));
if (cipher_only) {
} else {
/* this also handles ephemeral keys */
}
}
/*
* Now to the real work.
*/
if (addflag)
else if (compressflag)
else if (uncompressflag)
else if (deleteflag)
else if (filename || devicename)
else
if (lfd != -1)
closelib();
return (E_SUCCESS);
}