pk11.c 33.5 KB
Newer Older
Evan Hunt's avatar
Evan Hunt committed
1
/*
Mark Andrews's avatar
Mark Andrews committed
2
 * Copyright (C) 2014  Internet Systems Consortium, Inc. ("ISC")
Evan Hunt's avatar
Evan Hunt committed
3 4 5 6 7
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
Mark Andrews's avatar
Mark Andrews committed
8 9 10 11 12 13 14
 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
 * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
Evan Hunt's avatar
Evan Hunt committed
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
 */

/*
 * Portions copyright (c) 2008 Nominet UK.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * This product includes software developed by the OpenSSL Project for
 * use in the OpenSSL Toolkit (http://www.openssl.org/).
 *
 * This project also referenced hw_pkcs11-0.9.7b.patch written by
 * Afchine Madjlessi.
 */
/*
 * ====================================================================
 * Copyright (c) 2000-2001 The OpenSSL Project.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. All advertising materials mentioning features or use of this
 *    software must display the following acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
 *
 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For written permission, please contact
 *    licensing@OpenSSL.org.
 *
 * 5. Products derived from this software may not be called "OpenSSL"
 *    nor may "OpenSSL" appear in their names without prior written
 *    permission of the OpenSSL Project.
 *
 * 6. Redistributions of any form whatsoever must retain the following
 *    acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
 *
 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 * ====================================================================
 *
 * This product includes cryptographic software written by Eric Young
 * (eay@cryptsoft.com).  This product includes software written by Tim
 * Hudson (tjh@cryptsoft.com).
 *
 */

/* $Id$ */

#include <config.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <isc/log.h>
#include <isc/mem.h>
#include <isc/once.h>
119
#include <isc/platform.h>
Evan Hunt's avatar
Evan Hunt committed
120 121 122 123 124 125
#include <isc/stdio.h>
#include <isc/thread.h>
#include <isc/util.h>

#include <dst/result.h>

126 127
#include <pk11/pk11.h>
#include <pk11/internal.h>
128
#include <pk11/result.h>
Evan Hunt's avatar
Evan Hunt committed
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143

#include <pkcs11/cryptoki.h>
#include <pkcs11/pkcs11.h>

#define PINLEN	32

#ifndef PK11_NO_LOGERR
#define PK11_NO_LOGERR 1
#endif

static isc_once_t once = ISC_ONCE_INIT;
static isc_mem_t *pk11_mctx = NULL;
static isc_int32_t allocsize = 0;
static isc_boolean_t initialized = ISC_FALSE;

144 145 146
typedef struct pk11_session pk11_session_t;
typedef struct pk11_token pk11_token_t;
typedef ISC_LIST(pk11_session_t) pk11_sessionlist_t;
Evan Hunt's avatar
Evan Hunt committed
147

148
struct pk11_session {
Evan Hunt's avatar
Evan Hunt committed
149 150
	unsigned int		magic;
	CK_SESSION_HANDLE	session;
151 152
	ISC_LINK(pk11_session_t) link;
	pk11_token_t		*token;
Evan Hunt's avatar
Evan Hunt committed
153 154
};

155
struct pk11_token {
Evan Hunt's avatar
Evan Hunt committed
156 157
	unsigned int		magic;
	unsigned int		operations;
158
	ISC_LINK(pk11_token_t)	link;
Evan Hunt's avatar
Evan Hunt committed
159
	CK_SLOT_ID		slotid;
160
	pk11_sessionlist_t	sessions;
Evan Hunt's avatar
Evan Hunt committed
161 162 163 164 165 166 167
	isc_boolean_t		logged;
	char			name[32];
	char			manuf[32];
	char			model[16];
	char			serial[16];
	char			pin[PINLEN];
};
168
static ISC_LIST(pk11_token_t) tokens;
Evan Hunt's avatar
Evan Hunt committed
169

170 171 172 173 174 175 176
static pk11_token_t *rand_token;
static pk11_token_t *best_rsa_token;
static pk11_token_t *best_dsa_token;
static pk11_token_t *best_dh_token;
static pk11_token_t *digest_token;
static pk11_token_t *best_ec_token;
static pk11_token_t *best_gost_token;
177
static pk11_token_t *aes_token;
Evan Hunt's avatar
Evan Hunt committed
178 179

static isc_result_t free_all_sessions(void);
180 181 182
static isc_result_t free_session_list(pk11_sessionlist_t *slist);
static isc_result_t setup_session(pk11_session_t *sp,
				  pk11_token_t *token,
Evan Hunt's avatar
Evan Hunt committed
183 184
				  isc_boolean_t rw);
static void choose_slots(void);
185
static isc_result_t token_login(pk11_session_t *sp);
Evan Hunt's avatar
Evan Hunt committed
186 187 188
static char *percent_decode(char *x, size_t *len);
static isc_boolean_t pk11strcmp(const char *x, size_t lenx,
				const char *y, size_t leny);
189
static CK_ATTRIBUTE *push_attribute(pk11_object_t *obj,
Evan Hunt's avatar
Evan Hunt committed
190 191 192 193 194 195
				    isc_mem_t *mctx,
				    size_t len);

static isc_mutex_t alloclock;
static isc_mutex_t sessionlock;

196
static pk11_sessionlist_t actives;
Evan Hunt's avatar
Evan Hunt committed
197 198

static CK_C_INITIALIZE_ARGS pk11_init_args = {
Mark Andrews's avatar
Mark Andrews committed
199 200 201 202 203 204
	NULL_PTR,               /* CreateMutex */
	NULL_PTR,               /* DestroyMutex */
	NULL_PTR,               /* LockMutex */
	NULL_PTR,               /* UnlockMutex */
	CKF_OS_LOCKING_OK,      /* flags */
	NULL_PTR,               /* pReserved */
Evan Hunt's avatar
Evan Hunt committed
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
};

#ifndef PK11_LIB_LOCATION
#define PK11_LIB_LOCATION	"unknown_provider"
#endif

#ifndef WIN32
static const char *lib_name = PK11_LIB_LOCATION;
#else
static const char *lib_name = PK11_LIB_LOCATION ".dll";
#endif

