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
use std::fmt;
use crate::error::{Error, PeerMisbehaved};
use crate::msgs::enums::NamedGroup;
pub(crate) struct KeyExchange {
skxg: &'static SupportedKxGroup,
privkey: ring::agreement::EphemeralPrivateKey,
pub(crate) pubkey: ring::agreement::PublicKey,
}
impl KeyExchange {
pub(crate) fn choose(
name: NamedGroup,
supported: &[&'static SupportedKxGroup],
) -> Option<&'static SupportedKxGroup> {
supported
.iter()
.find(|skxg| skxg.name == name)
.cloned()
}
pub(crate) fn start(skxg: &'static SupportedKxGroup) -> Option<Self> {
let rng = ring::rand::SystemRandom::new();
let ours =
ring::agreement::EphemeralPrivateKey::generate(skxg.agreement_algorithm, &rng).ok()?;
let pubkey = ours.compute_public_key().ok()?;
Some(Self {
skxg,
privkey: ours,
pubkey,
})
}
pub(crate) fn group(&self) -> NamedGroup {
self.skxg.name
}
pub(crate) fn complete<T>(
self,
peer: &[u8],
f: impl FnOnce(&[u8]) -> Result<T, ()>,
) -> Result<T, Error> {
let peer_key = ring::agreement::UnparsedPublicKey::new(self.skxg.agreement_algorithm, peer);
ring::agreement::agree_ephemeral(self.privkey, &peer_key, (), f)
.map_err(|()| PeerMisbehaved::InvalidKeyShare.into())
}
}
pub struct SupportedKxGroup {
pub name: NamedGroup,
agreement_algorithm: &'static ring::agreement::Algorithm,
}
impl fmt::Debug for SupportedKxGroup {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.name.fmt(f)
}
}
pub static X25519: SupportedKxGroup = SupportedKxGroup {
name: NamedGroup::X25519,
agreement_algorithm: &ring::agreement::X25519,
};
pub static SECP256R1: SupportedKxGroup = SupportedKxGroup {
name: NamedGroup::secp256r1,
agreement_algorithm: &ring::agreement::ECDH_P256,
};
pub static SECP384R1: SupportedKxGroup = SupportedKxGroup {
name: NamedGroup::secp384r1,
agreement_algorithm: &ring::agreement::ECDH_P384,
};
pub static ALL_KX_GROUPS: [&SupportedKxGroup; 3] = [&X25519, &SECP256R1, &SECP384R1];