dmake: do not set MAKEFLAGS=k
[unleashed/tickless.git] / usr / src / cmd / lofiadm / main.c
blobdb1dad652c0897f17a428edf99afb9a6961574b6
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 <netinet/in.h>
44 #include <stdio.h>
45 #include <fcntl.h>
46 #include <locale.h>
47 #include <string.h>
48 #include <strings.h>
49 #include <errno.h>
50 #include <stdlib.h>
51 #include <unistd.h>
52 #include <stropts.h>
53 #include <libdevinfo.h>
54 #include <libgen.h>
55 #include <ctype.h>
56 #include <dlfcn.h>
57 #include <limits.h>
58 #include <security/cryptoki.h>
59 #include <cryptoutil.h>
60 #include <sys/crypto/ioctl.h>
61 #include <sys/crypto/ioctladmin.h>
62 #include <sys/cmlb.h>
63 #include <sys/mkdev.h>
64 #include "utils.h"
65 #include <LzmaEnc.h>
67 /* Only need the IV len #defines out of these files, nothing else. */
68 #include <aes/aes_impl.h>
69 #include <des/des_impl.h>
70 #include <blowfish/blowfish_impl.h>
72 static const char USAGE[] =
73 "Usage: %s [-r] [-l] -a file [ device ]\n"
74 " %s [-r] -c crypto_algorithm -a file [device]\n"
75 " %s [-r] -c crypto_algorithm -k raw_key_file -a file [device]\n"
76 " %s [-r] -c crypto_algorithm -T [token]:[manuf]:[serial]:key "
77 "-a file [device]\n"
78 " %s [-r] -c crypto_algorithm -T [token]:[manuf]:[serial]:key "
79 "-k wrapped_key_file -a file [device]\n"
80 " %s [-r] -c crypto_algorithm -e -a file [device]\n"
81 " %s -d file | device\n"
82 " %s -C [gzip|gzip-6|gzip-9|lzma] [-s segment_size] file\n"
83 " %s -U file\n"
84 " %s [ file | device ]\n";
86 typedef struct token_spec {
87 char *name;
88 char *mfr;
89 char *serno;
90 char *key;
91 } token_spec_t;
93 typedef struct mech_alias {
94 char *alias;
95 CK_MECHANISM_TYPE type;
96 char *name; /* for ioctl */
97 char *iv_name; /* for ioctl */
98 size_t iv_len; /* for ioctl */
99 iv_method_t iv_type; /* for ioctl */
100 size_t min_keysize; /* in bytes */
101 size_t max_keysize; /* in bytes */
102 token_spec_t *token;
103 CK_SLOT_ID slot;
104 } mech_alias_t;
106 static mech_alias_t mech_aliases[] = {
107 /* Preferred one should always be listed first. */
108 { "aes-256-cbc", CKM_AES_CBC, "CKM_AES_CBC", "CKM_AES_ECB", AES_IV_LEN,
109 IVM_ENC_BLKNO, ULONG_MAX, 0L, NULL, (CK_SLOT_ID) -1 },
110 { "aes-192-cbc", CKM_AES_CBC, "CKM_AES_CBC", "CKM_AES_ECB", AES_IV_LEN,
111 IVM_ENC_BLKNO, ULONG_MAX, 0L, NULL, (CK_SLOT_ID) -1 },
112 { "aes-128-cbc", CKM_AES_CBC, "CKM_AES_CBC", "CKM_AES_ECB", AES_IV_LEN,
113 IVM_ENC_BLKNO, ULONG_MAX, 0L, NULL, (CK_SLOT_ID) -1 },
114 { "des3-cbc", CKM_DES3_CBC, "CKM_DES3_CBC", "CKM_DES3_ECB", DES_IV_LEN,
115 IVM_ENC_BLKNO, ULONG_MAX, 0L, NULL, (CK_SLOT_ID)-1 },
116 { "blowfish-cbc", CKM_BLOWFISH_CBC, "CKM_BLOWFISH_CBC",
117 "CKM_BLOWFISH_ECB", BLOWFISH_IV_LEN, IVM_ENC_BLKNO, ULONG_MAX,
118 0L, NULL, (CK_SLOT_ID)-1 }
120 * A cipher without an iv requirement would look like this:
121 * { "aes-xex", CKM_AES_XEX, "CKM_AES_XEX", NULL, 0,
122 * IVM_NONE, ULONG_MAX, 0L, NULL, (CK_SLOT_ID)-1 }
126 int mech_aliases_count = (sizeof (mech_aliases) / sizeof (mech_alias_t));
128 /* Preferred cipher, if one isn't specified on command line. */
129 #define DEFAULT_CIPHER (&mech_aliases[0])
131 #define DEFAULT_CIPHER_NUM 64 /* guess # kernel ciphers available */
132 #define DEFAULT_MECHINFO_NUM 16 /* guess # kernel mechs available */
133 #define MIN_PASSLEN 8 /* min acceptable passphrase size */
135 static int gzip_compress(void *src, size_t srclen, void *dst,
136 size_t *destlen, int level);
137 static int lzma_compress(void *src, size_t srclen, void *dst,
138 size_t *destlen, int level);
140 lofi_compress_info_t lofi_compress_table[LOFI_COMPRESS_FUNCTIONS] = {
141 {NULL, gzip_compress, 6, "gzip"}, /* default */
142 {NULL, gzip_compress, 6, "gzip-6"},
143 {NULL, gzip_compress, 9, "gzip-9"},
144 {NULL, lzma_compress, 0, "lzma"}
147 /* For displaying lofi mappings */
148 #define FORMAT "%-20s %-30s %s\n"
150 #define COMPRESS_ALGORITHM "gzip"
151 #define COMPRESS_THRESHOLD 2048
152 #define SEGSIZE 131072
153 #define BLOCK_SIZE 512
154 #define KILOBYTE 1024
155 #define MEGABYTE (KILOBYTE * KILOBYTE)
156 #define GIGABYTE (KILOBYTE * MEGABYTE)
157 #define LIBZ "libz.so.1"
159 const char lofi_crypto_magic[6] = LOFI_CRYPTO_MAGIC;
161 static void
162 usage(const char *pname)
164 (void) fprintf(stderr, gettext(USAGE), pname, pname, pname,
165 pname, pname, pname, pname, pname, pname, pname);
166 exit(E_USAGE);
169 static int
170 gzip_compress(void *src, size_t srclen, void *dst, size_t *dstlen, int level)
172 static int (*compress2p)(void *, ulong_t *, void *, size_t, int) = NULL;
173 void *libz_hdl = NULL;
176 * The first time we are called, attempt to dlopen()
177 * libz.so.1 and get a pointer to the compress2() function
179 if (compress2p == NULL) {
180 if ((libz_hdl = openlib(LIBZ)) == NULL)
181 die(gettext("could not find %s. "
182 "gzip compression unavailable\n"), LIBZ);
184 if ((compress2p =
185 (int (*)(void *, ulong_t *, void *, size_t, int))
186 dlsym(libz_hdl, "compress2")) == NULL) {
187 closelib();
188 die(gettext("could not find the correct %s. "
189 "gzip compression unavailable\n"), LIBZ);
193 if ((*compress2p)(dst, (ulong_t *)dstlen, src, srclen, level) != 0)
194 return (-1);
195 return (0);
198 /*ARGSUSED*/
199 static void
200 *SzAlloc(void *p, size_t size)
202 return (malloc(size));
205 /*ARGSUSED*/
206 static void
207 SzFree(void *p, void *address, size_t size)
209 free(address);
212 static ISzAlloc g_Alloc = {
213 SzAlloc,
214 SzFree
217 #define LZMA_UNCOMPRESSED_SIZE 8
218 #define LZMA_HEADER_SIZE (LZMA_PROPS_SIZE + LZMA_UNCOMPRESSED_SIZE)
220 /*ARGSUSED*/
221 static int
222 lzma_compress(void *src, size_t srclen, void *dst,
223 size_t *dstlen, int level)
225 CLzmaEncProps props;
226 size_t outsize2;
227 size_t outsizeprocessed;
228 size_t outpropssize = LZMA_PROPS_SIZE;
229 uint64_t t = 0;
230 SRes res;
231 Byte *dstp;
232 int i;
234 outsize2 = *dstlen;
236 LzmaEncProps_Init(&props);
239 * The LZMA compressed file format is as follows -
241 * Offset Size(bytes) Description
242 * 0 1 LZMA properties (lc, lp, lp (encoded))
243 * 1 4 Dictionary size (little endian)
244 * 5 8 Uncompressed size (little endian)
245 * 13 Compressed data
248 /* set the dictionary size to be 8MB */
249 props.dictSize = 1 << 23;
251 if (*dstlen < LZMA_HEADER_SIZE)
252 return (SZ_ERROR_OUTPUT_EOF);
254 dstp = (Byte *)dst;
255 t = srclen;
257 * Set the uncompressed size in the LZMA header
258 * The LZMA properties (specified in 'props')
259 * will be set by the call to LzmaEncode()
261 for (i = 0; i < LZMA_UNCOMPRESSED_SIZE; i++, t >>= 8) {
262 dstp[LZMA_PROPS_SIZE + i] = (Byte)t;
265 outsizeprocessed = outsize2 - LZMA_HEADER_SIZE;
266 res = LzmaEncode(dstp + LZMA_HEADER_SIZE, &outsizeprocessed,
267 src, srclen, &props, dstp, &outpropssize, 0, NULL,
268 &g_Alloc, &g_Alloc);
270 if (res != 0)
271 return (-1);
273 *dstlen = outsizeprocessed + LZMA_HEADER_SIZE;
274 return (0);
278 * Translate a lofi device name to a minor number. We might be asked
279 * to do this when there is no association (such as when the user specifies
280 * a particular device), so we can only look at the string.
282 static int
283 name_to_minor(const char *devicename)
285 struct stat st;
288 * If devicename does not exist, then devicename contains
289 * the name of the device to be created.
290 * Note we only allow non-labeled devices here.
292 if (stat(devicename, &st)) {
293 int minor, rv;
295 rv = sscanf(devicename, "/dev/" LOFI_BLOCK_NAME "/%d", &minor);
296 if (rv == 1)
297 return (minor);
298 rv = sscanf(devicename, "/dev/" LOFI_CHAR_NAME "/%d", &minor);
299 if (rv == 1)
300 return (minor);
302 return (0);
305 if (st.st_mode & S_IFCHR || st.st_mode & S_IFBLK) {
306 return (LOFI_MINOR2ID(minor(st.st_rdev)));
309 return (0);
313 * This might be the first time we've used this minor number. If so,
314 * it might also be that the /dev links are in the process of being created
315 * by devfsadmd (or that they'll be created "soon"). We cannot return
316 * until they're there or the invoker of lofiadm might try to use them
317 * and not find them. This can happen if a shell script is running on
318 * an MP.
320 static int sleeptime = 2; /* number of seconds to sleep between stat's */
321 static int maxsleep = 120; /* maximum number of seconds to sleep */
323 static void
324 make_blkdevname(struct lofi_ioctl *li, char *path, size_t len)
326 char *r1, *r2;
327 size_t l1;
329 if (li->li_devpath[0] == '\0') {
330 if (li->li_labeled)
331 (void) strlcpy(path, "unknown", len);
332 else
333 (void) snprintf(path, len,
334 "/dev/" LOFI_BLOCK_NAME "/%d", li->li_id);
335 return;
337 (void) strlcpy(path, li->li_devpath, len);
338 r1 = strchr(path, 'r');
339 l1 = r1 - path;
340 r2 = strchr(li->li_devpath, 'r');
341 (void) strlcpy(r1, r2+1, len - l1);
343 if (li->li_labeled) {
344 (void) strlcat(path, "p0", len);
348 static void
349 wait_until_dev_complete(struct lofi_ioctl *li)
351 struct stat64 buf;
352 int cursleep;
353 char blkpath[MAXPATHLEN];
354 char charpath[MAXPATHLEN];
355 di_devlink_handle_t hdl;
357 make_blkdevname(li, blkpath, sizeof (blkpath));
358 (void) strlcpy(charpath, li->li_devpath, sizeof (charpath));
360 if (li->li_labeled) {
361 (void) strlcat(charpath, "p0", sizeof (charpath));
364 /* Check if links already present */
365 if (stat64(blkpath, &buf) == 0 && stat64(charpath, &buf) == 0)
366 return;
368 /* First use di_devlink_init() */
369 if (hdl = di_devlink_init("lofi", DI_MAKE_LINK)) {
370 (void) di_devlink_fini(&hdl);
371 goto out;
375 * Under normal conditions, di_devlink_init(DI_MAKE_LINK) above will
376 * only fail if the caller is non-root. In that case, wait for
377 * link creation via sysevents.
379 for (cursleep = 0; cursleep < maxsleep; cursleep += sleeptime) {
380 if (stat64(blkpath, &buf) == 0 && stat64(charpath, &buf) == 0)
381 return;
382 (void) sleep(sleeptime);
385 /* one last try */
386 out:
387 if (stat64(blkpath, &buf) == -1) {
388 die(gettext("%s was not created"), blkpath);
390 if (stat64(charpath, &buf) == -1) {
391 die(gettext("%s was not created"), charpath);
396 * Map the file and return the minor number the driver picked for the file
397 * DO NOT use this function if the filename is actually the device name.
399 static int
400 lofi_map_file(int lfd, struct lofi_ioctl *li, const char *filename)
402 int minor;
404 li->li_id = 0;
405 (void) strlcpy(li->li_filename, filename, sizeof (li->li_filename));
406 minor = ioctl(lfd, LOFI_MAP_FILE, li);
407 if (minor == -1) {
408 if (errno == ENOTSUP)
409 warn(gettext("encrypting compressed files is "
410 "unsupported"));
411 die(gettext("could not map file %s"), filename);
413 wait_until_dev_complete(li);
414 return (minor);
418 * Add a device association. If devicename is NULL, let the driver
419 * pick a device.
421 static void
422 add_mapping(int lfd, const char *devicename, const char *filename,
423 mech_alias_t *cipher, const char *rkey, size_t rksz, boolean_t rdonly,
424 boolean_t label)
426 struct lofi_ioctl li;
428 bzero(&li, sizeof (li));
429 li.li_readonly = rdonly;
430 li.li_labeled = label;
432 li.li_crypto_enabled = B_FALSE;
433 if (cipher != NULL) {
434 /* set up encryption for mapped file */
435 li.li_crypto_enabled = B_TRUE;
436 (void) strlcpy(li.li_cipher, cipher->name,
437 sizeof (li.li_cipher));
438 if (rksz > sizeof (li.li_key)) {
439 die(gettext("key too large"));
441 bcopy(rkey, li.li_key, rksz);
442 li.li_key_len = rksz << 3; /* convert to bits */
444 li.li_iv_type = cipher->iv_type;
445 li.li_iv_len = cipher->iv_len; /* 0 when no iv needed */
446 switch (cipher->iv_type) {
447 case IVM_ENC_BLKNO:
448 (void) strlcpy(li.li_iv_cipher, cipher->iv_name,
449 sizeof (li.li_iv_cipher));
450 break;
451 case IVM_NONE:
452 /* FALLTHROUGH */
453 default:
454 break;
458 if (devicename == NULL) {
459 int minor;
460 char path[MAXPATHLEN];
462 /* pick one via the driver */
463 minor = lofi_map_file(lfd, &li, filename);
464 if (minor > 0) {
465 make_blkdevname(&li, path, sizeof (path));
467 /* if mapping succeeds, print the one picked */
468 (void) printf("%s\n", path);
470 return;
473 /* use device we were given */
474 li.li_id = name_to_minor(devicename);
475 if (li.li_id == 0) {
476 die(gettext("malformed device name %s\n"), devicename);
478 (void) strlcpy(li.li_filename, filename, sizeof (li.li_filename));
480 /* if device is already in use li.li_minor won't change */
481 if (ioctl(lfd, LOFI_MAP_FILE_MINOR, &li) == -1) {
482 if (errno == ENOTSUP)
483 warn(gettext("encrypting compressed files is "
484 "unsupported"));
485 die(gettext("could not map file %s to %s"), filename,
486 devicename);
488 wait_until_dev_complete(&li);
492 * Remove an association. Delete by device name if non-NULL, or by
493 * filename otherwise.
495 static void
496 delete_mapping(int lfd, const char *devicename, const char *filename,
497 boolean_t force)
499 struct lofi_ioctl li;
501 li.li_force = force;
502 li.li_cleanup = B_FALSE;
504 if (devicename == NULL) {
505 /* delete by filename */
506 (void) strlcpy(li.li_filename, filename,
507 sizeof (li.li_filename));
508 li.li_id = 0;
509 if (ioctl(lfd, LOFI_UNMAP_FILE, &li) == -1) {
510 die(gettext("could not unmap file %s"), filename);
512 return;
515 /* delete by device */
516 li.li_id = name_to_minor(devicename);
517 if (li.li_id == 0) {
518 die(gettext("malformed device name %s\n"), devicename);
520 if (ioctl(lfd, LOFI_UNMAP_FILE_MINOR, &li) == -1) {
521 die(gettext("could not unmap device %s"), devicename);
526 * Show filename given devicename, or devicename given filename.
528 static void
529 print_one_mapping(int lfd, const char *devicename, const char *filename)
531 struct lofi_ioctl li;
532 char blkpath[MAXPATHLEN];
534 if (devicename == NULL) {
535 /* given filename, print devicename */
536 li.li_id = 0;
537 (void) strlcpy(li.li_filename, filename,
538 sizeof (li.li_filename));
539 if (ioctl(lfd, LOFI_GET_MINOR, &li) == -1) {
540 die(gettext("could not find device for %s"), filename);
542 make_blkdevname(&li, blkpath, sizeof (blkpath));
543 (void) printf("%s\n", blkpath);
544 return;
547 /* given devicename, print filename */
548 li.li_id = name_to_minor(devicename);
549 if (li.li_id == 0) {
550 die(gettext("malformed device name %s\n"), devicename);
552 if (ioctl(lfd, LOFI_GET_FILENAME, &li) == -1) {
553 die(gettext("could not find filename for %s"), devicename);
555 (void) printf("%s\n", li.li_filename);
559 * Print the list of all the mappings, including a header.
561 static void
562 print_mappings(int fd)
564 struct lofi_ioctl li;
565 int minor;
566 int maxminor;
567 char path[MAXPATHLEN];
568 char options[MAXPATHLEN] = { 0 };
570 li.li_id = 0;
571 if (ioctl(fd, LOFI_GET_MAXMINOR, &li) == -1) {
572 die("ioctl");
574 maxminor = li.li_id;
576 (void) printf(FORMAT, gettext("Block Device"), gettext("File"),
577 gettext("Options"));
578 for (minor = 1; minor <= maxminor; minor++) {
579 li.li_id = minor;
580 if (ioctl(fd, LOFI_GET_FILENAME, &li) == -1) {
581 if (errno == ENXIO)
582 continue;
583 warn("ioctl");
584 break;
586 make_blkdevname(&li, path, sizeof (path));
588 options[0] = '\0';
591 * Encrypted lofi and compressed lofi are mutually exclusive.
593 if (li.li_crypto_enabled)
594 (void) snprintf(options, sizeof (options),
595 gettext("Encrypted"));
596 else if (li.li_algorithm[0] != '\0')
597 (void) snprintf(options, sizeof (options),
598 gettext("Compressed(%s)"), li.li_algorithm);
599 if (li.li_readonly) {
600 if (strlen(options) != 0) {
601 (void) strlcat(options, ",Readonly",
602 sizeof (options));
603 } else {
604 (void) snprintf(options, sizeof (options),
605 gettext("Readonly"));
608 if (li.li_labeled) {
609 if (strlen(options) != 0) {
610 (void) strlcat(options, ",Labeled",
611 sizeof (options));
612 } else {
613 (void) snprintf(options, sizeof (options),
614 gettext("Labeled"));
617 if (strlen(options) == 0)
618 (void) snprintf(options, sizeof (options), "-");
620 (void) printf(FORMAT, path, li.li_filename, options);
625 * Verify the cipher selected by user.
627 static mech_alias_t *
628 ciph2mech(const char *alias)
630 int i;
632 for (i = 0; i < mech_aliases_count; i++) {
633 if (strcasecmp(alias, mech_aliases[i].alias) == 0)
634 return (&mech_aliases[i]);
636 return (NULL);
640 * Verify user selected cipher is also available in kernel.
642 * While traversing kernel list of mechs, if the cipher is supported in the
643 * kernel for both encryption and decryption, it also picks up the min/max
644 * key size.
646 static boolean_t
647 kernel_cipher_check(mech_alias_t *cipher)
649 boolean_t ciph_ok = B_FALSE;
650 boolean_t iv_ok = B_FALSE;
651 int i;
652 int count;
653 crypto_get_mechanism_list_t *kciphers = NULL;
654 crypto_get_all_mechanism_info_t *kinfo = NULL;
655 int fd = -1;
656 size_t keymin;
657 size_t keymax;
659 /* if cipher doesn't need iv generating mech, bypass that check now */
660 if (cipher->iv_name == NULL)
661 iv_ok = B_TRUE;
663 /* allocate some space for the list of kernel ciphers */
664 count = DEFAULT_CIPHER_NUM;
665 kciphers = malloc(sizeof (crypto_get_mechanism_list_t) +
666 sizeof (crypto_mech_name_t) * (count - 1));
667 if (kciphers == NULL)
668 die(gettext("failed to allocate memory for list of "
669 "kernel mechanisms"));
670 kciphers->ml_count = count;
672 /* query crypto device to get list of kernel ciphers */
673 if ((fd = open("/dev/crypto", O_RDWR)) == -1) {
674 warn(gettext("failed to open %s"), "/dev/crypto");
675 goto kcc_out;
678 if (ioctl(fd, CRYPTO_GET_MECHANISM_LIST, kciphers) == -1) {
679 warn(gettext("CRYPTO_GET_MECHANISM_LIST ioctl failed"));
680 goto kcc_out;
683 if (kciphers->ml_return_value == CRYPTO_BUFFER_TOO_SMALL) {
684 count = kciphers->ml_count;
685 free(kciphers);
686 kciphers = malloc(sizeof (crypto_get_mechanism_list_t) +
687 sizeof (crypto_mech_name_t) * (count - 1));
688 if (kciphers == NULL) {
689 warn(gettext("failed to allocate memory for list of "
690 "kernel mechanisms"));
691 goto kcc_out;
693 kciphers->ml_count = count;
695 if (ioctl(fd, CRYPTO_GET_MECHANISM_LIST, kciphers) == -1) {
696 warn(gettext("CRYPTO_GET_MECHANISM_LIST ioctl failed"));
697 goto kcc_out;
701 if (kciphers->ml_return_value != CRYPTO_SUCCESS) {
702 warn(gettext(
703 "CRYPTO_GET_MECHANISM_LIST ioctl return value = %d\n"),
704 kciphers->ml_return_value);
705 goto kcc_out;
709 * scan list of kernel ciphers looking for the selected one and if
710 * it needs an iv generated using another cipher, also look for that
711 * additional cipher to be used for generating the iv
713 count = kciphers->ml_count;
714 for (i = 0; i < count && !(ciph_ok && iv_ok); i++) {
715 if (!ciph_ok &&
716 strcasecmp(cipher->name, kciphers->ml_list[i]) == 0)
717 ciph_ok = B_TRUE;
718 if (!iv_ok &&
719 strcasecmp(cipher->iv_name, kciphers->ml_list[i]) == 0)
720 iv_ok = B_TRUE;
722 free(kciphers);
723 kciphers = NULL;
725 if (!ciph_ok)
726 warn(gettext("%s mechanism not supported in kernel\n"),
727 cipher->name);
728 if (!iv_ok)
729 warn(gettext("%s mechanism not supported in kernel\n"),
730 cipher->iv_name);
732 if (ciph_ok) {
733 /* Get the details about the user selected cipher */
734 count = DEFAULT_MECHINFO_NUM;
735 kinfo = malloc(sizeof (crypto_get_all_mechanism_info_t) +
736 sizeof (crypto_mechanism_info_t) * (count - 1));
737 if (kinfo == NULL) {
738 warn(gettext("failed to allocate memory for "
739 "kernel mechanism info"));
740 goto kcc_out;
742 kinfo->mi_count = count;
743 (void) strlcpy(kinfo->mi_mechanism_name, cipher->name,
744 CRYPTO_MAX_MECH_NAME);
746 if (ioctl(fd, CRYPTO_GET_ALL_MECHANISM_INFO, kinfo) == -1) {
747 warn(gettext(
748 "CRYPTO_GET_ALL_MECHANISM_INFO ioctl failed"));
749 goto kcc_out;
752 if (kinfo->mi_return_value == CRYPTO_BUFFER_TOO_SMALL) {
753 count = kinfo->mi_count;
754 free(kinfo);
755 kinfo = malloc(
756 sizeof (crypto_get_all_mechanism_info_t) +
757 sizeof (crypto_mechanism_info_t) * (count - 1));
758 if (kinfo == NULL) {
759 warn(gettext("failed to allocate memory for "
760 "kernel mechanism info"));
761 goto kcc_out;
763 kinfo->mi_count = count;
764 (void) strlcpy(kinfo->mi_mechanism_name, cipher->name,
765 CRYPTO_MAX_MECH_NAME);
767 if (ioctl(fd, CRYPTO_GET_ALL_MECHANISM_INFO, kinfo) ==
768 -1) {
769 warn(gettext("CRYPTO_GET_ALL_MECHANISM_INFO "
770 "ioctl failed"));
771 goto kcc_out;
775 if (kinfo->mi_return_value != CRYPTO_SUCCESS) {
776 warn(gettext("CRYPTO_GET_ALL_MECHANISM_INFO ioctl "
777 "return value = %d\n"), kinfo->mi_return_value);
778 goto kcc_out;
781 /* Set key min and max size */
782 count = kinfo->mi_count;
783 i = 0;
784 if (i < count) {
785 keymin = kinfo->mi_list[i].mi_min_key_size;
786 keymax = kinfo->mi_list[i].mi_max_key_size;
787 if (kinfo->mi_list[i].mi_keysize_unit &
788 CRYPTO_KEYSIZE_UNIT_IN_BITS) {
789 keymin = CRYPTO_BITS2BYTES(keymin);
790 keymax = CRYPTO_BITS2BYTES(keymax);
793 cipher->min_keysize = keymin;
794 cipher->max_keysize = keymax;
796 free(kinfo);
797 kinfo = NULL;
799 if (i == count) {
800 (void) close(fd);
801 die(gettext(
802 "failed to find usable %s kernel mechanism, "
803 "use \"cryptoadm list -m\" to find available "
804 "mechanisms\n"),
805 cipher->name);
809 /* Note: key min/max, unit size, usage for iv cipher are not checked. */
811 return (ciph_ok && iv_ok);
813 kcc_out:
814 free(kinfo);
815 free(kciphers);
816 if (fd != -1)
817 (void) close(fd);
818 return (B_FALSE);
822 * Break up token spec into its components (non-destructive)
824 static token_spec_t *
825 parsetoken(char *spec)
827 #define FLD_NAME 0
828 #define FLD_MANUF 1
829 #define FLD_SERIAL 2
830 #define FLD_LABEL 3
831 #define NFIELDS 4
832 #define nullfield(i) ((field[(i)+1] - field[(i)]) <= 1)
833 #define copyfield(fld, i) \
835 int n; \
836 (fld) = NULL; \
837 if ((n = (field[(i)+1] - field[(i)])) > 1) { \
838 if (((fld) = malloc(n)) != NULL) { \
839 (void) strncpy((fld), field[(i)], n); \
840 ((fld))[n - 1] = '\0'; \
845 int i;
846 char *field[NFIELDS + 1]; /* +1 to catch extra delimiters */
847 token_spec_t *ti = NULL;
849 if (spec == NULL)
850 return (NULL);
853 * Correct format is "[name]:[manuf]:[serial]:key". Can't use
854 * strtok because it treats ":::key" and "key:::" and "key" all
855 * as the same thing, and we can't have the :s compressed away.
857 field[0] = spec;
858 for (i = 1; i < NFIELDS + 1; i++) {
859 field[i] = strchr(field[i-1], ':');
860 if (field[i] == NULL)
861 break;
862 field[i]++;
864 if (i < NFIELDS) /* not enough fields */
865 return (NULL);
866 if (field[NFIELDS] != NULL) /* too many fields */
867 return (NULL);
868 field[NFIELDS] = strchr(field[NFIELDS-1], '\0') + 1;
870 /* key label can't be empty */
871 if (nullfield(FLD_LABEL))
872 return (NULL);
874 ti = malloc(sizeof (token_spec_t));
875 if (ti == NULL)
876 return (NULL);
878 copyfield(ti->name, FLD_NAME);
879 copyfield(ti->mfr, FLD_MANUF);
880 copyfield(ti->serno, FLD_SERIAL);
881 copyfield(ti->key, FLD_LABEL);
884 * If token specified and it only contains a key label, then
885 * search all tokens for the key, otherwise only those with
886 * matching name, mfr, and serno are used.
889 * That's how we'd like it to be, however, if only the key label
890 * is specified, default to using softtoken. It's easier.
892 if (ti->name == NULL && ti->mfr == NULL && ti->serno == NULL)
893 ti->name = strdup(pkcs11_default_token());
894 return (ti);
898 * PBE the passphrase into a raw key
900 static void
901 getkeyfromuser(mech_alias_t *cipher, char **raw_key, size_t *raw_key_sz,
902 boolean_t with_confirmation)
904 CK_SESSION_HANDLE sess;
905 CK_RV rv;
906 char *pass = NULL;
907 size_t passlen = 0;
908 void *salt = NULL; /* don't use NULL, see note on salt below */
909 size_t saltlen = 0;
910 CK_KEY_TYPE ktype;
911 void *kvalue;
912 size_t klen;
914 /* did init_crypto find a slot that supports this cipher? */
915 if (cipher->slot == (CK_SLOT_ID)-1 || cipher->max_keysize == 0) {
916 rv = CKR_MECHANISM_INVALID;
917 goto cleanup;
920 rv = pkcs11_mech2keytype(cipher->type, &ktype);
921 if (rv != CKR_OK)
922 goto cleanup;
925 * use the passphrase to generate a PBE PKCS#5 secret key and
926 * retrieve the raw key data to eventually pass it to the kernel;
928 rv = C_OpenSession(cipher->slot, CKF_SERIAL_SESSION, NULL, NULL, &sess);
929 if (rv != CKR_OK)
930 goto cleanup;
932 /* get user passphrase with 8 byte minimum */
933 if (pkcs11_get_pass(NULL, &pass, &passlen, MIN_PASSLEN,
934 with_confirmation) < 0) {
935 die(gettext("passphrases do not match\n"));
939 * salt should not be NULL, or else pkcs11_PasswdToKey() will
940 * complain about CKR_MECHANISM_PARAM_INVALID; the following is
941 * to make up for not having a salt until a proper one is used
943 salt = pass;
944 saltlen = passlen;
946 klen = cipher->max_keysize;
947 rv = pkcs11_PasswdToKey(sess, pass, passlen, salt, saltlen, ktype,
948 cipher->max_keysize, &kvalue, &klen);
950 (void) C_CloseSession(sess);
952 if (rv != CKR_OK) {
953 goto cleanup;
956 /* assert(klen == cipher->max_keysize); */
957 *raw_key_sz = klen;
958 *raw_key = (char *)kvalue;
959 return;
961 cleanup:
962 die(gettext("failed to generate %s key from passphrase: %s"),
963 cipher->alias, pkcs11_strerror(rv));
967 * Read raw key from file; also handles ephemeral keys.
969 void
970 getkeyfromfile(const char *pathname, mech_alias_t *cipher, char **key,
971 size_t *ksz)
973 int fd;
974 struct stat sbuf;
975 boolean_t notplain = B_FALSE;
976 ssize_t cursz;
977 ssize_t nread;
979 /* ephemeral keys are just random data */
980 if (pathname == NULL) {
981 *ksz = cipher->max_keysize;
982 *key = malloc(*ksz);
983 if (*key == NULL)
984 die(gettext("failed to allocate memory for"
985 " ephemeral key"));
986 if (pkcs11_get_urandom(*key, *ksz) < 0) {
987 free(*key);
988 die(gettext("failed to get enough random data"));
990 return;
994 * If the remaining section of code didn't also check for secure keyfile
995 * permissions and whether the key is within cipher min and max lengths,
996 * (or, if those things moved out of this block), we could have had:
997 * if (pkcs11_read_data(pathname, key, ksz) < 0)
998 * handle_error();
1001 if ((fd = open(pathname, O_RDONLY, 0)) == -1)
1002 die(gettext("open of keyfile (%s) failed"), pathname);
1004 if (fstat(fd, &sbuf) == -1)
1005 die(gettext("fstat of keyfile (%s) failed"), pathname);
1007 if (S_ISREG(sbuf.st_mode)) {
1008 if ((sbuf.st_mode & (S_IWGRP | S_IWOTH)) != 0)
1009 die(gettext("insecure permissions on keyfile %s\n"),
1010 pathname);
1012 *ksz = sbuf.st_size;
1013 if (*ksz < cipher->min_keysize || cipher->max_keysize < *ksz) {
1014 warn(gettext("%s: invalid keysize: %d\n"),
1015 pathname, (int)*ksz);
1016 die(gettext("\t%d <= keysize <= %d\n"),
1017 cipher->min_keysize, cipher->max_keysize);
1019 } else {
1020 *ksz = cipher->max_keysize;
1021 notplain = B_TRUE;
1024 *key = malloc(*ksz);
1025 if (*key == NULL)
1026 die(gettext("failed to allocate memory for key from file"));
1028 for (cursz = 0, nread = 0; cursz < *ksz; cursz += nread) {
1029 nread = read(fd, *key, *ksz);
1030 if (nread > 0)
1031 continue;
1033 * nread == 0. If it's not a regular file we were trying to
1034 * get the maximum keysize of data possible for this cipher.
1035 * But if we've got at least the minimum keysize of data,
1036 * round down to the nearest keysize unit and call it good.
1037 * If we haven't met the minimum keysize, that's an error.
1038 * If it's a regular file, nread = 0 is also an error.
1040 if (nread == 0 && notplain && cursz >= cipher->min_keysize) {
1041 *ksz = (cursz / cipher->min_keysize) *
1042 cipher->min_keysize;
1043 break;
1045 die(gettext("%s: can't read all keybytes"), pathname);
1047 (void) close(fd);
1051 * Read the raw key from token, or from a file that was wrapped with a
1052 * key from token
1054 void
1055 getkeyfromtoken(CK_SESSION_HANDLE sess,
1056 token_spec_t *token, const char *keyfile, mech_alias_t *cipher,
1057 char **raw_key, size_t *raw_key_sz)
1059 CK_RV rv = CKR_OK;
1060 CK_BBOOL trueval = B_TRUE;
1061 CK_OBJECT_CLASS kclass; /* secret key or RSA private key */
1062 CK_KEY_TYPE ktype; /* from selected cipher or CKK_RSA */
1063 CK_KEY_TYPE raw_ktype; /* from selected cipher */
1064 CK_ATTRIBUTE key_tmpl[] = {
1065 { CKA_CLASS, NULL, 0 }, /* re-used for token key and unwrap */
1066 { CKA_KEY_TYPE, NULL, 0 }, /* ditto */
1067 { CKA_LABEL, NULL, 0 },
1068 { CKA_TOKEN, NULL, 0 },
1069 { CKA_PRIVATE, NULL, 0 }
1071 CK_ULONG attrs = sizeof (key_tmpl) / sizeof (CK_ATTRIBUTE);
1072 int i;
1073 char *pass = NULL;
1074 size_t passlen = 0;
1075 CK_OBJECT_HANDLE obj, rawobj;
1076 CK_ULONG num_objs = 1; /* just want to find 1 token key */
1077 CK_MECHANISM unwrap = { CKM_RSA_PKCS, NULL, 0 };
1078 char *rkey;
1079 size_t rksz;
1081 if (token == NULL || token->key == NULL)
1082 return;
1084 /* did init_crypto find a slot that supports this cipher? */
1085 if (cipher->slot == (CK_SLOT_ID)-1 || cipher->max_keysize == 0) {
1086 die(gettext("failed to find any cryptographic provider, "
1087 "use \"cryptoadm list -p\" to find providers: %s\n"),
1088 pkcs11_strerror(CKR_MECHANISM_INVALID));
1091 if (pkcs11_get_pass(token->name, &pass, &passlen, 0, B_FALSE) < 0)
1092 die(gettext("unable to get passphrase"));
1094 /* use passphrase to login to token */
1095 if (pass != NULL && passlen > 0) {
1096 rv = C_Login(sess, CKU_USER, (CK_UTF8CHAR_PTR)pass, passlen);
1097 if (rv != CKR_OK) {
1098 die(gettext("cannot login to the token %s: %s\n"),
1099 token->name, pkcs11_strerror(rv));
1103 rv = pkcs11_mech2keytype(cipher->type, &raw_ktype);
1104 if (rv != CKR_OK) {
1105 die(gettext("failed to get key type for cipher %s: %s\n"),
1106 cipher->name, pkcs11_strerror(rv));
1110 * If no keyfile was given, then the token key is secret key to
1111 * be used for encryption/decryption. Otherwise, the keyfile
1112 * contains a wrapped secret key, and the token is actually the
1113 * unwrapping RSA private key.
1115 if (keyfile == NULL) {
1116 kclass = CKO_SECRET_KEY;
1117 ktype = raw_ktype;
1118 } else {
1119 kclass = CKO_PRIVATE_KEY;
1120 ktype = CKK_RSA;
1123 /* Find the key in the token first */
1124 for (i = 0; i < attrs; i++) {
1125 switch (key_tmpl[i].type) {
1126 case CKA_CLASS:
1127 key_tmpl[i].pValue = &kclass;
1128 key_tmpl[i].ulValueLen = sizeof (kclass);
1129 break;
1130 case CKA_KEY_TYPE:
1131 key_tmpl[i].pValue = &ktype;
1132 key_tmpl[i].ulValueLen = sizeof (ktype);
1133 break;
1134 case CKA_LABEL:
1135 key_tmpl[i].pValue = token->key;
1136 key_tmpl[i].ulValueLen = strlen(token->key);
1137 break;
1138 case CKA_TOKEN:
1139 key_tmpl[i].pValue = &trueval;
1140 key_tmpl[i].ulValueLen = sizeof (trueval);
1141 break;
1142 case CKA_PRIVATE:
1143 key_tmpl[i].pValue = &trueval;
1144 key_tmpl[i].ulValueLen = sizeof (trueval);
1145 break;
1146 default:
1147 break;
1150 rv = C_FindObjectsInit(sess, key_tmpl, attrs);
1151 if (rv != CKR_OK)
1152 die(gettext("cannot find key %s: %s\n"), token->key,
1153 pkcs11_strerror(rv));
1154 rv = C_FindObjects(sess, &obj, 1, &num_objs);
1155 (void) C_FindObjectsFinal(sess);
1157 if (num_objs == 0) {
1158 die(gettext("cannot find key %s\n"), token->key);
1159 } else if (rv != CKR_OK) {
1160 die(gettext("cannot find key %s: %s\n"), token->key,
1161 pkcs11_strerror(rv));
1165 * No keyfile means when token key is found, convert it to raw key,
1166 * and done. Otherwise still need do an unwrap to create yet another
1167 * obj and that needs to be converted to raw key before we're done.
1169 if (keyfile == NULL) {
1170 /* obj contains raw key, extract it */
1171 rv = pkcs11_ObjectToKey(sess, obj, (void **)&rkey, &rksz,
1172 B_FALSE);
1173 if (rv != CKR_OK) {
1174 die(gettext("failed to get key value for %s"
1175 " from token %s, %s\n"), token->key,
1176 token->name, pkcs11_strerror(rv));
1178 } else {
1179 getkeyfromfile(keyfile, cipher, &rkey, &rksz);
1182 * Got the wrapping RSA obj and the wrapped key from file.
1183 * Unwrap the key from file with RSA obj to get rawkey obj.
1186 /* re-use the first two attributes of key_tmpl */
1187 kclass = CKO_SECRET_KEY;
1188 ktype = raw_ktype;
1190 rv = C_UnwrapKey(sess, &unwrap, obj, (CK_BYTE_PTR)rkey,
1191 rksz, key_tmpl, 2, &rawobj);
1192 if (rv != CKR_OK) {
1193 die(gettext("failed to unwrap key in keyfile %s,"
1194 " %s\n"), keyfile, pkcs11_strerror(rv));
1196 /* rawobj contains raw key, extract it */
1197 rv = pkcs11_ObjectToKey(sess, rawobj, (void **)&rkey, &rksz,
1198 B_TRUE);
1199 if (rv != CKR_OK) {
1200 die(gettext("failed to get unwrapped key value for"
1201 " key in keyfile %s, %s\n"), keyfile,
1202 pkcs11_strerror(rv));
1206 /* validate raw key size */
1207 if (rksz < cipher->min_keysize || cipher->max_keysize < rksz) {
1208 warn(gettext("%s: invalid keysize: %d\n"), keyfile, (int)rksz);
1209 die(gettext("\t%d <= keysize <= %d\n"), cipher->min_keysize,
1210 cipher->max_keysize);
1213 *raw_key_sz = rksz;
1214 *raw_key = (char *)rkey;
1218 * Set up cipher key limits and verify PKCS#11 can be done
1219 * match_token_cipher is the function pointer used by
1220 * pkcs11_GetCriteriaSession() init_crypto.
1222 boolean_t
1223 match_token_cipher(CK_SLOT_ID slot_id, void *args, CK_RV *rv)
1225 token_spec_t *token;
1226 mech_alias_t *cipher;
1227 CK_TOKEN_INFO tokinfo;
1228 CK_MECHANISM_INFO mechinfo;
1229 boolean_t token_match;
1232 * While traversing slot list, pick up the following info per slot:
1233 * - if token specified, whether it matches this slot's token info
1234 * - if the slot supports the PKCS#5 PBKD2 cipher
1236 * If the user said on the command line
1237 * -T tok:mfr:ser:lab -k keyfile
1238 * -c cipher -T tok:mfr:ser:lab -k keyfile
1239 * the given cipher or the default cipher apply to keyfile,
1240 * If the user said instead
1241 * -T tok:mfr:ser:lab
1242 * -c cipher -T tok:mfr:ser:lab
1243 * the key named "lab" may or may not agree with the given
1244 * cipher or the default cipher. In those cases, cipher will
1245 * be overridden with the actual cipher type of the key "lab".
1247 *rv = CKR_FUNCTION_FAILED;
1249 if (args == NULL) {
1250 return (B_FALSE);
1253 cipher = (mech_alias_t *)args;
1254 token = cipher->token;
1256 if (C_GetMechanismInfo(slot_id, cipher->type, &mechinfo) != CKR_OK) {
1257 return (B_FALSE);
1260 if (token == NULL) {
1261 if (C_GetMechanismInfo(slot_id, CKM_PKCS5_PBKD2, &mechinfo) !=
1262 CKR_OK) {
1263 return (B_FALSE);
1265 goto foundit;
1268 /* does the token match the token spec? */
1269 if (token->key == NULL || (C_GetTokenInfo(slot_id, &tokinfo) != CKR_OK))
1270 return (B_FALSE);
1272 token_match = B_TRUE;
1274 if (token->name != NULL && (token->name)[0] != '\0' &&
1275 strncmp((char *)token->name, (char *)tokinfo.label,
1276 TOKEN_LABEL_SIZE) != 0)
1277 token_match = B_FALSE;
1278 if (token->mfr != NULL && (token->mfr)[0] != '\0' &&
1279 strncmp((char *)token->mfr, (char *)tokinfo.manufacturerID,
1280 TOKEN_MANUFACTURER_SIZE) != 0)
1281 token_match = B_FALSE;
1282 if (token->serno != NULL && (token->serno)[0] != '\0' &&
1283 strncmp((char *)token->serno, (char *)tokinfo.serialNumber,
1284 TOKEN_SERIAL_SIZE) != 0)
1285 token_match = B_FALSE;
1287 if (!token_match)
1288 return (B_FALSE);
1290 foundit:
1291 cipher->slot = slot_id;
1292 return (B_TRUE);
1296 * Clean up crypto loose ends
1298 static void
1299 end_crypto(CK_SESSION_HANDLE sess)
1301 (void) C_CloseSession(sess);
1302 (void) C_Finalize(NULL);
1306 * Set up crypto, opening session on slot that matches token and cipher
1308 static void
1309 init_crypto(token_spec_t *token, mech_alias_t *cipher,
1310 CK_SESSION_HANDLE_PTR sess)
1312 CK_RV rv;
1314 cipher->token = token;
1316 /* Turn off Metaslot so that we can see actual tokens */
1317 if (setenv("METASLOT_ENABLED", "false", 1) < 0) {
1318 die(gettext("could not disable Metaslot"));
1321 rv = pkcs11_GetCriteriaSession(match_token_cipher, (void *)cipher,
1322 sess);
1323 if (rv != CKR_OK) {
1324 end_crypto(*sess);
1325 if (rv == CKR_HOST_MEMORY) {
1326 die("malloc");
1328 die(gettext("failed to find any cryptographic provider, "
1329 "use \"cryptoadm list -p\" to find providers: %s\n"),
1330 pkcs11_strerror(rv));
1335 * Uncompress a file.
1337 * First map the file in to establish a device
1338 * association, then read from it. On-the-fly
1339 * decompression will automatically uncompress
1340 * the file if it's compressed
1342 * If the file is mapped and a device association
1343 * has been established, disallow uncompressing
1344 * the file until it is unmapped.
1346 static void
1347 lofi_uncompress(int lfd, const char *filename)
1349 struct lofi_ioctl li;
1350 char buf[MAXBSIZE];
1351 char devicename[32];
1352 char tmpfilename[MAXPATHLEN];
1353 char *x;
1354 char *dir = NULL;
1355 char *file = NULL;
1356 int minor = 0;
1357 struct stat64 statbuf;
1358 int compfd = -1;
1359 int uncompfd = -1;
1360 ssize_t rbytes;
1363 * Disallow uncompressing the file if it is
1364 * already mapped.
1366 li.li_crypto_enabled = B_FALSE;
1367 li.li_id = 0;
1368 (void) strlcpy(li.li_filename, filename, sizeof (li.li_filename));
1369 if (ioctl(lfd, LOFI_GET_MINOR, &li) != -1)
1370 die(gettext("%s must be unmapped before uncompressing"),
1371 filename);
1373 /* Zero length files don't need to be uncompressed */
1374 if (stat64(filename, &statbuf) == -1)
1375 die(gettext("stat: %s"), filename);
1376 if (statbuf.st_size == 0)
1377 return;
1379 minor = lofi_map_file(lfd, &li, filename);
1380 (void) snprintf(devicename, sizeof (devicename), "/dev/%s/%d",
1381 LOFI_BLOCK_NAME, minor);
1383 /* If the file isn't compressed, we just return */
1384 if ((ioctl(lfd, LOFI_CHECK_COMPRESSED, &li) == -1) ||
1385 (li.li_algorithm[0] == '\0')) {
1386 delete_mapping(lfd, devicename, filename, B_TRUE);
1387 die("%s is not compressed\n", filename);
1390 if ((compfd = open64(devicename, O_RDONLY | O_NONBLOCK)) == -1) {
1391 delete_mapping(lfd, devicename, filename, B_TRUE);
1392 die(gettext("open: %s"), filename);
1394 /* Create a temp file in the same directory */
1395 x = strdup(filename);
1396 dir = strdup(dirname(x));
1397 free(x);
1398 x = strdup(filename);
1399 file = strdup(basename(x));
1400 free(x);
1401 (void) snprintf(tmpfilename, sizeof (tmpfilename),
1402 "%s/.%sXXXXXX", dir, file);
1403 free(dir);
1404 free(file);
1406 if ((uncompfd = mkstemp64(tmpfilename)) == -1) {
1407 (void) close(compfd);
1408 delete_mapping(lfd, devicename, filename, B_TRUE);
1409 die("%s could not be uncompressed\n", filename);
1413 * Set the mode bits and the owner of this temporary
1414 * file to be that of the original uncompressed file
1416 (void) fchmod(uncompfd, statbuf.st_mode);
1418 if (fchown(uncompfd, statbuf.st_uid, statbuf.st_gid) == -1) {
1419 (void) close(compfd);
1420 (void) close(uncompfd);
1421 delete_mapping(lfd, devicename, filename, B_TRUE);
1422 die("%s could not be uncompressed\n", filename);
1425 /* Now read from the device in MAXBSIZE-sized chunks */
1426 for (;;) {
1427 rbytes = read(compfd, buf, sizeof (buf));
1429 if (rbytes <= 0)
1430 break;
1432 if (write(uncompfd, buf, rbytes) != rbytes) {
1433 rbytes = -1;
1434 break;
1438 (void) close(compfd);
1439 (void) close(uncompfd);
1441 /* Delete the mapping */
1442 delete_mapping(lfd, devicename, filename, B_TRUE);
1445 * If an error occured while reading or writing, rbytes will
1446 * be negative
1448 if (rbytes < 0) {
1449 (void) unlink(tmpfilename);
1450 die(gettext("could not read from %s"), filename);
1453 /* Rename the temp file to the actual file */
1454 if (rename(tmpfilename, filename) == -1)
1455 (void) unlink(tmpfilename);
1459 * Compress a file
1461 static void
1462 lofi_compress(int *lfd, const char *filename, int compress_index,
1463 uint32_t segsize)
1465 struct lofi_ioctl lic;
1466 lofi_compress_info_t *li;
1467 struct flock lock;
1468 char tmpfilename[MAXPATHLEN];
1469 char comp_filename[MAXPATHLEN];
1470 char algorithm[MAXALGLEN];
1471 char *x;
1472 char *dir = NULL, *file = NULL;
1473 uchar_t *uncompressed_seg = NULL;
1474 uchar_t *compressed_seg = NULL;
1475 uint32_t compressed_segsize;
1476 uint32_t len_compressed, count;
1477 uint32_t index_entries, index_sz;
1478 uint64_t *index = NULL;
1479 uint64_t offset;
1480 size_t real_segsize;
1481 struct stat64 statbuf;
1482 int compfd = -1, uncompfd = -1;
1483 int tfd = -1;
1484 ssize_t rbytes, wbytes, lastread;
1485 int i, type;
1488 * Disallow compressing the file if it is
1489 * already mapped
1491 lic.li_id = 0;
1492 (void) strlcpy(lic.li_filename, filename, sizeof (lic.li_filename));
1493 if (ioctl(*lfd, LOFI_GET_MINOR, &lic) != -1)
1494 die(gettext("%s must be unmapped before compressing"),
1495 filename);
1498 * Close the control device so other operations
1499 * can use it
1501 (void) close(*lfd);
1502 *lfd = -1;
1504 li = &lofi_compress_table[compress_index];
1507 * The size of the buffer to hold compressed data must
1508 * be slightly larger than the compressed segment size.
1510 * The compress functions use part of the buffer as
1511 * scratch space to do calculations.
1512 * Ref: http://www.zlib.net/manual.html#compress2
1514 compressed_segsize = segsize + (segsize >> 6);
1515 compressed_seg = (uchar_t *)malloc(compressed_segsize + SEGHDR);
1516 uncompressed_seg = (uchar_t *)malloc(segsize);
1518 if (compressed_seg == NULL || uncompressed_seg == NULL)
1519 die(gettext("No memory"));
1521 if ((uncompfd = open64(filename, O_RDWR|O_LARGEFILE, 0)) == -1)
1522 die(gettext("open: %s"), filename);
1524 lock.l_type = F_WRLCK;
1525 lock.l_whence = SEEK_SET;
1526 lock.l_start = 0;
1527 lock.l_len = 0;
1530 * Use an advisory lock to ensure that only a
1531 * single lofiadm process compresses a given
1532 * file at any given time
1534 * A close on the file descriptor automatically
1535 * closes all lock state on the file
1537 if (fcntl(uncompfd, F_SETLKW, &lock) == -1)
1538 die(gettext("fcntl: %s"), filename);
1540 if (fstat64(uncompfd, &statbuf) == -1) {
1541 (void) close(uncompfd);
1542 die(gettext("fstat: %s"), filename);
1545 /* Zero length files don't need to be compressed */
1546 if (statbuf.st_size == 0) {
1547 (void) close(uncompfd);
1548 return;
1552 * Create temporary files in the same directory that
1553 * will hold the intermediate data
1555 x = strdup(filename);
1556 dir = strdup(dirname(x));
1557 free(x);
1558 x = strdup(filename);
1559 file = strdup(basename(x));
1560 free(x);
1561 (void) snprintf(tmpfilename, sizeof (tmpfilename),
1562 "%s/.%sXXXXXX", dir, file);
1563 (void) snprintf(comp_filename, sizeof (comp_filename),
1564 "%s/.%sXXXXXX", dir, file);
1565 free(dir);
1566 free(file);
1568 if ((tfd = mkstemp64(tmpfilename)) == -1)
1569 goto cleanup;
1571 if ((compfd = mkstemp64(comp_filename)) == -1)
1572 goto cleanup;
1575 * Set the mode bits and owner of the compressed
1576 * file to be that of the original uncompressed file
1578 (void) fchmod(compfd, statbuf.st_mode);
1580 if (fchown(compfd, statbuf.st_uid, statbuf.st_gid) == -1)
1581 goto cleanup;
1584 * Calculate the number of index entries required.
1585 * index entries are stored as an array. adding
1586 * a '2' here accounts for the fact that the last
1587 * segment may not be a multiple of the segment size
1589 index_sz = (statbuf.st_size / segsize) + 2;
1590 index = malloc(sizeof (*index) * index_sz);
1592 if (index == NULL)
1593 goto cleanup;
1595 offset = 0;
1596 lastread = segsize;
1597 count = 0;
1600 * Now read from the uncompressed file in 'segsize'
1601 * sized chunks, compress what was read in and
1602 * write it out to a temporary file
1604 for (;;) {
1605 rbytes = read(uncompfd, uncompressed_seg, segsize);
1607 if (rbytes <= 0)
1608 break;
1610 if (lastread < segsize)
1611 goto cleanup;
1614 * Account for the first byte that
1615 * indicates whether a segment is
1616 * compressed or not
1618 real_segsize = segsize - 1;
1619 (void) li->l_compress(uncompressed_seg, rbytes,
1620 compressed_seg + SEGHDR, &real_segsize, li->l_level);
1623 * If the length of the compressed data is more
1624 * than a threshold then there isn't any benefit
1625 * to be had from compressing this segment - leave
1626 * it uncompressed.
1628 * NB. In case an error occurs during compression (above)
1629 * the 'real_segsize' isn't changed. The logic below
1630 * ensures that that segment is left uncompressed.
1632 len_compressed = real_segsize;
1633 if (segsize <= COMPRESS_THRESHOLD ||
1634 real_segsize > (segsize - COMPRESS_THRESHOLD)) {
1635 (void) memcpy(compressed_seg + SEGHDR, uncompressed_seg,
1636 rbytes);
1637 type = UNCOMPRESSED;
1638 len_compressed = rbytes;
1639 } else {
1640 type = COMPRESSED;
1644 * Set the first byte or the SEGHDR to
1645 * indicate if it's compressed or not
1647 *compressed_seg = type;
1648 wbytes = write(tfd, compressed_seg, len_compressed + SEGHDR);
1649 if (wbytes != (len_compressed + SEGHDR)) {
1650 rbytes = -1;
1651 break;
1654 index[count] = BE_64(offset);
1655 offset += wbytes;
1656 lastread = rbytes;
1657 count++;
1660 (void) close(uncompfd);
1662 if (rbytes < 0)
1663 goto cleanup;
1665 * The last index entry is a sentinel entry. It does not point to
1666 * an actual compressed segment but helps in computing the size of
1667 * the compressed segment. The size of each compressed segment is
1668 * computed by subtracting the current index value from the next
1669 * one (the compressed blocks are stored sequentially)
1671 index[count++] = BE_64(offset);
1674 * Now write the compressed data along with the
1675 * header information to this file which will
1676 * later be renamed to the original uncompressed
1677 * file name
1679 * The header is as follows -
1681 * Signature (name of the compression algorithm)
1682 * Compression segment size (a multiple of 512)
1683 * Number of index entries
1684 * Size of the last block
1685 * The array containing the index entries
1687 * the header is always stored in network byte
1688 * order
1690 (void) bzero(algorithm, sizeof (algorithm));
1691 (void) strlcpy(algorithm, li->l_name, sizeof (algorithm));
1692 if (write(compfd, algorithm, sizeof (algorithm))
1693 != sizeof (algorithm))
1694 goto cleanup;
1696 segsize = htonl(segsize);
1697 if (write(compfd, &segsize, sizeof (segsize)) != sizeof (segsize))
1698 goto cleanup;
1700 index_entries = htonl(count);
1701 if (write(compfd, &index_entries, sizeof (index_entries)) !=
1702 sizeof (index_entries))
1703 goto cleanup;
1705 lastread = htonl(lastread);
1706 if (write(compfd, &lastread, sizeof (lastread)) != sizeof (lastread))
1707 goto cleanup;
1709 for (i = 0; i < count; i++) {
1710 if (write(compfd, index + i, sizeof (*index)) !=
1711 sizeof (*index))
1712 goto cleanup;
1715 /* Header is written, now write the compressed data */
1716 if (lseek(tfd, 0, SEEK_SET) != 0)
1717 goto cleanup;
1719 rbytes = wbytes = 0;
1721 for (;;) {
1722 rbytes = read(tfd, compressed_seg, compressed_segsize + SEGHDR);
1724 if (rbytes <= 0)
1725 break;
1727 if (write(compfd, compressed_seg, rbytes) != rbytes)
1728 goto cleanup;
1731 if (fstat64(compfd, &statbuf) == -1)
1732 goto cleanup;
1735 * Round up the compressed file size to be a multiple of
1736 * DEV_BSIZE. lofi(7D) likes it that way.
1738 if ((offset = statbuf.st_size % DEV_BSIZE) > 0) {
1740 offset = DEV_BSIZE - offset;
1742 for (i = 0; i < offset; i++)
1743 uncompressed_seg[i] = '\0';
1744 if (write(compfd, uncompressed_seg, offset) != offset)
1745 goto cleanup;
1747 (void) close(compfd);
1748 (void) close(tfd);
1749 (void) unlink(tmpfilename);
1750 cleanup:
1751 if (rbytes < 0) {
1752 if (tfd != -1)
1753 (void) unlink(tmpfilename);
1754 if (compfd != -1)
1755 (void) unlink(comp_filename);
1756 die(gettext("error compressing file %s"), filename);
1757 } else {
1758 /* Rename the compressed file to the actual file */
1759 if (rename(comp_filename, filename) == -1) {
1760 (void) unlink(comp_filename);
1761 die(gettext("error compressing file %s"), filename);
1764 free(compressed_seg);
1765 free(uncompressed_seg);
1766 free(index);
1767 if (compfd != -1)
1768 (void) close(compfd);
1769 if (uncompfd != -1)
1770 (void) close(uncompfd);
1771 if (tfd != -1)
1772 (void) close(tfd);
1775 static int
1776 lofi_compress_select(const char *algname)
1778 int i;
1780 for (i = 0; i < LOFI_COMPRESS_FUNCTIONS; i++) {
1781 if (strcmp(lofi_compress_table[i].l_name, algname) == 0)
1782 return (i);
1784 return (-1);
1787 static void
1788 check_algorithm_validity(const char *algname, int *compress_index)
1790 *compress_index = lofi_compress_select(algname);
1791 if (*compress_index < 0)
1792 die(gettext("invalid algorithm name: %s\n"), algname);
1795 static void
1796 check_file_validity(const char *filename)
1798 struct stat64 buf;
1799 int error;
1800 int fd;
1802 fd = open64(filename, O_RDONLY);
1803 if (fd == -1) {
1804 die(gettext("open: %s"), filename);
1806 error = fstat64(fd, &buf);
1807 if (error == -1) {
1808 die(gettext("fstat: %s"), filename);
1809 } else if (!S_ISLOFIABLE(buf.st_mode)) {
1810 die(gettext("%s is not a regular file, "
1811 "block, or character device\n"),
1812 filename);
1813 } else if ((buf.st_size % DEV_BSIZE) != 0) {
1814 die(gettext("size of %s is not a multiple of %d\n"),
1815 filename, DEV_BSIZE);
1817 (void) close(fd);
1819 if (name_to_minor(filename) != 0) {
1820 die(gettext("cannot use %s on itself\n"), LOFI_DRIVER_NAME);
1824 static boolean_t
1825 check_file_is_encrypted(const char *filename)
1827 int fd;
1828 char buf[sizeof (lofi_crypto_magic)];
1829 int got;
1830 int rest = sizeof (lofi_crypto_magic);
1832 fd = open64(filename, O_RDONLY);
1833 if (fd == -1)
1834 die(gettext("failed to open: %s"), filename);
1836 if (lseek(fd, CRYOFF, SEEK_SET) != CRYOFF)
1837 die(gettext("failed to seek to offset 0x%lx in file %s"),
1838 CRYOFF, filename);
1840 do {
1841 got = read(fd, buf + sizeof (lofi_crypto_magic) - rest, rest);
1842 if ((got == 0) || ((got == -1) && (errno != EINTR)))
1843 die(gettext("failed to read crypto header"
1844 " at offset 0x%lx in file %s"), CRYOFF, filename);
1846 if (got > 0)
1847 rest -= got;
1848 } while (rest > 0);
1850 while (close(fd) == -1) {
1851 if (errno != EINTR)
1852 die(gettext("failed to close file %s"), filename);
1855 return (strncmp(buf, lofi_crypto_magic,
1856 sizeof (lofi_crypto_magic)) == 0);
1859 static uint32_t
1860 convert_to_num(const char *str)
1862 int len;
1863 uint32_t segsize, mult = 1;
1865 len = strlen(str);
1866 if (len && isalpha(str[len - 1])) {
1867 switch (str[len - 1]) {
1868 case 'k':
1869 case 'K':
1870 mult = KILOBYTE;
1871 break;
1872 case 'b':
1873 case 'B':
1874 mult = BLOCK_SIZE;
1875 break;
1876 case 'm':
1877 case 'M':
1878 mult = MEGABYTE;
1879 break;
1880 case 'g':
1881 case 'G':
1882 mult = GIGABYTE;
1883 break;
1884 default:
1885 die(gettext("invalid segment size %s\n"), str);
1889 segsize = atol(str);
1890 segsize *= mult;
1892 return (segsize);
1896 main(int argc, char *argv[])
1898 int lfd;
1899 int c;
1900 const char *devicename = NULL;
1901 const char *filename = NULL;
1902 const char *algname = COMPRESS_ALGORITHM;
1903 int openflag;
1904 int minor;
1905 int compress_index;
1906 uint32_t segsize = SEGSIZE;
1907 static char *lofictl = "/dev/" LOFI_CTL_NAME;
1908 boolean_t force = B_FALSE;
1909 const char *pname;
1910 boolean_t errflag = B_FALSE;
1911 boolean_t addflag = B_FALSE;
1912 boolean_t labelflag = B_FALSE;
1913 boolean_t rdflag = B_FALSE;
1914 boolean_t deleteflag = B_FALSE;
1915 boolean_t ephflag = B_FALSE;
1916 boolean_t compressflag = B_FALSE;
1917 boolean_t uncompressflag = B_FALSE;
1918 /* the next two work together for -c, -k, -T, -e options only */
1919 boolean_t need_crypto = B_FALSE; /* if any -c, -k, -T, -e */
1920 boolean_t cipher_only = B_TRUE; /* if -c only */
1921 const char *keyfile = NULL;
1922 mech_alias_t *cipher = NULL;
1923 token_spec_t *token = NULL;
1924 char *rkey = NULL;
1925 size_t rksz = 0;
1926 char realfilename[MAXPATHLEN];
1928 pname = getpname(argv[0]);
1930 (void) setlocale(LC_ALL, "");
1931 (void) textdomain(TEXT_DOMAIN);
1933 while ((c = getopt(argc, argv, "a:c:Cd:efk:lrs:T:U")) != EOF) {
1934 switch (c) {
1935 case 'a':
1936 addflag = B_TRUE;
1937 if ((filename = realpath(optarg, realfilename)) == NULL)
1938 die("%s", optarg);
1939 if (((argc - optind) > 0) && (*argv[optind] != '-')) {
1940 /* optional device */
1941 devicename = argv[optind];
1942 optind++;
1944 break;
1945 case 'C':
1946 compressflag = B_TRUE;
1947 if (((argc - optind) > 1) && (*argv[optind] != '-')) {
1948 /* optional algorithm */
1949 algname = argv[optind];
1950 optind++;
1952 check_algorithm_validity(algname, &compress_index);
1953 break;
1954 case 'c':
1955 /* is the chosen cipher allowed? */
1956 if ((cipher = ciph2mech(optarg)) == NULL) {
1957 errflag = B_TRUE;
1958 warn(gettext("cipher %s not allowed\n"),
1959 optarg);
1961 need_crypto = B_TRUE;
1962 /* cipher_only is already set */
1963 break;
1964 case 'd':
1965 deleteflag = B_TRUE;
1966 minor = name_to_minor(optarg);
1967 if (minor != 0)
1968 devicename = optarg;
1969 else {
1970 if ((filename = realpath(optarg,
1971 realfilename)) == NULL)
1972 die("%s", optarg);
1974 break;
1975 case 'e':
1976 ephflag = B_TRUE;
1977 need_crypto = B_TRUE;
1978 cipher_only = B_FALSE; /* need to unset cipher_only */
1979 break;
1980 case 'f':
1981 force = B_TRUE;
1982 break;
1983 case 'k':
1984 keyfile = optarg;
1985 need_crypto = B_TRUE;
1986 cipher_only = B_FALSE; /* need to unset cipher_only */
1987 break;
1988 case 'l':
1989 labelflag = B_TRUE;
1990 break;
1991 case 'r':
1992 rdflag = B_TRUE;
1993 break;
1994 case 's':
1995 segsize = convert_to_num(optarg);
1996 if (segsize < DEV_BSIZE || !ISP2(segsize))
1997 die(gettext("segment size %s is invalid "
1998 "or not a multiple of minimum block "
1999 "size %ld\n"), optarg, DEV_BSIZE);
2000 break;
2001 case 'T':
2002 if ((token = parsetoken(optarg)) == NULL) {
2003 errflag = B_TRUE;
2004 warn(
2005 gettext("invalid token key specifier %s\n"),
2006 optarg);
2008 need_crypto = B_TRUE;
2009 cipher_only = B_FALSE; /* need to unset cipher_only */
2010 break;
2011 case 'U':
2012 uncompressflag = B_TRUE;
2013 break;
2014 case '?':
2015 default:
2016 errflag = B_TRUE;
2017 break;
2021 /* Check for mutually exclusive combinations of options */
2022 if (errflag ||
2023 (addflag && deleteflag) ||
2024 (labelflag && !addflag) ||
2025 (rdflag && !addflag) ||
2026 (!addflag && need_crypto) ||
2027 (need_crypto && labelflag) ||
2028 ((compressflag || uncompressflag) &&
2029 (labelflag || addflag || deleteflag)))
2030 usage(pname);
2032 /* ephemeral key, and key from either file or token are incompatible */
2033 if (ephflag && (keyfile != NULL || token != NULL)) {
2034 die(gettext("ephemeral key cannot be used with keyfile"
2035 " or token key\n"));
2039 * "-c" but no "-k", "-T", "-e", or "-T -k" means derive key from
2040 * command line passphrase
2043 switch (argc - optind) {
2044 case 0: /* no more args */
2045 if (compressflag || uncompressflag) /* needs filename */
2046 usage(pname);
2047 break;
2048 case 1:
2049 if (addflag || deleteflag)
2050 usage(pname);
2051 /* one arg means compress/uncompress the file ... */
2052 if (compressflag || uncompressflag) {
2053 if ((filename = realpath(argv[optind],
2054 realfilename)) == NULL)
2055 die("%s", argv[optind]);
2056 /* ... or without options means print the association */
2057 } else {
2058 minor = name_to_minor(argv[optind]);
2059 if (minor != 0)
2060 devicename = argv[optind];
2061 else {
2062 if ((filename = realpath(argv[optind],
2063 realfilename)) == NULL)
2064 die("%s", argv[optind]);
2067 break;
2068 default:
2069 usage(pname);
2070 break;
2073 if (addflag || compressflag || uncompressflag)
2074 check_file_validity(filename);
2076 if (filename && !valid_abspath(filename))
2077 exit(E_ERROR);
2080 * Here, we know the arguments are correct, the filename is an
2081 * absolute path, it exists and is a regular file. We don't yet
2082 * know that the device name is ok or not.
2085 openflag = O_EXCL;
2086 if (addflag || deleteflag || compressflag || uncompressflag)
2087 openflag |= O_RDWR;
2088 else
2089 openflag |= O_RDONLY;
2090 lfd = open(lofictl, openflag);
2091 if (lfd == -1) {
2092 if ((errno == EPERM) || (errno == EACCES)) {
2093 die(gettext("you do not have permission to perform "
2094 "that operation.\n"));
2095 } else {
2096 die(gettext("open: %s"), lofictl);
2098 /*NOTREACHED*/
2102 * No passphrase is needed for ephemeral key, or when key is
2103 * in a file and not wrapped by another key from a token.
2104 * However, a passphrase is needed in these cases:
2105 * 1. cipher with no ephemeral key, key file, or token,
2106 * in which case the passphrase is used to build the key
2107 * 2. token with an optional cipher or optional key file,
2108 * in which case the passphrase unlocks the token
2109 * If only the cipher is specified, reconfirm the passphrase
2110 * to ensure the user hasn't mis-entered it. Otherwise, the
2111 * token will enforce the token passphrase.
2113 if (need_crypto) {
2114 CK_SESSION_HANDLE sess;
2116 /* pick a cipher if none specified */
2117 if (cipher == NULL)
2118 cipher = DEFAULT_CIPHER;
2120 if (!kernel_cipher_check(cipher))
2121 die(gettext(
2122 "use \"cryptoadm list -m\" to find available "
2123 "mechanisms\n"));
2125 init_crypto(token, cipher, &sess);
2127 if (cipher_only) {
2128 getkeyfromuser(cipher, &rkey, &rksz,
2129 !check_file_is_encrypted(filename));
2130 } else if (token != NULL) {
2131 getkeyfromtoken(sess, token, keyfile, cipher,
2132 &rkey, &rksz);
2133 } else {
2134 /* this also handles ephemeral keys */
2135 getkeyfromfile(keyfile, cipher, &rkey, &rksz);
2138 end_crypto(sess);
2142 * Now to the real work.
2144 if (addflag)
2145 add_mapping(lfd, devicename, filename, cipher, rkey, rksz,
2146 rdflag, labelflag);
2147 else if (compressflag)
2148 lofi_compress(&lfd, filename, compress_index, segsize);
2149 else if (uncompressflag)
2150 lofi_uncompress(lfd, filename);
2151 else if (deleteflag)
2152 delete_mapping(lfd, devicename, filename, force);
2153 else if (filename || devicename)
2154 print_one_mapping(lfd, devicename, filename);
2155 else
2156 print_mappings(lfd);
2158 if (lfd != -1)
2159 (void) close(lfd);
2160 closelib();
2161 return (E_SUCCESS);