xref: /titanic_52/usr/src/cmd/cmd-crypto/decrypt/decrypt.c (revision 0f1702c5201310f0529cd5abb77652e5e9b241b6)
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, B_FALSE);
486 		}
487 
488 		if (status != 0 || keysize == 0L) {
489 			cryptoerror(LOG_STDERR,
490 			    Kflag ? gettext("invalid password.") :
491 			    gettext("invalid key."));
492 			return (EXIT_FAILURE);
493 		}
494 	}
495 
496 	bzero(salt, sizeof (salt));
497 	/* Initialize pkcs */
498 	rv = C_Initialize(NULL);
499 	if (rv != CKR_OK && rv != CKR_CRYPTOKI_ALREADY_INITIALIZED) {
500 		cryptoerror(LOG_STDERR, gettext("failed to initialize "
501 		    "PKCS #11 framework: %s"), pkcs11_strerror(rv));
502 		goto cleanup;
503 	}
504 
505 	/* Get slot count */
506 	rv = C_GetSlotList(0, NULL_PTR, &slotcount);
507 	if (rv != CKR_OK || slotcount == 0) {
508 		cryptoerror(LOG_STDERR, gettext(
509 		    "failed to find any cryptographic provider,"
510 		    "please check with your system administrator: %s"),
511 		    pkcs11_strerror(rv));
512 		goto cleanup;
513 	}
514 
515 	/* Found at least one slot, allocate memory for slot list */
516 	pSlotList = malloc(slotcount * sizeof (CK_SLOT_ID));
517 	if (pSlotList == NULL_PTR) {
518 		int err = errno;
519 		cryptoerror(LOG_STDERR, gettext("malloc: %s"), strerror(err));
520 		goto cleanup;
521 	}
522 
523 	/* Get the list of slots */
524 	if ((rv = C_GetSlotList(0, pSlotList, &slotcount)) != CKR_OK) {
525 		cryptoerror(LOG_STDERR, gettext(
526 		    "failed to find any cryptographic provider,"
527 		    "please check with your system administrator: %s"),
528 		    pkcs11_strerror(rv));
529 		goto cleanup;
530 	}
531 
532 	if (lflag) {
533 
534 		/* Iterate through slots */
535 		for (slot = 0; slot < slotcount; slot++) {
536 
537 			/* Iterate through each mechanism */
538 			for (mek = 0; mek < MECH_ALIASES_COUNT; mek++) {
539 				rv = C_GetMechanismInfo(pSlotList[slot],
540 				    mech_aliases[mek].type, &info);
541 
542 				if (rv != CKR_OK)
543 					continue;
544 
545 				/*
546 				 * Set to minimum/maximum key sizes assuming
547 				 * the values available are not 0.
548 				 */
549 				if (info.ulMinKeySize && (info.ulMinKeySize <
550 				    mech_aliases[mek].keysize_min))
551 					mech_aliases[mek].keysize_min =
552 					    info.ulMinKeySize;
553 
554 				if (info.ulMaxKeySize && (info.ulMaxKeySize >
555 				    mech_aliases[mek].keysize_max))
556 					mech_aliases[mek].keysize_max =
557 					    info.ulMaxKeySize;
558 
559 				mech_aliases[mek].available = B_TRUE;
560 			}
561 
562 		}
563 
564 		algorithm_list();
565 
566 		errflag = B_FALSE;
567 		goto cleanup;
568 	}
569 
570 
571 	/*
572 	 * Find a slot with matching mechanism
573 	 *
574 	 * If -K is specified, we find the slot id for the token first, then
575 	 * check if the slot supports the algorithm.
576 	 */
577 	i = 0;
578 	if (Kflag) {
579 		kmfrv = kmf_pk11_token_lookup(NULL, token_label,
580 		    &token_slot_id);
581 		if (kmfrv != KMF_OK) {
582 			cryptoerror(LOG_STDERR,
583 			    gettext("no matching PKCS#11 token"));
584 			errflag = B_TRUE;
585 			goto cleanup;
586 		}
587 		rv = C_GetMechanismInfo(token_slot_id, mech_type, &info);
588 		if (rv == CKR_OK && (info.flags & cmd->flags))
589 			slotID = token_slot_id;
590 		else
591 			i = slotcount;
592 	} else {
593 		for (i = 0; i < slotcount; i++) {
594 			slotID = pSlotList[i];
595 			rv = C_GetMechanismInfo(slotID, mech_type, &info);
596 			if (rv != CKR_OK) {
597 				continue; /* to the next slot */
598 			} else {
599 				/*
600 				 * If the slot support the crypto, also
601 				 * make sure it supports the correct
602 				 * key generation mech if needed.
603 				 *
604 				 * We need PKCS5 when RC4 is used or
605 				 * when the key is entered on cmd line.
606 				 */
607 				if ((info.flags & cmd->flags) &&
608 				    (mech_type == CKM_RC4) ||
609 				    (keyfile == NULL)) {
610 					rv = C_GetMechanismInfo(slotID,
611 					    CKM_PKCS5_PBKD2, &kg_info);
612 					if (rv == CKR_OK)
613 						break;
614 				} else if (info.flags & cmd->flags) {
615 					break;
616 				}
617 			}
618 		}
619 	}
620 
621 	/* Show error if no matching mechanism found */
622 	if (i == slotcount) {
623 		cryptoerror(LOG_STDERR,
624 		    gettext("no cryptographic provider was "
625 		    "found for this algorithm -- %s"), algo_str);
626 		goto cleanup;
627 	}
628 
629 	/* Open a session */
630 	rv = C_OpenSession(slotID, CKF_SERIAL_SESSION,
631 	    NULL_PTR, NULL, &hSession);
632 
633 	if (rv != CKR_OK) {
634 		cryptoerror(LOG_STDERR,
635 		    gettext("can not open PKCS #11 session: %s"),
636 		    pkcs11_strerror(rv));
637 		goto cleanup;
638 	}
639 
640 	/*
641 	 * Generate IV data for encrypt.
642 	 */
643 	ivlen = mech_aliases[mech_match].ivlen;
644 	if ((pivbuf = malloc((size_t)ivlen)) == NULL) {
645 		int err = errno;
646 		cryptoerror(LOG_STDERR, gettext("malloc: %s"),
647 		    strerror(err));
648 		goto cleanup;
649 	}
650 
651 	if (cmd->type == CKA_ENCRYPT) {
652 		if ((pkcs11_random_data((void *)pivbuf,
653 		    mech_aliases[mech_match].ivlen)) != 0) {
654 			cryptoerror(LOG_STDERR, gettext(
655 			    "Unable to generate random "
656 			    "data for initialization vector."));
657 			goto cleanup;
658 		}
659 	}
660 
661 	/*
662 	 * Create the key object
663 	 */
664 	rv = pkcs11_mech2keytype(mech_type, &keytype);
665 	if (rv != CKR_OK) {
666 		cryptoerror(LOG_STDERR,
667 		    gettext("unable to find key type for algorithm."));
668 		goto cleanup;
669 	}
670 
671 	/* Open input file */
672 	if (iflag) {
673 		if ((infd = open(inputfile, O_RDONLY | O_NONBLOCK)) == -1) {
674 			cryptoerror(LOG_STDERR, gettext(
675 			    "can not open input file %s"), inputfile);
676 			goto cleanup;
677 		}
678 
679 		/* Get info on input file */
680 		if (fstat(infd, &insbuf) == -1) {
681 			cryptoerror(LOG_STDERR, gettext(
682 			    "can not stat input file %s"), inputfile);
683 			goto cleanup;
684 		}
685 	}
686 
687 	/*
688 	 * Prepare output file
689 	 * If the input & output file are same,
690 	 * the output is written to a temp
691 	 * file first, then renamed to the original file
692 	 * after the crypt operation
693 	 */
694 	inoutsame = B_FALSE;
695 	if (oflag) {
696 		outfilename = outputfile;
697 		if ((stat(outputfile, &outsbuf) != -1) &&
698 		    (insbuf.st_ino == outsbuf.st_ino)) {
699 			char *dir;
700 
701 			/* create temp file on same dir */
702 			dir = dirname(outputfile);
703 			(void) snprintf(tmpnam, sizeof (tmpnam),
704 			    "%s/encrXXXXXX", dir);
705 			outfilename = tmpnam;
706 			if ((outfd = mkstemp(tmpnam)) == -1) {
707 				cryptoerror(LOG_STDERR, gettext(
708 				    "cannot create temp file"));
709 				goto cleanup;
710 			}
711 			inoutsame = B_TRUE;
712 		} else {
713 			/* Create file for output */
714 			if ((outfd = open(outfilename,
715 			    O_CREAT|O_WRONLY|O_TRUNC, 0644)) == -1) {
716 				cryptoerror(LOG_STDERR, gettext(
717 				    "cannot open output file %s"),
718 				    outfilename);
719 				goto cleanup;
720 			}
721 		}
722 	}
723 
724 	/*
725 	 * Read the version number from the head of the file
726 	 * to know how to interpret the data that follows.
727 	 */
728 	if (cmd->type == CKA_DECRYPT) {
729 		if (read(infd, &version, sizeof (version)) !=
730 		    sizeof (version)) {
731 			cryptoerror(LOG_STDERR, gettext(
732 			    "failed to get format version from "
733 			    "input file."));
734 			goto cleanup;
735 		}
736 		/* convert to host byte order */
737 		version = ntohl(version);
738 
739 		switch (version) {
740 		case 1:
741 		/*
742 		 * Version 1 output format:
743 		 *  - Output format version 1 (4 bytes)
744 		 *  - Iterations used in key gen function (4 bytes)
745 		 *  - IV ('ivlen' bytes). The length algorithm-dependent
746 		 *  - Salt data used in key gen (16 bytes)
747 		 *  - Cipher text data (remainder of the file)
748 		 *
749 		 * An encrypted file has IV as first block (0 or
750 		 * more bytes depending on mechanism) followed
751 		 * by cipher text.  Get the IV from the encrypted
752 		 * file.
753 		 */
754 			/*
755 			 * Read iteration count and salt data.
756 			 */
757 			if (read(infd, &iterations,
758 			    sizeof (iterations)) != sizeof (iterations)) {
759 				cryptoerror(LOG_STDERR, gettext(
760 				    "failed to get iterations from "
761 				    "input file."));
762 				goto cleanup;
763 			}
764 			/* convert to host byte order */
765 			iterations = ntohl(iterations);
766 			if (ivlen > 0 &&
767 			    read(infd, pivbuf, ivlen) != ivlen) {
768 				cryptoerror(LOG_STDERR, gettext(
769 				    "failed to get initialization "
770 				    "vector from input file."));
771 				goto cleanup;
772 			}
773 			if (read(infd, salt, sizeof (salt))
774 			    != sizeof (salt)) {
775 				cryptoerror(LOG_STDERR, gettext(
776 				    "failed to get salt data from "
777 				    "input file."));
778 				goto cleanup;
779 			}
780 			break;
781 		default:
782 			cryptoerror(LOG_STDERR, gettext(
783 			    "Unrecognized format version read from "
784 			    "input file - expected %d, got %d."),
785 			    SUNW_ENCRYPT_FILE_VERSION, version);
786 			goto cleanup;
787 			break;
788 		}
789 	}
790 
791 	/*
792 	 * If Kflag is set, let's find the token key now.
793 	 *
794 	 * If Kflag is not set and if encrypting, we need some random
795 	 * salt data to create the key.  If decrypting,
796 	 * the salt should come from head of the file
797 	 * to be decrypted.
798 	 */
799 	if (Kflag) {
800 		rv = get_token_key(hSession, keytype, key_label, pkeydata,
801 		    keysize, &key);
802 		if (rv != CKR_OK) {
803 			cryptoerror(LOG_STDERR, gettext(
804 			    "Can not find the token key"));
805 			goto cleanup;
806 		} else {
807 			goto do_crypto;
808 		}
809 	} else if (cmd->type == CKA_ENCRYPT) {
810 		rv = pkcs11_random_data((void *)salt, sizeof (salt));
811 		if (rv != 0) {
812 			cryptoerror(LOG_STDERR,
813 			gettext("unable to generate random "
814 			    "data for key salt."));
815 			goto cleanup;
816 		}
817 	}
818 
819 
820 	/*
821 	 * If key input is read from  a file, treat it as
822 	 * raw key data, unless it is to be used with RC4,
823 	 * in which case it must be used to generate a pkcs5
824 	 * key to address security concerns with RC4 keys.
825 	 */
826 	if (kflag && keyfile != NULL && keytype != CKK_RC4) {
827 		/* XXX : why wasn't SUNW_C_KeyToObject used here? */
828 		CK_OBJECT_CLASS objclass = CKO_SECRET_KEY;
829 		CK_ATTRIBUTE template[5];
830 		int nattr = 0;
831 
832 		template[nattr].type = CKA_CLASS;
833 		template[nattr].pValue = &objclass;
834 		template[nattr].ulValueLen = sizeof (objclass);
835 		nattr++;
836 
837 		template[nattr].type = CKA_KEY_TYPE;
838 		template[nattr].pValue = &keytype;
839 		template[nattr].ulValueLen = sizeof (keytype);
840 		nattr++;
841 
842 		template[nattr].type = cmd->type;
843 		template[nattr].pValue = &truevalue;
844 		template[nattr].ulValueLen = sizeof (truevalue);
845 		nattr++;
846 
847 		template[nattr].type = CKA_TOKEN;
848 		template[nattr].pValue = &falsevalue;
849 		template[nattr].ulValueLen = sizeof (falsevalue);
850 		nattr++;
851 
852 		template[nattr].type = CKA_VALUE;
853 		template[nattr].pValue = pkeydata;
854 		template[nattr].ulValueLen = keysize;
855 		nattr++;
856 
857 		rv = C_CreateObject(hSession, template, nattr, &key);
858 	} else {
859 		/*
860 		 * If the encryption type has a fixed key length,
861 		 * then its not necessary to set the key length
862 		 * parameter when generating the key.
863 		 */
864 		if (keytype == CKK_DES || keytype == CKK_DES3)
865 			keylen = 0;
866 		else
867 			keylen = 16;
868 
869 		/*
870 		 * Generate a cryptographically secure key using
871 		 * the key read from the file given (-k keyfile) or
872 		 * the passphrase entered by the user.
873 		 */
874 		rv = pkcs11_PasswdToPBKD2Object(hSession, (char *)pkeydata,
875 		    (size_t)keysize, (void *)salt, sizeof (salt), iterations,
876 		    keytype, keylen, cmd->flags, &key);
877 	}
878 
879 	if (rv != CKR_OK) {
880 		cryptoerror(LOG_STDERR, gettext(
881 		    "failed to generate a key: %s"),
882 		    pkcs11_strerror(rv));
883 		goto cleanup;
884 	}
885 
886 
887 do_crypto:
888 	/* Setup up mechanism */
889 	mech.mechanism = mech_type;
890 	mech.pParameter = (CK_VOID_PTR)pivbuf;
891 	mech.ulParameterLen = ivlen;
892 
893 	if ((rv = cmd->Init(hSession, &mech, key)) != CKR_OK) {
894 		cryptoerror(LOG_STDERR, gettext(
895 		    "failed to initialize crypto operation: %s"),
896 		    pkcs11_strerror(rv));
897 		goto cleanup;
898 	}
899 
900 	/* Write the version header encrypt command */
901 	if (cmd->type == CKA_ENCRYPT) {
902 		/* convert to network order for storage */
903 		uint32_t	netversion = htonl(version);
904 		uint32_t	netiter;
905 
906 		if (write(outfd, &netversion, sizeof (netversion))
907 		    != sizeof (netversion)) {
908 			cryptoerror(LOG_STDERR, gettext(
909 			    "failed to write version number "
910 			    "to output file."));
911 			goto cleanup;
912 		}
913 		/*
914 		 * Write the iteration and salt data, even if they
915 		 * were not used to generate a key.
916 		 */
917 		netiter = htonl(iterations);
918 		if (write(outfd, &netiter,
919 		    sizeof (netiter)) != sizeof (netiter)) {
920 			cryptoerror(LOG_STDERR, gettext(
921 			    "failed to write iterations to output"));
922 			goto cleanup;
923 		}
924 		if (ivlen > 0 && write(outfd, pivbuf, ivlen) != ivlen) {
925 			cryptoerror(LOG_STDERR, gettext(
926 			    "failed to write initialization vector "
927 			    "to output"));
928 			goto cleanup;
929 		}
930 		if (write(outfd, salt, sizeof (salt)) != sizeof (salt)) {
931 			cryptoerror(LOG_STDERR, gettext(
932 			    "failed to write salt data to output"));
933 			goto cleanup;
934 		}
935 	}
936 
937 	if (crypt_multipart(cmd, hSession, infd, outfd, insbuf.st_size) == -1) {
938 		goto cleanup;
939 	}
940 
941 	errflag = B_FALSE;
942 
943 	/*
944 	 * Clean up
945 	 */
946 cleanup:
947 	/* Clear the key data, so others cannot snoop */
948 	if (pkeydata != NULL) {
949 		bzero(pkeydata, keysize);
950 		free(pkeydata);
951 		pkeydata = NULL;
952 	}
953 
954 	/* Destroy key object */
955 	if (Kflag != B_FALSE && key != (CK_OBJECT_HANDLE) 0) {
956 		(void) C_DestroyObject(hSession, key);
957 	}
958 
959 	/* free allocated memory */
960 	if (pSlotList != NULL)
961 		free(pSlotList);
962 	if (pivbuf != NULL)
963 		free(pivbuf);
964 
965 	/* close all the files */
966 	if (iflag && (infd != -1))
967 		(void) close(infd);
968 	if (oflag && (outfd != -1))
969 		(void) close(outfd);
970 
971 	/* rename tmp output to input file */
972 	if (inoutsame) {
973 		if (rename(outfilename, inputfile) == -1) {
974 			(void) unlink(outfilename);
975 			cryptoerror(LOG_STDERR, gettext("rename failed."));
976 		}
977 	}
978 
979 	/* If error occurred, remove the output file */
980 	if (errflag && outfilename != NULL) {
981 		(void) unlink(outfilename);
982 	}
983 
984 	/* close pkcs11 session */
985 	if (hSession != CK_INVALID_HANDLE)
986 		(void) C_CloseSession(hSession);
987 
988 	(void) C_Finalize(NULL);
989 
990 	return (errflag);
991 }
992 
993 /*
994  * Function for printing progress bar when the verbose flag
995  * is set.
996  *
997  * The vertical bar is printed at 25, 50, and 75% complete.
998  *
999  * The function is passed the number of positions on the screen it needs to
1000  * advance and loops.
1001  */
1002 
1003 static void
1004 print_status(int pos_to_advance)
1005 {
1006 
1007 	while (pos_to_advance > 0) {
1008 		switch (status_pos) {
1009 		case 0:
1010 			(void) fprintf(stderr, gettext("["));
1011 			break;
1012 		case 19:
1013 		case 39:
1014 		case 59:
1015 			(void) fprintf(stderr, gettext("|"));
1016 			break;
1017 		default:
1018 			(void) fprintf(stderr, gettext("."));
1019 		}
1020 		pos_to_advance--;
1021 		status_pos++;
1022 	}
1023 }
1024 
1025 /*
1026  * Encrypt/Decrypt in multi part.
1027  *
1028  * This function reads the input file (infd) and writes the
1029  * encrypted/decrypted output to file (outfd).
1030  *
1031  * cmd - pointing  to commandinfo
1032  * hSession - pkcs session
1033  * infd - input file descriptor
1034  * outfd - output file descriptor
1035  *
1036  */
1037 
1038 static int
1039 crypt_multipart(struct CommandInfo *cmd, CK_SESSION_HANDLE hSession,
1040 	int infd, int outfd, off_t insize)
1041 {
1042 	CK_RV		rv;
1043 	CK_ULONG	resultlen;
1044 	CK_ULONG	resultbuflen;
1045 	CK_BYTE_PTR	resultbuf;
1046 	CK_ULONG	datalen;
1047 	CK_BYTE		databuf[BUFFERSIZE];
1048 	CK_BYTE		outbuf[BUFFERSIZE+BLOCKSIZE];
1049 	CK_ULONG	status_index = 0; /* current total file size read */
1050 	float		status_last = 0.0; /* file size of last element used */
1051 	float		status_incr = 0.0; /* file size element increments */
1052 	int		pos; /* # of progress bar elements to be print */
1053 	ssize_t		nread;
1054 	boolean_t	errflag = B_FALSE;
1055 
1056 	datalen = sizeof (databuf);
1057 	resultbuflen = sizeof (outbuf);
1058 	resultbuf = outbuf;
1059 
1060 	/* Divide into 79 increments for progress bar element spacing */
1061 	if (vflag && iflag)
1062 		status_incr = (insize / 79.0);
1063 
1064 	while ((nread = read(infd, databuf, datalen)) > 0) {
1065 
1066 		/* Start with the initial buffer */
1067 		resultlen = resultbuflen;
1068 		rv = cmd->Update(hSession, databuf, (CK_ULONG)nread,
1069 		    resultbuf, &resultlen);
1070 
1071 		/* Need a bigger buffer? */
1072 		if (rv == CKR_BUFFER_TOO_SMALL) {
1073 
1074 			/* free the old buffer */
1075 			if (resultbuf != NULL && resultbuf != outbuf) {
1076 				bzero(resultbuf, resultbuflen);
1077 				free(resultbuf);
1078 			}
1079 
1080 			/* allocate a new big buffer */
1081 			if ((resultbuf = malloc((size_t)resultlen)) == NULL) {
1082 				int err = errno;
1083 				cryptoerror(LOG_STDERR, gettext("malloc: %s"),
1084 				    strerror(err));
1085 				return (-1);
1086 			}
1087 			resultbuflen = resultlen;
1088 
1089 			/* Try again with bigger buffer */
1090 			rv = cmd->Update(hSession, databuf, (CK_ULONG)nread,
1091 			    resultbuf, &resultlen);
1092 		}
1093 
1094 		if (rv != CKR_OK) {
1095 			errflag = B_TRUE;
1096 			cryptoerror(LOG_STDERR, gettext(
1097 			    "crypto operation failed: %s"),
1098 			    pkcs11_strerror(rv));
1099 			break;
1100 		}
1101 
1102 		/* write the output */
1103 		if (write(outfd, resultbuf, resultlen) != resultlen) {
1104 			cryptoerror(LOG_STDERR, gettext(
1105 			    "failed to write result to output file."));
1106 			errflag = B_TRUE;
1107 			break;
1108 		}
1109 
1110 		if (vflag) {
1111 			status_index += resultlen;
1112 
1113 			/*
1114 			 * If input is from stdin, do a our own progress bar
1115 			 * by printing periods at a pre-defined increment
1116 			 * until the file is done.
1117 			 */
1118 			if (!iflag) {
1119 
1120 				/*
1121 				 * Print at least 1 element in case the file
1122 				 * is small, it looks better than nothing.
1123 				 */
1124 				if (status_pos == 0) {
1125 					(void) fprintf(stderr, gettext("."));
1126 					status_pos = 1;
1127 				}
1128 
1129 				if ((status_index - status_last) >
1130 				    (PROGRESSSIZE)) {
1131 					(void) fprintf(stderr, gettext("."));
1132 					status_last = status_index;
1133 				}
1134 				continue;
1135 			}
1136 
1137 			/* Calculate the number of elements need to be print */
1138 			if (insize <= BUFFERSIZE)
1139 				pos = 78;
1140 			else
1141 				pos = (int)((status_index - status_last) /
1142 				    status_incr);
1143 
1144 			/* Add progress bar elements, if needed */
1145 			if (pos > 0) {
1146 				print_status(pos);
1147 				status_last += (status_incr * pos);
1148 			}
1149 		}
1150 	}
1151 
1152 	/* Print verbose completion */
1153 	if (vflag) {
1154 		if (iflag)
1155 			(void) fprintf(stderr, "]");
1156 
1157 		(void) fprintf(stderr, "\n%s\n", gettext("Done."));
1158 	}
1159 
1160 	/* Error in reading */
1161 	if (nread == -1) {
1162 		cryptoerror(LOG_STDERR, gettext(
1163 		    "error reading from input file"));
1164 		errflag = B_TRUE;
1165 	}
1166 
1167 	if (!errflag) {
1168 
1169 		/* Do the final part */
1170 
1171 		rv = cmd->Final(hSession, resultbuf, &resultlen);
1172 
1173 		if (rv == CKR_OK) {
1174 			/* write the output */
1175 			if (write(outfd, resultbuf, resultlen) != resultlen) {
1176 				cryptoerror(LOG_STDERR, gettext(
1177 				    "failed to write result to output file."));
1178 				errflag = B_TRUE;
1179 			}
1180 		} else {
1181 			cryptoerror(LOG_STDERR, gettext(
1182 			    "crypto operation failed: %s"),
1183 			    pkcs11_strerror(rv));
1184 			errflag = B_TRUE;
1185 		}
1186 
1187 	}
1188 
1189 	if (resultbuf != NULL && resultbuf != outbuf) {
1190 		bzero(resultbuf, resultbuflen);
1191 		free(resultbuf);
1192 	}
1193 
1194 	if (errflag) {
1195 		return (-1);
1196 	} else {
1197 		return (0);
1198 	}
1199 }
1200