pk11.c 32.6 KB
Newer Older
Evan Hunt's avatar
Evan Hunt committed
1
/*
2
 * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
Evan Hunt's avatar
Evan Hunt committed
3
 *
4 5 6
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
7 8 9
 *
 * See the COPYRIGHT file distributed with this work for additional
 * information regarding copyright ownership.
Evan Hunt's avatar
Evan Hunt committed
10 11 12 13 14
 */

#include <config.h>

#include <stdio.h>
15
#include <inttypes.h>
16
#include <stdbool.h>
Evan Hunt's avatar
Evan Hunt committed
17 18 19 20 21 22
#include <stdlib.h>
#include <string.h>

#include <isc/log.h>
#include <isc/mem.h>
#include <isc/once.h>
23
#include <isc/platform.h>
24
#include <isc/print.h>
Evan Hunt's avatar
Evan Hunt committed
25
#include <isc/stdio.h>
Mark Andrews's avatar
Mark Andrews committed
26
#include <isc/string.h>
Evan Hunt's avatar
Evan Hunt committed
27 28 29 30 31
#include <isc/thread.h>
#include <isc/util.h>

#include <dst/result.h>

32 33
#include <pk11/pk11.h>
#include <pk11/internal.h>
34
#include <pk11/result.h>
35
#include <pk11/site.h>
Evan Hunt's avatar
Evan Hunt committed
36 37 38

#include <pkcs11/cryptoki.h>
#include <pkcs11/pkcs11.h>
39
#include <pkcs11/eddsa.h>
Evan Hunt's avatar
Evan Hunt committed
40

41 42 43 44
/* was 32 octets, Petr Spacek suggested 1024, SoftHSMv2 uses 256... */
#ifndef PINLEN
#define PINLEN	256
#endif
Evan Hunt's avatar
Evan Hunt committed
45 46 47 48 49

#ifndef PK11_NO_LOGERR
#define PK11_NO_LOGERR 1
#endif

50
LIBISC_EXTERNAL_DATA bool pk11_verbose_init = false;
51

Evan Hunt's avatar
Evan Hunt committed
52 53
static isc_once_t once = ISC_ONCE_INIT;
static isc_mem_t *pk11_mctx = NULL;
54
static int32_t allocsize = 0;
55
static bool initialized = false;
Evan Hunt's avatar
Evan Hunt committed
56

57 58 59
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
60

61
struct pk11_session {
Evan Hunt's avatar
Evan Hunt committed
62 63
	unsigned int		magic;
	CK_SESSION_HANDLE	session;
64 65
	ISC_LINK(pk11_session_t) link;
	pk11_token_t		*token;
Evan Hunt's avatar
Evan Hunt committed
66 67
};

68
struct pk11_token {
Evan Hunt's avatar
Evan Hunt committed
69 70
	unsigned int		magic;
	unsigned int		operations;
71
	ISC_LINK(pk11_token_t)	link;
Evan Hunt's avatar
Evan Hunt committed
72
	CK_SLOT_ID		slotid;
73
	pk11_sessionlist_t	sessions;
74
	bool		logged;
Evan Hunt's avatar
Evan Hunt committed
75 76 77 78
	char			name[32];
	char			manuf[32];
	char			model[16];
	char			serial[16];
79
	char			pin[PINLEN + 1];
Evan Hunt's avatar
Evan Hunt committed
80
};
81
static ISC_LIST(pk11_token_t) tokens;
Evan Hunt's avatar
Evan Hunt committed
82

83 84 85 86 87 88 89
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;
90
static pk11_token_t *aes_token;
Evan Hunt's avatar
Evan Hunt committed
91 92

static isc_result_t free_all_sessions(void);
93 94 95
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,
96
				  bool rw);
97
static void scan_slots(void);
98
static isc_result_t token_login(pk11_session_t *sp);
Evan Hunt's avatar
Evan Hunt committed
99
static char *percent_decode(char *x, size_t *len);
100
static bool pk11strcmp(const char *x, size_t lenx,
Evan Hunt's avatar
Evan Hunt committed
101
				const char *y, size_t leny);
