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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
extern crate thrussh;
extern crate ring;
extern crate crypto;
#[macro_use]
extern crate log;
extern crate base64;
extern crate untrusted;
extern crate byteorder;
#[macro_use]
extern crate error_chain;
// extern crate tokio_uds;
// extern crate tokio_core;
// extern crate tokio_io;
// extern crate futures;
// extern crate cryptovec;

use base64::{decode_config, encode_config, MIME};
use thrussh::{key, parse_public_key, Named};
use std::path::Path;
use std::borrow::Cow;

use std::fs::{File, OpenOptions};
use std::io::{BufReader, BufRead, Read, Write, Seek, SeekFrom};
use thrussh::encoding::Reader;
use ring::signature;
use byteorder::{BigEndian, WriteBytesExt};


error_chain!{
    foreign_links {
        IO(std::io::Error);
        Utf8(std::str::Utf8Error);
        Ring(ring::error::Unspecified);
        Thrussh(thrussh::Error);
        Base64(base64::DecodeError);
    }
    errors {
        RustCrypto{}
        CouldNotReadKey {}
        KeyIsEncrypted {}
        NoHomeDir {}
        KeyChanged(changed: usize) {
        }
    }
}

const KEYTYPE_ED25519: &'static [u8] = b"ssh-ed25519";
const KEYTYPE_RSA: &'static [u8] = b"ssh-rsa";

/// Load a public key from a file. Ed25519 and RSA keys are supported.
///
/// ```
/// thrussh_keys::load_public_key("/home/pe/.ssh/id_ed25519.pub").unwrap();
/// ```
pub fn load_public_key<P:AsRef<Path>>(path: P) -> Result<key::PublicKey> {
    let mut pubkey = String::new();
    let mut file = try!(File::open(path.as_ref()));
    try!(file.read_to_string(&mut pubkey));

    debug!("decode_public_key: {:?}", pubkey);
    let mut split = pubkey.split_whitespace();
    match (split.next(), split.next()) {
        (Some(_), Some(key)) => parse_public_key_base64(key),
        (Some(key), None) => parse_public_key_base64(key),
        _ => Err(ErrorKind::CouldNotReadKey.into()),
    }
}

/// Reads a public key from the standard encoding. In some cases, the
/// encoding is prefixed with a key type identifier and a space (such
/// as `ssh-ed25519 AAAAC3N...`).
///
/// ```
/// thrussh_keys::parse_public_key_base64("AAAAC3NzaC1lZDI1NTE5AAAAIJdD7y3aLq454yWBdwLWbieU1ebz9/cu7/QEXn9OIeZJ").is_ok();
/// ```
pub fn parse_public_key_base64(key: &str) -> Result<key::PublicKey> {
    let base = decode_config(key, MIME)?;
    debug!("parse_public_key_base64: {:?}", base);
    Ok(parse_public_key(&base)?)
}


/// Write a public key onto the provided `Write`, encoded in base-64.
pub fn write_public_key_base64<W:Write>(mut w:W, publickey:&key::PublicKey) -> Result<()> {
    try!(w.write_all(publickey.name().as_bytes()));
    try!(w.write_all(b" "));
    let mut s = Vec::new();
    let name = publickey.name().as_bytes();
    s.write_u32::<BigEndian>(name.len() as u32).unwrap();
    s.extend(name);
    match *publickey {
        key::PublicKey::Ed25519(ref publickey) => {
            s.write_u32::<BigEndian>(publickey.len() as u32).unwrap();
            s.extend(publickey);
        }
        _ => unimplemented!()
    }
    w.write_all(encode_config(&s, MIME).as_bytes())?;
    Ok(())
}

enum Format {
    Rsa,
    Openssh
}

pub fn load_secret_key<P:AsRef<Path>>(secret_: P, password: Option<&[u8]>, public: Option<&Path>) -> Result<key::Algorithm> {
    let mut secret_file = std::fs::File::open(secret_)?;
    let mut secret = String::new();
    secret_file.read_to_string(&mut secret)?;

    let mut public_buf = String::new();
    let public = if let Some(public) = public {
        let mut public_file = std::fs::File::open(public)?;
        public_file.read_to_string(&mut public_buf)?;
        Some(public_buf.as_str())
    } else {
        None
    };

    decode_secret_key(&secret, password, public)
}

