Skip to main content

teter_core/
command.rs

1//! Signed commands to a machine (#88), without I/O: a device seals a
2//! command to the one-time key of a challenge the machine signed, and opens
3//! the machine's signed reply. The channel that carries them is
4//! `teter_client::command`'s.
5
6use std::io;
7
8use teter_common::command::{
9    Command, Outcome, Signed, challenge_bytes, command_bytes, command_info, reply_bytes, reply_info,
10};
11
12use crate::account::{AccountKeys, seal_to, verify};
13
14/// A challenge the machine signed.
15#[derive(Debug, Clone)]
16pub struct Challenge {
17    /// The nonce a command is bound to.
18    pub nonce: Vec<u8>,
19    /// The one-time key a command is sealed to.
20    pub key: Vec<u8>,
21}
22
23/// The challenge `nonce` and `key`, if `signature` is machine `machine`'s
24/// (whose public key is `machine_key`) of them.
25#[must_use]
26pub fn check_challenge(
27    machine: &str,
28    machine_key: &[u8],
29    nonce: Vec<u8>,
30    key: Vec<u8>,
31    signature: &[u8],
32) -> Option<Challenge> {
33    verify(
34        machine_key,
35        &challenge_bytes(machine, &nonce, &key),
36        signature,
37    )
38    .then_some(Challenge { nonce, key })
39}
40
41/// `command` signed by `account` for `machine` and `challenge`, sealed to the
42/// challenge's one-time key.
43///
44/// # Errors
45///
46/// A random source that fails.
47pub fn seal_command(
48    account: &AccountKeys,
49    machine: &str,
50    challenge: &Challenge,
51    command: Command,
52) -> io::Result<Vec<u8>> {
53    let signature = account.sign(&command_bytes(machine, &challenge.nonce, &command));
54    let signed = serde_json::to_vec(&Signed { command, signature }).map_err(io::Error::other)?;
55    seal_to(
56        &challenge.key,
57        &command_info(machine, &challenge.nonce),
58        &signed,
59    )
60}
61
62/// The outcome in machine `machine`'s reply to the command bound to `nonce`:
63/// checked against its signature by `machine_key`, and opened with
64/// `account`.
65///
66/// # Errors
67///
68/// A reply the machine did not sign, or one that does not open.
69pub fn open_reply(
70    account: &AccountKeys,
71    machine: &str,
72    machine_key: &[u8],
73    nonce: &[u8],
74    sealed: &[u8],
75    signature: &[u8],
76) -> io::Result<Outcome> {
77    if !verify(machine_key, &reply_bytes(machine, nonce, sealed), signature) {
78        return Err(io::Error::other("the reply is not signed by the machine"));
79    }
80    let plain = account
81        .open_sealed(&reply_info(machine, nonce), sealed)
82        .map_err(io::Error::other)?;
83    serde_json::from_slice(&plain).map_err(io::Error::other)
84}