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