pijul_org/thrussh

Debugging thrussh-agent

By pmeunier on December 6, 2017
the signature (by pmeunier) does not match the author (Pierre-Étienne Meunier ).
AzPC3b81y8ECxnEiUp2EMXhJauJythUssieftFMSzp5NgHyA8t1zD4jdefT3X6bJx64kbB2LVJxckxK87Tk1Ap3V

This patch is in the following branches:

master
Moved auth.rs to src/auth.rs
Moved chacha20poly1305.rs to src/cipher/chacha20poly1305.rs
Moved mod.rs to src/cipher/mod.rs
Moved encrypted.rs to src/client/encrypted.rs
Moved mod.rs to src/client/mod.rs
Moved encoding.rs to src/encoding.rs
Moved kex.rs to src/kex.rs
Moved key.rs to src/key.rs
Moved lib.rs to src/lib.rs
Moved msg.rs to src/msg.rs
Moved negotiation.rs to src/negotiation.rs
Moved encrypted.rs to src/server/encrypted.rs
Moved mod.rs to src/server/mod.rs
Moved session.rs to src/session.rs
Moved sshbuffer.rs to src/sshbuffer.rs
New file thrussh-agent
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
[package]
name = "thrussh-agent"
version = "0.1.0"
authors = ["pe@pijul.org <pe@pijul.org>"]
license = "Apache-2.0/MIT"
description = "An SSH agent, including a server (thrussh-agent) and a client (thrussh-add)."
repository = "https://nest.pijul.com/pijul_org/thrussh"
include = [ "Cargo.toml", "src/thrussh-agent.rs", "src/thrussh-add.rs" ]

[dependencies]
thrussh-keys = "0.8.1"
futures = "0.1"
tokio-uds = "0.1"
tokio-core = "0.1"
clap = "2.28"
rand = "0.3"
libc = "0.2"
termion = "1.5"

[[bin]]
name = "thrussh-agent"
path = "src/thrussh-agent.rs"

[[bin]]
name = "thrussh-add"
path = "src/thrussh-add.rs"
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
extern crate thrussh_keys;
extern crate futures;
extern crate tokio_uds;
extern crate tokio_core;
extern crate clap;
extern crate termion;

use futures::{Future, Stream};
use futures::future::Either;
use thrussh_keys::agent;
use std::path::Path;
use std::io::Read;
use std::fs::File;

fn main() {
    let matches = clap::App::new("Thrussh-add")
        .version("0.1")
        .author("Pierre-Étienne Meunier <pe@pijul.org>")
        .arg(clap::Arg::with_name("address")
             .short("a")
             .takes_value(true)
             .help("Bind the agent to that address"))
        .arg(clap::Arg::with_name("file")
             .takes_value(true)
             .multiple(true)
             .help("Secret key files to add"))
        .get_matches();

    let agent_path = {
        if let Some(addr) = matches.value_of("address") {
            std::path::Path::new(addr).to_path_buf()
        } else if let Ok(tmp) = std::env::var("SSH_AUTH_SOCK") {
            Path::new(&tmp).to_path_buf()
        } else {
            eprintln!("No $TMPDIR, and no address was given");
            std::process::exit(1)
        }
    };

    if let Some(files) = matches.values_of("file") {
        let mut core = tokio_core::reactor::Core::new().unwrap();
        let h = core.handle();
        let stream = tokio_uds::UnixStream::connect(&agent_path, &h).unwrap();
        let client = agent::client::AgentClient::connect(stream);

        core.run(
            futures::stream::iter_ok::<_, thrussh_keys::Error>(files)
                .fold(client, |client, s| {
                    let mut f = File::open(s).unwrap();
                    let mut key = String::new();
                    f.read_to_string(&mut key).unwrap();
                    let key = match thrussh_keys::decode_secret_key(&key, None) {
                        Ok(key) => Ok(key),
                        Err(_) => {
                            let password = password().unwrap();
                            thrussh_keys::decode_secret_key(&key, Some(password.as_bytes()))
                        }
                    };
                    match key {
                        Ok(key) => Either::A(client.add_identity(&key, &[]).map(move |(client, success)| {
                            if !success {
                                eprintln!("failed to add {:?}", s);
                            }
                            client
                        })),
                        Err(e) => {
                            eprintln!("Could not open key file: {:?}", e);
                            Either::B(futures::finished(client))
                        }
                    }
                })
        ).unwrap();
    }
}

fn password() -> Result<String, std::io::Error> {
    print!("Password: ");
    use std::io::{stdin, stdout};
    use termion::input::TermRead;
    let stdout = stdout();
    let mut stdout = stdout.lock();
    let stdin = stdin();
    let mut stdin = stdin.lock();
    if let Some(pass) = stdin.read_passwd(&mut stdout)? {
        return Ok(pass)
    } else {
        return Ok(String::new())
    }
}
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
extern crate thrussh_keys;
extern crate futures;
extern crate tokio_uds;
extern crate tokio_core;
extern crate rand;
extern crate clap;
extern crate libc;

use thrussh_keys::agent;
use std::path::Path;
use rand::Rng;

fn main() {
    let matches = clap::App::new("Thrussh-agent")
        .version("0.1")
        .author("Pierre-Étienne Meunier <pe@pijul.org>")
        .arg(clap::Arg::with_name("address")
             .short("a")
             .takes_value(true)
             .help("Bind the agent to that address"))
        .arg(clap::Arg::with_name("foreground")
             .short("D")
             .help("Foreground mode"))
        .get_matches();

    let mut rng = rand::thread_rng();
    let agent_path = {
        if let Some(addr) = matches.value_of("address") {
            std::path::Path::new(addr).to_path_buf()
        } else if let Ok(tmp) = std::env::var("TMPDIR") {
            let file: String = "thrussh-".chars().chain(rng.gen_ascii_chars().take(10)).collect();
            let mut path = Path::new(&tmp).join(&file);
            path.push("agent.ppid");
            path
        } else {
            eprintln!("No $TMPDIR, and no address was given");
            std::process::exit(1)
        }
    };

    if let Some(parent) = agent_path.parent() {
        std::fs::create_dir_all(parent).unwrap()
    }

    let foreground = matches.is_present("foreground");

    let pid = if foreground {
        unsafe { libc::getpid() }
    } else {
        unsafe { libc::fork() }
    };

    if pid > 0 || foreground {

        println!("SSH_AUTH_SOCK={:?}; export SSH_AUTH_SOCK;\nSSH_AGENT_ID={}; export SSH_AGENT_ID; echo Agent pid {}", agent_path, pid, pid);

    }

    if pid == 0 || foreground {
        let mut core = tokio_core::reactor::Core::new().unwrap();
        let h = core.handle();
        let listener = tokio_uds::UnixListener::bind(&agent_path, &h).unwrap().incoming();
        core.run(agent::server::AgentServer::new(listener, h, ())).unwrap();
    }

}
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
name = "thrussh-keys"
version = "0.8.0"
version = "0.8.1"
version = "0.9.4"
authors = ["Pierre-Étienne Meunier <pe@pijul.org>"]
description = "Deal with SSH keys: load them, decrypt them, call an SSH agent."
keywords = ["ssh"]
repository = "https://nest.pijul.com/pijul_org/thrussh"
homepage = "https://pijul.org/thrussh"
documentation = "https://docs.rs/thrussh-keys"
license = "Apache-2.0"
include = [
        "Cargo.toml",
        "src/lib.rs",
        "src/pem.rs",
        "src/agent/mod.rs",
        "src/agent/msg.rs",
        "src/agent/server.rs",
        "src/agent/client.rs"
        "src/agent/client.rs",
        "src/bcrypt_pbkdf.rs",
        "src/blowfish.rs",
        "src/encoding.rs",
        "src/format/mod.rs",
        "src/format/openssh.rs",
        "src/format/pkcs5.rs",
        "src/format/pkcs8.rs"
        "src/format/pkcs8.rs",
        "src/key.rs",
        "src/signature.rs"
        ]

[dependencies]
thrussh = { path = ".." }
thrussh = "0.17.1"
log = "0.3"
base64 = "0.8"
byteorder = "1.2"
tokio-core = "0.1"
tokio-io = "0.1"
futures = "0.1"
cryptovec = "0.4"
error-chain = "0.11"
hex = "0.3"
yasna = "0.1"
num-bigint = "0.1"
num-integer = "0.1"
openssl = { path = "../rust-openssl/openssl" }
num-bigint = { version = "0.1", default-features = false }
num-integer = { version = "0.1", default-features = false }
openssl = "0.9.23"
openssl = "0.10"
bit-vec = "0.4"
thrussh-libsodium = "0.1"
serde_derive = "1.0"
serde = "1.0"