void
pk11_set_lib_name(const char *name) {
	lib_name = name;
}

const char *
pk11_get_lib_name(void) {
	return (lib_name);
}

static void
initialize(void) {
	char *pk11_provider;

	RUNTIME_CHECK(isc_mutex_init(&alloclock) == ISC_R_SUCCESS);
	RUNTIME_CHECK(isc_mutex_init(&sessionlock) == ISC_R_SUCCESS);

	pk11_provider = getenv("PKCS11_PROVIDER");
	if (pk11_provider != NULL)
		lib_name = pk11_provider;
}

void *
pk11_mem_get(size_t size) {
	void *ptr;

	LOCK(&alloclock);
	if (pk11_mctx != NULL)
		ptr = isc_mem_get(pk11_mctx, size);
	else {
		ptr = malloc(size);
		if (ptr != NULL)
249
			allocsize += (int)size;
Evan Hunt's avatar
Evan Hunt committed
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
	}
	UNLOCK(&alloclock);

	if (ptr != NULL)
		memset(ptr, 0, size);
	return (ptr);
}

void
pk11_mem_put(void *ptr, size_t size) {
	if (ptr != NULL)
		memset(ptr, 0, size);
	LOCK(&alloclock);
	if (pk11_mctx != NULL)
		isc_mem_put(pk11_mctx, ptr, size);
	else {
		if (ptr != NULL)
267
			allocsize -= (int)size;
Evan Hunt's avatar
Evan Hunt committed
268 269 270 271 272
		free(ptr);
	}
	UNLOCK(&alloclock);
}

273 274 275
isc_result_t
pk11_initialize(isc_mem_t *mctx, const char *engine) {
	isc_result_t result;
Evan Hunt's avatar
Evan Hunt committed
276 277 278 279 280 281 282 283 284
	CK_RV rv;

	RUNTIME_CHECK(isc_once_do(&once, initialize) == ISC_R_SUCCESS);

	LOCK(&alloclock);
	if ((mctx != NULL) && (pk11_mctx == NULL) && (allocsize == 0))
		isc_mem_attach(mctx, &pk11_mctx);
	if (initialized) {
		UNLOCK(&alloclock);
285
		return (ISC_R_SUCCESS);
Evan Hunt's avatar
Evan Hunt committed
286 287 288 289 290 291
	} else {
		LOCK(&sessionlock);
		initialized = ISC_TRUE;
		UNLOCK(&alloclock);
	}

292 293 294
	ISC_LIST_INIT(tokens);
	ISC_LIST_INIT(actives);

Mark Andrews's avatar
Mark Andrews committed
295 296
	if (engine != NULL)
		lib_name = engine;
Evan Hunt's avatar
Evan Hunt committed
297 298 299 300

	/* Initialize the CRYPTOKI library */
	rv = pkcs_C_Initialize((CK_VOID_PTR) &pk11_init_args);

301 302 303 304
	if (rv == 0xfe) {
		result = PK11_R_NOPROVIDER;
		goto unlock;
	}
Evan Hunt's avatar
Evan Hunt committed
305
	if (rv != CKR_OK) {
306 307
		result = PK11_R_INITFAILED;
		goto unlock;
Evan Hunt's avatar
Evan Hunt committed
308 309 310 311
	}

	choose_slots();
#ifdef PKCS11CRYPTO
312 313 314 315 316 317 318 319
	if (rand_token == NULL) {
		result = PK11_R_NORANDOMSERVICE;
		goto unlock;
	}
	if (digest_token == NULL) {
		result = PK11_R_NODIGESTSERVICE;
		goto unlock;
	}
320
#if defined(ISC_PLATFORM_USESIT) && defined(AES_SIT)
321 322 323 324
	if (aes_token == NULL) {
		result = PK11_R_NOAESSERVICE;
		goto unlock;
	}
325
#endif
Evan Hunt's avatar
Evan Hunt committed
326
#endif /* PKCS11CRYPTO */
327 328
	result = ISC_R_SUCCESS;
 unlock:
Evan Hunt's avatar
Evan Hunt committed
329
	UNLOCK(&sessionlock);
330
	return (result);
Evan Hunt's avatar
Evan Hunt committed
331 332 333
}

isc_result_t
334
pk11_finalize(void) {
335
	pk11_token_t *token, *next;
Evan Hunt's avatar
Evan Hunt committed
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
	isc_result_t ret;

	ret = free_all_sessions();
	(void) pkcs_C_Finalize(NULL_PTR);
	token = ISC_LIST_HEAD(tokens);
	while (token != NULL) {
		next = ISC_LIST_NEXT(token, link);
		ISC_LIST_UNLINK(tokens, token, link);
		if (token == rand_token)
			rand_token = NULL;
		if (token == best_rsa_token)
			best_rsa_token = NULL;
		if (token == best_dsa_token)
			best_dsa_token = NULL;
		if (token == best_dh_token)
			best_dh_token = NULL;
		if (token == digest_token)
			digest_token = NULL;
		if (token == best_ec_token)
			best_ec_token = NULL;
		if (token == best_gost_token)
			best_gost_token = NULL;
358 359
		if (token == aes_token)
			aes_token = NULL;
Evan Hunt's avatar
Evan Hunt committed
360 361 362 363 364 365 366 367 368 369 370 371 372
		pk11_mem_put(token, sizeof(*token));
		token = next;
	}
	if (pk11_mctx != NULL)
		isc_mem_detach(&pk11_mctx);
	initialized = ISC_FALSE;
	return (ret);
}

