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 <netinet/in.h>
53 #include <libdevinfo.h>
58 #include <security/cryptoki.h>
59 #include <cryptoutil.h>
60 #include <sys/crypto/ioctl.h>
61 #include <sys/crypto/ioctladmin.h>
63 #include <sys/mkdev.h>
67 /* Only need the IV len #defines out of these files, nothing else. */
68 #include <aes/aes_impl.h>
69 #include <des/des_impl.h>
70 #include <blowfish/blowfish_impl.h>
72 static const char USAGE
[] =
73 "Usage: %s [-r] [-l] -a file [ device ]\n"
74 " %s [-r] -c crypto_algorithm -a file [device]\n"
75 " %s [-r] -c crypto_algorithm -k raw_key_file -a file [device]\n"
76 " %s [-r] -c crypto_algorithm -T [token]:[manuf]:[serial]:key "
78 " %s [-r] -c crypto_algorithm -T [token]:[manuf]:[serial]:key "
79 "-k wrapped_key_file -a file [device]\n"
80 " %s [-r] -c crypto_algorithm -e -a file [device]\n"
81 " %s -d file | device\n"
82 " %s -C [gzip|gzip-6|gzip-9|lzma] [-s segment_size] file\n"
84 " %s [ file | device ]\n";
86 typedef struct token_spec
{
93 typedef struct mech_alias
{
95 CK_MECHANISM_TYPE type
;
96 char *name
; /* for ioctl */
97 char *iv_name
; /* for ioctl */
98 size_t iv_len
; /* for ioctl */
99 iv_method_t iv_type
; /* for ioctl */
100 size_t min_keysize
; /* in bytes */
101 size_t max_keysize
; /* in bytes */
106 static mech_alias_t mech_aliases
[] = {
107 /* Preferred one should always be listed first. */
108 { "aes-256-cbc", CKM_AES_CBC
, "CKM_AES_CBC", "CKM_AES_ECB", AES_IV_LEN
,
109 IVM_ENC_BLKNO
, ULONG_MAX
, 0L, NULL
, (CK_SLOT_ID
) -1 },
110 { "aes-192-cbc", CKM_AES_CBC
, "CKM_AES_CBC", "CKM_AES_ECB", AES_IV_LEN
,
111 IVM_ENC_BLKNO
, ULONG_MAX
, 0L, NULL
, (CK_SLOT_ID
) -1 },
112 { "aes-128-cbc", CKM_AES_CBC
, "CKM_AES_CBC", "CKM_AES_ECB", AES_IV_LEN
,
113 IVM_ENC_BLKNO
, ULONG_MAX
, 0L, NULL
, (CK_SLOT_ID
) -1 },
114 { "des3-cbc", CKM_DES3_CBC
, "CKM_DES3_CBC", "CKM_DES3_ECB", DES_IV_LEN
,
115 IVM_ENC_BLKNO
, ULONG_MAX
, 0L, NULL
, (CK_SLOT_ID
)-1 },
116 { "blowfish-cbc", CKM_BLOWFISH_CBC
, "CKM_BLOWFISH_CBC",
117 "CKM_BLOWFISH_ECB", BLOWFISH_IV_LEN
, IVM_ENC_BLKNO
, ULONG_MAX
,
118 0L, NULL
, (CK_SLOT_ID
)-1 }
120 * A cipher without an iv requirement would look like this:
121 * { "aes-xex", CKM_AES_XEX, "CKM_AES_XEX", NULL, 0,
122 * IVM_NONE, ULONG_MAX, 0L, NULL, (CK_SLOT_ID)-1 }
126 int mech_aliases_count
= (sizeof (mech_aliases
) / sizeof (mech_alias_t
));
128 /* Preferred cipher, if one isn't specified on command line. */
129 #define DEFAULT_CIPHER (&mech_aliases[0])
131 #define DEFAULT_CIPHER_NUM 64 /* guess # kernel ciphers available */
132 #define DEFAULT_MECHINFO_NUM 16 /* guess # kernel mechs available */
133 #define MIN_PASSLEN 8 /* min acceptable passphrase size */
135 static int gzip_compress(void *src
, size_t srclen
, void *dst
,
136 size_t *destlen
, int level
);
137 static int lzma_compress(void *src
, size_t srclen
, void *dst
,
138 size_t *destlen
, int level
);
140 lofi_compress_info_t lofi_compress_table
[LOFI_COMPRESS_FUNCTIONS
] = {
141 {NULL
, gzip_compress
, 6, "gzip"}, /* default */
142 {NULL
, gzip_compress
, 6, "gzip-6"},
143 {NULL
, gzip_compress
, 9, "gzip-9"},
144 {NULL
, lzma_compress
, 0, "lzma"}
147 /* For displaying lofi mappings */
148 #define FORMAT "%-20s %-30s %s\n"
150 #define COMPRESS_ALGORITHM "gzip"
151 #define COMPRESS_THRESHOLD 2048
152 #define SEGSIZE 131072
153 #define BLOCK_SIZE 512
154 #define KILOBYTE 1024
155 #define MEGABYTE (KILOBYTE * KILOBYTE)
156 #define GIGABYTE (KILOBYTE * MEGABYTE)
157 #define LIBZ "libz.so.1"
159 const char lofi_crypto_magic
[6] = LOFI_CRYPTO_MAGIC
;
162 usage(const char *pname
)
164 (void) fprintf(stderr
, gettext(USAGE
), pname
, pname
, pname
,
165 pname
, pname
, pname
, pname
, pname
, pname
, pname
);
170 gzip_compress(void *src
, size_t srclen
, void *dst
, size_t *dstlen
, int level
)
172 static int (*compress2p
)(void *, ulong_t
*, void *, size_t, int) = NULL
;
173 void *libz_hdl
= NULL
;
176 * The first time we are called, attempt to dlopen()
177 * libz.so.1 and get a pointer to the compress2() function
179 if (compress2p
== NULL
) {
180 if ((libz_hdl
= openlib(LIBZ
)) == NULL
)
181 die(gettext("could not find %s. "
182 "gzip compression unavailable\n"), LIBZ
);
185 (int (*)(void *, ulong_t
*, void *, size_t, int))
186 dlsym(libz_hdl
, "compress2")) == NULL
) {
188 die(gettext("could not find the correct %s. "
189 "gzip compression unavailable\n"), LIBZ
);
193 if ((*compress2p
)(dst
, (ulong_t
*)dstlen
, src
, srclen
, level
) != 0)
200 *SzAlloc(void *p
, size_t size
)
202 return (malloc(size
));
207 SzFree(void *p
, void *address
, size_t size
)
212 static ISzAlloc g_Alloc
= {
217 #define LZMA_UNCOMPRESSED_SIZE 8
218 #define LZMA_HEADER_SIZE (LZMA_PROPS_SIZE + LZMA_UNCOMPRESSED_SIZE)
222 lzma_compress(void *src
, size_t srclen
, void *dst
,
223 size_t *dstlen
, int level
)
227 size_t outsizeprocessed
;
228 size_t outpropssize
= LZMA_PROPS_SIZE
;
236 LzmaEncProps_Init(&props
);
239 * The LZMA compressed file format is as follows -
241 * Offset Size(bytes) Description
242 * 0 1 LZMA properties (lc, lp, lp (encoded))
243 * 1 4 Dictionary size (little endian)
244 * 5 8 Uncompressed size (little endian)
248 /* set the dictionary size to be 8MB */
249 props
.dictSize
= 1 << 23;
251 if (*dstlen
< LZMA_HEADER_SIZE
)
252 return (SZ_ERROR_OUTPUT_EOF
);
257 * Set the uncompressed size in the LZMA header
258 * The LZMA properties (specified in 'props')
259 * will be set by the call to LzmaEncode()
261 for (i
= 0; i
< LZMA_UNCOMPRESSED_SIZE
; i
++, t
>>= 8) {
262 dstp
[LZMA_PROPS_SIZE
+ i
] = (Byte
)t
;
265 outsizeprocessed
= outsize2
- LZMA_HEADER_SIZE
;
266 res
= LzmaEncode(dstp
+ LZMA_HEADER_SIZE
, &outsizeprocessed
,
267 src
, srclen
, &props
, dstp
, &outpropssize
, 0, NULL
,
273 *dstlen
= outsizeprocessed
+ LZMA_HEADER_SIZE
;
278 * Translate a lofi device name to a minor number. We might be asked
279 * to do this when there is no association (such as when the user specifies
280 * a particular device), so we can only look at the string.
283 name_to_minor(const char *devicename
)
288 * If devicename does not exist, then devicename contains
289 * the name of the device to be created.
290 * Note we only allow non-labeled devices here.
292 if (stat(devicename
, &st
)) {
295 rv
= sscanf(devicename
, "/dev/" LOFI_BLOCK_NAME
"/%d", &minor
);
298 rv
= sscanf(devicename
, "/dev/" LOFI_CHAR_NAME
"/%d", &minor
);
305 if (st
.st_mode
& S_IFCHR
|| st
.st_mode
& S_IFBLK
) {
306 return (LOFI_MINOR2ID(minor(st
.st_rdev
)));
313 * This might be the first time we've used this minor number. If so,
314 * it might also be that the /dev links are in the process of being created
315 * by devfsadmd (or that they'll be created "soon"). We cannot return
316 * until they're there or the invoker of lofiadm might try to use them
317 * and not find them. This can happen if a shell script is running on
320 static int sleeptime
= 2; /* number of seconds to sleep between stat's */
321 static int maxsleep
= 120; /* maximum number of seconds to sleep */
324 make_blkdevname(struct lofi_ioctl
*li
, char *path
, size_t len
)
329 if (li
->li_devpath
[0] == '\0') {
331 (void) strlcpy(path
, "unknown", len
);
333 (void) snprintf(path
, len
,
334 "/dev/" LOFI_BLOCK_NAME
"/%d", li
->li_id
);
337 (void) strlcpy(path
, li
->li_devpath
, len
);
338 r1
= strchr(path
, 'r');
340 r2
= strchr(li
->li_devpath
, 'r');
341 (void) strlcpy(r1
, r2
+1, len
- l1
);
343 if (li
->li_labeled
) {
344 (void) strlcat(path
, "p0", len
);
349 wait_until_dev_complete(struct lofi_ioctl
*li
)
353 char blkpath
[MAXPATHLEN
];
354 char charpath
[MAXPATHLEN
];
355 di_devlink_handle_t hdl
;
357 make_blkdevname(li
, blkpath
, sizeof (blkpath
));
358 (void) strlcpy(charpath
, li
->li_devpath
, sizeof (charpath
));
360 if (li
->li_labeled
) {
361 (void) strlcat(charpath
, "p0", sizeof (charpath
));
364 /* Check if links already present */
365 if (stat64(blkpath
, &buf
) == 0 && stat64(charpath
, &buf
) == 0)
368 /* First use di_devlink_init() */
369 if (hdl
= di_devlink_init("lofi", DI_MAKE_LINK
)) {
370 (void) di_devlink_fini(&hdl
);
375 * Under normal conditions, di_devlink_init(DI_MAKE_LINK) above will
376 * only fail if the caller is non-root. In that case, wait for
377 * link creation via sysevents.
379 for (cursleep
= 0; cursleep
< maxsleep
; cursleep
+= sleeptime
) {
380 if (stat64(blkpath
, &buf
) == 0 && stat64(charpath
, &buf
) == 0)
382 (void) sleep(sleeptime
);
387 if (stat64(blkpath
, &buf
) == -1) {
388 die(gettext("%s was not created"), blkpath
);
390 if (stat64(charpath
, &buf
) == -1) {
391 die(gettext("%s was not created"), charpath
);
396 * Map the file and return the minor number the driver picked for the file
397 * DO NOT use this function if the filename is actually the device name.
400 lofi_map_file(int lfd
, struct lofi_ioctl
*li
, const char *filename
)
405 (void) strlcpy(li
->li_filename
, filename
, sizeof (li
->li_filename
));
406 minor
= ioctl(lfd
, LOFI_MAP_FILE
, li
);
408 if (errno
== ENOTSUP
)
409 warn(gettext("encrypting compressed files is "
411 die(gettext("could not map file %s"), filename
);
413 wait_until_dev_complete(li
);
418 * Add a device association. If devicename is NULL, let the driver
422 add_mapping(int lfd
, const char *devicename
, const char *filename
,
423 mech_alias_t
*cipher
, const char *rkey
, size_t rksz
, boolean_t rdonly
,
426 struct lofi_ioctl li
;
428 bzero(&li
, sizeof (li
));
429 li
.li_readonly
= rdonly
;
430 li
.li_labeled
= label
;
432 li
.li_crypto_enabled
= B_FALSE
;
433 if (cipher
!= NULL
) {
434 /* set up encryption for mapped file */
435 li
.li_crypto_enabled
= B_TRUE
;
436 (void) strlcpy(li
.li_cipher
, cipher
->name
,
437 sizeof (li
.li_cipher
));
438 if (rksz
> sizeof (li
.li_key
)) {
439 die(gettext("key too large"));
441 bcopy(rkey
, li
.li_key
, rksz
);
442 li
.li_key_len
= rksz
<< 3; /* convert to bits */
444 li
.li_iv_type
= cipher
->iv_type
;
445 li
.li_iv_len
= cipher
->iv_len
; /* 0 when no iv needed */
446 switch (cipher
->iv_type
) {
448 (void) strlcpy(li
.li_iv_cipher
, cipher
->iv_name
,
449 sizeof (li
.li_iv_cipher
));
458 if (devicename
== NULL
) {
460 char path
[MAXPATHLEN
];
462 /* pick one via the driver */
463 minor
= lofi_map_file(lfd
, &li
, filename
);
465 make_blkdevname(&li
, path
, sizeof (path
));
467 /* if mapping succeeds, print the one picked */
468 (void) printf("%s\n", path
);
473 /* use device we were given */
474 li
.li_id
= name_to_minor(devicename
);
476 die(gettext("malformed device name %s\n"), devicename
);
478 (void) strlcpy(li
.li_filename
, filename
, sizeof (li
.li_filename
));
480 /* if device is already in use li.li_minor won't change */
481 if (ioctl(lfd
, LOFI_MAP_FILE_MINOR
, &li
) == -1) {
482 if (errno
== ENOTSUP
)
483 warn(gettext("encrypting compressed files is "
485 die(gettext("could not map file %s to %s"), filename
,
488 wait_until_dev_complete(&li
);
492 * Remove an association. Delete by device name if non-NULL, or by
493 * filename otherwise.
496 delete_mapping(int lfd
, const char *devicename
, const char *filename
,
499 struct lofi_ioctl li
;
502 li
.li_cleanup
= B_FALSE
;
504 if (devicename
== NULL
) {
505 /* delete by filename */
506 (void) strlcpy(li
.li_filename
, filename
,
507 sizeof (li
.li_filename
));
509 if (ioctl(lfd
, LOFI_UNMAP_FILE
, &li
) == -1) {
510 die(gettext("could not unmap file %s"), filename
);
515 /* delete by device */
516 li
.li_id
= name_to_minor(devicename
);
518 die(gettext("malformed device name %s\n"), devicename
);
520 if (ioctl(lfd
, LOFI_UNMAP_FILE_MINOR
, &li
) == -1) {
521 die(gettext("could not unmap device %s"), devicename
);
526 * Show filename given devicename, or devicename given filename.
529 print_one_mapping(int lfd
, const char *devicename
, const char *filename
)
531 struct lofi_ioctl li
;
532 char blkpath
[MAXPATHLEN
];
534 if (devicename
== NULL
) {
535 /* given filename, print devicename */
537 (void) strlcpy(li
.li_filename
, filename
,
538 sizeof (li
.li_filename
));
539 if (ioctl(lfd
, LOFI_GET_MINOR
, &li
) == -1) {
540 die(gettext("could not find device for %s"), filename
);
542 make_blkdevname(&li
, blkpath
, sizeof (blkpath
));
543 (void) printf("%s\n", blkpath
);
547 /* given devicename, print filename */
548 li
.li_id
= name_to_minor(devicename
);
550 die(gettext("malformed device name %s\n"), devicename
);
552 if (ioctl(lfd
, LOFI_GET_FILENAME
, &li
) == -1) {
553 die(gettext("could not find filename for %s"), devicename
);
555 (void) printf("%s\n", li
.li_filename
);
559 * Print the list of all the mappings, including a header.
562 print_mappings(int fd
)
564 struct lofi_ioctl li
;
567 char path
[MAXPATHLEN
];
568 char options
[MAXPATHLEN
] = { 0 };
571 if (ioctl(fd
, LOFI_GET_MAXMINOR
, &li
) == -1) {
576 (void) printf(FORMAT
, gettext("Block Device"), gettext("File"),
578 for (minor
= 1; minor
<= maxminor
; minor
++) {
580 if (ioctl(fd
, LOFI_GET_FILENAME
, &li
) == -1) {
586 make_blkdevname(&li
, path
, sizeof (path
));
591 * Encrypted lofi and compressed lofi are mutually exclusive.
593 if (li
.li_crypto_enabled
)
594 (void) snprintf(options
, sizeof (options
),
595 gettext("Encrypted"));
596 else if (li
.li_algorithm
[0] != '\0')
597 (void) snprintf(options
, sizeof (options
),
598 gettext("Compressed(%s)"), li
.li_algorithm
);
599 if (li
.li_readonly
) {
600 if (strlen(options
) != 0) {
601 (void) strlcat(options
, ",Readonly",
604 (void) snprintf(options
, sizeof (options
),
605 gettext("Readonly"));
609 if (strlen(options
) != 0) {
610 (void) strlcat(options
, ",Labeled",
613 (void) snprintf(options
, sizeof (options
),
617 if (strlen(options
) == 0)
618 (void) snprintf(options
, sizeof (options
), "-");
620 (void) printf(FORMAT
, path
, li
.li_filename
, options
);
625 * Verify the cipher selected by user.
627 static mech_alias_t
*
628 ciph2mech(const char *alias
)
632 for (i
= 0; i
< mech_aliases_count
; i
++) {
633 if (strcasecmp(alias
, mech_aliases
[i
].alias
) == 0)
634 return (&mech_aliases
[i
]);
640 * Verify user selected cipher is also available in kernel.
642 * While traversing kernel list of mechs, if the cipher is supported in the
643 * kernel for both encryption and decryption, it also picks up the min/max
647 kernel_cipher_check(mech_alias_t
*cipher
)
649 boolean_t ciph_ok
= B_FALSE
;
650 boolean_t iv_ok
= B_FALSE
;
653 crypto_get_mechanism_list_t
*kciphers
= NULL
;
654 crypto_get_all_mechanism_info_t
*kinfo
= NULL
;
659 /* if cipher doesn't need iv generating mech, bypass that check now */
660 if (cipher
->iv_name
== NULL
)
663 /* allocate some space for the list of kernel ciphers */
664 count
= DEFAULT_CIPHER_NUM
;
665 kciphers
= malloc(sizeof (crypto_get_mechanism_list_t
) +
666 sizeof (crypto_mech_name_t
) * (count
- 1));
667 if (kciphers
== NULL
)
668 die(gettext("failed to allocate memory for list of "
669 "kernel mechanisms"));
670 kciphers
->ml_count
= count
;
672 /* query crypto device to get list of kernel ciphers */
673 if ((fd
= open("/dev/crypto", O_RDWR
)) == -1) {
674 warn(gettext("failed to open %s"), "/dev/crypto");
678 if (ioctl(fd
, CRYPTO_GET_MECHANISM_LIST
, kciphers
) == -1) {
679 warn(gettext("CRYPTO_GET_MECHANISM_LIST ioctl failed"));
683 if (kciphers
->ml_return_value
== CRYPTO_BUFFER_TOO_SMALL
) {
684 count
= kciphers
->ml_count
;
686 kciphers
= malloc(sizeof (crypto_get_mechanism_list_t
) +
687 sizeof (crypto_mech_name_t
) * (count
- 1));
688 if (kciphers
== NULL
) {
689 warn(gettext("failed to allocate memory for list of "
690 "kernel mechanisms"));
693 kciphers
->ml_count
= count
;
695 if (ioctl(fd
, CRYPTO_GET_MECHANISM_LIST
, kciphers
) == -1) {
696 warn(gettext("CRYPTO_GET_MECHANISM_LIST ioctl failed"));
701 if (kciphers
->ml_return_value
!= CRYPTO_SUCCESS
) {
703 "CRYPTO_GET_MECHANISM_LIST ioctl return value = %d\n"),
704 kciphers
->ml_return_value
);
709 * scan list of kernel ciphers looking for the selected one and if
710 * it needs an iv generated using another cipher, also look for that
711 * additional cipher to be used for generating the iv
713 count
= kciphers
->ml_count
;
714 for (i
= 0; i
< count
&& !(ciph_ok
&& iv_ok
); i
++) {
716 strcasecmp(cipher
->name
, kciphers
->ml_list
[i
]) == 0)
719 strcasecmp(cipher
->iv_name
, kciphers
->ml_list
[i
]) == 0)
726 warn(gettext("%s mechanism not supported in kernel\n"),
729 warn(gettext("%s mechanism not supported in kernel\n"),
733 /* Get the details about the user selected cipher */
734 count
= DEFAULT_MECHINFO_NUM
;
735 kinfo
= malloc(sizeof (crypto_get_all_mechanism_info_t
) +
736 sizeof (crypto_mechanism_info_t
) * (count
- 1));
738 warn(gettext("failed to allocate memory for "
739 "kernel mechanism info"));
742 kinfo
->mi_count
= count
;
743 (void) strlcpy(kinfo
->mi_mechanism_name
, cipher
->name
,
744 CRYPTO_MAX_MECH_NAME
);
746 if (ioctl(fd
, CRYPTO_GET_ALL_MECHANISM_INFO
, kinfo
) == -1) {
748 "CRYPTO_GET_ALL_MECHANISM_INFO ioctl failed"));
752 if (kinfo
->mi_return_value
== CRYPTO_BUFFER_TOO_SMALL
) {
753 count
= kinfo
->mi_count
;
756 sizeof (crypto_get_all_mechanism_info_t
) +
757 sizeof (crypto_mechanism_info_t
) * (count
- 1));
759 warn(gettext("failed to allocate memory for "
760 "kernel mechanism info"));
763 kinfo
->mi_count
= count
;
764 (void) strlcpy(kinfo
->mi_mechanism_name
, cipher
->name
,
765 CRYPTO_MAX_MECH_NAME
);
767 if (ioctl(fd
, CRYPTO_GET_ALL_MECHANISM_INFO
, kinfo
) ==
769 warn(gettext("CRYPTO_GET_ALL_MECHANISM_INFO "
775 if (kinfo
->mi_return_value
!= CRYPTO_SUCCESS
) {
776 warn(gettext("CRYPTO_GET_ALL_MECHANISM_INFO ioctl "
777 "return value = %d\n"), kinfo
->mi_return_value
);
781 /* Set key min and max size */
782 count
= kinfo
->mi_count
;
785 keymin
= kinfo
->mi_list
[i
].mi_min_key_size
;
786 keymax
= kinfo
->mi_list
[i
].mi_max_key_size
;
787 if (kinfo
->mi_list
[i
].mi_keysize_unit
&
788 CRYPTO_KEYSIZE_UNIT_IN_BITS
) {
789 keymin
= CRYPTO_BITS2BYTES(keymin
);
790 keymax
= CRYPTO_BITS2BYTES(keymax
);
793 cipher
->min_keysize
= keymin
;
794 cipher
->max_keysize
= keymax
;
802 "failed to find usable %s kernel mechanism, "
803 "use \"cryptoadm list -m\" to find available "
809 /* Note: key min/max, unit size, usage for iv cipher are not checked. */
811 return (ciph_ok
&& iv_ok
);
816 if (kciphers
!= NULL
)
824 * Break up token spec into its components (non-destructive)
826 static token_spec_t
*
827 parsetoken(char *spec
)
834 #define nullfield(i) ((field[(i)+1] - field[(i)]) <= 1)
835 #define copyfield(fld, i) \
839 if ((n = (field[(i)+1] - field[(i)])) > 1) { \
840 if (((fld) = malloc(n)) != NULL) { \
841 (void) strncpy((fld), field[(i)], n); \
842 ((fld))[n - 1] = '\0'; \
848 char *field
[NFIELDS
+ 1]; /* +1 to catch extra delimiters */
849 token_spec_t
*ti
= NULL
;
855 * Correct format is "[name]:[manuf]:[serial]:key". Can't use
856 * strtok because it treats ":::key" and "key:::" and "key" all
857 * as the same thing, and we can't have the :s compressed away.
860 for (i
= 1; i
< NFIELDS
+ 1; i
++) {
861 field
[i
] = strchr(field
[i
-1], ':');
862 if (field
[i
] == NULL
)
866 if (i
< NFIELDS
) /* not enough fields */
868 if (field
[NFIELDS
] != NULL
) /* too many fields */
870 field
[NFIELDS
] = strchr(field
[NFIELDS
-1], '\0') + 1;
872 /* key label can't be empty */
873 if (nullfield(FLD_LABEL
))
876 ti
= malloc(sizeof (token_spec_t
));
880 copyfield(ti
->name
, FLD_NAME
);
881 copyfield(ti
->mfr
, FLD_MANUF
);
882 copyfield(ti
->serno
, FLD_SERIAL
);
883 copyfield(ti
->key
, FLD_LABEL
);
886 * If token specified and it only contains a key label, then
887 * search all tokens for the key, otherwise only those with
888 * matching name, mfr, and serno are used.
891 * That's how we'd like it to be, however, if only the key label
892 * is specified, default to using softtoken. It's easier.
894 if (ti
->name
== NULL
&& ti
->mfr
== NULL
&& ti
->serno
== NULL
)
895 ti
->name
= strdup(pkcs11_default_token());
900 * PBE the passphrase into a raw key
903 getkeyfromuser(mech_alias_t
*cipher
, char **raw_key
, size_t *raw_key_sz
,
904 boolean_t with_confirmation
)
906 CK_SESSION_HANDLE sess
;
910 void *salt
= NULL
; /* don't use NULL, see note on salt below */
916 /* did init_crypto find a slot that supports this cipher? */
917 if (cipher
->slot
== (CK_SLOT_ID
)-1 || cipher
->max_keysize
== 0) {
918 rv
= CKR_MECHANISM_INVALID
;
922 rv
= pkcs11_mech2keytype(cipher
->type
, &ktype
);
927 * use the passphrase to generate a PBE PKCS#5 secret key and
928 * retrieve the raw key data to eventually pass it to the kernel;
930 rv
= C_OpenSession(cipher
->slot
, CKF_SERIAL_SESSION
, NULL
, NULL
, &sess
);
934 /* get user passphrase with 8 byte minimum */
935 if (pkcs11_get_pass(NULL
, &pass
, &passlen
, MIN_PASSLEN
,
936 with_confirmation
) < 0) {
937 die(gettext("passphrases do not match\n"));
941 * salt should not be NULL, or else pkcs11_PasswdToKey() will
942 * complain about CKR_MECHANISM_PARAM_INVALID; the following is
943 * to make up for not having a salt until a proper one is used
948 klen
= cipher
->max_keysize
;
949 rv
= pkcs11_PasswdToKey(sess
, pass
, passlen
, salt
, saltlen
, ktype
,
950 cipher
->max_keysize
, &kvalue
, &klen
);
952 (void) C_CloseSession(sess
);
958 /* assert(klen == cipher->max_keysize); */
960 *raw_key
= (char *)kvalue
;
964 die(gettext("failed to generate %s key from passphrase: %s"),
965 cipher
->alias
, pkcs11_strerror(rv
));
969 * Read raw key from file; also handles ephemeral keys.
972 getkeyfromfile(const char *pathname
, mech_alias_t
*cipher
, char **key
,
977 boolean_t notplain
= B_FALSE
;
981 /* ephemeral keys are just random data */
982 if (pathname
== NULL
) {
983 *ksz
= cipher
->max_keysize
;
986 die(gettext("failed to allocate memory for"
988 if (pkcs11_get_urandom(*key
, *ksz
) < 0) {
990 die(gettext("failed to get enough random data"));
996 * If the remaining section of code didn't also check for secure keyfile
997 * permissions and whether the key is within cipher min and max lengths,
998 * (or, if those things moved out of this block), we could have had:
999 * if (pkcs11_read_data(pathname, key, ksz) < 0)
1003 if ((fd
= open(pathname
, O_RDONLY
, 0)) == -1)
1004 die(gettext("open of keyfile (%s) failed"), pathname
);
1006 if (fstat(fd
, &sbuf
) == -1)
1007 die(gettext("fstat of keyfile (%s) failed"), pathname
);
1009 if (S_ISREG(sbuf
.st_mode
)) {
1010 if ((sbuf
.st_mode
& (S_IWGRP
| S_IWOTH
)) != 0)
1011 die(gettext("insecure permissions on keyfile %s\n"),
1014 *ksz
= sbuf
.st_size
;
1015 if (*ksz
< cipher
->min_keysize
|| cipher
->max_keysize
< *ksz
) {
1016 warn(gettext("%s: invalid keysize: %d\n"),
1017 pathname
, (int)*ksz
);
1018 die(gettext("\t%d <= keysize <= %d\n"),
1019 cipher
->min_keysize
, cipher
->max_keysize
);
1022 *ksz
= cipher
->max_keysize
;
1026 *key
= malloc(*ksz
);
1028 die(gettext("failed to allocate memory for key from file"));
1030 for (cursz
= 0, nread
= 0; cursz
< *ksz
; cursz
+= nread
) {
1031 nread
= read(fd
, *key
, *ksz
);
1035 * nread == 0. If it's not a regular file we were trying to
1036 * get the maximum keysize of data possible for this cipher.
1037 * But if we've got at least the minimum keysize of data,
1038 * round down to the nearest keysize unit and call it good.
1039 * If we haven't met the minimum keysize, that's an error.
1040 * If it's a regular file, nread = 0 is also an error.
1042 if (nread
== 0 && notplain
&& cursz
>= cipher
->min_keysize
) {
1043 *ksz
= (cursz
/ cipher
->min_keysize
) *
1044 cipher
->min_keysize
;
1047 die(gettext("%s: can't read all keybytes"), pathname
);
1053 * Read the raw key from token, or from a file that was wrapped with a
1057 getkeyfromtoken(CK_SESSION_HANDLE sess
,
1058 token_spec_t
*token
, const char *keyfile
, mech_alias_t
*cipher
,
1059 char **raw_key
, size_t *raw_key_sz
)
1062 CK_BBOOL trueval
= B_TRUE
;
1063 CK_OBJECT_CLASS kclass
; /* secret key or RSA private key */
1064 CK_KEY_TYPE ktype
; /* from selected cipher or CKK_RSA */
1065 CK_KEY_TYPE raw_ktype
; /* from selected cipher */
1066 CK_ATTRIBUTE key_tmpl
[] = {
1067 { CKA_CLASS
, NULL
, 0 }, /* re-used for token key and unwrap */
1068 { CKA_KEY_TYPE
, NULL
, 0 }, /* ditto */
1069 { CKA_LABEL
, NULL
, 0 },
1070 { CKA_TOKEN
, NULL
, 0 },
1071 { CKA_PRIVATE
, NULL
, 0 }
1073 CK_ULONG attrs
= sizeof (key_tmpl
) / sizeof (CK_ATTRIBUTE
);
1077 CK_OBJECT_HANDLE obj
, rawobj
;
1078 CK_ULONG num_objs
= 1; /* just want to find 1 token key */
1079 CK_MECHANISM unwrap
= { CKM_RSA_PKCS
, NULL
, 0 };
1083 if (token
== NULL
|| token
->key
== NULL
)
1086 /* did init_crypto find a slot that supports this cipher? */
1087 if (cipher
->slot
== (CK_SLOT_ID
)-1 || cipher
->max_keysize
== 0) {
1088 die(gettext("failed to find any cryptographic provider, "
1089 "use \"cryptoadm list -p\" to find providers: %s\n"),
1090 pkcs11_strerror(CKR_MECHANISM_INVALID
));
1093 if (pkcs11_get_pass(token
->name
, &pass
, &passlen
, 0, B_FALSE
) < 0)
1094 die(gettext("unable to get passphrase"));
1096 /* use passphrase to login to token */
1097 if (pass
!= NULL
&& passlen
> 0) {
1098 rv
= C_Login(sess
, CKU_USER
, (CK_UTF8CHAR_PTR
)pass
, passlen
);
1100 die(gettext("cannot login to the token %s: %s\n"),
1101 token
->name
, pkcs11_strerror(rv
));
1105 rv
= pkcs11_mech2keytype(cipher
->type
, &raw_ktype
);
1107 die(gettext("failed to get key type for cipher %s: %s\n"),
1108 cipher
->name
, pkcs11_strerror(rv
));
1112 * If no keyfile was given, then the token key is secret key to
1113 * be used for encryption/decryption. Otherwise, the keyfile
1114 * contains a wrapped secret key, and the token is actually the
1115 * unwrapping RSA private key.
1117 if (keyfile
== NULL
) {
1118 kclass
= CKO_SECRET_KEY
;
1121 kclass
= CKO_PRIVATE_KEY
;
1125 /* Find the key in the token first */
1126 for (i
= 0; i
< attrs
; i
++) {
1127 switch (key_tmpl
[i
].type
) {
1129 key_tmpl
[i
].pValue
= &kclass
;
1130 key_tmpl
[i
].ulValueLen
= sizeof (kclass
);
1133 key_tmpl
[i
].pValue
= &ktype
;
1134 key_tmpl
[i
].ulValueLen
= sizeof (ktype
);
1137 key_tmpl
[i
].pValue
= token
->key
;
1138 key_tmpl
[i
].ulValueLen
= strlen(token
->key
);
1141 key_tmpl
[i
].pValue
= &trueval
;
1142 key_tmpl
[i
].ulValueLen
= sizeof (trueval
);
1145 key_tmpl
[i
].pValue
= &trueval
;
1146 key_tmpl
[i
].ulValueLen
= sizeof (trueval
);
1152 rv
= C_FindObjectsInit(sess
, key_tmpl
, attrs
);
1154 die(gettext("cannot find key %s: %s\n"), token
->key
,
1155 pkcs11_strerror(rv
));
1156 rv
= C_FindObjects(sess
, &obj
, 1, &num_objs
);
1157 (void) C_FindObjectsFinal(sess
);
1159 if (num_objs
== 0) {
1160 die(gettext("cannot find key %s\n"), token
->key
);
1161 } else if (rv
!= CKR_OK
) {
1162 die(gettext("cannot find key %s: %s\n"), token
->key
,
1163 pkcs11_strerror(rv
));
1167 * No keyfile means when token key is found, convert it to raw key,
1168 * and done. Otherwise still need do an unwrap to create yet another
1169 * obj and that needs to be converted to raw key before we're done.
1171 if (keyfile
== NULL
) {
1172 /* obj contains raw key, extract it */
1173 rv
= pkcs11_ObjectToKey(sess
, obj
, (void **)&rkey
, &rksz
,
1176 die(gettext("failed to get key value for %s"
1177 " from token %s, %s\n"), token
->key
,
1178 token
->name
, pkcs11_strerror(rv
));
1181 getkeyfromfile(keyfile
, cipher
, &rkey
, &rksz
);
1184 * Got the wrapping RSA obj and the wrapped key from file.
1185 * Unwrap the key from file with RSA obj to get rawkey obj.
1188 /* re-use the first two attributes of key_tmpl */
1189 kclass
= CKO_SECRET_KEY
;
1192 rv
= C_UnwrapKey(sess
, &unwrap
, obj
, (CK_BYTE_PTR
)rkey
,
1193 rksz
, key_tmpl
, 2, &rawobj
);
1195 die(gettext("failed to unwrap key in keyfile %s,"
1196 " %s\n"), keyfile
, pkcs11_strerror(rv
));
1198 /* rawobj contains raw key, extract it */
1199 rv
= pkcs11_ObjectToKey(sess
, rawobj
, (void **)&rkey
, &rksz
,
1202 die(gettext("failed to get unwrapped key value for"
1203 " key in keyfile %s, %s\n"), keyfile
,
1204 pkcs11_strerror(rv
));
1208 /* validate raw key size */
1209 if (rksz
< cipher
->min_keysize
|| cipher
->max_keysize
< rksz
) {
1210 warn(gettext("%s: invalid keysize: %d\n"), keyfile
, (int)rksz
);
1211 die(gettext("\t%d <= keysize <= %d\n"), cipher
->min_keysize
,
1212 cipher
->max_keysize
);
1216 *raw_key
= (char *)rkey
;
1220 * Set up cipher key limits and verify PKCS#11 can be done
1221 * match_token_cipher is the function pointer used by
1222 * pkcs11_GetCriteriaSession() init_crypto.
1225 match_token_cipher(CK_SLOT_ID slot_id
, void *args
, CK_RV
*rv
)
1227 token_spec_t
*token
;
1228 mech_alias_t
*cipher
;
1229 CK_TOKEN_INFO tokinfo
;
1230 CK_MECHANISM_INFO mechinfo
;
1231 boolean_t token_match
;
1234 * While traversing slot list, pick up the following info per slot:
1235 * - if token specified, whether it matches this slot's token info
1236 * - if the slot supports the PKCS#5 PBKD2 cipher
1238 * If the user said on the command line
1239 * -T tok:mfr:ser:lab -k keyfile
1240 * -c cipher -T tok:mfr:ser:lab -k keyfile
1241 * the given cipher or the default cipher apply to keyfile,
1242 * If the user said instead
1243 * -T tok:mfr:ser:lab
1244 * -c cipher -T tok:mfr:ser:lab
1245 * the key named "lab" may or may not agree with the given
1246 * cipher or the default cipher. In those cases, cipher will
1247 * be overridden with the actual cipher type of the key "lab".
1249 *rv
= CKR_FUNCTION_FAILED
;
1255 cipher
= (mech_alias_t
*)args
;
1256 token
= cipher
->token
;
1258 if (C_GetMechanismInfo(slot_id
, cipher
->type
, &mechinfo
) != CKR_OK
) {
1262 if (token
== NULL
) {
1263 if (C_GetMechanismInfo(slot_id
, CKM_PKCS5_PBKD2
, &mechinfo
) !=
1270 /* does the token match the token spec? */
1271 if (token
->key
== NULL
|| (C_GetTokenInfo(slot_id
, &tokinfo
) != CKR_OK
))
1274 token_match
= B_TRUE
;
1276 if (token
->name
!= NULL
&& (token
->name
)[0] != '\0' &&
1277 strncmp((char *)token
->name
, (char *)tokinfo
.label
,
1278 TOKEN_LABEL_SIZE
) != 0)
1279 token_match
= B_FALSE
;
1280 if (token
->mfr
!= NULL
&& (token
->mfr
)[0] != '\0' &&
1281 strncmp((char *)token
->mfr
, (char *)tokinfo
.manufacturerID
,
1282 TOKEN_MANUFACTURER_SIZE
) != 0)
1283 token_match
= B_FALSE
;
1284 if (token
->serno
!= NULL
&& (token
->serno
)[0] != '\0' &&
1285 strncmp((char *)token
->serno
, (char *)tokinfo
.serialNumber
,
1286 TOKEN_SERIAL_SIZE
) != 0)
1287 token_match
= B_FALSE
;
1293 cipher
->slot
= slot_id
;
1298 * Clean up crypto loose ends
1301 end_crypto(CK_SESSION_HANDLE sess
)
1303 (void) C_CloseSession(sess
);
1304 (void) C_Finalize(NULL
);
1308 * Set up crypto, opening session on slot that matches token and cipher
1311 init_crypto(token_spec_t
*token
, mech_alias_t
*cipher
,
1312 CK_SESSION_HANDLE_PTR sess
)
1316 cipher
->token
= token
;
1318 /* Turn off Metaslot so that we can see actual tokens */
1319 if (setenv("METASLOT_ENABLED", "false", 1) < 0) {
1320 die(gettext("could not disable Metaslot"));
1323 rv
= pkcs11_GetCriteriaSession(match_token_cipher
, (void *)cipher
,
1327 if (rv
== CKR_HOST_MEMORY
) {
1330 die(gettext("failed to find any cryptographic provider, "
1331 "use \"cryptoadm list -p\" to find providers: %s\n"),
1332 pkcs11_strerror(rv
));
1337 * Uncompress a file.
1339 * First map the file in to establish a device
1340 * association, then read from it. On-the-fly
1341 * decompression will automatically uncompress
1342 * the file if it's compressed
1344 * If the file is mapped and a device association
1345 * has been established, disallow uncompressing
1346 * the file until it is unmapped.
1349 lofi_uncompress(int lfd
, const char *filename
)
1351 struct lofi_ioctl li
;
1353 char devicename
[32];
1354 char tmpfilename
[MAXPATHLEN
];
1359 struct stat64 statbuf
;
1365 * Disallow uncompressing the file if it is
1368 li
.li_crypto_enabled
= B_FALSE
;
1370 (void) strlcpy(li
.li_filename
, filename
, sizeof (li
.li_filename
));
1371 if (ioctl(lfd
, LOFI_GET_MINOR
, &li
) != -1)
1372 die(gettext("%s must be unmapped before uncompressing"),
1375 /* Zero length files don't need to be uncompressed */
1376 if (stat64(filename
, &statbuf
) == -1)
1377 die(gettext("stat: %s"), filename
);
1378 if (statbuf
.st_size
== 0)
1381 minor
= lofi_map_file(lfd
, &li
, filename
);
1382 (void) snprintf(devicename
, sizeof (devicename
), "/dev/%s/%d",
1383 LOFI_BLOCK_NAME
, minor
);
1385 /* If the file isn't compressed, we just return */
1386 if ((ioctl(lfd
, LOFI_CHECK_COMPRESSED
, &li
) == -1) ||
1387 (li
.li_algorithm
[0] == '\0')) {
1388 delete_mapping(lfd
, devicename
, filename
, B_TRUE
);
1389 die("%s is not compressed\n", filename
);
1392 if ((compfd
= open64(devicename
, O_RDONLY
| O_NONBLOCK
)) == -1) {
1393 delete_mapping(lfd
, devicename
, filename
, B_TRUE
);
1394 die(gettext("open: %s"), filename
);
1396 /* Create a temp file in the same directory */
1397 x
= strdup(filename
);
1398 dir
= strdup(dirname(x
));
1400 x
= strdup(filename
);
1401 file
= strdup(basename(x
));
1403 (void) snprintf(tmpfilename
, sizeof (tmpfilename
),
1404 "%s/.%sXXXXXX", dir
, file
);
1408 if ((uncompfd
= mkstemp64(tmpfilename
)) == -1) {
1409 (void) close(compfd
);
1410 delete_mapping(lfd
, devicename
, filename
, B_TRUE
);
1411 die("%s could not be uncompressed\n", filename
);
1415 * Set the mode bits and the owner of this temporary
1416 * file to be that of the original uncompressed file
1418 (void) fchmod(uncompfd
, statbuf
.st_mode
);
1420 if (fchown(uncompfd
, statbuf
.st_uid
, statbuf
.st_gid
) == -1) {
1421 (void) close(compfd
);
1422 (void) close(uncompfd
);
1423 delete_mapping(lfd
, devicename
, filename
, B_TRUE
);
1424 die("%s could not be uncompressed\n", filename
);
1427 /* Now read from the device in MAXBSIZE-sized chunks */
1429 rbytes
= read(compfd
, buf
, sizeof (buf
));
1434 if (write(uncompfd
, buf
, rbytes
) != rbytes
) {
1440 (void) close(compfd
);
1441 (void) close(uncompfd
);
1443 /* Delete the mapping */
1444 delete_mapping(lfd
, devicename
, filename
, B_TRUE
);
1447 * If an error occured while reading or writing, rbytes will
1451 (void) unlink(tmpfilename
);
1452 die(gettext("could not read from %s"), filename
);
1455 /* Rename the temp file to the actual file */
1456 if (rename(tmpfilename
, filename
) == -1)
1457 (void) unlink(tmpfilename
);
1464 lofi_compress(int *lfd
, const char *filename
, int compress_index
,
1467 struct lofi_ioctl lic
;
1468 lofi_compress_info_t
*li
;
1470 char tmpfilename
[MAXPATHLEN
];
1471 char comp_filename
[MAXPATHLEN
];
1472 char algorithm
[MAXALGLEN
];
1474 char *dir
= NULL
, *file
= NULL
;
1475 uchar_t
*uncompressed_seg
= NULL
;
1476 uchar_t
*compressed_seg
= NULL
;
1477 uint32_t compressed_segsize
;
1478 uint32_t len_compressed
, count
;
1479 uint32_t index_entries
, index_sz
;
1480 uint64_t *index
= NULL
;
1482 size_t real_segsize
;
1483 struct stat64 statbuf
;
1484 int compfd
= -1, uncompfd
= -1;
1486 ssize_t rbytes
, wbytes
, lastread
;
1490 * Disallow compressing the file if it is
1494 (void) strlcpy(lic
.li_filename
, filename
, sizeof (lic
.li_filename
));
1495 if (ioctl(*lfd
, LOFI_GET_MINOR
, &lic
) != -1)
1496 die(gettext("%s must be unmapped before compressing"),
1500 * Close the control device so other operations
1506 li
= &lofi_compress_table
[compress_index
];
1509 * The size of the buffer to hold compressed data must
1510 * be slightly larger than the compressed segment size.
1512 * The compress functions use part of the buffer as
1513 * scratch space to do calculations.
1514 * Ref: http://www.zlib.net/manual.html#compress2
1516 compressed_segsize
= segsize
+ (segsize
>> 6);
1517 compressed_seg
= (uchar_t
*)malloc(compressed_segsize
+ SEGHDR
);
1518 uncompressed_seg
= (uchar_t
*)malloc(segsize
);
1520 if (compressed_seg
== NULL
|| uncompressed_seg
== NULL
)
1521 die(gettext("No memory"));
1523 if ((uncompfd
= open64(filename
, O_RDWR
|O_LARGEFILE
, 0)) == -1)
1524 die(gettext("open: %s"), filename
);
1526 lock
.l_type
= F_WRLCK
;
1527 lock
.l_whence
= SEEK_SET
;
1532 * Use an advisory lock to ensure that only a
1533 * single lofiadm process compresses a given
1534 * file at any given time
1536 * A close on the file descriptor automatically
1537 * closes all lock state on the file
1539 if (fcntl(uncompfd
, F_SETLKW
, &lock
) == -1)
1540 die(gettext("fcntl: %s"), filename
);
1542 if (fstat64(uncompfd
, &statbuf
) == -1) {
1543 (void) close(uncompfd
);
1544 die(gettext("fstat: %s"), filename
);
1547 /* Zero length files don't need to be compressed */
1548 if (statbuf
.st_size
== 0) {
1549 (void) close(uncompfd
);
1554 * Create temporary files in the same directory that
1555 * will hold the intermediate data
1557 x
= strdup(filename
);
1558 dir
= strdup(dirname(x
));
1560 x
= strdup(filename
);
1561 file
= strdup(basename(x
));
1563 (void) snprintf(tmpfilename
, sizeof (tmpfilename
),
1564 "%s/.%sXXXXXX", dir
, file
);
1565 (void) snprintf(comp_filename
, sizeof (comp_filename
),
1566 "%s/.%sXXXXXX", dir
, file
);
1570 if ((tfd
= mkstemp64(tmpfilename
)) == -1)
1573 if ((compfd
= mkstemp64(comp_filename
)) == -1)
1577 * Set the mode bits and owner of the compressed
1578 * file to be that of the original uncompressed file
1580 (void) fchmod(compfd
, statbuf
.st_mode
);
1582 if (fchown(compfd
, statbuf
.st_uid
, statbuf
.st_gid
) == -1)
1586 * Calculate the number of index entries required.
1587 * index entries are stored as an array. adding
1588 * a '2' here accounts for the fact that the last
1589 * segment may not be a multiple of the segment size
1591 index_sz
= (statbuf
.st_size
/ segsize
) + 2;
1592 index
= malloc(sizeof (*index
) * index_sz
);
1602 * Now read from the uncompressed file in 'segsize'
1603 * sized chunks, compress what was read in and
1604 * write it out to a temporary file
1607 rbytes
= read(uncompfd
, uncompressed_seg
, segsize
);
1612 if (lastread
< segsize
)
1616 * Account for the first byte that
1617 * indicates whether a segment is
1620 real_segsize
= segsize
- 1;
1621 (void) li
->l_compress(uncompressed_seg
, rbytes
,
1622 compressed_seg
+ SEGHDR
, &real_segsize
, li
->l_level
);
1625 * If the length of the compressed data is more
1626 * than a threshold then there isn't any benefit
1627 * to be had from compressing this segment - leave
1630 * NB. In case an error occurs during compression (above)
1631 * the 'real_segsize' isn't changed. The logic below
1632 * ensures that that segment is left uncompressed.
1634 len_compressed
= real_segsize
;
1635 if (segsize
<= COMPRESS_THRESHOLD
||
1636 real_segsize
> (segsize
- COMPRESS_THRESHOLD
)) {
1637 (void) memcpy(compressed_seg
+ SEGHDR
, uncompressed_seg
,
1639 type
= UNCOMPRESSED
;
1640 len_compressed
= rbytes
;
1646 * Set the first byte or the SEGHDR to
1647 * indicate if it's compressed or not
1649 *compressed_seg
= type
;
1650 wbytes
= write(tfd
, compressed_seg
, len_compressed
+ SEGHDR
);
1651 if (wbytes
!= (len_compressed
+ SEGHDR
)) {
1656 index
[count
] = BE_64(offset
);
1662 (void) close(uncompfd
);
1667 * The last index entry is a sentinel entry. It does not point to
1668 * an actual compressed segment but helps in computing the size of
1669 * the compressed segment. The size of each compressed segment is
1670 * computed by subtracting the current index value from the next
1671 * one (the compressed blocks are stored sequentially)
1673 index
[count
++] = BE_64(offset
);
1676 * Now write the compressed data along with the
1677 * header information to this file which will
1678 * later be renamed to the original uncompressed
1681 * The header is as follows -
1683 * Signature (name of the compression algorithm)
1684 * Compression segment size (a multiple of 512)
1685 * Number of index entries
1686 * Size of the last block
1687 * The array containing the index entries
1689 * the header is always stored in network byte
1692 (void) bzero(algorithm
, sizeof (algorithm
));
1693 (void) strlcpy(algorithm
, li
->l_name
, sizeof (algorithm
));
1694 if (write(compfd
, algorithm
, sizeof (algorithm
))
1695 != sizeof (algorithm
))
1698 segsize
= htonl(segsize
);
1699 if (write(compfd
, &segsize
, sizeof (segsize
)) != sizeof (segsize
))
1702 index_entries
= htonl(count
);
1703 if (write(compfd
, &index_entries
, sizeof (index_entries
)) !=
1704 sizeof (index_entries
))
1707 lastread
= htonl(lastread
);
1708 if (write(compfd
, &lastread
, sizeof (lastread
)) != sizeof (lastread
))
1711 for (i
= 0; i
< count
; i
++) {
1712 if (write(compfd
, index
+ i
, sizeof (*index
)) !=
1717 /* Header is written, now write the compressed data */
1718 if (lseek(tfd
, 0, SEEK_SET
) != 0)
1721 rbytes
= wbytes
= 0;
1724 rbytes
= read(tfd
, compressed_seg
, compressed_segsize
+ SEGHDR
);
1729 if (write(compfd
, compressed_seg
, rbytes
) != rbytes
)
1733 if (fstat64(compfd
, &statbuf
) == -1)
1737 * Round up the compressed file size to be a multiple of
1738 * DEV_BSIZE. lofi(7D) likes it that way.
1740 if ((offset
= statbuf
.st_size
% DEV_BSIZE
) > 0) {
1742 offset
= DEV_BSIZE
- offset
;
1744 for (i
= 0; i
< offset
; i
++)
1745 uncompressed_seg
[i
] = '\0';
1746 if (write(compfd
, uncompressed_seg
, offset
) != offset
)
1749 (void) close(compfd
);
1751 (void) unlink(tmpfilename
);
1755 (void) unlink(tmpfilename
);
1757 (void) unlink(comp_filename
);
1758 die(gettext("error compressing file %s"), filename
);
1760 /* Rename the compressed file to the actual file */
1761 if (rename(comp_filename
, filename
) == -1) {
1762 (void) unlink(comp_filename
);
1763 die(gettext("error compressing file %s"), filename
);
1766 if (compressed_seg
!= NULL
)
1767 free(compressed_seg
);
1768 if (uncompressed_seg
!= NULL
)
1769 free(uncompressed_seg
);
1773 (void) close(compfd
);
1775 (void) close(uncompfd
);
1781 lofi_compress_select(const char *algname
)
1785 for (i
= 0; i
< LOFI_COMPRESS_FUNCTIONS
; i
++) {
1786 if (strcmp(lofi_compress_table
[i
].l_name
, algname
) == 0)
1793 check_algorithm_validity(const char *algname
, int *compress_index
)
1795 *compress_index
= lofi_compress_select(algname
);
1796 if (*compress_index
< 0)
1797 die(gettext("invalid algorithm name: %s\n"), algname
);
1801 check_file_validity(const char *filename
)
1807 fd
= open64(filename
, O_RDONLY
);
1809 die(gettext("open: %s"), filename
);
1811 error
= fstat64(fd
, &buf
);
1813 die(gettext("fstat: %s"), filename
);
1814 } else if (!S_ISLOFIABLE(buf
.st_mode
)) {
1815 die(gettext("%s is not a regular file, "
1816 "block, or character device\n"),
1818 } else if ((buf
.st_size
% DEV_BSIZE
) != 0) {
1819 die(gettext("size of %s is not a multiple of %d\n"),
1820 filename
, DEV_BSIZE
);
1824 if (name_to_minor(filename
) != 0) {
1825 die(gettext("cannot use %s on itself\n"), LOFI_DRIVER_NAME
);
1830 check_file_is_encrypted(const char *filename
)
1833 char buf
[sizeof (lofi_crypto_magic
)];
1835 int rest
= sizeof (lofi_crypto_magic
);
1837 fd
= open64(filename
, O_RDONLY
);
1839 die(gettext("failed to open: %s"), filename
);
1841 if (lseek(fd
, CRYOFF
, SEEK_SET
) != CRYOFF
)
1842 die(gettext("failed to seek to offset 0x%lx in file %s"),
1846 got
= read(fd
, buf
+ sizeof (lofi_crypto_magic
) - rest
, rest
);
1847 if ((got
== 0) || ((got
== -1) && (errno
!= EINTR
)))
1848 die(gettext("failed to read crypto header"
1849 " at offset 0x%lx in file %s"), CRYOFF
, filename
);
1855 while (close(fd
) == -1) {
1857 die(gettext("failed to close file %s"), filename
);
1860 return (strncmp(buf
, lofi_crypto_magic
,
1861 sizeof (lofi_crypto_magic
)) == 0);
1865 convert_to_num(const char *str
)
1868 uint32_t segsize
, mult
= 1;
1871 if (len
&& isalpha(str
[len
- 1])) {
1872 switch (str
[len
- 1]) {
1890 die(gettext("invalid segment size %s\n"), str
);
1894 segsize
= atol(str
);
1901 main(int argc
, char *argv
[])
1905 const char *devicename
= NULL
;
1906 const char *filename
= NULL
;
1907 const char *algname
= COMPRESS_ALGORITHM
;
1911 uint32_t segsize
= SEGSIZE
;
1912 static char *lofictl
= "/dev/" LOFI_CTL_NAME
;
1913 boolean_t force
= B_FALSE
;
1915 boolean_t errflag
= B_FALSE
;
1916 boolean_t addflag
= B_FALSE
;
1917 boolean_t labelflag
= B_FALSE
;
1918 boolean_t rdflag
= B_FALSE
;
1919 boolean_t deleteflag
= B_FALSE
;
1920 boolean_t ephflag
= B_FALSE
;
1921 boolean_t compressflag
= B_FALSE
;
1922 boolean_t uncompressflag
= B_FALSE
;
1923 /* the next two work together for -c, -k, -T, -e options only */
1924 boolean_t need_crypto
= B_FALSE
; /* if any -c, -k, -T, -e */
1925 boolean_t cipher_only
= B_TRUE
; /* if -c only */
1926 const char *keyfile
= NULL
;
1927 mech_alias_t
*cipher
= NULL
;
1928 token_spec_t
*token
= NULL
;
1931 char realfilename
[MAXPATHLEN
];
1933 pname
= getpname(argv
[0]);
1935 (void) setlocale(LC_ALL
, "");
1936 (void) textdomain(TEXT_DOMAIN
);
1938 while ((c
= getopt(argc
, argv
, "a:c:Cd:efk:lrs:T:U")) != EOF
) {
1942 if ((filename
= realpath(optarg
, realfilename
)) == NULL
)
1944 if (((argc
- optind
) > 0) && (*argv
[optind
] != '-')) {
1945 /* optional device */
1946 devicename
= argv
[optind
];
1951 compressflag
= B_TRUE
;
1952 if (((argc
- optind
) > 1) && (*argv
[optind
] != '-')) {
1953 /* optional algorithm */
1954 algname
= argv
[optind
];
1957 check_algorithm_validity(algname
, &compress_index
);
1960 /* is the chosen cipher allowed? */
1961 if ((cipher
= ciph2mech(optarg
)) == NULL
) {
1963 warn(gettext("cipher %s not allowed\n"),
1966 need_crypto
= B_TRUE
;
1967 /* cipher_only is already set */
1970 deleteflag
= B_TRUE
;
1971 minor
= name_to_minor(optarg
);
1973 devicename
= optarg
;
1975 if ((filename
= realpath(optarg
,
1976 realfilename
)) == NULL
)
1982 need_crypto
= B_TRUE
;
1983 cipher_only
= B_FALSE
; /* need to unset cipher_only */
1990 need_crypto
= B_TRUE
;
1991 cipher_only
= B_FALSE
; /* need to unset cipher_only */
2000 segsize
= convert_to_num(optarg
);
2001 if (segsize
< DEV_BSIZE
|| !ISP2(segsize
))
2002 die(gettext("segment size %s is invalid "
2003 "or not a multiple of minimum block "
2004 "size %ld\n"), optarg
, DEV_BSIZE
);
2007 if ((token
= parsetoken(optarg
)) == NULL
) {
2010 gettext("invalid token key specifier %s\n"),
2013 need_crypto
= B_TRUE
;
2014 cipher_only
= B_FALSE
; /* need to unset cipher_only */
2017 uncompressflag
= B_TRUE
;
2026 /* Check for mutually exclusive combinations of options */
2028 (addflag
&& deleteflag
) ||
2029 (labelflag
&& !addflag
) ||
2030 (rdflag
&& !addflag
) ||
2031 (!addflag
&& need_crypto
) ||
2032 (need_crypto
&& labelflag
) ||
2033 ((compressflag
|| uncompressflag
) &&
2034 (labelflag
|| addflag
|| deleteflag
)))
2037 /* ephemeral key, and key from either file or token are incompatible */
2038 if (ephflag
&& (keyfile
!= NULL
|| token
!= NULL
)) {
2039 die(gettext("ephemeral key cannot be used with keyfile"
2040 " or token key\n"));
2044 * "-c" but no "-k", "-T", "-e", or "-T -k" means derive key from
2045 * command line passphrase
2048 switch (argc
- optind
) {
2049 case 0: /* no more args */
2050 if (compressflag
|| uncompressflag
) /* needs filename */
2054 if (addflag
|| deleteflag
)
2056 /* one arg means compress/uncompress the file ... */
2057 if (compressflag
|| uncompressflag
) {
2058 if ((filename
= realpath(argv
[optind
],
2059 realfilename
)) == NULL
)
2060 die("%s", argv
[optind
]);
2061 /* ... or without options means print the association */
2063 minor
= name_to_minor(argv
[optind
]);
2065 devicename
= argv
[optind
];
2067 if ((filename
= realpath(argv
[optind
],
2068 realfilename
)) == NULL
)
2069 die("%s", argv
[optind
]);
2078 if (addflag
|| compressflag
|| uncompressflag
)
2079 check_file_validity(filename
);
2081 if (filename
&& !valid_abspath(filename
))
2085 * Here, we know the arguments are correct, the filename is an
2086 * absolute path, it exists and is a regular file. We don't yet
2087 * know that the device name is ok or not.
2091 if (addflag
|| deleteflag
|| compressflag
|| uncompressflag
)
2094 openflag
|= O_RDONLY
;
2095 lfd
= open(lofictl
, openflag
);
2097 if ((errno
== EPERM
) || (errno
== EACCES
)) {
2098 die(gettext("you do not have permission to perform "
2099 "that operation.\n"));
2101 die(gettext("open: %s"), lofictl
);
2107 * No passphrase is needed for ephemeral key, or when key is
2108 * in a file and not wrapped by another key from a token.
2109 * However, a passphrase is needed in these cases:
2110 * 1. cipher with no ephemeral key, key file, or token,
2111 * in which case the passphrase is used to build the key
2112 * 2. token with an optional cipher or optional key file,
2113 * in which case the passphrase unlocks the token
2114 * If only the cipher is specified, reconfirm the passphrase
2115 * to ensure the user hasn't mis-entered it. Otherwise, the
2116 * token will enforce the token passphrase.
2119 CK_SESSION_HANDLE sess
;
2121 /* pick a cipher if none specified */
2123 cipher
= DEFAULT_CIPHER
;
2125 if (!kernel_cipher_check(cipher
))
2127 "use \"cryptoadm list -m\" to find available "
2130 init_crypto(token
, cipher
, &sess
);
2133 getkeyfromuser(cipher
, &rkey
, &rksz
,
2134 !check_file_is_encrypted(filename
));
2135 } else if (token
!= NULL
) {
2136 getkeyfromtoken(sess
, token
, keyfile
, cipher
,
2139 /* this also handles ephemeral keys */
2140 getkeyfromfile(keyfile
, cipher
, &rkey
, &rksz
);
2147 * Now to the real work.
2150 add_mapping(lfd
, devicename
, filename
, cipher
, rkey
, rksz
,
2152 else if (compressflag
)
2153 lofi_compress(&lfd
, filename
, compress_index
, segsize
);
2154 else if (uncompressflag
)
2155 lofi_uncompress(lfd
, filename
);
2156 else if (deleteflag
)
2157 delete_mapping(lfd
, devicename
, filename
, force
);
2158 else if (filename
|| devicename
)
2159 print_one_mapping(lfd
, devicename
, filename
);
2161 print_mappings(lfd
);