#[test]
fn test_decode_secret_key() {
    extern crate env_logger;
    env_logger::init().unwrap_or(());
    let secret = "-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jYmMAAAAGYmNyeXB0AAAAGAAAABDLGyfA39
J2FcJygtYqi5ISAAAAEAAAAAEAAAAzAAAAC3NzaC1lZDI1NTE5AAAAIN+Wjn4+4Fcvl2Jl
KpggT+wCRxpSvtqqpVrQrKN1/A22AAAAkOHDLnYZvYS6H9Q3S3Nk4ri3R2jAZlQlBbUos5
FkHpYgNw65KCWCTXtP7ye2czMC3zjn2r98pJLobsLYQgRiHIv/CUdAdsqbvMPECB+wl/UQ
e+JpiSq66Z6GIt0801skPh20jxOO3F52SoX1IeO5D5PXfZrfSZlw6S8c7bwyp2FHxDewRx
7/wNsnDM0T7nLv/Q==
-----END OPENSSH PRIVATE KEY-----
";
    decode_secret_key(secret, Some(b"blabla"), None).unwrap();
}

fn decode_secret_key(secret: &str, password: Option<&[u8]>, public: Option<&str>) -> Result<key::Algorithm> {

    let mut format = None;
    let secret = {
        let mut start = 0;
        let mut end = 0;
        let mut started = false;
        for l in secret.lines() {
            debug!("l = {:?}", l);
            if started == true && start == 0 {
                start = l.as_ptr() as usize - secret.as_ptr() as usize
            }
            if l == "-----BEGIN OPENSSH PRIVATE KEY-----" {
                started = true;
                format = Some(Format::Openssh);
            } else if l == "-----BEGIN RSA PRIVATE KEY-----" {
                started = true;
                format = Some(Format::Rsa);
            } else if l == "-----END OPENSSH PRIVATE KEY-----" || l == "-----END RSA PRIVATE KEY-----" {
                end = l.as_ptr() as usize - secret.as_ptr() as usize;
                break;
            }
        }
        secret.split_at(end).0.split_at(start).1
    };

    debug!("secret = {:?}", secret);
    let secret = decode_config(&secret, MIME)?;
    match format {
        Some(Format::Openssh) => {
            debug!("secret: {:?}", secret);
            if &secret[0..15] == b"openssh-key-v1\0" {
                let mut position = secret.reader(15);

                let ciphername = try!(position.read_string());
                let kdfname = try!(position.read_string());
                let kdfoptions = try!(position.read_string());
                info!("ciphername: {:?}", std::str::from_utf8(ciphername));
                debug!("kdf: {:?} {:?}",
                       std::str::from_utf8(kdfname),
                       kdfoptions);

                let nkeys = try!(position.read_u32());

                for _ in 0..nkeys {
                    let public_string = try!(position.read_string());
                    let mut pos = public_string.reader(0);
                    let t = try!(pos.read_string());
                    let pubkey = pos.read_string()?;
                    if t == KEYTYPE_ED25519 {
                        info!("public: ED25519:{:?}", pubkey);
                    } else if t == KEYTYPE_RSA {
                        info!("public: RSA:{:?}", pubkey);
                    } else {
                        info!("warning: no public key");
                    }
                }
                info!("there are {} keys in this file", nkeys);
                let secret_ = try!(position.read_string());
                let mut secret = secret_.to_vec();
                decrypt_secret_key(
                    ciphername, kdfname, kdfoptions, password, secret_, &mut secret
                )?;
                let mut position = secret.reader(0);
                let check0 = try!(position.read_u32());
                let check1 = try!(position.read_u32());
                debug!("check0: {:?}", check0);
                debug!("check1: {:?}", check1);
                for _ in 0..nkeys {

                    let key_type = try!(position.read_string());
                    let pubkey = try!(position.read_string());
                    debug!("pubkey = {:?}", pubkey);
                    let seckey = try!(position.read_string());
                    let comment = try!(position.read_string());
                    debug!("comment = {:?}", comment);

                    if key_type == KEYTYPE_ED25519 {
                        let (a,b) = seckey.split_at(32);
                        assert_eq!(pubkey, b);
                        let keypair = try!(signature::Ed25519KeyPair::from_seed_and_public_key(untrusted::Input::from(a), untrusted::Input::from(pubkey)));
                        let keypair = key::Algorithm::Ed25519(keypair);
                        return Ok(keypair)
                    } else {
                        info!("unsupported key type {:?}", std::str::from_utf8(key_type));
                    }
                }
                Err(ErrorKind::CouldNotReadKey.into())

            } else {
                Err(ErrorKind::CouldNotReadKey.into())
            }
        }
        Some(Format::Rsa) => {
            debug!("secret: {:?}", secret);
            let keypair = signature::RSAKeyPair::from_der(untrusted::Input::from(&secret))?;
            if let Some(public) = public {
                let mut split = public.split_whitespace();
                if let (Some("ssh-rsa"), Some(public)) = (split.next(), split.next()) {
                    if let key::PublicKey::RSA(public) = parse_public_key_base64(public)? {
                        return Ok(key::Algorithm::RSA(
                            std::sync::Arc::new(keypair),
                            public,
                        ))
                    }
                }
            }
            Err(ErrorKind::CouldNotReadKey.into())
        }
        None => Err(ErrorKind::CouldNotReadKey.into())
    }
}