isc_result_t
pk11_rand_bytes(unsigned char *buf, int num) {
	isc_result_t ret;
	CK_RV rv;
373
	pk11_context_t ctx;
Evan Hunt's avatar
Evan Hunt committed
374

375 376 377 378 379
	ret = pk11_get_session(&ctx, OP_RAND, ISC_FALSE, ISC_FALSE,
			       ISC_FALSE, NULL, 0);
	if ((ret != ISC_R_SUCCESS) &&
	    (ret != PK11_R_NODIGESTSERVICE) &&
	    (ret != PK11_R_NOAESSERVICE))
Evan Hunt's avatar
Evan Hunt committed
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
		return (ret);
	RUNTIME_CHECK(ctx.session != CK_INVALID_HANDLE);
	rv = pkcs_C_GenerateRandom(ctx.session,
				   (CK_BYTE_PTR) buf, (CK_ULONG) num);
	pk11_return_session(&ctx);
	if (rv == CKR_OK)
		return (ISC_R_SUCCESS);
	else
		return (DST_R_CRYPTOFAILURE);
}

#define SEEDSIZE	1024

static CK_BYTE seed[SEEDSIZE];

void
pk11_rand_seed_fromfile(const char *randomfile) {
397
	pk11_context_t ctx;
Evan Hunt's avatar
Evan Hunt committed
398 399 400 401
	FILE *stream = NULL;
	size_t cc = 0;
	isc_result_t ret;

402 403 404 405 406
	ret = pk11_get_session(&ctx, OP_RAND, ISC_FALSE, ISC_FALSE,
			       ISC_FALSE, NULL, 0);
	if ((ret != ISC_R_SUCCESS) &&
	    (ret != PK11_R_NODIGESTSERVICE) &&
	    (ret != PK11_R_NOAESSERVICE))
Evan Hunt's avatar
Evan Hunt committed
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
		return;
	RUNTIME_CHECK(ctx.session != CK_INVALID_HANDLE);
	ret = isc_stdio_open(randomfile, "r", &stream);
	if (ret != ISC_R_SUCCESS)
		goto cleanup;
	ret = isc_stdio_read(seed, 1, SEEDSIZE, stream, &cc);
	if (ret!= ISC_R_SUCCESS)
		goto cleanup;
	ret = isc_stdio_close(stream);
	stream = NULL;
	if (ret!= ISC_R_SUCCESS)
		goto cleanup;
	(void) pkcs_C_SeedRandom(ctx.session, seed, (CK_ULONG) cc);

    cleanup:
	if (stream != NULL)
		(void) isc_stdio_close(stream);
	pk11_return_session(&ctx);
Mark Andrews's avatar
Mark Andrews committed
425
}
Evan Hunt's avatar
Evan Hunt committed
426 427

isc_result_t
428
pk11_get_session(pk11_context_t *ctx, pk11_optype_t optype,
429 430
		 isc_boolean_t need_services, isc_boolean_t rw,
		 isc_boolean_t logon, const char *pin, CK_SLOT_ID slot)
Evan Hunt's avatar
Evan Hunt committed
431
{
432 433 434
	pk11_token_t *token = NULL;
	pk11_sessionlist_t *freelist;
	pk11_session_t *sp;
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
	isc_result_t ret;
#ifdef PKCS11CRYPTO
	isc_result_t service_ret = ISC_R_SUCCESS;
#else
	UNUSED(need_services);
#endif 

	memset(ctx, 0, sizeof(pk11_context_t));
	ctx->handle = NULL;
	ctx->session = CK_INVALID_HANDLE;

	ret = pk11_initialize(NULL, NULL);
#ifdef PKCS11CRYPTO
	if (ret == PK11_R_NORANDOMSERVICE ||
	    ret == PK11_R_NODIGESTSERVICE ||
	    ret == PK11_R_NOAESSERVICE) {
		if (need_services)
			return (ret);
		service_ret = ret;
	}
	else
#endif /* PKCS11CRYPTO */
	if (ret != ISC_R_SUCCESS)
		return (ret);
Evan Hunt's avatar
Evan Hunt committed
459 460 461 462 463 464 465 466 467 468 469 470 471

	LOCK(&sessionlock);
	/* wait for initialization to finish */
	UNLOCK(&sessionlock);

	switch(optype) {
#ifdef PKCS11CRYPTO
	case OP_RAND:
		token = rand_token;
		break;
	case OP_DIGEST:
		token = digest_token;
		break;
472 473 474
	case OP_AES:
		token = aes_token;
		break;
Evan Hunt's avatar
Evan Hunt committed
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
	case OP_ANY:
		for (token = ISC_LIST_HEAD(tokens);
		     token != NULL;
		     token = ISC_LIST_NEXT(token, link))
			if (token->slotid == slot)
				break;
		break;
#endif
	default:
		for (token = ISC_LIST_HEAD(tokens);
		     token != NULL;
		     token = ISC_LIST_NEXT(token, link))
			if (token->slotid == slot)
				break;
#ifdef PKCS11CRYPTO
		if ((token == NULL) ||
		    ((token->operations & (1 << optype)) == 0))
			return (ISC_R_NOTFOUND);
#endif
		break;
	}
	if (token == NULL)
		return (ISC_R_NOTFOUND);

	/* Override the token's PIN */
	if (logon && pin != NULL && *pin != '\0') {
		memset(token->pin, 0, PINLEN);
		strncpy(token->pin, pin, PINLEN);
	}

	freelist = &token->sessions;

	LOCK(&sessionlock);
	sp = ISC_LIST_HEAD(*freelist);
	if (sp != NULL) {
		ISC_LIST_UNLINK(*freelist, sp, link);
		ISC_LIST_APPEND(actives, sp, link);
		UNLOCK(&sessionlock);
		if (logon)
			ret = token_login(sp);
		ctx->handle = sp;
		ctx->session = sp->session;
		return (ret);
	}
	UNLOCK(&sessionlock);

	sp = pk11_mem_get(sizeof(*sp));
	if (sp == NULL)
		return (ISC_R_NOMEMORY);
	sp->magic = SES_MAGIC;
	sp->token = token;
	sp->session = CK_INVALID_HANDLE;
	ISC_LINK_INIT(sp, link);
	ret = setup_session(sp, token, rw);
	if ((ret == ISC_R_SUCCESS) && logon)
		ret = token_login(sp);
	LOCK(&sessionlock);
	ISC_LIST_APPEND(actives, sp, link);
	UNLOCK(&sessionlock);
	ctx->handle = sp;
	ctx->session = sp->session;
536 537 538 539
#ifdef PKCS11CRYPTO
	if (ret == ISC_R_SUCCESS)
		ret = service_ret;
#endif
Evan Hunt's avatar
Evan Hunt committed
540 541 542 543
	return (ret);
}

