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