[dev-dependencies]
env_logger = "0.3"
tempdir="0.3"
tokio-uds = "0.1"tokio-uds = "0.1"
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
use Error;
use tokio_io::io::{Flush, WriteAll, ReadExact};
use tokio_io::{AsyncRead, AsyncWrite};
use cryptovec::CryptoVec;
use futures::{Async, Poll, Future};
use encoding::Reader;
use byteorder::{BigEndian, ByteOrder};
use tokio_io;
use key::{PublicKey, SignatureHash};
use encoding::Encoding;
use key;

use super::msg;
use super::Constraint;

/// SSH agent client.
pub struct AgentClient<S: AsyncRead+AsyncWrite> {
    stream: S,
    buf: CryptoVec
}

enum State<S: AsyncRead+AsyncWrite> {
    ReadLen(ReadExact<S, CryptoVec>),
    Read(ReadExact<S, CryptoVec>),
    Write(WriteAll<S, CryptoVec>),
    Flush { flush: Flush<S>, buf: CryptoVec }
}


/// Future resolving to a response from the agent.
pub struct ReadResponse<S: AsyncRead+AsyncWrite>(Option<State<S>>);

impl<S: AsyncRead+AsyncWrite> Future for ReadResponse<S> {
    type Item = (AgentClient<S>, bool);
    type Error = Error;
    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        loop {
            match self.0.take() {
                Some(State::Write(mut w)) => {
                    if let Async::Ready((stream, buf)) = w.poll()? {
                        self.0 = Some(State::Flush {
                            buf,
                            flush: tokio_io::io::flush(stream)
                        })
                    } else {
                        self.0 = Some(State::Write(w));
                        return Ok(Async::NotReady)
                    }
                }
                Some(State::Flush { mut flush, mut buf }) => {
                    if let Async::Ready(stream) = flush.poll()? {
                        buf.clear();
                        buf.resize(4);
                        self.0 = Some(State::ReadLen(tokio_io::io::read_exact(stream, buf)))
                    } else {
                        self.0 = Some(State::Flush { flush, buf });
                        return Ok(Async::NotReady)
                    }
                }
                Some(State::ReadLen(mut read)) => {
                    if let Async::Ready((stream, mut buf)) = read.poll()? {
                        let len = BigEndian::read_u32(&buf) as usize;
                        buf.clear();
                        buf.resize(len);
                        self.0 = Some(State::Read(tokio_io::io::read_exact(stream, buf)))
                    } else {
                        self.0 = Some(State::ReadLen(read));
                        return Ok(Async::NotReady)
                    }
                }
                Some(State::Read(mut read)) => {
                    if let Async::Ready((stream, buf)) = read.poll()? {
                        let success = !buf.is_empty() && buf[0] == msg::SUCCESS;
                        return Ok(Async::Ready((AgentClient { stream, buf }, success)))
                    } else {
                        self.0 = Some(State::ReadLen(read));
                        return Ok(Async::NotReady)
                    }
                }
                _ => panic!("future called after yielded")
            }
        }
    }
}

/// Future resolving to a response from the agent.
pub struct RequestIdentities<S: AsyncRead+AsyncWrite>(ReadResponse<S>);

impl<S: AsyncRead+AsyncWrite> Future for RequestIdentities<S> {
    type Item = (AgentClient<S>, Option<Vec<PublicKey>>);
    type Error = Error;
    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        if let Async::Ready((agent, _)) = self.0.poll()? {
            let mut keys = Vec::new();
            if agent.buf[0] == msg::IDENTITIES_ANSWER {
                let mut r = agent.buf.reader(1);
                let n = r.read_u32()?;
                for _ in 0..n {
                    let key = r.read_string()?;
                    let mut r = key.reader(0);
                    let t = r.read_string()?;
                    match t {
                        b"ssh-rsa" => {
                            let e = r.read_mpint()?;
                            let n = r.read_mpint()?;
                            use openssl::rsa::Rsa;
                            use openssl::bn::BigNum;
                            use openssl::pkey::PKey;
                            keys.push(PublicKey::RSA {
                                key: key::OpenSSLPKey(PKey::from_rsa(Rsa::from_public_components(
                                    BigNum::from_slice(n)?,
                                    BigNum::from_slice(e)?,
                                )?)?),
                                hash: SignatureHash::SHA2_512
                            })
                        }
                        b"ssh-ed25519" => {
                            let mut p = key::ed25519::PublicKey::new_zeroed();
                            p.key.clone_from_slice(r.read_string()?);
                            keys.push(PublicKey::Ed25519(p))
                        }
                        t => debug!("identity type not supported: {:?}", t)
                    }
                }
            }
            return Ok(Async::Ready((agent, Some(keys))))
        } else {
            return Ok(Async::NotReady)
        }
    }
}

/// Future resolving to a response from the agent.
pub struct SignRequest<S: AsyncRead+AsyncWrite>(ReadResponse<S>);

impl<S: AsyncRead+AsyncWrite> Future for SignRequest<S> {
    type Item = (AgentClient<S>, Option<CryptoVec>);
    type Error = Error;
    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        if let Async::Ready((agent, _)) = self.0.poll()? {
            if agent.buf.is_empty() {
                return Ok(Async::Ready((agent, None)))
            } else if agent.buf[0] == msg::SIGN_RESPONSE {
                let sig = {
                    let mut r = agent.buf.reader(1);
                    CryptoVec::from_slice(r.read_string()?)
                };
                return Ok(Async::Ready((agent, Some(sig))))
            } else {
                return Ok(Async::Ready((agent, None)))
            }
        } else {
            return Ok(Async::NotReady)
        }
    }
}

/// Future resolving to a response from the agent.
pub struct QueryExtension<S: AsyncRead+AsyncWrite>(ReadResponse<S>, Option<CryptoVec>);

impl<S: AsyncRead+AsyncWrite> Future for QueryExtension<S> {
    type Item = (AgentClient<S>, CryptoVec, bool);
    type Error = Error;
    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        if let Async::Ready((agent, _)) = self.0.poll()? {
            let mut buf = self.1.take().unwrap();
            if agent.buf[0] == msg::SUCCESS {
                {
                    let mut r = agent.buf.reader(1);
                    buf.extend(r.read_string()?)
                }
                return Ok(Async::Ready((agent, buf, true)))
            } else {
                debug!("msg is {:?}, expected {:?}", agent.buf[0], msg::EXTENSION_FAILURE);
                return Ok(Async::Ready((agent, buf, false)))
            }
        } else {
            return Ok(Async::NotReady)
        }
    }
}

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

impl<S: AsyncRead+AsyncWrite> AgentClient<S> {

    /// Build a future that connects to an SSH agent via the provided
    /// stream (on Unix, usually a Unix-domain socket).
    pub fn connect(stream: S) -> AgentClient<S> {
        AgentClient { stream, buf: CryptoVec::new() }
    }

    /// Send a key to the agent, with a (possibly empty) slice of
    /// constraints to apply when using the key to sign.
    pub fn add_identity(mut self, key: &key::KeyPair, constraints: &[Constraint]) -> ReadResponse<S> {
        use encoding::Encoding;
        self.buf.clear();
        self.buf.resize(4);
        if constraints.is_empty() {
            self.buf.push(msg::ADD_IDENTITY)
        } else {
            self.buf.push(msg::ADD_ID_CONSTRAINED)
        }
        match *key {
            key::KeyPair::Ed25519(ref secret) => {
                self.buf.extend_ssh_string(b"ssh-ed25519");
                let public = &secret.key[32..];
                self.buf.extend_ssh_string(public);
                self.buf.push_u32_be(64);
                self.buf.extend(&secret.key);
                self.buf.extend_ssh_string(b"");
            }
            key::KeyPair::RSA { ref key, .. } => {
                self.buf.extend_ssh_string(b"ssh-rsa");
                self.buf.extend_ssh_mpint(&key.n().to_vec());
                self.buf.extend_ssh_mpint(&key.e().to_vec());
                self.buf.extend_ssh_mpint(&key.d().to_vec());
                self.buf.extend_ssh_mpint(&key.iqmp().unwrap().to_vec());
                self.buf.extend_ssh_mpint(&key.p().unwrap().to_vec());
                self.buf.extend_ssh_mpint(&key.q().unwrap().to_vec());
                self.buf.extend_ssh_string(b"");
            }
        }
        if !constraints.is_empty() {
            self.buf.push_u32_be(constraints.len() as u32);
            for cons in constraints {
                match *cons {
                    Constraint::KeyLifetime { seconds } => {
                        self.buf.push(msg::CONSTRAIN_LIFETIME);
                        self.buf.push_u32_be(seconds)
                    }
                    Constraint::Confirm => self.buf.push(msg::CONSTRAIN_CONFIRM),
                    Constraint::Extensions { ref name, ref details } => {
                        self.buf.push(msg::CONSTRAIN_EXTENSION);
                        self.buf.extend_ssh_string(name);
                        self.buf.extend_ssh_string(details);
                    },
                }
            }
        }
        let len = self.buf.len() - 4;
        BigEndian::write_u32(&mut self.buf[..], len as u32);
        ReadResponse(Some(State::Write(tokio_io::io::write_all(self.stream, self.buf))))
    }