102
static CK_ATTRIBUTE *push_attribute(pk11_object_t *obj,
Evan Hunt's avatar
Evan Hunt committed
103 104 105 106 107 108
				    isc_mem_t *mctx,
				    size_t len);

static isc_mutex_t alloclock;
static isc_mutex_t sessionlock;

109
static pk11_sessionlist_t actives;
Evan Hunt's avatar
Evan Hunt committed
110 111

static CK_C_INITIALIZE_ARGS pk11_init_args = {
Mark Andrews's avatar
Mark Andrews committed
112 113 114 115 116 117
	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
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
};

#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)
162
			allocsize += (int)size;
Evan Hunt's avatar
Evan Hunt committed
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
	}
	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)
180
			allocsize -= (int)size;
Evan Hunt's avatar
Evan Hunt committed
181 182 183 184 185
		free(ptr);
	}
	UNLOCK(&alloclock);
}

186 187 188
isc_result_t
pk11_initialize(isc_mem_t *mctx, const char *engine) {
	isc_result_t result;
Evan Hunt's avatar
Evan Hunt committed
189 190 191 192 193 194 195 196 197
	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);
198
		return (ISC_R_SUCCESS);
Evan Hunt's avatar
Evan Hunt committed
199 200
	} else {
		LOCK(&sessionlock);
201
		initialized = true;
Evan Hunt's avatar
Evan Hunt committed
202 203 204
		UNLOCK(&alloclock);
	}

205 206 207
	ISC_LIST_INIT(tokens);
	ISC_LIST_INIT(actives);

Mark Andrews's avatar
Mark Andrews committed
208 209
	if (engine != NULL)
		lib_name = engine;
Evan Hunt's avatar
Evan Hunt committed
210 211 212 213

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

214 215
	if (rv == 0xfe) {
		result = PK11_R_NOPROVIDER;
216 217
		fprintf(stderr, "Can't load PKCS#11 provider: %s\n",
			pk11_get_load_error_message());
218 219
		goto unlock;
	}
Evan Hunt's avatar
Evan Hunt committed
220
	if (rv != CKR_OK) {
221 222
		result = PK11_R_INITFAILED;
		goto unlock;
Evan Hunt's avatar
Evan Hunt committed
223 224
	}

225
	scan_slots();
Evan Hunt's avatar
Evan Hunt committed
226
#ifdef PKCS11CRYPTO
227 228 229 230 231 232 233 234
	if (rand_token == NULL) {
		result = PK11_R_NORANDOMSERVICE;
		goto unlock;
	}
	if (digest_token == NULL) {
		result = PK11_R_NODIGESTSERVICE;
		goto unlock;
	}
235
#if defined(AES_CC)
236 237 238 239
	if (aes_token == NULL) {
		result = PK11_R_NOAESSERVICE;
		goto unlock;
	}
240
#endif
Evan Hunt's avatar
Evan Hunt committed
241
#endif /* PKCS11CRYPTO */
242 243
	result = ISC_R_SUCCESS;
 unlock:
Evan Hunt's avatar
Evan Hunt committed
244
	UNLOCK(&sessionlock);
245
	return (result);
Evan Hunt's avatar
Evan Hunt committed
246 247 248
}

isc_result_t
249
pk11_finalize(void) {
250
	pk11_token_t *token, *next;
Evan Hunt's avatar
Evan Hunt committed
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
	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;
273 274
		if (token == aes_token)
			aes_token = NULL;
Evan Hunt's avatar
Evan Hunt committed
275 276 277 278 279
		pk11_mem_put(token, sizeof(*token));
		token = next;
	}
	if (pk11_mctx != NULL)
		isc_mem_detach(&pk11_mctx);
280
	initialized = false;
Evan Hunt's avatar
Evan Hunt committed
281 282 283 284 285 286 287
	return (ret);
}

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

