siguldry 0.8.0

A signing server and client.
Documentation
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
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
416
417
418
419
420
421
422
423
424
425
426
// SPDX-License-Identifier: MIT
// Copyright (c) Microsoft Corporation.

use std::collections::HashMap;
use std::path::PathBuf;

use anyhow::Context;
use cryptoki::context::Pkcs11;
use cryptoki::session::UserType;
use cryptoki::slot::Slot;
use cryptoki::types::AuthPin;
use openssl::pkey::PKey;
use sequoia_openpgp::crypto::Password;
use serde::{Deserialize, Serialize};
use sqlx::SqliteConnection;
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader};
use tokio_util::sync::CancellationToken;
use tracing::instrument;
use uuid::Uuid;

use crate::error::ServerError;
use crate::ipc_common::IpcClient;
use crate::protocol;
use crate::server::config::Pkcs11Binding;
use crate::{
    protocol::{DigestAlgorithm, Signature},
    server::{Config, crypto, db},
};

type KeyMap = HashMap<String, UnlockedKey>;

enum UnlockedKey {
    Private {
        key: PKey<openssl::pkey::Private>,
    },
    Pkcs11 {
        // Used to track if we've already loaded the module
        module: PathBuf,
        pkcs11: Pkcs11,
        slot: Slot,
        pin: AuthPin,
    },
}

/// The PKCS#11 bindings required to access keys, along with the PINs provided at service startup.
/// This is redefined from [`Pkcs11Binding`] because it does need to serialize/deserialize the PIN.
#[derive(Serialize, Deserialize)]
#[allow(clippy::exhaustive_enums)]
#[doc(hidden)]
struct BindingWithPin {
    public_key: PathBuf,
    private_key: String,
    pin: String,
}

impl From<BindingWithPin> for Pkcs11Binding {
    fn from(value: BindingWithPin) -> Self {
        Pkcs11Binding {
            certificate: value.public_key,
            private_key: Some(value.private_key),
            pin: Some(Password::from(value.pin)),
        }
    }
}

#[derive(Serialize, Deserialize)]
#[allow(clippy::exhaustive_enums)]
#[doc(hidden)]
enum Request {
    Config {
        user: String,
        database_path: String,
        session_id: Uuid,
        pkcs11_bindings: Vec<BindingWithPin>,
    },
    Unlock {
        key: String,
        password: String,
    },
    Sign {
        key: String,
        digests: Vec<(DigestAlgorithm, String)>,
    },
}

#[derive(Serialize, Deserialize)]
#[allow(clippy::exhaustive_enums)]
#[doc(hidden)]
enum Response {
    Signatures { signatures: Vec<Signature> },
    PgpSign { payload_size: usize },
    Success {},
    Failure { reason: String },
}

pub(crate) struct Client {
    inner: IpcClient,
}

impl Client {
    pub(crate) async fn new(
        user: String,
        config: Config,
        session_id: Uuid,
    ) -> anyhow::Result<Self> {
        let inner = IpcClient::new(&config.signer_socket_path).await?;
        let mut client = Self { inner };

        tracing::trace!("requesting signing helper config");
        let mut bindings = vec![];
        for binding in config.pkcs11_bindings.iter() {
            if let (Some(private_key), Some(pin)) = (&binding.private_key, &binding.pin) {
                let pin = pin.map(|p| String::from_utf8(p.to_vec()))?;
                bindings.push(BindingWithPin {
                    public_key: binding.certificate.clone(),
                    private_key: private_key.clone(),
                    pin,
                });
            }
        }
        let database_path = config
            .database()
            .as_os_str()
            .to_str()
            .ok_or_else(|| anyhow::anyhow!("Database path isn't valid UTF8"))?
            .to_string();
        client
            .inner
            .request(&Request::Config {
                user,
                database_path,
                session_id,
                pkcs11_bindings: bindings,
            })
            .await?;
        tracing::trace!("requested signing helper config");

        Ok(client)
    }

    #[instrument(skip_all, err, fields(key))]
    pub(crate) async fn unlock_request(
        &mut self,
        key: String,
        password: String,
    ) -> Result<protocol::Response, ServerError> {
        let response = self
            .inner
            .request(&Request::Unlock { key, password })
            .await?;
        let response = serde_json::from_value(response).map_err(|error| {
            tracing::error!(?error, "helper returned invalid response");
            ServerError::Internal
        })?;

        match response {
            Response::Failure { reason } => {
                tracing::error!(reason, "Failed to unlock key");
                Err(ServerError::Internal)
            }
            Response::Success {} => Ok(protocol::Response::Unlock {}),
            _ => {
                tracing::error!("helper returned invalid response");
                Err(ServerError::Internal)
            }
        }
    }

