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