1 /*
2  * Copyright (c) 2020-2021, Arm Limited and Contributors. All rights reserved.
3  *
4  * SPDX-License-Identifier: BSD-3-Clause
5  */
6 
7 #include "crypto_service_context.h"
8 #include <service/crypto/factory/crypto_provider_factory.h>
9 #include <service/crypto/backend/mbedcrypto/mbedcrypto_backend.h>
10 
crypto_service_context(const char * sn,unsigned int encoding)11 crypto_service_context::crypto_service_context(const char *sn, unsigned int encoding) :
12     standalone_service_context(sn),
13     m_encoding(encoding),
14     m_crypto_provider(NULL),
15     m_storage_client(),
16     m_null_store(),
17     m_storage_service_context(NULL),
18     m_storage_session(NULL)
19 {
20 
21 }
22 
~crypto_service_context()23 crypto_service_context::~crypto_service_context()
24 {
25 
26 }
27 
do_init()28 void crypto_service_context::do_init()
29 {
30     struct storage_backend *storage_backend = NULL;
31     struct storage_backend *null_storage_backend = null_store_init(&m_null_store);
32 
33     /* Locate and open RPC session with internal-trusted-storage service to
34      * provide a persistent keystore
35      */
36     m_storage_service_context =
37         service_locator_query("sn:trustedfirmware.org:internal-trusted-storage:0");
38 
39     if (m_storage_service_context) {
40 
41         m_storage_session =
42             service_context_open(m_storage_service_context);
43 
44         if (m_storage_session) {
45 
46             storage_backend = secure_storage_client_init(&m_storage_client, m_storage_session);
47         }
48     }
49 
50     if (!storage_backend) {
51 
52         /* Something has gone wrong with establishing a session with the
53          * storage service endpoint
54          */
55         storage_backend = null_storage_backend;
56     }
57 
58     /* Initialise the crypto service provider */
59     struct rpc_service_interface *crypto_iface = NULL;
60 
61     if (mbedcrypto_backend_init(storage_backend, 0) == PSA_SUCCESS) {
62 
63         if (m_encoding == TS_RPC_ENCODING_PACKED_C)
64             m_crypto_provider = crypto_provider_factory_create();
65         else
66             m_crypto_provider = crypto_protobuf_provider_factory_create();
67 
68         crypto_iface = service_provider_get_rpc_interface(&m_crypto_provider->base_provider);
69     }
70 
71     standalone_service_context::set_rpc_interface(crypto_iface);
72 }
73 
do_deinit()74 void crypto_service_context::do_deinit()
75 {
76     if (m_storage_session) {
77         service_context_close(m_storage_service_context, m_storage_session);
78         m_storage_session = NULL;
79     }
80 
81     if (m_storage_service_context) {
82         service_context_relinquish(m_storage_service_context);
83         m_storage_service_context = NULL;
84     }
85 
86     crypto_provider_factory_destroy(m_crypto_provider);
87     secure_storage_client_deinit(&m_storage_client);
88     null_store_deinit(&m_null_store);
89 }
90