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