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
);
822 * Break up token spec into its components (non-destructive)
824 static token_spec_t
*
825 parsetoken(char *spec
)
832 #define nullfield(i) ((field[(i)+1] - field[(i)]) <= 1)
833 #define copyfield(fld, i) \
837 if ((n = (field[(i)+1] - field[(i)])) > 1) { \
838 if (((fld) = malloc(n)) != NULL) { \
839 (void) strncpy((fld), field[(i)], n); \
840 ((fld))[n - 1] = '\0'; \
846 char *field
[NFIELDS
+ 1]; /* +1 to catch extra delimiters */
847 token_spec_t
*ti
= NULL
;
853 * Correct format is "[name]:[manuf]:[serial]:key". Can't use
854 * strtok because it treats ":::key" and "key:::" and "key" all
855 * as the same thing, and we can't have the :s compressed away.
858 for (i
= 1; i
< NFIELDS
+ 1; i
++) {
859 field
[i
] = strchr(field
[i
-1], ':');
860 if (field
[i
] == NULL
)
864 if (i
< NFIELDS
) /* not enough fields */
866 if (field
[NFIELDS
] != NULL
) /* too many fields */
868 field
[NFIELDS
] = strchr(field
[NFIELDS
-1], '\0') + 1;
870 /* key label can't be empty */
871 if (nullfield(FLD_LABEL
))
874 ti
= malloc(sizeof (token_spec_t
));
878 copyfield(ti
->name
, FLD_NAME
);
879 copyfield(ti
->mfr
, FLD_MANUF
);
880 copyfield(ti
->serno
, FLD_SERIAL
);
881 copyfield(ti
->key
, FLD_LABEL
);
884 * If token specified and it only contains a key label, then
885 * search all tokens for the key, otherwise only those with
886 * matching name, mfr, and serno are used.
889 * That's how we'd like it to be, however, if only the key label
890 * is specified, default to using softtoken. It's easier.
892 if (ti
->name
== NULL
&& ti
->mfr
== NULL
&& ti
->serno
== NULL
)
893 ti
->name
= strdup(pkcs11_default_token());
898 * PBE the passphrase into a raw key
901 getkeyfromuser(mech_alias_t
*cipher
, char **raw_key
, size_t *raw_key_sz
,
902 boolean_t with_confirmation
)
904 CK_SESSION_HANDLE sess
;
908 void *salt
= NULL
; /* don't use NULL, see note on salt below */
914 /* did init_crypto find a slot that supports this cipher? */
915 if (cipher
->slot
== (CK_SLOT_ID
)-1 || cipher
->max_keysize
== 0) {
916 rv
= CKR_MECHANISM_INVALID
;
920 rv
= pkcs11_mech2keytype(cipher
->type
, &ktype
);
925 * use the passphrase to generate a PBE PKCS#5 secret key and
926 * retrieve the raw key data to eventually pass it to the kernel;
928 rv
= C_OpenSession(cipher
->slot
, CKF_SERIAL_SESSION
, NULL
, NULL
, &sess
);
932 /* get user passphrase with 8 byte minimum */
933 if (pkcs11_get_pass(NULL
, &pass
, &passlen
, MIN_PASSLEN
,
934 with_confirmation
) < 0) {
935 die(gettext("passphrases do not match\n"));
939 * salt should not be NULL, or else pkcs11_PasswdToKey() will
940 * complain about CKR_MECHANISM_PARAM_INVALID; the following is
941 * to make up for not having a salt until a proper one is used
946 klen
= cipher
->max_keysize
;
947 rv
= pkcs11_PasswdToKey(sess
, pass
, passlen
, salt
, saltlen
, ktype
,
948 cipher
->max_keysize
, &kvalue
, &klen
);
950 (void) C_CloseSession(sess
);
956 /* assert(klen == cipher->max_keysize); */
958 *raw_key
= (char *)kvalue
;
962 die(gettext("failed to generate %s key from passphrase: %s"),
963 cipher
->alias
, pkcs11_strerror(rv
));
967 * Read raw key from file; also handles ephemeral keys.
970 getkeyfromfile(const char *pathname
, mech_alias_t
*cipher
, char **key
,
975 boolean_t notplain
= B_FALSE
;
979 /* ephemeral keys are just random data */
980 if (pathname
== NULL
) {
981 *ksz
= cipher
->max_keysize
;
984 die(gettext("failed to allocate memory for"
986 if (pkcs11_get_urandom(*key
, *ksz
) < 0) {
988 die(gettext("failed to get enough random data"));
994 * If the remaining section of code didn't also check for secure keyfile
995 * permissions and whether the key is within cipher min and max lengths,
996 * (or, if those things moved out of this block), we could have had:
997 * if (pkcs11_read_data(pathname, key, ksz) < 0)
1001 if ((fd
= open(pathname
, O_RDONLY
, 0)) == -1)
1002 die(gettext("open of keyfile (%s) failed"), pathname
);
1004 if (fstat(fd
, &sbuf
) == -1)
1005 die(gettext("fstat of keyfile (%s) failed"), pathname
);
1007 if (S_ISREG(sbuf
.st_mode
)) {
1008 if ((sbuf
.st_mode
& (S_IWGRP
| S_IWOTH
)) != 0)
1009 die(gettext("insecure permissions on keyfile %s\n"),
1012 *ksz
= sbuf
.st_size
;
1013 if (*ksz
< cipher
->min_keysize
|| cipher
->max_keysize
< *ksz
) {
1014 warn(gettext("%s: invalid keysize: %d\n"),
1015 pathname
, (int)*ksz
);
1016 die(gettext("\t%d <= keysize <= %d\n"),
1017 cipher
->min_keysize
, cipher
->max_keysize
);
1020 *ksz
= cipher
->max_keysize
;
1024 *key
= malloc(*ksz
);
1026 die(gettext("failed to allocate memory for key from file"));
1028 for (cursz
= 0, nread
= 0; cursz
< *ksz
; cursz
+= nread
) {
1029 nread
= read(fd
, *key
, *ksz
);
1033 * nread == 0. If it's not a regular file we were trying to
1034 * get the maximum keysize of data possible for this cipher.
1035 * But if we've got at least the minimum keysize of data,
1036 * round down to the nearest keysize unit and call it good.
1037 * If we haven't met the minimum keysize, that's an error.
1038 * If it's a regular file, nread = 0 is also an error.
1040 if (nread
== 0 && notplain
&& cursz
>= cipher
->min_keysize
) {
1041 *ksz
= (cursz
/ cipher
->min_keysize
) *
1042 cipher
->min_keysize
;
1045 die(gettext("%s: can't read all keybytes"), pathname
);
1051 * Read the raw key from token, or from a file that was wrapped with a
1055 getkeyfromtoken(CK_SESSION_HANDLE sess
,
1056 token_spec_t
*token
, const char *keyfile
, mech_alias_t
*cipher
,
1057 char **raw_key
, size_t *raw_key_sz
)
1060 CK_BBOOL trueval
= B_TRUE
;
1061 CK_OBJECT_CLASS kclass
; /* secret key or RSA private key */
1062 CK_KEY_TYPE ktype
; /* from selected cipher or CKK_RSA */
1063 CK_KEY_TYPE raw_ktype
; /* from selected cipher */
1064 CK_ATTRIBUTE key_tmpl
[] = {
1065 { CKA_CLASS
, NULL
, 0 }, /* re-used for token key and unwrap */
1066 { CKA_KEY_TYPE
, NULL
, 0 }, /* ditto */
1067 { CKA_LABEL
, NULL
, 0 },
1068 { CKA_TOKEN
, NULL
, 0 },
1069 { CKA_PRIVATE
, NULL
, 0 }
1071 CK_ULONG attrs
= sizeof (key_tmpl
) / sizeof (CK_ATTRIBUTE
);
1075 CK_OBJECT_HANDLE obj
, rawobj
;
1076 CK_ULONG num_objs
= 1; /* just want to find 1 token key */
1077 CK_MECHANISM unwrap
= { CKM_RSA_PKCS
, NULL
, 0 };
1081 if (token
== NULL
|| token
->key
== NULL
)
1084 /* did init_crypto find a slot that supports this cipher? */
1085 if (cipher
->slot
== (CK_SLOT_ID
)-1 || cipher
->max_keysize
== 0) {
1086 die(gettext("failed to find any cryptographic provider, "
1087 "use \"cryptoadm list -p\" to find providers: %s\n"),
1088 pkcs11_strerror(CKR_MECHANISM_INVALID
));
1091 if (pkcs11_get_pass(token
->name
, &pass
, &passlen
, 0, B_FALSE
) < 0)
1092 die(gettext("unable to get passphrase"));
1094 /* use passphrase to login to token */
1095 if (pass
!= NULL
&& passlen
> 0) {
1096 rv
= C_Login(sess
, CKU_USER
, (CK_UTF8CHAR_PTR
)pass
, passlen
);
1098 die(gettext("cannot login to the token %s: %s\n"),
1099 token
->name
, pkcs11_strerror(rv
));
1103 rv
= pkcs11_mech2keytype(cipher
->type
, &raw_ktype
);
1105 die(gettext("failed to get key type for cipher %s: %s\n"),
1106 cipher
->name
, pkcs11_strerror(rv
));
1110 * If no keyfile was given, then the token key is secret key to
1111 * be used for encryption/decryption. Otherwise, the keyfile
1112 * contains a wrapped secret key, and the token is actually the
1113 * unwrapping RSA private key.
1115 if (keyfile
== NULL
) {
1116 kclass
= CKO_SECRET_KEY
;
1119 kclass
= CKO_PRIVATE_KEY
;
1123 /* Find the key in the token first */
1124 for (i
= 0; i
< attrs
; i
++) {
1125 switch (key_tmpl
[i
].type
) {
1127 key_tmpl
[i
].pValue
= &kclass
;
1128 key_tmpl
[i
].ulValueLen
= sizeof (kclass
);
1131 key_tmpl
[i
].pValue
= &ktype
;
1132 key_tmpl
[i
].ulValueLen
= sizeof (ktype
);
1135 key_tmpl
[i
].pValue
= token
->key
;
1136 key_tmpl
[i
].ulValueLen
= strlen(token
->key
);
1139 key_tmpl
[i
].pValue
= &trueval
;
1140 key_tmpl
[i
].ulValueLen
= sizeof (trueval
);
1143 key_tmpl
[i
].pValue
= &trueval
;
1144 key_tmpl
[i
].ulValueLen
= sizeof (trueval
);
1150 rv
= C_FindObjectsInit(sess
, key_tmpl
, attrs
);
1152 die(gettext("cannot find key %s: %s\n"), token
->key
,
1153 pkcs11_strerror(rv
));
1154 rv
= C_FindObjects(sess
, &obj
, 1, &num_objs
);
1155 (void) C_FindObjectsFinal(sess
);
1157 if (num_objs
== 0) {
1158 die(gettext("cannot find key %s\n"), token
->key
);
1159 } else if (rv
!= CKR_OK
) {
1160 die(gettext("cannot find key %s: %s\n"), token
->key
,
1161 pkcs11_strerror(rv
));
1165 * No keyfile means when token key is found, convert it to raw key,
1166 * and done. Otherwise still need do an unwrap to create yet another
1167 * obj and that needs to be converted to raw key before we're done.
1169 if (keyfile
== NULL
) {
1170 /* obj contains raw key, extract it */
1171 rv
= pkcs11_ObjectToKey(sess
, obj
, (void **)&rkey
, &rksz
,
1174 die(gettext("failed to get key value for %s"
1175 " from token %s, %s\n"), token
->key
,
1176 token
->name
, pkcs11_strerror(rv
));
1179 getkeyfromfile(keyfile
, cipher
, &rkey
, &rksz
);
1182 * Got the wrapping RSA obj and the wrapped key from file.
1183 * Unwrap the key from file with RSA obj to get rawkey obj.
1186 /* re-use the first two attributes of key_tmpl */
1187 kclass
= CKO_SECRET_KEY
;
1190 rv
= C_UnwrapKey(sess
, &unwrap
, obj
, (CK_BYTE_PTR
)rkey
,
1191 rksz
, key_tmpl
, 2, &rawobj
);
1193 die(gettext("failed to unwrap key in keyfile %s,"
1194 " %s\n"), keyfile
, pkcs11_strerror(rv
));
1196 /* rawobj contains raw key, extract it */
1197 rv
= pkcs11_ObjectToKey(sess
, rawobj
, (void **)&rkey
, &rksz
,
1200 die(gettext("failed to get unwrapped key value for"
1201 " key in keyfile %s, %s\n"), keyfile
,
1202 pkcs11_strerror(rv
));
1206 /* validate raw key size */
1207 if (rksz
< cipher
->min_keysize
|| cipher
->max_keysize
< rksz
) {
1208 warn(gettext("%s: invalid keysize: %d\n"), keyfile
, (int)rksz
);
1209 die(gettext("\t%d <= keysize <= %d\n"), cipher
->min_keysize
,
1210 cipher
->max_keysize
);
1214 *raw_key
= (char *)rkey
;
1218 * Set up cipher key limits and verify PKCS#11 can be done
1219 * match_token_cipher is the function pointer used by
1220 * pkcs11_GetCriteriaSession() init_crypto.
1223 match_token_cipher(CK_SLOT_ID slot_id
, void *args
, CK_RV
*rv
)
1225 token_spec_t
*token
;
1226 mech_alias_t
*cipher
;
1227 CK_TOKEN_INFO tokinfo
;
1228 CK_MECHANISM_INFO mechinfo
;
1229 boolean_t token_match
;
1232 * While traversing slot list, pick up the following info per slot:
1233 * - if token specified, whether it matches this slot's token info
1234 * - if the slot supports the PKCS#5 PBKD2 cipher
1236 * If the user said on the command line
1237 * -T tok:mfr:ser:lab -k keyfile
1238 * -c cipher -T tok:mfr:ser:lab -k keyfile
1239 * the given cipher or the default cipher apply to keyfile,
1240 * If the user said instead
1241 * -T tok:mfr:ser:lab
1242 * -c cipher -T tok:mfr:ser:lab
1243 * the key named "lab" may or may not agree with the given
1244 * cipher or the default cipher. In those cases, cipher will
1245 * be overridden with the actual cipher type of the key "lab".
1247 *rv
= CKR_FUNCTION_FAILED
;
1253 cipher
= (mech_alias_t
*)args
;
1254 token
= cipher
->token
;
1256 if (C_GetMechanismInfo(slot_id
, cipher
->type
, &mechinfo
) != CKR_OK
) {
1260 if (token
== NULL
) {
1261 if (C_GetMechanismInfo(slot_id
, CKM_PKCS5_PBKD2
, &mechinfo
) !=
1268 /* does the token match the token spec? */
1269 if (token
->key
== NULL
|| (C_GetTokenInfo(slot_id
, &tokinfo
) != CKR_OK
))
1272 token_match
= B_TRUE
;
1274 if (token
->name
!= NULL
&& (token
->name
)[0] != '\0' &&
1275 strncmp((char *)token
->name
, (char *)tokinfo
.label
,
1276 TOKEN_LABEL_SIZE
) != 0)
1277 token_match
= B_FALSE
;
1278 if (token
->mfr
!= NULL
&& (token
->mfr
)[0] != '\0' &&
1279 strncmp((char *)token
->mfr
, (char *)tokinfo
.manufacturerID
,
1280 TOKEN_MANUFACTURER_SIZE
) != 0)
1281 token_match
= B_FALSE
;
1282 if (token
->serno
!= NULL
&& (token
->serno
)[0] != '\0' &&
1283 strncmp((char *)token
->serno
, (char *)tokinfo
.serialNumber
,
1284 TOKEN_SERIAL_SIZE
) != 0)
1285 token_match
= B_FALSE
;
1291 cipher
->slot
= slot_id
;
1296 * Clean up crypto loose ends
1299 end_crypto(CK_SESSION_HANDLE sess
)
1301 (void) C_CloseSession(sess
);
1302 (void) C_Finalize(NULL
);
1306 * Set up crypto, opening session on slot that matches token and cipher
1309 init_crypto(token_spec_t
*token
, mech_alias_t
*cipher
,
1310 CK_SESSION_HANDLE_PTR sess
)
1314 cipher
->token
= token
;
1316 /* Turn off Metaslot so that we can see actual tokens */
1317 if (setenv("METASLOT_ENABLED", "false", 1) < 0) {
1318 die(gettext("could not disable Metaslot"));
1321 rv
= pkcs11_GetCriteriaSession(match_token_cipher
, (void *)cipher
,
1325 if (rv
== CKR_HOST_MEMORY
) {
1328 die(gettext("failed to find any cryptographic provider, "
1329 "use \"cryptoadm list -p\" to find providers: %s\n"),
1330 pkcs11_strerror(rv
));
1335 * Uncompress a file.
1337 * First map the file in to establish a device
1338 * association, then read from it. On-the-fly
1339 * decompression will automatically uncompress
1340 * the file if it's compressed
1342 * If the file is mapped and a device association
1343 * has been established, disallow uncompressing
1344 * the file until it is unmapped.
1347 lofi_uncompress(int lfd
, const char *filename
)
1349 struct lofi_ioctl li
;
1351 char devicename
[32];
1352 char tmpfilename
[MAXPATHLEN
];
1357 struct stat64 statbuf
;
1363 * Disallow uncompressing the file if it is
1366 li
.li_crypto_enabled
= B_FALSE
;
1368 (void) strlcpy(li
.li_filename
, filename
, sizeof (li
.li_filename
));
1369 if (ioctl(lfd
, LOFI_GET_MINOR
, &li
) != -1)
1370 die(gettext("%s must be unmapped before uncompressing"),
1373 /* Zero length files don't need to be uncompressed */
1374 if (stat64(filename
, &statbuf
) == -1)
1375 die(gettext("stat: %s"), filename
);
1376 if (statbuf
.st_size
== 0)
1379 minor
= lofi_map_file(lfd
, &li
, filename
);
1380 (void) snprintf(devicename
, sizeof (devicename
), "/dev/%s/%d",
1381 LOFI_BLOCK_NAME
, minor
);
1383 /* If the file isn't compressed, we just return */
1384 if ((ioctl(lfd
, LOFI_CHECK_COMPRESSED
, &li
) == -1) ||
1385 (li
.li_algorithm
[0] == '\0')) {
1386 delete_mapping(lfd
, devicename
, filename
, B_TRUE
);
1387 die("%s is not compressed\n", filename
);
1390 if ((compfd
= open64(devicename
, O_RDONLY
| O_NONBLOCK
)) == -1) {
1391 delete_mapping(lfd
, devicename
, filename
, B_TRUE
);
1392 die(gettext("open: %s"), filename
);
1394 /* Create a temp file in the same directory */
1395 x
= strdup(filename
);
1396 dir
= strdup(dirname(x
));
1398 x
= strdup(filename
);
1399 file
= strdup(basename(x
));
1401 (void) snprintf(tmpfilename
, sizeof (tmpfilename
),
1402 "%s/.%sXXXXXX", dir
, file
);
1406 if ((uncompfd
= mkstemp64(tmpfilename
)) == -1) {
1407 (void) close(compfd
);
1408 delete_mapping(lfd
, devicename
, filename
, B_TRUE
);
1409 die("%s could not be uncompressed\n", filename
);
1413 * Set the mode bits and the owner of this temporary
1414 * file to be that of the original uncompressed file
1416 (void) fchmod(uncompfd
, statbuf
.st_mode
);
1418 if (fchown(uncompfd
, statbuf
.st_uid
, statbuf
.st_gid
) == -1) {
1419 (void) close(compfd
);
1420 (void) close(uncompfd
);
1421 delete_mapping(lfd
, devicename
, filename
, B_TRUE
);
1422 die("%s could not be uncompressed\n", filename
);
1425 /* Now read from the device in MAXBSIZE-sized chunks */
1427 rbytes
= read(compfd
, buf
, sizeof (buf
));
1432 if (write(uncompfd
, buf
, rbytes
) != rbytes
) {
1438 (void) close(compfd
);
1439 (void) close(uncompfd
);
1441 /* Delete the mapping */
1442 delete_mapping(lfd
, devicename
, filename
, B_TRUE
);
1445 * If an error occured while reading or writing, rbytes will
1449 (void) unlink(tmpfilename
);
1450 die(gettext("could not read from %s"), filename
);
1453 /* Rename the temp file to the actual file */
1454 if (rename(tmpfilename
, filename
) == -1)
1455 (void) unlink(tmpfilename
);
1462 lofi_compress(int *lfd
, const char *filename
, int compress_index
,
1465 struct lofi_ioctl lic
;
1466 lofi_compress_info_t
*li
;
1468 char tmpfilename
[MAXPATHLEN
];
1469 char comp_filename
[MAXPATHLEN
];
1470 char algorithm
[MAXALGLEN
];
1472 char *dir
= NULL
, *file
= NULL
;
1473 uchar_t
*uncompressed_seg
= NULL
;
1474 uchar_t
*compressed_seg
= NULL
;
1475 uint32_t compressed_segsize
;
1476 uint32_t len_compressed
, count
;
1477 uint32_t index_entries
, index_sz
;
1478 uint64_t *index
= NULL
;
1480 size_t real_segsize
;
1481 struct stat64 statbuf
;
1482 int compfd
= -1, uncompfd
= -1;
1484 ssize_t rbytes
, wbytes
, lastread
;
1488 * Disallow compressing the file if it is
1492 (void) strlcpy(lic
.li_filename
, filename
, sizeof (lic
.li_filename
));
1493 if (ioctl(*lfd
, LOFI_GET_MINOR
, &lic
) != -1)
1494 die(gettext("%s must be unmapped before compressing"),
1498 * Close the control device so other operations
1504 li
= &lofi_compress_table
[compress_index
];
1507 * The size of the buffer to hold compressed data must
1508 * be slightly larger than the compressed segment size.
1510 * The compress functions use part of the buffer as
1511 * scratch space to do calculations.
1512 * Ref: http://www.zlib.net/manual.html#compress2
1514 compressed_segsize
= segsize
+ (segsize
>> 6);
1515 compressed_seg
= (uchar_t
*)malloc(compressed_segsize
+ SEGHDR
);
1516 uncompressed_seg
= (uchar_t
*)malloc(segsize
);
1518 if (compressed_seg
== NULL
|| uncompressed_seg
== NULL
)
1519 die(gettext("No memory"));
1521 if ((uncompfd
= open64(filename
, O_RDWR
|O_LARGEFILE
, 0)) == -1)
1522 die(gettext("open: %s"), filename
);
1524 lock
.l_type
= F_WRLCK
;
1525 lock
.l_whence
= SEEK_SET
;
1530 * Use an advisory lock to ensure that only a
1531 * single lofiadm process compresses a given
1532 * file at any given time
1534 * A close on the file descriptor automatically
1535 * closes all lock state on the file
1537 if (fcntl(uncompfd
, F_SETLKW
, &lock
) == -1)
1538 die(gettext("fcntl: %s"), filename
);
1540 if (fstat64(uncompfd
, &statbuf
) == -1) {
1541 (void) close(uncompfd
);
1542 die(gettext("fstat: %s"), filename
);
1545 /* Zero length files don't need to be compressed */
1546 if (statbuf
.st_size
== 0) {
1547 (void) close(uncompfd
);
1552 * Create temporary files in the same directory that
1553 * will hold the intermediate data
1555 x
= strdup(filename
);
1556 dir
= strdup(dirname(x
));
1558 x
= strdup(filename
);
1559 file
= strdup(basename(x
));
1561 (void) snprintf(tmpfilename
, sizeof (tmpfilename
),
1562 "%s/.%sXXXXXX", dir
, file
);
1563 (void) snprintf(comp_filename
, sizeof (comp_filename
),
1564 "%s/.%sXXXXXX", dir
, file
);
1568 if ((tfd
= mkstemp64(tmpfilename
)) == -1)
1571 if ((compfd
= mkstemp64(comp_filename
)) == -1)
1575 * Set the mode bits and owner of the compressed
1576 * file to be that of the original uncompressed file
1578 (void) fchmod(compfd
, statbuf
.st_mode
);
1580 if (fchown(compfd
, statbuf
.st_uid
, statbuf
.st_gid
) == -1)
1584 * Calculate the number of index entries required.
1585 * index entries are stored as an array. adding
1586 * a '2' here accounts for the fact that the last
1587 * segment may not be a multiple of the segment size
1589 index_sz
= (statbuf
.st_size
/ segsize
) + 2;
1590 index
= malloc(sizeof (*index
) * index_sz
);
1600 * Now read from the uncompressed file in 'segsize'
1601 * sized chunks, compress what was read in and
1602 * write it out to a temporary file
1605 rbytes
= read(uncompfd
, uncompressed_seg
, segsize
);
1610 if (lastread
< segsize
)
1614 * Account for the first byte that
1615 * indicates whether a segment is
1618 real_segsize
= segsize
- 1;
1619 (void) li
->l_compress(uncompressed_seg
, rbytes
,
1620 compressed_seg
+ SEGHDR
, &real_segsize
, li
->l_level
);
1623 * If the length of the compressed data is more
1624 * than a threshold then there isn't any benefit
1625 * to be had from compressing this segment - leave
1628 * NB. In case an error occurs during compression (above)
1629 * the 'real_segsize' isn't changed. The logic below
1630 * ensures that that segment is left uncompressed.
1632 len_compressed
= real_segsize
;
1633 if (segsize
<= COMPRESS_THRESHOLD
||
1634 real_segsize
> (segsize
- COMPRESS_THRESHOLD
)) {
1635 (void) memcpy(compressed_seg
+ SEGHDR
, uncompressed_seg
,
1637 type
= UNCOMPRESSED
;
1638 len_compressed
= rbytes
;
1644 * Set the first byte or the SEGHDR to
1645 * indicate if it's compressed or not
1647 *compressed_seg
= type
;
1648 wbytes
= write(tfd
, compressed_seg
, len_compressed
+ SEGHDR
);
1649 if (wbytes
!= (len_compressed
+ SEGHDR
)) {
1654 index
[count
] = BE_64(offset
);
1660 (void) close(uncompfd
);
1665 * The last index entry is a sentinel entry. It does not point to
1666 * an actual compressed segment but helps in computing the size of
1667 * the compressed segment. The size of each compressed segment is
1668 * computed by subtracting the current index value from the next
1669 * one (the compressed blocks are stored sequentially)
1671 index
[count
++] = BE_64(offset
);
1674 * Now write the compressed data along with the
1675 * header information to this file which will
1676 * later be renamed to the original uncompressed
1679 * The header is as follows -
1681 * Signature (name of the compression algorithm)
1682 * Compression segment size (a multiple of 512)
1683 * Number of index entries
1684 * Size of the last block
1685 * The array containing the index entries
1687 * the header is always stored in network byte
1690 (void) bzero(algorithm
, sizeof (algorithm
));
1691 (void) strlcpy(algorithm
, li
->l_name
, sizeof (algorithm
));
1692 if (write(compfd
, algorithm
, sizeof (algorithm
))
1693 != sizeof (algorithm
))
1696 segsize
= htonl(segsize
);
1697 if (write(compfd
, &segsize
, sizeof (segsize
)) != sizeof (segsize
))
1700 index_entries
= htonl(count
);
1701 if (write(compfd
, &index_entries
, sizeof (index_entries
)) !=
1702 sizeof (index_entries
))
1705 lastread
= htonl(lastread
);
1706 if (write(compfd
, &lastread
, sizeof (lastread
)) != sizeof (lastread
))
1709 for (i
= 0; i
< count
; i
++) {
1710 if (write(compfd
, index
+ i
, sizeof (*index
)) !=
1715 /* Header is written, now write the compressed data */
1716 if (lseek(tfd
, 0, SEEK_SET
) != 0)
1719 rbytes
= wbytes
= 0;
1722 rbytes
= read(tfd
, compressed_seg
, compressed_segsize
+ SEGHDR
);
1727 if (write(compfd
, compressed_seg
, rbytes
) != rbytes
)
1731 if (fstat64(compfd
, &statbuf
) == -1)
1735 * Round up the compressed file size to be a multiple of
1736 * DEV_BSIZE. lofi(7D) likes it that way.
1738 if ((offset
= statbuf
.st_size
% DEV_BSIZE
) > 0) {
1740 offset
= DEV_BSIZE
- offset
;
1742 for (i
= 0; i
< offset
; i
++)
1743 uncompressed_seg
[i
] = '\0';
1744 if (write(compfd
, uncompressed_seg
, offset
) != offset
)
1747 (void) close(compfd
);
1749 (void) unlink(tmpfilename
);
1753 (void) unlink(tmpfilename
);
1755 (void) unlink(comp_filename
);
1756 die(gettext("error compressing file %s"), filename
);
1758 /* Rename the compressed file to the actual file */
1759 if (rename(comp_filename
, filename
) == -1) {
1760 (void) unlink(comp_filename
);
1761 die(gettext("error compressing file %s"), filename
);
1764 free(compressed_seg
);
1765 free(uncompressed_seg
);
1768 (void) close(compfd
);
1770 (void) close(uncompfd
);
1776 lofi_compress_select(const char *algname
)
1780 for (i
= 0; i
< LOFI_COMPRESS_FUNCTIONS
; i
++) {
1781 if (strcmp(lofi_compress_table
[i
].l_name
, algname
) == 0)
1788 check_algorithm_validity(const char *algname
, int *compress_index
)
1790 *compress_index
= lofi_compress_select(algname
);
1791 if (*compress_index
< 0)
1792 die(gettext("invalid algorithm name: %s\n"), algname
);
1796 check_file_validity(const char *filename
)
1802 fd
= open64(filename
, O_RDONLY
);
1804 die(gettext("open: %s"), filename
);
1806 error
= fstat64(fd
, &buf
);
1808 die(gettext("fstat: %s"), filename
);
1809 } else if (!S_ISLOFIABLE(buf
.st_mode
)) {
1810 die(gettext("%s is not a regular file, "
1811 "block, or character device\n"),
1813 } else if ((buf
.st_size
% DEV_BSIZE
) != 0) {
1814 die(gettext("size of %s is not a multiple of %d\n"),
1815 filename
, DEV_BSIZE
);
1819 if (name_to_minor(filename
) != 0) {
1820 die(gettext("cannot use %s on itself\n"), LOFI_DRIVER_NAME
);
1825 check_file_is_encrypted(const char *filename
)
1828 char buf
[sizeof (lofi_crypto_magic
)];
1830 int rest
= sizeof (lofi_crypto_magic
);
1832 fd
= open64(filename
, O_RDONLY
);
1834 die(gettext("failed to open: %s"), filename
);
1836 if (lseek(fd
, CRYOFF
, SEEK_SET
) != CRYOFF
)
1837 die(gettext("failed to seek to offset 0x%lx in file %s"),
1841 got
= read(fd
, buf
+ sizeof (lofi_crypto_magic
) - rest
, rest
);
1842 if ((got
== 0) || ((got
== -1) && (errno
!= EINTR
)))
1843 die(gettext("failed to read crypto header"
1844 " at offset 0x%lx in file %s"), CRYOFF
, filename
);
1850 while (close(fd
) == -1) {
1852 die(gettext("failed to close file %s"), filename
);
1855 return (strncmp(buf
, lofi_crypto_magic
,
1856 sizeof (lofi_crypto_magic
)) == 0);
1860 convert_to_num(const char *str
)
1863 uint32_t segsize
, mult
= 1;
1866 if (len
&& isalpha(str
[len
- 1])) {
1867 switch (str
[len
- 1]) {
1885 die(gettext("invalid segment size %s\n"), str
);
1889 segsize
= atol(str
);
1896 main(int argc
, char *argv
[])
1900 const char *devicename
= NULL
;
1901 const char *filename
= NULL
;
1902 const char *algname
= COMPRESS_ALGORITHM
;
1906 uint32_t segsize
= SEGSIZE
;
1907 static char *lofictl
= "/dev/" LOFI_CTL_NAME
;
1908 boolean_t force
= B_FALSE
;
1910 boolean_t errflag
= B_FALSE
;
1911 boolean_t addflag
= B_FALSE
;
1912 boolean_t labelflag
= B_FALSE
;
1913 boolean_t rdflag
= B_FALSE
;
1914 boolean_t deleteflag
= B_FALSE
;
1915 boolean_t ephflag
= B_FALSE
;
1916 boolean_t compressflag
= B_FALSE
;
1917 boolean_t uncompressflag
= B_FALSE
;
1918 /* the next two work together for -c, -k, -T, -e options only */
1919 boolean_t need_crypto
= B_FALSE
; /* if any -c, -k, -T, -e */
1920 boolean_t cipher_only
= B_TRUE
; /* if -c only */
1921 const char *keyfile
= NULL
;
1922 mech_alias_t
*cipher
= NULL
;
1923 token_spec_t
*token
= NULL
;
1926 char realfilename
[MAXPATHLEN
];
1928 pname
= getpname(argv
[0]);
1930 (void) setlocale(LC_ALL
, "");
1931 (void) textdomain(TEXT_DOMAIN
);
1933 while ((c
= getopt(argc
, argv
, "a:c:Cd:efk:lrs:T:U")) != EOF
) {
1937 if ((filename
= realpath(optarg
, realfilename
)) == NULL
)
1939 if (((argc
- optind
) > 0) && (*argv
[optind
] != '-')) {
1940 /* optional device */
1941 devicename
= argv
[optind
];
1946 compressflag
= B_TRUE
;
1947 if (((argc
- optind
) > 1) && (*argv
[optind
] != '-')) {
1948 /* optional algorithm */
1949 algname
= argv
[optind
];
1952 check_algorithm_validity(algname
, &compress_index
);
1955 /* is the chosen cipher allowed? */
1956 if ((cipher
= ciph2mech(optarg
)) == NULL
) {
1958 warn(gettext("cipher %s not allowed\n"),
1961 need_crypto
= B_TRUE
;
1962 /* cipher_only is already set */
1965 deleteflag
= B_TRUE
;
1966 minor
= name_to_minor(optarg
);
1968 devicename
= optarg
;
1970 if ((filename
= realpath(optarg
,
1971 realfilename
)) == NULL
)
1977 need_crypto
= B_TRUE
;
1978 cipher_only
= B_FALSE
; /* need to unset cipher_only */
1985 need_crypto
= B_TRUE
;
1986 cipher_only
= B_FALSE
; /* need to unset cipher_only */
1995 segsize
= convert_to_num(optarg
);
1996 if (segsize
< DEV_BSIZE
|| !ISP2(segsize
))
1997 die(gettext("segment size %s is invalid "
1998 "or not a multiple of minimum block "
1999 "size %ld\n"), optarg
, DEV_BSIZE
);
2002 if ((token
= parsetoken(optarg
)) == NULL
) {
2005 gettext("invalid token key specifier %s\n"),
2008 need_crypto
= B_TRUE
;
2009 cipher_only
= B_FALSE
; /* need to unset cipher_only */
2012 uncompressflag
= B_TRUE
;
2021 /* Check for mutually exclusive combinations of options */
2023 (addflag
&& deleteflag
) ||
2024 (labelflag
&& !addflag
) ||
2025 (rdflag
&& !addflag
) ||
2026 (!addflag
&& need_crypto
) ||
2027 (need_crypto
&& labelflag
) ||
2028 ((compressflag
|| uncompressflag
) &&
2029 (labelflag
|| addflag
|| deleteflag
)))
2032 /* ephemeral key, and key from either file or token are incompatible */
2033 if (ephflag
&& (keyfile
!= NULL
|| token
!= NULL
)) {
2034 die(gettext("ephemeral key cannot be used with keyfile"
2035 " or token key\n"));
2039 * "-c" but no "-k", "-T", "-e", or "-T -k" means derive key from
2040 * command line passphrase
2043 switch (argc
- optind
) {
2044 case 0: /* no more args */
2045 if (compressflag
|| uncompressflag
) /* needs filename */
2049 if (addflag
|| deleteflag
)
2051 /* one arg means compress/uncompress the file ... */
2052 if (compressflag
|| uncompressflag
) {
2053 if ((filename
= realpath(argv
[optind
],
2054 realfilename
)) == NULL
)
2055 die("%s", argv
[optind
]);
2056 /* ... or without options means print the association */
2058 minor
= name_to_minor(argv
[optind
]);
2060 devicename
= argv
[optind
];
2062 if ((filename
= realpath(argv
[optind
],
2063 realfilename
)) == NULL
)
2064 die("%s", argv
[optind
]);
2073 if (addflag
|| compressflag
|| uncompressflag
)
2074 check_file_validity(filename
);
2076 if (filename
&& !valid_abspath(filename
))
2080 * Here, we know the arguments are correct, the filename is an
2081 * absolute path, it exists and is a regular file. We don't yet
2082 * know that the device name is ok or not.
2086 if (addflag
|| deleteflag
|| compressflag
|| uncompressflag
)
2089 openflag
|= O_RDONLY
;
2090 lfd
= open(lofictl
, openflag
);
2092 if ((errno
== EPERM
) || (errno
== EACCES
)) {
2093 die(gettext("you do not have permission to perform "
2094 "that operation.\n"));
2096 die(gettext("open: %s"), lofictl
);
2102 * No passphrase is needed for ephemeral key, or when key is
2103 * in a file and not wrapped by another key from a token.
2104 * However, a passphrase is needed in these cases:
2105 * 1. cipher with no ephemeral key, key file, or token,
2106 * in which case the passphrase is used to build the key
2107 * 2. token with an optional cipher or optional key file,
2108 * in which case the passphrase unlocks the token
2109 * If only the cipher is specified, reconfirm the passphrase
2110 * to ensure the user hasn't mis-entered it. Otherwise, the
2111 * token will enforce the token passphrase.
2114 CK_SESSION_HANDLE sess
;
2116 /* pick a cipher if none specified */
2118 cipher
= DEFAULT_CIPHER
;
2120 if (!kernel_cipher_check(cipher
))
2122 "use \"cryptoadm list -m\" to find available "
2125 init_crypto(token
, cipher
, &sess
);
2128 getkeyfromuser(cipher
, &rkey
, &rksz
,
2129 !check_file_is_encrypted(filename
));
2130 } else if (token
!= NULL
) {
2131 getkeyfromtoken(sess
, token
, keyfile
, cipher
,
2134 /* this also handles ephemeral keys */
2135 getkeyfromfile(keyfile
, cipher
, &rkey
, &rksz
);
2142 * Now to the real work.
2145 add_mapping(lfd
, devicename
, filename
, cipher
, rkey
, rksz
,
2147 else if (compressflag
)
2148 lofi_compress(&lfd
, filename
, compress_index
, segsize
);
2149 else if (uncompressflag
)
2150 lofi_uncompress(lfd
, filename
);
2151 else if (deleteflag
)
2152 delete_mapping(lfd
, devicename
, filename
, force
);
2153 else if (filename
|| devicename
)
2154 print_one_mapping(lfd
, devicename
, filename
);
2156 print_mappings(lfd
);