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