void
544 545
pk11_return_session(pk11_context_t *ctx) {
	pk11_session_t *sp = (pk11_session_t *) ctx->handle;
Evan Hunt's avatar
Evan Hunt committed
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566

	if (sp == NULL)
		return;
	ctx->handle = NULL;
	ctx->session = CK_INVALID_HANDLE;

	LOCK(&sessionlock);
	ISC_LIST_UNLINK(actives, sp, link);
	UNLOCK(&sessionlock);
	if (sp->session == CK_INVALID_HANDLE) {
		pk11_mem_put(sp, sizeof(*sp));
		return;
	}

	LOCK(&sessionlock);
	ISC_LIST_APPEND(sp->token->sessions, sp, link);
	UNLOCK(&sessionlock);
}

static isc_result_t
free_all_sessions(void) {
567
	pk11_token_t *token;
Evan Hunt's avatar
Evan Hunt committed
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
	isc_result_t ret = ISC_R_SUCCESS;
	isc_result_t oret;

	for (token = ISC_LIST_HEAD(tokens);
	     token != NULL;
	     token = ISC_LIST_NEXT(token, link)) {
		oret = free_session_list(&token->sessions);
		if (oret != ISC_R_SUCCESS)
			ret = oret;
	}
	if (!ISC_LIST_EMPTY(actives)) {
		ret = ISC_R_ADDRINUSE;
		oret = free_session_list(&actives);
		if (oret != ISC_R_SUCCESS)
			ret = oret;
	}
	return (ret);
}

static isc_result_t
588 589
free_session_list(pk11_sessionlist_t *slist) {
	pk11_session_t *sp;
Evan Hunt's avatar
Evan Hunt committed
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
	CK_RV rv;
	isc_result_t ret;

	ret = ISC_R_SUCCESS;
	LOCK(&sessionlock);
	while (!ISC_LIST_EMPTY(*slist)) {
		sp = ISC_LIST_HEAD(*slist);
		UNLOCK(&sessionlock);
		if (sp->session != CK_INVALID_HANDLE) {
			rv = pkcs_C_CloseSession(sp->session);
			if (rv != CKR_OK)
				ret = DST_R_CRYPTOFAILURE;
		}
		LOCK(&sessionlock);
		ISC_LIST_UNLINK(*slist, sp, link);
		pk11_mem_put(sp, sizeof(*sp));
	}
	UNLOCK(&sessionlock);

	return (ret);
}

static isc_result_t
613
setup_session(pk11_session_t *sp, pk11_token_t *token,
Evan Hunt's avatar
Evan Hunt committed
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
	      isc_boolean_t rw)
{
	CK_RV rv;
	CK_FLAGS flags = CKF_SERIAL_SESSION;

	if (rw)
		flags += CKF_RW_SESSION;

	rv = pkcs_C_OpenSession(token->slotid, flags, NULL_PTR,
				NULL_PTR, &sp->session);
	if (rv != CKR_OK)
		return (DST_R_CRYPTOFAILURE);
	return (ISC_R_SUCCESS);
}

static isc_result_t
630
token_login(pk11_session_t *sp) {
Evan Hunt's avatar
Evan Hunt committed
631
	CK_RV rv;
632
	pk11_token_t *token = sp->token;
Evan Hunt's avatar
Evan Hunt committed
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
	isc_result_t ret = ISC_R_SUCCESS;

	LOCK(&sessionlock);
	if (!token->logged) {
		rv = pkcs_C_Login(sp->session, CKU_USER,
				  (CK_UTF8CHAR_PTR) token->pin,
				  (CK_ULONG) strlen(token->pin));
		if (rv != CKR_OK) {
			ret = ISC_R_NOPERM;
#if PK11_NO_LOGERR
			pk11_error_fatalcheck(__FILE__, __LINE__,
					      "pkcs_C_Login", rv);
#endif
		} else
			token->logged = ISC_TRUE;
	}
	UNLOCK(&sessionlock);
	return (ret);
}

