Move /var/svc/log to /var/log/svc
[unleashed/lotheac.git] / usr / src / cmd / lofiadm / main.c
blob9cbc9f0aa6091506377fa150e21f9f018c85d381
1 /*
2 * CDDL HEADER START
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
19 * CDDL HEADER END
22 * Copyright 2009 Sun Microsystems, Inc. All rights reserved.
23 * Use is subject to license terms.
24 * Copyright 2012 Joyent, Inc. All rights reserved.
26 * Copyright 2013 Nexenta Systems, Inc. All rights reserved.
27 * Copyright (c) 2014 Gary Mills
28 * Copyright (c) 2016 Andrey Sokolov
32 * lofiadm - administer lofi(7d). Very simple, add and remove file<->device
33 * associations, and display status. All the ioctls are private between
34 * lofi and lofiadm, and so are very simple - device information is
35 * communicated via a minor number.
38 #include <sys/types.h>
39 #include <sys/param.h>
40 #include <sys/lofi.h>
41 #include <sys/stat.h>
42 #include <sys/sysmacros.h>
43 #include <sys/modctl.h>
44 #include <netinet/in.h>
45 #include <stdio.h>
46 #include <fcntl.h>
47 #include <locale.h>
48 #include <string.h>
49 #include <strings.h>
50 #include <errno.h>
51 #include <stdlib.h>
52 #include <unistd.h>
53 #include <stropts.h>
54 #include <libdevinfo.h>
55 #include <libgen.h>
56 #include <ctype.h>
57 #include <dlfcn.h>
58 #include <limits.h>
59 #include <security/cryptoki.h>
60 #include <cryptoutil.h>
61 #include <sys/crypto/ioctl.h>
62 #include <sys/crypto/ioctladmin.h>
63 #include <sys/cmlb.h>
64 #include <sys/mkdev.h>
65 #include "utils.h"
66 #include <LzmaEnc.h>
68 /* Only need the IV len #defines out of these files, nothing else. */
69 #include <aes/aes_impl.h>
70 #include <des/des_impl.h>
71 #include <blowfish/blowfish_impl.h>
73 static const char USAGE[] =
74 "Usage: %s [-r] [-l] -a file [ device ]\n"
75 " %s [-r] -c crypto_algorithm -a file [device]\n"
76 " %s [-r] -c crypto_algorithm -k raw_key_file -a file [device]\n"
77 " %s [-r] -c crypto_algorithm -T [token]:[manuf]:[serial]:key "
78 "-a file [device]\n"
79 " %s [-r] -c crypto_algorithm -T [token]:[manuf]:[serial]:key "
80 "-k wrapped_key_file -a file [device]\n"
81 " %s [-r] -c crypto_algorithm -e -a file [device]\n"
82 " %s -d file | device\n"
83 " %s -C [gzip|gzip-6|gzip-9|lzma] [-s segment_size] file\n"
84 " %s -U file\n"
85 " %s [ file | device ]\n";
87 typedef struct token_spec {
88 char *name;
89 char *mfr;
90 char *serno;
91 char *key;
92 } token_spec_t;
94 typedef struct mech_alias {
95 char *alias;
96 CK_MECHANISM_TYPE type;
97 char *name; /* for ioctl */
98 char *iv_name; /* for ioctl */
99 size_t iv_len; /* for ioctl */
100 iv_method_t iv_type; /* for ioctl */
101 size_t min_keysize; /* in bytes */
102 size_t max_keysize; /* in bytes */
103 token_spec_t *token;
104 CK_SLOT_ID slot;
105 } mech_alias_t;
107 static mech_alias_t mech_aliases[] = {
108 /* Preferred one should always be listed first. */
109 { "aes-256-cbc", CKM_AES_CBC, "CKM_AES_CBC", "CKM_AES_ECB", AES_IV_LEN,
110 IVM_ENC_BLKNO, ULONG_MAX, 0L, NULL, (CK_SLOT_ID) -1 },
111 { "aes-192-cbc", CKM_AES_CBC, "CKM_AES_CBC", "CKM_AES_ECB", AES_IV_LEN,
112 IVM_ENC_BLKNO, ULONG_MAX, 0L, NULL, (CK_SLOT_ID) -1 },
113 { "aes-128-cbc", CKM_AES_CBC, "CKM_AES_CBC", "CKM_AES_ECB", AES_IV_LEN,
114 IVM_ENC_BLKNO, ULONG_MAX, 0L, NULL, (CK_SLOT_ID) -1 },
115 { "des3-cbc", CKM_DES3_CBC, "CKM_DES3_CBC", "CKM_DES3_ECB", DES_IV_LEN,
116 IVM_ENC_BLKNO, ULONG_MAX, 0L, NULL, (CK_SLOT_ID)-1 },
117 { "blowfish-cbc", CKM_BLOWFISH_CBC, "CKM_BLOWFISH_CBC",
118 "CKM_BLOWFISH_ECB", BLOWFISH_IV_LEN, IVM_ENC_BLKNO, ULONG_MAX,
119 0L, NULL, (CK_SLOT_ID)-1 }
121 * A cipher without an iv requirement would look like this:
122 * { "aes-xex", CKM_AES_XEX, "CKM_AES_XEX", NULL, 0,
123 * IVM_NONE, ULONG_MAX, 0L, NULL, (CK_SLOT_ID)-1 }
127 int mech_aliases_count = (sizeof (mech_aliases) / sizeof (mech_alias_t));
129 /* Preferred cipher, if one isn't specified on command line. */
130 #define DEFAULT_CIPHER (&mech_aliases[0])
132 #define DEFAULT_CIPHER_NUM 64 /* guess # kernel ciphers available */
133 #define DEFAULT_MECHINFO_NUM 16 /* guess # kernel mechs available */
134 #define MIN_PASSLEN 8 /* min acceptable passphrase size */
136 static int gzip_compress(void *src, size_t srclen, void *dst,
137 size_t *destlen, int level);
138 static int lzma_compress(void *src, size_t srclen, void *dst,
139 size_t *destlen, int level);
141 lofi_compress_info_t lofi_compress_table[LOFI_COMPRESS_FUNCTIONS] = {
142 {NULL, gzip_compress, 6, "gzip"}, /* default */
143 {NULL, gzip_compress, 6, "gzip-6"},
144 {NULL, gzip_compress, 9, "gzip-9"},
145 {NULL, lzma_compress, 0, "lzma"}
148 /* For displaying lofi mappings */
149 #define FORMAT "%-20s %-30s %s\n"
151 #define COMPRESS_ALGORITHM "gzip"
152 #define COMPRESS_THRESHOLD 2048
153 #define SEGSIZE 131072
154 #define BLOCK_SIZE 512
155 #define KILOBYTE 1024
156 #define MEGABYTE (KILOBYTE * KILOBYTE)
157 #define GIGABYTE (KILOBYTE * MEGABYTE)
158 #define LIBZ "libz.so.1"
160 const char lofi_crypto_magic[6] = LOFI_CRYPTO_MAGIC;
162 static void
163 usage(const char *pname)
165 (void) fprintf(stderr, gettext(USAGE), pname, pname, pname,
166 pname, pname, pname, pname, pname, pname, pname);
167 exit(E_USAGE);
170 static int
171 gzip_compress(void *src, size_t srclen, void *dst, size_t *dstlen, int level)
173 static int (*compress2p)(void *, ulong_t *, void *, size_t, int) = NULL;
174 void *libz_hdl = NULL;
177 * The first time we are called, attempt to dlopen()
178 * libz.so.1 and get a pointer to the compress2() function
180 if (compress2p == NULL) {
181 if ((libz_hdl = openlib(LIBZ)) == NULL)
182 die(gettext("could not find %s. "
183 "gzip compression unavailable\n"), LIBZ);
185 if ((compress2p =
186 (int (*)(void *, ulong_t *, void *, size_t, int))
187 dlsym(libz_hdl, "compress2")) == NULL) {
188 closelib();
189 die(gettext("could not find the correct %s. "
190 "gzip compression unavailable\n"), LIBZ);
194 if ((*compress2p)(dst, (ulong_t *)dstlen, src, srclen, level) != 0)
195 return (-1);
196 return (0);
199 /*ARGSUSED*/
200 static void
201 *SzAlloc(void *p, size_t size)
203 return (malloc(size));
206 /*ARGSUSED*/
207 static void
208 SzFree(void *p, void *address, size_t size)
210 free(address);
213 static ISzAlloc g_Alloc = {
214 SzAlloc,
215 SzFree
218 #define LZMA_UNCOMPRESSED_SIZE 8
219 #define LZMA_HEADER_SIZE (LZMA_PROPS_SIZE + LZMA_UNCOMPRESSED_SIZE)
221 /*ARGSUSED*/
222 static int
223 lzma_compress(void *src, size_t srclen, void *dst,
224 size_t *dstlen, int level)
226 CLzmaEncProps props;
227 size_t outsize2;
228 size_t outsizeprocessed;
229 size_t outpropssize = LZMA_PROPS_SIZE;
230 uint64_t t = 0;
231 SRes res;
232 Byte *dstp;
233 int i;
235 outsize2 = *dstlen;
237 LzmaEncProps_Init(&props);
240 * The LZMA compressed file format is as follows -
242 * Offset Size(bytes) Description
243 * 0 1 LZMA properties (lc, lp, lp (encoded))
244 * 1 4 Dictionary size (little endian)
245 * 5 8 Uncompressed size (little endian)
246 * 13 Compressed data
249 /* set the dictionary size to be 8MB */
250 props.dictSize = 1 << 23;
252 if (*dstlen < LZMA_HEADER_SIZE)
253 return (SZ_ERROR_OUTPUT_EOF);
255 dstp = (Byte *)dst;
256 t = srclen;
258 * Set the uncompressed size in the LZMA header
259 * The LZMA properties (specified in 'props')
260 * will be set by the call to LzmaEncode()
262 for (i = 0; i < LZMA_UNCOMPRESSED_SIZE; i++, t >>= 8) {
263 dstp[LZMA_PROPS_SIZE + i] = (Byte)t;
266 outsizeprocessed = outsize2 - LZMA_HEADER_SIZE;
267 res = LzmaEncode(dstp + LZMA_HEADER_SIZE, &outsizeprocessed,
268 src, srclen, &props, dstp, &outpropssize, 0, NULL,
269 &g_Alloc, &g_Alloc);
271 if (res != 0)
272 return (-1);
274 *dstlen = outsizeprocessed + LZMA_HEADER_SIZE;
275 return (0);
279 * Translate a lofi device name to a minor number. We might be asked
280 * to do this when there is no association (such as when the user specifies
281 * a particular device), so we can only look at the string.
283 static int
284 name_to_minor(const char *devicename)
286 struct stat st;
289 * If devicename does not exist, then devicename contains
290 * the name of the device to be created.
291 * Note we only allow non-labeled devices here.
293 if (stat(devicename, &st)) {
294 int minor, rv;
296 rv = sscanf(devicename, "/dev/" LOFI_BLOCK_NAME "/%d", &minor);
297 if (rv == 1)
298 return (minor);
299 rv = sscanf(devicename, "/dev/" LOFI_CHAR_NAME "/%d", &minor);
300 if (rv == 1)
301 return (minor);
303 return (0);
307 * For disk devices we use modctl(MODGETNAME) to read driver name
308 * for major device.
310 if (st.st_mode & S_IFCHR || st.st_mode & S_IFBLK) {
311 major_t maj;
312 char mname[MODMAXNAMELEN];
314 maj = major(st.st_rdev);
316 if (modctl(MODGETNAME, mname, MODMAXNAMELEN, &maj) == 0) {
317 if (strncmp(mname, LOFI_DRIVER_NAME,
318 sizeof (LOFI_DRIVER_NAME)) == 0) {
319 return (LOFI_MINOR2ID(minor(st.st_rdev)));
324 return (0);
328 * This might be the first time we've used this minor number. If so,
329 * it might also be that the /dev links are in the process of being created
330 * by devfsadmd (or that they'll be created "soon"). We cannot return
331 * until they're there or the invoker of lofiadm might try to use them
332 * and not find them. This can happen if a shell script is running on
333 * an MP.
335 static int sleeptime = 2; /* number of seconds to sleep between stat's */
336 static int maxsleep = 120; /* maximum number of seconds to sleep */
338 static void
339 make_blkdevname(struct lofi_ioctl *li, char *path, size_t len)
341 char *r1, *r2;
342 size_t l1;
344 if (li->li_devpath[0] == '\0') {
345 if (li->li_labeled)
346 (void) strlcpy(path, "unknown", len);
347 else
348 (void) snprintf(path, len,
349 "/dev/" LOFI_BLOCK_NAME "/%d", li->li_id);
350 return;
352 (void) strlcpy(path, li->li_devpath, len);
353 r1 = strchr(path, 'r');
354 l1 = r1 - path;
355 r2 = strchr(li->li_devpath, 'r');
356 (void) strlcpy(r1, r2+1, len - l1);
358 if (li->li_labeled) {
359 (void) strlcat(path, "p0", len);
363 static void
364 wait_until_dev_complete(struct lofi_ioctl *li)
366 struct stat buf;
367 int cursleep;
368 char blkpath[MAXPATHLEN];
369 char charpath[MAXPATHLEN];
370 di_devlink_handle_t hdl;
372 make_blkdevname(li, blkpath, sizeof (blkpath));
373 (void) strlcpy(charpath, li->li_devpath, sizeof (charpath));
375 if (li->li_labeled) {
376 (void) strlcat(charpath, "p0", sizeof (charpath));
379 /* Check if links already present */
380 if (stat(blkpath, &buf) == 0 && stat(charpath, &buf) == 0)
381 return;
383 /* First use di_devlink_init() */
384 if (hdl = di_devlink_init("lofi", DI_MAKE_LINK)) {
385 (void) di_devlink_fini(&hdl);
386 goto out;
390 * Under normal conditions, di_devlink_init(DI_MAKE_LINK) above will
391 * only fail if the caller is non-root. In that case, wait for
392 * link creation via sysevents.
394 for (cursleep = 0; cursleep < maxsleep; cursleep += sleeptime) {
395 if (stat(blkpath, &buf) == 0 && stat(charpath, &buf) == 0)
396 return;
397 (void) sleep(sleeptime);
400 /* one last try */
401 out:
402 if (stat(blkpath, &buf) == -1) {
403 die(gettext("%s was not created"), blkpath);
405 if (stat(charpath, &buf) == -1) {
406 die(gettext("%s was not created"), charpath);
411 * Map the file and return the minor number the driver picked for the file
412 * DO NOT use this function if the filename is actually the device name.
414 static int
415 lofi_map_file(int lfd, struct lofi_ioctl *li, const char *filename)
417 int minor;
419 li->li_id = 0;
420 (void) strlcpy(li->li_filename, filename, sizeof (li->li_filename));
421 minor = ioctl(lfd, LOFI_MAP_FILE, li);
422 if (minor == -1) {
423 if (errno == ENOTSUP)
424 warn(gettext("encrypting compressed files is "
425 "unsupported"));
426 die(gettext("could not map file %s"), filename);
428 wait_until_dev_complete(li);
429 return (minor);
433 * Add a device association. If devicename is NULL, let the driver
434 * pick a device.
436 static void
437 add_mapping(int lfd, const char *devicename, const char *filename,
438 mech_alias_t *cipher, const char *rkey, size_t rksz, boolean_t rdonly,
439 boolean_t label)
441 struct lofi_ioctl li;
443 bzero(&li, sizeof (li));
444 li.li_readonly = rdonly;
445 li.li_labeled = label;
447 li.li_crypto_enabled = B_FALSE;
448 if (cipher != NULL) {
449 /* set up encryption for mapped file */
450 li.li_crypto_enabled = B_TRUE;
451 (void) strlcpy(li.li_cipher, cipher->name,
452 sizeof (li.li_cipher));
453 if (rksz > sizeof (li.li_key)) {
454 die(gettext("key too large"));
456 bcopy(rkey, li.li_key, rksz);
457 li.li_key_len = rksz << 3; /* convert to bits */
459 li.li_iv_type = cipher->iv_type;
460 li.li_iv_len = cipher->iv_len; /* 0 when no iv needed */
461 switch (cipher->iv_type) {
462 case IVM_ENC_BLKNO:
463 (void) strlcpy(li.li_iv_cipher, cipher->iv_name,
464 sizeof (li.li_iv_cipher));
465 break;
466 case IVM_NONE:
467 /* FALLTHROUGH */
468 default:
469 break;
473 if (devicename == NULL) {
474 int minor;
475 char path[MAXPATHLEN];
477 /* pick one via the driver */
478 minor = lofi_map_file(lfd, &li, filename);
479 if (minor > 0) {
480 make_blkdevname(&li, path, sizeof (path));
482 /* if mapping succeeds, print the one picked */
483 (void) printf("%s\n", path);
485 return;
488 /* use device we were given */
489 li.li_id = name_to_minor(devicename);
490 if (li.li_id == 0) {
491 die(gettext("malformed device name %s\n"), devicename);
493 (void) strlcpy(li.li_filename, filename, sizeof (li.li_filename));
495 /* if device is already in use li.li_minor won't change */
496 if (ioctl(lfd, LOFI_MAP_FILE_MINOR, &li) == -1) {
497 if (errno == ENOTSUP)
498 warn(gettext("encrypting compressed files is "
499 "unsupported"));
500 die(gettext("could not map file %s to %s"), filename,
501 devicename);
503 wait_until_dev_complete(&li);
507 * Remove an association. Delete by device name if non-NULL, or by
508 * filename otherwise.
510 static void
511 delete_mapping(int lfd, const char *devicename, const char *filename,
512 boolean_t force)
514 struct lofi_ioctl li;
516 li.li_force = force;
517 li.li_cleanup = B_FALSE;
519 if (devicename == NULL) {
520 /* delete by filename */
521 (void) strlcpy(li.li_filename, filename,
522 sizeof (li.li_filename));
523 li.li_id = 0;
524 if (ioctl(lfd, LOFI_UNMAP_FILE, &li) == -1) {
525 die(gettext("could not unmap file %s"), filename);
527 return;
530 /* delete by device */
531 li.li_id = name_to_minor(devicename);
532 if (li.li_id == 0) {
533 die(gettext("malformed device name %s\n"), devicename);
535 if (ioctl(lfd, LOFI_UNMAP_FILE_MINOR, &li) == -1) {
536 die(gettext("could not unmap device %s"), devicename);
541 * Show filename given devicename, or devicename given filename.
543 static void
544 print_one_mapping(int lfd, const char *devicename, const char *filename)
546 struct lofi_ioctl li;
547 char blkpath[MAXPATHLEN];
549 if (devicename == NULL) {
550 /* given filename, print devicename */
551 li.li_id = 0;
552 (void) strlcpy(li.li_filename, filename,
553 sizeof (li.li_filename));
554 if (ioctl(lfd, LOFI_GET_MINOR, &li) == -1) {
555 die(gettext("could not find device for %s"), filename);
557 make_blkdevname(&li, blkpath, sizeof (blkpath));
558 (void) printf("%s\n", blkpath);
559 return;
562 /* given devicename, print filename */
563 li.li_id = name_to_minor(devicename);
564 if (li.li_id == 0) {
565 die(gettext("malformed device name %s\n"), devicename);
567 if (ioctl(lfd, LOFI_GET_FILENAME, &li) == -1) {
568 die(gettext("could not find filename for %s"), devicename);
570 (void) printf("%s\n", li.li_filename);
574 * Print the list of all the mappings, including a header.
576 static void
577 print_mappings(int fd)
579 struct lofi_ioctl li;
580 int minor;
581 int maxminor;
582 char path[MAXPATHLEN];
583 char options[MAXPATHLEN] = { 0 };
585 li.li_id = 0;
586 if (ioctl(fd, LOFI_GET_MAXMINOR, &li) == -1) {
587 die("ioctl");
589 maxminor = li.li_id;
591 (void) printf(FORMAT, gettext("Block Device"), gettext("File"),
592 gettext("Options"));
593 for (minor = 1; minor <= maxminor; minor++) {
594 li.li_id = minor;
595 if (ioctl(fd, LOFI_GET_FILENAME, &li) == -1) {
596 if (errno == ENXIO)
597 continue;
598 warn("ioctl");
599 break;
601 make_blkdevname(&li, path, sizeof (path));
603 options[0] = '\0';
606 * Encrypted lofi and compressed lofi are mutually exclusive.
608 if (li.li_crypto_enabled)
609 (void) snprintf(options, sizeof (options),
610 gettext("Encrypted"));
611 else if (li.li_algorithm[0] != '\0')
612 (void) snprintf(options, sizeof (options),
613 gettext("Compressed(%s)"), li.li_algorithm);
614 if (li.li_readonly) {
615 if (strlen(options) != 0) {
616 (void) strlcat(options, ",Readonly",
617 sizeof (options));
618 } else {
619 (void) snprintf(options, sizeof (options),
620 gettext("Readonly"));
623 if (li.li_labeled) {
624 if (strlen(options) != 0) {
625 (void) strlcat(options, ",Labeled",
626 sizeof (options));
627 } else {
628 (void) snprintf(options, sizeof (options),
629 gettext("Labeled"));
632 if (strlen(options) == 0)
633 (void) snprintf(options, sizeof (options), "-");
635 (void) printf(FORMAT, path, li.li_filename, options);
640 * Verify the cipher selected by user.
642 static mech_alias_t *
643 ciph2mech(const char *alias)
645 int i;
647 for (i = 0; i < mech_aliases_count; i++) {
648 if (strcasecmp(alias, mech_aliases[i].alias) == 0)
649 return (&mech_aliases[i]);
651 return (NULL);
655 * Verify user selected cipher is also available in kernel.
657 * While traversing kernel list of mechs, if the cipher is supported in the
658 * kernel for both encryption and decryption, it also picks up the min/max
659 * key size.
661 static boolean_t
662 kernel_cipher_check(mech_alias_t *cipher)
664 boolean_t ciph_ok = B_FALSE;
665 boolean_t iv_ok = B_FALSE;
666 int i;
667 int count;
668 crypto_get_mechanism_list_t *kciphers = NULL;
669 crypto_get_all_mechanism_info_t *kinfo = NULL;
670 int fd = -1;
671 size_t keymin;
672 size_t keymax;
674 /* if cipher doesn't need iv generating mech, bypass that check now */
675 if (cipher->iv_name == NULL)
676 iv_ok = B_TRUE;
678 /* allocate some space for the list of kernel ciphers */
679 count = DEFAULT_CIPHER_NUM;
680 kciphers = malloc(sizeof (crypto_get_mechanism_list_t) +
681 sizeof (crypto_mech_name_t) * (count - 1));
682 if (kciphers == NULL)
683 die(gettext("failed to allocate memory for list of "
684 "kernel mechanisms"));
685 kciphers->ml_count = count;
687 /* query crypto device to get list of kernel ciphers */
688 if ((fd = open("/dev/crypto", O_RDWR)) == -1) {
689 warn(gettext("failed to open %s"), "/dev/crypto");
690 goto kcc_out;
693 if (ioctl(fd, CRYPTO_GET_MECHANISM_LIST, kciphers) == -1) {
694 warn(gettext("CRYPTO_GET_MECHANISM_LIST ioctl failed"));
695 goto kcc_out;
698 if (kciphers->ml_return_value == CRYPTO_BUFFER_TOO_SMALL) {
699 count = kciphers->ml_count;
700 free(kciphers);
701 kciphers = malloc(sizeof (crypto_get_mechanism_list_t) +
702 sizeof (crypto_mech_name_t) * (count - 1));
703 if (kciphers == NULL) {
704 warn(gettext("failed to allocate memory for list of "
705 "kernel mechanisms"));
706 goto kcc_out;
708 kciphers->ml_count = count;
710 if (ioctl(fd, CRYPTO_GET_MECHANISM_LIST, kciphers) == -1) {
711 warn(gettext("CRYPTO_GET_MECHANISM_LIST ioctl failed"));
712 goto kcc_out;
716 if (kciphers->ml_return_value != CRYPTO_SUCCESS) {
717 warn(gettext(
718 "CRYPTO_GET_MECHANISM_LIST ioctl return value = %d\n"),
719 kciphers->ml_return_value);
720 goto kcc_out;
724 * scan list of kernel ciphers looking for the selected one and if
725 * it needs an iv generated using another cipher, also look for that
726 * additional cipher to be used for generating the iv
728 count = kciphers->ml_count;
729 for (i = 0; i < count && !(ciph_ok && iv_ok); i++) {
730 if (!ciph_ok &&
731 strcasecmp(cipher->name, kciphers->ml_list[i]) == 0)
732 ciph_ok = B_TRUE;
733 if (!iv_ok &&
734 strcasecmp(cipher->iv_name, kciphers->ml_list[i]) == 0)
735 iv_ok = B_TRUE;
737 free(kciphers);
738 kciphers = NULL;
740 if (!ciph_ok)
741 warn(gettext("%s mechanism not supported in kernel\n"),
742 cipher->name);
743 if (!iv_ok)
744 warn(gettext("%s mechanism not supported in kernel\n"),
745 cipher->iv_name);
747 if (ciph_ok) {
748 /* Get the details about the user selected cipher */
749 count = DEFAULT_MECHINFO_NUM;
750 kinfo = malloc(sizeof (crypto_get_all_mechanism_info_t) +
751 sizeof (crypto_mechanism_info_t) * (count - 1));
752 if (kinfo == NULL) {
753 warn(gettext("failed to allocate memory for "
754 "kernel mechanism info"));
755 goto kcc_out;
757 kinfo->mi_count = count;
758 (void) strlcpy(kinfo->mi_mechanism_name, cipher->name,
759 CRYPTO_MAX_MECH_NAME);
761 if (ioctl(fd, CRYPTO_GET_ALL_MECHANISM_INFO, kinfo) == -1) {
762 warn(gettext(
763 "CRYPTO_GET_ALL_MECHANISM_INFO ioctl failed"));
764 goto kcc_out;
767 if (kinfo->mi_return_value == CRYPTO_BUFFER_TOO_SMALL) {
768 count = kinfo->mi_count;
769 free(kinfo);
770 kinfo = malloc(
771 sizeof (crypto_get_all_mechanism_info_t) +
772 sizeof (crypto_mechanism_info_t) * (count - 1));
773 if (kinfo == NULL) {
774 warn(gettext("failed to allocate memory for "
775 "kernel mechanism info"));
776 goto kcc_out;
778 kinfo->mi_count = count;
779 (void) strlcpy(kinfo->mi_mechanism_name, cipher->name,
780 CRYPTO_MAX_MECH_NAME);
782 if (ioctl(fd, CRYPTO_GET_ALL_MECHANISM_INFO, kinfo) ==
783 -1) {
784 warn(gettext("CRYPTO_GET_ALL_MECHANISM_INFO "
785 "ioctl failed"));
786 goto kcc_out;
790 if (kinfo->mi_return_value != CRYPTO_SUCCESS) {
791 warn(gettext("CRYPTO_GET_ALL_MECHANISM_INFO ioctl "
792 "return value = %d\n"), kinfo->mi_return_value);
793 goto kcc_out;
796 /* Set key min and max size */
797 count = kinfo->mi_count;
798 i = 0;
799 if (i < count) {
800 keymin = kinfo->mi_list[i].mi_min_key_size;
801 keymax = kinfo->mi_list[i].mi_max_key_size;
802 if (kinfo->mi_list[i].mi_keysize_unit &
803 CRYPTO_KEYSIZE_UNIT_IN_BITS) {
804 keymin = CRYPTO_BITS2BYTES(keymin);
805 keymax = CRYPTO_BITS2BYTES(keymax);
808 cipher->min_keysize = keymin;
809 cipher->max_keysize = keymax;
811 free(kinfo);
812 kinfo = NULL;
814 if (i == count) {
815 (void) close(fd);
816 die(gettext(
817 "failed to find usable %s kernel mechanism, "
818 "use \"cryptoadm list -m\" to find available "
819 "mechanisms\n"),
820 cipher->name);
824 /* Note: key min/max, unit size, usage for iv cipher are not checked. */
826 return (ciph_ok && iv_ok);
828 kcc_out:
829 free(kinfo);
830 free(kciphers);
831 if (fd != -1)
832 (void) close(fd);
833 return (B_FALSE);
837 * Break up token spec into its components (non-destructive)
839 static token_spec_t *
840 parsetoken(char *spec)
842 #define FLD_NAME 0
843 #define FLD_MANUF 1
844 #define FLD_SERIAL 2
845 #define FLD_LABEL 3
846 #define NFIELDS 4
847 #define nullfield(i) ((field[(i)+1] - field[(i)]) <= 1)
848 #define copyfield(fld, i) \
850 int n; \
851 (fld) = NULL; \
852 if ((n = (field[(i)+1] - field[(i)])) > 1) { \
853 if (((fld) = malloc(n)) != NULL) { \
854 (void) strncpy((fld), field[(i)], n); \
855 ((fld))[n - 1] = '\0'; \
860 int i;
861 char *field[NFIELDS + 1]; /* +1 to catch extra delimiters */
862 token_spec_t *ti = NULL;
864 if (spec == NULL)
865 return (NULL);
868 * Correct format is "[name]:[manuf]:[serial]:key". Can't use
869 * strtok because it treats ":::key" and "key:::" and "key" all
870 * as the same thing, and we can't have the :s compressed away.
872 field[0] = spec;
873 for (i = 1; i < NFIELDS + 1; i++) {
874 field[i] = strchr(field[i-1], ':');
875 if (field[i] == NULL)
876 break;
877 field[i]++;
879 if (i < NFIELDS) /* not enough fields */
880 return (NULL);
881 if (field[NFIELDS] != NULL) /* too many fields */
882 return (NULL);
883 field[NFIELDS] = strchr(field[NFIELDS-1], '\0') + 1;
885 /* key label can't be empty */
886 if (nullfield(FLD_LABEL))
887 return (NULL);
889 ti = malloc(sizeof (token_spec_t));
890 if (ti == NULL)
891 return (NULL);
893 copyfield(ti->name, FLD_NAME);
894 copyfield(ti->mfr, FLD_MANUF);
895 copyfield(ti->serno, FLD_SERIAL);
896 copyfield(ti->key, FLD_LABEL);
899 * If token specified and it only contains a key label, then
900 * search all tokens for the key, otherwise only those with
901 * matching name, mfr, and serno are used.
904 * That's how we'd like it to be, however, if only the key label
905 * is specified, default to using softtoken. It's easier.
907 if (ti->name == NULL && ti->mfr == NULL && ti->serno == NULL)
908 ti->name = strdup(pkcs11_default_token());
909 return (ti);
913 * PBE the passphrase into a raw key
915 static void
916 getkeyfromuser(mech_alias_t *cipher, char **raw_key, size_t *raw_key_sz,
917 boolean_t with_confirmation)
919 CK_SESSION_HANDLE sess;
920 CK_RV rv;
921 char *pass = NULL;
922 size_t passlen = 0;
923 void *salt = NULL; /* don't use NULL, see note on salt below */
924 size_t saltlen = 0;
925 CK_KEY_TYPE ktype;
926 void *kvalue;
927 size_t klen;
929 /* did init_crypto find a slot that supports this cipher? */
930 if (cipher->slot == (CK_SLOT_ID)-1 || cipher->max_keysize == 0) {
931 rv = CKR_MECHANISM_INVALID;
932 goto cleanup;
935 rv = pkcs11_mech2keytype(cipher->type, &ktype);
936 if (rv != CKR_OK)
937 goto cleanup;
940 * use the passphrase to generate a PBE PKCS#5 secret key and
941 * retrieve the raw key data to eventually pass it to the kernel;
943 rv = C_OpenSession(cipher->slot, CKF_SERIAL_SESSION, NULL, NULL, &sess);
944 if (rv != CKR_OK)
945 goto cleanup;
947 /* get user passphrase with 8 byte minimum */
948 if (pkcs11_get_pass(NULL, &pass, &passlen, MIN_PASSLEN,
949 with_confirmation) < 0) {
950 die(gettext("passphrases do not match\n"));
954 * salt should not be NULL, or else pkcs11_PasswdToKey() will
955 * complain about CKR_MECHANISM_PARAM_INVALID; the following is
956 * to make up for not having a salt until a proper one is used
958 salt = pass;
959 saltlen = passlen;
961 klen = cipher->max_keysize;
962 rv = pkcs11_PasswdToKey(sess, pass, passlen, salt, saltlen, ktype,
963 cipher->max_keysize, &kvalue, &klen);
965 (void) C_CloseSession(sess);
967 if (rv != CKR_OK) {
968 goto cleanup;
971 /* assert(klen == cipher->max_keysize); */
972 *raw_key_sz = klen;
973 *raw_key = (char *)kvalue;
974 return;
976 cleanup:
977 die(gettext("failed to generate %s key from passphrase: %s"),
978 cipher->alias, pkcs11_strerror(rv));
982 * Read raw key from file; also handles ephemeral keys.
984 void
985 getkeyfromfile(const char *pathname, mech_alias_t *cipher, char **key,
986 size_t *ksz)
988 int fd;
989 struct stat sbuf;
990 boolean_t notplain = B_FALSE;
991 ssize_t cursz;
992 ssize_t nread;
994 /* ephemeral keys are just random data */
995 if (pathname == NULL) {
996 *ksz = cipher->max_keysize;
997 *key = malloc(*ksz);
998 if (*key == NULL)
999 die(gettext("failed to allocate memory for"
1000 " ephemeral key"));
1001 if (pkcs11_get_urandom(*key, *ksz) < 0) {
1002 free(*key);
1003 die(gettext("failed to get enough random data"));
1005 return;
1009 * If the remaining section of code didn't also check for secure keyfile
1010 * permissions and whether the key is within cipher min and max lengths,
1011 * (or, if those things moved out of this block), we could have had:
1012 * if (pkcs11_read_data(pathname, key, ksz) < 0)
1013 * handle_error();
1016 if ((fd = open(pathname, O_RDONLY, 0)) == -1)
1017 die(gettext("open of keyfile (%s) failed"), pathname);
1019 if (fstat(fd, &sbuf) == -1)
1020 die(gettext("fstat of keyfile (%s) failed"), pathname);
1022 if (S_ISREG(sbuf.st_mode)) {
1023 if ((sbuf.st_mode & (S_IWGRP | S_IWOTH)) != 0)
1024 die(gettext("insecure permissions on keyfile %s\n"),
1025 pathname);
1027 *ksz = sbuf.st_size;
1028 if (*ksz < cipher->min_keysize || cipher->max_keysize < *ksz) {
1029 warn(gettext("%s: invalid keysize: %d\n"),
1030 pathname, (int)*ksz);
1031 die(gettext("\t%d <= keysize <= %d\n"),
1032 cipher->min_keysize, cipher->max_keysize);
1034 } else {
1035 *ksz = cipher->max_keysize;
1036 notplain = B_TRUE;
1039 *key = malloc(*ksz);
1040 if (*key == NULL)
1041 die(gettext("failed to allocate memory for key from file"));
1043 for (cursz = 0, nread = 0; cursz < *ksz; cursz += nread) {
1044 nread = read(fd, *key, *ksz);
1045 if (nread > 0)
1046 continue;
1048 * nread == 0. If it's not a regular file we were trying to
1049 * get the maximum keysize of data possible for this cipher.
1050 * But if we've got at least the minimum keysize of data,
1051 * round down to the nearest keysize unit and call it good.
1052 * If we haven't met the minimum keysize, that's an error.
1053 * If it's a regular file, nread = 0 is also an error.
1055 if (nread == 0 && notplain && cursz >= cipher->min_keysize) {
1056 *ksz = (cursz / cipher->min_keysize) *
1057 cipher->min_keysize;
1058 break;
1060 die(gettext("%s: can't read all keybytes"), pathname);
1062 (void) close(fd);
1066 * Read the raw key from token, or from a file that was wrapped with a
1067 * key from token
1069 void
1070 getkeyfromtoken(CK_SESSION_HANDLE sess,
1071 token_spec_t *token, const char *keyfile, mech_alias_t *cipher,
1072 char **raw_key, size_t *raw_key_sz)
1074 CK_RV rv = CKR_OK;
1075 CK_BBOOL trueval = B_TRUE;
1076 CK_OBJECT_CLASS kclass; /* secret key or RSA private key */
1077 CK_KEY_TYPE ktype; /* from selected cipher or CKK_RSA */
1078 CK_KEY_TYPE raw_ktype; /* from selected cipher */
1079 CK_ATTRIBUTE key_tmpl[] = {
1080 { CKA_CLASS, NULL, 0 }, /* re-used for token key and unwrap */
1081 { CKA_KEY_TYPE, NULL, 0 }, /* ditto */
1082 { CKA_LABEL, NULL, 0 },
1083 { CKA_TOKEN, NULL, 0 },
1084 { CKA_PRIVATE, NULL, 0 }
1086 CK_ULONG attrs = sizeof (key_tmpl) / sizeof (CK_ATTRIBUTE);
1087 int i;
1088 char *pass = NULL;
1089 size_t passlen = 0;
1090 CK_OBJECT_HANDLE obj, rawobj;
1091 CK_ULONG num_objs = 1; /* just want to find 1 token key */
1092 CK_MECHANISM unwrap = { CKM_RSA_PKCS, NULL, 0 };
1093 char *rkey;
1094 size_t rksz;
1096 if (token == NULL || token->key == NULL)
1097 return;
1099 /* did init_crypto find a slot that supports this cipher? */
1100 if (cipher->slot == (CK_SLOT_ID)-1 || cipher->max_keysize == 0) {
1101 die(gettext("failed to find any cryptographic provider, "
1102 "use \"cryptoadm list -p\" to find providers: %s\n"),
1103 pkcs11_strerror(CKR_MECHANISM_INVALID));
1106 if (pkcs11_get_pass(token->name, &pass, &passlen, 0, B_FALSE) < 0)
1107 die(gettext("unable to get passphrase"));
1109 /* use passphrase to login to token */
1110 if (pass != NULL && passlen > 0) {
1111 rv = C_Login(sess, CKU_USER, (CK_UTF8CHAR_PTR)pass, passlen);
1112 if (rv != CKR_OK) {
1113 die(gettext("cannot login to the token %s: %s\n"),
1114 token->name, pkcs11_strerror(rv));
1118 rv = pkcs11_mech2keytype(cipher->type, &raw_ktype);
1119 if (rv != CKR_OK) {
1120 die(gettext("failed to get key type for cipher %s: %s\n"),
1121 cipher->name, pkcs11_strerror(rv));
1125 * If no keyfile was given, then the token key is secret key to
1126 * be used for encryption/decryption. Otherwise, the keyfile
1127 * contains a wrapped secret key, and the token is actually the
1128 * unwrapping RSA private key.
1130 if (keyfile == NULL) {
1131 kclass = CKO_SECRET_KEY;
1132 ktype = raw_ktype;
1133 } else {
1134 kclass = CKO_PRIVATE_KEY;
1135 ktype = CKK_RSA;
1138 /* Find the key in the token first */
1139 for (i = 0; i < attrs; i++) {
1140 switch (key_tmpl[i].type) {
1141 case CKA_CLASS:
1142 key_tmpl[i].pValue = &kclass;
1143 key_tmpl[i].ulValueLen = sizeof (kclass);
1144 break;
1145 case CKA_KEY_TYPE:
1146 key_tmpl[i].pValue = &ktype;
1147 key_tmpl[i].ulValueLen = sizeof (ktype);
1148 break;
1149 case CKA_LABEL:
1150 key_tmpl[i].pValue = token->key;
1151 key_tmpl[i].ulValueLen = strlen(token->key);
1152 break;
1153 case CKA_TOKEN:
1154 key_tmpl[i].pValue = &trueval;
1155 key_tmpl[i].ulValueLen = sizeof (trueval);
1156 break;
1157 case CKA_PRIVATE:
1158 key_tmpl[i].pValue = &trueval;
1159 key_tmpl[i].ulValueLen = sizeof (trueval);
1160 break;
1161 default:
1162 break;
1165 rv = C_FindObjectsInit(sess, key_tmpl, attrs);
1166 if (rv != CKR_OK)
1167 die(gettext("cannot find key %s: %s\n"), token->key,
1168 pkcs11_strerror(rv));
1169 rv = C_FindObjects(sess, &obj, 1, &num_objs);
1170 (void) C_FindObjectsFinal(sess);
1172 if (num_objs == 0) {
1173 die(gettext("cannot find key %s\n"), token->key);
1174 } else if (rv != CKR_OK) {
1175 die(gettext("cannot find key %s: %s\n"), token->key,
1176 pkcs11_strerror(rv));
1180 * No keyfile means when token key is found, convert it to raw key,
1181 * and done. Otherwise still need do an unwrap to create yet another
1182 * obj and that needs to be converted to raw key before we're done.
1184 if (keyfile == NULL) {
1185 /* obj contains raw key, extract it */
1186 rv = pkcs11_ObjectToKey(sess, obj, (void **)&rkey, &rksz,
1187 B_FALSE);
1188 if (rv != CKR_OK) {
1189 die(gettext("failed to get key value for %s"
1190 " from token %s, %s\n"), token->key,
1191 token->name, pkcs11_strerror(rv));
1193 } else {
1194 getkeyfromfile(keyfile, cipher, &rkey, &rksz);
1197 * Got the wrapping RSA obj and the wrapped key from file.
1198 * Unwrap the key from file with RSA obj to get rawkey obj.
1201 /* re-use the first two attributes of key_tmpl */
1202 kclass = CKO_SECRET_KEY;
1203 ktype = raw_ktype;
1205 rv = C_UnwrapKey(sess, &unwrap, obj, (CK_BYTE_PTR)rkey,
1206 rksz, key_tmpl, 2, &rawobj);
1207 if (rv != CKR_OK) {
1208 die(gettext("failed to unwrap key in keyfile %s,"
1209 " %s\n"), keyfile, pkcs11_strerror(rv));
1211 /* rawobj contains raw key, extract it */
1212 rv = pkcs11_ObjectToKey(sess, rawobj, (void **)&rkey, &rksz,
1213 B_TRUE);
1214 if (rv != CKR_OK) {
1215 die(gettext("failed to get unwrapped key value for"
1216 " key in keyfile %s, %s\n"), keyfile,
1217 pkcs11_strerror(rv));
1221 /* validate raw key size */
1222 if (rksz < cipher->min_keysize || cipher->max_keysize < rksz) {
1223 warn(gettext("%s: invalid keysize: %d\n"), keyfile, (int)rksz);
1224 die(gettext("\t%d <= keysize <= %d\n"), cipher->min_keysize,
1225 cipher->max_keysize);
1228 *raw_key_sz = rksz;
1229 *raw_key = (char *)rkey;
1233 * Set up cipher key limits and verify PKCS#11 can be done
1234 * match_token_cipher is the function pointer used by
1235 * pkcs11_GetCriteriaSession() init_crypto.
1237 boolean_t
1238 match_token_cipher(CK_SLOT_ID slot_id, void *args, CK_RV *rv)
1240 token_spec_t *token;
1241 mech_alias_t *cipher;
1242 CK_TOKEN_INFO tokinfo;
1243 CK_MECHANISM_INFO mechinfo;
1244 boolean_t token_match;
1247 * While traversing slot list, pick up the following info per slot:
1248 * - if token specified, whether it matches this slot's token info
1249 * - if the slot supports the PKCS#5 PBKD2 cipher
1251 * If the user said on the command line
1252 * -T tok:mfr:ser:lab -k keyfile
1253 * -c cipher -T tok:mfr:ser:lab -k keyfile
1254 * the given cipher or the default cipher apply to keyfile,
1255 * If the user said instead
1256 * -T tok:mfr:ser:lab
1257 * -c cipher -T tok:mfr:ser:lab
1258 * the key named "lab" may or may not agree with the given
1259 * cipher or the default cipher. In those cases, cipher will
1260 * be overridden with the actual cipher type of the key "lab".
1262 *rv = CKR_FUNCTION_FAILED;
1264 if (args == NULL) {
1265 return (B_FALSE);
1268 cipher = (mech_alias_t *)args;
1269 token = cipher->token;
1271 if (C_GetMechanismInfo(slot_id, cipher->type, &mechinfo) != CKR_OK) {
1272 return (B_FALSE);
1275 if (token == NULL) {
1276 if (C_GetMechanismInfo(slot_id, CKM_PKCS5_PBKD2, &mechinfo) !=
1277 CKR_OK) {
1278 return (B_FALSE);
1280 goto foundit;
1283 /* does the token match the token spec? */
1284 if (token->key == NULL || (C_GetTokenInfo(slot_id, &tokinfo) != CKR_OK))
1285 return (B_FALSE);
1287 token_match = B_TRUE;
1289 if (token->name != NULL && (token->name)[0] != '\0' &&
1290 strncmp((char *)token->name, (char *)tokinfo.label,
1291 TOKEN_LABEL_SIZE) != 0)
1292 token_match = B_FALSE;
1293 if (token->mfr != NULL && (token->mfr)[0] != '\0' &&
1294 strncmp((char *)token->mfr, (char *)tokinfo.manufacturerID,
1295 TOKEN_MANUFACTURER_SIZE) != 0)
1296 token_match = B_FALSE;
1297 if (token->serno != NULL && (token->serno)[0] != '\0' &&
1298 strncmp((char *)token->serno, (char *)tokinfo.serialNumber,
1299 TOKEN_SERIAL_SIZE) != 0)
1300 token_match = B_FALSE;
1302 if (!token_match)
1303 return (B_FALSE);
1305 foundit:
1306 cipher->slot = slot_id;
1307 return (B_TRUE);
1311 * Clean up crypto loose ends
1313 static void
1314 end_crypto(CK_SESSION_HANDLE sess)
1316 (void) C_CloseSession(sess);
1317 (void) C_Finalize(NULL);
1321 * Set up crypto, opening session on slot that matches token and cipher
1323 static void
1324 init_crypto(token_spec_t *token, mech_alias_t *cipher,
1325 CK_SESSION_HANDLE_PTR sess)
1327 CK_RV rv;
1329 cipher->token = token;
1331 /* Turn off Metaslot so that we can see actual tokens */
1332 if (setenv("METASLOT_ENABLED", "false", 1) < 0) {
1333 die(gettext("could not disable Metaslot"));
1336 rv = pkcs11_GetCriteriaSession(match_token_cipher, (void *)cipher,
1337 sess);
1338 if (rv != CKR_OK) {
1339 end_crypto(*sess);
1340 if (rv == CKR_HOST_MEMORY) {
1341 die("malloc");
1343 die(gettext("failed to find any cryptographic provider, "
1344 "use \"cryptoadm list -p\" to find providers: %s\n"),
1345 pkcs11_strerror(rv));
1350 * Uncompress a file.
1352 * First map the file in to establish a device
1353 * association, then read from it. On-the-fly
1354 * decompression will automatically uncompress
1355 * the file if it's compressed
1357 * If the file is mapped and a device association
1358 * has been established, disallow uncompressing
1359 * the file until it is unmapped.
1361 static void
1362 lofi_uncompress(int lfd, const char *filename)
1364 struct lofi_ioctl li;
1365 char buf[MAXBSIZE];
1366 char devicename[32];
1367 char tmpfilename[MAXPATHLEN];
1368 char *x;
1369 char *dir = NULL;
1370 char *file = NULL;
1371 int minor = 0;
1372 struct stat statbuf;
1373 int compfd = -1;
1374 int uncompfd = -1;
1375 ssize_t rbytes;
1378 * Disallow uncompressing the file if it is
1379 * already mapped.
1381 li.li_crypto_enabled = B_FALSE;
1382 li.li_id = 0;
1383 (void) strlcpy(li.li_filename, filename, sizeof (li.li_filename));
1384 if (ioctl(lfd, LOFI_GET_MINOR, &li) != -1)
1385 die(gettext("%s must be unmapped before uncompressing"),
1386 filename);
1388 /* Zero length files don't need to be uncompressed */
1389 if (stat(filename, &statbuf) == -1)
1390 die(gettext("stat: %s"), filename);
1391 if (statbuf.st_size == 0)
1392 return;
1394 minor = lofi_map_file(lfd, &li, filename);
1395 (void) snprintf(devicename, sizeof (devicename), "/dev/%s/%d",
1396 LOFI_BLOCK_NAME, minor);
1398 /* If the file isn't compressed, we just return */
1399 if ((ioctl(lfd, LOFI_CHECK_COMPRESSED, &li) == -1) ||
1400 (li.li_algorithm[0] == '\0')) {
1401 delete_mapping(lfd, devicename, filename, B_TRUE);
1402 die("%s is not compressed\n", filename);
1405 if ((compfd = open(devicename, O_RDONLY | O_NONBLOCK)) == -1) {
1406 delete_mapping(lfd, devicename, filename, B_TRUE);
1407 die(gettext("open: %s"), filename);
1409 /* Create a temp file in the same directory */
1410 x = strdup(filename);
1411 dir = strdup(dirname(x));
1412 free(x);
1413 x = strdup(filename);
1414 file = strdup(basename(x));
1415 free(x);
1416 (void) snprintf(tmpfilename, sizeof (tmpfilename),
1417 "%s/.%sXXXXXX", dir, file);
1418 free(dir);
1419 free(file);
1421 if ((uncompfd = mkstemp(tmpfilename)) == -1) {
1422 (void) close(compfd);
1423 delete_mapping(lfd, devicename, filename, B_TRUE);
1424 die("%s could not be uncompressed\n", filename);
1428 * Set the mode bits and the owner of this temporary
1429 * file to be that of the original uncompressed file
1431 (void) fchmod(uncompfd, statbuf.st_mode);
1433 if (fchown(uncompfd, statbuf.st_uid, statbuf.st_gid) == -1) {
1434 (void) close(compfd);
1435 (void) close(uncompfd);
1436 delete_mapping(lfd, devicename, filename, B_TRUE);
1437 die("%s could not be uncompressed\n", filename);
1440 /* Now read from the device in MAXBSIZE-sized chunks */
1441 for (;;) {
1442 rbytes = read(compfd, buf, sizeof (buf));
1444 if (rbytes <= 0)
1445 break;
1447 if (write(uncompfd, buf, rbytes) != rbytes) {
1448 rbytes = -1;
1449 break;
1453 (void) close(compfd);
1454 (void) close(uncompfd);
1456 /* Delete the mapping */
1457 delete_mapping(lfd, devicename, filename, B_TRUE);
1460 * If an error occured while reading or writing, rbytes will
1461 * be negative
1463 if (rbytes < 0) {
1464 (void) unlink(tmpfilename);
1465 die(gettext("could not read from %s"), filename);
1468 /* Rename the temp file to the actual file */
1469 if (rename(tmpfilename, filename) == -1)
1470 (void) unlink(tmpfilename);
1474 * Compress a file
1476 static void
1477 lofi_compress(int *lfd, const char *filename, int compress_index,
1478 uint32_t segsize)
1480 struct lofi_ioctl lic;
1481 lofi_compress_info_t *li;
1482 struct flock lock;
1483 char tmpfilename[MAXPATHLEN];
1484 char comp_filename[MAXPATHLEN];
1485 char algorithm[MAXALGLEN];
1486 char *x;
1487 char *dir = NULL, *file = NULL;
1488 uchar_t *uncompressed_seg = NULL;
1489 uchar_t *compressed_seg = NULL;
1490 uint32_t compressed_segsize;
1491 uint32_t len_compressed, count;
1492 uint32_t index_entries, index_sz;
1493 uint64_t *index = NULL;
1494 uint64_t offset;
1495 size_t real_segsize;
1496 struct stat statbuf;
1497 int compfd = -1, uncompfd = -1;
1498 int tfd = -1;
1499 ssize_t rbytes, wbytes, lastread;
1500 int i, type;
1503 * Disallow compressing the file if it is
1504 * already mapped
1506 lic.li_id = 0;
1507 (void) strlcpy(lic.li_filename, filename, sizeof (lic.li_filename));
1508 if (ioctl(*lfd, LOFI_GET_MINOR, &lic) != -1)
1509 die(gettext("%s must be unmapped before compressing"),
1510 filename);
1513 * Close the control device so other operations
1514 * can use it
1516 (void) close(*lfd);
1517 *lfd = -1;
1519 li = &lofi_compress_table[compress_index];
1522 * The size of the buffer to hold compressed data must
1523 * be slightly larger than the compressed segment size.
1525 * The compress functions use part of the buffer as
1526 * scratch space to do calculations.
1527 * Ref: http://www.zlib.net/manual.html#compress2
1529 compressed_segsize = segsize + (segsize >> 6);
1530 compressed_seg = (uchar_t *)malloc(compressed_segsize + SEGHDR);
1531 uncompressed_seg = (uchar_t *)malloc(segsize);
1533 if (compressed_seg == NULL || uncompressed_seg == NULL)
1534 die(gettext("No memory"));
1536 if ((uncompfd = open(filename, O_RDWR, 0)) == -1)
1537 die(gettext("open: %s"), filename);
1539 lock.l_type = F_WRLCK;
1540 lock.l_whence = SEEK_SET;
1541 lock.l_start = 0;
1542 lock.l_len = 0;
1545 * Use an advisory lock to ensure that only a
1546 * single lofiadm process compresses a given
1547 * file at any given time
1549 * A close on the file descriptor automatically
1550 * closes all lock state on the file
1552 if (fcntl(uncompfd, F_SETLKW, &lock) == -1)
1553 die(gettext("fcntl: %s"), filename);
1555 if (fstat(uncompfd, &statbuf) == -1) {
1556 (void) close(uncompfd);
1557 die(gettext("fstat: %s"), filename);
1560 /* Zero length files don't need to be compressed */
1561 if (statbuf.st_size == 0) {
1562 (void) close(uncompfd);
1563 return;
1567 * Create temporary files in the same directory that
1568 * will hold the intermediate data
1570 x = strdup(filename);
1571 dir = strdup(dirname(x));
1572 free(x);
1573 x = strdup(filename);
1574 file = strdup(basename(x));
1575 free(x);
1576 (void) snprintf(tmpfilename, sizeof (tmpfilename),
1577 "%s/.%sXXXXXX", dir, file);
1578 (void) snprintf(comp_filename, sizeof (comp_filename),
1579 "%s/.%sXXXXXX", dir, file);
1580 free(dir);
1581 free(file);
1583 if ((tfd = mkstemp(tmpfilename)) == -1)
1584 goto cleanup;
1586 if ((compfd = mkstemp(comp_filename)) == -1)
1587 goto cleanup;
1590 * Set the mode bits and owner of the compressed
1591 * file to be that of the original uncompressed file
1593 (void) fchmod(compfd, statbuf.st_mode);
1595 if (fchown(compfd, statbuf.st_uid, statbuf.st_gid) == -1)
1596 goto cleanup;
1599 * Calculate the number of index entries required.
1600 * index entries are stored as an array. adding
1601 * a '2' here accounts for the fact that the last
1602 * segment may not be a multiple of the segment size
1604 index_sz = (statbuf.st_size / segsize) + 2;
1605 index = malloc(sizeof (*index) * index_sz);
1607 if (index == NULL)
1608 goto cleanup;
1610 offset = 0;
1611 lastread = segsize;
1612 count = 0;
1615 * Now read from the uncompressed file in 'segsize'
1616 * sized chunks, compress what was read in and
1617 * write it out to a temporary file
1619 for (;;) {
1620 rbytes = read(uncompfd, uncompressed_seg, segsize);
1622 if (rbytes <= 0)
1623 break;
1625 if (lastread < segsize)
1626 goto cleanup;
1629 * Account for the first byte that
1630 * indicates whether a segment is
1631 * compressed or not
1633 real_segsize = segsize - 1;
1634 (void) li->l_compress(uncompressed_seg, rbytes,
1635 compressed_seg + SEGHDR, &real_segsize, li->l_level);
1638 * If the length of the compressed data is more
1639 * than a threshold then there isn't any benefit
1640 * to be had from compressing this segment - leave
1641 * it uncompressed.
1643 * NB. In case an error occurs during compression (above)
1644 * the 'real_segsize' isn't changed. The logic below
1645 * ensures that that segment is left uncompressed.
1647 len_compressed = real_segsize;
1648 if (segsize <= COMPRESS_THRESHOLD ||
1649 real_segsize > (segsize - COMPRESS_THRESHOLD)) {
1650 (void) memcpy(compressed_seg + SEGHDR, uncompressed_seg,
1651 rbytes);
1652 type = UNCOMPRESSED;
1653 len_compressed = rbytes;
1654 } else {
1655 type = COMPRESSED;
1659 * Set the first byte or the SEGHDR to
1660 * indicate if it's compressed or not
1662 *compressed_seg = type;
1663 wbytes = write(tfd, compressed_seg, len_compressed + SEGHDR);
1664 if (wbytes != (len_compressed + SEGHDR)) {
1665 rbytes = -1;
1666 break;
1669 index[count] = BE_64(offset);
1670 offset += wbytes;
1671 lastread = rbytes;
1672 count++;
1675 (void) close(uncompfd);
1677 if (rbytes < 0)
1678 goto cleanup;
1680 * The last index entry is a sentinel entry. It does not point to
1681 * an actual compressed segment but helps in computing the size of
1682 * the compressed segment. The size of each compressed segment is
1683 * computed by subtracting the current index value from the next
1684 * one (the compressed blocks are stored sequentially)
1686 index[count++] = BE_64(offset);
1689 * Now write the compressed data along with the
1690 * header information to this file which will
1691 * later be renamed to the original uncompressed
1692 * file name
1694 * The header is as follows -
1696 * Signature (name of the compression algorithm)
1697 * Compression segment size (a multiple of 512)
1698 * Number of index entries
1699 * Size of the last block
1700 * The array containing the index entries
1702 * the header is always stored in network byte
1703 * order
1705 (void) bzero(algorithm, sizeof (algorithm));
1706 (void) strlcpy(algorithm, li->l_name, sizeof (algorithm));
1707 if (write(compfd, algorithm, sizeof (algorithm))
1708 != sizeof (algorithm))
1709 goto cleanup;
1711 segsize = htonl(segsize);
1712 if (write(compfd, &segsize, sizeof (segsize)) != sizeof (segsize))
1713 goto cleanup;
1715 index_entries = htonl(count);
1716 if (write(compfd, &index_entries, sizeof (index_entries)) !=
1717 sizeof (index_entries))
1718 goto cleanup;
1720 lastread = htonl(lastread);
1721 if (write(compfd, &lastread, sizeof (lastread)) != sizeof (lastread))
1722 goto cleanup;
1724 for (i = 0; i < count; i++) {
1725 if (write(compfd, index + i, sizeof (*index)) !=
1726 sizeof (*index))
1727 goto cleanup;
1730 /* Header is written, now write the compressed data */
1731 if (lseek(tfd, 0, SEEK_SET) != 0)
1732 goto cleanup;
1734 rbytes = wbytes = 0;
1736 for (;;) {
1737 rbytes = read(tfd, compressed_seg, compressed_segsize + SEGHDR);
1739 if (rbytes <= 0)
1740 break;
1742 if (write(compfd, compressed_seg, rbytes) != rbytes)
1743 goto cleanup;
1746 if (fstat(compfd, &statbuf) == -1)
1747 goto cleanup;
1750 * Round up the compressed file size to be a multiple of
1751 * DEV_BSIZE. lofi(7D) likes it that way.
1753 if ((offset = statbuf.st_size % DEV_BSIZE) > 0) {
1755 offset = DEV_BSIZE - offset;
1757 for (i = 0; i < offset; i++)
1758 uncompressed_seg[i] = '\0';
1759 if (write(compfd, uncompressed_seg, offset) != offset)
1760 goto cleanup;
1762 (void) close(compfd);
1763 (void) close(tfd);
1764 (void) unlink(tmpfilename);
1765 cleanup:
1766 if (rbytes < 0) {
1767 if (tfd != -1)
1768 (void) unlink(tmpfilename);
1769 if (compfd != -1)
1770 (void) unlink(comp_filename);
1771 die(gettext("error compressing file %s"), filename);
1772 } else {
1773 /* Rename the compressed file to the actual file */
1774 if (rename(comp_filename, filename) == -1) {
1775 (void) unlink(comp_filename);
1776 die(gettext("error compressing file %s"), filename);
1779 free(compressed_seg);
1780 free(uncompressed_seg);
1781 free(index);
1782 if (compfd != -1)
1783 (void) close(compfd);
1784 if (uncompfd != -1)
1785 (void) close(uncompfd);
1786 if (tfd != -1)
1787 (void) close(tfd);
1790 static int
1791 lofi_compress_select(const char *algname)
1793 int i;
1795 for (i = 0; i < LOFI_COMPRESS_FUNCTIONS; i++) {
1796 if (strcmp(lofi_compress_table[i].l_name, algname) == 0)
1797 return (i);
1799 return (-1);
1802 static void
1803 check_algorithm_validity(const char *algname, int *compress_index)
1805 *compress_index = lofi_compress_select(algname);
1806 if (*compress_index < 0)
1807 die(gettext("invalid algorithm name: %s\n"), algname);
1810 static void
1811 check_file_validity(const char *filename)
1813 struct stat buf;
1814 int error;
1815 int fd;
1817 fd = open(filename, O_RDONLY);
1818 if (fd == -1) {
1819 die(gettext("open: %s"), filename);
1821 error = fstat(fd, &buf);
1822 if (error == -1) {
1823 die(gettext("fstat: %s"), filename);
1824 } else if (!S_ISLOFIABLE(buf.st_mode)) {
1825 die(gettext("%s is not a regular file, "
1826 "block, or character device\n"),
1827 filename);
1828 } else if ((buf.st_size % DEV_BSIZE) != 0) {
1829 die(gettext("size of %s is not a multiple of %d\n"),
1830 filename, DEV_BSIZE);
1832 (void) close(fd);
1834 if (name_to_minor(filename) != 0) {
1835 die(gettext("cannot use %s on itself\n"), LOFI_DRIVER_NAME);
1839 static boolean_t
1840 check_file_is_encrypted(const char *filename)
1842 int fd;
1843 char buf[sizeof (lofi_crypto_magic)];
1844 int got;
1845 int rest = sizeof (lofi_crypto_magic);
1847 fd = open(filename, O_RDONLY);
1848 if (fd == -1)
1849 die(gettext("failed to open: %s"), filename);
1851 if (lseek(fd, CRYOFF, SEEK_SET) != CRYOFF)
1852 die(gettext("failed to seek to offset 0x%lx in file %s"),
1853 CRYOFF, filename);
1855 do {
1856 got = read(fd, buf + sizeof (lofi_crypto_magic) - rest, rest);
1857 if ((got == 0) || ((got == -1) && (errno != EINTR)))
1858 die(gettext("failed to read crypto header"
1859 " at offset 0x%lx in file %s"), CRYOFF, filename);
1861 if (got > 0)
1862 rest -= got;
1863 } while (rest > 0);
1865 while (close(fd) == -1) {
1866 if (errno != EINTR)
1867 die(gettext("failed to close file %s"), filename);
1870 return (strncmp(buf, lofi_crypto_magic,
1871 sizeof (lofi_crypto_magic)) == 0);
1874 static uint32_t
1875 convert_to_num(const char *str)
1877 int len;
1878 uint32_t segsize, mult = 1;
1880 len = strlen(str);
1881 if (len && isalpha(str[len - 1])) {
1882 switch (str[len - 1]) {
1883 case 'k':
1884 case 'K':
1885 mult = KILOBYTE;
1886 break;
1887 case 'b':
1888 case 'B':
1889 mult = BLOCK_SIZE;
1890 break;
1891 case 'm':
1892 case 'M':
1893 mult = MEGABYTE;
1894 break;
1895 case 'g':
1896 case 'G':
1897 mult = GIGABYTE;
1898 break;
1899 default:
1900 die(gettext("invalid segment size %s\n"), str);
1904 segsize = atol(str);
1905 segsize *= mult;
1907 return (segsize);
1911 main(int argc, char *argv[])
1913 int lfd;
1914 int c;
1915 const char *devicename = NULL;
1916 const char *filename = NULL;
1917 const char *algname = COMPRESS_ALGORITHM;
1918 int openflag;
1919 int minor;
1920 int compress_index;
1921 uint32_t segsize = SEGSIZE;
1922 static char *lofictl = "/dev/" LOFI_CTL_NAME;
1923 boolean_t force = B_FALSE;
1924 const char *pname;
1925 boolean_t errflag = B_FALSE;
1926 boolean_t addflag = B_FALSE;
1927 boolean_t labelflag = B_FALSE;
1928 boolean_t rdflag = B_FALSE;
1929 boolean_t deleteflag = B_FALSE;
1930 boolean_t ephflag = B_FALSE;
1931 boolean_t compressflag = B_FALSE;
1932 boolean_t uncompressflag = B_FALSE;
1933 /* the next two work together for -c, -k, -T, -e options only */
1934 boolean_t need_crypto = B_FALSE; /* if any -c, -k, -T, -e */
1935 boolean_t cipher_only = B_TRUE; /* if -c only */
1936 const char *keyfile = NULL;
1937 mech_alias_t *cipher = NULL;
1938 token_spec_t *token = NULL;
1939 char *rkey = NULL;
1940 size_t rksz = 0;
1941 char realfilename[MAXPATHLEN];
1943 pname = getpname(argv[0]);
1945 (void) setlocale(LC_ALL, "");
1946 (void) textdomain(TEXT_DOMAIN);
1948 while ((c = getopt(argc, argv, "a:c:Cd:efk:lrs:T:U")) != EOF) {
1949 switch (c) {
1950 case 'a':
1951 addflag = B_TRUE;
1952 if ((filename = realpath(optarg, realfilename)) == NULL)
1953 die("%s", optarg);
1954 if (((argc - optind) > 0) && (*argv[optind] != '-')) {
1955 /* optional device */
1956 devicename = argv[optind];
1957 optind++;
1959 break;
1960 case 'C':
1961 compressflag = B_TRUE;
1962 if (((argc - optind) > 1) && (*argv[optind] != '-')) {
1963 /* optional algorithm */
1964 algname = argv[optind];
1965 optind++;
1967 check_algorithm_validity(algname, &compress_index);
1968 break;
1969 case 'c':
1970 /* is the chosen cipher allowed? */
1971 if ((cipher = ciph2mech(optarg)) == NULL) {
1972 errflag = B_TRUE;
1973 warn(gettext("cipher %s not allowed\n"),
1974 optarg);
1976 need_crypto = B_TRUE;
1977 /* cipher_only is already set */
1978 break;
1979 case 'd':
1980 deleteflag = B_TRUE;
1981 minor = name_to_minor(optarg);
1982 if (minor != 0)
1983 devicename = optarg;
1984 else {
1985 if ((filename = realpath(optarg,
1986 realfilename)) == NULL)
1987 die("%s", optarg);
1989 break;
1990 case 'e':
1991 ephflag = B_TRUE;
1992 need_crypto = B_TRUE;
1993 cipher_only = B_FALSE; /* need to unset cipher_only */
1994 break;
1995 case 'f':
1996 force = B_TRUE;
1997 break;
1998 case 'k':
1999 keyfile = optarg;
2000 need_crypto = B_TRUE;
2001 cipher_only = B_FALSE; /* need to unset cipher_only */
2002 break;
2003 case 'l':
2004 labelflag = B_TRUE;
2005 break;
2006 case 'r':
2007 rdflag = B_TRUE;
2008 break;
2009 case 's':
2010 segsize = convert_to_num(optarg);
2011 if (segsize < DEV_BSIZE || !ISP2(segsize))
2012 die(gettext("segment size %s is invalid "
2013 "or not a multiple of minimum block "
2014 "size %ld\n"), optarg, DEV_BSIZE);
2015 break;
2016 case 'T':
2017 if ((token = parsetoken(optarg)) == NULL) {
2018 errflag = B_TRUE;
2019 warn(
2020 gettext("invalid token key specifier %s\n"),
2021 optarg);
2023 need_crypto = B_TRUE;
2024 cipher_only = B_FALSE; /* need to unset cipher_only */
2025 break;
2026 case 'U':
2027 uncompressflag = B_TRUE;
2028 break;
2029 case '?':
2030 default:
2031 errflag = B_TRUE;
2032 break;
2036 /* Check for mutually exclusive combinations of options */
2037 if (errflag ||
2038 (addflag && deleteflag) ||
2039 (labelflag && !addflag) ||
2040 (rdflag && !addflag) ||
2041 (!addflag && need_crypto) ||
2042 (need_crypto && labelflag) ||
2043 ((compressflag || uncompressflag) &&
2044 (labelflag || addflag || deleteflag)))
2045 usage(pname);
2047 /* ephemeral key, and key from either file or token are incompatible */
2048 if (ephflag && (keyfile != NULL || token != NULL)) {
2049 die(gettext("ephemeral key cannot be used with keyfile"
2050 " or token key\n"));
2054 * "-c" but no "-k", "-T", "-e", or "-T -k" means derive key from
2055 * command line passphrase
2058 switch (argc - optind) {
2059 case 0: /* no more args */
2060 if (compressflag || uncompressflag) /* needs filename */
2061 usage(pname);
2062 break;
2063 case 1:
2064 if (addflag || deleteflag)
2065 usage(pname);
2066 /* one arg means compress/uncompress the file ... */
2067 if (compressflag || uncompressflag) {
2068 if ((filename = realpath(argv[optind],
2069 realfilename)) == NULL)
2070 die("%s", argv[optind]);
2071 /* ... or without options means print the association */
2072 } else {
2073 minor = name_to_minor(argv[optind]);
2074 if (minor != 0)
2075 devicename = argv[optind];
2076 else {
2077 if ((filename = realpath(argv[optind],
2078 realfilename)) == NULL)
2079 die("%s", argv[optind]);
2082 break;
2083 default:
2084 usage(pname);
2085 break;
2088 if (addflag || compressflag || uncompressflag)
2089 check_file_validity(filename);
2091 if (filename && !valid_abspath(filename))
2092 exit(E_ERROR);
2095 * Here, we know the arguments are correct, the filename is an
2096 * absolute path, it exists and is a regular file. We don't yet
2097 * know that the device name is ok or not.
2100 openflag = O_EXCL;
2101 if (addflag || deleteflag || compressflag || uncompressflag)
2102 openflag |= O_RDWR;
2103 else
2104 openflag |= O_RDONLY;
2105 lfd = open(lofictl, openflag);
2106 if (lfd == -1) {
2107 if ((errno == EPERM) || (errno == EACCES)) {
2108 die(gettext("you do not have permission to perform "
2109 "that operation.\n"));
2110 } else {
2111 die(gettext("open: %s"), lofictl);
2113 /*NOTREACHED*/
2117 * No passphrase is needed for ephemeral key, or when key is
2118 * in a file and not wrapped by another key from a token.
2119 * However, a passphrase is needed in these cases:
2120 * 1. cipher with no ephemeral key, key file, or token,
2121 * in which case the passphrase is used to build the key
2122 * 2. token with an optional cipher or optional key file,
2123 * in which case the passphrase unlocks the token
2124 * If only the cipher is specified, reconfirm the passphrase
2125 * to ensure the user hasn't mis-entered it. Otherwise, the
2126 * token will enforce the token passphrase.
2128 if (need_crypto) {
2129 CK_SESSION_HANDLE sess;
2131 /* pick a cipher if none specified */
2132 if (cipher == NULL)
2133 cipher = DEFAULT_CIPHER;
2135 if (!kernel_cipher_check(cipher))
2136 die(gettext(
2137 "use \"cryptoadm list -m\" to find available "
2138 "mechanisms\n"));
2140 init_crypto(token, cipher, &sess);
2142 if (cipher_only) {
2143 getkeyfromuser(cipher, &rkey, &rksz,
2144 !check_file_is_encrypted(filename));
2145 } else if (token != NULL) {
2146 getkeyfromtoken(sess, token, keyfile, cipher,
2147 &rkey, &rksz);
2148 } else {
2149 /* this also handles ephemeral keys */
2150 getkeyfromfile(keyfile, cipher, &rkey, &rksz);
2153 end_crypto(sess);
2157 * Now to the real work.
2159 if (addflag)
2160 add_mapping(lfd, devicename, filename, cipher, rkey, rksz,
2161 rdflag, labelflag);
2162 else if (compressflag)
2163 lofi_compress(&lfd, filename, compress_index, segsize);
2164 else if (uncompressflag)
2165 lofi_uncompress(lfd, filename);
2166 else if (deleteflag)
2167 delete_mapping(lfd, devicename, filename, force);
2168 else if (filename || devicename)
2169 print_one_mapping(lfd, devicename, filename);
2170 else
2171 print_mappings(lfd);
2173 if (lfd != -1)
2174 (void) close(lfd);
2175 closelib();
2176 return (E_SUCCESS);