pijul_org / pijul

Ignoring SSH agent errors (moving to the next possible method)

By blabla on February 28, 2019
This patch is not signed.
9GksLyspV4YQSkVXG1eKB8NHctdgyFhXY3Lhqto2kckBrPhqupVK7Pwo2tia54oyTbhdc8mXDvv2noUqbK7cMeUi
This patch is in the following branches:
latest
master
testing
234
235
236
237
238
239
240
241
242
243


244
245
246
247
                    .sign_request(key, &to_sign)
                    .then(move |result| match result {
                        Ok((client, sig)) => {
                            debug!("sig = {:?}", sig);
                            if let Some(sig) = sig {
                                to_sign.extend_ssh_string(&sig[..]);
                            }
                            self.agent = Some(client);
                            futures::finished::<_, Error>((self, to_sign))
                        }
                        self.agent = Some(client);
                        futures::finished((self, to_sign))
                        Err(e) => {
                            error!("SSH agent error: {:?}", e);
                            futures::finished((self, to_sign))
                        }






















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
            match auth.poll() {
                Ok(Async::Ready(session)) => {
                    if session.is_authenticated() {
                        debug!("is_authenticated!");
                        return Ok(Async::Ready(session));
                    } else if let Some(next) = self.it.next() {
                        self.auth = Some(Either::A(next_auth(session, &self.user, next)))
                    } else {
                        return Ok(Async::Ready(session));
                    }
                Ok(Async::NotReady) => {
                    self.auth = Some(auth);
                    return Ok(Async::NotReady);
                }
                Err(e) => {
                    // Our instance of thrussh::client::Handler
                    // defined in commands::remote doesn't return
                    // errors when it fails to use the
                    // agent. Therefore, this is necessarily an error
                    // from SSH (the remote server has dropped the
                    // connection, for instance).
                    return Err(e)
use dirs;
use error::Error;
use futures::future::Either;
use futures::Future;
use meta;
use rpassword;
use std;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use thrussh::client::{Authenticate, Connection, Handler};
use thrussh::Tcp;
use thrussh_keys;
use tokio::io::{AsyncRead, AsyncWrite};

pub enum AuthAttempt {
    Agent(thrussh_keys::key::PublicKey),
    Key(Arc<thrussh_keys::key::KeyPair>),
    Password(String),
}

#[derive(Debug)]
enum AuthState {
    Agent(KeyPath),
    Key(KeyPath),
    Password,
}

pub struct AuthAttempts {
    state: AuthState,
    local_repo_root: Option<PathBuf>,
    server_name: String,
}

impl AuthAttempts {
    pub fn new(server_name: String, local_repo_root: Option<PathBuf>, use_agent: bool) -> Self {
        AuthAttempts {
            state: if use_agent {
                AuthState::Agent(KeyPath::first())
            } else {
                AuthState::Key(KeyPath::first())
            },
            local_repo_root,
            server_name,
        }
    }
}

#[derive(Debug, Clone, Copy)]
enum KeyLocation {
    Local,
    Pijul,
    Ssh,
}

impl KeyLocation {
    fn next(&self) -> Option<Self> {
        match *self {
            KeyLocation::Local => Some(KeyLocation::Pijul),
            KeyLocation::Pijul => Some(KeyLocation::Ssh),
            KeyLocation::Ssh => None,
        }
    }
}

#[derive(Debug, Clone, Copy)]
enum KeyType {
    Ed25519,
    Rsa,
}

#[derive(Debug, Clone, Copy)]
struct KeyPath {
    location: KeyLocation,
    typ: KeyType,
}

impl KeyPath {
    fn first() -> Self {
        KeyPath {
            location: KeyLocation::Local,
            typ: KeyType::Ed25519,
        }
    }
    fn next(&self) -> Option<KeyPath> {
        match self.typ {
            KeyType::Ed25519 => {
                if let Some(location) = self.location.next() {
                    Some(KeyPath {
                        location,
                        typ: KeyType::Ed25519,
                    })
                } else {
                    Some(KeyPath {
                        location: KeyLocation::Local,
                        typ: KeyType::Rsa,
                    })
                }
            }
            KeyType::Rsa => {
                if let Some(location) = self.location.next() {
                    Some(KeyPath {
                        location,
                        typ: KeyType::Rsa,
                    })
                } else {
                    None
                }
            }
        }
    }
}

impl AuthAttempts {
    fn key_dir(&self, key: &KeyPath) -> Option<PathBuf> {
        match key.location {
            KeyLocation::Local => self.local_repo_root.clone(),
            KeyLocation::Pijul => meta::global_path().ok(),
            KeyLocation::Ssh => {
                if let Some(mut path) = dirs::home_dir() {
                    path.push(".ssh");
                    Some(path)
                } else {
                    None
                }
            }
        }
    }

    fn key(&self, key: &KeyPath) -> Option<PathBuf> {
        self.key_dir(key).map(|mut p| {
            p.push(match key.typ {
                KeyType::Ed25519 => "id_ed25519",
                KeyType::Rsa => "id_rsa",
            });
            p
        })
    }

    fn public_key(&self, key: &KeyPath) -> Option<PathBuf> {
        self.key(key).map(|mut p| {
            p.set_extension("pub");
            p
        })
    }
}

impl Iterator for AuthAttempts {
    type Item = AuthAttempt;
    fn next(&mut self) -> Option<Self::Item> {
        loop {
            debug!("state {:?}", self.state);
            match self.state {
                AuthState::Agent(key_path) => {
                    let path = self.public_key(&key_path);
                    debug!("agent path {:?}", path);
                    if let Some(key_path) = key_path.next() {
                        self.state = AuthState::Agent(key_path)
                    } else {
                        self.state = AuthState::Key(KeyPath::first())
                    }
                    if let Some(path) = path {
                        if let Ok(key) = thrussh_keys::load_public_key(&path) {
                            return Some(AuthAttempt::Agent(key));
                        }
                    }
                }
                AuthState::Key(key_path) => {
                    let path = self.key(&key_path);
                    debug!("path {:?}", path);
                    if let Some(path) = path {
                        if let Some(key_path) = key_path.next() {
                            self.state = AuthState::Key(key_path)
                        } else {
                            self.state = AuthState::Password
                        }
                        if let Ok(key) = load_key_or_ask(&path) {
                            return Some(AuthAttempt::Key(Arc::new(key)));
                        }
                    } else {
                        self.state = AuthState::Password
                    }
                }
                AuthState::Password => {
                    let password = rpassword::prompt_password_stdout(&format!(
                        "Password for {:?}: ",
                        self.server_name
                    ));
                    if let Ok(password) = password {
                        return Some(AuthAttempt::Password(password));
                    }
                }
            }
        }
    }
}

pub fn auth_attempt_future<R: Tcp + AsyncRead + AsyncWrite>(
    co: Connection<R, super::remote::Client>,
    auth_attempts: AuthAttempts,
    user: String,
    add_to_agent: thrussh_config::AddKeysToAgent,
) -> impl Future<Item = Connection<R, super::remote::Client>, Error = Error> {
    super::fold_until::new(
        futures::stream::iter_ok(auth_attempts),
        co,
        move |mut co, attempt| {
            if let AuthAttempt::Key(key) = attempt {
                debug!("not authenticated");
                let agent_constraints = match add_to_agent {
                    thrussh_config::AddKeysToAgent::Yes => Some(&[][..]),
                    thrussh_config::AddKeysToAgent::No => None,
                    thrussh_config::AddKeysToAgent::Confirm => {
                        Some(&[thrussh_keys::agent::Constraint::Confirm][..])
                    }
                    thrussh_config::AddKeysToAgent::Ask => None, // not yet implemented.
                };
                if let Some(cons) = agent_constraints {
                    if let Some(agent) = co.handler_mut().agent.take() {
                        let user = user.clone();
                        return Either::A(agent.add_identity(&key, cons).from_err().and_then(
                            move |(agent, _)| {
                                co.handler_mut().agent = Some(agent);
                                next_auth(co, &user, AuthAttempt::Key(key))
                            },
                        ));
                    }
                }
                Either::B(next_auth(co, &user, AuthAttempt::Key(key)))
            } else {
                Either::B(next_auth(co, &user, attempt))
            }