static void
choose_slots(void) {
	CK_MECHANISM_INFO mechInfo;
	CK_TOKEN_INFO tokenInfo;
	CK_RV rv;
	CK_SLOT_ID slot;
	CK_SLOT_ID_PTR slotList;
	CK_ULONG slotCount;
661
	pk11_token_t *token;
Evan Hunt's avatar
Evan Hunt committed
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
	unsigned int i;

	slotCount = 0;
	PK11_FATALCHECK(pkcs_C_GetSlotList, (CK_FALSE, NULL_PTR, &slotCount));
	/* it's not an error if we didn't find any providers */
	if (slotCount == 0)
		return;
	slotList = pk11_mem_get(sizeof(CK_SLOT_ID_PTR) * slotCount);
	RUNTIME_CHECK(slotList != NULL);
	PK11_FATALCHECK(pkcs_C_GetSlotList, (CK_FALSE, slotList, &slotCount));

	for (i = 0; i < slotCount; i++) {
		slot = slotList[i];

		rv = pkcs_C_GetTokenInfo(slot, &tokenInfo);
		if (rv != CKR_OK)
			continue;
		token = pk11_mem_get(sizeof(*token));
		RUNTIME_CHECK(token != NULL);
		token->magic = TOK_MAGIC;
		token->slotid = slot;
		ISC_LINK_INIT(token, link);
		ISC_LIST_INIT(token->sessions);
685 686 687 688
		memmove(token->name, tokenInfo.label, 32);
		memmove(token->manuf, tokenInfo.manufacturerID, 32);
		memmove(token->model, tokenInfo.model, 16);
		memmove(token->serial, tokenInfo.serialNumber, 16);
Evan Hunt's avatar
Evan Hunt committed
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
		ISC_LIST_APPEND(tokens, token, link);
		if ((tokenInfo.flags & CKF_RNG) == 0)
			goto try_rsa;
		token->operations |= 1 << OP_RAND;
		if (rand_token == NULL)
			rand_token = token;

	try_rsa:
		rv = pkcs_C_GetMechanismInfo(slot, CKM_RSA_PKCS_KEY_PAIR_GEN,
					     &mechInfo);
		if ((rv != CKR_OK) ||
		    ((mechInfo.flags & CKF_GENERATE_KEY_PAIR) == 0))
			goto try_dsa;
		rv = pkcs_C_GetMechanismInfo(slot, CKM_MD5_RSA_PKCS,
					     &mechInfo);
		if ((rv != CKR_OK) ||
		    ((mechInfo.flags & CKF_SIGN) == 0) ||
		    ((mechInfo.flags & CKF_VERIFY) == 0))
			goto try_dsa;
		rv = pkcs_C_GetMechanismInfo(slot, CKM_SHA1_RSA_PKCS,
					     &mechInfo);
		if ((rv != CKR_OK) ||
		    ((mechInfo.flags & CKF_SIGN) == 0) ||
		    ((mechInfo.flags & CKF_VERIFY) == 0))
			goto try_dsa;
		rv = pkcs_C_GetMechanismInfo(slot, CKM_SHA256_RSA_PKCS,
					     &mechInfo);
		if ((rv != CKR_OK) ||
		    ((mechInfo.flags & CKF_SIGN) == 0) ||
		    ((mechInfo.flags & CKF_VERIFY) == 0))
			goto try_dsa;
		rv = pkcs_C_GetMechanismInfo(slot, CKM_SHA512_RSA_PKCS,
					     &mechInfo);
		if ((rv != CKR_OK) ||
		    ((mechInfo.flags & CKF_SIGN) == 0) ||
		    ((mechInfo.flags & CKF_VERIFY) == 0))
			goto try_dsa;
		token->operations |= 1 << OP_RSA;
		if (best_rsa_token == NULL)
			best_rsa_token = token;

	try_dsa:
		rv = pkcs_C_GetMechanismInfo(slot, CKM_DSA_PARAMETER_GEN,
					     &mechInfo);
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_GENERATE) == 0))
			goto try_dh;
		rv = pkcs_C_GetMechanismInfo(slot, CKM_DSA_KEY_PAIR_GEN,
					     &mechInfo);
		if ((rv != CKR_OK) ||
		    ((mechInfo.flags & CKF_GENERATE_KEY_PAIR) == 0))
			goto try_dh;
		rv = pkcs_C_GetMechanismInfo(slot, CKM_DSA_SHA1, &mechInfo);
		if ((rv != CKR_OK) ||
		    ((mechInfo.flags & CKF_SIGN) == 0) ||
		    ((mechInfo.flags & CKF_VERIFY) == 0))
			goto try_dh;
		token->operations |= 1 << OP_DSA;
		if (best_dsa_token == NULL)
			best_dsa_token = token;

	try_dh:
#ifdef notdef
		rv = pkcs_C_GetMechanismInfo(slot, CKM_DH_PKCS_PARAMETER_GEN,
					     &mechInfo);
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_GENERATE) == 0))
			goto try_digest;
#endif
		rv = pkcs_C_GetMechanismInfo(slot, CKM_DH_PKCS_KEY_PAIR_GEN,
					     &mechInfo);
		if ((rv != CKR_OK) ||
		    ((mechInfo.flags & CKF_GENERATE_KEY_PAIR) == 0))
			goto try_digest;
		rv = pkcs_C_GetMechanismInfo(slot, CKM_DH_PKCS_DERIVE,
					     &mechInfo);
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_DERIVE) == 0))
			goto try_digest;
		token->operations |= 1 << OP_DH;
		if (best_dh_token == NULL)
			best_dh_token = token;

	try_digest:
		rv = pkcs_C_GetMechanismInfo(slot, CKM_MD5, &mechInfo);
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_DIGEST) == 0))
			continue;
		rv = pkcs_C_GetMechanismInfo(slot, CKM_SHA_1, &mechInfo);
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_DIGEST) == 0))
			continue;
		rv = pkcs_C_GetMechanismInfo(slot, CKM_SHA224, &mechInfo);
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_DIGEST) == 0))
			continue;
		rv = pkcs_C_GetMechanismInfo(slot, CKM_SHA256, &mechInfo);
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_DIGEST) == 0))
			continue;
		rv = pkcs_C_GetMechanismInfo(slot, CKM_SHA384, &mechInfo);
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_DIGEST) == 0))
			continue;
		rv = pkcs_C_GetMechanismInfo(slot, CKM_SHA512, &mechInfo);
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_DIGEST) == 0))
			continue;
#ifdef PKCS11CRYPTOWITHHMAC
		rv = pkcs_C_GetMechanismInfo(slot, CKM_MD5_HMAC, &mechInfo);
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_SIGN) == 0))
			continue;
#endif
		rv = pkcs_C_GetMechanismInfo(slot, CKM_SHA_1_HMAC, &mechInfo);
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_SIGN) == 0))
			continue;
		rv = pkcs_C_GetMechanismInfo(slot, CKM_SHA224_HMAC, &mechInfo);
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_SIGN) == 0))
			continue;
		rv = pkcs_C_GetMechanismInfo(slot, CKM_SHA256_HMAC, &mechInfo);
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_SIGN) == 0))
			continue;
		rv = pkcs_C_GetMechanismInfo(slot, CKM_SHA384_HMAC, &mechInfo);
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_SIGN) == 0))
			continue;
		rv = pkcs_C_GetMechanismInfo(slot, CKM_SHA512_HMAC, &mechInfo);
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_SIGN) == 0))
			continue;
		token->operations |= 1 << OP_DIGEST;
		if (digest_token == NULL)
			digest_token = token;

		/* ECDSA requires digest */
		rv = pkcs_C_GetMechanismInfo(slot, CKM_EC_KEY_PAIR_GEN,
					     &mechInfo);
		if ((rv != CKR_OK) ||
		    ((mechInfo.flags & CKF_GENERATE_KEY_PAIR) == 0))
			goto try_gost;
		rv = pkcs_C_GetMechanismInfo(slot, CKM_ECDSA, &mechInfo);
		if ((rv != CKR_OK) ||
		    ((mechInfo.flags & CKF_SIGN) == 0) ||
		    ((mechInfo.flags & CKF_VERIFY) == 0))
			goto try_gost;
		token->operations |= 1 << OP_EC;
		if (best_ec_token == NULL)
			best_ec_token = token;

	try_gost:
		/* does GOST require digest too? */
		rv = pkcs_C_GetMechanismInfo(slot, CKM_GOSTR3411, &mechInfo);
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_DIGEST) == 0))
831
			goto try_aes;