fn decrypt_secret_key(
    ciphername: &[u8],
    kdfname: &[u8], kdfoptions: &[u8], password: Option<&[u8]>,
    secret_key: &[u8], output: &mut [u8]
) -> Result<()> {

    if kdfname == b"none" {
        if password.is_none() {
            debug!("key: {:?}", secret_key);
            output.clone_from_slice(secret_key);
            Ok(())
        } else {
            Err(ErrorKind::CouldNotReadKey.into())
        }
    } else if let Some(password) = password {

        let mut key =
            match ciphername {
                b"aes256-cbc" => vec![0; 16 + 32],
                _ => return Err(ErrorKind::CouldNotReadKey.into())
            };

        match kdfname {
            b"bcrypt" => {
                let mut kdfopts = kdfoptions.reader(0);
                let salt = kdfopts.read_string()?;
                let rounds = kdfopts.read_u32()?;
                debug!("salt = {:?}, rounds = {:?}", salt, rounds);
                crypto::bcrypt_pbkdf::bcrypt_pbkdf(password, salt, rounds, &mut key);
            },
            _ => return Err(ErrorKind::CouldNotReadKey.into())
        };
        debug!("key = {:?}", key);
        let (key, iv) = key.split_at(32);
        let mut refread = crypto::buffer::RefReadBuffer::new(secret_key);
        let mut refwrite = crypto::buffer::RefWriteBuffer::new(output);
        crypto::aes::cbc_decryptor(
            crypto::aes::KeySize::KeySize256,
            key, iv, crypto::blockmodes::NoPadding
        )
            .decrypt(&mut refread, &mut refwrite, true)
            .map_err(|_| ErrorKind::RustCrypto)?;

        Ok(())
    } else {
        Err(ErrorKind::KeyIsEncrypted.into())
    }
}



/// Record a host's public key into a nonstandard location.
pub fn learn_known_hosts_path<P:AsRef<Path>>(host:&str, port:u16, pubkey:&key::PublicKey, path:P) -> Result<()> {


    let mut file = try!(OpenOptions::new()
                        .read(true)
                        .append(true)
                        .create(true)
                        .open(path));

    // Test whether the known_hosts file ends with a \n
    let mut buf = [0;1];
    try!(file.seek(SeekFrom::End(-1)));
    try!(file.read_exact(&mut buf));
    let ends_in_newline = buf[0] == b'\n';

    // Write the key.
    try!(file.seek(SeekFrom::Start(0)));
    let mut file = std::io::BufWriter::new(file);
    if !ends_in_newline {
        try!(write!(file, "\n"));
    }
    if port != 22 {
        try!(write!(file, "[{}]:{} ", host, port))
    } else {
        try!(write!(file, "{} ", host))
    }
    try!(write_public_key_base64(&mut file, pubkey));
    try!(write!(file, "\n"));
    Ok(())
}