    #[instrument(skip_all, err, fields(key))]
    pub(crate) async fn sign_request(
        &mut self,
        key: String,
        digests: Vec<(DigestAlgorithm, String)>,
    ) -> Result<Vec<Signature>, ServerError> {
        let response = self.inner.request(&Request::Sign { key, digests }).await?;
        let response = serde_json::from_value(response).map_err(|error| {
            tracing::error!(?error, "helper returned invalid response");
            ServerError::Internal
        })?;

        match response {
            Response::Signatures { signatures } => Ok(signatures),
            Response::Failure { reason } => {
                tracing::error!(reason, "Failed to unlock key");
                Err(ServerError::Internal)
            }
            _ => {
                tracing::error!("helper returned invalid response");
                Err(ServerError::Internal)
            }
        }
    }

    /// Shut down the IPC client.
    pub(crate) async fn shutdown(self) -> anyhow::Result<()> {
        self.inner.shutdown().await?;
        Ok(())
    }
}

/// Start a siguldry-signer helper server.
#[instrument(name = "siguldry-signer", skip_all, fields(user = tracing::field::Empty, session_id = tracing::field::Empty))]
pub async fn serve<
    R: AsyncRead + Unpin + std::fmt::Debug,
    W: AsyncWrite + Unpin + std::fmt::Debug,
>(
    halt_token: CancellationToken,
    requests: R,
    mut responses: W,
) -> anyhow::Result<()> {
    tracing::debug!("Handling requests");
    let mut requests = BufReader::new(requests).lines();

    // Keys that the client has unlocked are stored in this map of key names to key passwords.
    // A performance optimization might be to decrypt the key once; we should benchmark and
    // decide on that.
    let mut key_passwords: KeyMap = HashMap::new();
    let (user, database_path, pkcs11_bindings) = tokio::select! {
        _ = halt_token.cancelled() => {
            tracing::info!("siguldry-helper received shut down signal");
            return Ok(())
        }
        request = requests.next_line() => {
            match request? {
                Some(request) => {
                    let request: Request = serde_json::from_str(&request)?;
                    match request {
                        Request::Config { user, database_path, session_id, pkcs11_bindings } => {
                            tracing::Span::current().record("session_id", tracing::field::display(session_id));
                            let mut response = serde_json::to_string(&Response::Success {  })?;
                            response.push('\n');
                            responses.write_all(response.as_bytes()).await?;
                            let bindings = pkcs11_bindings.into_iter().map(|b| b.into()).collect::<Vec<Pkcs11Binding>>();
                            (user, database_path, bindings)},
                        _ => return Err(anyhow::anyhow!("The first message must configure this helper"))
                    }
                },
                None => return Ok(())
            }
        }
    };

    let db_pool = db::pool(&database_path, true).await?;
    let mut db_conn = db_pool.acquire().await?;
    let user = db::User::get(&mut db_conn, &user).await?;
    tracing::Span::current().record("user", &user.name);
    drop(db_conn);
    tracing::info!("siguldry-signer is configured and ready to accept requests");

    loop {
        let request = tokio::select! {
            _ = halt_token.cancelled() => {
                tracing::info!("siguldry-signer received shut down signal");
                break;
            }
            request = requests.next_line() => request,
        }?;
        tracing::debug!("siguldry-signer got request");

        let request = if let Some(request) = request {
            serde_json::from_str(&request)?
        } else {
            tracing::info!("siguldry-signer received EOF and is shutting down");
            break;
        };

        let response = match request {
            Request::Config {
                user: _,
                database_path: _,
                session_id: _,
                pkcs11_bindings: _,
            } => Response::Failure {
                reason: "helper cannot be configured twice".to_string(),
            },
            Request::Unlock { key, password } => {
                let mut conn = db_pool.begin().await?;
                match unlock(
                    &mut conn,
                    &mut key_passwords,
                    &pkcs11_bindings,
                    &user,
                    key,
                    Password::from(password),
                )
                .await
                {
                    Ok(_) => Response::Success {},
                    Err(error) => Response::Failure {
                        reason: error.to_string(),
                    },
                }
            }
            Request::Sign { key, digests } => {
                let mut conn = db_pool.begin().await?;
                match sign(&mut conn, &mut key_passwords, &key, digests).await {
                    Ok(signatures) => Response::Signatures { signatures },
                    Err(error) => Response::Failure {
                        reason: error.to_string(),
                    },
                }
            }
        };
        tracing::trace!("About to write response");
        let mut response = serde_json::to_string(&response)?;
        response.push('\n');
        responses.write_all(response.as_bytes()).await?;
        tracing::trace!("Successfully wrote response");
    }

    Ok(())
}

