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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
use cryptovec::CryptoVec;
use negotiation::Named;
use Error;
use encoding::{Encoding, Reader, mpint_len};
use ring::{digest, rand, signature};
use std;
use untrusted;
use std::sync::Arc;
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub struct Name(&'static str);
impl AsRef<str> for Name {
fn as_ref(&self) -> &str {
self.0
}
}
pub const ED25519: Name = Name("ssh-ed25519");
pub const RSA_SHA2_512: Name = Name("rsa-sha2-512");
pub const RSA_SHA2_256: Name = Name("rsa-sha2-256");
const SSH_RSA: &'static str = "ssh-rsa";
impl Name {
pub fn identity_file(&self) -> &'static str {
match *self {
ED25519 => "id_ed25519",
RSA_SHA2_512 => "id_rsa",
RSA_SHA2_256 => "id_rsa",
_ => unreachable!(),
}
}
}
#[doc(hidden)]
pub trait Verify {
fn verify_client_auth(&self, buffer: &[u8], sig: &[u8]) -> bool;
fn verify_server_auth(&self, buffer: &[u8], sig: &[u8]) -> bool;
}
const ED25519_PUBLICKEY_BYTES: usize = 32;
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct RSAPublicKey {
e: Vec<u8>,
n: Vec<u8>,
hash: SignatureHash
}
#[derive(Eq, PartialEq, Clone, Copy, Debug)]
#[allow(non_camel_case_types)]
pub enum SignatureHash {
SHA2_256,
SHA2_512,
}
impl SignatureHash {
fn name(&self) -> Name {
match *self {
SignatureHash::SHA2_256 => RSA_SHA2_256,
SignatureHash::SHA2_512 => RSA_SHA2_512,
}
}
}
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum PublicKey {
#[doc(hidden)]
Ed25519([u8; ED25519_PUBLICKEY_BYTES]),
#[doc(hidden)]
RSA(RSAPublicKey)
}
#[doc(hidden)]
impl PublicKey {
pub fn parse(algo: &[u8], pubkey: &[u8]) -> Result<Self, Error> {
debug!("parse, algo: {:?}", std::str::from_utf8(algo));
match algo {
b"ssh-ed25519" => {
let mut p = pubkey.reader(0);
let key_algo = try!(p.read_string());
let key_bytes = try!(p.read_string());
if key_algo != b"ssh-ed25519" || key_bytes.len() != ED25519_PUBLICKEY_BYTES {
return Err(Error::Inconsistent);
}
let mut p = [0; ED25519_PUBLICKEY_BYTES];
p.clone_from_slice(key_bytes);
Ok(PublicKey::Ed25519(p))
}
b"rsa-sha2-256" | b"rsa-sha2-512" => {
let mut p = pubkey.reader(0);
let key_algo = try!(p.read_string());
let key_e = try!(p.read_string());
let key_n = try!(p.read_string());
debug!("key_algo = {:?}", key_algo);
Ok(PublicKey::RSA(RSAPublicKey {
e: key_e.to_vec(),
n: key_n.to_vec(),
hash: { if algo == b"rsa-sha2-256" {
SignatureHash::SHA2_256
} else {
SignatureHash::SHA2_512
}}
}))
}
_ => Err(Error::UnknownKey),
}
}
}
impl Verify for PublicKey {
fn verify_client_auth(&self, buffer: &[u8], sig: &[u8]) -> bool {
debug!("verify_detached: {:?}", self);
debug!("buffer: {:?}", &buffer[..]);
debug!("sig: {:?}", sig);
match self {
&PublicKey::Ed25519(ref public) => {
signature::verify(&signature::ED25519,
untrusted::Input::from(public),
untrusted::Input::from(buffer),
untrusted::Input::from(sig))
.is_ok()
}
&PublicKey::RSA(ref key) => {
debug!("verify RSA: {:?} {:?}", key.n, key.e);
signature::primitive::verify_rsa(
match key.hash {
SignatureHash::SHA2_256 => &signature::RSA_PKCS1_2048_8192_SHA256,
SignatureHash::SHA2_512 => &signature::RSA_PKCS1_2048_8192_SHA512,
},
(untrusted::Input::from(without_leading_zeros(&key.n)),
untrusted::Input::from(without_leading_zeros(&key.e))),
untrusted::Input::from(buffer),
untrusted::Input::from(sig))
.is_ok()
}
}
}
fn verify_server_auth(&self, buffer: &[u8], sig: &[u8]) -> bool {
debug!("verify_detached: {:?}", self);
debug!("buffer: {:?}", &buffer[..]);
debug!("sig: {:?}", sig);
match self {
&PublicKey::Ed25519(ref public) => {
signature::verify(&signature::ED25519,
untrusted::Input::from(public),
untrusted::Input::from(buffer),
untrusted::Input::from(sig))
.is_ok()
}
&PublicKey::RSA(ref key) => {
debug!("verify RSA: {:?} {:?}", key.n, key.e);
signature::primitive::verify_rsa(
match key.hash {
SignatureHash::SHA2_256 => &signature::RSA_PKCS1_2048_8192_SHA256,
SignatureHash::SHA2_512 => &signature::RSA_PKCS1_2048_8192_SHA512,
},
(untrusted::Input::from(without_leading_zeros(&key.n)),
untrusted::Input::from(without_leading_zeros(&key.e))),
untrusted::Input::from(buffer),
untrusted::Input::from(sig))
.is_ok()
}
}
}
}
fn without_leading_zeros(x: &[u8]) -> &[u8] {
let mut i = 0;
while i < x.len() && x[i] == 0 {
i += 1
}
&x[i..]
}
pub enum Algorithm {
#[doc(hidden)]
Ed25519(signature::Ed25519KeyPair),
#[doc(hidden)]
RSA(Arc<signature::RSAKeyPair>, RSAPublicKey),
}
impl std::fmt::Debug for Algorithm {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match *self {
Algorithm::Ed25519(ref key_pair) => {
write!(f,
"Ed25519 {{ public: {:?}, secret: (hidden) }}",
key_pair.public_key_bytes())
}
Algorithm::RSA(_, ref public) => {
write!(f, "RSA {{ public: {:?}, secret: (hidden) }}", public)
}
}
}
}
#[doc(hidden)]
pub trait PubKey {
fn push_to(&self, buffer: &mut CryptoVec);
}
impl PubKey for PublicKey {
fn push_to(&self, buffer: &mut CryptoVec) {
match self {
&PublicKey::Ed25519(ref public) => {
buffer.push_u32_be((ED25519.0.len() + public.len() + 8) as u32);
buffer.extend_ssh_string(ED25519.0.as_bytes());
buffer.extend_ssh_string(public);
}
&PublicKey::RSA(ref key) => {
buffer.push_u32_be((4 + SSH_RSA.len() + mpint_len(&key.n) + mpint_len(&key.e)) as u32);
buffer.extend_ssh_string(SSH_RSA.as_bytes());
buffer.extend_ssh_mpint(&key.e);
buffer.extend_ssh_mpint(&key.n);
}
}
}
}
impl PubKey for Algorithm {
fn push_to(&self, buffer: &mut CryptoVec) {
match self {
&Algorithm::Ed25519(ref key_pair) => {
let public = key_pair.public_key_bytes();
buffer.push_u32_be((ED25519.0.len() + public.len() + 8) as u32);
buffer.extend_ssh_string(ED25519.0.as_bytes());
buffer.extend_ssh_string(public);
}
&Algorithm::RSA(_, ref key) => {
buffer.push_u32_be((4 + SSH_RSA.len() + mpint_len(&key.n) + mpint_len(&key.e)) as u32);
buffer.extend_ssh_string(SSH_RSA.as_bytes());
let len0 = buffer.len();
buffer.extend_ssh_mpint(&key.e);
let len1 = buffer.len();
buffer.extend_ssh_mpint(&key.n);
debug!("e: {:?} {:?}", key.e.len(), &buffer[len0..len1]);
debug!("n: {:?} {:?}", key.n.len(), &buffer[len1..]);
}
}
}
}
impl Named for PublicKey {
fn name(&self) -> &'static str {
match self {
&PublicKey::Ed25519(_) => ED25519.0,
&PublicKey::RSA(_) => SSH_RSA,
}
}
}
impl Named for Algorithm {
fn name(&self) -> &'static str {
match self {
&Algorithm::Ed25519(..) => ED25519.0,
&Algorithm::RSA(_, ref public) => public.hash.name().0,
}
}
}
impl Algorithm {
pub fn clone_public_key(&self) -> PublicKey {
match self {
&Algorithm::Ed25519(ref key_pair) => {
let mut p = [0; ED25519_PUBLICKEY_BYTES];
p.clone_from_slice(key_pair.public_key_bytes());
PublicKey::Ed25519(p)
}
&Algorithm::RSA(_, ref public) => {
PublicKey::RSA(public.clone())
}
}
}
pub fn generate_keypair(t: Name, rng: &rand::SecureRandom) -> Option<Self> {
match t {
ED25519 => {
signature::Ed25519KeyPair::generate_pkcs8(rng)
.map(|key_pair| Algorithm::Ed25519(
signature::Ed25519KeyPair::from_pkcs8(untrusted::Input::from(&key_pair)).unwrap()
))
.ok()
}
_ => None,
}
}
#[doc(hidden)]
pub fn add_signature(&self, buffer: &mut CryptoVec, hash: &digest::Digest) -> Result<(), Error> {
match self {
&Algorithm::Ed25519(ref key_pair) => {
let signature = key_pair.sign(hash.as_ref());
let signature = signature.as_ref();
buffer.push_u32_be((ED25519.0.len() + signature.len() + 8) as u32);
buffer.extend_ssh_string(ED25519.0.as_bytes());
buffer.extend_ssh_string(signature);
}
&Algorithm::RSA(ref key_pair, ref public) => {
let mut state = signature::RSASigningState::new(key_pair.clone()).unwrap();
let signature_len = key_pair.public_modulus_len();
let rng = rand::SystemRandom::new();
match public.hash {
SignatureHash::SHA2_256 => {
buffer.push_u32_be((RSA_SHA2_256.0.len() + signature_len + 8) as u32);
buffer.extend_ssh_string(RSA_SHA2_256.0.as_bytes());
{
let signature = buffer.extend_ssh_string_blank(signature_len);
state.sign(&signature::RSA_PKCS1_SHA256, &rng, hash.as_ref(), signature)?;
}
let l = buffer.len();
debug!("signed: {:?}", &buffer[l - signature_len .. ]);
}
SignatureHash::SHA2_512 => {
buffer.push_u32_be((RSA_SHA2_512.0.len() + signature_len + 8) as u32);
buffer.extend_ssh_string(RSA_SHA2_512.0.as_bytes());
{
let signature = buffer.extend_ssh_string_blank(signature_len);
state.sign(&signature::RSA_PKCS1_SHA512, &rng, hash.as_ref(), signature)?;
}
let l = buffer.len();
debug!("signed: {:?}", &buffer[l - signature_len .. ]);
}
}
}
}
Ok(())
}
#[doc(hidden)]
pub fn add_self_signature(&self, buffer: &mut CryptoVec) -> Result<(), Error> {
match self {
&Algorithm::Ed25519(ref key_pair) => {
let signature = key_pair.sign(&buffer);
let signature = signature.as_ref();
buffer.push_u32_be((ED25519.0.len() + signature.len() + 8) as u32);
buffer.extend_ssh_string(ED25519.0.as_bytes());
buffer.extend_ssh_string(signature);
}
&Algorithm::RSA(ref key_pair, ref public) => {
let mut state = signature::RSASigningState::new(key_pair.clone()).unwrap();
let signature_len = key_pair.public_modulus_len();
let cur_len = buffer.len();
let rng = rand::SystemRandom::new();
let name = public.hash.name();
buffer.push_u32_be((name.0.len() + signature_len + 8) as u32);
buffer.extend_ssh_string(name.0.as_bytes());
buffer.push_u32_be(signature_len as u32);
let first_sig = buffer.len();
buffer.resize(first_sig + signature_len);
let (buf, sig) = buffer.split_at_mut(first_sig);
let buf = &buf[ .. cur_len];
match public.hash {
SignatureHash::SHA2_256 => state.sign(
&signature::RSA_PKCS1_SHA256, &rng, buf, sig
)?,
SignatureHash::SHA2_512 => state.sign(
&signature::RSA_PKCS1_SHA512, &rng, buf, sig
)?,
}
}
}
Ok(())
}
}
pub fn parse_public_key(p: &[u8]) -> Result<PublicKey, Error> {
debug!("parse_public_key {:?}", p);
let mut pos = p.reader(0);
let t = try!(pos.read_string());
if t == b"ssh-ed25519" {
if let Ok(pubkey) = pos.read_string() {
let mut p = [0; ED25519_PUBLICKEY_BYTES];
p.clone_from_slice(pubkey);
return Ok(PublicKey::Ed25519(p));
}
}
if t == b"ssh-rsa" {
let e = pos.read_string()?;
let n = pos.read_string()?;
return Ok(PublicKey::RSA(RSAPublicKey {
e: e.to_vec(),
n: n.to_vec(),
hash: SignatureHash::SHA2_256,
}))
}
Err(Error::CouldNotReadKey)
}