Evan Hunt's avatar
Evan Hunt committed
832 833 834 835
		rv = pkcs_C_GetMechanismInfo(slot, CKM_GOSTR3410_KEY_PAIR_GEN,
					     &mechInfo);
		if ((rv != CKR_OK) ||
		    ((mechInfo.flags & CKF_GENERATE_KEY_PAIR) == 0))
836
			goto try_aes;
Evan Hunt's avatar
Evan Hunt committed
837 838 839 840 841 842
		rv = pkcs_C_GetMechanismInfo(slot,
					     CKM_GOSTR3410_WITH_GOSTR3411,
					     &mechInfo);
		if ((rv != CKR_OK) ||
		    ((mechInfo.flags & CKF_SIGN) == 0) ||
		    ((mechInfo.flags & CKF_VERIFY) == 0))
843
			goto try_aes;
Evan Hunt's avatar
Evan Hunt committed
844 845 846
		token->operations |= 1 << OP_GOST;
		if (best_gost_token == NULL)
			best_gost_token = token;
847 848 849 850 851 852 853 854

	try_aes:
		rv = pkcs_C_GetMechanismInfo(slot, CKM_AES_ECB, &mechInfo);
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_ENCRYPT) == 0))
			continue;
		token->operations |= 1 << OP_AES;
		if (aes_token == NULL)
			aes_token = token;
Evan Hunt's avatar
Evan Hunt committed
855 856 857 858 859 860 861
	}

	if (slotList != NULL)
		pk11_mem_put(slotList, sizeof(CK_SLOT_ID_PTR) * slotCount);
}

CK_SLOT_ID
862 863
pk11_get_best_token(pk11_optype_t optype) {
	pk11_token_t *token = NULL;
Evan Hunt's avatar
Evan Hunt committed
864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886

	switch (optype) {
	case OP_RAND:
		token = rand_token;
		break;
	case OP_RSA:
		token = best_rsa_token;
		break;
	case OP_DSA:
		token = best_dsa_token;
		break;
	case OP_DH:
		token = best_dh_token;
		break;
	case OP_DIGEST:
		token = digest_token;
		break;
	case OP_EC:
		token = best_ec_token;
		break;
	case OP_GOST:
		token = best_gost_token;
		break;
887 888 889
	case OP_AES:
		token = aes_token;
		break;
Evan Hunt's avatar
Evan Hunt committed
890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
	default:
		break;
	}
	if (token == NULL)
		return (0);
	return (token->slotid);
}

unsigned int
pk11_numbits(CK_BYTE_PTR data, unsigned int bytecnt) {
	unsigned int bitcnt, i;
	CK_BYTE top;

	if (bytecnt == 0)
		return (0);
	bitcnt = bytecnt * 8;
	for (i = 0; i < bytecnt; i++) {
		top = data[i];
		if (top == 0) {
			bitcnt -= 8;
			continue;
		}
		if (top & 0x80)
			return (bitcnt);
		if (top & 0x40)
			return (bitcnt - 1);
		if (top & 0x20)
			return (bitcnt - 2);
		if (top & 0x10)
			return (bitcnt - 3);
		if (top & 0x08)
			return (bitcnt - 4);
		if (top & 0x04)
			return (bitcnt - 5);
		if (top & 0x02)
			return (bitcnt - 6);
		if (top & 0x01)
			return (bitcnt - 7);
		break;
	}
	INSIST(0);
}

CK_ATTRIBUTE *
934
pk11_attribute_first(const pk11_object_t *obj) {
Evan Hunt's avatar
Evan Hunt committed
935 936 937 938
	return (obj->repr);
}

CK_ATTRIBUTE *
939
pk11_attribute_next(const pk11_object_t *obj, CK_ATTRIBUTE *attr) {
Evan Hunt's avatar
Evan Hunt committed
940 941 942 943 944 945 946 947 948
	CK_ATTRIBUTE *next;

	next = attr + 1;
	if ((next - obj->repr) >= obj->attrcnt)
		return (NULL);
	return (next);
}

CK_ATTRIBUTE *
949
pk11_attribute_bytype(const pk11_object_t *obj, CK_ATTRIBUTE_TYPE type) {
Evan Hunt's avatar
Evan Hunt committed
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
	CK_ATTRIBUTE *attr;

	for(attr = pk11_attribute_first(obj);
	    attr != NULL;
	    attr = pk11_attribute_next(obj, attr))
		if (attr->type == type)
			return (attr);
	return (NULL);
}

static char *
percent_decode(char *x, size_t *len) {
	char *p, *c;
	unsigned char v;

	INSIST(len != NULL);

	for (p = c = x; p[0] != '\0'; p++, c++) {
		switch (p[0]) {
		case '%':
			v = 0;
			switch (p[1]) {
			case '0':
			case '1':
			case '2':
			case '3':
			case '4':
			case '5':
			case '6':
			case '7':
			case '8':
			case '9':
				v = (p[1] - '0') << 4;
				break;
			case 'A':
			case 'B':
			case 'C':
			case 'D':
			case 'E':
			case 'F':
				v = (p[1] - 'A' + 10) << 4;
				break;
			case 'a':
			case 'b':
			case 'c':
			case 'd':
			case 'e':
			case 'f':
				v = (p[1] - 'a' + 10) << 4;
				break;
			default:
				return (NULL);
			}
			switch (p[2]) {
			case '0':
			case '1':
			case '2':
			case '3':
			case '4':
			case '5':
			case '6':
			case '7':
			case '8':
			case '9':
				v |= (p[2] - '0') & 0x0f;
				break;
			case 'A':
			case 'B':
			case 'C':
			case 'D':
			case 'E':
			case 'F':
				v = (p[2] - 'A' + 10) & 0x0f;
				break;
			case 'a':
			case 'b':
			case 'c':
			case 'd':
			case 'e':
			case 'f':
				v = (p[2] - 'a' + 10) & 0x0f;
				break;
			default:
				return (NULL);
			}
			p += 2;
			*c = (char) v;
			(*len)++;
			break;
		default:
			*c = *p;
			(*len)++;
		}
	}
	return (x);
}

