1 /* 2 * CDDL HEADER START 3 * 4 * The contents of this file are subject to the terms of the 5 * Common Development and Distribution License (the "License"). 6 * You may not use this file except in compliance with the License. 7 * 8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE 9 * or http://www.opensolaris.org/os/licensing. 10 * See the License for the specific language governing permissions 11 * and limitations under the License. 12 * 13 * When distributing Covered Code, include this CDDL HEADER in each 14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE. 15 * If applicable, add the following below this CDDL HEADER, with the 16 * fields enclosed by brackets "[]" replaced with your own identifying 17 * information: Portions Copyright [yyyy] [name of copyright owner] 18 * 19 * CDDL HEADER END 20 */ 21 /* Portions Copyright 2005 Richard Lowe */ 22 /* 23 * Copyright 2008 Sun Microsystems, Inc. All rights reserved. 24 * Use is subject to license terms. 25 */ 26 27 /* 28 * decrypt.c 29 * 30 * Implements encrypt(1) and decrypt(1) commands 31 * 32 * One binary performs both encrypt/decrypt operation. 33 * 34 * Usage: 35 * -a algorithm mechanism name without CKM_ prefix. Case 36 * does not matter 37 * -k keyfile file containing key data. If not specified user is 38 * prompted to enter key. key length > 0 is required 39 * -i infile input file to encrypt/decrypt. If omitted, stdin used. 40 * -o outfile output file to encrypt/decrypt. If omitted, stdout used. 41 * if infile & outfile are same, a temp file is used for 42 * output and infile is replaced with this file after 43 * operation is complete 44 * -l Display the list of algorithms 45 * -v Display verbose information 46 * -T tokenspec Specify a PKCS#11 token (optionally used with -K) 47 * -K keylabel Specify the symmetric PKCS#11 token key label 48 * 49 * Implementation notes: 50 * IV data - It is generated by random bytes equal to one block size. 51 * 52 * Encrypted output format - 53 * - Output format version number (1) - 4 bytes in network byte order. 54 * - Iterations used in key gen function, 4 bytes in network byte order. 55 * - IV ('ivlen' bytes). Length is algorithm-dependent (see mech_aliases) 56 * - Salt data used in key gen (16 bytes) 57 * - Cipher text data (remainder of the file) 58 */ 59 60 #include <stdio.h> 61 #include <stdlib.h> 62 #include <unistd.h> 63 #include <errno.h> 64 #include <fcntl.h> 65 #include <ctype.h> 66 #include <strings.h> 67 #include <libintl.h> 68 #include <libgen.h> 69 #include <locale.h> 70 #include <limits.h> 71 #include <sys/types.h> 72 #include <sys/stat.h> 73 #include <netinet/in.h> 74 #include <security/cryptoki.h> 75 #include <cryptoutil.h> 76 #include <kmfapi.h> 77 78 #define BUFFERSIZE (2048) /* Buffer size for reading file */ 79 #define BLOCKSIZE (128) /* Largest guess for block size */ 80 #define PROGRESSSIZE (BUFFERSIZE*20) /* stdin progress indicator size */ 81 82 #define SUNW_ENCRYPT_FILE_VERSION 1 83 84 /* 85 * Exit Status codes 86 */ 87 #ifndef EXIT_SUCCESS 88 #define EXIT_SUCCESS 0 /* No errors */ 89 #define EXIT_FAILURE 1 /* All errors except usage */ 90 #endif /* EXIT_SUCCESS */ 91 92 #define EXIT_USAGE 2 /* usage/syntax error */ 93 94 #define ENCRYPT_NAME "encrypt" /* name of encrypt command */ 95 #define ENCRYPT_OPTIONS "a:T:K:k:i:o:lv" /* options for encrypt */ 96 #define DECRYPT_NAME "decrypt" /* name of decrypt command */ 97 #define DECRYPT_OPTIONS "a:T:K:k:i:o:lv" /* options for decrypt */ 98 99 /* 100 * Structure containing info for encrypt/decrypt 101 * command 102 */ 103 struct CommandInfo { 104 char *name; /* name of the command */ 105 char *options; /* command line options */ 106 CK_FLAGS flags; 107 CK_ATTRIBUTE_TYPE type; /* type of command */ 108 109 /* function pointers for various operations */ 110 CK_RV (*Init)(CK_SESSION_HANDLE, CK_MECHANISM_PTR, CK_OBJECT_HANDLE); 111 CK_RV (*Update)(CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, 112 CK_ULONG_PTR); 113 CK_RV (*Crypt)(CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG, CK_BYTE_PTR, 114 CK_ULONG_PTR); 115 CK_RV (*Final)(CK_SESSION_HANDLE, CK_BYTE_PTR, CK_ULONG_PTR); 116 }; 117 118 static struct CommandInfo encrypt_cmd = { 119 ENCRYPT_NAME, 120 ENCRYPT_OPTIONS, 121 CKF_ENCRYPT, 122 CKA_ENCRYPT, 123 C_EncryptInit, 124 C_EncryptUpdate, 125 C_Encrypt, 126 C_EncryptFinal 127 }; 128 129 static struct CommandInfo decrypt_cmd = { 130 DECRYPT_NAME, 131 DECRYPT_OPTIONS, 132 CKF_DECRYPT, 133 CKA_DECRYPT, 134 C_DecryptInit, 135 C_DecryptUpdate, 136 C_Decrypt, 137 C_DecryptFinal 138 }; 139 140 struct mech_alias { 141 CK_MECHANISM_TYPE type; 142 char *alias; 143 CK_ULONG keysize_min; 144 CK_ULONG keysize_max; 145 int keysize_unit; 146 int ivlen; 147 boolean_t available; 148 }; 149 150 #define MECH_ALIASES_COUNT 4 151 152 static struct mech_alias mech_aliases[] = { 153 { CKM_AES_CBC_PAD, "aes", ULONG_MAX, 0L, 8, 16, B_FALSE }, 154 { CKM_RC4, "arcfour", ULONG_MAX, 0L, 1, 0, B_FALSE }, 155 { CKM_DES_CBC_PAD, "des", 8, 8, 8, 8, B_FALSE }, 156 { CKM_DES3_CBC_PAD, "3des", 24, 24, 8, 8, B_FALSE }, 157 }; 158 159 static CK_BBOOL truevalue = TRUE; 160 static CK_BBOOL falsevalue = FALSE; 161 162 static boolean_t aflag = B_FALSE; /* -a <algorithm> flag, required */ 163 static boolean_t kflag = B_FALSE; /* -k <keyfile> flag */ 164 static boolean_t iflag = B_FALSE; /* -i <infile> flag, use stdin if absent */ 165 static boolean_t oflag = B_FALSE; /* -o <outfile> flag, use stdout if absent */ 166 static boolean_t lflag = B_FALSE; /* -l flag (list) */ 167 static boolean_t vflag = B_FALSE; /* -v flag (verbose) */ 168 static boolean_t Tflag = B_FALSE; /* -T flag (tokenspec) */ 169 static boolean_t Kflag = B_FALSE; /* -K flag (keylabel) */ 170 171 static char *keyfile = NULL; /* name of keyfile */ 172 static char *inputfile = NULL; /* name of input file */ 173 static char *outputfile = NULL; /* name of output file */ 174 static char *token_label = NULL; /* name of PKCS#11 token */ 175 static char *key_label = NULL; /* name of PKCS#11 token key label */ 176 177 static int status_pos = 0; /* current position of progress bar element */ 178 179 /* 180 * function prototypes 181 */ 182 static void usage(struct CommandInfo *cmd); 183 static int execute_cmd(struct CommandInfo *cmd, char *algo_str); 184 static int crypt_multipart(struct CommandInfo *cmd, CK_SESSION_HANDLE hSession, 185 int infd, int outfd, off_t insize); 186 187 int 188 main(int argc, char **argv) 189 { 190 191 extern char *optarg; 192 extern int optind; 193 char *optstr; 194 char c; /* current getopts flag */ 195 char *algo_str = NULL; /* algorithm string */ 196 struct CommandInfo *cmd; 197 char *cmdname; /* name of command */ 198 boolean_t errflag = B_FALSE; 199 200 (void) setlocale(LC_ALL, ""); 201 #if !defined(TEXT_DOMAIN) /* Should be defined by cc -D */ 202 #define TEXT_DOMAIN "SYS_TEST" /* Use this only if it weren't */ 203 #endif 204 (void) textdomain(TEXT_DOMAIN); 205 206 /* 207 * Based on command name, determine 208 * type of command. 209 */ 210 cmdname = basename(argv[0]); 211 212 cryptodebug_init(cmdname); 213 214 if (strcmp(cmdname, encrypt_cmd.name) == 0) { 215 cmd = &encrypt_cmd; 216 } else if (strcmp(cmdname, decrypt_cmd.name) == 0) { 217 cmd = &decrypt_cmd; 218 } else { 219 cryptoerror(LOG_STDERR, gettext( 220 "command name must be either encrypt or decrypt")); 221 exit(EXIT_USAGE); 222 } 223 224 optstr = cmd->options; 225 226 /* Parse command line arguments */ 227 while (!errflag && (c = getopt(argc, argv, optstr)) != -1) { 228 229 switch (c) { 230 case 'a': 231 aflag = B_TRUE; 232 algo_str = optarg; 233 break; 234 case 'k': 235 kflag = B_TRUE; 236 keyfile = optarg; 237 break; 238 case 'T': 239 Tflag = B_TRUE; 240 token_label = optarg; 241 break; 242 case 'K': 243 Kflag = B_TRUE; 244 key_label = optarg; 245 break; 246 case 'i': 247 iflag = B_TRUE; 248 inputfile = optarg; 249 break; 250 case 'o': 251 oflag = B_TRUE; 252 outputfile = optarg; 253 break; 254 case 'l': 255 lflag = B_TRUE; 256 break; 257 case 'v': 258 vflag = B_TRUE; 259 break; 260 default: 261 errflag = B_TRUE; 262 } 263 } 264 265 if (errflag || (!aflag && !lflag) || (lflag && argc > 2) || 266 (kflag && Kflag) || (Tflag && !Kflag) || 267 (optind < argc)) { 268 usage(cmd); 269 exit(EXIT_USAGE); 270 } 271 272 return (execute_cmd(cmd, algo_str)); 273 } 274 275 /* 276 * usage message 277 */ 278 static void 279 usage(struct CommandInfo *cmd) 280 { 281 (void) fprintf(stderr, gettext("Usage:\n")); 282 if (cmd->type == CKA_ENCRYPT) { 283 (void) fprintf(stderr, gettext(" encrypt -l\n")); 284 (void) fprintf(stderr, gettext(" encrypt -a <algorithm> " 285 "[-v] [-k <keyfile> | -K <keylabel> [-T <tokenspec>]] " 286 "[-i <infile>] [-o <outfile>]\n")); 287 288 } else { 289 (void) fprintf(stderr, gettext(" decrypt -l\n")); 290 (void) fprintf(stderr, gettext(" decrypt -a <algorithm> " 291 "[-v] [-k <keyfile> | -K <keylabel> [-T <tokenspec>]] " 292 "[-i <infile>] [-o <outfile>]\n")); 293 } 294 } 295 296 /* 297 * Print out list of algorithms in default and verbose mode 298 */ 299 static void 300 algorithm_list() 301 { 302 int mech; 303 304 (void) printf(gettext("Algorithm Keysize: Min Max (bits)\n" 305 "------------------------------------------\n")); 306 307 for (mech = 0; mech < MECH_ALIASES_COUNT; mech++) { 308 309 if (mech_aliases[mech].available == B_FALSE) 310 continue; 311 312 (void) printf("%-15s", mech_aliases[mech].alias); 313 314 if (mech_aliases[mech].keysize_min != UINT_MAX && 315 mech_aliases[mech].keysize_max != 0) 316 (void) printf(" %5lu %5lu\n", 317 (mech_aliases[mech].keysize_min * 318 mech_aliases[mech].keysize_unit), 319 (mech_aliases[mech].keysize_max * 320 mech_aliases[mech].keysize_unit)); 321 else 322 (void) printf("\n"); 323 324 } 325 } 326 327 /* 328 * This function will login into the token with the provided password and 329 * find the token key object with the specified keytype and keylabel. 330 */ 331 static int 332 get_token_key(CK_SESSION_HANDLE hSession, CK_KEY_TYPE keytype, 333 char *keylabel, CK_BYTE *password, int password_len, 334 CK_OBJECT_HANDLE *keyobj) 335 { 336 CK_RV rv; 337 CK_ATTRIBUTE pTmpl[10]; 338 CK_OBJECT_CLASS class = CKO_SECRET_KEY; 339 CK_BBOOL true = 1; 340 CK_BBOOL is_token = 1; 341 CK_ULONG key_obj_count = 1; 342 int i; 343 CK_KEY_TYPE ckKeyType = keytype; 344 345 346 rv = C_Login(hSession, CKU_USER, (CK_UTF8CHAR_PTR)password, 347 (CK_ULONG)password_len); 348 if (rv != CKR_OK) { 349 (void) fprintf(stderr, "Cannot login to the token." 350 " error = %s\n", pkcs11_strerror(rv)); 351 return (-1); 352 } 353 354 i = 0; 355 pTmpl[i].type = CKA_TOKEN; 356 pTmpl[i].pValue = &is_token; 357 pTmpl[i].ulValueLen = sizeof (CK_BBOOL); 358 i++; 359 360 pTmpl[i].type = CKA_CLASS; 361 pTmpl[i].pValue = &class; 362 pTmpl[i].ulValueLen = sizeof (class); 363 i++; 364 365 pTmpl[i].type = CKA_LABEL; 366 pTmpl[i].pValue = keylabel; 367 pTmpl[i].ulValueLen = strlen(keylabel); 368 i++; 369 370 pTmpl[i].type = CKA_KEY_TYPE; 371 pTmpl[i].pValue = &ckKeyType; 372 pTmpl[i].ulValueLen = sizeof (ckKeyType); 373 i++; 374 375 pTmpl[i].type = CKA_PRIVATE; 376 pTmpl[i].pValue = &true; 377 pTmpl[i].ulValueLen = sizeof (true); 378 i++; 379 380 rv = C_FindObjectsInit(hSession, pTmpl, i); 381 if (rv != CKR_OK) { 382 goto out; 383 } 384 385 rv = C_FindObjects(hSession, keyobj, 1, &key_obj_count); 386 387 (void) C_FindObjectsFinal(hSession); 388 389 out: 390 if (rv != CKR_OK) { 391 (void) fprintf(stderr, 392 "Cannot retrieve key object. error = %s\n", 393 pkcs11_strerror(rv)); 394 return (-1); 395 } 396 397 if (key_obj_count == 0) { 398 (void) fprintf(stderr, "Cannot find the key object.\n"); 399 return (-1); 400 } 401 402 return (0); 403 } 404 405 406 /* 407 * Execute the command. 408 * cmd - command pointing to type of operation. 409 * algo_str - alias of the algorithm passed. 410 */ 411 static int 412 execute_cmd(struct CommandInfo *cmd, char *algo_str) 413 { 414 CK_RV rv; 415 CK_ULONG slotcount; 416 CK_SLOT_ID slotID; 417 CK_SLOT_ID_PTR pSlotList = NULL; 418 CK_MECHANISM_TYPE mech_type = 0; 419 CK_MECHANISM_INFO info, kg_info; 420 CK_MECHANISM mech; 421 CK_SESSION_HANDLE hSession = CK_INVALID_HANDLE; 422 CK_BYTE_PTR pkeydata = NULL; 423 CK_BYTE salt[CK_PKCS5_PBKD2_SALT_SIZE]; 424 CK_ULONG keysize = 0; 425 int i, slot, mek; /* index variables */ 426 int status; 427 struct stat insbuf; /* stat buf for infile */ 428 struct stat outsbuf; /* stat buf for outfile */ 429 char tmpnam[PATH_MAX]; /* tmp file name */ 430 CK_OBJECT_HANDLE key = (CK_OBJECT_HANDLE) 0; 431 int infd = 0; /* input file, stdin default */ 432 int outfd = 1; /* output file, stdout default */ 433 char *outfilename = NULL; 434 boolean_t errflag = B_TRUE; 435 boolean_t inoutsame = B_FALSE; /* if both input & output are same */ 436 CK_BYTE_PTR pivbuf = NULL_PTR; 437 CK_ULONG ivlen = 0L; 438 int mech_match = 0; 439 uint32_t iterations = CK_PKCS5_PBKD2_ITERATIONS; 440 CK_ULONG keylen; 441 uint32_t version = SUNW_ENCRYPT_FILE_VERSION; 442 CK_KEY_TYPE keytype; 443 KMF_RETURN kmfrv; 444 CK_SLOT_ID token_slot_id; 445 446 if (aflag) { 447 /* Determine if algorithm is valid */ 448 for (mech_match = 0; mech_match < MECH_ALIASES_COUNT; 449 mech_match++) { 450 if (strcmp(algo_str, 451 mech_aliases[mech_match].alias) == 0) { 452 mech_type = mech_aliases[mech_match].type; 453 break; 454 } 455 } 456 457 if (mech_match == MECH_ALIASES_COUNT) { 458 cryptoerror(LOG_STDERR, 459 gettext("unknown algorithm -- %s"), algo_str); 460 return (EXIT_FAILURE); 461 } 462 463 /* 464 * Process keyfile or get the token pin if -K is specified. 465 * 466 * If a keyfile is provided, get the key data from 467 * the file. Otherwise, prompt for a passphrase. The 468 * passphrase is used as the key data. 469 */ 470 if (Kflag) { 471 /* get the pin of the token */ 472 if (token_label == NULL || !strlen(token_label)) { 473 token_label = pkcs11_default_token(); 474 } 475 476 status = pkcs11_get_pass(token_label, 477 (char **)&pkeydata, (size_t *)&keysize, 0, B_FALSE); 478 } else if (kflag) { 479 /* get the key file */ 480 status = pkcs11_read_data(keyfile, (void **)&pkeydata, 481 (size_t *)&keysize); 482 } else { 483 /* get the key from input */ 484 status = pkcs11_get_pass(NULL, (char **)&pkeydata, 485 (size_t *)&keysize, 0, 486 (cmd->type == CKA_ENCRYPT) ? B_TRUE : B_FALSE); 487 } 488 489 if (status != 0 || keysize == 0L) { 490 cryptoerror(LOG_STDERR, 491 kflag ? gettext("invalid key.") : 492 gettext("invalid passphrase.")); 493 return (EXIT_FAILURE); 494 } 495 } 496 497 bzero(salt, sizeof (salt)); 498 /* Initialize pkcs */ 499 rv = C_Initialize(NULL); 500 if (rv != CKR_OK && rv != CKR_CRYPTOKI_ALREADY_INITIALIZED) { 501 cryptoerror(LOG_STDERR, gettext("failed to initialize " 502 "PKCS #11 framework: %s"), pkcs11_strerror(rv)); 503 goto cleanup; 504 } 505 506 /* Get slot count */ 507 rv = C_GetSlotList(0, NULL_PTR, &slotcount); 508 if (rv != CKR_OK || slotcount == 0) { 509 cryptoerror(LOG_STDERR, gettext( 510 "failed to find any cryptographic provider," 511 "please check with your system administrator: %s"), 512 pkcs11_strerror(rv)); 513 goto cleanup; 514 } 515 516 /* Found at least one slot, allocate memory for slot list */ 517 pSlotList = malloc(slotcount * sizeof (CK_SLOT_ID)); 518 if (pSlotList == NULL_PTR) { 519 int err = errno; 520 cryptoerror(LOG_STDERR, gettext("malloc: %s"), strerror(err)); 521 goto cleanup; 522 } 523 524 /* Get the list of slots */ 525 if ((rv = C_GetSlotList(0, pSlotList, &slotcount)) != CKR_OK) { 526 cryptoerror(LOG_STDERR, gettext( 527 "failed to find any cryptographic provider," 528 "please check with your system administrator: %s"), 529 pkcs11_strerror(rv)); 530 goto cleanup; 531 } 532 533 if (lflag) { 534 535 /* Iterate through slots */ 536 for (slot = 0; slot < slotcount; slot++) { 537 538 /* Iterate through each mechanism */ 539 for (mek = 0; mek < MECH_ALIASES_COUNT; mek++) { 540 rv = C_GetMechanismInfo(pSlotList[slot], 541 mech_aliases[mek].type, &info); 542 543 if (rv != CKR_OK) 544 continue; 545 546 /* 547 * Set to minimum/maximum key sizes assuming 548 * the values available are not 0. 549 */ 550 if (info.ulMinKeySize && (info.ulMinKeySize < 551 mech_aliases[mek].keysize_min)) 552 mech_aliases[mek].keysize_min = 553 info.ulMinKeySize; 554 555 if (info.ulMaxKeySize && (info.ulMaxKeySize > 556 mech_aliases[mek].keysize_max)) 557 mech_aliases[mek].keysize_max = 558 info.ulMaxKeySize; 559 560 mech_aliases[mek].available = B_TRUE; 561 } 562 563 } 564 565 algorithm_list(); 566 567 errflag = B_FALSE; 568 goto cleanup; 569 } 570 571 572 /* 573 * Find a slot with matching mechanism 574 * 575 * If -K is specified, we find the slot id for the token first, then 576 * check if the slot supports the algorithm. 577 */ 578 i = 0; 579 if (Kflag) { 580 kmfrv = kmf_pk11_token_lookup(NULL, token_label, 581 &token_slot_id); 582 if (kmfrv != KMF_OK) { 583 cryptoerror(LOG_STDERR, 584 gettext("no matching PKCS#11 token")); 585 errflag = B_TRUE; 586 goto cleanup; 587 } 588 rv = C_GetMechanismInfo(token_slot_id, mech_type, &info); 589 if (rv == CKR_OK && (info.flags & cmd->flags)) 590 slotID = token_slot_id; 591 else 592 i = slotcount; 593 } else { 594 for (i = 0; i < slotcount; i++) { 595 slotID = pSlotList[i]; 596 rv = C_GetMechanismInfo(slotID, mech_type, &info); 597 if (rv != CKR_OK) { 598 continue; /* to the next slot */ 599 } else { 600 /* 601 * If the slot support the crypto, also 602 * make sure it supports the correct 603 * key generation mech if needed. 604 * 605 * We need PKCS5 when RC4 is used or 606 * when the key is entered on cmd line. 607 */ 608 if ((info.flags & cmd->flags) && 609 (mech_type == CKM_RC4) || 610 (keyfile == NULL)) { 611 rv = C_GetMechanismInfo(slotID, 612 CKM_PKCS5_PBKD2, &kg_info); 613 if (rv == CKR_OK) 614 break; 615 } else if (info.flags & cmd->flags) { 616 break; 617 } 618 } 619 } 620 } 621 622 /* Show error if no matching mechanism found */ 623 if (i == slotcount) { 624 cryptoerror(LOG_STDERR, 625 gettext("no cryptographic provider was " 626 "found for this algorithm -- %s"), algo_str); 627 goto cleanup; 628 } 629 630 /* Open a session */ 631 rv = C_OpenSession(slotID, CKF_SERIAL_SESSION, 632 NULL_PTR, NULL, &hSession); 633 634 if (rv != CKR_OK) { 635 cryptoerror(LOG_STDERR, 636 gettext("can not open PKCS #11 session: %s"), 637 pkcs11_strerror(rv)); 638 goto cleanup; 639 } 640 641 /* 642 * Generate IV data for encrypt. 643 */ 644 ivlen = mech_aliases[mech_match].ivlen; 645 if ((pivbuf = malloc((size_t)ivlen)) == NULL) { 646 int err = errno; 647 cryptoerror(LOG_STDERR, gettext("malloc: %s"), 648 strerror(err)); 649 goto cleanup; 650 } 651 652 if (cmd->type == CKA_ENCRYPT) { 653 if ((pkcs11_random_data((void *)pivbuf, 654 mech_aliases[mech_match].ivlen)) != 0) { 655 cryptoerror(LOG_STDERR, gettext( 656 "Unable to generate random " 657 "data for initialization vector.")); 658 goto cleanup; 659 } 660 } 661 662 /* 663 * Create the key object 664 */ 665 rv = pkcs11_mech2keytype(mech_type, &keytype); 666 if (rv != CKR_OK) { 667 cryptoerror(LOG_STDERR, 668 gettext("unable to find key type for algorithm.")); 669 goto cleanup; 670 } 671 672 /* Open input file */ 673 if (iflag) { 674 if ((infd = open(inputfile, O_RDONLY | O_NONBLOCK)) == -1) { 675 cryptoerror(LOG_STDERR, gettext( 676 "can not open input file %s"), inputfile); 677 goto cleanup; 678 } 679 680 /* Get info on input file */ 681 if (fstat(infd, &insbuf) == -1) { 682 cryptoerror(LOG_STDERR, gettext( 683 "can not stat input file %s"), inputfile); 684 goto cleanup; 685 } 686 } 687 688 /* 689 * Prepare output file 690 * If the input & output file are same, 691 * the output is written to a temp 692 * file first, then renamed to the original file 693 * after the crypt operation 694 */ 695 inoutsame = B_FALSE; 696 if (oflag) { 697 outfilename = outputfile; 698 if ((stat(outputfile, &outsbuf) != -1) && 699 (insbuf.st_ino == outsbuf.st_ino)) { 700 char *dir; 701 702 /* create temp file on same dir */ 703 dir = dirname(outputfile); 704 (void) snprintf(tmpnam, sizeof (tmpnam), 705 "%s/encrXXXXXX", dir); 706 outfilename = tmpnam; 707 if ((outfd = mkstemp(tmpnam)) == -1) { 708 cryptoerror(LOG_STDERR, gettext( 709 "cannot create temp file")); 710 goto cleanup; 711 } 712 inoutsame = B_TRUE; 713 } else { 714 /* Create file for output */ 715 if ((outfd = open(outfilename, 716 O_CREAT|O_WRONLY|O_TRUNC, 0644)) == -1) { 717 cryptoerror(LOG_STDERR, gettext( 718 "cannot open output file %s"), 719 outfilename); 720 goto cleanup; 721 } 722 } 723 } 724 725 /* 726 * Read the version number from the head of the file 727 * to know how to interpret the data that follows. 728 */ 729 if (cmd->type == CKA_DECRYPT) { 730 if (read(infd, &version, sizeof (version)) != 731 sizeof (version)) { 732 cryptoerror(LOG_STDERR, gettext( 733 "failed to get format version from " 734 "input file.")); 735 goto cleanup; 736 } 737 /* convert to host byte order */ 738 version = ntohl(version); 739 740 switch (version) { 741 case 1: 742 /* 743 * Version 1 output format: 744 * - Output format version 1 (4 bytes) 745 * - Iterations used in key gen function (4 bytes) 746 * - IV ('ivlen' bytes). The length algorithm-dependent 747 * - Salt data used in key gen (16 bytes) 748 * - Cipher text data (remainder of the file) 749 * 750 * An encrypted file has IV as first block (0 or 751 * more bytes depending on mechanism) followed 752 * by cipher text. Get the IV from the encrypted 753 * file. 754 */ 755 /* 756 * Read iteration count and salt data. 757 */ 758 if (read(infd, &iterations, 759 sizeof (iterations)) != sizeof (iterations)) { 760 cryptoerror(LOG_STDERR, gettext( 761 "failed to get iterations from " 762 "input file.")); 763 goto cleanup; 764 } 765 /* convert to host byte order */ 766 iterations = ntohl(iterations); 767 if (ivlen > 0 && 768 read(infd, pivbuf, ivlen) != ivlen) { 769 cryptoerror(LOG_STDERR, gettext( 770 "failed to get initialization " 771 "vector from input file.")); 772 goto cleanup; 773 } 774 if (read(infd, salt, sizeof (salt)) 775 != sizeof (salt)) { 776 cryptoerror(LOG_STDERR, gettext( 777 "failed to get salt data from " 778 "input file.")); 779 goto cleanup; 780 } 781 break; 782 default: 783 cryptoerror(LOG_STDERR, gettext( 784 "Unrecognized format version read from " 785 "input file - expected %d, got %d."), 786 SUNW_ENCRYPT_FILE_VERSION, version); 787 goto cleanup; 788 break; 789 } 790 } 791 792 /* 793 * If Kflag is set, let's find the token key now. 794 * 795 * If Kflag is not set and if encrypting, we need some random 796 * salt data to create the key. If decrypting, 797 * the salt should come from head of the file 798 * to be decrypted. 799 */ 800 if (Kflag) { 801 rv = get_token_key(hSession, keytype, key_label, pkeydata, 802 keysize, &key); 803 if (rv != CKR_OK) { 804 cryptoerror(LOG_STDERR, gettext( 805 "Can not find the token key")); 806 goto cleanup; 807 } else { 808 goto do_crypto; 809 } 810 } else if (cmd->type == CKA_ENCRYPT) { 811 rv = pkcs11_random_data((void *)salt, sizeof (salt)); 812 if (rv != 0) { 813 cryptoerror(LOG_STDERR, 814 gettext("unable to generate random " 815 "data for key salt.")); 816 goto cleanup; 817 } 818 } 819 820 821 /* 822 * If key input is read from a file, treat it as 823 * raw key data, unless it is to be used with RC4, 824 * in which case it must be used to generate a pkcs5 825 * key to address security concerns with RC4 keys. 826 */ 827 if (kflag && keyfile != NULL && keytype != CKK_RC4) { 828 /* XXX : why wasn't SUNW_C_KeyToObject used here? */ 829 CK_OBJECT_CLASS objclass = CKO_SECRET_KEY; 830 CK_ATTRIBUTE template[5]; 831 int nattr = 0; 832 833 template[nattr].type = CKA_CLASS; 834 template[nattr].pValue = &objclass; 835 template[nattr].ulValueLen = sizeof (objclass); 836 nattr++; 837 838 template[nattr].type = CKA_KEY_TYPE; 839 template[nattr].pValue = &keytype; 840 template[nattr].ulValueLen = sizeof (keytype); 841 nattr++; 842 843 template[nattr].type = cmd->type; 844 template[nattr].pValue = &truevalue; 845 template[nattr].ulValueLen = sizeof (truevalue); 846 nattr++; 847 848 template[nattr].type = CKA_TOKEN; 849 template[nattr].pValue = &falsevalue; 850 template[nattr].ulValueLen = sizeof (falsevalue); 851 nattr++; 852 853 template[nattr].type = CKA_VALUE; 854 template[nattr].pValue = pkeydata; 855 template[nattr].ulValueLen = keysize; 856 nattr++; 857 858 rv = C_CreateObject(hSession, template, nattr, &key); 859 } else { 860 /* 861 * If the encryption type has a fixed key length, 862 * then its not necessary to set the key length 863 * parameter when generating the key. 864 */ 865 if (keytype == CKK_DES || keytype == CKK_DES3) 866 keylen = 0; 867 else 868 keylen = 16; 869 870 /* 871 * Generate a cryptographically secure key using 872 * the key read from the file given (-k keyfile) or 873 * the passphrase entered by the user. 874 */ 875 rv = pkcs11_PasswdToPBKD2Object(hSession, (char *)pkeydata, 876 (size_t)keysize, (void *)salt, sizeof (salt), iterations, 877 keytype, keylen, cmd->flags, &key); 878 } 879 880 if (rv != CKR_OK) { 881 cryptoerror(LOG_STDERR, gettext( 882 "failed to generate a key: %s"), 883 pkcs11_strerror(rv)); 884 goto cleanup; 885 } 886 887 888 do_crypto: 889 /* Setup up mechanism */ 890 mech.mechanism = mech_type; 891 mech.pParameter = (CK_VOID_PTR)pivbuf; 892 mech.ulParameterLen = ivlen; 893 894 if ((rv = cmd->Init(hSession, &mech, key)) != CKR_OK) { 895 cryptoerror(LOG_STDERR, gettext( 896 "failed to initialize crypto operation: %s"), 897 pkcs11_strerror(rv)); 898 goto cleanup; 899 } 900 901 /* Write the version header encrypt command */ 902 if (cmd->type == CKA_ENCRYPT) { 903 /* convert to network order for storage */ 904 uint32_t netversion = htonl(version); 905 uint32_t netiter; 906 907 if (write(outfd, &netversion, sizeof (netversion)) 908 != sizeof (netversion)) { 909 cryptoerror(LOG_STDERR, gettext( 910 "failed to write version number " 911 "to output file.")); 912 goto cleanup; 913 } 914 /* 915 * Write the iteration and salt data, even if they 916 * were not used to generate a key. 917 */ 918 netiter = htonl(iterations); 919 if (write(outfd, &netiter, 920 sizeof (netiter)) != sizeof (netiter)) { 921 cryptoerror(LOG_STDERR, gettext( 922 "failed to write iterations to output")); 923 goto cleanup; 924 } 925 if (ivlen > 0 && write(outfd, pivbuf, ivlen) != ivlen) { 926 cryptoerror(LOG_STDERR, gettext( 927 "failed to write initialization vector " 928 "to output")); 929 goto cleanup; 930 } 931 if (write(outfd, salt, sizeof (salt)) != sizeof (salt)) { 932 cryptoerror(LOG_STDERR, gettext( 933 "failed to write salt data to output")); 934 goto cleanup; 935 } 936 } 937 938 if (crypt_multipart(cmd, hSession, infd, outfd, insbuf.st_size) == -1) { 939 goto cleanup; 940 } 941 942 errflag = B_FALSE; 943 944 /* 945 * Clean up 946 */ 947 cleanup: 948 /* Clear the key data, so others cannot snoop */ 949 if (pkeydata != NULL) { 950 bzero(pkeydata, keysize); 951 free(pkeydata); 952 pkeydata = NULL; 953 } 954 955 /* Destroy key object */ 956 if (Kflag != B_FALSE && key != (CK_OBJECT_HANDLE) 0) { 957 (void) C_DestroyObject(hSession, key); 958 } 959 960 /* free allocated memory */ 961 if (pSlotList != NULL) 962 free(pSlotList); 963 if (pivbuf != NULL) 964 free(pivbuf); 965 966 /* close all the files */ 967 if (iflag && (infd != -1)) 968 (void) close(infd); 969 if (oflag && (outfd != -1)) 970 (void) close(outfd); 971 972 /* rename tmp output to input file */ 973 if (inoutsame) { 974 if (rename(outfilename, inputfile) == -1) { 975 (void) unlink(outfilename); 976 cryptoerror(LOG_STDERR, gettext("rename failed.")); 977 } 978 } 979 980 /* If error occurred, remove the output file */ 981 if (errflag && outfilename != NULL) { 982 (void) unlink(outfilename); 983 } 984 985 /* close pkcs11 session */ 986 if (hSession != CK_INVALID_HANDLE) 987 (void) C_CloseSession(hSession); 988 989 (void) C_Finalize(NULL); 990 991 return (errflag); 992 } 993 994 /* 995 * Function for printing progress bar when the verbose flag 996 * is set. 997 * 998 * The vertical bar is printed at 25, 50, and 75% complete. 999 * 1000 * The function is passed the number of positions on the screen it needs to 1001 * advance and loops. 1002 */ 1003 1004 static void 1005 print_status(int pos_to_advance) 1006 { 1007 1008 while (pos_to_advance > 0) { 1009 switch (status_pos) { 1010 case 0: 1011 (void) fprintf(stderr, gettext("[")); 1012 break; 1013 case 19: 1014 case 39: 1015 case 59: 1016 (void) fprintf(stderr, gettext("|")); 1017 break; 1018 default: 1019 (void) fprintf(stderr, gettext(".")); 1020 } 1021 pos_to_advance--; 1022 status_pos++; 1023 } 1024 } 1025 1026 /* 1027 * Encrypt/Decrypt in multi part. 1028 * 1029 * This function reads the input file (infd) and writes the 1030 * encrypted/decrypted output to file (outfd). 1031 * 1032 * cmd - pointing to commandinfo 1033 * hSession - pkcs session 1034 * infd - input file descriptor 1035 * outfd - output file descriptor 1036 * 1037 */ 1038 1039 static int 1040 crypt_multipart(struct CommandInfo *cmd, CK_SESSION_HANDLE hSession, 1041 int infd, int outfd, off_t insize) 1042 { 1043 CK_RV rv; 1044 CK_ULONG resultlen; 1045 CK_ULONG resultbuflen; 1046 CK_BYTE_PTR resultbuf; 1047 CK_ULONG datalen; 1048 CK_BYTE databuf[BUFFERSIZE]; 1049 CK_BYTE outbuf[BUFFERSIZE+BLOCKSIZE]; 1050 CK_ULONG status_index = 0; /* current total file size read */ 1051 float status_last = 0.0; /* file size of last element used */ 1052 float status_incr = 0.0; /* file size element increments */ 1053 int pos; /* # of progress bar elements to be print */ 1054 ssize_t nread; 1055 boolean_t errflag = B_FALSE; 1056 1057 datalen = sizeof (databuf); 1058 resultbuflen = sizeof (outbuf); 1059 resultbuf = outbuf; 1060 1061 /* Divide into 79 increments for progress bar element spacing */ 1062 if (vflag && iflag) 1063 status_incr = (insize / 79.0); 1064 1065 while ((nread = read(infd, databuf, datalen)) > 0) { 1066 1067 /* Start with the initial buffer */ 1068 resultlen = resultbuflen; 1069 rv = cmd->Update(hSession, databuf, (CK_ULONG)nread, 1070 resultbuf, &resultlen); 1071 1072 /* Need a bigger buffer? */ 1073 if (rv == CKR_BUFFER_TOO_SMALL) { 1074 1075 /* free the old buffer */ 1076 if (resultbuf != NULL && resultbuf != outbuf) { 1077 bzero(resultbuf, resultbuflen); 1078 free(resultbuf); 1079 } 1080 1081 /* allocate a new big buffer */ 1082 if ((resultbuf = malloc((size_t)resultlen)) == NULL) { 1083 int err = errno; 1084 cryptoerror(LOG_STDERR, gettext("malloc: %s"), 1085 strerror(err)); 1086 return (-1); 1087 } 1088 resultbuflen = resultlen; 1089 1090 /* Try again with bigger buffer */ 1091 rv = cmd->Update(hSession, databuf, (CK_ULONG)nread, 1092 resultbuf, &resultlen); 1093 } 1094 1095 if (rv != CKR_OK) { 1096 errflag = B_TRUE; 1097 cryptoerror(LOG_STDERR, gettext( 1098 "crypto operation failed: %s"), 1099 pkcs11_strerror(rv)); 1100 break; 1101 } 1102 1103 /* write the output */ 1104 if (write(outfd, resultbuf, resultlen) != resultlen) { 1105 cryptoerror(LOG_STDERR, gettext( 1106 "failed to write result to output file.")); 1107 errflag = B_TRUE; 1108 break; 1109 } 1110 1111 if (vflag) { 1112 status_index += resultlen; 1113 1114 /* 1115 * If input is from stdin, do a our own progress bar 1116 * by printing periods at a pre-defined increment 1117 * until the file is done. 1118 */ 1119 if (!iflag) { 1120 1121 /* 1122 * Print at least 1 element in case the file 1123 * is small, it looks better than nothing. 1124 */ 1125 if (status_pos == 0) { 1126 (void) fprintf(stderr, gettext(".")); 1127 status_pos = 1; 1128 } 1129 1130 if ((status_index - status_last) > 1131 (PROGRESSSIZE)) { 1132 (void) fprintf(stderr, gettext(".")); 1133 status_last = status_index; 1134 } 1135 continue; 1136 } 1137 1138 /* Calculate the number of elements need to be print */ 1139 if (insize <= BUFFERSIZE) 1140 pos = 78; 1141 else 1142 pos = (int)((status_index - status_last) / 1143 status_incr); 1144 1145 /* Add progress bar elements, if needed */ 1146 if (pos > 0) { 1147 print_status(pos); 1148 status_last += (status_incr * pos); 1149 } 1150 } 1151 } 1152 1153 /* Print verbose completion */ 1154 if (vflag) { 1155 if (iflag) 1156 (void) fprintf(stderr, "]"); 1157 1158 (void) fprintf(stderr, "\n%s\n", gettext("Done.")); 1159 } 1160 1161 /* Error in reading */ 1162 if (nread == -1) { 1163 cryptoerror(LOG_STDERR, gettext( 1164 "error reading from input file")); 1165 errflag = B_TRUE; 1166 } 1167 1168 if (!errflag) { 1169 1170 /* Do the final part */ 1171 1172 rv = cmd->Final(hSession, resultbuf, &resultlen); 1173 1174 if (rv == CKR_OK) { 1175 /* write the output */ 1176 if (write(outfd, resultbuf, resultlen) != resultlen) { 1177 cryptoerror(LOG_STDERR, gettext( 1178 "failed to write result to output file.")); 1179 errflag = B_TRUE; 1180 } 1181 } else { 1182 cryptoerror(LOG_STDERR, gettext( 1183 "crypto operation failed: %s"), 1184 pkcs11_strerror(rv)); 1185 errflag = B_TRUE; 1186 } 1187 1188 } 1189 1190 if (resultbuf != NULL && resultbuf != outbuf) { 1191 bzero(resultbuf, resultbuflen); 1192 free(resultbuf); 1193 } 1194 1195 if (errflag) { 1196 return (-1); 1197 } else { 1198 return (0); 1199 } 1200 } 1201