xref: /illumos-gate/usr/src/cmd/lofiadm/main.c (revision 69a119caa6570c7077699161b7c28b6ee9f8b0f4)
1 /*
2  * CDDL HEADER START
3  *
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.
7  *
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.
12  *
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]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  * Copyright 2012 Joyent, Inc.  All rights reserved.
25  */
26 
27 /*
28  * lofiadm - administer lofi(7d). Very simple, add and remove file<->device
29  * associations, and display status. All the ioctls are private between
30  * lofi and lofiadm, and so are very simple - device information is
31  * communicated via a minor number.
32  */
33 
34 #include <sys/types.h>
35 #include <sys/param.h>
36 #include <sys/lofi.h>
37 #include <sys/stat.h>
38 #include <sys/sysmacros.h>
39 #include <netinet/in.h>
40 #include <stdio.h>
41 #include <fcntl.h>
42 #include <locale.h>
43 #include <string.h>
44 #include <strings.h>
45 #include <errno.h>
46 #include <stdlib.h>
47 #include <unistd.h>
48 #include <stropts.h>
49 #include <libdevinfo.h>
50 #include <libgen.h>
51 #include <ctype.h>
52 #include <dlfcn.h>
53 #include <limits.h>
54 #include <security/cryptoki.h>
55 #include <cryptoutil.h>
56 #include <sys/crypto/ioctl.h>
57 #include <sys/crypto/ioctladmin.h>
58 #include "utils.h"
59 #include <LzmaEnc.h>
60 
61 /* Only need the IV len #defines out of these files, nothing else. */
62 #include <aes/aes_impl.h>
63 #include <des/des_impl.h>
64 #include <blowfish/blowfish_impl.h>
65 
66 static const char USAGE[] =
67 	"Usage: %s -a file [ device ] "
68 	" [-c aes-128-cbc|aes-192-cbc|aes-256-cbc|des3-cbc|blowfish-cbc]"
69 	" [-e] [-k keyfile] [-T [token]:[manuf]:[serial]:key]\n"
70 	"       %s -d file | device\n"
71 	"       %s -C [gzip|gzip-6|gzip-9|lzma] [-s segment_size] file\n"
72 	"       %s -U file\n"
73 	"       %s [ file | device ]\n";
74 
75 typedef struct token_spec {
76 	char	*name;
77 	char	*mfr;
78 	char	*serno;
79 	char	*key;
80 } token_spec_t;
81 
82 typedef struct mech_alias {
83 	char	*alias;
84 	CK_MECHANISM_TYPE type;
85 	char	*name;		/* for ioctl */
86 	char	*iv_name;	/* for ioctl */
87 	size_t	iv_len;		/* for ioctl */
88 	iv_method_t iv_type;	/* for ioctl */
89 	size_t	min_keysize;	/* in bytes */
90 	size_t	max_keysize;	/* in bytes */
91 	token_spec_t *token;
92 	CK_SLOT_ID slot;
93 } mech_alias_t;
94 
95 static mech_alias_t mech_aliases[] = {
96 	/* Preferred one should always be listed first. */
97 	{ "aes-256-cbc", CKM_AES_CBC, "CKM_AES_CBC", "CKM_AES_ECB", AES_IV_LEN,
98 	    IVM_ENC_BLKNO, ULONG_MAX, 0L, NULL, (CK_SLOT_ID) -1 },
99 	{ "aes-192-cbc", CKM_AES_CBC, "CKM_AES_CBC", "CKM_AES_ECB", AES_IV_LEN,
100 	    IVM_ENC_BLKNO, ULONG_MAX, 0L, NULL, (CK_SLOT_ID) -1 },
101 	{ "aes-128-cbc", CKM_AES_CBC, "CKM_AES_CBC", "CKM_AES_ECB", AES_IV_LEN,
102 	    IVM_ENC_BLKNO, ULONG_MAX, 0L, NULL, (CK_SLOT_ID) -1 },
103 	{ "des3-cbc", CKM_DES3_CBC, "CKM_DES3_CBC", "CKM_DES3_ECB", DES_IV_LEN,
104 	    IVM_ENC_BLKNO, ULONG_MAX, 0L, NULL, (CK_SLOT_ID)-1 },
105 	{ "blowfish-cbc", CKM_BLOWFISH_CBC, "CKM_BLOWFISH_CBC",
106 	    "CKM_BLOWFISH_ECB", BLOWFISH_IV_LEN, IVM_ENC_BLKNO, ULONG_MAX,
107 	    0L, NULL, (CK_SLOT_ID)-1 }
108 	/*
109 	 * A cipher without an iv requirement would look like this:
110 	 * { "aes-xex", CKM_AES_XEX, "CKM_AES_XEX", NULL, 0,
111 	 *    IVM_NONE, ULONG_MAX, 0L, NULL, (CK_SLOT_ID)-1 }
112 	 */
113 };
114 
115 int	mech_aliases_count = (sizeof (mech_aliases) / sizeof (mech_alias_t));
116 
117 /* Preferred cipher, if one isn't specified on command line. */
118 #define	DEFAULT_CIPHER	(&mech_aliases[0])
119 
120 #define	DEFAULT_CIPHER_NUM	64	/* guess # kernel ciphers available */
121 #define	DEFAULT_MECHINFO_NUM	16	/* guess # kernel mechs available */
122 #define	MIN_PASSLEN		8	/* min acceptable passphrase size */
123 
124 static int gzip_compress(void *src, size_t srclen, void *dst,
125 	size_t *destlen, int level);
126 static int lzma_compress(void *src, size_t srclen, void *dst,
127 	size_t *destlen, int level);
128 
129 lofi_compress_info_t lofi_compress_table[LOFI_COMPRESS_FUNCTIONS] = {
130 	{NULL,  		gzip_compress,  6,	"gzip"}, /* default */
131 	{NULL,			gzip_compress,	6,	"gzip-6"},
132 	{NULL,			gzip_compress,	9, 	"gzip-9"},
133 	{NULL,  		lzma_compress, 	0, 	"lzma"}
134 };
135 
136 /* For displaying lofi mappings */
137 #define	FORMAT 			"%-20s     %-30s	%s\n"
138 
139 #define	COMPRESS_ALGORITHM	"gzip"
140 #define	COMPRESS_THRESHOLD	2048
141 #define	SEGSIZE			131072
142 #define	BLOCK_SIZE		512
143 #define	KILOBYTE		1024
144 #define	MEGABYTE		(KILOBYTE * KILOBYTE)
145 #define	GIGABYTE		(KILOBYTE * MEGABYTE)
146 #define	LIBZ			"libz.so"
147 
148 static void
149 usage(const char *pname)
150 {
151 	(void) fprintf(stderr, gettext(USAGE), pname, pname, pname,
152 	    pname, pname);
153 	exit(E_USAGE);
154 }
155 
156 static int
157 gzip_compress(void *src, size_t srclen, void *dst, size_t *dstlen, int level)
158 {
159 	static int (*compress2p)(void *, ulong_t *, void *, size_t, int) = NULL;
160 	void *libz_hdl = NULL;
161 
162 	/*
163 	 * The first time we are called, attempt to dlopen()
164 	 * libz.so and get a pointer to the compress2() function
165 	 */
166 	if (compress2p == NULL) {
167 		if ((libz_hdl = openlib(LIBZ)) == NULL)
168 			die(gettext("could not find %s. "
169 			    "gzip compression unavailable\n"), LIBZ);
170 
171 		if ((compress2p =
172 		    (int (*)(void *, ulong_t *, void *, size_t, int))
173 		    dlsym(libz_hdl, "compress2")) == NULL) {
174 			closelib();
175 			die(gettext("could not find the correct %s. "
176 			    "gzip compression unavailable\n"), LIBZ);
177 		}
178 	}
179 
180 	if ((*compress2p)(dst, (ulong_t *)dstlen, src, srclen, level) != 0)
181 		return (-1);
182 	return (0);
183 }
184 
185 /*ARGSUSED*/
186 static void
187 *SzAlloc(void *p, size_t size)
188 {
189 	return (malloc(size));
190 }
191 
192 /*ARGSUSED*/
193 static void
194 SzFree(void *p, void *address, size_t size)
195 {
196 	free(address);
197 }
198 
199 static ISzAlloc g_Alloc = {
200 	SzAlloc,
201 	SzFree
202 };
203 
204 #define	LZMA_UNCOMPRESSED_SIZE	8
205 #define	LZMA_HEADER_SIZE (LZMA_PROPS_SIZE + LZMA_UNCOMPRESSED_SIZE)
206 
207 /*ARGSUSED*/
208 static int
209 lzma_compress(void *src, size_t srclen, void *dst,
210 	size_t *dstlen, int level)
211 {
212 	CLzmaEncProps props;
213 	size_t outsize2;
214 	size_t outsizeprocessed;
215 	size_t outpropssize = LZMA_PROPS_SIZE;
216 	uint64_t t = 0;
217 	SRes res;
218 	Byte *dstp;
219 	int i;
220 
221 	outsize2 = *dstlen;
222 
223 	LzmaEncProps_Init(&props);
224 
225 	/*
226 	 * The LZMA compressed file format is as follows -
227 	 *
228 	 * Offset Size(bytes) Description
229 	 * 0		1	LZMA properties (lc, lp, lp (encoded))
230 	 * 1		4	Dictionary size (little endian)
231 	 * 5		8	Uncompressed size (little endian)
232 	 * 13			Compressed data
233 	 */
234 
235 	/* set the dictionary size to be 8MB */
236 	props.dictSize = 1 << 23;
237 
238 	if (*dstlen < LZMA_HEADER_SIZE)
239 		return (SZ_ERROR_OUTPUT_EOF);
240 
241 	dstp = (Byte *)dst;
242 	t = srclen;
243 	/*
244 	 * Set the uncompressed size in the LZMA header
245 	 * The LZMA properties (specified in 'props')
246 	 * will be set by the call to LzmaEncode()
247 	 */
248 	for (i = 0; i < LZMA_UNCOMPRESSED_SIZE; i++, t >>= 8) {
249 		dstp[LZMA_PROPS_SIZE + i] = (Byte)t;
250 	}
251 
252 	outsizeprocessed = outsize2 - LZMA_HEADER_SIZE;
253 	res = LzmaEncode(dstp + LZMA_HEADER_SIZE, &outsizeprocessed,
254 	    src, srclen, &props, dstp, &outpropssize, 0, NULL,
255 	    &g_Alloc, &g_Alloc);
256 
257 	if (res != 0)
258 		return (-1);
259 
260 	*dstlen = outsizeprocessed + LZMA_HEADER_SIZE;
261 	return (0);
262 }
263 
264 /*
265  * Translate a lofi device name to a minor number. We might be asked
266  * to do this when there is no association (such as when the user specifies
267  * a particular device), so we can only look at the string.
268  */
269 static int
270 name_to_minor(const char *devicename)
271 {
272 	int	minor;
273 
274 	if (sscanf(devicename, "/dev/" LOFI_BLOCK_NAME "/%d", &minor) == 1) {
275 		return (minor);
276 	}
277 	if (sscanf(devicename, "/dev/" LOFI_CHAR_NAME "/%d", &minor) == 1) {
278 		return (minor);
279 	}
280 	return (0);
281 }
282 
283 /*
284  * This might be the first time we've used this minor number. If so,
285  * it might also be that the /dev links are in the process of being created
286  * by devfsadmd (or that they'll be created "soon"). We cannot return
287  * until they're there or the invoker of lofiadm might try to use them
288  * and not find them. This can happen if a shell script is running on
289  * an MP.
290  */
291 static int sleeptime = 2;	/* number of seconds to sleep between stat's */
292 static int maxsleep = 120;	/* maximum number of seconds to sleep */
293 
294 static void
295 wait_until_dev_complete(int minor)
296 {
297 	struct stat64 buf;
298 	int	cursleep;
299 	char	blkpath[MAXPATHLEN];
300 	char	charpath[MAXPATHLEN];
301 	di_devlink_handle_t hdl;
302 
303 	(void) snprintf(blkpath, sizeof (blkpath), "/dev/%s/%d",
304 	    LOFI_BLOCK_NAME, minor);
305 	(void) snprintf(charpath, sizeof (charpath), "/dev/%s/%d",
306 	    LOFI_CHAR_NAME, minor);
307 
308 	/* Check if links already present */
309 	if (stat64(blkpath, &buf) == 0 && stat64(charpath, &buf) == 0)
310 		return;
311 
312 	/* First use di_devlink_init() */
313 	if (hdl = di_devlink_init("lofi", DI_MAKE_LINK)) {
314 		(void) di_devlink_fini(&hdl);
315 		goto out;
316 	}
317 
318 	/*
319 	 * Under normal conditions, di_devlink_init(DI_MAKE_LINK) above will
320 	 * only fail if the caller is non-root. In that case, wait for
321 	 * link creation via sysevents.
322 	 */
323 	for (cursleep = 0; cursleep < maxsleep; cursleep += sleeptime) {
324 		if (stat64(blkpath, &buf) == 0 && stat64(charpath, &buf) == 0)
325 			return;
326 		(void) sleep(sleeptime);
327 	}
328 
329 	/* one last try */
330 out:
331 	if (stat64(blkpath, &buf) == -1) {
332 		die(gettext("%s was not created"), blkpath);
333 	}
334 	if (stat64(charpath, &buf) == -1) {
335 		die(gettext("%s was not created"), charpath);
336 	}
337 }
338 
339 /*
340  * Map the file and return the minor number the driver picked for the file
341  * DO NOT use this function if the filename is actually the device name.
342  */
343 static int
344 lofi_map_file(int lfd, struct lofi_ioctl li, const char *filename)
345 {
346 	int	minor;
347 
348 	li.li_minor = 0;
349 	(void) strlcpy(li.li_filename, filename, sizeof (li.li_filename));
350 	minor = ioctl(lfd, LOFI_MAP_FILE, &li);
351 	if (minor == -1) {
352 		if (errno == ENOTSUP)
353 			warn(gettext("encrypting compressed files is "
354 			    "unsupported"));
355 		die(gettext("could not map file %s"), filename);
356 	}
357 	wait_until_dev_complete(minor);
358 	return (minor);
359 }
360 
361 /*
362  * Add a device association. If devicename is NULL, let the driver
363  * pick a device.
364  */
365 static void
366 add_mapping(int lfd, const char *devicename, const char *filename,
367     mech_alias_t *cipher, const char *rkey, size_t rksz)
368 {
369 	struct lofi_ioctl li;
370 
371 	li.li_crypto_enabled = B_FALSE;
372 	if (cipher != NULL) {
373 		/* set up encryption for mapped file */
374 		li.li_crypto_enabled = B_TRUE;
375 		(void) strlcpy(li.li_cipher, cipher->name,
376 		    sizeof (li.li_cipher));
377 		if (rksz > sizeof (li.li_key)) {
378 			die(gettext("key too large"));
379 		}
380 		bcopy(rkey, li.li_key, rksz);
381 		li.li_key_len = rksz << 3;	/* convert to bits */
382 
383 		li.li_iv_type = cipher->iv_type;
384 		li.li_iv_len = cipher->iv_len;	/* 0 when no iv needed */
385 		switch (cipher->iv_type) {
386 		case IVM_ENC_BLKNO:
387 			(void) strlcpy(li.li_iv_cipher, cipher->iv_name,
388 			    sizeof (li.li_iv_cipher));
389 			break;
390 		case IVM_NONE:
391 			/* FALLTHROUGH */
392 		default:
393 			break;
394 		}
395 	}
396 
397 	if (devicename == NULL) {
398 		int	minor;
399 
400 		/* pick one via the driver */
401 		minor = lofi_map_file(lfd, li, filename);
402 		/* if mapping succeeds, print the one picked */
403 		(void) printf("/dev/%s/%d\n", LOFI_BLOCK_NAME, minor);
404 		return;
405 	}
406 
407 	/* use device we were given */
408 	li.li_minor = name_to_minor(devicename);
409 	if (li.li_minor == 0) {
410 		die(gettext("malformed device name %s\n"), devicename);
411 	}
412 	(void) strlcpy(li.li_filename, filename, sizeof (li.li_filename));
413 
414 	/* if device is already in use li.li_minor won't change */
415 	if (ioctl(lfd, LOFI_MAP_FILE_MINOR, &li) == -1) {
416 		if (errno == ENOTSUP)
417 			warn(gettext("encrypting compressed files is "
418 			    "unsupported"));
419 		die(gettext("could not map file %s to %s"), filename,
420 		    devicename);
421 	}
422 	wait_until_dev_complete(li.li_minor);
423 }
424 
425 /*
426  * Remove an association. Delete by device name if non-NULL, or by
427  * filename otherwise.
428  */
429 static void
430 delete_mapping(int lfd, const char *devicename, const char *filename,
431     boolean_t force)
432 {
433 	struct lofi_ioctl li;
434 
435 	li.li_force = force;
436 	li.li_cleanup = B_FALSE;
437 
438 	if (devicename == NULL) {
439 		/* delete by filename */
440 		(void) strlcpy(li.li_filename, filename,
441 		    sizeof (li.li_filename));
442 		li.li_minor = 0;
443 		if (ioctl(lfd, LOFI_UNMAP_FILE, &li) == -1) {
444 			die(gettext("could not unmap file %s"), filename);
445 		}
446 		return;
447 	}
448 
449 	/* delete by device */
450 	li.li_minor = name_to_minor(devicename);
451 	if (li.li_minor == 0) {
452 		die(gettext("malformed device name %s\n"), devicename);
453 	}
454 	if (ioctl(lfd, LOFI_UNMAP_FILE_MINOR, &li) == -1) {
455 		die(gettext("could not unmap device %s"), devicename);
456 	}
457 }
458 
459 /*
460  * Show filename given devicename, or devicename given filename.
461  */
462 static void
463 print_one_mapping(int lfd, const char *devicename, const char *filename)
464 {
465 	struct lofi_ioctl li;
466 
467 	if (devicename == NULL) {
468 		/* given filename, print devicename */
469 		li.li_minor = 0;
470 		(void) strlcpy(li.li_filename, filename,
471 		    sizeof (li.li_filename));
472 		if (ioctl(lfd, LOFI_GET_MINOR, &li) == -1) {
473 			die(gettext("could not find device for %s"), filename);
474 		}
475 		(void) printf("/dev/%s/%d\n", LOFI_BLOCK_NAME, li.li_minor);
476 		return;
477 	}
478 
479 	/* given devicename, print filename */
480 	li.li_minor = name_to_minor(devicename);
481 	if (li.li_minor == 0) {
482 		die(gettext("malformed device name %s\n"), devicename);
483 	}
484 	if (ioctl(lfd, LOFI_GET_FILENAME, &li) == -1) {
485 		die(gettext("could not find filename for %s"), devicename);
486 	}
487 	(void) printf("%s\n", li.li_filename);
488 }
489 
490 /*
491  * Print the list of all the mappings, including a header.
492  */
493 static void
494 print_mappings(int fd)
495 {
496 	struct lofi_ioctl li;
497 	int	minor;
498 	int	maxminor;
499 	char	path[MAXPATHLEN];
500 	char	options[MAXPATHLEN];
501 
502 	li.li_minor = 0;
503 	if (ioctl(fd, LOFI_GET_MAXMINOR, &li) == -1) {
504 		die("ioctl");
505 	}
506 	maxminor = li.li_minor;
507 
508 	(void) printf(FORMAT, gettext("Block Device"), gettext("File"),
509 	    gettext("Options"));
510 	for (minor = 1; minor <= maxminor; minor++) {
511 		li.li_minor = minor;
512 		if (ioctl(fd, LOFI_GET_FILENAME, &li) == -1) {
513 			if (errno == ENXIO)
514 				continue;
515 			warn("ioctl");
516 			break;
517 		}
518 		(void) snprintf(path, sizeof (path), "/dev/%s/%d",
519 		    LOFI_BLOCK_NAME, minor);
520 		/*
521 		 * Encrypted lofi and compressed lofi are mutually exclusive.
522 		 */
523 		if (li.li_crypto_enabled)
524 			(void) snprintf(options, sizeof (options),
525 			    gettext("Encrypted"));
526 		else if (li.li_algorithm[0] != '\0')
527 			(void) snprintf(options, sizeof (options),
528 			    gettext("Compressed(%s)"), li.li_algorithm);
529 		else
530 			(void) snprintf(options, sizeof (options), "-");
531 
532 		(void) printf(FORMAT, path, li.li_filename, options);
533 	}
534 }
535 
536 /*
537  * Verify the cipher selected by user.
538  */
539 static mech_alias_t *
540 ciph2mech(const char *alias)
541 {
542 	int	i;
543 
544 	for (i = 0; i < mech_aliases_count; i++) {
545 		if (strcasecmp(alias, mech_aliases[i].alias) == 0)
546 			return (&mech_aliases[i]);
547 	}
548 	return (NULL);
549 }
550 
551 /*
552  * Verify user selected cipher is also available in kernel.
553  *
554  * While traversing kernel list of mechs, if the cipher is supported in the
555  * kernel for both encryption and decryption, it also picks up the min/max
556  * key size.
557  */
558 static boolean_t
559 kernel_cipher_check(mech_alias_t *cipher)
560 {
561 	boolean_t ciph_ok = B_FALSE;
562 	boolean_t iv_ok = B_FALSE;
563 	int	i;
564 	int	count;
565 	crypto_get_mechanism_list_t *kciphers = NULL;
566 	crypto_get_all_mechanism_info_t *kinfo = NULL;
567 	int	fd = -1;
568 	size_t	keymin;
569 	size_t	keymax;
570 
571 	/* if cipher doesn't need iv generating mech, bypass that check now */
572 	if (cipher->iv_name == NULL)
573 		iv_ok = B_TRUE;
574 
575 	/* allocate some space for the list of kernel ciphers */
576 	count = DEFAULT_CIPHER_NUM;
577 	kciphers = malloc(sizeof (crypto_get_mechanism_list_t) +
578 	    sizeof (crypto_mech_name_t) * (count - 1));
579 	if (kciphers == NULL)
580 		die(gettext("failed to allocate memory for list of "
581 		    "kernel mechanisms"));
582 	kciphers->ml_count = count;
583 
584 	/* query crypto device to get list of kernel ciphers */
585 	if ((fd = open("/dev/crypto", O_RDWR)) == -1) {
586 		warn(gettext("failed to open %s"), "/dev/crypto");
587 		goto kcc_out;
588 	}
589 
590 	if (ioctl(fd, CRYPTO_GET_MECHANISM_LIST, kciphers) == -1) {
591 		warn(gettext("CRYPTO_GET_MECHANISM_LIST ioctl failed"));
592 		goto kcc_out;
593 	}
594 
595 	if (kciphers->ml_return_value == CRYPTO_BUFFER_TOO_SMALL) {
596 		count = kciphers->ml_count;
597 		free(kciphers);
598 		kciphers = malloc(sizeof (crypto_get_mechanism_list_t) +
599 		    sizeof (crypto_mech_name_t) * (count - 1));
600 		if (kciphers == NULL) {
601 			warn(gettext("failed to allocate memory for list of "
602 			    "kernel mechanisms"));
603 			goto kcc_out;
604 		}
605 		kciphers->ml_count = count;
606 
607 		if (ioctl(fd, CRYPTO_GET_MECHANISM_LIST, kciphers) == -1) {
608 			warn(gettext("CRYPTO_GET_MECHANISM_LIST ioctl failed"));
609 			goto kcc_out;
610 		}
611 	}
612 
613 	if (kciphers->ml_return_value != CRYPTO_SUCCESS) {
614 		warn(gettext(
615 		    "CRYPTO_GET_MECHANISM_LIST ioctl return value = %d\n"),
616 		    kciphers->ml_return_value);
617 		goto kcc_out;
618 	}
619 
620 	/*
621 	 * scan list of kernel ciphers looking for the selected one and if
622 	 * it needs an iv generated using another cipher, also look for that
623 	 * additional cipher to be used for generating the iv
624 	 */
625 	count = kciphers->ml_count;
626 	for (i = 0; i < count && !(ciph_ok && iv_ok); i++) {
627 		if (!ciph_ok &&
628 		    strcasecmp(cipher->name, kciphers->ml_list[i]) == 0)
629 			ciph_ok = B_TRUE;
630 		if (!iv_ok &&
631 		    strcasecmp(cipher->iv_name, kciphers->ml_list[i]) == 0)
632 			iv_ok = B_TRUE;
633 	}
634 	free(kciphers);
635 	kciphers = NULL;
636 
637 	if (!ciph_ok)
638 		warn(gettext("%s mechanism not supported in kernel\n"),
639 		    cipher->name);
640 	if (!iv_ok)
641 		warn(gettext("%s mechanism not supported in kernel\n"),
642 		    cipher->iv_name);
643 
644 	if (ciph_ok) {
645 		/* Get the details about the user selected cipher */
646 		count = DEFAULT_MECHINFO_NUM;
647 		kinfo = malloc(sizeof (crypto_get_all_mechanism_info_t) +
648 		    sizeof (crypto_mechanism_info_t) * (count - 1));
649 		if (kinfo == NULL) {
650 			warn(gettext("failed to allocate memory for "
651 			    "kernel mechanism info"));
652 			goto kcc_out;
653 		}
654 		kinfo->mi_count = count;
655 		(void) strlcpy(kinfo->mi_mechanism_name, cipher->name,
656 		    CRYPTO_MAX_MECH_NAME);
657 
658 		if (ioctl(fd, CRYPTO_GET_ALL_MECHANISM_INFO, kinfo) == -1) {
659 			warn(gettext(
660 			    "CRYPTO_GET_ALL_MECHANISM_INFO ioctl failed"));
661 			goto kcc_out;
662 		}
663 
664 		if (kinfo->mi_return_value == CRYPTO_BUFFER_TOO_SMALL) {
665 			count = kinfo->mi_count;
666 			free(kinfo);
667 			kinfo = malloc(
668 			    sizeof (crypto_get_all_mechanism_info_t) +
669 			    sizeof (crypto_mechanism_info_t) * (count - 1));
670 			if (kinfo == NULL) {
671 				warn(gettext("failed to allocate memory for "
672 				    "kernel mechanism info"));
673 				goto kcc_out;
674 			}
675 			kinfo->mi_count = count;
676 			(void) strlcpy(kinfo->mi_mechanism_name, cipher->name,
677 			    CRYPTO_MAX_MECH_NAME);
678 
679 			if (ioctl(fd, CRYPTO_GET_ALL_MECHANISM_INFO, kinfo) ==
680 			    -1) {
681 				warn(gettext("CRYPTO_GET_ALL_MECHANISM_INFO "
682 				    "ioctl failed"));
683 				goto kcc_out;
684 			}
685 		}
686 
687 		if (kinfo->mi_return_value != CRYPTO_SUCCESS) {
688 			warn(gettext("CRYPTO_GET_ALL_MECHANISM_INFO ioctl "
689 			    "return value = %d\n"), kinfo->mi_return_value);
690 			goto kcc_out;
691 		}
692 
693 		/* Set key min and max size */
694 		count = kinfo->mi_count;
695 		i = 0;
696 		if (i < count) {
697 			keymin = kinfo->mi_list[i].mi_min_key_size;
698 			keymax = kinfo->mi_list[i].mi_max_key_size;
699 			if (kinfo->mi_list[i].mi_keysize_unit &
700 			    CRYPTO_KEYSIZE_UNIT_IN_BITS) {
701 				keymin = CRYPTO_BITS2BYTES(keymin);
702 				keymax = CRYPTO_BITS2BYTES(keymax);
703 
704 			}
705 			cipher->min_keysize = keymin;
706 			cipher->max_keysize = keymax;
707 		}
708 		free(kinfo);
709 		kinfo = NULL;
710 
711 		if (i == count) {
712 			(void) close(fd);
713 			die(gettext(
714 			    "failed to find usable %s kernel mechanism, "
715 			    "use \"cryptoadm list -m\" to find available "
716 			    "mechanisms\n"),
717 			    cipher->name);
718 		}
719 	}
720 
721 	/* Note: key min/max, unit size, usage for iv cipher are not checked. */
722 
723 	return (ciph_ok && iv_ok);
724 
725 kcc_out:
726 	if (kinfo != NULL)
727 		free(kinfo);
728 	if (kciphers != NULL)
729 		free(kciphers);
730 	if (fd != -1)
731 		(void) close(fd);
732 	return (B_FALSE);
733 }
734 
735 /*
736  * Break up token spec into its components (non-destructive)
737  */
738 static token_spec_t *
739 parsetoken(char *spec)
740 {
741 #define	FLD_NAME	0
742 #define	FLD_MANUF	1
743 #define	FLD_SERIAL	2
744 #define	FLD_LABEL	3
745 #define	NFIELDS		4
746 #define	nullfield(i)	((field[(i)+1] - field[(i)]) <= 1)
747 #define	copyfield(fld, i)	\
748 		{							\
749 			int	n;					\
750 			(fld) = NULL;					\
751 			if ((n = (field[(i)+1] - field[(i)])) > 1) {	\
752 				if (((fld) = malloc(n)) != NULL) {	\
753 					(void) strncpy((fld), field[(i)], n); \
754 					((fld))[n - 1] = '\0';		\
755 				}					\
756 			}						\
757 		}
758 
759 	int	i;
760 	char	*field[NFIELDS + 1];	/* +1 to catch extra delimiters */
761 	token_spec_t *ti = NULL;
762 
763 	if (spec == NULL)
764 		return (NULL);
765 
766 	/*
767 	 * Correct format is "[name]:[manuf]:[serial]:key". Can't use
768 	 * strtok because it treats ":::key" and "key:::" and "key" all
769 	 * as the same thing, and we can't have the :s compressed away.
770 	 */
771 	field[0] = spec;
772 	for (i = 1; i < NFIELDS + 1; i++) {
773 		field[i] = strchr(field[i-1], ':');
774 		if (field[i] == NULL)
775 			break;
776 		field[i]++;
777 	}
778 	if (i < NFIELDS)		/* not enough fields */
779 		return (NULL);
780 	if (field[NFIELDS] != NULL)	/* too many fields */
781 		return (NULL);
782 	field[NFIELDS] = strchr(field[NFIELDS-1], '\0') + 1;
783 
784 	/* key label can't be empty */
785 	if (nullfield(FLD_LABEL))
786 		return (NULL);
787 
788 	ti = malloc(sizeof (token_spec_t));
789 	if (ti == NULL)
790 		return (NULL);
791 
792 	copyfield(ti->name, FLD_NAME);
793 	copyfield(ti->mfr, FLD_MANUF);
794 	copyfield(ti->serno, FLD_SERIAL);
795 	copyfield(ti->key, FLD_LABEL);
796 
797 	/*
798 	 * If token specified and it only contains a key label, then
799 	 * search all tokens for the key, otherwise only those with
800 	 * matching name, mfr, and serno are used.
801 	 */
802 	/*
803 	 * That's how we'd like it to be, however, if only the key label
804 	 * is specified, default to using softtoken.  It's easier.
805 	 */
806 	if (ti->name == NULL && ti->mfr == NULL && ti->serno == NULL)
807 		ti->name = strdup(pkcs11_default_token());
808 	return (ti);
809 }
810 
811 /*
812  * PBE the passphrase into a raw key
813  */
814 static void
815 getkeyfromuser(mech_alias_t *cipher, char **raw_key, size_t *raw_key_sz)
816 {
817 	CK_SESSION_HANDLE sess;
818 	CK_RV	rv;
819 	char	*pass = NULL;
820 	size_t	passlen = 0;
821 	void	*salt = NULL;	/* don't use NULL, see note on salt below */
822 	size_t	saltlen = 0;
823 	CK_KEY_TYPE ktype;
824 	void	*kvalue;
825 	size_t	klen;
826 
827 	/* did init_crypto find a slot that supports this cipher? */
828 	if (cipher->slot == (CK_SLOT_ID)-1 || cipher->max_keysize == 0) {
829 		rv = CKR_MECHANISM_INVALID;
830 		goto cleanup;
831 	}
832 
833 	rv = pkcs11_mech2keytype(cipher->type, &ktype);
834 	if (rv != CKR_OK)
835 		goto cleanup;
836 
837 	/*
838 	 * use the passphrase to generate a PBE PKCS#5 secret key and
839 	 * retrieve the raw key data to eventually pass it to the kernel;
840 	 */
841 	rv = C_OpenSession(cipher->slot, CKF_SERIAL_SESSION, NULL, NULL, &sess);
842 	if (rv != CKR_OK)
843 		goto cleanup;
844 
845 	/* get user passphrase with 8 byte minimum */
846 	if (pkcs11_get_pass(NULL, &pass, &passlen, MIN_PASSLEN, B_TRUE) < 0) {
847 		die(gettext("passphrases do not match\n"));
848 	}
849 
850 	/*
851 	 * salt should not be NULL, or else pkcs11_PasswdToKey() will
852 	 * complain about CKR_MECHANISM_PARAM_INVALID; the following is
853 	 * to make up for not having a salt until a proper one is used
854 	 */
855 	salt = pass;
856 	saltlen = passlen;
857 
858 	klen = cipher->max_keysize;
859 	rv = pkcs11_PasswdToKey(sess, pass, passlen, salt, saltlen, ktype,
860 	    cipher->max_keysize, &kvalue, &klen);
861 
862 	(void) C_CloseSession(sess);
863 
864 	if (rv != CKR_OK) {
865 		goto cleanup;
866 	}
867 
868 	/* assert(klen == cipher->max_keysize); */
869 	*raw_key_sz = klen;
870 	*raw_key = (char *)kvalue;
871 	return;
872 
873 cleanup:
874 	die(gettext("failed to generate %s key from passphrase: %s"),
875 	    cipher->alias, pkcs11_strerror(rv));
876 }
877 
878 /*
879  * Read raw key from file; also handles ephemeral keys.
880  */
881 void
882 getkeyfromfile(const char *pathname, mech_alias_t *cipher, char **key,
883     size_t *ksz)
884 {
885 	int	fd;
886 	struct stat sbuf;
887 	boolean_t notplain = B_FALSE;
888 	ssize_t	cursz;
889 	ssize_t	nread;
890 
891 	/* ephemeral keys are just random data */
892 	if (pathname == NULL) {
893 		*ksz = cipher->max_keysize;
894 		*key = malloc(*ksz);
895 		if (*key == NULL)
896 			die(gettext("failed to allocate memory for"
897 			    " ephemeral key"));
898 		if (pkcs11_get_urandom(*key, *ksz) < 0) {
899 			free(*key);
900 			die(gettext("failed to get enough random data"));
901 		}
902 		return;
903 	}
904 
905 	/*
906 	 * If the remaining section of code didn't also check for secure keyfile
907 	 * permissions and whether the key is within cipher min and max lengths,
908 	 * (or, if those things moved out of this block), we could have had:
909 	 *	if (pkcs11_read_data(pathname, key, ksz) < 0)
910 	 *		handle_error();
911 	 */
912 
913 	if ((fd = open(pathname, O_RDONLY, 0)) == -1)
914 		die(gettext("open of keyfile (%s) failed"), pathname);
915 
916 	if (fstat(fd, &sbuf) == -1)
917 		die(gettext("fstat of keyfile (%s) failed"), pathname);
918 
919 	if (S_ISREG(sbuf.st_mode)) {
920 		if ((sbuf.st_mode & (S_IWGRP | S_IWOTH)) != 0)
921 			die(gettext("insecure permissions on keyfile %s\n"),
922 			    pathname);
923 
924 		*ksz = sbuf.st_size;
925 		if (*ksz < cipher->min_keysize || cipher->max_keysize < *ksz) {
926 			warn(gettext("%s: invalid keysize: %d\n"),
927 			    pathname, (int)*ksz);
928 			die(gettext("\t%d <= keysize <= %d\n"),
929 			    cipher->min_keysize, cipher->max_keysize);
930 		}
931 	} else {
932 		*ksz = cipher->max_keysize;
933 		notplain = B_TRUE;
934 	}
935 
936 	*key = malloc(*ksz);
937 	if (*key == NULL)
938 		die(gettext("failed to allocate memory for key from file"));
939 
940 	for (cursz = 0, nread = 0; cursz < *ksz; cursz += nread) {
941 		nread = read(fd, *key, *ksz);
942 		if (nread > 0)
943 			continue;
944 		/*
945 		 * nread == 0.  If it's not a regular file we were trying to
946 		 * get the maximum keysize of data possible for this cipher.
947 		 * But if we've got at least the minimum keysize of data,
948 		 * round down to the nearest keysize unit and call it good.
949 		 * If we haven't met the minimum keysize, that's an error.
950 		 * If it's a regular file, nread = 0 is also an error.
951 		 */
952 		if (nread == 0 && notplain && cursz >= cipher->min_keysize) {
953 			*ksz = (cursz / cipher->min_keysize) *
954 			    cipher->min_keysize;
955 			break;
956 		}
957 		die(gettext("%s: can't read all keybytes"), pathname);
958 	}
959 	(void) close(fd);
960 }
961 
962 /*
963  * Read the raw key from token, or from a file that was wrapped with a
964  * key from token
965  */
966 void
967 getkeyfromtoken(CK_SESSION_HANDLE sess,
968     token_spec_t *token, const char *keyfile, mech_alias_t *cipher,
969     char **raw_key, size_t *raw_key_sz)
970 {
971 	CK_RV	rv = CKR_OK;
972 	CK_BBOOL trueval = B_TRUE;
973 	CK_OBJECT_CLASS kclass;		/* secret key or RSA private key */
974 	CK_KEY_TYPE ktype;		/* from selected cipher or CKK_RSA */
975 	CK_KEY_TYPE raw_ktype;		/* from selected cipher */
976 	CK_ATTRIBUTE	key_tmpl[] = {
977 		{ CKA_CLASS, NULL, 0 },	/* re-used for token key and unwrap */
978 		{ CKA_KEY_TYPE, NULL, 0 },	/* ditto */
979 		{ CKA_LABEL, NULL, 0 },
980 		{ CKA_TOKEN, NULL, 0 },
981 		{ CKA_PRIVATE, NULL, 0 }
982 	    };
983 	CK_ULONG attrs = sizeof (key_tmpl) / sizeof (CK_ATTRIBUTE);
984 	int	i;
985 	char	*pass = NULL;
986 	size_t	passlen = 0;
987 	CK_OBJECT_HANDLE obj, rawobj;
988 	CK_ULONG num_objs = 1;		/* just want to find 1 token key */
989 	CK_MECHANISM unwrap = { CKM_RSA_PKCS, NULL, 0 };
990 	char	*rkey;
991 	size_t	rksz;
992 
993 	if (token == NULL || token->key == NULL)
994 		return;
995 
996 	/* did init_crypto find a slot that supports this cipher? */
997 	if (cipher->slot == (CK_SLOT_ID)-1 || cipher->max_keysize == 0) {
998 		die(gettext("failed to find any cryptographic provider, "
999 		    "use \"cryptoadm list -p\" to find providers: %s\n"),
1000 		    pkcs11_strerror(CKR_MECHANISM_INVALID));
1001 	}
1002 
1003 	if (pkcs11_get_pass(token->name, &pass, &passlen, 0, B_FALSE) < 0)
1004 		die(gettext("unable to get passphrase"));
1005 
1006 	/* use passphrase to login to token */
1007 	if (pass != NULL && passlen > 0) {
1008 		rv = C_Login(sess, CKU_USER, (CK_UTF8CHAR_PTR)pass, passlen);
1009 		if (rv != CKR_OK) {
1010 			die(gettext("cannot login to the token %s: %s\n"),
1011 			    token->name, pkcs11_strerror(rv));
1012 		}
1013 	}
1014 
1015 	rv = pkcs11_mech2keytype(cipher->type, &raw_ktype);
1016 	if (rv != CKR_OK) {
1017 		die(gettext("failed to get key type for cipher %s: %s\n"),
1018 		    cipher->name, pkcs11_strerror(rv));
1019 	}
1020 
1021 	/*
1022 	 * If no keyfile was given, then the token key is secret key to
1023 	 * be used for encryption/decryption.  Otherwise, the keyfile
1024 	 * contains a wrapped secret key, and the token is actually the
1025 	 * unwrapping RSA private key.
1026 	 */
1027 	if (keyfile == NULL) {
1028 		kclass = CKO_SECRET_KEY;
1029 		ktype = raw_ktype;
1030 	} else {
1031 		kclass = CKO_PRIVATE_KEY;
1032 		ktype = CKK_RSA;
1033 	}
1034 
1035 	/* Find the key in the token first */
1036 	for (i = 0; i < attrs; i++) {
1037 		switch (key_tmpl[i].type) {
1038 		case CKA_CLASS:
1039 			key_tmpl[i].pValue = &kclass;
1040 			key_tmpl[i].ulValueLen = sizeof (kclass);
1041 			break;
1042 		case CKA_KEY_TYPE:
1043 			key_tmpl[i].pValue = &ktype;
1044 			key_tmpl[i].ulValueLen = sizeof (ktype);
1045 			break;
1046 		case CKA_LABEL:
1047 			key_tmpl[i].pValue = token->key;
1048 			key_tmpl[i].ulValueLen = strlen(token->key);
1049 			break;
1050 		case CKA_TOKEN:
1051 			key_tmpl[i].pValue = &trueval;
1052 			key_tmpl[i].ulValueLen = sizeof (trueval);
1053 			break;
1054 		case CKA_PRIVATE:
1055 			key_tmpl[i].pValue = &trueval;
1056 			key_tmpl[i].ulValueLen = sizeof (trueval);
1057 			break;
1058 		default:
1059 			break;
1060 		}
1061 	}
1062 	rv = C_FindObjectsInit(sess, key_tmpl, attrs);
1063 	if (rv != CKR_OK)
1064 		die(gettext("cannot find key %s: %s\n"), token->key,
1065 		    pkcs11_strerror(rv));
1066 	rv = C_FindObjects(sess, &obj, 1, &num_objs);
1067 	(void) C_FindObjectsFinal(sess);
1068 
1069 	if (num_objs == 0) {
1070 		die(gettext("cannot find key %s\n"), token->key);
1071 	} else if (rv != CKR_OK) {
1072 		die(gettext("cannot find key %s: %s\n"), token->key,
1073 		    pkcs11_strerror(rv));
1074 	}
1075 
1076 	/*
1077 	 * No keyfile means when token key is found, convert it to raw key,
1078 	 * and done.  Otherwise still need do an unwrap to create yet another
1079 	 * obj and that needs to be converted to raw key before we're done.
1080 	 */
1081 	if (keyfile == NULL) {
1082 		/* obj contains raw key, extract it */
1083 		rv = pkcs11_ObjectToKey(sess, obj, (void **)&rkey, &rksz,
1084 		    B_FALSE);
1085 		if (rv != CKR_OK) {
1086 			die(gettext("failed to get key value for %s"
1087 			    " from token %s, %s\n"), token->key,
1088 			    token->name, pkcs11_strerror(rv));
1089 		}
1090 	} else {
1091 		getkeyfromfile(keyfile, cipher, &rkey, &rksz);
1092 
1093 		/*
1094 		 * Got the wrapping RSA obj and the wrapped key from file.
1095 		 * Unwrap the key from file with RSA obj to get rawkey obj.
1096 		 */
1097 
1098 		/* re-use the first two attributes of key_tmpl */
1099 		kclass = CKO_SECRET_KEY;
1100 		ktype = raw_ktype;
1101 
1102 		rv = C_UnwrapKey(sess, &unwrap, obj, (CK_BYTE_PTR)rkey,
1103 		    rksz, key_tmpl, 2, &rawobj);
1104 		if (rv != CKR_OK) {
1105 			die(gettext("failed to unwrap key in keyfile %s,"
1106 			    " %s\n"), keyfile, pkcs11_strerror(rv));
1107 		}
1108 		/* rawobj contains raw key, extract it */
1109 		rv = pkcs11_ObjectToKey(sess, rawobj, (void **)&rkey, &rksz,
1110 		    B_TRUE);
1111 		if (rv != CKR_OK) {
1112 			die(gettext("failed to get unwrapped key value for"
1113 			    " key in keyfile %s, %s\n"), keyfile,
1114 			    pkcs11_strerror(rv));
1115 		}
1116 	}
1117 
1118 	/* validate raw key size */
1119 	if (rksz < cipher->min_keysize || cipher->max_keysize < rksz) {
1120 		warn(gettext("%s: invalid keysize: %d\n"), keyfile, (int)rksz);
1121 		die(gettext("\t%d <= keysize <= %d\n"), cipher->min_keysize,
1122 		    cipher->max_keysize);
1123 	}
1124 
1125 	*raw_key_sz = rksz;
1126 	*raw_key = (char *)rkey;
1127 }
1128 
1129 /*
1130  * Set up cipher key limits and verify PKCS#11 can be done
1131  * match_token_cipher is the function pointer used by
1132  * pkcs11_GetCriteriaSession() init_crypto.
1133  */
1134 boolean_t
1135 match_token_cipher(CK_SLOT_ID slot_id, void *args, CK_RV *rv)
1136 {
1137 	token_spec_t *token;
1138 	mech_alias_t *cipher;
1139 	CK_TOKEN_INFO tokinfo;
1140 	CK_MECHANISM_INFO mechinfo;
1141 	boolean_t token_match;
1142 
1143 	/*
1144 	 * While traversing slot list, pick up the following info per slot:
1145 	 * - if token specified, whether it matches this slot's token info
1146 	 * - if the slot supports the PKCS#5 PBKD2 cipher
1147 	 *
1148 	 * If the user said on the command line
1149 	 *	-T tok:mfr:ser:lab -k keyfile
1150 	 *	-c cipher -T tok:mfr:ser:lab -k keyfile
1151 	 * the given cipher or the default cipher apply to keyfile,
1152 	 * If the user said instead
1153 	 *	-T tok:mfr:ser:lab
1154 	 *	-c cipher -T tok:mfr:ser:lab
1155 	 * the key named "lab" may or may not agree with the given
1156 	 * cipher or the default cipher.  In those cases, cipher will
1157 	 * be overridden with the actual cipher type of the key "lab".
1158 	 */
1159 	*rv = CKR_FUNCTION_FAILED;
1160 
1161 	if (args == NULL) {
1162 		return (B_FALSE);
1163 	}
1164 
1165 	cipher = (mech_alias_t *)args;
1166 	token = cipher->token;
1167 
1168 	if (C_GetMechanismInfo(slot_id, cipher->type, &mechinfo) != CKR_OK) {
1169 		return (B_FALSE);
1170 	}
1171 
1172 	if (token == NULL) {
1173 		if (C_GetMechanismInfo(slot_id, CKM_PKCS5_PBKD2, &mechinfo) !=
1174 		    CKR_OK) {
1175 			return (B_FALSE);
1176 		}
1177 		goto foundit;
1178 	}
1179 
1180 	/* does the token match the token spec? */
1181 	if (token->key == NULL || (C_GetTokenInfo(slot_id, &tokinfo) != CKR_OK))
1182 		return (B_FALSE);
1183 
1184 	token_match = B_TRUE;
1185 
1186 	if (token->name != NULL && (token->name)[0] != '\0' &&
1187 	    strncmp((char *)token->name, (char *)tokinfo.label,
1188 	    TOKEN_LABEL_SIZE) != 0)
1189 		token_match = B_FALSE;
1190 	if (token->mfr != NULL && (token->mfr)[0] != '\0' &&
1191 	    strncmp((char *)token->mfr, (char *)tokinfo.manufacturerID,
1192 	    TOKEN_MANUFACTURER_SIZE) != 0)
1193 		token_match = B_FALSE;
1194 	if (token->serno != NULL && (token->serno)[0] != '\0' &&
1195 	    strncmp((char *)token->serno, (char *)tokinfo.serialNumber,
1196 	    TOKEN_SERIAL_SIZE) != 0)
1197 		token_match = B_FALSE;
1198 
1199 	if (!token_match)
1200 		return (B_FALSE);
1201 
1202 foundit:
1203 	cipher->slot = slot_id;
1204 	return (B_TRUE);
1205 }
1206 
1207 /*
1208  * Clean up crypto loose ends
1209  */
1210 static void
1211 end_crypto(CK_SESSION_HANDLE sess)
1212 {
1213 	(void) C_CloseSession(sess);
1214 	(void) C_Finalize(NULL);
1215 }
1216 
1217 /*
1218  * Set up crypto, opening session on slot that matches token and cipher
1219  */
1220 static void
1221 init_crypto(token_spec_t *token, mech_alias_t *cipher,
1222     CK_SESSION_HANDLE_PTR sess)
1223 {
1224 	CK_RV	rv;
1225 
1226 	cipher->token = token;
1227 
1228 	/* Turn off Metaslot so that we can see actual tokens */
1229 	if (setenv("METASLOT_ENABLED", "false", 1) < 0) {
1230 		die(gettext("could not disable Metaslot"));
1231 	}
1232 
1233 	rv = pkcs11_GetCriteriaSession(match_token_cipher, (void *)cipher,
1234 	    sess);
1235 	if (rv != CKR_OK) {
1236 		end_crypto(*sess);
1237 		if (rv == CKR_HOST_MEMORY) {
1238 			die("malloc");
1239 		}
1240 		die(gettext("failed to find any cryptographic provider, "
1241 		    "use \"cryptoadm list -p\" to find providers: %s\n"),
1242 		    pkcs11_strerror(rv));
1243 	}
1244 }
1245 
1246 /*
1247  * Uncompress a file.
1248  *
1249  * First map the file in to establish a device
1250  * association, then read from it. On-the-fly
1251  * decompression will automatically uncompress
1252  * the file if it's compressed
1253  *
1254  * If the file is mapped and a device association
1255  * has been established, disallow uncompressing
1256  * the file until it is unmapped.
1257  */
1258 static void
1259 lofi_uncompress(int lfd, const char *filename)
1260 {
1261 	struct lofi_ioctl li;
1262 	char buf[MAXBSIZE];
1263 	char devicename[32];
1264 	char tmpfilename[MAXPATHLEN];
1265 	char *x;
1266 	char *dir = NULL;
1267 	char *file = NULL;
1268 	int minor = 0;
1269 	struct stat64 statbuf;
1270 	int compfd = -1;
1271 	int uncompfd = -1;
1272 	ssize_t rbytes;
1273 
1274 	/*
1275 	 * Disallow uncompressing the file if it is
1276 	 * already mapped.
1277 	 */
1278 	li.li_crypto_enabled = B_FALSE;
1279 	li.li_minor = 0;
1280 	(void) strlcpy(li.li_filename, filename, sizeof (li.li_filename));
1281 	if (ioctl(lfd, LOFI_GET_MINOR, &li) != -1)
1282 		die(gettext("%s must be unmapped before uncompressing"),
1283 		    filename);
1284 
1285 	/* Zero length files don't need to be uncompressed */
1286 	if (stat64(filename, &statbuf) == -1)
1287 		die(gettext("stat: %s"), filename);
1288 	if (statbuf.st_size == 0)
1289 		return;
1290 
1291 	minor = lofi_map_file(lfd, li, filename);
1292 	(void) snprintf(devicename, sizeof (devicename), "/dev/%s/%d",
1293 	    LOFI_BLOCK_NAME, minor);
1294 
1295 	/* If the file isn't compressed, we just return */
1296 	if ((ioctl(lfd, LOFI_CHECK_COMPRESSED, &li) == -1) ||
1297 	    (li.li_algorithm[0] == '\0')) {
1298 		delete_mapping(lfd, devicename, filename, B_TRUE);
1299 		die("%s is not compressed\n", filename);
1300 	}
1301 
1302 	if ((compfd = open64(devicename, O_RDONLY | O_NONBLOCK)) == -1) {
1303 		delete_mapping(lfd, devicename, filename, B_TRUE);
1304 		die(gettext("open: %s"), filename);
1305 	}
1306 	/* Create a temp file in the same directory */
1307 	x = strdup(filename);
1308 	dir = strdup(dirname(x));
1309 	free(x);
1310 	x = strdup(filename);
1311 	file = strdup(basename(x));
1312 	free(x);
1313 	(void) snprintf(tmpfilename, sizeof (tmpfilename),
1314 	    "%s/.%sXXXXXX", dir, file);
1315 	free(dir);
1316 	free(file);
1317 
1318 	if ((uncompfd = mkstemp64(tmpfilename)) == -1) {
1319 		(void) close(compfd);
1320 		delete_mapping(lfd, devicename, filename, B_TRUE);
1321 		die("%s could not be uncompressed\n", filename);
1322 	}
1323 
1324 	/*
1325 	 * Set the mode bits and the owner of this temporary
1326 	 * file to be that of the original uncompressed file
1327 	 */
1328 	(void) fchmod(uncompfd, statbuf.st_mode);
1329 
1330 	if (fchown(uncompfd, statbuf.st_uid, statbuf.st_gid) == -1) {
1331 		(void) close(compfd);
1332 		(void) close(uncompfd);
1333 		delete_mapping(lfd, devicename, filename, B_TRUE);
1334 		die("%s could not be uncompressed\n", filename);
1335 	}
1336 
1337 	/* Now read from the device in MAXBSIZE-sized chunks */
1338 	for (;;) {
1339 		rbytes = read(compfd, buf, sizeof (buf));
1340 
1341 		if (rbytes <= 0)
1342 			break;
1343 
1344 		if (write(uncompfd, buf, rbytes) != rbytes) {
1345 			rbytes = -1;
1346 			break;
1347 		}
1348 	}
1349 
1350 	(void) close(compfd);
1351 	(void) close(uncompfd);
1352 
1353 	/* Delete the mapping */
1354 	delete_mapping(lfd, devicename, filename, B_TRUE);
1355 
1356 	/*
1357 	 * If an error occured while reading or writing, rbytes will
1358 	 * be negative
1359 	 */
1360 	if (rbytes < 0) {
1361 		(void) unlink(tmpfilename);
1362 		die(gettext("could not read from %s"), filename);
1363 	}
1364 
1365 	/* Rename the temp file to the actual file */
1366 	if (rename(tmpfilename, filename) == -1)
1367 		(void) unlink(tmpfilename);
1368 }
1369 
1370 /*
1371  * Compress a file
1372  */
1373 static void
1374 lofi_compress(int *lfd, const char *filename, int compress_index,
1375     uint32_t segsize)
1376 {
1377 	struct lofi_ioctl lic;
1378 	lofi_compress_info_t *li;
1379 	struct flock lock;
1380 	char tmpfilename[MAXPATHLEN];
1381 	char comp_filename[MAXPATHLEN];
1382 	char algorithm[MAXALGLEN];
1383 	char *x;
1384 	char *dir = NULL, *file = NULL;
1385 	uchar_t *uncompressed_seg = NULL;
1386 	uchar_t *compressed_seg = NULL;
1387 	uint32_t compressed_segsize;
1388 	uint32_t len_compressed, count;
1389 	uint32_t index_entries, index_sz;
1390 	uint64_t *index = NULL;
1391 	uint64_t offset;
1392 	size_t real_segsize;
1393 	struct stat64 statbuf;
1394 	int compfd = -1, uncompfd = -1;
1395 	int tfd = -1;
1396 	ssize_t rbytes, wbytes, lastread;
1397 	int i, type;
1398 
1399 	/*
1400 	 * Disallow compressing the file if it is
1401 	 * already mapped
1402 	 */
1403 	lic.li_minor = 0;
1404 	(void) strlcpy(lic.li_filename, filename, sizeof (lic.li_filename));
1405 	if (ioctl(*lfd, LOFI_GET_MINOR, &lic) != -1)
1406 		die(gettext("%s must be unmapped before compressing"),
1407 		    filename);
1408 
1409 	/*
1410 	 * Close the control device so other operations
1411 	 * can use it
1412 	 */
1413 	(void) close(*lfd);
1414 	*lfd = -1;
1415 
1416 	li = &lofi_compress_table[compress_index];
1417 
1418 	/*
1419 	 * The size of the buffer to hold compressed data must
1420 	 * be slightly larger than the compressed segment size.
1421 	 *
1422 	 * The compress functions use part of the buffer as
1423 	 * scratch space to do calculations.
1424 	 * Ref: http://www.zlib.net/manual.html#compress2
1425 	 */
1426 	compressed_segsize = segsize + (segsize >> 6);
1427 	compressed_seg = (uchar_t *)malloc(compressed_segsize + SEGHDR);
1428 	uncompressed_seg = (uchar_t *)malloc(segsize);
1429 
1430 	if (compressed_seg == NULL || uncompressed_seg == NULL)
1431 		die(gettext("No memory"));
1432 
1433 	if ((uncompfd = open64(filename, O_RDWR|O_LARGEFILE, 0)) == -1)
1434 		die(gettext("open: %s"), filename);
1435 
1436 	lock.l_type = F_WRLCK;
1437 	lock.l_whence = SEEK_SET;
1438 	lock.l_start = 0;
1439 	lock.l_len = 0;
1440 
1441 	/*
1442 	 * Use an advisory lock to ensure that only a
1443 	 * single lofiadm process compresses a given
1444 	 * file at any given time
1445 	 *
1446 	 * A close on the file descriptor automatically
1447 	 * closes all lock state on the file
1448 	 */
1449 	if (fcntl(uncompfd, F_SETLKW, &lock) == -1)
1450 		die(gettext("fcntl: %s"), filename);
1451 
1452 	if (fstat64(uncompfd, &statbuf) == -1) {
1453 		(void) close(uncompfd);
1454 		die(gettext("fstat: %s"), filename);
1455 	}
1456 
1457 	/* Zero length files don't need to be compressed */
1458 	if (statbuf.st_size == 0) {
1459 		(void) close(uncompfd);
1460 		return;
1461 	}
1462 
1463 	/*
1464 	 * Create temporary files in the same directory that
1465 	 * will hold the intermediate data
1466 	 */
1467 	x = strdup(filename);
1468 	dir = strdup(dirname(x));
1469 	free(x);
1470 	x = strdup(filename);
1471 	file = strdup(basename(x));
1472 	free(x);
1473 	(void) snprintf(tmpfilename, sizeof (tmpfilename),
1474 	    "%s/.%sXXXXXX", dir, file);
1475 	(void) snprintf(comp_filename, sizeof (comp_filename),
1476 	    "%s/.%sXXXXXX", dir, file);
1477 	free(dir);
1478 	free(file);
1479 
1480 	if ((tfd = mkstemp64(tmpfilename)) == -1)
1481 		goto cleanup;
1482 
1483 	if ((compfd = mkstemp64(comp_filename)) == -1)
1484 		goto cleanup;
1485 
1486 	/*
1487 	 * Set the mode bits and owner of the compressed
1488 	 * file to be that of the original uncompressed file
1489 	 */
1490 	(void) fchmod(compfd, statbuf.st_mode);
1491 
1492 	if (fchown(compfd, statbuf.st_uid, statbuf.st_gid) == -1)
1493 		goto cleanup;
1494 
1495 	/*
1496 	 * Calculate the number of index entries required.
1497 	 * index entries are stored as an array. adding
1498 	 * a '2' here accounts for the fact that the last
1499 	 * segment may not be a multiple of the segment size
1500 	 */
1501 	index_sz = (statbuf.st_size / segsize) + 2;
1502 	index = malloc(sizeof (*index) * index_sz);
1503 
1504 	if (index == NULL)
1505 		goto cleanup;
1506 
1507 	offset = 0;
1508 	lastread = segsize;
1509 	count = 0;
1510 
1511 	/*
1512 	 * Now read from the uncompressed file in 'segsize'
1513 	 * sized chunks, compress what was read in and
1514 	 * write it out to a temporary file
1515 	 */
1516 	for (;;) {
1517 		rbytes = read(uncompfd, uncompressed_seg, segsize);
1518 
1519 		if (rbytes <= 0)
1520 			break;
1521 
1522 		if (lastread < segsize)
1523 			goto cleanup;
1524 
1525 		/*
1526 		 * Account for the first byte that
1527 		 * indicates whether a segment is
1528 		 * compressed or not
1529 		 */
1530 		real_segsize = segsize - 1;
1531 		(void) li->l_compress(uncompressed_seg, rbytes,
1532 		    compressed_seg + SEGHDR, &real_segsize, li->l_level);
1533 
1534 		/*
1535 		 * If the length of the compressed data is more
1536 		 * than a threshold then there isn't any benefit
1537 		 * to be had from compressing this segment - leave
1538 		 * it uncompressed.
1539 		 *
1540 		 * NB. In case an error occurs during compression (above)
1541 		 * the 'real_segsize' isn't changed. The logic below
1542 		 * ensures that that segment is left uncompressed.
1543 		 */
1544 		len_compressed = real_segsize;
1545 		if (segsize <= COMPRESS_THRESHOLD ||
1546 		    real_segsize > (segsize - COMPRESS_THRESHOLD)) {
1547 			(void) memcpy(compressed_seg + SEGHDR, uncompressed_seg,
1548 			    rbytes);
1549 			type = UNCOMPRESSED;
1550 			len_compressed = rbytes;
1551 		} else {
1552 			type = COMPRESSED;
1553 		}
1554 
1555 		/*
1556 		 * Set the first byte or the SEGHDR to
1557 		 * indicate if it's compressed or not
1558 		 */
1559 		*compressed_seg = type;
1560 		wbytes = write(tfd, compressed_seg, len_compressed + SEGHDR);
1561 		if (wbytes != (len_compressed + SEGHDR)) {
1562 			rbytes = -1;
1563 			break;
1564 		}
1565 
1566 		index[count] = BE_64(offset);
1567 		offset += wbytes;
1568 		lastread = rbytes;
1569 		count++;
1570 	}
1571 
1572 	(void) close(uncompfd);
1573 
1574 	if (rbytes < 0)
1575 		goto cleanup;
1576 	/*
1577 	 * The last index entry is a sentinel entry. It does not point to
1578 	 * an actual compressed segment but helps in computing the size of
1579 	 * the compressed segment. The size of each compressed segment is
1580 	 * computed by subtracting the current index value from the next
1581 	 * one (the compressed blocks are stored sequentially)
1582 	 */
1583 	index[count++] = BE_64(offset);
1584 
1585 	/*
1586 	 * Now write the compressed data along with the
1587 	 * header information to this file which will
1588 	 * later be renamed to the original uncompressed
1589 	 * file name
1590 	 *
1591 	 * The header is as follows -
1592 	 *
1593 	 * Signature (name of the compression algorithm)
1594 	 * Compression segment size (a multiple of 512)
1595 	 * Number of index entries
1596 	 * Size of the last block
1597 	 * The array containing the index entries
1598 	 *
1599 	 * the header is always stored in network byte
1600 	 * order
1601 	 */
1602 	(void) bzero(algorithm, sizeof (algorithm));
1603 	(void) strlcpy(algorithm, li->l_name, sizeof (algorithm));
1604 	if (write(compfd, algorithm, sizeof (algorithm))
1605 	    != sizeof (algorithm))
1606 		goto cleanup;
1607 
1608 	segsize = htonl(segsize);
1609 	if (write(compfd, &segsize, sizeof (segsize)) != sizeof (segsize))
1610 		goto cleanup;
1611 
1612 	index_entries = htonl(count);
1613 	if (write(compfd, &index_entries, sizeof (index_entries)) !=
1614 	    sizeof (index_entries))
1615 		goto cleanup;
1616 
1617 	lastread = htonl(lastread);
1618 	if (write(compfd, &lastread, sizeof (lastread)) != sizeof (lastread))
1619 		goto cleanup;
1620 
1621 	for (i = 0; i < count; i++) {
1622 		if (write(compfd, index + i, sizeof (*index)) !=
1623 		    sizeof (*index))
1624 			goto cleanup;
1625 	}
1626 
1627 	/* Header is written, now write the compressed data */
1628 	if (lseek(tfd, 0, SEEK_SET) != 0)
1629 		goto cleanup;
1630 
1631 	rbytes = wbytes = 0;
1632 
1633 	for (;;) {
1634 		rbytes = read(tfd, compressed_seg, compressed_segsize + SEGHDR);
1635 
1636 		if (rbytes <= 0)
1637 			break;
1638 
1639 		if (write(compfd, compressed_seg, rbytes) != rbytes)
1640 			goto cleanup;
1641 	}
1642 
1643 	if (fstat64(compfd, &statbuf) == -1)
1644 		goto cleanup;
1645 
1646 	/*
1647 	 * Round up the compressed file size to be a multiple of
1648 	 * DEV_BSIZE. lofi(7D) likes it that way.
1649 	 */
1650 	if ((offset = statbuf.st_size % DEV_BSIZE) > 0) {
1651 
1652 		offset = DEV_BSIZE - offset;
1653 
1654 		for (i = 0; i < offset; i++)
1655 			uncompressed_seg[i] = '\0';
1656 		if (write(compfd, uncompressed_seg, offset) != offset)
1657 			goto cleanup;
1658 	}
1659 	(void) close(compfd);
1660 	(void) close(tfd);
1661 	(void) unlink(tmpfilename);
1662 cleanup:
1663 	if (rbytes < 0) {
1664 		if (tfd != -1)
1665 			(void) unlink(tmpfilename);
1666 		if (compfd != -1)
1667 			(void) unlink(comp_filename);
1668 		die(gettext("error compressing file %s"), filename);
1669 	} else {
1670 		/* Rename the compressed file to the actual file */
1671 		if (rename(comp_filename, filename) == -1) {
1672 			(void) unlink(comp_filename);
1673 			die(gettext("error compressing file %s"), filename);
1674 		}
1675 	}
1676 	if (compressed_seg != NULL)
1677 		free(compressed_seg);
1678 	if (uncompressed_seg != NULL)
1679 		free(uncompressed_seg);
1680 	if (index != NULL)
1681 		free(index);
1682 	if (compfd != -1)
1683 		(void) close(compfd);
1684 	if (uncompfd != -1)
1685 		(void) close(uncompfd);
1686 	if (tfd != -1)
1687 		(void) close(tfd);
1688 }
1689 
1690 static int
1691 lofi_compress_select(const char *algname)
1692 {
1693 	int i;
1694 
1695 	for (i = 0; i < LOFI_COMPRESS_FUNCTIONS; i++) {
1696 		if (strcmp(lofi_compress_table[i].l_name, algname) == 0)
1697 			return (i);
1698 	}
1699 	return (-1);
1700 }
1701 
1702 static void
1703 check_algorithm_validity(const char *algname, int *compress_index)
1704 {
1705 	*compress_index = lofi_compress_select(algname);
1706 	if (*compress_index < 0)
1707 		die(gettext("invalid algorithm name: %s\n"), algname);
1708 }
1709 
1710 static void
1711 check_file_validity(const char *filename)
1712 {
1713 	struct stat64 buf;
1714 	int 	error;
1715 	int	fd;
1716 
1717 	fd = open64(filename, O_RDONLY);
1718 	if (fd == -1) {
1719 		die(gettext("open: %s"), filename);
1720 	}
1721 	error = fstat64(fd, &buf);
1722 	if (error == -1) {
1723 		die(gettext("fstat: %s"), filename);
1724 	} else if (!S_ISLOFIABLE(buf.st_mode)) {
1725 		die(gettext("%s is not a regular file, "
1726 		    "block, or character device\n"),
1727 		    filename);
1728 	} else if ((buf.st_size % DEV_BSIZE) != 0) {
1729 		die(gettext("size of %s is not a multiple of %d\n"),
1730 		    filename, DEV_BSIZE);
1731 	}
1732 	(void) close(fd);
1733 
1734 	if (name_to_minor(filename) != 0) {
1735 		die(gettext("cannot use %s on itself\n"), LOFI_DRIVER_NAME);
1736 	}
1737 }
1738 
1739 static uint32_t
1740 convert_to_num(const char *str)
1741 {
1742 	int len;
1743 	uint32_t segsize, mult = 1;
1744 
1745 	len = strlen(str);
1746 	if (len && isalpha(str[len - 1])) {
1747 		switch (str[len - 1]) {
1748 		case 'k':
1749 		case 'K':
1750 			mult = KILOBYTE;
1751 			break;
1752 		case 'b':
1753 		case 'B':
1754 			mult = BLOCK_SIZE;
1755 			break;
1756 		case 'm':
1757 		case 'M':
1758 			mult = MEGABYTE;
1759 			break;
1760 		case 'g':
1761 		case 'G':
1762 			mult = GIGABYTE;
1763 			break;
1764 		default:
1765 			die(gettext("invalid segment size %s\n"), str);
1766 		}
1767 	}
1768 
1769 	segsize = atol(str);
1770 	segsize *= mult;
1771 
1772 	return (segsize);
1773 }
1774 
1775 int
1776 main(int argc, char *argv[])
1777 {
1778 	int	lfd;
1779 	int	c;
1780 	const char *devicename = NULL;
1781 	const char *filename = NULL;
1782 	const char *algname = COMPRESS_ALGORITHM;
1783 	int	openflag;
1784 	int	minor;
1785 	int 	compress_index;
1786 	uint32_t segsize = SEGSIZE;
1787 	static char *lofictl = "/dev/" LOFI_CTL_NAME;
1788 	boolean_t force = B_FALSE;
1789 	const char *pname;
1790 	boolean_t errflag = B_FALSE;
1791 	boolean_t addflag = B_FALSE;
1792 	boolean_t deleteflag = B_FALSE;
1793 	boolean_t ephflag = B_FALSE;
1794 	boolean_t compressflag = B_FALSE;
1795 	boolean_t uncompressflag = B_FALSE;
1796 	/* the next two work together for -c, -k, -T, -e options only */
1797 	boolean_t need_crypto = B_FALSE;	/* if any -c, -k, -T, -e */
1798 	boolean_t cipher_only = B_TRUE;		/* if -c only */
1799 	const char *keyfile = NULL;
1800 	mech_alias_t *cipher = NULL;
1801 	token_spec_t *token = NULL;
1802 	char	*rkey = NULL;
1803 	size_t	rksz = 0;
1804 	char realfilename[MAXPATHLEN];
1805 
1806 	pname = getpname(argv[0]);
1807 
1808 	(void) setlocale(LC_ALL, "");
1809 	(void) textdomain(TEXT_DOMAIN);
1810 
1811 	while ((c = getopt(argc, argv, "a:c:Cd:efk:o:s:T:U")) != EOF) {
1812 		switch (c) {
1813 		case 'a':
1814 			addflag = B_TRUE;
1815 			if ((filename = realpath(optarg, realfilename)) == NULL)
1816 				die("%s", optarg);
1817 			if (((argc - optind) > 0) && (*argv[optind] != '-')) {
1818 				/* optional device */
1819 				devicename = argv[optind];
1820 				optind++;
1821 			}
1822 			break;
1823 		case 'C':
1824 			compressflag = B_TRUE;
1825 			if (((argc - optind) > 1) && (*argv[optind] != '-')) {
1826 				/* optional algorithm */
1827 				algname = argv[optind];
1828 				optind++;
1829 			}
1830 			check_algorithm_validity(algname, &compress_index);
1831 			break;
1832 		case 'c':
1833 			/* is the chosen cipher allowed? */
1834 			if ((cipher = ciph2mech(optarg)) == NULL) {
1835 				errflag = B_TRUE;
1836 				warn(gettext("cipher %s not allowed\n"),
1837 				    optarg);
1838 			}
1839 			need_crypto = B_TRUE;
1840 			/* cipher_only is already set */
1841 			break;
1842 		case 'd':
1843 			deleteflag = B_TRUE;
1844 			minor = name_to_minor(optarg);
1845 			if (minor != 0)
1846 				devicename = optarg;
1847 			else {
1848 				if ((filename = realpath(optarg,
1849 				    realfilename)) == NULL)
1850 					die("%s", optarg);
1851 			}
1852 			break;
1853 		case 'e':
1854 			ephflag = B_TRUE;
1855 			need_crypto = B_TRUE;
1856 			cipher_only = B_FALSE;	/* need to unset cipher_only */
1857 			break;
1858 		case 'f':
1859 			force = B_TRUE;
1860 			break;
1861 		case 'k':
1862 			keyfile = optarg;
1863 			need_crypto = B_TRUE;
1864 			cipher_only = B_FALSE;	/* need to unset cipher_only */
1865 			break;
1866 		case 's':
1867 			segsize = convert_to_num(optarg);
1868 			if (segsize < DEV_BSIZE || !ISP2(segsize))
1869 				die(gettext("segment size %s is invalid "
1870 				    "or not a multiple of minimum block "
1871 				    "size %ld\n"), optarg, DEV_BSIZE);
1872 			break;
1873 		case 'T':
1874 			if ((token = parsetoken(optarg)) == NULL) {
1875 				errflag = B_TRUE;
1876 				warn(
1877 				    gettext("invalid token key specifier %s\n"),
1878 				    optarg);
1879 			}
1880 			need_crypto = B_TRUE;
1881 			cipher_only = B_FALSE;	/* need to unset cipher_only */
1882 			break;
1883 		case 'U':
1884 			uncompressflag = B_TRUE;
1885 			break;
1886 		case '?':
1887 		default:
1888 			errflag = B_TRUE;
1889 			break;
1890 		}
1891 	}
1892 
1893 	/* Check for mutually exclusive combinations of options */
1894 	if (errflag ||
1895 	    (addflag && deleteflag) ||
1896 	    (!addflag && need_crypto) ||
1897 	    ((compressflag || uncompressflag) && (addflag || deleteflag)))
1898 		usage(pname);
1899 
1900 	/* ephemeral key, and key from either file or token are incompatible */
1901 	if (ephflag && (keyfile != NULL || token != NULL)) {
1902 		die(gettext("ephemeral key cannot be used with keyfile"
1903 		    " or token key\n"));
1904 	}
1905 
1906 	/*
1907 	 * "-c" but no "-k", "-T", "-e", or "-T -k" means derive key from
1908 	 * command line passphrase
1909 	 */
1910 
1911 	switch (argc - optind) {
1912 	case 0: /* no more args */
1913 		if (compressflag || uncompressflag)	/* needs filename */
1914 			usage(pname);
1915 		break;
1916 	case 1:
1917 		if (addflag || deleteflag)
1918 			usage(pname);
1919 		/* one arg means compress/uncompress the file ... */
1920 		if (compressflag || uncompressflag) {
1921 			if ((filename = realpath(argv[optind],
1922 			    realfilename)) == NULL)
1923 				die("%s", argv[optind]);
1924 		/* ... or without options means print the association */
1925 		} else {
1926 			minor = name_to_minor(argv[optind]);
1927 			if (minor != 0)
1928 				devicename = argv[optind];
1929 			else {
1930 				if ((filename = realpath(argv[optind],
1931 				    realfilename)) == NULL)
1932 					die("%s", argv[optind]);
1933 			}
1934 		}
1935 		break;
1936 	default:
1937 		usage(pname);
1938 		break;
1939 	}
1940 
1941 	if (addflag || compressflag || uncompressflag)
1942 		check_file_validity(filename);
1943 
1944 	if (filename && !valid_abspath(filename))
1945 		exit(E_ERROR);
1946 
1947 	/*
1948 	 * Here, we know the arguments are correct, the filename is an
1949 	 * absolute path, it exists and is a regular file. We don't yet
1950 	 * know that the device name is ok or not.
1951 	 */
1952 
1953 	openflag = O_EXCL;
1954 	if (addflag || deleteflag || compressflag || uncompressflag)
1955 		openflag |= O_RDWR;
1956 	else
1957 		openflag |= O_RDONLY;
1958 	lfd = open(lofictl, openflag);
1959 	if (lfd == -1) {
1960 		if ((errno == EPERM) || (errno == EACCES)) {
1961 			die(gettext("you do not have permission to perform "
1962 			    "that operation.\n"));
1963 		} else {
1964 			die(gettext("open: %s"), lofictl);
1965 		}
1966 		/*NOTREACHED*/
1967 	}
1968 
1969 	/*
1970 	 * No passphrase is needed for ephemeral key, or when key is
1971 	 * in a file and not wrapped by another key from a token.
1972 	 * However, a passphrase is needed in these cases:
1973 	 * 1. cipher with no ephemeral key, key file, or token,
1974 	 *    in which case the passphrase is used to build the key
1975 	 * 2. token with an optional cipher or optional key file,
1976 	 *    in which case the passphrase unlocks the token
1977 	 * If only the cipher is specified, reconfirm the passphrase
1978 	 * to ensure the user hasn't mis-entered it.  Otherwise, the
1979 	 * token will enforce the token passphrase.
1980 	 */
1981 	if (need_crypto) {
1982 		CK_SESSION_HANDLE	sess;
1983 
1984 		/* pick a cipher if none specified */
1985 		if (cipher == NULL)
1986 			cipher = DEFAULT_CIPHER;
1987 
1988 		if (!kernel_cipher_check(cipher))
1989 			die(gettext(
1990 			    "use \"cryptoadm list -m\" to find available "
1991 			    "mechanisms\n"));
1992 
1993 		init_crypto(token, cipher, &sess);
1994 
1995 		if (cipher_only) {
1996 			getkeyfromuser(cipher, &rkey, &rksz);
1997 		} else if (token != NULL) {
1998 			getkeyfromtoken(sess, token, keyfile, cipher,
1999 			    &rkey, &rksz);
2000 		} else {
2001 			/* this also handles ephemeral keys */
2002 			getkeyfromfile(keyfile, cipher, &rkey, &rksz);
2003 		}
2004 
2005 		end_crypto(sess);
2006 	}
2007 
2008 	/*
2009 	 * Now to the real work.
2010 	 */
2011 	if (addflag)
2012 		add_mapping(lfd, devicename, filename, cipher, rkey, rksz);
2013 	else if (compressflag)
2014 		lofi_compress(&lfd, filename, compress_index, segsize);
2015 	else if (uncompressflag)
2016 		lofi_uncompress(lfd, filename);
2017 	else if (deleteflag)
2018 		delete_mapping(lfd, devicename, filename, force);
2019 	else if (filename || devicename)
2020 		print_one_mapping(lfd, devicename, filename);
2021 	else
2022 		print_mappings(lfd);
2023 
2024 	if (lfd != -1)
2025 		(void) close(lfd);
2026 	closelib();
2027 	return (E_SUCCESS);
2028 }
2029