xref: /optee_os/ta/pkcs11/src/pkcs11_token.c (revision 37c672344730143717046b64e5ebce2e01e5d278)
1 // SPDX-License-Identifier: BSD-2-Clause
2 /*
3  * Copyright (c) 2017-2020, Linaro Limited
4  */
5 
6 #include <assert.h>
7 #include <pkcs11_ta.h>
8 #include <string.h>
9 #include <string_ext.h>
10 #include <sys/queue.h>
11 #include <tee_api_types.h>
12 #include <tee_internal_api_extensions.h>
13 #include <util.h>
14 
15 #include "pkcs11_token.h"
16 #include "pkcs11_helpers.h"
17 
18 /* Provide 3 slots/tokens, ID is token index */
19 #ifndef CFG_PKCS11_TA_TOKEN_COUNT
20 #define TOKEN_COUNT		3
21 #else
22 #define TOKEN_COUNT		CFG_PKCS11_TA_TOKEN_COUNT
23 #endif
24 
25 /* Static allocation of tokens runtime instances (reset to 0 at load) */
26 struct ck_token ck_token[TOKEN_COUNT];
27 
28 /* Static allocation of tokens runtime instances */
29 struct ck_token *get_token(unsigned int token_id)
30 {
31 	if (token_id > TOKEN_COUNT)
32 		return NULL;
33 
34 	return &ck_token[token_id];
35 }
36 
37 unsigned int get_token_id(struct ck_token *token)
38 {
39 	ptrdiff_t id = token - ck_token;
40 
41 	assert(id >= 0 && id < TOKEN_COUNT);
42 	return id;
43 }
44 
45 static TEE_Result pkcs11_token_init(unsigned int id)
46 {
47 	struct ck_token *token = init_persistent_db(id);
48 
49 	if (!token)
50 		return TEE_ERROR_SECURITY;
51 
52 	if (token->state == PKCS11_TOKEN_RESET) {
53 		/* As per PKCS#11 spec, token resets to read/write state */
54 		token->state = PKCS11_TOKEN_READ_WRITE;
55 		token->session_count = 0;
56 		token->rw_session_count = 0;
57 	}
58 
59 	return TEE_SUCCESS;
60 }
61 
62 TEE_Result pkcs11_init(void)
63 {
64 	unsigned int id = 0;
65 	TEE_Result ret = TEE_ERROR_GENERIC;
66 
67 	for (id = 0; id < TOKEN_COUNT; id++) {
68 		ret = pkcs11_token_init(id);
69 		if (ret)
70 			return ret;
71 	}
72 
73 	return ret;
74 }
75 
76 void pkcs11_deinit(void)
77 {
78 	unsigned int id = 0;
79 
80 	for (id = 0; id < TOKEN_COUNT; id++)
81 		close_persistent_db(get_token(id));
82 }
83