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