static isc_boolean_t
pk11strcmp(const char *x, size_t lenx, const char *y, size_t leny) {
	char buf[32];

	INSIST((leny == 32) || (leny == 16));

	memset(buf, ' ', 32);
	if (lenx > leny)
		lenx = leny;
1056
	memmove(buf, x, lenx);
Evan Hunt's avatar
Evan Hunt committed
1057 1058 1059 1060
	return (ISC_TF(memcmp(buf, y, leny) == 0));
}

static CK_ATTRIBUTE *
1061
push_attribute(pk11_object_t *obj, isc_mem_t *mctx, size_t len) {
Evan Hunt's avatar
Evan Hunt committed
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
	CK_ATTRIBUTE *old = obj->repr;
	CK_ATTRIBUTE *attr;
	CK_BYTE cnt = obj->attrcnt;

	obj->repr = isc_mem_get(mctx, (cnt + 1) * sizeof(*attr));
	if (obj->repr == NULL) {
		obj->repr = old;
		return (NULL);
	}
	memset(obj->repr, 0, (cnt + 1) * sizeof(*attr));
1072
	memmove(obj->repr, old, cnt * sizeof(*attr));
Evan Hunt's avatar
Evan Hunt committed
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
	attr = obj->repr + cnt;
	attr->ulValueLen = (CK_ULONG) len;
	attr->pValue = isc_mem_get(mctx, len);
	if (attr->pValue == NULL) {
		memset(obj->repr, 0, (cnt + 1) * sizeof(*attr));
		isc_mem_put(mctx, obj->repr, (cnt + 1) * sizeof(*attr));
		obj->repr = old;
		return (NULL);
	}
	memset(attr->pValue, 0, len);
	if (old != NULL) {
		memset(old, 0, cnt * sizeof(*attr));
		isc_mem_put(mctx, old, cnt * sizeof(*attr));
	}
	obj->attrcnt++;
	return (attr);
}

#define DST_RET(a)	{ ret = a; goto err; }

isc_result_t
1094 1095
pk11_parse_uri(pk11_object_t *obj, const char *label,
	       isc_mem_t *mctx, pk11_optype_t optype)
