Skip to main content

alien_signing/
session.rs

1//! The channel of a signed exec session, without any network code.
2//!
3//! 1. The enforcer sends a [`Challenge`]: a fresh nonce and an ephemeral
4//!    X25519 key for this session.
5//! 2. The engineer's device signs a `session/v1` statement naming that nonce,
6//!    that key and the client's own ephemeral key.
7//! 3. Both sides run `Noise_KK_25519_ChaChaPoly_SHA256` with the two keys,
8//!    bound to the statement's digest, so the session is the one that was
9//!    signed. Every later frame is encrypted and numbered: whoever relays
10//!    the frames reads nothing, and a frame it injects, drops, reorders or
11//!    replays fails to decrypt.
12//! 4. The enforcer appends every frame to a hash-chained [`Transcript`].
13
14use alien_error::AlienError;
15use base64::engine::general_purpose::STANDARD;
16use base64::Engine as _;
17use chrono::{DateTime, Utc};
18use serde::{Deserialize, Serialize};
19use sha2::{Digest, Sha256};
20
21use crate::envelope::Kind;
22use crate::error::{ErrorData, Result};
23
24/// Longest exec session a statement may allow.
25pub const MAX_SESSION_SECONDS: u32 = 30 * 60;
26
27/// What a session runs.
28#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
29#[serde(rename_all = "camelCase", deny_unknown_fields)]
30pub struct SessionTarget {
31    /// Machine id, for machine sessions.
32    #[serde(default, skip_serializing_if = "Option::is_none")]
33    pub machine: Option<String>,
34    /// Workload name, for replica sessions.
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub workload: Option<String>,
37}
38
39/// `session/v1`: one exec session.
40#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
41#[serde(rename_all = "camelCase", deny_unknown_fields)]
42pub struct SessionBody {
43    /// Unique session id; an enforcer refuses one it has seen.
44    pub session_id: String,
45    /// What the session reaches.
46    pub target: SessionTarget,
47    /// Program and arguments, or absent for the default shell.
48    #[serde(default, skip_serializing_if = "Option::is_none")]
49    pub argv: Option<Vec<String>>,
50    /// Whether a terminal is allocated.
51    pub tty: bool,
52    /// Longest the session may last.
53    pub max_duration_seconds: u32,
54    /// Who asked, for the transcript.
55    pub requester: String,
56    /// Why, for the transcript.
57    pub reason: String,
58    /// The enforcer's fresh nonce, base64.
59    pub verifier_nonce: String,
60    /// The enforcer's ephemeral public key for this session, base64.
61    pub verifier_key: String,
62    /// The client's ephemeral public key, base64.
63    pub client_key: String,
64}
65
66/// What the enforcer handed out for one session request.
67#[derive(Debug, Clone, PartialEq, Eq)]
68pub struct SessionChallenge {
69    /// Nonce the enforcer generated, base64.
70    pub nonce: String,
71    /// Enforcer's ephemeral public key, base64.
72    pub verifier_key: String,
73    /// When the nonce was issued.
74    pub issued_at: DateTime<Utc>,
75    /// How long a nonce stays usable.
76    pub nonce_lifetime_seconds: u32,
77}
78
79impl SessionBody {
80    /// Check the session against the challenge the enforcer issued. The
81    /// caller also records the session id and refuses one it has seen.
82    pub fn check(&self, challenge: &SessionChallenge, now: DateTime<Utc>) -> Result<()> {
83        if self.verifier_nonce != challenge.nonce {
84            return Err(refused(
85                Kind::Session,
86                "the nonce is not the one this enforcer issued",
87            ));
88        }
89        if self.verifier_key != challenge.verifier_key {
90            return Err(refused(
91                Kind::Session,
92                "the session is bound to another enforcer key",
93            ));
94        }
95        let age = now.signed_duration_since(challenge.issued_at).num_seconds();
96        if age < 0 || age > i64::from(challenge.nonce_lifetime_seconds) {
97            return Err(refused(Kind::Session, "the nonce has expired"));
98        }
99        if self.max_duration_seconds == 0 || self.max_duration_seconds > MAX_SESSION_SECONDS {
100            return Err(refused(
101                Kind::Session,
102                format!("a session may last 1 to {MAX_SESSION_SECONDS} seconds"),
103            ));
104        }
105        if self.session_id.is_empty() || self.client_key.is_empty() {
106            return Err(refused(
107                Kind::Session,
108                "the session id and client key are required",
109            ));
110        }
111        Ok(())
112    }
113}
114
115const NOISE_PATTERN: &str = "Noise_KK_25519_ChaChaPoly_SHA256";
116/// Largest Noise message.
117const MAX_MESSAGE: usize = 65535;
118/// Plaintext room in one Noise message, after the tag and the frame kind.
119pub const MAX_FRAME_PAYLOAD: usize = MAX_MESSAGE - 16 - 1;
120/// How long a challenge's nonce stays usable.
121pub const NONCE_LIFETIME_SECONDS: u32 = 120;
122
123/// An X25519 key pair for one session.
124pub struct SessionKeys {
125    private: Vec<u8>,
126    public: Vec<u8>,
127}
128
129impl SessionKeys {
130    /// A new key pair.
131    pub fn generate() -> Result<Self> {
132        let keypair = builder()?
133            .generate_keypair()
134            .map_err(|error| channel_error(format!("could not generate a session key: {error}")))?;
135        Ok(Self {
136            private: keypair.private,
137            public: keypair.public,
138        })
139    }
140
141    /// The public key, base64.
142    pub fn public_key(&self) -> String {
143        STANDARD.encode(&self.public)
144    }
145}
146
147/// What the enforcer sends first.
148#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
149#[serde(rename_all = "camelCase", deny_unknown_fields)]
150pub struct Challenge {
151    /// Session id the enforcer was asked to open.
152    pub session_id: String,
153    /// Fresh random nonce, base64.
154    pub nonce: String,
155    /// The enforcer's ephemeral public key for this session, base64.
156    pub verifier_key: String,
157    /// When the enforcer issued it.
158    pub issued_at: DateTime<Utc>,
159}
160
161impl Challenge {
162    /// A new challenge for `session_id` with `keys`.
163    pub fn new(session_id: &str, keys: &SessionKeys) -> Result<Self> {
164        let mut nonce = [0u8; 32];
165        getrandom::fill(&mut nonce)
166            .map_err(|error| channel_error(format!("no randomness: {error}")))?;
167        Ok(Self {
168            session_id: session_id.to_string(),
169            nonce: STANDARD.encode(nonce),
170            verifier_key: keys.public_key(),
171            issued_at: Utc::now(),
172        })
173    }
174
175    /// What [`SessionBody::check`] compares the statement to.
176    pub fn expectation(&self) -> SessionChallenge {
177        SessionChallenge {
178            nonce: self.nonce.clone(),
179            verifier_key: self.verifier_key.clone(),
180            issued_at: self.issued_at,
181            nonce_lifetime_seconds: NONCE_LIFETIME_SECONDS,
182        }
183    }
184}
185
186/// One side of the handshake, before it completes.
187pub struct Handshake {
188    state: snow::HandshakeState,
189}
190
191/// Which side of the channel this is.
192#[derive(Debug, Clone, Copy, PartialEq, Eq)]
193pub enum Side {
194    /// The engineer's CLI, which starts the handshake.
195    Client,
196    /// The enforcer.
197    Enforcer,
198}
199
200impl Handshake {
201    /// Start a handshake. `own` are this side's session keys, `remote_key` the
202    /// other side's public key (base64) and `statement_digest` the signed
203    /// session statement's digest, which both sides mix in.
204    pub fn new(
205        side: Side,
206        own: &SessionKeys,
207        remote_key: &str,
208        statement_digest: &str,
209    ) -> Result<Self> {
210        let remote = STANDARD
211            .decode(remote_key)
212            .map_err(|_| channel_error("the remote session key is not base64"))?;
213        if remote.len() != 32 {
214            return Err(channel_error("the remote session key is not 32 bytes"));
215        }
216        let prologue = prologue(statement_digest);
217        let builder = builder()?
218            .local_private_key(&own.private)
219            .map_err(|error| channel_error(format!("bad local key: {error}")))?
220            .remote_public_key(&remote)
221            .map_err(|error| channel_error(format!("bad remote key: {error}")))?
222            .prologue(&prologue)
223            .map_err(|error| channel_error(format!("bad prologue: {error}")))?;
224        let state = match side {
225            Side::Client => builder.build_initiator(),
226            Side::Enforcer => builder.build_responder(),
227        }
228        .map_err(|error| channel_error(format!("could not start the handshake: {error}")))?;
229        Ok(Self { state })
230    }
231
232    /// The next handshake message to send.
233    pub fn write(&mut self) -> Result<Vec<u8>> {
234        let mut message = vec![0u8; MAX_MESSAGE];
235        let length = self
236            .state
237            .write_message(&[], &mut message)
238            .map_err(|error| channel_error(format!("handshake failed: {error}")))?;
239        message.truncate(length);
240        Ok(message)
241    }
242
243    /// Read the other side's handshake message.
244    pub fn read(&mut self, message: &[u8]) -> Result<()> {
245        let mut payload = vec![0u8; MAX_MESSAGE];
246        self.state
247            .read_message(message, &mut payload)
248            .map_err(|error| channel_error(format!("handshake failed: {error}")))?;
249        Ok(())
250    }
251
252    /// Finish into an encrypted channel.
253    pub fn finish(self) -> Result<Channel> {
254        if !self.state.is_handshake_finished() {
255            return Err(channel_error("the handshake is not finished"));
256        }
257        let transport = self
258            .state
259            .into_transport_mode()
260            .map_err(|error| channel_error(format!("handshake failed: {error}")))?;
261        Ok(Channel { transport })
262    }
263}
264
265/// What one frame carries.
266#[derive(Debug, Clone, Copy, PartialEq, Eq)]
267pub enum FrameKind {
268    /// Terminal or process bytes.
269    Data,
270    /// A JSON control message (resize, exit, error).
271    Control,
272}
273
274/// An encrypted, numbered channel.
275pub struct Channel {
276    transport: snow::TransportState,
277}
278
279impl Channel {
280    /// Encrypt one frame.
281    pub fn seal(&mut self, kind: FrameKind, payload: &[u8]) -> Result<Vec<u8>> {
282        if payload.len() > MAX_FRAME_PAYLOAD {
283            return Err(channel_error("the frame is too large"));
284        }
285        let mut plaintext = Vec::with_capacity(payload.len() + 1);
286        plaintext.push(match kind {
287            FrameKind::Data => 0,
288            FrameKind::Control => 1,
289        });
290        plaintext.extend_from_slice(payload);
291        let mut message = vec![0u8; plaintext.len() + 16];
292        let length = self
293            .transport
294            .write_message(&plaintext, &mut message)
295            .map_err(|error| channel_error(format!("could not encrypt a frame: {error}")))?;
296        message.truncate(length);
297        Ok(message)
298    }
299
300    /// Decrypt one frame. A frame that was changed, injected, replayed or
301    /// reordered fails, and the channel can't be used after that.
302    pub fn open(&mut self, message: &[u8]) -> Result<(FrameKind, Vec<u8>)> {
303        let mut plaintext = vec![0u8; message.len()];
304        let length = self
305            .transport
306            .read_message(message, &mut plaintext)
307            .map_err(|_| {
308                channel_error("a frame failed to decrypt: it was changed, injected or replayed")
309            })?;
310        plaintext.truncate(length);
311        let (kind, payload) = plaintext
312            .split_first()
313            .ok_or_else(|| channel_error("an empty frame"))?;
314        let kind = match kind {
315            0 => FrameKind::Data,
316            1 => FrameKind::Control,
317            _ => return Err(channel_error("an unknown frame kind")),
318        };
319        Ok((kind, payload.to_vec()))
320    }
321}
322
323/// Direction of a transcript entry.
324#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
325#[serde(rename_all = "camelCase")]
326pub enum Direction {
327    /// From the engineer to the enforcer.
328    In,
329    /// From the enforcer to the engineer.
330    Out,
331}
332
333/// One transcript entry. Each names the hash of the one before, so an entry
334/// that is removed or changed breaks the chain.
335#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
336#[serde(rename_all = "camelCase", deny_unknown_fields)]
337pub struct TranscriptEntry {
338    /// Session id.
339    pub session_id: String,
340    /// Position in the session, from 0. Entry 0 holds the statement.
341    pub index: u64,
342    /// `sha256:<hex>` of the previous entry, or the statement digest for entry 0.
343    pub previous: String,
344    /// When it was recorded.
345    pub at: DateTime<Utc>,
346    /// Direction, for frames.
347    #[serde(default, skip_serializing_if = "Option::is_none")]
348    pub direction: Option<Direction>,
349    /// Base64 of the frame, or of the statement JSON for entry 0.
350    pub data: String,
351}
352
353impl TranscriptEntry {
354    /// `sha256:<hex>` of this entry's JSON.
355    pub fn digest(&self) -> String {
356        let bytes = serde_json::to_vec(self).expect("an entry always serializes");
357        format!("sha256:{}", hex::encode(Sha256::digest(bytes)))
358    }
359}
360
361/// A hash-chained transcript of one session.
362pub struct Transcript {
363    session_id: String,
364    index: u64,
365    previous: String,
366}
367
368impl Transcript {
369    /// Start with the signed statement as entry 0.
370    pub fn start(
371        session_id: &str,
372        statement_digest: &str,
373        statement_json: &str,
374    ) -> (Self, TranscriptEntry) {
375        let entry = TranscriptEntry {
376            session_id: session_id.to_string(),
377            index: 0,
378            previous: statement_digest.to_string(),
379            at: Utc::now(),
380            direction: None,
381            data: STANDARD.encode(statement_json),
382        };
383        let transcript = Self {
384            session_id: session_id.to_string(),
385            index: 1,
386            previous: entry.digest(),
387        };
388        (transcript, entry)
389    }
390
391    /// Record one frame.
392    pub fn record(&mut self, direction: Direction, bytes: &[u8]) -> TranscriptEntry {
393        let entry = TranscriptEntry {
394            session_id: self.session_id.clone(),
395            index: self.index,
396            previous: self.previous.clone(),
397            at: Utc::now(),
398            direction: Some(direction),
399            data: STANDARD.encode(bytes),
400        };
401        self.index += 1;
402        self.previous = entry.digest();
403        entry
404    }
405}
406
407/// Check that `entries` form one unbroken chain from the statement.
408pub fn verify_transcript(statement_digest: &str, entries: &[TranscriptEntry]) -> Result<()> {
409    let mut previous = statement_digest.to_string();
410    for (index, entry) in entries.iter().enumerate() {
411        if entry.index != index as u64 || entry.previous != previous {
412            return Err(channel_error(format!(
413                "the transcript breaks at entry {index}"
414            )));
415        }
416        previous = entry.digest();
417    }
418    Ok(())
419}
420
421fn builder() -> Result<snow::Builder<'static>> {
422    let params: snow::params::NoiseParams = NOISE_PATTERN
423        .parse()
424        .map_err(|error| channel_error(format!("bad noise pattern: {error:?}")))?;
425    Ok(snow::Builder::new(params))
426}
427
428fn prologue(statement_digest: &str) -> Vec<u8> {
429    format!("session/v1 {statement_digest}").into_bytes()
430}
431
432fn channel_error(reason: impl Into<String>) -> AlienError<ErrorData> {
433    AlienError::new(ErrorData::BodyRefused {
434        kind: "session/v1".to_string(),
435        reason: reason.into(),
436    })
437}
438
439fn refused(kind: Kind, reason: impl Into<String>) -> AlienError<ErrorData> {
440    AlienError::new(ErrorData::BodyRefused {
441        kind: kind.as_str().to_string(),
442        reason: reason.into(),
443    })
444}
445
446#[cfg(test)]
447mod tests {
448    use super::*;
449
450    fn pair(digest_client: &str, digest_enforcer: &str) -> Result<(Channel, Channel)> {
451        let client_keys = SessionKeys::generate()?;
452        let enforcer_keys = SessionKeys::generate()?;
453        let mut client = Handshake::new(
454            Side::Client,
455            &client_keys,
456            &enforcer_keys.public_key(),
457            digest_client,
458        )?;
459        let mut enforcer = Handshake::new(
460            Side::Enforcer,
461            &enforcer_keys,
462            &client_keys.public_key(),
463            digest_enforcer,
464        )?;
465        enforcer.read(&client.write()?)?;
466        client.read(&enforcer.write()?)?;
467        Ok((client.finish()?, enforcer.finish()?))
468    }
469
470    #[test]
471    fn frames_cross_the_channel_and_nothing_else_does() {
472        let (mut client, mut enforcer) = pair("sha256:s", "sha256:s").unwrap();
473        let first = client.seal(FrameKind::Data, b"ls -la\n").unwrap();
474        let second = client.seal(FrameKind::Data, b"whoami\n").unwrap();
475        assert!(
476            !first.windows(6).any(|window| window == b"ls -la"),
477            "the relay sees ciphertext"
478        );
479
480        // A relay that drops the first frame or injects its own breaks the channel.
481        let mut skipped = pair("sha256:s", "sha256:s").unwrap();
482        let a = skipped.0.seal(FrameKind::Data, b"one").unwrap();
483        let b = skipped.0.seal(FrameKind::Data, b"two").unwrap();
484        skipped
485            .1
486            .open(&b)
487            .expect_err("a reordered or dropped frame fails");
488        drop(a);
489
490        assert_eq!(
491            enforcer.open(&first).unwrap(),
492            (FrameKind::Data, b"ls -la\n".to_vec())
493        );
494        enforcer.open(&first).expect_err("a replayed frame fails");
495
496        let (mut client2, mut enforcer2) = pair("sha256:s", "sha256:s").unwrap();
497        let mut forged = client2.seal(FrameKind::Data, b"exit\n").unwrap();
498        forged[3] ^= 0x01;
499        enforcer2.open(&forged).expect_err("a changed frame fails");
500        drop((second, client2));
501
502        let reply = enforcer
503            .seal(FrameKind::Control, br#"{"type":"exit","exitCode":0}"#)
504            .unwrap();
505        assert_eq!(client.open(&reply).unwrap().0, FrameKind::Control);
506    }
507
508    #[test]
509    fn the_handshake_is_bound_to_the_signed_statement() {
510        assert!(
511            pair("sha256:signed", "sha256:other").is_err(),
512            "a different statement can't complete the handshake"
513        );
514    }
515
516    #[test]
517    fn the_handshake_needs_the_keys_the_statement_names() {
518        let client_keys = SessionKeys::generate().unwrap();
519        let enforcer_keys = SessionKeys::generate().unwrap();
520        let relay_keys = SessionKeys::generate().unwrap();
521        // The relay substitutes its own key for the enforcer's.
522        let mut client = Handshake::new(
523            Side::Client,
524            &client_keys,
525            &relay_keys.public_key(),
526            "sha256:s",
527        )
528        .unwrap();
529        let mut enforcer = Handshake::new(
530            Side::Enforcer,
531            &enforcer_keys,
532            &client_keys.public_key(),
533            "sha256:s",
534        )
535        .unwrap();
536        assert!(enforcer.read(&client.write().unwrap()).is_err());
537    }
538
539    #[test]
540    fn a_transcript_with_a_removed_or_changed_entry_is_caught() {
541        let (mut transcript, first) = Transcript::start("ses_1", "sha256:statement", "{}");
542        let mut entries = vec![first];
543        entries.push(transcript.record(Direction::In, b"rm -rf /tmp/x\n"));
544        entries.push(transcript.record(Direction::Out, b"done\n"));
545        verify_transcript("sha256:statement", &entries).unwrap();
546
547        let mut removed = entries.clone();
548        removed.remove(1);
549        verify_transcript("sha256:statement", &removed).expect_err("a removed entry is caught");
550        let mut changed = entries.clone();
551        changed[1].data = STANDARD.encode(b"ls\n");
552        verify_transcript("sha256:statement", &changed).expect_err("a changed entry is caught");
553        verify_transcript("sha256:other", &entries).expect_err("another statement is caught");
554    }
555}