/// Check that a server key matches the one recorded in file `path`.
pub fn check_known_hosts_path<P: AsRef<Path>>(host: &str,
                                              port: u16,
                                              pubkey: &key::PublicKey,
                                              path: P)
                                              -> Result<bool> {
    let mut f = BufReader::new(try!(File::open(path)));
    let mut buffer = String::new();

    let host_port = if port == 22 {
        Cow::Borrowed(host)
    } else {
        Cow::Owned(format!("[{}]:{}", host, port))
    };
    let mut line = 1;
    while f.read_line(&mut buffer).unwrap() > 0 {
        debug!("check_known_hosts_path: {:?}", buffer);
        {
            if buffer.as_bytes()[0] == b'#' {
                buffer.clear();
                continue;
            }
            let mut s = buffer.split(' ');
            let hosts = s.next();
            let _ = s.next();
            let key = s.next();
            debug!("{:?} {:?}", hosts, key);
            match (hosts, key) {
                (Some(h), Some(k)) => {
                    let host_matches = h.split(',').any(|x| x == host_port);
                    debug!("host matches: {:?}", host_matches);
                    // debug!("{:?} {:?}", parse_public_key_base64(k), pubkey);
                    if host_matches {
                        if &try!(parse_public_key_base64(k)) == pubkey {
                            return Ok(true);
                        } else {
                            return Err(ErrorKind::KeyChanged(line).into());
                        }
                    }

                }
                _ => {}
            }
        }
        buffer.clear();
        line += 1;
    }
    Ok(false)
}


/// Record a host's public key into the user's known_hosts file.
#[cfg(target_os = "windows")]
pub fn learn_known_hosts(host: &str, port: u16, pubkey: &key::PublicKey) -> Result<()> {
    if let Some(mut known_host_file) = std::env::home_dir() {
        known_host_file.push("ssh");
        known_host_file.push("known_hosts");
        learn_known_hosts_path(host, port, pubkey, &known_host_file)
    } else {
        Err(ErrorKind::NoHomeDir.into())
    }
}

/// Record a host's public key into the user's known_hosts file.
#[cfg(not(target_os = "windows"))]
pub fn learn_known_hosts(host: &str, port: u16, pubkey: &key::PublicKey) -> Result<()> {
    if let Some(mut known_host_file) = std::env::home_dir() {
        known_host_file.push(".ssh");
        known_host_file.push("known_hosts");
        learn_known_hosts_path(host, port, pubkey, &known_host_file)
    } else {
        Err(ErrorKind::NoHomeDir.into())
    }
}

/// Check whether the host is known, from its standard location.
#[cfg(target_os = "windows")]
pub fn check_known_hosts(host: &str, port: u16, pubkey: &key::PublicKey) -> Result<bool> {
    if let Some(mut known_host_file) = std::env::home_dir() {
        known_host_file.push("ssh");
        known_host_file.push("known_hosts");
        check_known_hosts_path(host, port, pubkey, &known_host_file)
    } else {
        Err(ErrorKind::NoHomeDir.into())
    }
}

/// Check whether the host is known, from its standard location.
#[cfg(not(target_os = "windows"))]
pub fn check_known_hosts(host: &str, port: u16, pubkey: &key::PublicKey) -> Result<bool> {
    if let Some(mut known_host_file) = std::env::home_dir() {
        known_host_file.push(".ssh");
        known_host_file.push("known_hosts");
        debug!("known_hosts file = {:?}", known_host_file);
        check_known_hosts_path(host, port, pubkey, &known_host_file)
    } else {
        Err(ErrorKind::NoHomeDir.into())
    }
}


#[cfg(test)]
mod test {
    extern crate tempdir;
    extern crate env_logger;
    use std::fs::File;
    use std::io::Write;
    use super::*;