290 291
	ret = pk11_get_session(&ctx, OP_RAND, false, false,
			       false, NULL, 0);
292 293 294
	if ((ret != ISC_R_SUCCESS) &&
	    (ret != PK11_R_NODIGESTSERVICE) &&
	    (ret != PK11_R_NOAESSERVICE))
Evan Hunt's avatar
Evan Hunt committed
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
		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) {
312
	pk11_context_t ctx;
Evan Hunt's avatar
Evan Hunt committed
313 314 315 316
	FILE *stream = NULL;
	size_t cc = 0;
	isc_result_t ret;

317 318
	ret = pk11_get_session(&ctx, OP_RAND, false, false,
			       false, NULL, 0);
319 320 321
	if ((ret != ISC_R_SUCCESS) &&
	    (ret != PK11_R_NODIGESTSERVICE) &&
	    (ret != PK11_R_NOAESSERVICE))
Evan Hunt's avatar
Evan Hunt committed
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
		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
340
}
Evan Hunt's avatar
Evan Hunt committed
341 342

isc_result_t
343
pk11_get_session(pk11_context_t *ctx, pk11_optype_t optype,
344 345
		 bool need_services, bool rw,
		 bool logon, const char *pin, CK_SLOT_ID slot)
Evan Hunt's avatar
Evan Hunt committed
346
{
347 348 349
	pk11_token_t *token = NULL;
	pk11_sessionlist_t *freelist;
	pk11_session_t *sp;
350 351 352 353 354
	isc_result_t ret;
#ifdef PKCS11CRYPTO
	isc_result_t service_ret = ISC_R_SUCCESS;
#else
	UNUSED(need_services);
Tinderbox User's avatar
Tinderbox User committed
355
#endif
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373

	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
374 375 376 377 378 379 380 381 382 383 384 385 386

	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;
387 388 389
	case OP_AES:
		token = aes_token;
		break;
Evan Hunt's avatar
Evan Hunt committed
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
	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') {
416
		if (strlen(pin) > PINLEN)
417 418 419 420 421 422 423
			return (ISC_R_RANGE);
		/*
		 * We want to zero out the old pin before
		 * overwriting with a new one.
		 */
		memset(token->pin, 0, sizeof(token->pin));
		strlcpy(token->pin, pin, sizeof(token->pin));
Evan Hunt's avatar
Evan Hunt committed
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
	}

	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;
457 458 459 460
#ifdef PKCS11CRYPTO
	if (ret == ISC_R_SUCCESS)
		ret = service_ret;
#endif
Evan Hunt's avatar
Evan Hunt committed
461 462 463 464
	return (ret);
}

