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