parsec_service/utils/
config.rs

1// Copyright 2021 Contributors to the Parsec project.
2// SPDX-License-Identifier: Apache-2.0
3//! Structures for the Parsec configuration file
4
5#[cfg(feature = "cryptoauthlib-provider")]
6use crate::providers::cryptoauthlib::Provider as CryptoAuthLibProvider;
7#[cfg(feature = "mbed-crypto-provider")]
8use crate::providers::mbed_crypto::Provider as MbedCryptoProvider;
9#[cfg(feature = "pkcs11-provider")]
10use crate::providers::pkcs11::Provider as Pkcs11Provider;
11#[cfg(feature = "tpm-provider")]
12use crate::providers::tpm::Provider as TpmProvider;
13#[cfg(feature = "trusted-service-provider")]
14use crate::providers::trusted_service::Provider as TrustedServiceProvider;
15#[cfg(not(all(
16    feature = "mbed-crypto-provider",
17    feature = "pkcs11-provider",
18    feature = "tpm-provider",
19    feature = "cryptoauthlib-provider",
20    feature = "trusted-service-provider"
21)))]
22use log::error;
23use log::LevelFilter;
24use parsec_interface::requests::ProviderId;
25use serde::Deserialize;
26use std::io::Error;
27#[cfg(not(all(
28    feature = "mbed-crypto-provider",
29    feature = "pkcs11-provider",
30    feature = "tpm-provider",
31    feature = "cryptoauthlib-provider",
32    feature = "trusted-service-provider"
33)))]
34use std::io::ErrorKind;
35use zeroize::Zeroize;
36
37/// Core settings
38///
39/// See the config.toml file for a description of each field.
40#[derive(Copy, Clone, Deserialize, Debug)]
41#[allow(missing_docs)]
42pub struct CoreSettings {
43    pub thread_pool_size: Option<usize>,
44    pub idle_listener_sleep_duration: Option<u64>,
45    pub log_level: Option<LevelFilter>,
46    pub log_timestamp: Option<bool>,
47    pub body_len_limit: Option<usize>,
48    pub log_error_details: Option<bool>,
49    pub allow_root: Option<bool>,
50    pub buffer_size_limit: Option<usize>,
51    pub allow_deprecated: Option<bool>,
52}
53
54/// Type of the Listener used
55#[derive(Copy, Clone, Deserialize, Debug)]
56pub enum ListenerType {
57    /// Listener using Unix Domain Socket
58    DomainSocket,
59}
60
61/// Configuration of the Listener
62#[derive(Clone, Deserialize, Debug)]
63pub struct ListenerConfig {
64    /// Type of the Listener
65    pub listener_type: ListenerType,
66    /// Timeout of the Listener before the connection errors out (in milliseconds)
67    pub timeout: u64,
68    /// Path of the Unix Domain socket
69    pub socket_path: Option<String>,
70}
71
72/// Authenticator configuration structure
73#[derive(Deserialize, Debug, Zeroize)]
74#[zeroize(drop)]
75#[serde(tag = "auth_type")]
76pub enum AuthenticatorConfig {
77    /// Direct authentication
78    Direct {
79        /// List of service admins
80        admins: Option<Vec<Admin>>,
81    },
82    /// Unix Peer Credentials authentication
83    UnixPeerCredentials {
84        /// List of service admins
85        admins: Option<Vec<Admin>>,
86    },
87    /// JWT-SVID
88    JwtSvid {
89        /// Path to the Workload API socket
90        workload_endpoint: String,
91        /// List of service admins
92        admins: Option<Vec<Admin>>,
93    },
94}
95
96/// Structure defining the properties of a service admin
97#[derive(Deserialize, Debug, Zeroize, Clone)]
98#[zeroize(drop)]
99pub struct Admin {
100    name: String,
101}
102
103impl Admin {
104    /// Give the application name of the admin
105    pub fn name(&self) -> &str {
106        &self.name
107    }
108}
109
110/// Type of the KeyInfoManager
111#[derive(Copy, Clone, Deserialize, Debug)]
112pub enum KeyInfoManagerType {
113    /// KeyInfoManager storing the mappings on disk
114    OnDisk,
115    /// KeyInfoManager for storing mappings within a SQLite database on disk.
116    SQLite,
117}
118
119/// KeyInfoManager configuration
120#[derive(Deserialize, Debug)]
121pub struct KeyInfoManagerConfig {
122    /// Name of the KeyInfoManager
123    pub name: String,
124    /// Type of the KeyInfoManager
125    pub manager_type: KeyInfoManagerType,
126    /// Path used to store the OnDiskKeyInfoManager mappings
127    pub store_path: Option<String>,
128    /// File path where the SQLite database should be stored when using SQLiteKeyInfoManager
129    pub sqlite_db_path: Option<String>,
130}
131
132/// Provider configuration structure
133/// For providers configs in Parsec config.toml we use a format similar
134/// to the one described in the Internally Tagged Enum representation
135/// where "provider_type" is the tag field. For details see:
136/// https://serde.rs/enum-representations.html
137#[derive(Deserialize, Debug, Zeroize)]
138#[zeroize(drop)]
139#[serde(tag = "provider_type")]
140pub enum ProviderConfig {
141    /// Mbed Crypto provider configuration
142    MbedCrypto {
143        /// The name of the provider
144        name: Option<String>,
145        /// Name of the Key Info Manager to use
146        key_info_manager: String,
147    },
148    /// PKCS 11 provider configuration
149    Pkcs11 {
150        /// The name of the provider
151        name: Option<String>,
152        /// Name of the Key Info Manager to use
153        key_info_manager: String,
154        /// Path of the PKCS 11 library
155        library_path: String,
156        /// Slot number to use
157        slot_number: Option<u64>,
158        /// Token serial number to use
159        serial_number: Option<String>,
160        /// User Pin
161        user_pin: Option<String>,
162        /// Control whether public key operations are performed in software
163        software_public_operations: Option<bool>,
164        /// Control whether it is allowed for a key to be exportable
165        allow_export: Option<bool>,
166    },
167    /// TPM provider configuration
168    Tpm {
169        /// The name of the provider
170        name: Option<String>,
171        /// Name of the Key Info Manager to use
172        key_info_manager: String,
173        /// TCTI to use with the provider
174        tcti: String,
175        /// Owner Hierarchy Authentication
176        owner_hierarchy_auth: String,
177        /// Endorsement Hierarchy Authentication Value
178        endorsement_hierarchy_auth: Option<String>,
179        /// Allows the service to still start without this provider if there is no TPM on the
180        /// system. The priority list of providers will be as if this provider was commented out.
181        skip_if_no_tpm: Option<bool>,
182    },
183    /// Microchip CryptoAuthentication Library provider configuration
184    CryptoAuthLib {
185        /// The name of the provider
186        name: Option<String>,
187        /// Name of the Key Info Manager to use
188        key_info_manager: String,
189        /// ATECC Device type
190        device_type: String,
191        /// Interface type
192        iface_type: String,
193        /// Wake delay
194        wake_delay: Option<u16>,
195        /// Number of rx retries
196        rx_retries: Option<i32>,
197        /// I2C slave address
198        slave_address: Option<u8>,
199        /// I2C bus
200        bus: Option<u8>,
201        /// I2C baud rate
202        baud: Option<u32>,
203        /// Access key configuration file name
204        access_key_file_name: Option<String>,
205    },
206    /// Trusted Service provider configuration
207    TrustedService {
208        /// The name of the provider
209        name: Option<String>,
210        /// Name of Key Info Manager to use
211        key_info_manager: String,
212    },
213}
214
215impl ProviderConfig {
216    /// Get the name of the Key Info Manager in the provider configuration
217    pub fn key_info_manager(&self) -> &String {
218        match *self {
219            ProviderConfig::MbedCrypto {
220                ref key_info_manager,
221                ..
222            } => key_info_manager,
223            ProviderConfig::Pkcs11 {
224                ref key_info_manager,
225                ..
226            } => key_info_manager,
227            ProviderConfig::Tpm {
228                ref key_info_manager,
229                ..
230            } => key_info_manager,
231            ProviderConfig::CryptoAuthLib {
232                ref key_info_manager,
233                ..
234            } => key_info_manager,
235            ProviderConfig::TrustedService {
236                ref key_info_manager,
237                ..
238            } => key_info_manager,
239        }
240    }
241    /// Get the Provider ID of the provider
242    pub fn provider_id(&self) -> ProviderId {
243        match *self {
244            ProviderConfig::MbedCrypto { .. } => ProviderId::MbedCrypto,
245            ProviderConfig::Pkcs11 { .. } => ProviderId::Pkcs11,
246            ProviderConfig::Tpm { .. } => ProviderId::Tpm,
247            ProviderConfig::CryptoAuthLib { .. } => ProviderId::CryptoAuthLib,
248            ProviderConfig::TrustedService { .. } => ProviderId::TrustedService,
249        }
250    }
251    /// Get the name of the Provider
252    /// If there is not one set, use the default.
253    pub fn provider_name(&self) -> Result<String, Error> {
254        match *self {
255            #[cfg(feature = "mbed-crypto-provider")]
256            ProviderConfig::MbedCrypto { ref name, .. } => Ok(name
257                .clone()
258                .unwrap_or_else(|| String::from(MbedCryptoProvider::DEFAULT_PROVIDER_NAME))),
259            #[cfg(feature = "pkcs11-provider")]
260            ProviderConfig::Pkcs11 { ref name, .. } => Ok(name
261                .clone()
262                .unwrap_or_else(|| String::from(Pkcs11Provider::DEFAULT_PROVIDER_NAME))),
263            #[cfg(feature = "tpm-provider")]
264            ProviderConfig::Tpm { ref name, .. } => Ok(name
265                .clone()
266                .unwrap_or_else(|| String::from(TpmProvider::DEFAULT_PROVIDER_NAME))),
267            #[cfg(feature = "cryptoauthlib-provider")]
268            ProviderConfig::CryptoAuthLib { ref name, .. } => Ok(name
269                .clone()
270                .unwrap_or_else(|| String::from(CryptoAuthLibProvider::DEFAULT_PROVIDER_NAME))),
271            #[cfg(feature = "trusted-service-provider")]
272            ProviderConfig::TrustedService { ref name, .. } => Ok(name
273                .clone()
274                .unwrap_or_else(|| String::from(TrustedServiceProvider::DEFAULT_PROVIDER_NAME))),
275            #[cfg(not(all(
276                feature = "mbed-crypto-provider",
277                feature = "pkcs11-provider",
278                feature = "tpm-provider",
279                feature = "cryptoauthlib-provider",
280                feature = "trusted-service-provider"
281            )))]
282            _ => {
283                error!("Provider ({:?}) chosen in the configuration was not compiled in Parsec binary.", self);
284                Err(Error::new(ErrorKind::InvalidData, "provider not compiled"))
285            }
286        }
287    }
288}
289
290/// Configuration of Parsec
291///
292/// See the config.toml file for a description of each field.
293#[derive(Deserialize, Debug)]
294#[allow(missing_docs)]
295pub struct ServiceConfig {
296    pub core_settings: CoreSettings,
297    pub listener: ListenerConfig,
298    pub authenticator: AuthenticatorConfig,
299    pub key_manager: Option<Vec<KeyInfoManagerConfig>>,
300    pub provider: Option<Vec<ProviderConfig>>,
301}