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