Evan Hunt's avatar
Evan Hunt committed
1096 1097
{
	CK_ATTRIBUTE *attr;
1098
	pk11_token_t *token = NULL;
Evan Hunt's avatar
Evan Hunt committed
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
	char *uri, *p, *a, *na, *v;
	size_t len, l;
	FILE *stream = NULL;
	char pin[PINLEN];
	isc_boolean_t gotpin = ISC_FALSE;
	isc_result_t ret;

	/* get values to work on */
	len = strlen(label) + 1;
	uri = isc_mem_get(mctx, len);
	if (uri == NULL)
		return (ISC_R_NOMEMORY);
1111
	memmove(uri, label, len);
Evan Hunt's avatar
Evan Hunt committed
1112 1113 1114 1115

	/* get the URI scheme */
	p = strchr(uri, ':');
	if (p == NULL)
1116
		DST_RET(PK11_R_NOPROVIDER);
Evan Hunt's avatar
Evan Hunt committed
1117 1118
	*p++ = '\0';
	if (strcmp(uri, "pkcs11") != 0)
1119
		DST_RET(PK11_R_NOPROVIDER);
Evan Hunt's avatar
Evan Hunt committed
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140

	/* get attributes */
	for (na = p; na != NULL;) {
		a = na;
		p = strchr(a, ';');
		if (p == NULL) {
			/* last attribute */
			na = NULL;
		} else {
			*p++ = '\0';
			na = p;
		}
		p = strchr(a, '=');
		if (p != NULL) {
			*p++ = '\0';
			v = p;
		} else
			v = a;
		l = 0;
		v = percent_decode(v, &l);
		if (v == NULL)
1141
			DST_RET(PK11_R_NOPROVIDER);
Evan Hunt's avatar
Evan Hunt committed
1142 1143 1144 1145
		if ((a == v) || (strcmp(a, "object") == 0)) {
			/* object: CKA_LABEL */
			attr = pk11_attribute_bytype(obj, CKA_LABEL);
			if (attr != NULL)
1146
				DST_RET(PK11_R_NOPROVIDER);
Evan Hunt's avatar
Evan Hunt committed
1147 1148 1149 1150
			attr = push_attribute(obj, mctx, l);
			if (attr == NULL)
				DST_RET(ISC_R_NOMEMORY);
			attr->type = CKA_LABEL;
1151
			memmove(attr->pValue, v, l);
Evan Hunt's avatar
Evan Hunt committed
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
		} else if (strcmp(a, "token") == 0) {
			/* token: CK_TOKEN_INFO label */
			if (token == NULL)
				for (token = ISC_LIST_HEAD(tokens);
				     token != NULL;
				     token = ISC_LIST_NEXT(token, link))
					if (pk11strcmp(v, l, token->name, 32))
						break;
		} else if (strcmp(a, "manufacturer") == 0) {
			/* manufacturer: CK_TOKEN_INFO manufacturerID */
			if (token == NULL)
				for (token = ISC_LIST_HEAD(tokens);
				     token != NULL;
				     token = ISC_LIST_NEXT(token, link))
					if (pk11strcmp(v, l, token->manuf, 32))
						break;
		} else if (strcmp(a, "serial") == 0) {
			/* serial: CK_TOKEN_INFO serialNumber */
			if (token == NULL)
				for (token = ISC_LIST_HEAD(tokens);
				     token != NULL;
				     token = ISC_LIST_NEXT(token, link))
					if (pk11strcmp(v, l, token->serial, 16))
						break;
		} else if (strcmp(a, "model") == 0) {
			/* model: CK_TOKEN_INFO model */
			if (token == NULL)
				for (token = ISC_LIST_HEAD(tokens);
				     token != NULL;
				     token = ISC_LIST_NEXT(token, link))
					if (pk11strcmp(v, l, token->model, 16))
						break;
		} else if (strcmp(a, "library-manufacturer") == 0) {
			/* ignored */
		} else if (strcmp(a, "library-description") == 0) {
			/* ignored */
		} else if (strcmp(a, "library-version") == 0) {
			/* ignored */
		} else if (strcmp(a, "object-type") == 0) {
			/* object-type: CKA_CLASS */
			/* only private makes sense */
			if (strcmp(v, "private") != 0)
1194
				DST_RET(PK11_R_NOPROVIDER);
Evan Hunt's avatar
Evan Hunt committed
1195 1196 1197 1198
		} else if (strcmp(a, "id") == 0) {
			/* id: CKA_ID */
			attr = pk11_attribute_bytype(obj, CKA_ID);
			if (attr != NULL)
1199
				DST_RET(PK11_R_NOPROVIDER);
Evan Hunt's avatar
Evan Hunt committed
1200 1201 1202 1203
			attr = push_attribute(obj, mctx, l);
			if (attr == NULL)
				DST_RET(ISC_R_NOMEMORY);
			attr->type = CKA_ID;
1204
			memmove(attr->pValue, v, l);
Evan Hunt's avatar
Evan Hunt committed
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
		} else if (strcmp(a, "pin-source") == 0) {
			/* pin-source: PIN */
			ret = isc_stdio_open(v, "r", &stream);
			if (ret != ISC_R_SUCCESS)
				goto err;
			memset(pin, 0, PINLEN);
			ret = isc_stdio_read(pin, 1, PINLEN - 1, stream, NULL);
			if ((ret != ISC_R_SUCCESS) && (ret != ISC_R_EOF))
				goto err;
			ret = isc_stdio_close(stream);
			stream = NULL;
			if (ret != ISC_R_SUCCESS)
				goto err;
			gotpin = ISC_TRUE;
		} else
1220
			DST_RET(PK11_R_NOPROVIDER);
Evan Hunt's avatar
Evan Hunt committed
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
	}

	if ((pk11_attribute_bytype(obj, CKA_LABEL) == NULL) &&
	    (pk11_attribute_bytype(obj, CKA_ID) == NULL))
		DST_RET(ISC_R_NOTFOUND);

	if (token == NULL) {
		if (optype == OP_RSA)
			token = best_rsa_token;
		else if (optype == OP_DSA)
			token = best_dsa_token;
		else if (optype == OP_DH)
			token = best_dh_token;
		else if (optype == OP_EC)
			token = best_ec_token;
	}
	if (token == NULL)
		DST_RET(ISC_R_NOTFOUND);
	obj->slot = token->slotid;
	if (gotpin) {
1241
		memmove(token->pin, pin, PINLEN);
Evan Hunt's avatar
Evan Hunt committed
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
		obj->reqlogon = ISC_TRUE;
	}

	ret = ISC_R_SUCCESS;

  err:
	if (stream != NULL)
		(void) isc_stdio_close(stream);
	isc_mem_put(mctx, uri, len);
	return (ret);
}

void
pk11_error_fatalcheck(const char *file, int line,
		      const char *funcname, CK_RV rv)
{
	isc_error_fatal(file, line, "%s: Error = 0x%.8lX\n", funcname, rv);
}

void
pk11_dump_tokens(void)
{
1264
	pk11_token_t *token;
Evan Hunt's avatar
Evan Hunt committed
1265 1266 1267 1268 1269 1270 1271 1272 1273
	isc_boolean_t first;

	printf("DEFAULTS\n");
	printf("\trand_token=%p\n", rand_token);
	printf("\tbest_rsa_token=%p\n", best_rsa_token);
	printf("\tbest_dsa_token=%p\n", best_dsa_token);
	printf("\tbest_dh_token=%p\n", best_dh_token);
	printf("\tdigest_token=%p\n", digest_token);
	printf("\tbest_ec_token=%p\n", best_ec_token);
1274 1275
	printf("\tbest_gost_token=%p\n", best_gost_token);
	printf("\taes_token=%p\n", aes_token);
Evan Hunt's avatar
Evan Hunt committed
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327

	for (token = ISC_LIST_HEAD(tokens);
	     token != NULL;
	     token = ISC_LIST_NEXT(token, link)) {
		printf("\nTOKEN\n");
		printf("\taddress=%p\n", token);
		printf("\tslotID=%lu\n", token->slotid);
		printf("\tlabel=%.32s\n", token->name);
		printf("\tmanufacturerID=%.32s\n", token->manuf);
		printf("\tmodel=%.16s\n", token->model);
		printf("\tserialNumber=%.16s\n", token->serial);
		printf("\tsupported operations=0x%x (", token->operations);
		first = ISC_TRUE;
		if (token->operations & (1 << OP_RAND)) {
			if (!first)
				printf(",");
			first = ISC_FALSE;
			printf("RAND");
		}
		if (token->operations & (1 << OP_RSA)) {
			if (!first)
				printf(",");
			first = ISC_FALSE;
			printf("RSA");
		}
		if (token->operations & (1 << OP_DSA)) {
			if (!first)
				printf(",");
			first = ISC_FALSE;
			printf("DSA");
		}
		if (token->operations & (1 << OP_DH)) {
			if (!first)
				printf(",");
			first = ISC_FALSE;
			printf("DH");
		}
		if (token->operations & (1 << OP_DIGEST)) {
			if (!first)
				printf(",");
			first = ISC_FALSE;
			printf("DIGEST");
		}
		if (token->operations & (1 << OP_EC)) {
			if (!first)
				printf(",");
			first = ISC_FALSE;
			printf("EC");
		}
		printf(")\n");
	}
}