1use crate::ckdf::{temp_keys, temp_prk, DerivedKeys};
8use crate::Error;
9use x25519_dalek::{PublicKey, StaticSecret};
10
11pub const KEX_SCHEME_1: u8 = 0x02;
13pub const ECDH_CURVE25519: u8 = 0x01;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18#[repr(u8)]
19pub enum KexFail {
20 Key = 0x01,
22 Scheme = 0x02,
24 Curves = 0x03,
26 Decrypt = 0x05,
28 Cancel = 0x06,
30 Auth = 0x07,
32 KeyGet = 0x08,
34 KeyVerify = 0x09,
36 KeyReport = 0x0a,
38}
39
40impl KexFail {
41 pub fn from_u8(v: u8) -> Option<Self> {
43 Some(match v {
44 0x01 => KexFail::Key,
45 0x02 => KexFail::Scheme,
46 0x03 => KexFail::Curves,
47 0x05 => KexFail::Decrypt,
48 0x06 => KexFail::Cancel,
49 0x07 => KexFail::Auth,
50 0x08 => KexFail::KeyGet,
51 0x09 => KexFail::KeyVerify,
52 0x0a => KexFail::KeyReport,
53 _ => return None,
54 })
55 }
56}
57
58#[derive(Clone)]
60pub struct KeyPair {
61 secret: StaticSecret,
62 public: [u8; 32],
63}
64
65impl std::fmt::Debug for KeyPair {
66 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67 write!(f, "KeyPair {{ public: {:02x?} }}", &self.public[..4])
68 }
69}
70
71impl KeyPair {
72 pub fn generate() -> Result<Self, Error> {
74 Ok(Self::from_private(crate::random_bytes::<32>()?))
75 }
76
77 pub fn from_private(private: [u8; 32]) -> Self {
79 let secret = StaticSecret::from(private);
80 let public = PublicKey::from(&secret).to_bytes();
81 KeyPair { secret, public }
82 }
83
84 pub fn private_bytes(&self) -> [u8; 32] {
86 self.secret.to_bytes()
87 }
88
89 pub fn public(&self) -> &[u8; 32] {
91 &self.public
92 }
93
94 pub fn shared_secret(&self, peer_public: &[u8; 32]) -> Result<[u8; 32], Error> {
97 let shared = self.secret.diffie_hellman(&PublicKey::from(*peer_public));
98 if !shared.was_contributory() {
99 return Err(Error::Invalid("public key"));
100 }
101 Ok(shared.to_bytes())
102 }
103}
104
105pub fn bootstrap_keys(
110 shared_secret: &[u8; 32],
111 controller_public: &[u8; 32],
112 node_public: &[u8; 32],
113) -> DerivedKeys {
114 temp_keys(&temp_prk(shared_secret, controller_public, node_public))
115}
116
117#[cfg(test)]
118mod tests {
119 use super::*;
120
121 #[test]
123 fn x25519_rfc7748() {
124 let h = |s: &str| -> [u8; 32] { hex::decode(s).unwrap().try_into().unwrap() };
125 let alice = KeyPair::from_private(h(
126 "77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a",
127 ));
128 let bob = KeyPair::from_private(h(
129 "5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb",
130 ));
131 assert_eq!(
132 alice.public(),
133 &h("8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a")
134 );
135 assert_eq!(
136 bob.public(),
137 &h("de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f")
138 );
139 let k = h("4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742");
140 assert_eq!(alice.shared_secret(bob.public()).unwrap(), k);
141 assert_eq!(bob.shared_secret(alice.public()).unwrap(), k);
142 }
143
144 #[test]
145 fn low_order_point_refused() {
146 let a = KeyPair::generate().unwrap();
147 assert!(a.shared_secret(&[0u8; 32]).is_err());
148 }
149
150 #[test]
151 fn both_ends_derive_the_same_temp_keys() {
152 let ctrl = KeyPair::generate().unwrap();
153 let node = KeyPair::generate().unwrap();
154 let a = bootstrap_keys(
155 &ctrl.shared_secret(node.public()).unwrap(),
156 ctrl.public(),
157 node.public(),
158 );
159 let b = bootstrap_keys(
160 &node.shared_secret(ctrl.public()).unwrap(),
161 ctrl.public(),
162 node.public(),
163 );
164 assert_eq!(a, b);
165 }
166}