#[allow(clippy::too_many_arguments)]
#[instrument(skip_all, err, fields(key = key_name))]
async fn unlock(
    conn: &mut SqliteConnection,
    key_passwords: &mut KeyMap,
    pkcs11_bindings: &[Pkcs11Binding],
    user: &db::User,
    key_name: String,
    user_password: Password,
) -> anyhow::Result<()> {
    let key = db::Key::get(conn, &key_name).await?;
    let key_access = db::KeyAccess::get(conn, &key, user).await?;
    let password = crypto::binding::decrypt_key_password(
        pkcs11_bindings,
        user_password.clone(),
        &key_access.encrypted_passphrase,
    )
    .await?;
    if let Some(token_id) = key.pkcs11_token_id {
        let db_token = db::Pkcs11Token::get(conn, token_id).await?;
        let pin = password
            .map(|p| String::from_utf8(p.to_vec()))
            .map(AuthPin::from)?;

        let unlocked_key = if let Some(UnlockedKey::Pkcs11 {
            module: _,
            pkcs11,
            slot: _,
            pin: _,
        }) = key_passwords.values().find(|k| match k {
            UnlockedKey::Pkcs11 {
                module,
                pkcs11: _,
                slot: _,
                pin: _,
            } => &db_token.module_path == module,
            UnlockedKey::Private { .. } => false,
        }) {
            // This module has previously been loaded so we shouldn't re-initialize it
            let slot = db_token.slot(pkcs11)?;
            let session = pkcs11.open_ro_session(slot)?;
            session
                .login(cryptoki::session::UserType::User, Some(&pin))
                .context("Failed to login to the PKCS#11 token")?;

            UnlockedKey::Pkcs11 {
                module: db_token.module_path,
                pkcs11: pkcs11.clone(),
                slot,
                pin,
            }
        } else {
            let pkcs11 = db_token.intialize()?;
            let slot = db_token.slot(&pkcs11)?;
            let session = pkcs11.open_ro_session(slot)?;
            session
                .login(cryptoki::session::UserType::User, Some(&pin))
                .context("Failed to login to the PKCS#11 token")?;

            UnlockedKey::Pkcs11 {
                module: db_token.module_path,
                pkcs11,
                slot,
                pin,
            }
        };

        key_passwords.insert(key.name, unlocked_key);
    } else {
        let private_key = crypto::binding::decrypt_private_key(
            &key,
            &key_access.encrypted_passphrase,
            pkcs11_bindings,
            user_password,
        )
        .await?;
        key_passwords.insert(key.name, UnlockedKey::Private { key: private_key });
    }

    tracing::info!("Unlocked key");
    return Ok(());
}

#[instrument(skip_all, err, fields(key = key_name))]
async fn sign(
    conn: &mut SqliteConnection,
    key_passwords: &mut KeyMap,
    key_name: &str,
    digests: Vec<(DigestAlgorithm, String)>,
) -> anyhow::Result<Vec<Signature>> {
    let key = db::Key::get(conn, key_name).await?;
    let unlocked_key = key_passwords
        .get(key_name)
        .ok_or_else(|| anyhow::anyhow!("You need to unlock the key"))?;

    let signatures = match unlocked_key {
        UnlockedKey::Private { key: private_key } => {
            crypto::signing::sign_with_softkey(&key, private_key, digests)
        }
        UnlockedKey::Pkcs11 {
            module: _,
            pkcs11,
            slot,
            pin,
        } => {
            let session = pkcs11.open_ro_session(*slot)?;
            session.login(UserType::User, Some(pin))?;
            crypto::signing::sign_with_pkcs11(&key, &session, digests)
        }
    }?;

    Ok(signatures)
}