    /// Add a smart card to the agent, with a (possibly empty) set of
    /// constraints to apply when signing.
    pub fn add_smartcard_key(mut self, id: &str, pin: &[u8], constraints: &[Constraint]) -> ReadResponse<S> {
        use encoding::Encoding;
        self.buf.clear();
        self.buf.resize(4);
        if constraints.is_empty() {
            self.buf.push(msg::ADD_SMARTCARD_KEY)
        } else {
            self.buf.push(msg::ADD_SMARTCARD_KEY_CONSTRAINED)
        }
        self.buf.extend_ssh_string(id.as_bytes());
        self.buf.extend_ssh_string(pin);
        if !constraints.is_empty() {
            self.buf.push_u32_be(constraints.len() as u32);
            for cons in constraints {
                match *cons {
                    Constraint::KeyLifetime { seconds } => {
                        self.buf.push(msg::CONSTRAIN_LIFETIME);
                        self.buf.push_u32_be(seconds)
                    }
                    Constraint::Confirm => self.buf.push(msg::CONSTRAIN_CONFIRM),
                    Constraint::Extensions { ref name, ref details } => {
                        self.buf.push(msg::CONSTRAIN_EXTENSION);
                        self.buf.extend_ssh_string(name);
                        self.buf.extend_ssh_string(details);
                    },
                }
            }
        }
        let len = self.buf.len() - 4;
        BigEndian::write_u32(&mut self.buf[0..], len as u32);
        ReadResponse(Some(State::Write(tokio_io::io::write_all(self.stream, self.buf))))
    }

    /// Lock the agent, making it refuse to sign until unlocked.
    pub fn lock(mut self, passphrase: &[u8]) -> ReadResponse<S> {
        use encoding::Encoding;
        self.buf.clear();
        self.buf.resize(4);
        self.buf.push(msg::LOCK);
        self.buf.extend_ssh_string(passphrase);
        let len = self.buf.len() - 4;
        BigEndian::write_u32(&mut self.buf[0..], len as u32);
        ReadResponse(Some(State::Write(tokio_io::io::write_all(self.stream, self.buf))))
    }

    /// Unlock the agent, allowing it to sign again.
    pub fn unlock(mut self, passphrase: &[u8]) -> ReadResponse<S> {
        use encoding::Encoding;
        self.buf.clear();
        self.buf.resize(4);
        self.buf.push(msg::UNLOCK);
        self.buf.extend_ssh_string(passphrase);
        let len = self.buf.len() - 4;
        BigEndian::write_u32(&mut self.buf[0..], len as u32);
        ReadResponse(Some(State::Write(tokio_io::io::write_all(self.stream, self.buf))))
    }

    /// Ask the agent for a list of the currently registered secret
    /// keys.
    pub fn request_identities(mut self) -> RequestIdentities<S> {
        self.buf.clear();
        self.buf.resize(4);
        self.buf.push(msg::REQUEST_IDENTITIES);
        let len = self.buf.len() - 4;
        BigEndian::write_u32(&mut self.buf[0..], len as u32);
        RequestIdentities(ReadResponse(Some(State::Write(
            tokio_io::io::write_all(self.stream, self.buf)
        ))))
    }

    /// Ask the agent to sign the supplied piece of data.
    pub fn sign_request(mut self, public: &key::PublicKey, data: &[u8]) -> SignRequest<S> {
        self.buf.clear();
        self.buf.resize(4);
        self.buf.push(msg::SIGN_REQUEST);
        key_blob(public, &mut self.buf);
        self.buf.extend_ssh_string(data);
        match *public {
            PublicKey::RSA { hash, .. } =>
                self.buf.push_u32_be(match hash {
                    SignatureHash::SHA2_256 => 2,
                    SignatureHash::SHA2_512 => 4,
                }),
            _ => self.buf.push_u32_be(0),
        }
        let len = self.buf.len() - 4;
        BigEndian::write_u32(&mut self.buf[0..], len as u32);
        SignRequest(ReadResponse(Some(State::Write(tokio_io::io::write_all(self.stream, self.buf)))))
    }

    /// Ask the agent to remove a key from its memory.
    pub fn remove_identity(mut self, public: &key::PublicKey) -> ReadResponse<S> {
        self.buf.clear();
        self.buf.resize(4);
        self.buf.push(msg::REMOVE_IDENTITY);
        key_blob(public, &mut self.buf);
        let len = self.buf.len() - 4;
        BigEndian::write_u32(&mut self.buf[0..], len as u32);
        ReadResponse(Some(State::Write(tokio_io::io::write_all(self.stream, self.buf))))
    }

    /// Ask the agent to remove a smartcard from its memory.
    pub fn remove_smartcard_key(mut self, id: &str, pin: &[u8]) -> ReadResponse<S> {
        self.buf.clear();
        self.buf.resize(4);
        self.buf.push(msg::REMOVE_SMARTCARD_KEY);
        self.buf.extend_ssh_string(id.as_bytes());
        self.buf.extend_ssh_string(pin);
        let len = self.buf.len() - 4;
        BigEndian::write_u32(&mut self.buf[0..], len as u32);
        ReadResponse(Some(State::Write(tokio_io::io::write_all(self.stream, self.buf))))
    }

    /// Ask the agent to forget all known keys.
    pub fn remove_all_identities(mut self) -> ReadResponse<S> {
        self.buf.clear();
        self.buf.resize(4);
        self.buf.push(msg::REMOVE_ALL_IDENTITIES);
        BigEndian::write_u32(&mut self.buf[0..], 5);
        ReadResponse(Some(State::Write(tokio_io::io::write_all(self.stream, self.buf))))
    }

    /// Send a custom message to the agent.
    pub fn extension(mut self, typ: &[u8], ext: &[u8]) -> ReadResponse<S> {
        self.buf.clear();
        self.buf.resize(4);
        self.buf.push(msg::EXTENSION);
        self.buf.extend_ssh_string(typ);
        self.buf.extend_ssh_string(ext);
        let len = self.buf.len() - 4;
        BigEndian::write_u32(&mut self.buf[0..], len as u32);
        ReadResponse(Some(State::Write(tokio_io::io::write_all(self.stream, self.buf))))
    }