    #[test]
    fn test_check_known_hosts() {
        env_logger::init().unwrap_or(());
        let dir = tempdir::TempDir::new("thrussh").unwrap();
        let path = dir.path().join("known_hosts");
        {
            let mut f = File::create(&path).unwrap();
            f.write(b"[localhost]:13265 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIJdD7y3aLq454yWBdwLWbieU1ebz9/cu7/QEXn9OIeZJ\n#pijul.org,37.120.161.53 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIA6rWI3G2sz07DnfFlrouTcysQlj2P+jpNSOEWD9OJ3X\npijul.org,37.120.161.53 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIA6rWI3G1sz07DnfFlrouTcysQlj2P+jpNSOEWD9OJ3X\n").unwrap();
        }

        // Valid key, non-standard port.
        let host = "localhost";
        let port = 13265;
        let hostkey = parse_public_key_base64("AAAAC3NzaC1lZDI1NTE5AAAAIJdD7y3aLq454yWBdwLWbieU1ebz9/cu7/QEXn9OIeZJ")
            .unwrap();
        assert!(check_known_hosts_path(host, port, &hostkey, &path).unwrap());

        // Valid key, several hosts, port 22
        let host = "pijul.org";
        let port = 22;
        let hostkey = parse_public_key_base64("AAAAC3NzaC1lZDI1NTE5AAAAIA6rWI3G1sz07DnfFlrouTcysQlj2P+jpNSOEWD9OJ3X")
            .unwrap();
        assert!(check_known_hosts_path(host, port, &hostkey, &path).unwrap());

        // Now with the key in a comment above, check that it's not recognized
        let host = "pijul.org";
        let port = 22;
        let hostkey = parse_public_key_base64("AAAAC3NzaC1lZDI1NTE5AAAAIA6rWI3G2sz07DnfFlrouTcysQlj2P+jpNSOEWD9OJ3X")
            .unwrap();
        assert!(check_known_hosts_path(host, port, &hostkey, &path).is_err());
    }

    #[test]
    fn test_nikao() {
        env_logger::init().unwrap_or(());
        let key = "-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEAw/FG8YLVoXhsUVZcWaY7iZekMxQ2TAfSVh0LTnRuzsumeLhb
0fh4scIt4C4MLwpGe/u3vj290C28jLkOtysqnIpB4iBUrFNRmEz2YuvjOzkFE8Ju
0l1VrTZ9APhpLZvzT2N7YmTXcLz1yWopCe4KqTHczEP4lfkothxEoACXMaxezt5o
wIYfagDaaH6jXJgJk1SQ5VYrROVpDjjX8/Zg01H1faFQUikYx0M8EwL1fY5B80Hd
6DYSok8kUZGfkZT8HQ54DBgocjSs449CVqkVoQC1aDB+LZpMWovY15q7hFgfQmYD
qulbZRWDxxogS6ui/zUR2IpX7wpQMKKkBS1qdQIDAQABAoIBAQCodpcCKfS2gSzP
uapowY1KvP/FkskkEU18EDiaWWyzi1AzVn5LRo+udT6wEacUAoebLU5K2BaMF+aW
Lr1CKnDWaeA/JIDoMDJk+TaU0i5pyppc5LwXTXvOEpzi6rCzL/O++88nR4AbQ7sm
Uom6KdksotwtGvttJe0ktaUi058qaoFZbels5Fwk5bM5GHDdV6De8uQjSfYV813P
tM/6A5rRVBjC5uY0ocBHxPXkqAdHfJuVk0uApjLrbm6k0M2dg1X5oyhDOf7ZIzAg
QGPgvtsVZkQlyrD1OoCMPwzgULPXTe8SktaP9EGvKdMf5kQOqUstqfyx+E4OZa0A
T82weLjBAoGBAOUChhaLQShL3Vsml/Nuhhw5LsxU7Li34QWM6P5AH0HMtsSncH8X
ULYcUKGbCmmMkVb7GtsrHa4ozy0fjq0Iq9cgufolytlvC0t1vKRsOY6poC2MQgaZ
bqRa05IKwhZdHTr9SUwB/ngtVNWRzzbFKLkn2W5oCpQGStAKqz3LbKstAoGBANsJ
EyrXPbWbG+QWzerCIi6shQl+vzOd3cxqWyWJVaZglCXtlyySV2eKWRW7TcVvaXQr
Nzm/99GNnux3pUCY6szy+9eevjFLLHbd+knzCZWKTZiWZWr503h/ztfFwrMzhoAh
z4nukD/OETugPvtG01c2sxZb/F8LH9KORznhlSlpAoGBAJnqg1J9j3JU4tZTbwcG
fo5ThHeCkINp2owPc70GPbvMqf4sBzjz46QyDaM//9SGzFwocplhNhaKiQvrzMnR
LSVucnCEm/xdXLr/y6S6tEiFCwnx3aJv1uQRw2bBYkcDmBTAjVXPdUcyOHU+BYXr
Jv6ioMlKlel8/SUsNoFWypeVAoGAXhr3Bjf1xlm+0O9PRyZjQ0RR4DN5eHbB/XpQ
cL8hclsaK3V5tuek79JL1f9kOYhVeVi74G7uzTSYbCY3dJp+ftGCjDAirNEMaIGU
cEMgAgSqs/0h06VESwg2WRQZQ57GkbR1E2DQzuj9FG4TwSe700OoC9o3gqon4PHJ
/j9CM8kCgYEAtPJf3xaeqtbiVVzpPAGcuPyajTzU0QHPrXEl8zr/+iSK4Thc1K+c
b9sblB+ssEUQD5IQkhTWcsXdslINQeL77WhIMZ2vBAH8Hcin4jgcLmwUZfpfnnFs
QaChXiDsryJZwsRnruvMRX9nedtqHrgnIsJLTXjppIhGhq5Kg4RQfOU=
-----END RSA PRIVATE KEY-----
";
        let public = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDD8UbxgtWheGxRVlxZpjuJl6QzFDZMB9JWHQtOdG7Oy6Z4uFvR+Hixwi3gLgwvCkZ7+7e+Pb3QLbyMuQ63KyqcikHiIFSsU1GYTPZi6+M7OQUTwm7SXVWtNn0A+Gktm/NPY3tiZNdwvPXJaikJ7gqpMdzMQ/iV+Si2HESgAJcxrF7O3mjAhh9qANpofqNcmAmTVJDlVitE5WkOONfz9mDTUfV9oVBSKRjHQzwTAvV9jkHzQd3oNhKiTyRRkZ+RlPwdDngMGChyNKzjj0JWqRWhALVoMH4tmkxai9jXmruEWB9CZgOq6VtlFYPHGiBLq6L/NRHYilfvClAwoqQFLWp1 nschaban@Vicuna-2.local";
        decode_secret_key(key, None, Some(public)).unwrap();
    }
    /*
    #[test]
    fn test_agent() {
        env_logger::init().unwrap_or(());
        use std::process::Command;
        let dir = tempdir::TempDir::new("thrussh").unwrap();
        let agent_path = dir.path().join("agent");

        let mut agent = Command::new("ssh-agent")
            .arg("-a")
            .arg(&agent_path)
            .arg("-D")
            .spawn()
            .expect("failed to execute process");

        std::thread::sleep(std::time::Duration::from_millis(10));
        let core = tokio_core::reactor::Core::new().unwrap();
        let client = AgentClient::connect(&agent_path, &core.handle()).unwrap();

        agent.kill().unwrap();
    }
     */
}

