1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
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
// SPDX-License-Identifier: MIT
// Copyright (c) Microsoft Corporation.
//! The Siguldry client configuration.
use std::{num::NonZeroU64, path::PathBuf};
use sequoia_openpgp::crypto::Password;
use serde::{Deserialize, Serialize};
use crate::config::Credentials;
/// Configuration for the siguldry client.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
/// The Siguldry server hostname. This is used to validate the server's TLS certificate.
pub server_hostname: String,
/// The Siguldry bridge hostname. This is used to validate the bridge's TLS certificate.
pub bridge_hostname: String,
/// The port on the Siguldry bridge to connect to; the default is 44334.
pub bridge_port: u16,
/// The time, in seconds, to leave an idle connection to the signing server open.
///
/// Idle time is measured from the last time the client sent a request to the server,
/// and clients transparently restart the connection on the next request. The server
/// will also shut down idle client connections after a time (in a much less graceful
/// manner) so this value should be somewhat less than the server-set timeout. It should
/// also be *larger* than the `request_timeout` setting.
///
/// The default idle timeout is 600 (10 minutes).
#[serde(default = "default_idle_timeout")]
pub idle_timeout: NonZeroU64,
/// The amount of time, in seconds, to wait before giving up on a request and retrying.
///
/// This covers both sending requests and receiving responses. In other words, the client
/// will retry the request on a new connection if it cannot write the request to the socket
/// within `request_timeout`, *and* it will retry if it fails to read a response to that
/// request from the socket within `request_timeout`.
///
/// The default is 30 seconds.
#[serde(default = "default_request_timeout")]
pub request_timeout: NonZeroU64,
/// The credentials to use when authenticating to the Siguldry bridge and server. Note that
/// the certificate must have the `clientAuth` extended key usage extension.
pub credentials: Credentials,
/// Enforce a limit on the number of concurrent connections to accept when running as a proxy.
///
/// This only applies when using the `bind` or `accept-no` proxy modes. The default is unlimited.
#[serde(default = "default_concurrency")]
pub proxy_concurrency: usize,
/// A list of keys to unlock for the client.
///
/// This can be set for users of the client who can't (or don't want to) call unlock or safely
/// store a password. One example would be the PKCS#11 module used inside a build environment.
pub keys: Vec<Key>,
}
const fn default_idle_timeout() -> NonZeroU64 {
NonZeroU64::new(600).expect("Set a non-zero default")
}
const fn default_request_timeout() -> NonZeroU64 {
NonZeroU64::new(30).expect("Set a non-zero default")
}
fn default_concurrency() -> usize {
tokio::sync::Semaphore::MAX_PERMITS
}
impl Default for Config {
fn default() -> Self {
Self {
server_hostname: "server.example.com".to_string(),
bridge_hostname: "bridge.example.com".to_string(),
bridge_port: 44334,
idle_timeout: default_idle_timeout(),
request_timeout: default_request_timeout(),
credentials: Credentials {
private_key: PathBuf::from("siguldry.client.private_key.pem"),
certificate: PathBuf::from("siguldry.client.certificate.pem"),
ca_certificate: PathBuf::from("siguldry.ca_certificate.pem"),
},
proxy_concurrency: default_concurrency(),
keys: vec![],
}
}
}
#[cfg(feature = "cli")]
impl std::fmt::Display for Config {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
toml::ser::to_string_pretty(&self).unwrap_or_default()
)
}
}
/// A key to unlock for the client
#[derive(Debug, Clone, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Key {
/// The name of the key in the Siguldry server.
pub key_name: String,
/// The systemd credential ID containing the passphrase.
///
/// The passphrase inside the file must be entirely on the first line of
/// the file and the file should be terminated with a newline. The default
/// settings for `systemd-ask-password` will produce an acceptable file:
///
/// ```bash
/// systemd-ask-password | systemd-creds encrypt - /etc/credstore.encrypted/siguldry.my_key_password
/// ```
pub passphrase_path: PathBuf,
#[serde(skip)]
pub(crate) passphrase: Password,
}
impl Key {
// Useful for tests that serialize entries out.
#[doc(hidden)]
pub fn private_new(key_name: String, passphrase_path: PathBuf) -> Self {
Self {
key_name,
passphrase_path,
passphrase: "".into(),
}
}
}
impl<'de> Deserialize<'de> for Key {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(Deserialize)]
struct KeyHelper {
key_name: String,
passphrase_path: PathBuf,
}
let helper = {
let mut helper = KeyHelper::deserialize(deserializer)?;
if !helper.passphrase_path.is_absolute() {
let creds_dir = std::env::var_os("CREDENTIALS_DIRECTORY").ok_or_else(||
serde::de::Error::custom(format!(
"key passphrase_path {} is relative but CREDENTIALS_DIRECTORY environment variable is unset",
helper.passphrase_path.display(),
)))?;
let base = PathBuf::from(creds_dir);
helper.passphrase_path = base.join(helper.passphrase_path);
helper
} else {
helper
}
};
let passphrase = std::fs::read_to_string(&helper.passphrase_path)
.map_err(|e| {
serde::de::Error::custom(format!(
"Failed to read passphrase file {}: {}",
helper.passphrase_path.display(),
e
))
})?
.lines()
.next()
.and_then(|pass| {
let pass = pass.trim();
if !pass.is_empty() { Some(pass) } else { None }
})
.ok_or_else(|| {
serde::de::Error::custom(format!(
"Passphrase file {} does not contain a password on the first line",
helper.passphrase_path.display()
))
})?
.to_string()
.into();
Ok(Key {
key_name: helper.key_name,
passphrase_path: helper.passphrase_path,
passphrase,
})
}
}
impl Key {
pub fn password(&self) -> String {
self.passphrase
.map(|p| String::from_utf8(p.to_vec()).expect("The password deserialized to a string"))
}
}
#[cfg(test)]
mod tests {
#[test]
fn load_example_config() -> anyhow::Result<()> {
let example_conf_path =
std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("client.toml.example");
let example_conf = std::fs::read_to_string(&example_conf_path)?;
toml::de::from_str::<super::Config>(&example_conf)?;
Ok(())
}
#[test]
fn config_extra_key() -> anyhow::Result<()> {
let config = r#"
server_hostname = "server.example.com"
bridge_hostname = "bridge.example.com"
bridge_port = 44333
another_key = 42
request_timeout = 30
[credentials]
private_key = "siguldry.client.private_key.pem"
certificate = "/etc/siguldry/client.cert"
ca_certificate = "/etc/siguldry/ca.crt"
"#;
if let Err(error) = toml::from_str::<super::Config>(config) {
assert!(error.message().contains("unknown field `another_key`"));
} else {
panic!("Config should fail to load");
}
Ok(())
}
}