void
465 466
pk11_return_session(pk11_context_t *ctx) {
	pk11_session_t *sp = (pk11_session_t *) ctx->handle;
Evan Hunt's avatar
Evan Hunt committed
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487

	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) {
488
	pk11_token_t *token;
Evan Hunt's avatar
Evan Hunt committed
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
	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
509 510
free_session_list(pk11_sessionlist_t *slist) {
	pk11_session_t *sp;
Evan Hunt's avatar
Evan Hunt committed
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
	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
534
setup_session(pk11_session_t *sp, pk11_token_t *token,
535
	      bool rw)
Evan Hunt's avatar
Evan Hunt committed
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
{
	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
551
token_login(pk11_session_t *sp) {
Evan Hunt's avatar
Evan Hunt committed
552
	CK_RV rv;
553
	pk11_token_t *token = sp->token;
Evan Hunt's avatar
Evan Hunt committed
554 555 556 557 558 559 560 561 562 563 564 565 566 567
	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
568
			token->logged = true;
Evan Hunt's avatar
Evan Hunt committed
569 570 571 572 573
	}
	UNLOCK(&sessionlock);
	return (ret);
}

574 575 576 577 578 579 580 581 582
#define PK11_TRACE(fmt) \
	if (pk11_verbose_init) fprintf(stderr, fmt)
#define PK11_TRACE1(fmt, arg) \
	if (pk11_verbose_init) fprintf(stderr, fmt, arg)
#define PK11_TRACE2(fmt, arg1, arg2) \
	if (pk11_verbose_init) fprintf(stderr, fmt, arg1, arg2)
#define PK11_TRACEM(mech) \
	if (pk11_verbose_init) fprintf(stderr, #mech ": 0x%lx\n", rv)

Evan Hunt's avatar
Evan Hunt committed
583
static void
584
scan_slots(void) {
Evan Hunt's avatar
Evan Hunt committed
585 586 587 588 589 590
	CK_MECHANISM_INFO mechInfo;
	CK_TOKEN_INFO tokenInfo;
	CK_RV rv;
	CK_SLOT_ID slot;
	CK_SLOT_ID_PTR slotList;
	CK_ULONG slotCount;
591
	pk11_token_t *token;
Evan Hunt's avatar
Evan Hunt committed
592
	unsigned int i;
593
	bool bad;
Evan Hunt's avatar
Evan Hunt committed
594 595 596

	slotCount = 0;
	PK11_FATALCHECK(pkcs_C_GetSlotList, (CK_FALSE, NULL_PTR, &slotCount));
597
	PK11_TRACE1("slotCount=%lu\n", slotCount);
Evan Hunt's avatar
Evan Hunt committed
598 599 600 601 602 603 604 605 606
	/* 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];
607
		PK11_TRACE2("slot#%u=0x%lx\n", i, slot);
Evan Hunt's avatar
Evan Hunt committed
608 609 610 611 612 613 614 615 616 617

		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);
618 619 620 621
		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
622
		ISC_LIST_APPEND(tokens, token, link);
623 624
		if ((tokenInfo.flags & CKF_RNG) == 0) {
			PK11_TRACE("no CKF_RNG\n");
Evan Hunt's avatar
Evan Hunt committed
625
			goto try_rsa;
626
		}
Evan Hunt's avatar
Evan Hunt committed
627 628 629 630 631
		token->operations |= 1 << OP_RAND;
		if (rand_token == NULL)
			rand_token = token;

	try_rsa:
632
		bad = false;
Evan Hunt's avatar
Evan Hunt committed
633 634 635
		rv = pkcs_C_GetMechanismInfo(slot, CKM_RSA_PKCS_KEY_PAIR_GEN,
					     &mechInfo);
		if ((rv != CKR_OK) ||
636
		    ((mechInfo.flags & CKF_GENERATE_KEY_PAIR) == 0)) {
637
			bad = true;
638 639
			PK11_TRACEM(CKM_RSA_PKCS_KEY_PAIR_GEN);
		}
Evan Hunt's avatar
Evan Hunt committed
640 641 642 643
		rv = pkcs_C_GetMechanismInfo(slot, CKM_MD5_RSA_PKCS,
					     &mechInfo);
		if ((rv != CKR_OK) ||
		    ((mechInfo.flags & CKF_SIGN) == 0) ||
644
		    ((mechInfo.flags & CKF_VERIFY) == 0)) {
645
#if !defined(PK11_MD5_DISABLE) && !defined(PK11_RSA_PKCS_REPLACE)
646
			bad = true;
647 648 649
#endif
			PK11_TRACEM(CKM_MD5_RSA_PKCS);
		}
Evan Hunt's avatar
Evan Hunt committed
650 651 652 653
		rv = pkcs_C_GetMechanismInfo(slot, CKM_SHA1_RSA_PKCS,
					     &mechInfo);
		if ((rv != CKR_OK) ||
		    ((mechInfo.flags & CKF_SIGN) == 0) ||
654
		    ((mechInfo.flags & CKF_VERIFY) == 0)) {
655
#ifndef PK11_RSA_PKCS_REPLACE
656
			bad = true;
657
#endif
658 659
			PK11_TRACEM(CKM_SHA1_RSA_PKCS);
		}
Evan Hunt's avatar
Evan Hunt committed
660 661 662 663
		rv = pkcs_C_GetMechanismInfo(slot, CKM_SHA256_RSA_PKCS,
					     &mechInfo);
		if ((rv != CKR_OK) ||
		    ((mechInfo.flags & CKF_SIGN) == 0) ||
664
		    ((mechInfo.flags & CKF_VERIFY) == 0)) {
665
#ifndef PK11_RSA_PKCS_REPLACE
666
			bad = true;
667
#endif
668 669
			PK11_TRACEM(CKM_SHA256_RSA_PKCS);
		}
Evan Hunt's avatar
Evan Hunt committed
670 671 672 673
		rv = pkcs_C_GetMechanismInfo(slot, CKM_SHA512_RSA_PKCS,
					     &mechInfo);
		if ((rv != CKR_OK) ||
		    ((mechInfo.flags & CKF_SIGN) == 0) ||
674
		    ((mechInfo.flags & CKF_VERIFY) == 0)) {
675
#ifndef PK11_RSA_PKCS_REPLACE
676
			bad = true;
677
#endif
678 679
			PK11_TRACEM(CKM_SHA512_RSA_PKCS);
		}
680 681 682 683 684
		rv = pkcs_C_GetMechanismInfo(slot, CKM_RSA_PKCS, &mechInfo);
		if ((rv != CKR_OK) ||
		    ((mechInfo.flags & CKF_SIGN) == 0) ||
		    ((mechInfo.flags & CKF_VERIFY) == 0)) {
#ifdef PK11_RSA_PKCS_REPLACE
685
			bad = true;
686 687 688
#endif
			PK11_TRACEM(CKM_RSA_PKCS);
		}
689
		if (bad)
Evan Hunt's avatar
Evan Hunt committed
690 691 692 693 694 695
			goto try_dsa;
		token->operations |= 1 << OP_RSA;
		if (best_rsa_token == NULL)
			best_rsa_token = token;

	try_dsa:
696
		bad = false;
Evan Hunt's avatar
Evan Hunt committed
697 698
		rv = pkcs_C_GetMechanismInfo(slot, CKM_DSA_PARAMETER_GEN,
					     &mechInfo);
699 700
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_GENERATE) == 0)) {
#ifndef PK11_DSA_PARAMETER_GEN_SKIP
701
			bad = true;
702 703 704
#endif
			PK11_TRACEM(CKM_DSA_PARAMETER_GEN);
		}
Evan Hunt's avatar
Evan Hunt committed
705 706 707
		rv = pkcs_C_GetMechanismInfo(slot, CKM_DSA_KEY_PAIR_GEN,
					     &mechInfo);
		if ((rv != CKR_OK) ||
708
		    ((mechInfo.flags & CKF_GENERATE_KEY_PAIR) == 0)) {
709
			bad = true;
710 711
			PK11_TRACEM(CKM_DSA_PARAMETER_GEN);
		}
Evan Hunt's avatar
Evan Hunt committed
712 713 714
		rv = pkcs_C_GetMechanismInfo(slot, CKM_DSA_SHA1, &mechInfo);
		if ((rv != CKR_OK) ||
		    ((mechInfo.flags & CKF_SIGN) == 0) ||
715
		    ((mechInfo.flags & CKF_VERIFY) == 0)) {
716
			bad = true;
717 718 719
			PK11_TRACEM(CKM_DSA_SHA1);
		}
		if (bad)
Evan Hunt's avatar
Evan Hunt committed
720
			goto try_dh;
721
#ifndef PK11_DSA_DISABLE
Evan Hunt's avatar
Evan Hunt committed
722 723 724
		token->operations |= 1 << OP_DSA;
		if (best_dsa_token == NULL)
			best_dsa_token = token;
725
#endif
Evan Hunt's avatar
Evan Hunt committed
726 727

	try_dh:
728
		bad = false;
Evan Hunt's avatar
Evan Hunt committed
729 730
		rv = pkcs_C_GetMechanismInfo(slot, CKM_DH_PKCS_PARAMETER_GEN,
					     &mechInfo);
731 732 733
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_GENERATE) == 0)) {
			PK11_TRACEM(CKM_DH_PKCS_PARAMETER_GEN);
		}
Evan Hunt's avatar
Evan Hunt committed
734 735 736
		rv = pkcs_C_GetMechanismInfo(slot, CKM_DH_PKCS_KEY_PAIR_GEN,
					     &mechInfo);
		if ((rv != CKR_OK) ||
737 738
		    ((mechInfo.flags & CKF_GENERATE_KEY_PAIR) == 0)) {
#ifndef PK11_DH_PKCS_PARAMETER_GEN_SKIP
739
			bad = true;
740 741 742
#endif
			PK11_TRACEM(CKM_DH_PKCS_KEY_PAIR_GEN);
		}
Evan Hunt's avatar
Evan Hunt committed
743 744
		rv = pkcs_C_GetMechanismInfo(slot, CKM_DH_PKCS_DERIVE,
					     &mechInfo);
745
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_DERIVE) == 0)) {
746
			bad = true;
747 748 749
			PK11_TRACEM(CKM_DH_PKCS_DERIVE);
		}
		if (bad)
Evan Hunt's avatar
Evan Hunt committed
750
			goto try_digest;
751
#ifndef PK11_DH_DISABLE
Evan Hunt's avatar
Evan Hunt committed
752 753 754
		token->operations |= 1 << OP_DH;
		if (best_dh_token == NULL)
			best_dh_token = token;
755
#endif
Evan Hunt's avatar
Evan Hunt committed
756 757

	try_digest:
758
		bad = false;
Evan Hunt's avatar
Evan Hunt committed
759
		rv = pkcs_C_GetMechanismInfo(slot, CKM_MD5, &mechInfo);
760 761
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_DIGEST) == 0)) {
#ifndef PK11_MD5_DISABLE
762
			bad = true;
763 764 765
#endif
			PK11_TRACEM(CKM_MD5);
		}
Evan Hunt's avatar
Evan Hunt committed
766
		rv = pkcs_C_GetMechanismInfo(slot, CKM_SHA_1, &mechInfo);
767
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_DIGEST) == 0)) {
768
			bad = true;
769 770
			PK11_TRACEM(CKM_SHA_1);
		}
Evan Hunt's avatar
Evan Hunt committed
771
		rv = pkcs_C_GetMechanismInfo(slot, CKM_SHA224, &mechInfo);
772
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_DIGEST) == 0)) {
773
			bad = true;
774 775
			PK11_TRACEM(CKM_SHA224);
		}
Evan Hunt's avatar
Evan Hunt committed
776
		rv = pkcs_C_GetMechanismInfo(slot, CKM_SHA256, &mechInfo);
777
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_DIGEST) == 0)) {
778
			bad = true;
779 780
			PK11_TRACEM(CKM_SHA256);
		}
Evan Hunt's avatar
Evan Hunt committed
781
		rv = pkcs_C_GetMechanismInfo(slot, CKM_SHA384, &mechInfo);
782
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_DIGEST) == 0)) {
783
			bad = true;
784 785
			PK11_TRACEM(CKM_SHA384);
		}
Evan Hunt's avatar
Evan Hunt committed
786
		rv = pkcs_C_GetMechanismInfo(slot, CKM_SHA512, &mechInfo);
787
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_DIGEST) == 0)) {
788
			bad = true;
789 790
			PK11_TRACEM(CKM_SHA512);
		}
Evan Hunt's avatar
Evan Hunt committed
791
		rv = pkcs_C_GetMechanismInfo(slot, CKM_MD5_HMAC, &mechInfo);
792 793
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_SIGN) == 0)) {
#if !defined(PK11_MD5_DISABLE) && !defined(PK11_MD5_HMAC_REPLACE)
794
			bad = true;
Evan Hunt's avatar
Evan Hunt committed
795
#endif
796 797
			PK11_TRACEM(CKM_MD5_HMAC);
		}
Evan Hunt's avatar
Evan Hunt committed
798
		rv = pkcs_C_GetMechanismInfo(slot, CKM_SHA_1_HMAC, &mechInfo);
799 800
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_SIGN) == 0)) {
#ifndef PK11_SHA_1_HMAC_REPLACE
801
			bad = true;
802 803 804
#endif
			PK11_TRACEM(CKM_SHA_1_HMAC);
		}
Evan Hunt's avatar
Evan Hunt committed
805
		rv = pkcs_C_GetMechanismInfo(slot, CKM_SHA224_HMAC, &mechInfo);
806 807
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_SIGN) == 0)) {
#ifndef PK11_SHA224_HMAC_REPLACE
808
			bad = true;
809 810 811
#endif
			PK11_TRACEM(CKM_SHA224_HMAC);
		}
Evan Hunt's avatar
Evan Hunt committed
812
		rv = pkcs_C_GetMechanismInfo(slot, CKM_SHA256_HMAC, &mechInfo);
813 814
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_SIGN) == 0)) {
#ifndef PK11_SHA256_HMAC_REPLACE
815
			bad = true;
816 817 818
#endif
			PK11_TRACEM(CKM_SHA256_HMAC);
		}
Evan Hunt's avatar
Evan Hunt committed
819
		rv = pkcs_C_GetMechanismInfo(slot, CKM_SHA384_HMAC, &mechInfo);
820 821
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_SIGN) == 0)) {
#ifndef PK11_SHA384_HMAC_REPLACE
822
			bad = true;
823 824 825
#endif
			PK11_TRACEM(CKM_SHA384_HMAC);
		}
Evan Hunt's avatar
Evan Hunt committed
826
		rv = pkcs_C_GetMechanismInfo(slot, CKM_SHA512_HMAC, &mechInfo);
827 828
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_SIGN) == 0)) {
#ifndef PK11_SHA512_HMAC_REPLACE
829
			bad = true;
830 831 832 833 834 835 836 837
#endif
			PK11_TRACEM(CKM_SHA512_HMAC);
		}
		if (!bad) {
			token->operations |= 1 << OP_DIGEST;
			if (digest_token == NULL)
				digest_token = token;
		}
Evan Hunt's avatar
Evan Hunt committed
838 839 840 841 842

		/* ECDSA requires digest */
		rv = pkcs_C_GetMechanismInfo(slot, CKM_EC_KEY_PAIR_GEN,
					     &mechInfo);
		if ((rv != CKR_OK) ||
843
		    ((mechInfo.flags & CKF_GENERATE_KEY_PAIR) == 0)) {
844
			bad = true;
845 846
			PK11_TRACEM(CKM_EC_KEY_PAIR_GEN);
		}
Evan Hunt's avatar
Evan Hunt committed
847 848 849
		rv = pkcs_C_GetMechanismInfo(slot, CKM_ECDSA, &mechInfo);
		if ((rv != CKR_OK) ||
		    ((mechInfo.flags & CKF_SIGN) == 0) ||
850
		    ((mechInfo.flags & CKF_VERIFY) == 0)) {
851
			bad = true;
852 853 854
			PK11_TRACEM(CKM_ECDSA);
		}
		if (bad)
Evan Hunt's avatar
Evan Hunt committed
855 856 857 858 859 860
			goto try_gost;
		token->operations |= 1 << OP_EC;
		if (best_ec_token == NULL)
			best_ec_token = token;

	try_gost:
861
		bad = false;
Evan Hunt's avatar
Evan Hunt committed
862 863
		/* does GOST require digest too? */
		rv = pkcs_C_GetMechanismInfo(slot, CKM_GOSTR3411, &mechInfo);
864
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_DIGEST) == 0)) {
865
			bad = true;
866 867
			PK11_TRACEM(CKM_GOSTR3411);
		}
Evan Hunt's avatar
Evan Hunt committed
868 869 870
		rv = pkcs_C_GetMechanismInfo(slot, CKM_GOSTR3410_KEY_PAIR_GEN,
					     &mechInfo);
		if ((rv != CKR_OK) ||
871
		    ((mechInfo.flags & CKF_GENERATE_KEY_PAIR) == 0)) {
872
			bad = true;
873 874
			PK11_TRACEM(CKM_GOSTR3410_KEY_PAIR_GEN);
		}
Evan Hunt's avatar
Evan Hunt committed
875 876 877 878 879
		rv = pkcs_C_GetMechanismInfo(slot,
					     CKM_GOSTR3410_WITH_GOSTR3411,
					     &mechInfo);
		if ((rv != CKR_OK) ||
		    ((mechInfo.flags & CKF_SIGN) == 0) ||
880
		    ((mechInfo.flags & CKF_VERIFY) == 0)) {
881
			bad = true;
882 883 884
			PK11_TRACEM(CKM_GOSTR3410_WITH_GOSTR3411);
		}
		if (bad)
885
			goto try_eddsa;
Evan Hunt's avatar
Evan Hunt committed
886 887 888
		token->operations |= 1 << OP_GOST;
		if (best_gost_token == NULL)
			best_gost_token = token;
889

890 891
	try_eddsa:
#if defined(CKM_EDDSA_KEY_PAIR_GEN) && defined(CKM_EDDSA) && defined(CKK_EDDSA)
892
		bad = false;
893 894 895 896
		rv = pkcs_C_GetMechanismInfo(slot, CKM_EDDSA_KEY_PAIR_GEN,
					     &mechInfo);
		if ((rv != CKR_OK) ||
		    ((mechInfo.flags & CKF_GENERATE_KEY_PAIR) == 0)) {
897
			bad = true;
898 899 900 901 902 903
			PK11_TRACEM(CKM_EDDSA_KEY_PAIR_GEN);
		}
		rv = pkcs_C_GetMechanismInfo(slot, CKM_EDDSA, &mechInfo);
		if ((rv != CKR_OK) ||
		    ((mechInfo.flags & CKF_SIGN) == 0) ||
		    ((mechInfo.flags & CKF_VERIFY) == 0)) {
904
			bad = true;
905 906 907 908 909
			PK11_TRACEM(CKM_EDDSA);
		}
		if (bad)
			goto try_aes;

910
	try_aes:
911
#endif
912
		bad = false;
913
		rv = pkcs_C_GetMechanismInfo(slot, CKM_AES_ECB, &mechInfo);
914
		if ((rv != CKR_OK) || ((mechInfo.flags & CKF_ENCRYPT) == 0)) {
915
			bad = true;
916 917 918
			PK11_TRACEM(CKM_AES_ECB);
		}
		if (bad)
919 920 921 922
			continue;
		token->operations |= 1 << OP_AES;
		if (aes_token == NULL)
			aes_token = token;
Evan Hunt's avatar
Evan Hunt committed
923 924 925 926 927 928 929
	}

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

CK_SLOT_ID
930 931
pk11_get_best_token(pk11_optype_t optype) {
	pk11_token_t *token = NULL;
Evan Hunt's avatar
Evan Hunt committed
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954

	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;
955 956 957
	case OP_AES:
		token = aes_token;
		break;
Evan Hunt's avatar
Evan Hunt committed
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
	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 *
1002
pk11_attribute_first(const pk11_object_t *obj) {
Evan Hunt's avatar
Evan Hunt committed
1003 1004 1005 1006
	return (obj->repr);
}

CK_ATTRIBUTE *
1007
pk11_attribute_next(const pk11_object_t *obj, CK_ATTRIBUTE *attr) {
Evan Hunt's avatar
Evan Hunt committed
1008 1009 1010 1011 1012 1013 1014 1015 1016
	CK_ATTRIBUTE *next;

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

CK_ATTRIBUTE *
1017
pk11_attribute_bytype(const pk11_object_t *obj, CK_ATTRIBUTE_TYPE type) {
Evan Hunt's avatar
Evan Hunt committed
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 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
	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