/*
use tokio_uds::*;
use tokio_core::reactor::Handle;
use tokio_io::io::WriteAll;
use cryptovec::CryptoVec;

pub struct AgentClient {
    stream: UnixStream,
    buf: CryptoVec
}

pub struct AddKey {
    state: Option<AddKeyState>
}

enum AddKeyState {
    Write(WriteAll<UnixStream, CryptoVec>)
}

mod msg {
    const ADD_IDENTITY:u8 = 0;
    const ADD_ID_CONSTRAINED:u8 = 0;
}

use thrussh::key::Algorithm;

// https://tools.ietf.org/html/draft-miller-ssh-agent-00#section-4.1

impl AgentClient {

    pub fn connect<P:AsRef<Path>>(path: P, handle: &Handle) -> Result<AgentClient, Error> {
        Ok(AgentClient {
            stream: UnixStream::connect(path.as_ref(), handle)?,
            buf: CryptoVec::new()
        })
    }

    // Unfortunately, because *ring* doesn't export its secret keys,
    // this can't go any further…
    /*
    pub fn add_key(mut self, key: thrussh::key::Algorithm) -> AddKey {
        self.buf.clear();
        self.buf.resize(4);
        self.buf.push(msg::ADD_IDENTITY);
        match *self {
            Algorithm::Ed25519(ref key_pair) => {
                self.buf.extend(b"ssh-ed25519");
                self.buf.extend(key_pair.public_key_bytes())
            }
            Algorithm::RSA(_, ref public) => {
                write!(f, "RSA {{ public: {:?}, secret: (hidden) }}", public)
            }
        }

        self.buf.extend_ssh_string("ssh-rsa");
        AddKey {
            state: Some(AddKeyState::Write(
                tokio_io::io::write_all(self.stream, self.buf)
            ))
        }
    }
     */
}
*/