    /// Ask the agent what extensions about supported extensions.
    pub fn query_extension(mut self, typ: &[u8], ext: CryptoVec) -> QueryExtension<S> {
3
4
5
6
7
8
9
10
11
12
13
14
15
pub mod client;
/// Write servers for SSH agents.
pub mod server;

/// Constraints on how keys can be used
#[derive(Debug)]
pub enum Constraint {
    /// The key shall disappear from the agent's memory after that many seconds.
    KeyLifetime { seconds: u32 },
    /// Signatures need to be confirmed by the agent (for instance using a dialog).
    Confirm,
    /// Custom constraints
    Extensions { name: Vec<u8>, details: Vec<u8> }
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
use futures::{Future, Stream, Poll, Async};
use tokio_core::reactor::{Handle};
use futures;
use tokio_core::reactor::Handle;
use tokio_io::io::{read_exact, ReadExact, flush, Flush, write_all, WriteAll};
use tokio_io::{AsyncRead, AsyncWrite};
use byteorder::{BigEndian, ByteOrder};
use std::time::Duration;
use tokio_core::reactor::Timeout;
use std::time::SystemTime;
use thrussh::FromFinished;
use key::SignatureHash;
use encoding::{Position, Reader, Encoding};
use key;

use {Error, ErrorKind};
use super::msg;
use super::Constraint;

#[derive(Clone)]
pub struct KeyStore(Arc<RwLock<HashMap<Vec<u8>, (thrussh::key::Algorithm, SystemTime, Vec<Constraint>)>>>);

impl KeyStore {
    pub fn new() -> Self {
        KeyStore(Arc::new(RwLock::new(HashMap::new())))
    }
}
struct KeyStore(Arc<RwLock<HashMap<Vec<u8>, (thrussh::key::Algorithm, SystemTime, Vec<Constraint>)>>>);
struct KeyStore(Arc<RwLock<HashMap<Vec<u8>, (key::KeyPair, SystemTime, Vec<Constraint>)>>>);

#[derive(Clone)]
pub struct Lock(Arc<RwLock<CryptoVec>>);

impl Lock {
    pub fn new() -> Self {
        Lock(Arc::new(RwLock::new(CryptoVec::new())))
    }
}
struct Lock(Arc<RwLock<CryptoVec>>);

#[allow(missing_docs)]
#[derive(Debug)]
pub enum ServerError<E> {
    E(E),
    Error(Error)
}

pub struct AgentServer<S: AsyncRead+AsyncWrite, Addr, E, L: Stream<Item = (S, Addr), Error = E>> {
    pub listener: L,
    pub lock: Lock,
    pub lock: Lock,
    pub keys: KeyStore,
    pub handle: Handle,
pub trait Agent: Clone {
    type F: Future<Item = bool, Error = Error> + thrussh::FromFinished<bool, Error>;
    type F: Future<Item = bool, Error = Error> + From<bool>;
    /// Called when data is about to be signed, and a confirmation is needed.
    #[allow(unused_variables)]
    fn confirm(&self, pk: &thrussh::key::Algorithm) -> Self::F {
        Self::F::finished(false)
    fn confirm(&self, pk: &key::KeyPair) -> Self::F {
        From::from(false)
    }
}

impl<S: AsyncRead+AsyncWrite+'static, Addr, E, L: Stream<Item = (S, Addr), Error = E>> Future for AgentServer<S, Addr, E, L> {
impl Agent for () {
    type F = futures::Finished<bool, Error>;
}

/// The agent
pub struct AgentServer<S: AsyncRead+AsyncWrite, Addr, E, L: Stream<Item = (S, Addr), Error = E>, A: Agent> {
    listener: L,
    lock: Lock,
    keys: KeyStore,
    handle: Handle,
    agent: A,
}

impl<S: AsyncRead+AsyncWrite, Addr, E, L: Stream<Item = (S, Addr), Error = E>, A: Agent> AgentServer<S, Addr, E, L, A> {

    /// Create a new agent.
    pub fn new(listener: L, handle: Handle, agent: A) -> Self {
        AgentServer {
            listener,
            handle,
            agent,
            lock: Lock(Arc::new(RwLock::new(CryptoVec::new()))),
            keys: KeyStore(Arc::new(RwLock::new(HashMap::new()))),
        }
    }
}

impl<S: AsyncRead+AsyncWrite+'static, Addr, E, L: Stream<Item = (S, Addr), Error = E>, A: Agent+'static> Future for AgentServer<S, Addr, E, L, A> {
    type Item = ();
    type Error = ServerError<E>;
    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        loop {
            match self.listener.poll() {
                Ok(Async::Ready(Some((stream, _)))) => {
                    let mut buf = CryptoVec::new();
                    buf.resize(4);
                    self.handle.spawn(Connection {
                        lock: self.lock.clone(),
                        keys: self.keys.clone(),
                        state: Some(State::ReadLen(read_exact(stream, buf), CryptoVec::new())),
                        handle: self.handle.clone(),
                        agent: self.agent.clone(),
                    }.map_err(|e| error!("{:?}", e)))
                }
                Ok(Async::Ready(None)) => return Ok(Async::Ready(())),
                Ok(Async::NotReady) => return Ok(Async::NotReady),
                Err(e) => return Err(ServerError::E(e))
            }
        }
    }
}

struct Connection<S: AsyncRead+AsyncWrite> {
struct Connection<S: AsyncRead+AsyncWrite, A: Agent> {
    lock: Lock,
    keys: KeyStore,
    state: Option<State<S>>,
    state: Option<State<S, A>>,
    handle: Handle,
    agent: A,
}

enum State<S: AsyncRead+AsyncWrite> {
enum State<S: AsyncRead+AsyncWrite, A: Agent> {
    ReadLen(ReadExact<S, CryptoVec>, CryptoVec),
    Read(ReadExact<S, CryptoVec>, CryptoVec),
    Write(WriteAll<S, CryptoVec>, CryptoVec),
    Respond { futures: Vec<A::F>, i: usize, stream: S, writebuf: CryptoVec, buf: CryptoVec },
    Flush(Flush<S>, CryptoVec, CryptoVec)
}

impl<S: AsyncRead+AsyncWrite> Future for Connection<S> {
impl<S: AsyncRead+AsyncWrite, A: Agent> Future for Connection<S, A> {
    type Item = ();
    type Error = Error;
    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        loop {
            match self.state.take() {
                Some(State::ReadLen(mut r, writebuf)) => {
                    if let Async::Ready((stream, mut buf)) = r.poll()? {
                        let len = BigEndian::read_u32(&buf) as usize;
                        buf.clear();
                        buf.resize(len);
                        self.state = Some(State::Read(read_exact(stream, buf), writebuf))
                    } else {
                        self.state = Some(State::ReadLen(r, writebuf));
                        return Ok(Async::NotReady)
                    }
                }
                Some(State::Read(mut r, mut writebuf)) => {
                    if let Async::Ready((stream, buf)) = r.poll()? {
                        writebuf.clear();
                        self.respond(&buf, &mut writebuf);
                        self.state = Some(State::Write(write_all(stream, writebuf), buf))
                        if let Some(v) = self.respond(&buf, &mut writebuf) {
                            self.state = Some(State::Respond { futures: v, i: 0, stream, writebuf, buf })
                        } else {
                            self.state = Some(State::Write(write_all(stream, writebuf), buf))
                        }
                    } else {
                        self.state = Some(State::Read(r, writebuf));
                        return Ok(Async::NotReady)
                    }
                }
                Some(State::Respond { mut futures, i, stream, mut writebuf, buf }) => {
                    // Validate constraints and sign.
                    if i >= futures.len() {
                        // All constraints passed!
                        {
                            let mut r = buf.reader(0);
                            r.read_byte()?;
                            self.really_sign(r, &mut writebuf)?;
                        }
                        self.state = Some(State::Write(write_all(stream, writebuf), buf))
                    } else {
                        match futures[i].poll()? {
                            Async::Ready(true) =>
                                self.state = Some(State::Respond {
                                    futures,
                                    i: i + 1,
                                    stream,
                                    writebuf,
                                    buf
                                }),
                            Async::Ready(false) => {
                                // failure
                                writebuf.resize(4);
                                writebuf.push(msg::FAILURE);
                                self.state = Some(State::Write(write_all(stream, writebuf), buf))
                            }
                            Async::NotReady => return Ok(Async::NotReady),
                        }
                    }
                }
                Some(State::Write(mut w, readbuf)) => {
                    if let Async::Ready((stream, buf)) = w.poll()? {
                        self.state = Some(State::Flush(flush(stream), readbuf, buf))
                    } else {
                        self.state = Some(State::Write(w, readbuf));
                        return Ok(Async::NotReady)
                    }
                }
                Some(State::Flush(mut w, mut readbuf, writebuf)) => {
                    if let Async::Ready(stream) = w.poll()? {
                        readbuf.clear();
                        readbuf.resize(4);
                        self.state = Some(State::ReadLen(read_exact(stream, readbuf), writebuf))
                    } else {
                        self.state = Some(State::Flush(w, readbuf, writebuf));
                        return Ok(Async::NotReady)
                    }
                }
                None => {
                    panic!("future polled after completion")
                }
            }
        }
    }
}

impl<S: AsyncRead+AsyncWrite> Connection<S> {
impl<S: AsyncRead+AsyncWrite, A: Agent> Connection<S, A> {

    fn respond(&self, buf: &CryptoVec, w: &mut CryptoVec) {
    fn respond(&self, buf: &CryptoVec, w: &mut CryptoVec) -> Option<Vec<A::F>> {
        let is_locked = {
            if let Ok(password) = self.lock.0.read() {
                !password.is_empty()
            } else {
                true
            }
        };
        w.extend(&[0, 0, 0, 0]);
        let mut r = buf.reader(0);
        match r.read_byte() {
            Ok(11) if !is_locked => {
                // request identities
                if let Ok(keys) = self.keys.0.read() {
                    w.push(msg::IDENTITIES_ANSWER);
                    w.push_u32_be(keys.len() as u32);
                    for (k, _) in keys.iter() {
                        w.extend_ssh_string(k);
                        w.extend_ssh_string(b"");
                    }
                } else {
                    w.push(msg::FAILURE)
                }
            }
            Ok(13) if !is_locked => {
                // sign request
                if let Ok(true) = self.sign(r, w) {
                    w.push(msg::SUCCESS)
                if let Ok(v) = self.try_sign(r) {
                    return Some(v)
                } else {
                    w.resize(4);
                    w.push(msg::FAILURE)
                }
            }
            Ok(17) if !is_locked => {
                // add identity
                if let Ok(true) = self.add_key(buf, w, r, false) {
                } else {
                    w.push(msg::FAILURE)
                }
            }
            Ok(18) if !is_locked => {
                // remove identity
                if let Ok(true) = self.remove_identity(r) {
                    w.push(msg::SUCCESS)
                } else {
                    w.push(msg::FAILURE)
                }
            }
            Ok(19) if !is_locked => {
                // remove all identities
                if let Ok(mut keys) = self.keys.0.write() {
                    keys.clear();
                    w.push(msg::SUCCESS)
                } else {
                    w.push(msg::FAILURE)
                }
            }
            Ok(22) if !is_locked => {
                // lock
                if let Ok(()) = self.lock(r) {
                    w.push(msg::SUCCESS)
                } else {
                    w.push(msg::FAILURE)
                }
            }
            Ok(23) if is_locked => {
                // unlock
                if let Ok(true) = self.unlock(r) {
                    w.push(msg::SUCCESS)
                } else {
                    w.push(msg::FAILURE)
                }
            }
            Ok(25) if !is_locked => {
                // add identity constrained
                if let Ok(true) = self.add_key(buf, w, r, true) {
                } else {
                    w.push(msg::FAILURE)
                }
            }
            m => {
                error!("message not understood {:?}", m);
                w.push(msg::FAILURE)
            }
        }
        let len = w.len() - 4;
        BigEndian::write_u32(&mut w[0..], len as u32);
        None
    }

    fn lock(&self, mut r: Position) -> Result<(), Error> {
        let password = r.read_string()?;
        let mut lock = self.lock.0.write().map_err(|_| ErrorKind::Poison)?;
        lock.extend(password);
        Ok(())
    }

    fn unlock(&self, mut r: Position) -> Result<bool, Error> {
        let password = r.read_string()?;
        let mut lock = self.lock.0.write().map_err(|_| ErrorKind::Poison)?;
        if &lock[0..] == password {
            lock.clear();
            Ok(true)
        } else {
            Ok(false)
        }
    }

    fn remove_identity(&self, mut r: Position) -> Result<bool, Error> {
        if let Ok(mut keys) = self.keys.0.write() {
            if keys.remove(r.read_string()?).is_some() {
                Ok(true)
            } else {
                Ok(false)
            }
        } else {
            Ok(false)
        }

    }

    fn add_key(&self, buf: &CryptoVec, w: &mut CryptoVec, mut r: Position, constrained: bool) -> Result<bool, Error> {
        let pos0 = r.position;
        let t = r.read_string()?;
        let (blob, key) = match t {
            b"ssh-ed25519" => {
                let public_ = r.read_string()?;
                let pos1 = r.position;
                let concat = r.read_string()?;
                let _comment = r.read_string()?;
                if &concat[32..64] != public_ {
                    return Ok(false)
                }
                use key::ed25519::*;
                let mut public = PublicKey::new_zeroed();
                let mut secret = SecretKey::new_zeroed();
                public.key.clone_from_slice(&public_[..32]);
                secret.key.clone_from_slice(&concat[..32]);
                secret.key.clone_from_slice(&concat[..]);
                w.push(msg::SUCCESS);
                (buf[pos0..pos1].to_vec(),
                 key::KeyPair::Ed25519(secret))
            }
            b"ssh-rsa" => {
                use openssl::bn::{BigNum, BigNumContext};
                use openssl::rsa::Rsa;
                let n = r.read_mpint()?;
                let e = r.read_mpint()?;
                let d = BigNum::from_slice(r.read_mpint()?)?;
                let q_inv = r.read_mpint()?;
                let p = BigNum::from_slice(r.read_mpint()?)?;
                let q = BigNum::from_slice(r.read_mpint()?)?;
                let (dp, dq) = {
                    let one = BigNum::from_u32(1)?;
                    let p1 = p.as_ref() - one.as_ref();
                    let q1 = q.as_ref() - one.as_ref();
                    let mut context = BigNumContext::new()?;
                    let mut dp = BigNum::new()?;
                    let mut dq = BigNum::new()?;
                    dp.checked_rem(&d, &p1, &mut context)?;
                    dq.checked_rem(&d, &q1, &mut context)?;
                    (dp, dq)
                };
                let _comment = r.read_string()?;
                let key = Rsa::from_private_components (
                    BigNum::from_slice(n)?,
                    BigNum::from_slice(e)?,
                    d,
                    p,
                    q,
                    dp,
                    dq,
                    BigNum::from_slice(&q_inv)?,
                )?;

                let len0 = w.len();
                w.extend_ssh_string(b"ssh-rsa");
                w.extend_ssh_mpint(&e);
                w.extend_ssh_mpint(&n);
                let blob = w[len0..].to_vec();
                w.resize(len0);
                w.push(msg::SUCCESS);
                (blob, key::KeyPair::RSA { key, hash: SignatureHash::SHA2_256 })
            }
            _ => return Ok(false)
        };
        let mut w = self.keys.0.write().unwrap();
        let now = SystemTime::now();
        if constrained {
            let n = r.read_u32()?;
            let mut c = Vec::new();
            for _ in 0..n {
                let t = r.read_byte()?;
                if t == msg::CONSTRAIN_LIFETIME {
                    let seconds = r.read_u32()?;
                    c.push(Constraint::KeyLifetime { seconds });
                    let blob = blob.clone();
                    let keys = self.keys.clone();
                    self.handle.spawn(
                        Timeout::new(Duration::from_secs(seconds as u64), &self.handle).unwrap()
                            .map(move |_| {
                                let mut keys = keys.0.write().unwrap();
                                let delete = if let Some(&(_, time, _)) = keys.get(&blob) {
                                    time == now
                                } else {
                                    false
                                };
                                if delete {
                                    keys.remove(&blob);
                                }
                            })
                            .map_err(|_| ())
                    )
                } else if t == msg::CONSTRAIN_CONFIRM {
                    c.push(Constraint::Confirm)
                } else {
                    return Ok(false)
                }
            }
            w.insert(blob, (key, now, Vec::new()));
        } else {
            w.insert(blob, (key, now, Vec::new()));
        }
        Ok(true)
    }

    fn sign(&self, mut r: Position, w: &mut CryptoVec) -> Result<bool, Error> {
    fn try_sign(&self, mut r: Position) -> Result<Vec<A::F>, Error> {
        let blob = r.read_string()?;
        let k = self.keys.0.read().unwrap();
        if let Some(&(ref key, _, ref constraints)) = k.get(blob) {
            let mut v = Vec::new();
            for cons in constraints {
                match *cons {
                    Constraint::KeyLifetime { .. } | Constraint::Extensions { .. } => {}
                    Constraint::Confirm => v.push(self.agent.confirm(key))
                }
            }
            Ok(v)
        } else {
            Ok(vec![A::F::finished(false)])
            Ok(vec![A::F::from(false)])
        }
    }

    fn really_sign(&self, mut r: Position, w: &mut CryptoVec) -> Result<(), Error> {
        let blob = r.read_string()?;
        let data = r.read_string()?;
        let k = self.keys.0.read().unwrap();
        if let Some(&(ref key, _, _)) = k.get(blob) {
            w.push(msg::SIGN_RESPONSE);
            key.add_signature(w, data)?;
            Ok(true)
        } else {
            Ok(false)
            let len = w.len();
            BigEndian::write_u32(&mut w[0..], (len-4) as u32);
        }
        Ok(())
    }
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
pub enum Encryption {
    /// Key for AES128
    Aes128Cbc([u8; 16]),
    /// Key for AES256
    Aes256Cbc([u8; 16]),
}

#[derive(Clone, Debug)]
enum Format {
    Rsa,
    Openssh,
    Pkcs5Encrypted(Encryption),
    Pkcs8Encrypted,
    Pkcs8,
}

/// Decode a secret key, possibly deciphering it with the supplied
/// password.
pub fn decode_secret_key(
10
11
/// needed using the supplied password.
pub fn decode_openssh(
10
11
/// using the supplied password.
pub fn decode_pkcs5(
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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638







639
640
641
#![deny(trivial_casts,
        unstable_features,
        unused_import_braces)]
//! This crate contains methods to deal with SSH keys, as defined in
//! crate Thrussh. This includes in particular various functions for
//! opening key files, deciphering encrypted keys, and dealing with
//! agents.
//!
//! The following example shows how to do all these in a single
//! example: start and SSH agent server, connect to it with a client,
//! decipher an encrypted private key (the password is `b"blabla"`),
//! send it to the agent, and ask the agent to sign a piece of data
//! (`b"I'd like this to be signed", below).
//!
//!```
//! extern crate thrussh_keys;
//! extern crate futures;
//! extern crate tempdir;
//! extern crate tokio_uds;
//! extern crate tokio_core;
//! use thrussh_keys::agent;
//! use futures::Future;
//!
//! fn main() {
//!   let dir = tempdir::TempDir::new("thrussh").unwrap();
//!   let agent_path = dir.path().join("agent");
//!   let pkcs8_encrypted = "-----BEGIN ENCRYPTED PRIVATE KEY-----
//!MIIFLTBXBgkqhkiG9w0BBQ0wSjApBgkqhkiG9w0BBQwwHAQITo1O0b8YrS0CAggA
//!MAwGCCqGSIb3DQIJBQAwHQYJYIZIAWUDBAEqBBBtLH4T1KOfo1GGr7salhR8BIIE
//!0KN9ednYwcTGSX3hg7fROhTw7JAJ1D4IdT1fsoGeNu2BFuIgF3cthGHe6S5zceI2
//!MpkfwvHbsOlDFWMUIAb/VY8/iYxhNmd5J6NStMYRC9NC0fVzOmrJqE1wITqxtORx
//!IkzqkgFUbaaiFFQPepsh5CvQfAgGEWV329SsTOKIgyTj97RxfZIKA+TR5J5g2dJY
//!j346SvHhSxJ4Jc0asccgMb0HGh9UUDzDSql0OIdbnZW5KzYJPOx+aDqnpbz7UzY/
//!P8N0w/pEiGmkdkNyvGsdttcjFpOWlLnLDhtLx8dDwi/sbEYHtpMzsYC9jPn3hnds
//!TcotqjoSZ31O6rJD4z18FOQb4iZs3MohwEdDd9XKblTfYKM62aQJWH6cVQcg+1C7
//!jX9l2wmyK26Tkkl5Qg/qSfzrCveke5muZgZkFwL0GCcgPJ8RixSB4GOdSMa/hAMU
//!kvFAtoV2GluIgmSe1pG5cNMhurxM1dPPf4WnD+9hkFFSsMkTAuxDZIdDk3FA8zof
//!Yhv0ZTfvT6V+vgH3Hv7Tqcxomy5Qr3tj5vvAqqDU6k7fC4FvkxDh2mG5ovWvc4Nb
//!Xv8sed0LGpYitIOMldu6650LoZAqJVv5N4cAA2Edqldf7S2Iz1QnA/usXkQd4tLa
//!Z80+sDNv9eCVkfaJ6kOVLk/ghLdXWJYRLenfQZtVUXrPkaPpNXgD0dlaTN8KuvML
//!Uw/UGa+4ybnPsdVflI0YkJKbxouhp4iB4S5ACAwqHVmsH5GRnujf10qLoS7RjDAl
//!o/wSHxdT9BECp7TT8ID65u2mlJvH13iJbktPczGXt07nBiBse6OxsClfBtHkRLzE
//!QF6UMEXsJnIIMRfrZQnduC8FUOkfPOSXc8r9SeZ3GhfbV/DmWZvFPCpjzKYPsM5+
//!N8Bw/iZ7NIH4xzNOgwdp5BzjH9hRtCt4sUKVVlWfEDtTnkHNOusQGKu7HkBF87YZ
//!RN/Nd3gvHob668JOcGchcOzcsqsgzhGMD8+G9T9oZkFCYtwUXQU2XjMN0R4VtQgZ
//!rAxWyQau9xXMGyDC67gQ5xSn+oqMK0HmoW8jh2LG/cUowHFAkUxdzGadnjGhMOI2
//!zwNJPIjF93eDF/+zW5E1l0iGdiYyHkJbWSvcCuvTwma9FIDB45vOh5mSR+YjjSM5
//!nq3THSWNi7Cxqz12Q1+i9pz92T2myYKBBtu1WDh+2KOn5DUkfEadY5SsIu/Rb7ub
//!5FBihk2RN3y/iZk+36I69HgGg1OElYjps3D+A9AjVby10zxxLAz8U28YqJZm4wA/
//!T0HLxBiVw+rsHmLP79KvsT2+b4Diqih+VTXouPWC/W+lELYKSlqnJCat77IxgM9e
//!YIhzD47OgWl33GJ/R10+RDoDvY4koYE+V5NLglEhbwjloo9Ryv5ywBJNS7mfXMsK
//!/uf+l2AscZTZ1mhtL38efTQCIRjyFHc3V31DI0UdETADi+/Omz+bXu0D5VvX+7c6
//!b1iVZKpJw8KUjzeUV8yOZhvGu3LrQbhkTPVYL555iP1KN0Eya88ra+FUKMwLgjYr
//!JkUx4iad4dTsGPodwEP/Y9oX/Qk3ZQr+REZ8lg6IBoKKqqrQeBJ9gkm1jfKE6Xkc
//!Cog3JMeTrb3LiPHgN6gU2P30MRp6L1j1J/MtlOAr5rux
//!-----END ENCRYPTED PRIVATE KEY-----";
//!
//!   let mut core = tokio_core::reactor::Core::new().unwrap();
//!
//!   let h = core.handle();
//!   let listener = tokio_uds::UnixListener::bind(&agent_path, &h).unwrap().incoming();
//!   h.spawn(agent::server::AgentServer::new(listener, core.handle(), ()).map_err(|e| eprintln!("{:?}", e)));
//!
//!   let key = thrussh_keys::decode_secret_key(pkcs8_encrypted, Some(b"blabla")).unwrap();
//!   let public = key.clone_public_key();
//!   let h = core.handle();
//!   let stream = tokio_uds::UnixStream::connect(&agent_path, &h).unwrap();
//!   core.run(
//!     agent::client::AgentClient::connect(stream)
//!         .add_identity(&key, &[agent::Constraint::KeyLifetime { seconds: 60 }]).and_then(|(client, _)| {
//!             client.request_identities().and_then(|(client, _id)| {
//!                 client.sign_request(&public, b"I'd like this to be signed").and_then(|(_, sig)| {
//!                     sig.unwrap();
//!                     futures::finished(())
//!                 })
//!             })
//!         })
//!   ).unwrap();
//! }
//!```



#![recursion_limit="128"]
// extern crate thrussh;
#[macro_use]
extern crate log;
extern crate base64;
extern crate hex;
extern crate byteorder;
#[macro_use]
extern crate error_chain;
extern crate yasna;
extern crate tokio_core;
extern crate tokio_io;
extern crate futures;
extern crate cryptovec;
extern crate num_bigint;
extern crate num_integer;
extern crate bit_vec;
extern crate openssl;
extern crate thrussh_libsodium as sodium;
#[cfg(test)]
extern crate env_logger;
#[cfg(test)]
extern crate tokio_uds;
#[macro_use]
extern crate serde_derive;
extern crate serde;

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 byteorder::{BigEndian, WriteBytesExt};

pub mod key;
pub mod signature;
pub mod encoding;

mod blowfish;
mod bcrypt_pbkdf;
mod format;
pub use format::*;

/// A module to write SSH agent.
pub mod agent;

error_chain!{
    foreign_links {
        IO(std::io::Error);
        Utf8(std::str::Utf8Error);
        OpenSSL(openssl::error::Error);
        OpenSSLStack(openssl::error::ErrorStack);
        Base64(base64::DecodeError);
        Hex(hex::FromHexError);
        Yasna(yasna::ASN1Error);
    }
    errors {
        /// Unknown error
        Unit {}
        /// The key could not be read, for an unknown reason
        CouldNotReadKey {}
        /// The key is encrypted (should supply a password?)
        KeyIsEncrypted {}
        /// Home directory could not be found
        NoHomeDir {}
        /// The server key has changed
        KeyChanged(changed: usize) {
        }
        /// The key uses an unsupported algorithm
        UnknownAlgorithm(oid: yasna::models::ObjectIdentifier) {
        }
        /// Lock poisoning error
        Poison{}
        /// Index out of bounds
        IndexOutOfBounds {}
    }
}

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(key::parse_public_key(&base)?)
}

pub trait PublicKeyBase64 {
    /// Create the base64 part of the public key blob.
    fn public_key_base64(&self) -> String;
}

impl PublicKeyBase64 for key::PublicKey {
    fn public_key_base64(&self) -> String {
        let name = self.name().as_bytes();
        let mut s = cryptovec::CryptoVec::new();
        s.write_u32::<BigEndian>(name.len() as u32).unwrap();
        s.extend(name);
        match *self {
            key::PublicKey::Ed25519(ref publickey) => {
                s.write_u32::<BigEndian>(publickey.key.len() as u32).unwrap();
                s.extend(&publickey.key);
            }
            key::PublicKey::RSA { ref key, .. } => {
                use encoding::Encoding;
                s.extend_ssh_mpint(&key.0.rsa().unwrap().e().to_vec());
                s.extend_ssh_mpint(&key.0.rsa().unwrap().n().to_vec());
            }
        }
        encode_config(&s, MIME)
    }
}

impl PublicKeyBase64 for key::KeyPair {
    fn public_key_base64(&self) -> String {
        let name = self.name().as_bytes();
        let mut s = cryptovec::CryptoVec::new();
        s.write_u32::<BigEndian>(name.len() as u32).unwrap();
        s.extend(name);
        match *self {
            key::KeyPair::Ed25519(ref key) => {
                let public = &key.key[32.. ];
                s.write_u32::<BigEndian>(32).unwrap();
                s.extend(&public);
            }
            key::KeyPair::RSA { ref key, .. } => {
                use encoding::Encoding;
                s.extend_ssh_mpint(&key.e().to_vec());
                s.extend_ssh_mpint(&key.n().to_vec());
            }
        }
        encode_config(&s, MIME)
    }
}

/// 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<()> {
    let name = publickey.name().as_bytes();
    w.write_all(name)?;
    w.write_all(b" ")?;
    w.write_all(publickey.public_key_base64().as_bytes())?;
    Ok(())
}


/// Load a secret key, deciphering it with the supplied password if necessary.
pub fn load_secret_key<P:AsRef<Path>>(secret_: P, password: Option<&[u8]>) -> Result<key::KeyPair> {
    let mut secret_file = std::fs::File::open(secret_)?;
    let mut secret = String::new();
    secret_file.read_to_string(&mut secret)?;
    decode_secret_key(&secret, password)
}

fn is_base64_char(c: char) -> bool {
    (c >= 'a' && c <= 'z')
        || (c >= 'A' && c <= 'Z')
        || (c >= '0' && c <= '9')
        || c == '/' || c == '+' || c == '='
}


/// 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<()> {

    if let Some(parent) = path.as_ref().parent() {
        std::fs::create_dir_all(parent)?
    }
    let mut file = 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];
    let mut ends_in_newline = false;
    if file.seek(SeekFrom::End(-1)).is_ok() {
        file.read_exact(&mut buf)?;
        ends_in_newline = buf[0] == b'\n';
    }

    // Write the key.
    file.seek(SeekFrom::Start(0))?;
    let mut file = std::io::BufWriter::new(file);
    if !ends_in_newline {
        file.write(b"\n")?;
    }
    if port != 22 {
        write!(file, "[{}]:{} ", host, port)?
    } else {
        write!(file, "{} ", host)?
    }
    write_public_key_base64(&mut file, pubkey)?;
    file.write(b"\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 = if let Ok(f) = File::open(path) {
        BufReader::new(f)
    } else {
        return Ok(false)
    };
    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;
    use std::fs::File;
    use std::io::Write;
    use futures::Future;
    use super::*;


    const ED25519_KEY: &'static str = "-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jYmMAAAAGYmNyeXB0AAAAGAAAABDLGyfA39
J2FcJygtYqi5ISAAAAEAAAAAEAAAAzAAAAC3NzaC1lZDI1NTE5AAAAIN+Wjn4+4Fcvl2Jl
KpggT+wCRxpSvtqqpVrQrKN1/A22AAAAkOHDLnYZvYS6H9Q3S3Nk4ri3R2jAZlQlBbUos5
FkHpYgNw65KCWCTXtP7ye2czMC3zjn2r98pJLobsLYQgRiHIv/CUdAdsqbvMPECB+wl/UQ
e+JpiSq66Z6GIt0801skPh20jxOO3F52SoX1IeO5D5PXfZrfSZlw6S8c7bwyp2FHxDewRx
7/wNsnDM0T7nLv/Q==
-----END OPENSSH PRIVATE KEY-----";


    #[test]
    fn test_decode_secret_key() {
        extern crate env_logger;
        env_logger::init().unwrap_or(());
        decode_secret_key(ED25519_KEY, Some(b"blabla")).unwrap();
    }

    #[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-----
";
        decode_secret_key(key, None).unwrap();
    }

    pub const PKCS8_RSA: &'static str = "-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAwBGetHjW+3bDQpVktdemnk7JXgu1NBWUM+ysifYLDBvJ9ttX
GNZSyQKA4v/dNr0FhAJ8I9BuOTjYCy1YfKylhl5D/DiSSXFPsQzERMmGgAlYvU2U
+FTxpBC11EZg69CPVMKKevfoUD+PZA5zB7Hc1dXFfwqFc5249SdbAwD39VTbrOUI
WECvWZs6/ucQxHHXP2O9qxWqhzb/ddOnqsDHUNoeceiNiCf2anNymovrIMjAqq1R
t2UP3f06/Zt7Jx5AxKqS4seFkaDlMAK8JkEDuMDOdKI36raHkKanfx8CnGMSNjFQ
QtvnpD8VSGkDTJN3Qs14vj2wvS477BQXkBKN1QIDAQABAoIBABb6xLMw9f+2ENyJ
hTggagXsxTjkS7TElCu2OFp1PpMfTAWl7oDBO7xi+UqvdCcVbHCD35hlWpqsC2Ui
8sBP46n040ts9UumK/Ox5FWaiuYMuDpF6vnfJ94KRcb0+KmeFVf9wpW9zWS0hhJh
jC+yfwpyfiOZ/ad8imGCaOguGHyYiiwbRf381T/1FlaOGSae88h+O8SKTG1Oahq4
0HZ/KBQf9pij0mfVQhYBzsNu2JsHNx9+DwJkrXT7K9SHBpiBAKisTTCnQmS89GtE
6J2+bq96WgugiM7X6OPnmBmE/q1TgV18OhT+rlvvNi5/n8Z1ag5Xlg1Rtq/bxByP
CeIVHsECgYEA9dX+LQdv/Mg/VGIos2LbpJUhJDj0XWnTRq9Kk2tVzr+9aL5VikEb
09UPIEa2ToL6LjlkDOnyqIMd/WY1W0+9Zf1ttg43S/6Rvv1W8YQde0Nc7QTcuZ1K
9jSSP9hzsa3KZtx0fCtvVHm+ac9fP6u80tqumbiD2F0cnCZcSxOb4+UCgYEAyAKJ
70nNKegH4rTCStAqR7WGAsdPE3hBsC814jguplCpb4TwID+U78Xxu0DQF8WtVJ10
SJuR0R2q4L9uYWpo0MxdawSK5s9Am27MtJL0mkFQX0QiM7hSZ3oqimsdUdXwxCGg
oktxCUUHDIPJNVd4Xjg0JTh4UZT6WK9hl1zLQzECgYEAiZRCFGc2KCzVLF9m0cXA
kGIZUxFAyMqBv+w3+zq1oegyk1z5uE7pyOpS9cg9HME2TAo4UPXYpLAEZ5z8vWZp
45sp/BoGnlQQsudK8gzzBtnTNp5i/MnnetQ/CNYVIVnWjSxRUHBqdMdRZhv0/Uga
e5KA5myZ9MtfSJA7VJTbyHUCgYBCcS13M1IXaMAt3JRqm+pftfqVs7YeJqXTrGs/
AiDlGQigRk4quFR2rpAV/3rhWsawxDmb4So4iJ16Wb2GWP4G1sz1vyWRdSnmOJGC
LwtYrvfPHegqvEGLpHa7UsgDpol77hvZriwXwzmLO8A8mxkeW5dfAfpeR5o+mcxW
pvnTEQKBgQCKx6Ln0ku6jDyuDzA9xV2/PET5D75X61R2yhdxi8zurY/5Qon3OWzk
jn/nHT3AZghGngOnzyv9wPMKt9BTHyTB6DlB6bRVLDkmNqZh5Wi8U1/IjyNYI0t2
xV/JrzLAwPoKk3bkqys3bUmgo6DxVC/6RmMwPQ0rmpw78kOgEej90g==
-----END RSA PRIVATE KEY-----
";

    #[test]
    fn test_pkcs8() {
        env_logger::init().unwrap_or(());
        println!("test");
        decode_secret_key(PKCS8_RSA, Some(b"blabla")).unwrap();
    }

    const PKCS8_ENCRYPTED: &'static str = "-----BEGIN ENCRYPTED PRIVATE KEY-----
MIIFLTBXBgkqhkiG9w0BBQ0wSjApBgkqhkiG9w0BBQwwHAQITo1O0b8YrS0CAggA
MAwGCCqGSIb3DQIJBQAwHQYJYIZIAWUDBAEqBBBtLH4T1KOfo1GGr7salhR8BIIE
0KN9ednYwcTGSX3hg7fROhTw7JAJ1D4IdT1fsoGeNu2BFuIgF3cthGHe6S5zceI2
MpkfwvHbsOlDFWMUIAb/VY8/iYxhNmd5J6NStMYRC9NC0fVzOmrJqE1wITqxtORx
IkzqkgFUbaaiFFQPepsh5CvQfAgGEWV329SsTOKIgyTj97RxfZIKA+TR5J5g2dJY
j346SvHhSxJ4Jc0asccgMb0HGh9UUDzDSql0OIdbnZW5KzYJPOx+aDqnpbz7UzY/
P8N0w/pEiGmkdkNyvGsdttcjFpOWlLnLDhtLx8dDwi/sbEYHtpMzsYC9jPn3hnds
TcotqjoSZ31O6rJD4z18FOQb4iZs3MohwEdDd9XKblTfYKM62aQJWH6cVQcg+1C7
jX9l2wmyK26Tkkl5Qg/qSfzrCveke5muZgZkFwL0GCcgPJ8RixSB4GOdSMa/hAMU
kvFAtoV2GluIgmSe1pG5cNMhurxM1dPPf4WnD+9hkFFSsMkTAuxDZIdDk3FA8zof
Yhv0ZTfvT6V+vgH3Hv7Tqcxomy5Qr3tj5vvAqqDU6k7fC4FvkxDh2mG5ovWvc4Nb
Xv8sed0LGpYitIOMldu6650LoZAqJVv5N4cAA2Edqldf7S2Iz1QnA/usXkQd4tLa
Z80+sDNv9eCVkfaJ6kOVLk/ghLdXWJYRLenfQZtVUXrPkaPpNXgD0dlaTN8KuvML
Uw/UGa+4ybnPsdVflI0YkJKbxouhp4iB4S5ACAwqHVmsH5GRnujf10qLoS7RjDAl
o/wSHxdT9BECp7TT8ID65u2mlJvH13iJbktPczGXt07nBiBse6OxsClfBtHkRLzE
QF6UMEXsJnIIMRfrZQnduC8FUOkfPOSXc8r9SeZ3GhfbV/DmWZvFPCpjzKYPsM5+
N8Bw/iZ7NIH4xzNOgwdp5BzjH9hRtCt4sUKVVlWfEDtTnkHNOusQGKu7HkBF87YZ
RN/Nd3gvHob668JOcGchcOzcsqsgzhGMD8+G9T9oZkFCYtwUXQU2XjMN0R4VtQgZ
rAxWyQau9xXMGyDC67gQ5xSn+oqMK0HmoW8jh2LG/cUowHFAkUxdzGadnjGhMOI2
zwNJPIjF93eDF/+zW5E1l0iGdiYyHkJbWSvcCuvTwma9FIDB45vOh5mSR+YjjSM5
nq3THSWNi7Cxqz12Q1+i9pz92T2myYKBBtu1WDh+2KOn5DUkfEadY5SsIu/Rb7ub
5FBihk2RN3y/iZk+36I69HgGg1OElYjps3D+A9AjVby10zxxLAz8U28YqJZm4wA/
T0HLxBiVw+rsHmLP79KvsT2+b4Diqih+VTXouPWC/W+lELYKSlqnJCat77IxgM9e
YIhzD47OgWl33GJ/R10+RDoDvY4koYE+V5NLglEhbwjloo9Ryv5ywBJNS7mfXMsK
/uf+l2AscZTZ1mhtL38efTQCIRjyFHc3V31DI0UdETADi+/Omz+bXu0D5VvX+7c6
b1iVZKpJw8KUjzeUV8yOZhvGu3LrQbhkTPVYL555iP1KN0Eya88ra+FUKMwLgjYr
JkUx4iad4dTsGPodwEP/Y9oX/Qk3ZQr+REZ8lg6IBoKKqqrQeBJ9gkm1jfKE6Xkc
Cog3JMeTrb3LiPHgN6gU2P30MRp6L1j1J/MtlOAr5rux
-----END ENCRYPTED PRIVATE KEY-----";

    #[test]
    fn test_pkcs8_encrypted() {
        env_logger::init().unwrap_or(());
        println!("test");
        decode_secret_key(PKCS8_ENCRYPTED, Some(b"blabla")).unwrap();
    }

    fn test_client_agent(key: &key::Algorithm) {
        env_logger::init().unwrap_or(());
        use std::process::Command;
        let dir = tempdir::TempDir::new("thrussh").unwrap();
        let agent_path = dir.path().join("agent");
        debug!("agent_path = {:?}", agent_path);
        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 mut core = tokio_core::reactor::Core::new().unwrap();
        let public = key.clone_public_key();
        let h = core.handle();
        let stream = tokio_uds::UnixStream::connect(&agent_path, &h).unwrap();
        core.run(
            agent::client::AgentClient::connect(stream)
                .add_identity(&key, &[]).and_then(|(client, _)| {
                    client.request_identities().and_then(|(client, id)| {
                        debug!("id = {:?}", id);
                        client.sign_request(&public, b"blabla").and_then(|(_, sig)| {
                            let sig = sig.unwrap();
                            debug!("sig = {:?}", &sig[..]);
                            futures::finished(())
                        })
                    })
                })
        ).unwrap();
        agent.kill().unwrap();
        agent.wait().unwrap();
    }

    #[test]
    fn test_client_agent_ed25519() {
        let key = decode_secret_key(ED25519_KEY, Some(b"blabla")).unwrap();
        test_client_agent(&key)
    }

    #[test]
    fn test_client_agent_rsa() {
        let key = decode_secret_key(PKCS8_ENCRYPTED, Some(b"blabla")).unwrap();
        test_client_agent(&key)
    }

    #[test]
    fn test_agent() {
        env_logger::init().unwrap_or(());
        let dir = tempdir::TempDir::new("thrussh").unwrap();
        let agent_path = dir.path().join("agent");
        debug!("agent_path = {:?}", agent_path);

        let mut core = tokio_core::reactor::Core::new().unwrap();

        use agent;
        let h = core.handle();
        let listener = tokio_uds::UnixListener::bind(&agent_path, &h).unwrap().incoming();
        h.spawn(
            agent::server::AgentServer {
                listener,
                keys: agent::server::KeyStore::new(),
                keys: agent::server::KeyStore::new(),
                lock: agent::server::Lock::new(),
                handle: core.handle()
            }.map_err(|e| error!("{:?}", e))
            agent::server::AgentServer::new(listener, core.handle(), ())
                .map_err(|e| error!("{:?}", e))
        );