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