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.
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.
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]
22 * Copyright 2009 Sun Microsystems, Inc. All rights reserved.
23 * Use is subject to license terms.
24 * Copyright 2012 Joyent, Inc. All rights reserved.
26 * Copyright 2013 Nexenta Systems, Inc. All rights reserved.
27 * Copyright (c) 2014 Gary Mills
28 * Copyright (c) 2016 Andrey Sokolov
32 * lofiadm - administer lofi(7d). Very simple, add and remove file<->device
33 * associations, and display status. All the ioctls are private between
34 * lofi and lofiadm, and so are very simple - device information is
35 * communicated via a minor number.
38 #include <sys/types.h>
39 #include <sys/param.h>
42 #include <sys/sysmacros.h>
43 #include <sys/modctl.h>
44 #include <netinet/in.h>
54 #include <libdevinfo.h>
59 #include <security/cryptoki.h>
60 #include <cryptoutil.h>
61 #include <sys/crypto/ioctl.h>
62 #include <sys/crypto/ioctladmin.h>
64 #include <sys/mkdev.h>
68 /* Only need the IV len #defines out of these files, nothing else. */
69 #include <aes/aes_impl.h>
70 #include <des/des_impl.h>
71 #include <blowfish/blowfish_impl.h>
73 static const char USAGE
[] =
74 "Usage: %s [-r] [-l] -a file [ device ]\n"
75 " %s [-r] -c crypto_algorithm -a file [device]\n"
76 " %s [-r] -c crypto_algorithm -k raw_key_file -a file [device]\n"
77 " %s [-r] -c crypto_algorithm -T [token]:[manuf]:[serial]:key "
79 " %s [-r] -c crypto_algorithm -T [token]:[manuf]:[serial]:key "
80 "-k wrapped_key_file -a file [device]\n"
81 " %s [-r] -c crypto_algorithm -e -a file [device]\n"
82 " %s -d file | device\n"
83 " %s -C [gzip|gzip-6|gzip-9|lzma] [-s segment_size] file\n"
85 " %s [ file | device ]\n";
87 typedef struct token_spec
{
94 typedef struct mech_alias
{
96 CK_MECHANISM_TYPE type
;
97 char *name
; /* for ioctl */
98 char *iv_name
; /* for ioctl */
99 size_t iv_len
; /* for ioctl */
100 iv_method_t iv_type
; /* for ioctl */
101 size_t min_keysize
; /* in bytes */
102 size_t max_keysize
; /* in bytes */
107 static mech_alias_t mech_aliases
[] = {
108 /* Preferred one should always be listed first. */
109 { "aes-256-cbc", CKM_AES_CBC
, "CKM_AES_CBC", "CKM_AES_ECB", AES_IV_LEN
,
110 IVM_ENC_BLKNO
, ULONG_MAX
, 0L, NULL
, (CK_SLOT_ID
) -1 },
111 { "aes-192-cbc", CKM_AES_CBC
, "CKM_AES_CBC", "CKM_AES_ECB", AES_IV_LEN
,
112 IVM_ENC_BLKNO
, ULONG_MAX
, 0L, NULL
, (CK_SLOT_ID
) -1 },
113 { "aes-128-cbc", CKM_AES_CBC
, "CKM_AES_CBC", "CKM_AES_ECB", AES_IV_LEN
,
114 IVM_ENC_BLKNO
, ULONG_MAX
, 0L, NULL
, (CK_SLOT_ID
) -1 },
115 { "des3-cbc", CKM_DES3_CBC
, "CKM_DES3_CBC", "CKM_DES3_ECB", DES_IV_LEN
,
116 IVM_ENC_BLKNO
, ULONG_MAX
, 0L, NULL
, (CK_SLOT_ID
)-1 },
117 { "blowfish-cbc", CKM_BLOWFISH_CBC
, "CKM_BLOWFISH_CBC",
118 "CKM_BLOWFISH_ECB", BLOWFISH_IV_LEN
, IVM_ENC_BLKNO
, ULONG_MAX
,
119 0L, NULL
, (CK_SLOT_ID
)-1 }
121 * A cipher without an iv requirement would look like this:
122 * { "aes-xex", CKM_AES_XEX, "CKM_AES_XEX", NULL, 0,
123 * IVM_NONE, ULONG_MAX, 0L, NULL, (CK_SLOT_ID)-1 }
127 int mech_aliases_count
= (sizeof (mech_aliases
) / sizeof (mech_alias_t
));
129 /* Preferred cipher, if one isn't specified on command line. */
130 #define DEFAULT_CIPHER (&mech_aliases[0])
132 #define DEFAULT_CIPHER_NUM 64 /* guess # kernel ciphers available */
133 #define DEFAULT_MECHINFO_NUM 16 /* guess # kernel mechs available */
134 #define MIN_PASSLEN 8 /* min acceptable passphrase size */
136 static int gzip_compress(void *src
, size_t srclen
, void *dst
,
137 size_t *destlen
, int level
);
138 static int lzma_compress(void *src
, size_t srclen
, void *dst
,
139 size_t *destlen
, int level
);
141 lofi_compress_info_t lofi_compress_table
[LOFI_COMPRESS_FUNCTIONS
] = {
142 {NULL
, gzip_compress
, 6, "gzip"}, /* default */
143 {NULL
, gzip_compress
, 6, "gzip-6"},
144 {NULL
, gzip_compress
, 9, "gzip-9"},
145 {NULL
, lzma_compress
, 0, "lzma"}
148 /* For displaying lofi mappings */
149 #define FORMAT "%-20s %-30s %s\n"
151 #define COMPRESS_ALGORITHM "gzip"
152 #define COMPRESS_THRESHOLD 2048
153 #define SEGSIZE 131072
154 #define BLOCK_SIZE 512
155 #define KILOBYTE 1024
156 #define MEGABYTE (KILOBYTE * KILOBYTE)
157 #define GIGABYTE (KILOBYTE * MEGABYTE)
158 #define LIBZ "libz.so.1"
160 const char lofi_crypto_magic
[6] = LOFI_CRYPTO_MAGIC
;
163 usage(const char *pname
)
165 (void) fprintf(stderr
, gettext(USAGE
), pname
, pname
, pname
,
166 pname
, pname
, pname
, pname
, pname
, pname
, pname
);
171 gzip_compress(void *src
, size_t srclen
, void *dst
, size_t *dstlen
, int level
)
173 static int (*compress2p
)(void *, ulong_t
*, void *, size_t, int) = NULL
;
174 void *libz_hdl
= NULL
;
177 * The first time we are called, attempt to dlopen()
178 * libz.so.1 and get a pointer to the compress2() function
180 if (compress2p
== NULL
) {
181 if ((libz_hdl
= openlib(LIBZ
)) == NULL
)
182 die(gettext("could not find %s. "
183 "gzip compression unavailable\n"), LIBZ
);
186 (int (*)(void *, ulong_t
*, void *, size_t, int))
187 dlsym(libz_hdl
, "compress2")) == NULL
) {
189 die(gettext("could not find the correct %s. "
190 "gzip compression unavailable\n"), LIBZ
);
194 if ((*compress2p
)(dst
, (ulong_t
*)dstlen
, src
, srclen
, level
) != 0)
201 *SzAlloc(void *p
, size_t size
)
203 return (malloc(size
));
208 SzFree(void *p
, void *address
, size_t size
)
213 static ISzAlloc g_Alloc
= {
218 #define LZMA_UNCOMPRESSED_SIZE 8
219 #define LZMA_HEADER_SIZE (LZMA_PROPS_SIZE + LZMA_UNCOMPRESSED_SIZE)
223 lzma_compress(void *src
, size_t srclen
, void *dst
,
224 size_t *dstlen
, int level
)
228 size_t outsizeprocessed
;
229 size_t outpropssize
= LZMA_PROPS_SIZE
;
237 LzmaEncProps_Init(&props
);
240 * The LZMA compressed file format is as follows -
242 * Offset Size(bytes) Description
243 * 0 1 LZMA properties (lc, lp, lp (encoded))
244 * 1 4 Dictionary size (little endian)
245 * 5 8 Uncompressed size (little endian)
249 /* set the dictionary size to be 8MB */
250 props
.dictSize
= 1 << 23;
252 if (*dstlen
< LZMA_HEADER_SIZE
)
253 return (SZ_ERROR_OUTPUT_EOF
);
258 * Set the uncompressed size in the LZMA header
259 * The LZMA properties (specified in 'props')
260 * will be set by the call to LzmaEncode()
262 for (i
= 0; i
< LZMA_UNCOMPRESSED_SIZE
; i
++, t
>>= 8) {
263 dstp
[LZMA_PROPS_SIZE
+ i
] = (Byte
)t
;
266 outsizeprocessed
= outsize2
- LZMA_HEADER_SIZE
;
267 res
= LzmaEncode(dstp
+ LZMA_HEADER_SIZE
, &outsizeprocessed
,
268 src
, srclen
, &props
, dstp
, &outpropssize
, 0, NULL
,
274 *dstlen
= outsizeprocessed
+ LZMA_HEADER_SIZE
;
279 * Translate a lofi device name to a minor number. We might be asked
280 * to do this when there is no association (such as when the user specifies
281 * a particular device), so we can only look at the string.
284 name_to_minor(const char *devicename
)
289 * If devicename does not exist, then devicename contains
290 * the name of the device to be created.
291 * Note we only allow non-labeled devices here.
293 if (stat(devicename
, &st
)) {
296 rv
= sscanf(devicename
, "/dev/" LOFI_BLOCK_NAME
"/%d", &minor
);
299 rv
= sscanf(devicename
, "/dev/" LOFI_CHAR_NAME
"/%d", &minor
);
307 * For disk devices we use modctl(MODGETNAME) to read driver name
310 if (st
.st_mode
& S_IFCHR
|| st
.st_mode
& S_IFBLK
) {
312 char mname
[MODMAXNAMELEN
];
314 maj
= major(st
.st_rdev
);
316 if (modctl(MODGETNAME
, mname
, MODMAXNAMELEN
, &maj
) == 0) {
317 if (strncmp(mname
, LOFI_DRIVER_NAME
,
318 sizeof (LOFI_DRIVER_NAME
)) == 0) {
319 return (LOFI_MINOR2ID(minor(st
.st_rdev
)));
328 * This might be the first time we've used this minor number. If so,
329 * it might also be that the /dev links are in the process of being created
330 * by devfsadmd (or that they'll be created "soon"). We cannot return
331 * until they're there or the invoker of lofiadm might try to use them
332 * and not find them. This can happen if a shell script is running on
335 static int sleeptime
= 2; /* number of seconds to sleep between stat's */
336 static int maxsleep
= 120; /* maximum number of seconds to sleep */
339 make_blkdevname(struct lofi_ioctl
*li
, char *path
, size_t len
)
344 if (li
->li_devpath
[0] == '\0') {
346 (void) strlcpy(path
, "unknown", len
);
348 (void) snprintf(path
, len
,
349 "/dev/" LOFI_BLOCK_NAME
"/%d", li
->li_id
);
352 (void) strlcpy(path
, li
->li_devpath
, len
);
353 r1
= strchr(path
, 'r');
355 r2
= strchr(li
->li_devpath
, 'r');
356 (void) strlcpy(r1
, r2
+1, len
- l1
);
358 if (li
->li_labeled
) {
359 (void) strlcat(path
, "p0", len
);
364 wait_until_dev_complete(struct lofi_ioctl
*li
)
368 char blkpath
[MAXPATHLEN
];
369 char charpath
[MAXPATHLEN
];
370 di_devlink_handle_t hdl
;
372 make_blkdevname(li
, blkpath
, sizeof (blkpath
));
373 (void) strlcpy(charpath
, li
->li_devpath
, sizeof (charpath
));
375 if (li
->li_labeled
) {
376 (void) strlcat(charpath
, "p0", sizeof (charpath
));
379 /* Check if links already present */
380 if (stat(blkpath
, &buf
) == 0 && stat(charpath
, &buf
) == 0)
383 /* First use di_devlink_init() */
384 if (hdl
= di_devlink_init("lofi", DI_MAKE_LINK
)) {
385 (void) di_devlink_fini(&hdl
);
390 * Under normal conditions, di_devlink_init(DI_MAKE_LINK) above will
391 * only fail if the caller is non-root. In that case, wait for
392 * link creation via sysevents.
394 for (cursleep
= 0; cursleep
< maxsleep
; cursleep
+= sleeptime
) {
395 if (stat(blkpath
, &buf
) == 0 && stat(charpath
, &buf
) == 0)
397 (void) sleep(sleeptime
);
402 if (stat(blkpath
, &buf
) == -1) {
403 die(gettext("%s was not created"), blkpath
);
405 if (stat(charpath
, &buf
) == -1) {
406 die(gettext("%s was not created"), charpath
);
411 * Map the file and return the minor number the driver picked for the file
412 * DO NOT use this function if the filename is actually the device name.
415 lofi_map_file(int lfd
, struct lofi_ioctl
*li
, const char *filename
)
420 (void) strlcpy(li
->li_filename
, filename
, sizeof (li
->li_filename
));
421 minor
= ioctl(lfd
, LOFI_MAP_FILE
, li
);
423 if (errno
== ENOTSUP
)
424 warn(gettext("encrypting compressed files is "
426 die(gettext("could not map file %s"), filename
);
428 wait_until_dev_complete(li
);
433 * Add a device association. If devicename is NULL, let the driver
437 add_mapping(int lfd
, const char *devicename
, const char *filename
,
438 mech_alias_t
*cipher
, const char *rkey
, size_t rksz
, boolean_t rdonly
,
441 struct lofi_ioctl li
;
443 bzero(&li
, sizeof (li
));
444 li
.li_readonly
= rdonly
;
445 li
.li_labeled
= label
;
447 li
.li_crypto_enabled
= B_FALSE
;
448 if (cipher
!= NULL
) {
449 /* set up encryption for mapped file */
450 li
.li_crypto_enabled
= B_TRUE
;
451 (void) strlcpy(li
.li_cipher
, cipher
->name
,
452 sizeof (li
.li_cipher
));
453 if (rksz
> sizeof (li
.li_key
)) {
454 die(gettext("key too large"));
456 bcopy(rkey
, li
.li_key
, rksz
);
457 li
.li_key_len
= rksz
<< 3; /* convert to bits */
459 li
.li_iv_type
= cipher
->iv_type
;
460 li
.li_iv_len
= cipher
->iv_len
; /* 0 when no iv needed */
461 switch (cipher
->iv_type
) {
463 (void) strlcpy(li
.li_iv_cipher
, cipher
->iv_name
,
464 sizeof (li
.li_iv_cipher
));
473 if (devicename
== NULL
) {
475 char path
[MAXPATHLEN
];
477 /* pick one via the driver */
478 minor
= lofi_map_file(lfd
, &li
, filename
);
480 make_blkdevname(&li
, path
, sizeof (path
));
482 /* if mapping succeeds, print the one picked */
483 (void) printf("%s\n", path
);
488 /* use device we were given */
489 li
.li_id
= name_to_minor(devicename
);
491 die(gettext("malformed device name %s\n"), devicename
);
493 (void) strlcpy(li
.li_filename
, filename
, sizeof (li
.li_filename
));
495 /* if device is already in use li.li_minor won't change */
496 if (ioctl(lfd
, LOFI_MAP_FILE_MINOR
, &li
) == -1) {
497 if (errno
== ENOTSUP
)
498 warn(gettext("encrypting compressed files is "
500 die(gettext("could not map file %s to %s"), filename
,
503 wait_until_dev_complete(&li
);
507 * Remove an association. Delete by device name if non-NULL, or by
508 * filename otherwise.
511 delete_mapping(int lfd
, const char *devicename
, const char *filename
,
514 struct lofi_ioctl li
;
517 li
.li_cleanup
= B_FALSE
;
519 if (devicename
== NULL
) {
520 /* delete by filename */
521 (void) strlcpy(li
.li_filename
, filename
,
522 sizeof (li
.li_filename
));
524 if (ioctl(lfd
, LOFI_UNMAP_FILE
, &li
) == -1) {
525 die(gettext("could not unmap file %s"), filename
);
530 /* delete by device */
531 li
.li_id
= name_to_minor(devicename
);
533 die(gettext("malformed device name %s\n"), devicename
);
535 if (ioctl(lfd
, LOFI_UNMAP_FILE_MINOR
, &li
) == -1) {
536 die(gettext("could not unmap device %s"), devicename
);
541 * Show filename given devicename, or devicename given filename.
544 print_one_mapping(int lfd
, const char *devicename
, const char *filename
)
546 struct lofi_ioctl li
;
547 char blkpath
[MAXPATHLEN
];
549 if (devicename
== NULL
) {
550 /* given filename, print devicename */
552 (void) strlcpy(li
.li_filename
, filename
,
553 sizeof (li
.li_filename
));
554 if (ioctl(lfd
, LOFI_GET_MINOR
, &li
) == -1) {
555 die(gettext("could not find device for %s"), filename
);
557 make_blkdevname(&li
, blkpath
, sizeof (blkpath
));
558 (void) printf("%s\n", blkpath
);
562 /* given devicename, print filename */
563 li
.li_id
= name_to_minor(devicename
);
565 die(gettext("malformed device name %s\n"), devicename
);
567 if (ioctl(lfd
, LOFI_GET_FILENAME
, &li
) == -1) {
568 die(gettext("could not find filename for %s"), devicename
);
570 (void) printf("%s\n", li
.li_filename
);
574 * Print the list of all the mappings, including a header.
577 print_mappings(int fd
)
579 struct lofi_ioctl li
;
582 char path
[MAXPATHLEN
];
583 char options
[MAXPATHLEN
] = { 0 };
586 if (ioctl(fd
, LOFI_GET_MAXMINOR
, &li
) == -1) {
591 (void) printf(FORMAT
, gettext("Block Device"), gettext("File"),
593 for (minor
= 1; minor
<= maxminor
; minor
++) {
595 if (ioctl(fd
, LOFI_GET_FILENAME
, &li
) == -1) {
601 make_blkdevname(&li
, path
, sizeof (path
));
606 * Encrypted lofi and compressed lofi are mutually exclusive.
608 if (li
.li_crypto_enabled
)
609 (void) snprintf(options
, sizeof (options
),
610 gettext("Encrypted"));
611 else if (li
.li_algorithm
[0] != '\0')
612 (void) snprintf(options
, sizeof (options
),
613 gettext("Compressed(%s)"), li
.li_algorithm
);
614 if (li
.li_readonly
) {
615 if (strlen(options
) != 0) {
616 (void) strlcat(options
, ",Readonly",
619 (void) snprintf(options
, sizeof (options
),
620 gettext("Readonly"));
624 if (strlen(options
) != 0) {
625 (void) strlcat(options
, ",Labeled",
628 (void) snprintf(options
, sizeof (options
),
632 if (strlen(options
) == 0)
633 (void) snprintf(options
, sizeof (options
), "-");
635 (void) printf(FORMAT
, path
, li
.li_filename
, options
);
640 * Verify the cipher selected by user.
642 static mech_alias_t
*
643 ciph2mech(const char *alias
)
647 for (i
= 0; i
< mech_aliases_count
; i
++) {
648 if (strcasecmp(alias
, mech_aliases
[i
].alias
) == 0)
649 return (&mech_aliases
[i
]);
655 * Verify user selected cipher is also available in kernel.
657 * While traversing kernel list of mechs, if the cipher is supported in the
658 * kernel for both encryption and decryption, it also picks up the min/max
662 kernel_cipher_check(mech_alias_t
*cipher
)
664 boolean_t ciph_ok
= B_FALSE
;
665 boolean_t iv_ok
= B_FALSE
;
668 crypto_get_mechanism_list_t
*kciphers
= NULL
;
669 crypto_get_all_mechanism_info_t
*kinfo
= NULL
;
674 /* if cipher doesn't need iv generating mech, bypass that check now */
675 if (cipher
->iv_name
== NULL
)
678 /* allocate some space for the list of kernel ciphers */
679 count
= DEFAULT_CIPHER_NUM
;
680 kciphers
= malloc(sizeof (crypto_get_mechanism_list_t
) +
681 sizeof (crypto_mech_name_t
) * (count
- 1));
682 if (kciphers
== NULL
)
683 die(gettext("failed to allocate memory for list of "
684 "kernel mechanisms"));
685 kciphers
->ml_count
= count
;
687 /* query crypto device to get list of kernel ciphers */
688 if ((fd
= open("/dev/crypto", O_RDWR
)) == -1) {
689 warn(gettext("failed to open %s"), "/dev/crypto");
693 if (ioctl(fd
, CRYPTO_GET_MECHANISM_LIST
, kciphers
) == -1) {
694 warn(gettext("CRYPTO_GET_MECHANISM_LIST ioctl failed"));
698 if (kciphers
->ml_return_value
== CRYPTO_BUFFER_TOO_SMALL
) {
699 count
= kciphers
->ml_count
;
701 kciphers
= malloc(sizeof (crypto_get_mechanism_list_t
) +
702 sizeof (crypto_mech_name_t
) * (count
- 1));
703 if (kciphers
== NULL
) {
704 warn(gettext("failed to allocate memory for list of "
705 "kernel mechanisms"));
708 kciphers
->ml_count
= count
;
710 if (ioctl(fd
, CRYPTO_GET_MECHANISM_LIST
, kciphers
) == -1) {
711 warn(gettext("CRYPTO_GET_MECHANISM_LIST ioctl failed"));
716 if (kciphers
->ml_return_value
!= CRYPTO_SUCCESS
) {
718 "CRYPTO_GET_MECHANISM_LIST ioctl return value = %d\n"),
719 kciphers
->ml_return_value
);
724 * scan list of kernel ciphers looking for the selected one and if
725 * it needs an iv generated using another cipher, also look for that
726 * additional cipher to be used for generating the iv
728 count
= kciphers
->ml_count
;
729 for (i
= 0; i
< count
&& !(ciph_ok
&& iv_ok
); i
++) {
731 strcasecmp(cipher
->name
, kciphers
->ml_list
[i
]) == 0)
734 strcasecmp(cipher
->iv_name
, kciphers
->ml_list
[i
]) == 0)
741 warn(gettext("%s mechanism not supported in kernel\n"),
744 warn(gettext("%s mechanism not supported in kernel\n"),
748 /* Get the details about the user selected cipher */
749 count
= DEFAULT_MECHINFO_NUM
;
750 kinfo
= malloc(sizeof (crypto_get_all_mechanism_info_t
) +
751 sizeof (crypto_mechanism_info_t
) * (count
- 1));
753 warn(gettext("failed to allocate memory for "
754 "kernel mechanism info"));
757 kinfo
->mi_count
= count
;
758 (void) strlcpy(kinfo
->mi_mechanism_name
, cipher
->name
,
759 CRYPTO_MAX_MECH_NAME
);
761 if (ioctl(fd
, CRYPTO_GET_ALL_MECHANISM_INFO
, kinfo
) == -1) {
763 "CRYPTO_GET_ALL_MECHANISM_INFO ioctl failed"));
767 if (kinfo
->mi_return_value
== CRYPTO_BUFFER_TOO_SMALL
) {
768 count
= kinfo
->mi_count
;
771 sizeof (crypto_get_all_mechanism_info_t
) +
772 sizeof (crypto_mechanism_info_t
) * (count
- 1));
774 warn(gettext("failed to allocate memory for "
775 "kernel mechanism info"));
778 kinfo
->mi_count
= count
;
779 (void) strlcpy(kinfo
->mi_mechanism_name
, cipher
->name
,
780 CRYPTO_MAX_MECH_NAME
);
782 if (ioctl(fd
, CRYPTO_GET_ALL_MECHANISM_INFO
, kinfo
) ==
784 warn(gettext("CRYPTO_GET_ALL_MECHANISM_INFO "
790 if (kinfo
->mi_return_value
!= CRYPTO_SUCCESS
) {
791 warn(gettext("CRYPTO_GET_ALL_MECHANISM_INFO ioctl "
792 "return value = %d\n"), kinfo
->mi_return_value
);
796 /* Set key min and max size */
797 count
= kinfo
->mi_count
;
800 keymin
= kinfo
->mi_list
[i
].mi_min_key_size
;
801 keymax
= kinfo
->mi_list
[i
].mi_max_key_size
;
802 if (kinfo
->mi_list
[i
].mi_keysize_unit
&
803 CRYPTO_KEYSIZE_UNIT_IN_BITS
) {
804 keymin
= CRYPTO_BITS2BYTES(keymin
);
805 keymax
= CRYPTO_BITS2BYTES(keymax
);
808 cipher
->min_keysize
= keymin
;
809 cipher
->max_keysize
= keymax
;
817 "failed to find usable %s kernel mechanism, "
818 "use \"cryptoadm list -m\" to find available "
824 /* Note: key min/max, unit size, usage for iv cipher are not checked. */
826 return (ciph_ok
&& iv_ok
);
837 * Break up token spec into its components (non-destructive)
839 static token_spec_t
*
840 parsetoken(char *spec
)
847 #define nullfield(i) ((field[(i)+1] - field[(i)]) <= 1)
848 #define copyfield(fld, i) \
852 if ((n = (field[(i)+1] - field[(i)])) > 1) { \
853 if (((fld) = malloc(n)) != NULL) { \
854 (void) strncpy((fld), field[(i)], n); \
855 ((fld))[n - 1] = '\0'; \
861 char *field
[NFIELDS
+ 1]; /* +1 to catch extra delimiters */
862 token_spec_t
*ti
= NULL
;
868 * Correct format is "[name]:[manuf]:[serial]:key". Can't use
869 * strtok because it treats ":::key" and "key:::" and "key" all
870 * as the same thing, and we can't have the :s compressed away.
873 for (i
= 1; i
< NFIELDS
+ 1; i
++) {
874 field
[i
] = strchr(field
[i
-1], ':');
875 if (field
[i
] == NULL
)
879 if (i
< NFIELDS
) /* not enough fields */
881 if (field
[NFIELDS
] != NULL
) /* too many fields */
883 field
[NFIELDS
] = strchr(field
[NFIELDS
-1], '\0') + 1;
885 /* key label can't be empty */
886 if (nullfield(FLD_LABEL
))
889 ti
= malloc(sizeof (token_spec_t
));
893 copyfield(ti
->name
, FLD_NAME
);
894 copyfield(ti
->mfr
, FLD_MANUF
);
895 copyfield(ti
->serno
, FLD_SERIAL
);
896 copyfield(ti
->key
, FLD_LABEL
);
899 * If token specified and it only contains a key label, then
900 * search all tokens for the key, otherwise only those with
901 * matching name, mfr, and serno are used.
904 * That's how we'd like it to be, however, if only the key label
905 * is specified, default to using softtoken. It's easier.
907 if (ti
->name
== NULL
&& ti
->mfr
== NULL
&& ti
->serno
== NULL
)
908 ti
->name
= strdup(pkcs11_default_token());
913 * PBE the passphrase into a raw key
916 getkeyfromuser(mech_alias_t
*cipher
, char **raw_key
, size_t *raw_key_sz
,
917 boolean_t with_confirmation
)
919 CK_SESSION_HANDLE sess
;
923 void *salt
= NULL
; /* don't use NULL, see note on salt below */
929 /* did init_crypto find a slot that supports this cipher? */
930 if (cipher
->slot
== (CK_SLOT_ID
)-1 || cipher
->max_keysize
== 0) {
931 rv
= CKR_MECHANISM_INVALID
;
935 rv
= pkcs11_mech2keytype(cipher
->type
, &ktype
);
940 * use the passphrase to generate a PBE PKCS#5 secret key and
941 * retrieve the raw key data to eventually pass it to the kernel;
943 rv
= C_OpenSession(cipher
->slot
, CKF_SERIAL_SESSION
, NULL
, NULL
, &sess
);
947 /* get user passphrase with 8 byte minimum */
948 if (pkcs11_get_pass(NULL
, &pass
, &passlen
, MIN_PASSLEN
,
949 with_confirmation
) < 0) {
950 die(gettext("passphrases do not match\n"));
954 * salt should not be NULL, or else pkcs11_PasswdToKey() will
955 * complain about CKR_MECHANISM_PARAM_INVALID; the following is
956 * to make up for not having a salt until a proper one is used
961 klen
= cipher
->max_keysize
;
962 rv
= pkcs11_PasswdToKey(sess
, pass
, passlen
, salt
, saltlen
, ktype
,
963 cipher
->max_keysize
, &kvalue
, &klen
);
965 (void) C_CloseSession(sess
);
971 /* assert(klen == cipher->max_keysize); */
973 *raw_key
= (char *)kvalue
;
977 die(gettext("failed to generate %s key from passphrase: %s"),
978 cipher
->alias
, pkcs11_strerror(rv
));
982 * Read raw key from file; also handles ephemeral keys.
985 getkeyfromfile(const char *pathname
, mech_alias_t
*cipher
, char **key
,
990 boolean_t notplain
= B_FALSE
;
994 /* ephemeral keys are just random data */
995 if (pathname
== NULL
) {
996 *ksz
= cipher
->max_keysize
;
999 die(gettext("failed to allocate memory for"
1001 if (pkcs11_get_urandom(*key
, *ksz
) < 0) {
1003 die(gettext("failed to get enough random data"));
1009 * If the remaining section of code didn't also check for secure keyfile
1010 * permissions and whether the key is within cipher min and max lengths,
1011 * (or, if those things moved out of this block), we could have had:
1012 * if (pkcs11_read_data(pathname, key, ksz) < 0)
1016 if ((fd
= open(pathname
, O_RDONLY
, 0)) == -1)
1017 die(gettext("open of keyfile (%s) failed"), pathname
);
1019 if (fstat(fd
, &sbuf
) == -1)
1020 die(gettext("fstat of keyfile (%s) failed"), pathname
);
1022 if (S_ISREG(sbuf
.st_mode
)) {
1023 if ((sbuf
.st_mode
& (S_IWGRP
| S_IWOTH
)) != 0)
1024 die(gettext("insecure permissions on keyfile %s\n"),
1027 *ksz
= sbuf
.st_size
;
1028 if (*ksz
< cipher
->min_keysize
|| cipher
->max_keysize
< *ksz
) {
1029 warn(gettext("%s: invalid keysize: %d\n"),
1030 pathname
, (int)*ksz
);
1031 die(gettext("\t%d <= keysize <= %d\n"),
1032 cipher
->min_keysize
, cipher
->max_keysize
);
1035 *ksz
= cipher
->max_keysize
;
1039 *key
= malloc(*ksz
);
1041 die(gettext("failed to allocate memory for key from file"));
1043 for (cursz
= 0, nread
= 0; cursz
< *ksz
; cursz
+= nread
) {
1044 nread
= read(fd
, *key
, *ksz
);
1048 * nread == 0. If it's not a regular file we were trying to
1049 * get the maximum keysize of data possible for this cipher.
1050 * But if we've got at least the minimum keysize of data,
1051 * round down to the nearest keysize unit and call it good.
1052 * If we haven't met the minimum keysize, that's an error.
1053 * If it's a regular file, nread = 0 is also an error.
1055 if (nread
== 0 && notplain
&& cursz
>= cipher
->min_keysize
) {
1056 *ksz
= (cursz
/ cipher
->min_keysize
) *
1057 cipher
->min_keysize
;
1060 die(gettext("%s: can't read all keybytes"), pathname
);
1066 * Read the raw key from token, or from a file that was wrapped with a
1070 getkeyfromtoken(CK_SESSION_HANDLE sess
,
1071 token_spec_t
*token
, const char *keyfile
, mech_alias_t
*cipher
,
1072 char **raw_key
, size_t *raw_key_sz
)
1075 CK_BBOOL trueval
= B_TRUE
;
1076 CK_OBJECT_CLASS kclass
; /* secret key or RSA private key */
1077 CK_KEY_TYPE ktype
; /* from selected cipher or CKK_RSA */
1078 CK_KEY_TYPE raw_ktype
; /* from selected cipher */
1079 CK_ATTRIBUTE key_tmpl
[] = {
1080 { CKA_CLASS
, NULL
, 0 }, /* re-used for token key and unwrap */
1081 { CKA_KEY_TYPE
, NULL
, 0 }, /* ditto */
1082 { CKA_LABEL
, NULL
, 0 },
1083 { CKA_TOKEN
, NULL
, 0 },
1084 { CKA_PRIVATE
, NULL
, 0 }
1086 CK_ULONG attrs
= sizeof (key_tmpl
) / sizeof (CK_ATTRIBUTE
);
1090 CK_OBJECT_HANDLE obj
, rawobj
;
1091 CK_ULONG num_objs
= 1; /* just want to find 1 token key */
1092 CK_MECHANISM unwrap
= { CKM_RSA_PKCS
, NULL
, 0 };
1096 if (token
== NULL
|| token
->key
== NULL
)
1099 /* did init_crypto find a slot that supports this cipher? */
1100 if (cipher
->slot
== (CK_SLOT_ID
)-1 || cipher
->max_keysize
== 0) {
1101 die(gettext("failed to find any cryptographic provider, "
1102 "use \"cryptoadm list -p\" to find providers: %s\n"),
1103 pkcs11_strerror(CKR_MECHANISM_INVALID
));
1106 if (pkcs11_get_pass(token
->name
, &pass
, &passlen
, 0, B_FALSE
) < 0)
1107 die(gettext("unable to get passphrase"));
1109 /* use passphrase to login to token */
1110 if (pass
!= NULL
&& passlen
> 0) {
1111 rv
= C_Login(sess
, CKU_USER
, (CK_UTF8CHAR_PTR
)pass
, passlen
);
1113 die(gettext("cannot login to the token %s: %s\n"),
1114 token
->name
, pkcs11_strerror(rv
));
1118 rv
= pkcs11_mech2keytype(cipher
->type
, &raw_ktype
);
1120 die(gettext("failed to get key type for cipher %s: %s\n"),
1121 cipher
->name
, pkcs11_strerror(rv
));
1125 * If no keyfile was given, then the token key is secret key to
1126 * be used for encryption/decryption. Otherwise, the keyfile
1127 * contains a wrapped secret key, and the token is actually the
1128 * unwrapping RSA private key.
1130 if (keyfile
== NULL
) {
1131 kclass
= CKO_SECRET_KEY
;
1134 kclass
= CKO_PRIVATE_KEY
;
1138 /* Find the key in the token first */
1139 for (i
= 0; i
< attrs
; i
++) {
1140 switch (key_tmpl
[i
].type
) {
1142 key_tmpl
[i
].pValue
= &kclass
;
1143 key_tmpl
[i
].ulValueLen
= sizeof (kclass
);
1146 key_tmpl
[i
].pValue
= &ktype
;
1147 key_tmpl
[i
].ulValueLen
= sizeof (ktype
);
1150 key_tmpl
[i
].pValue
= token
->key
;
1151 key_tmpl
[i
].ulValueLen
= strlen(token
->key
);
1154 key_tmpl
[i
].pValue
= &trueval
;
1155 key_tmpl
[i
].ulValueLen
= sizeof (trueval
);
1158 key_tmpl
[i
].pValue
= &trueval
;
1159 key_tmpl
[i
].ulValueLen
= sizeof (trueval
);
1165 rv
= C_FindObjectsInit(sess
, key_tmpl
, attrs
);
1167 die(gettext("cannot find key %s: %s\n"), token
->key
,
1168 pkcs11_strerror(rv
));
1169 rv
= C_FindObjects(sess
, &obj
, 1, &num_objs
);
1170 (void) C_FindObjectsFinal(sess
);
1172 if (num_objs
== 0) {
1173 die(gettext("cannot find key %s\n"), token
->key
);
1174 } else if (rv
!= CKR_OK
) {
1175 die(gettext("cannot find key %s: %s\n"), token
->key
,
1176 pkcs11_strerror(rv
));
1180 * No keyfile means when token key is found, convert it to raw key,
1181 * and done. Otherwise still need do an unwrap to create yet another
1182 * obj and that needs to be converted to raw key before we're done.
1184 if (keyfile
== NULL
) {
1185 /* obj contains raw key, extract it */
1186 rv
= pkcs11_ObjectToKey(sess
, obj
, (void **)&rkey
, &rksz
,
1189 die(gettext("failed to get key value for %s"
1190 " from token %s, %s\n"), token
->key
,
1191 token
->name
, pkcs11_strerror(rv
));
1194 getkeyfromfile(keyfile
, cipher
, &rkey
, &rksz
);
1197 * Got the wrapping RSA obj and the wrapped key from file.
1198 * Unwrap the key from file with RSA obj to get rawkey obj.
1201 /* re-use the first two attributes of key_tmpl */
1202 kclass
= CKO_SECRET_KEY
;
1205 rv
= C_UnwrapKey(sess
, &unwrap
, obj
, (CK_BYTE_PTR
)rkey
,
1206 rksz
, key_tmpl
, 2, &rawobj
);
1208 die(gettext("failed to unwrap key in keyfile %s,"
1209 " %s\n"), keyfile
, pkcs11_strerror(rv
));
1211 /* rawobj contains raw key, extract it */
1212 rv
= pkcs11_ObjectToKey(sess
, rawobj
, (void **)&rkey
, &rksz
,
1215 die(gettext("failed to get unwrapped key value for"
1216 " key in keyfile %s, %s\n"), keyfile
,
1217 pkcs11_strerror(rv
));
1221 /* validate raw key size */
1222 if (rksz
< cipher
->min_keysize
|| cipher
->max_keysize
< rksz
) {
1223 warn(gettext("%s: invalid keysize: %d\n"), keyfile
, (int)rksz
);
1224 die(gettext("\t%d <= keysize <= %d\n"), cipher
->min_keysize
,
1225 cipher
->max_keysize
);
1229 *raw_key
= (char *)rkey
;
1233 * Set up cipher key limits and verify PKCS#11 can be done
1234 * match_token_cipher is the function pointer used by
1235 * pkcs11_GetCriteriaSession() init_crypto.
1238 match_token_cipher(CK_SLOT_ID slot_id
, void *args
, CK_RV
*rv
)
1240 token_spec_t
*token
;
1241 mech_alias_t
*cipher
;
1242 CK_TOKEN_INFO tokinfo
;
1243 CK_MECHANISM_INFO mechinfo
;
1244 boolean_t token_match
;
1247 * While traversing slot list, pick up the following info per slot:
1248 * - if token specified, whether it matches this slot's token info
1249 * - if the slot supports the PKCS#5 PBKD2 cipher
1251 * If the user said on the command line
1252 * -T tok:mfr:ser:lab -k keyfile
1253 * -c cipher -T tok:mfr:ser:lab -k keyfile
1254 * the given cipher or the default cipher apply to keyfile,
1255 * If the user said instead
1256 * -T tok:mfr:ser:lab
1257 * -c cipher -T tok:mfr:ser:lab
1258 * the key named "lab" may or may not agree with the given
1259 * cipher or the default cipher. In those cases, cipher will
1260 * be overridden with the actual cipher type of the key "lab".
1262 *rv
= CKR_FUNCTION_FAILED
;
1268 cipher
= (mech_alias_t
*)args
;
1269 token
= cipher
->token
;
1271 if (C_GetMechanismInfo(slot_id
, cipher
->type
, &mechinfo
) != CKR_OK
) {
1275 if (token
== NULL
) {
1276 if (C_GetMechanismInfo(slot_id
, CKM_PKCS5_PBKD2
, &mechinfo
) !=
1283 /* does the token match the token spec? */
1284 if (token
->key
== NULL
|| (C_GetTokenInfo(slot_id
, &tokinfo
) != CKR_OK
))
1287 token_match
= B_TRUE
;
1289 if (token
->name
!= NULL
&& (token
->name
)[0] != '\0' &&
1290 strncmp((char *)token
->name
, (char *)tokinfo
.label
,
1291 TOKEN_LABEL_SIZE
) != 0)
1292 token_match
= B_FALSE
;
1293 if (token
->mfr
!= NULL
&& (token
->mfr
)[0] != '\0' &&
1294 strncmp((char *)token
->mfr
, (char *)tokinfo
.manufacturerID
,
1295 TOKEN_MANUFACTURER_SIZE
) != 0)
1296 token_match
= B_FALSE
;
1297 if (token
->serno
!= NULL
&& (token
->serno
)[0] != '\0' &&
1298 strncmp((char *)token
->serno
, (char *)tokinfo
.serialNumber
,
1299 TOKEN_SERIAL_SIZE
) != 0)
1300 token_match
= B_FALSE
;
1306 cipher
->slot
= slot_id
;
1311 * Clean up crypto loose ends
1314 end_crypto(CK_SESSION_HANDLE sess
)
1316 (void) C_CloseSession(sess
);
1317 (void) C_Finalize(NULL
);
1321 * Set up crypto, opening session on slot that matches token and cipher
1324 init_crypto(token_spec_t
*token
, mech_alias_t
*cipher
,
1325 CK_SESSION_HANDLE_PTR sess
)
1329 cipher
->token
= token
;
1331 /* Turn off Metaslot so that we can see actual tokens */
1332 if (setenv("METASLOT_ENABLED", "false", 1) < 0) {
1333 die(gettext("could not disable Metaslot"));
1336 rv
= pkcs11_GetCriteriaSession(match_token_cipher
, (void *)cipher
,
1340 if (rv
== CKR_HOST_MEMORY
) {
1343 die(gettext("failed to find any cryptographic provider, "
1344 "use \"cryptoadm list -p\" to find providers: %s\n"),
1345 pkcs11_strerror(rv
));
1350 * Uncompress a file.
1352 * First map the file in to establish a device
1353 * association, then read from it. On-the-fly
1354 * decompression will automatically uncompress
1355 * the file if it's compressed
1357 * If the file is mapped and a device association
1358 * has been established, disallow uncompressing
1359 * the file until it is unmapped.
1362 lofi_uncompress(int lfd
, const char *filename
)
1364 struct lofi_ioctl li
;
1366 char devicename
[32];
1367 char tmpfilename
[MAXPATHLEN
];
1372 struct stat statbuf
;
1378 * Disallow uncompressing the file if it is
1381 li
.li_crypto_enabled
= B_FALSE
;
1383 (void) strlcpy(li
.li_filename
, filename
, sizeof (li
.li_filename
));
1384 if (ioctl(lfd
, LOFI_GET_MINOR
, &li
) != -1)
1385 die(gettext("%s must be unmapped before uncompressing"),
1388 /* Zero length files don't need to be uncompressed */
1389 if (stat(filename
, &statbuf
) == -1)
1390 die(gettext("stat: %s"), filename
);
1391 if (statbuf
.st_size
== 0)
1394 minor
= lofi_map_file(lfd
, &li
, filename
);
1395 (void) snprintf(devicename
, sizeof (devicename
), "/dev/%s/%d",
1396 LOFI_BLOCK_NAME
, minor
);
1398 /* If the file isn't compressed, we just return */
1399 if ((ioctl(lfd
, LOFI_CHECK_COMPRESSED
, &li
) == -1) ||
1400 (li
.li_algorithm
[0] == '\0')) {
1401 delete_mapping(lfd
, devicename
, filename
, B_TRUE
);
1402 die("%s is not compressed\n", filename
);
1405 if ((compfd
= open(devicename
, O_RDONLY
| O_NONBLOCK
)) == -1) {
1406 delete_mapping(lfd
, devicename
, filename
, B_TRUE
);
1407 die(gettext("open: %s"), filename
);
1409 /* Create a temp file in the same directory */
1410 x
= strdup(filename
);
1411 dir
= strdup(dirname(x
));
1413 x
= strdup(filename
);
1414 file
= strdup(basename(x
));
1416 (void) snprintf(tmpfilename
, sizeof (tmpfilename
),
1417 "%s/.%sXXXXXX", dir
, file
);
1421 if ((uncompfd
= mkstemp(tmpfilename
)) == -1) {
1422 (void) close(compfd
);
1423 delete_mapping(lfd
, devicename
, filename
, B_TRUE
);
1424 die("%s could not be uncompressed\n", filename
);
1428 * Set the mode bits and the owner of this temporary
1429 * file to be that of the original uncompressed file
1431 (void) fchmod(uncompfd
, statbuf
.st_mode
);
1433 if (fchown(uncompfd
, statbuf
.st_uid
, statbuf
.st_gid
) == -1) {
1434 (void) close(compfd
);
1435 (void) close(uncompfd
);
1436 delete_mapping(lfd
, devicename
, filename
, B_TRUE
);
1437 die("%s could not be uncompressed\n", filename
);
1440 /* Now read from the device in MAXBSIZE-sized chunks */
1442 rbytes
= read(compfd
, buf
, sizeof (buf
));
1447 if (write(uncompfd
, buf
, rbytes
) != rbytes
) {
1453 (void) close(compfd
);
1454 (void) close(uncompfd
);
1456 /* Delete the mapping */
1457 delete_mapping(lfd
, devicename
, filename
, B_TRUE
);
1460 * If an error occured while reading or writing, rbytes will
1464 (void) unlink(tmpfilename
);
1465 die(gettext("could not read from %s"), filename
);
1468 /* Rename the temp file to the actual file */
1469 if (rename(tmpfilename
, filename
) == -1)
1470 (void) unlink(tmpfilename
);
1477 lofi_compress(int *lfd
, const char *filename
, int compress_index
,
1480 struct lofi_ioctl lic
;
1481 lofi_compress_info_t
*li
;
1483 char tmpfilename
[MAXPATHLEN
];
1484 char comp_filename
[MAXPATHLEN
];
1485 char algorithm
[MAXALGLEN
];
1487 char *dir
= NULL
, *file
= NULL
;
1488 uchar_t
*uncompressed_seg
= NULL
;
1489 uchar_t
*compressed_seg
= NULL
;
1490 uint32_t compressed_segsize
;
1491 uint32_t len_compressed
, count
;
1492 uint32_t index_entries
, index_sz
;
1493 uint64_t *index
= NULL
;
1495 size_t real_segsize
;
1496 struct stat statbuf
;
1497 int compfd
= -1, uncompfd
= -1;
1499 ssize_t rbytes
, wbytes
, lastread
;
1503 * Disallow compressing the file if it is
1507 (void) strlcpy(lic
.li_filename
, filename
, sizeof (lic
.li_filename
));
1508 if (ioctl(*lfd
, LOFI_GET_MINOR
, &lic
) != -1)
1509 die(gettext("%s must be unmapped before compressing"),
1513 * Close the control device so other operations
1519 li
= &lofi_compress_table
[compress_index
];
1522 * The size of the buffer to hold compressed data must
1523 * be slightly larger than the compressed segment size.
1525 * The compress functions use part of the buffer as
1526 * scratch space to do calculations.
1527 * Ref: http://www.zlib.net/manual.html#compress2
1529 compressed_segsize
= segsize
+ (segsize
>> 6);
1530 compressed_seg
= (uchar_t
*)malloc(compressed_segsize
+ SEGHDR
);
1531 uncompressed_seg
= (uchar_t
*)malloc(segsize
);
1533 if (compressed_seg
== NULL
|| uncompressed_seg
== NULL
)
1534 die(gettext("No memory"));
1536 if ((uncompfd
= open(filename
, O_RDWR
, 0)) == -1)
1537 die(gettext("open: %s"), filename
);
1539 lock
.l_type
= F_WRLCK
;
1540 lock
.l_whence
= SEEK_SET
;
1545 * Use an advisory lock to ensure that only a
1546 * single lofiadm process compresses a given
1547 * file at any given time
1549 * A close on the file descriptor automatically
1550 * closes all lock state on the file
1552 if (fcntl(uncompfd
, F_SETLKW
, &lock
) == -1)
1553 die(gettext("fcntl: %s"), filename
);
1555 if (fstat(uncompfd
, &statbuf
) == -1) {
1556 (void) close(uncompfd
);
1557 die(gettext("fstat: %s"), filename
);
1560 /* Zero length files don't need to be compressed */
1561 if (statbuf
.st_size
== 0) {
1562 (void) close(uncompfd
);
1567 * Create temporary files in the same directory that
1568 * will hold the intermediate data
1570 x
= strdup(filename
);
1571 dir
= strdup(dirname(x
));
1573 x
= strdup(filename
);
1574 file
= strdup(basename(x
));
1576 (void) snprintf(tmpfilename
, sizeof (tmpfilename
),
1577 "%s/.%sXXXXXX", dir
, file
);
1578 (void) snprintf(comp_filename
, sizeof (comp_filename
),
1579 "%s/.%sXXXXXX", dir
, file
);
1583 if ((tfd
= mkstemp(tmpfilename
)) == -1)
1586 if ((compfd
= mkstemp(comp_filename
)) == -1)
1590 * Set the mode bits and owner of the compressed
1591 * file to be that of the original uncompressed file
1593 (void) fchmod(compfd
, statbuf
.st_mode
);
1595 if (fchown(compfd
, statbuf
.st_uid
, statbuf
.st_gid
) == -1)
1599 * Calculate the number of index entries required.
1600 * index entries are stored as an array. adding
1601 * a '2' here accounts for the fact that the last
1602 * segment may not be a multiple of the segment size
1604 index_sz
= (statbuf
.st_size
/ segsize
) + 2;
1605 index
= malloc(sizeof (*index
) * index_sz
);
1615 * Now read from the uncompressed file in 'segsize'
1616 * sized chunks, compress what was read in and
1617 * write it out to a temporary file
1620 rbytes
= read(uncompfd
, uncompressed_seg
, segsize
);
1625 if (lastread
< segsize
)
1629 * Account for the first byte that
1630 * indicates whether a segment is
1633 real_segsize
= segsize
- 1;
1634 (void) li
->l_compress(uncompressed_seg
, rbytes
,
1635 compressed_seg
+ SEGHDR
, &real_segsize
, li
->l_level
);
1638 * If the length of the compressed data is more
1639 * than a threshold then there isn't any benefit
1640 * to be had from compressing this segment - leave
1643 * NB. In case an error occurs during compression (above)
1644 * the 'real_segsize' isn't changed. The logic below
1645 * ensures that that segment is left uncompressed.
1647 len_compressed
= real_segsize
;
1648 if (segsize
<= COMPRESS_THRESHOLD
||
1649 real_segsize
> (segsize
- COMPRESS_THRESHOLD
)) {
1650 (void) memcpy(compressed_seg
+ SEGHDR
, uncompressed_seg
,
1652 type
= UNCOMPRESSED
;
1653 len_compressed
= rbytes
;
1659 * Set the first byte or the SEGHDR to
1660 * indicate if it's compressed or not
1662 *compressed_seg
= type
;
1663 wbytes
= write(tfd
, compressed_seg
, len_compressed
+ SEGHDR
);
1664 if (wbytes
!= (len_compressed
+ SEGHDR
)) {
1669 index
[count
] = BE_64(offset
);
1675 (void) close(uncompfd
);
1680 * The last index entry is a sentinel entry. It does not point to
1681 * an actual compressed segment but helps in computing the size of
1682 * the compressed segment. The size of each compressed segment is
1683 * computed by subtracting the current index value from the next
1684 * one (the compressed blocks are stored sequentially)
1686 index
[count
++] = BE_64(offset
);
1689 * Now write the compressed data along with the
1690 * header information to this file which will
1691 * later be renamed to the original uncompressed
1694 * The header is as follows -
1696 * Signature (name of the compression algorithm)
1697 * Compression segment size (a multiple of 512)
1698 * Number of index entries
1699 * Size of the last block
1700 * The array containing the index entries
1702 * the header is always stored in network byte
1705 (void) bzero(algorithm
, sizeof (algorithm
));
1706 (void) strlcpy(algorithm
, li
->l_name
, sizeof (algorithm
));
1707 if (write(compfd
, algorithm
, sizeof (algorithm
))
1708 != sizeof (algorithm
))
1711 segsize
= htonl(segsize
);
1712 if (write(compfd
, &segsize
, sizeof (segsize
)) != sizeof (segsize
))
1715 index_entries
= htonl(count
);
1716 if (write(compfd
, &index_entries
, sizeof (index_entries
)) !=
1717 sizeof (index_entries
))
1720 lastread
= htonl(lastread
);
1721 if (write(compfd
, &lastread
, sizeof (lastread
)) != sizeof (lastread
))
1724 for (i
= 0; i
< count
; i
++) {
1725 if (write(compfd
, index
+ i
, sizeof (*index
)) !=
1730 /* Header is written, now write the compressed data */
1731 if (lseek(tfd
, 0, SEEK_SET
) != 0)
1734 rbytes
= wbytes
= 0;
1737 rbytes
= read(tfd
, compressed_seg
, compressed_segsize
+ SEGHDR
);
1742 if (write(compfd
, compressed_seg
, rbytes
) != rbytes
)
1746 if (fstat(compfd
, &statbuf
) == -1)
1750 * Round up the compressed file size to be a multiple of
1751 * DEV_BSIZE. lofi(7D) likes it that way.
1753 if ((offset
= statbuf
.st_size
% DEV_BSIZE
) > 0) {
1755 offset
= DEV_BSIZE
- offset
;
1757 for (i
= 0; i
< offset
; i
++)
1758 uncompressed_seg
[i
] = '\0';
1759 if (write(compfd
, uncompressed_seg
, offset
) != offset
)
1762 (void) close(compfd
);
1764 (void) unlink(tmpfilename
);
1768 (void) unlink(tmpfilename
);
1770 (void) unlink(comp_filename
);
1771 die(gettext("error compressing file %s"), filename
);
1773 /* Rename the compressed file to the actual file */
1774 if (rename(comp_filename
, filename
) == -1) {
1775 (void) unlink(comp_filename
);
1776 die(gettext("error compressing file %s"), filename
);
1779 free(compressed_seg
);
1780 free(uncompressed_seg
);
1783 (void) close(compfd
);
1785 (void) close(uncompfd
);
1791 lofi_compress_select(const char *algname
)
1795 for (i
= 0; i
< LOFI_COMPRESS_FUNCTIONS
; i
++) {
1796 if (strcmp(lofi_compress_table
[i
].l_name
, algname
) == 0)
1803 check_algorithm_validity(const char *algname
, int *compress_index
)
1805 *compress_index
= lofi_compress_select(algname
);
1806 if (*compress_index
< 0)
1807 die(gettext("invalid algorithm name: %s\n"), algname
);
1811 check_file_validity(const char *filename
)
1817 fd
= open(filename
, O_RDONLY
);
1819 die(gettext("open: %s"), filename
);
1821 error
= fstat(fd
, &buf
);
1823 die(gettext("fstat: %s"), filename
);
1824 } else if (!S_ISLOFIABLE(buf
.st_mode
)) {
1825 die(gettext("%s is not a regular file, "
1826 "block, or character device\n"),
1828 } else if ((buf
.st_size
% DEV_BSIZE
) != 0) {
1829 die(gettext("size of %s is not a multiple of %d\n"),
1830 filename
, DEV_BSIZE
);
1834 if (name_to_minor(filename
) != 0) {
1835 die(gettext("cannot use %s on itself\n"), LOFI_DRIVER_NAME
);
1840 check_file_is_encrypted(const char *filename
)
1843 char buf
[sizeof (lofi_crypto_magic
)];
1845 int rest
= sizeof (lofi_crypto_magic
);
1847 fd
= open(filename
, O_RDONLY
);
1849 die(gettext("failed to open: %s"), filename
);
1851 if (lseek(fd
, CRYOFF
, SEEK_SET
) != CRYOFF
)
1852 die(gettext("failed to seek to offset 0x%lx in file %s"),
1856 got
= read(fd
, buf
+ sizeof (lofi_crypto_magic
) - rest
, rest
);
1857 if ((got
== 0) || ((got
== -1) && (errno
!= EINTR
)))
1858 die(gettext("failed to read crypto header"
1859 " at offset 0x%lx in file %s"), CRYOFF
, filename
);
1865 while (close(fd
) == -1) {
1867 die(gettext("failed to close file %s"), filename
);
1870 return (strncmp(buf
, lofi_crypto_magic
,
1871 sizeof (lofi_crypto_magic
)) == 0);
1875 convert_to_num(const char *str
)
1878 uint32_t segsize
, mult
= 1;
1881 if (len
&& isalpha(str
[len
- 1])) {
1882 switch (str
[len
- 1]) {
1900 die(gettext("invalid segment size %s\n"), str
);
1904 segsize
= atol(str
);
1911 main(int argc
, char *argv
[])
1915 const char *devicename
= NULL
;
1916 const char *filename
= NULL
;
1917 const char *algname
= COMPRESS_ALGORITHM
;
1921 uint32_t segsize
= SEGSIZE
;
1922 static char *lofictl
= "/dev/" LOFI_CTL_NAME
;
1923 boolean_t force
= B_FALSE
;
1925 boolean_t errflag
= B_FALSE
;
1926 boolean_t addflag
= B_FALSE
;
1927 boolean_t labelflag
= B_FALSE
;
1928 boolean_t rdflag
= B_FALSE
;
1929 boolean_t deleteflag
= B_FALSE
;
1930 boolean_t ephflag
= B_FALSE
;
1931 boolean_t compressflag
= B_FALSE
;
1932 boolean_t uncompressflag
= B_FALSE
;
1933 /* the next two work together for -c, -k, -T, -e options only */
1934 boolean_t need_crypto
= B_FALSE
; /* if any -c, -k, -T, -e */
1935 boolean_t cipher_only
= B_TRUE
; /* if -c only */
1936 const char *keyfile
= NULL
;
1937 mech_alias_t
*cipher
= NULL
;
1938 token_spec_t
*token
= NULL
;
1941 char realfilename
[MAXPATHLEN
];
1943 pname
= getpname(argv
[0]);
1945 (void) setlocale(LC_ALL
, "");
1946 (void) textdomain(TEXT_DOMAIN
);
1948 while ((c
= getopt(argc
, argv
, "a:c:Cd:efk:lrs:T:U")) != EOF
) {
1952 if ((filename
= realpath(optarg
, realfilename
)) == NULL
)
1954 if (((argc
- optind
) > 0) && (*argv
[optind
] != '-')) {
1955 /* optional device */
1956 devicename
= argv
[optind
];
1961 compressflag
= B_TRUE
;
1962 if (((argc
- optind
) > 1) && (*argv
[optind
] != '-')) {
1963 /* optional algorithm */
1964 algname
= argv
[optind
];
1967 check_algorithm_validity(algname
, &compress_index
);
1970 /* is the chosen cipher allowed? */
1971 if ((cipher
= ciph2mech(optarg
)) == NULL
) {
1973 warn(gettext("cipher %s not allowed\n"),
1976 need_crypto
= B_TRUE
;
1977 /* cipher_only is already set */
1980 deleteflag
= B_TRUE
;
1981 minor
= name_to_minor(optarg
);
1983 devicename
= optarg
;
1985 if ((filename
= realpath(optarg
,
1986 realfilename
)) == NULL
)
1992 need_crypto
= B_TRUE
;
1993 cipher_only
= B_FALSE
; /* need to unset cipher_only */
2000 need_crypto
= B_TRUE
;
2001 cipher_only
= B_FALSE
; /* need to unset cipher_only */
2010 segsize
= convert_to_num(optarg
);
2011 if (segsize
< DEV_BSIZE
|| !ISP2(segsize
))
2012 die(gettext("segment size %s is invalid "
2013 "or not a multiple of minimum block "
2014 "size %ld\n"), optarg
, DEV_BSIZE
);
2017 if ((token
= parsetoken(optarg
)) == NULL
) {
2020 gettext("invalid token key specifier %s\n"),
2023 need_crypto
= B_TRUE
;
2024 cipher_only
= B_FALSE
; /* need to unset cipher_only */
2027 uncompressflag
= B_TRUE
;
2036 /* Check for mutually exclusive combinations of options */
2038 (addflag
&& deleteflag
) ||
2039 (labelflag
&& !addflag
) ||
2040 (rdflag
&& !addflag
) ||
2041 (!addflag
&& need_crypto
) ||
2042 (need_crypto
&& labelflag
) ||
2043 ((compressflag
|| uncompressflag
) &&
2044 (labelflag
|| addflag
|| deleteflag
)))
2047 /* ephemeral key, and key from either file or token are incompatible */
2048 if (ephflag
&& (keyfile
!= NULL
|| token
!= NULL
)) {
2049 die(gettext("ephemeral key cannot be used with keyfile"
2050 " or token key\n"));
2054 * "-c" but no "-k", "-T", "-e", or "-T -k" means derive key from
2055 * command line passphrase
2058 switch (argc
- optind
) {
2059 case 0: /* no more args */
2060 if (compressflag
|| uncompressflag
) /* needs filename */
2064 if (addflag
|| deleteflag
)
2066 /* one arg means compress/uncompress the file ... */
2067 if (compressflag
|| uncompressflag
) {
2068 if ((filename
= realpath(argv
[optind
],
2069 realfilename
)) == NULL
)
2070 die("%s", argv
[optind
]);
2071 /* ... or without options means print the association */
2073 minor
= name_to_minor(argv
[optind
]);
2075 devicename
= argv
[optind
];
2077 if ((filename
= realpath(argv
[optind
],
2078 realfilename
)) == NULL
)
2079 die("%s", argv
[optind
]);
2088 if (addflag
|| compressflag
|| uncompressflag
)
2089 check_file_validity(filename
);
2091 if (filename
&& !valid_abspath(filename
))
2095 * Here, we know the arguments are correct, the filename is an
2096 * absolute path, it exists and is a regular file. We don't yet
2097 * know that the device name is ok or not.
2101 if (addflag
|| deleteflag
|| compressflag
|| uncompressflag
)
2104 openflag
|= O_RDONLY
;
2105 lfd
= open(lofictl
, openflag
);
2107 if ((errno
== EPERM
) || (errno
== EACCES
)) {
2108 die(gettext("you do not have permission to perform "
2109 "that operation.\n"));
2111 die(gettext("open: %s"), lofictl
);
2117 * No passphrase is needed for ephemeral key, or when key is
2118 * in a file and not wrapped by another key from a token.
2119 * However, a passphrase is needed in these cases:
2120 * 1. cipher with no ephemeral key, key file, or token,
2121 * in which case the passphrase is used to build the key
2122 * 2. token with an optional cipher or optional key file,
2123 * in which case the passphrase unlocks the token
2124 * If only the cipher is specified, reconfirm the passphrase
2125 * to ensure the user hasn't mis-entered it. Otherwise, the
2126 * token will enforce the token passphrase.
2129 CK_SESSION_HANDLE sess
;
2131 /* pick a cipher if none specified */
2133 cipher
= DEFAULT_CIPHER
;
2135 if (!kernel_cipher_check(cipher
))
2137 "use \"cryptoadm list -m\" to find available "
2140 init_crypto(token
, cipher
, &sess
);
2143 getkeyfromuser(cipher
, &rkey
, &rksz
,
2144 !check_file_is_encrypted(filename
));
2145 } else if (token
!= NULL
) {
2146 getkeyfromtoken(sess
, token
, keyfile
, cipher
,
2149 /* this also handles ephemeral keys */
2150 getkeyfromfile(keyfile
, cipher
, &rkey
, &rksz
);
2157 * Now to the real work.
2160 add_mapping(lfd
, devicename
, filename
, cipher
, rkey
, rksz
,
2162 else if (compressflag
)
2163 lofi_compress(&lfd
, filename
, compress_index
, segsize
);
2164 else if (uncompressflag
)
2165 lofi_uncompress(lfd
, filename
);
2166 else if (deleteflag
)
2167 delete_mapping(lfd
, devicename
, filename
, force
);
2168 else if (filename
|| devicename
)
2169 print_one_mapping(lfd
, devicename
, filename
);
2171 print_mappings(lfd
);