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