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