-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
10 changed files
with
223 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,175 @@ | ||
#[allow(unused_imports)] | ||
use log::{debug, error, info, log, trace, warn}; | ||
|
||
use std::fs::{File, OpenOptions}; | ||
use std::path::{Path, PathBuf}; | ||
use std::io::{BufRead, Write}; | ||
use std::io; | ||
|
||
use snafu::prelude::*; | ||
|
||
use crate::*; | ||
use sunset::packets::PubKey; | ||
|
||
type OpenSSHKey = ssh_key::PublicKey; | ||
|
||
#[derive(Snafu, Debug)] | ||
#[snafu(context(suffix(false)))] | ||
pub enum KnownHostsError { | ||
/// Host Key Mismatch | ||
Mismatch { path: PathBuf, line: usize, existing: OpenSSHKey }, | ||
|
||
/// New Host Key | ||
NewHost { new_key: OpenSSHKey }, | ||
|
||
/// User didn't accept new key | ||
NotAccepted, | ||
|
||
/// Failure | ||
Failure { | ||
// The | ||
// .map_err(|e| Box::new(e) as _).context(Failure)?; | ||
// syntax is ugly, perhaps there's a better way | ||
source: Box<dyn std::error::Error> | ||
}, | ||
|
||
#[snafu(display("{msg}"))] | ||
Other { msg: String }, | ||
} | ||
|
||
const USER_KNOWN_HOSTS: &str = &".ssh/known_hosts"; | ||
|
||
fn user_known_hosts() -> Result<PathBuf, KnownHostsError> { | ||
// home_dir() works fine on linux. | ||
#[allow(deprecated)] | ||
let p = std::env::home_dir().ok_or_else(|| KnownHostsError::Other { | ||
msg: "Failed getting home directory".into(), | ||
})?; | ||
Ok(p.join(USER_KNOWN_HOSTS)) | ||
} | ||
|
||
pub fn check_known_hosts( | ||
host: &str, | ||
port: u16, | ||
key: &PubKey, | ||
) -> Result<(), KnownHostsError> { | ||
let p = user_known_hosts()?; | ||
check_known_hosts_file(host, port, key, &p) | ||
} | ||
|
||
/// Returns a `(host, key)` entry from a known_hosts line, or `None` if not matching | ||
fn line_entry(line: &str) -> Option<(String, String)> { | ||
line.split_once(' ').map(|(h, k)| (h.into(), k.into())) | ||
} | ||
|
||
/// Returns the host string. Non-22 ports are appended. | ||
fn host_part(host: &str, port: u16) -> String { | ||
let mut host = host.to_lowercase(); | ||
if port != sunset::sshnames::SSH_PORT { | ||
host = format!("[{host}]:{port}"); | ||
} | ||
host | ||
} | ||
|
||
pub fn check_known_hosts_file( | ||
host: &str, | ||
port: u16, | ||
key: &PubKey, | ||
p: &Path, | ||
) -> Result<(), KnownHostsError> { | ||
let f = File::open(p) | ||
.map_err(|e| Box::new(e) as _).context(Failure)?; | ||
let f = io::BufReader::new(f); | ||
|
||
let match_host = host_part(host, port); | ||
|
||
let pubk: OpenSSHKey = key.try_into() | ||
.map_err(|e| Box::new(e) as _).context(Failure)?; | ||
|
||
for (line, (lh, lk)) in f.lines().enumerate() | ||
.filter_map(|(num, l)| { | ||
if let Ok(l) = l { | ||
line_entry(&l).map(|entry| (num, entry)) | ||
} else { | ||
None | ||
} | ||
}) { | ||
let line = line + 1; | ||
|
||
if lh != match_host { | ||
continue; | ||
} | ||
|
||
let known_key = OpenSSHKey::from_openssh(&lk).map_err(|_| { | ||
KnownHostsError::Other { msg: format!("Bad key format {}:{}", p.display(), line) } | ||
})?; | ||
|
||
if pubk.algorithm() != known_key.algorithm() { | ||
debug!("Line {line}, Ignoring other-format existing key {known_key:?}") | ||
} else { | ||
if pubk.key_data() == known_key.key_data() { | ||
debug!("Line {line}, found matching key"); | ||
return Ok(()) | ||
} else { | ||
let fp = known_key.fingerprint(Default::default()); | ||
println!("\nHost key mismatch for {match_host} in ~/.ssh/known_hosts line {line}\n\ | ||
Existing key has fingerprint {fp}\n"); | ||
return Err(KnownHostsError::Mismatch { path: p.to_path_buf(), line, existing: known_key }); | ||
} | ||
} | ||
} | ||
|
||
// no match, maybe add it | ||
ask_to_confirm(host, port, key, p) | ||
} | ||
|
||
fn ask_to_confirm( | ||
host: &str, | ||
port: u16, | ||
key: &PubKey, | ||
p: &Path, | ||
) -> Result<(), KnownHostsError> { | ||
|
||
let k: OpenSSHKey = key.try_into().map_err(|e| Box::new(e) as _).context(Failure)?; | ||
let fp = k.fingerprint(Default::default()); | ||
let h = host_part(host, port); | ||
println!("\nHost {h} is not in ~/.ssh/known_hosts\nFingerprint {fp}\nDo you want to continue connecting? (y/n)"); | ||
|
||
let mut resp = String::new(); | ||
io::stdin().read_line(&mut resp) | ||
.map_err(|e| Box::new(e) as _).context(Failure)?; | ||
|
||
resp.make_ascii_lowercase(); | ||
if resp.starts_with('y') { | ||
add_key(host, port, key, p) | ||
} else { | ||
Err(KnownHostsError::NotAccepted) | ||
} | ||
} | ||
|
||
fn add_key( | ||
host: &str, | ||
port: u16, | ||
key: &PubKey, | ||
p: &Path, | ||
) -> Result<(), KnownHostsError> { | ||
|
||
let k: OpenSSHKey = key.try_into() | ||
.map_err(|e| Box::new(e) as _).context(Failure)?; | ||
// encode it | ||
let k = k.to_openssh() | ||
.map_err(|e| Box::new(e) as _).context(Failure)?; | ||
|
||
let h = host_part(host, port); | ||
|
||
let entry = format!("{h} {k}\n"); | ||
|
||
let mut f = std::fs::OpenOptions::new().append(true).open(p) | ||
.map_err(|e| Box::new(e) as _).context(Failure)?; | ||
|
||
f.write_all(entry.as_bytes()) | ||
.map_err(|e| Box::new(e) as _).context(Failure)?; | ||
|
||
Ok(()) | ||
} | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,6 +5,7 @@ | |
|
||
mod pty; | ||
mod cmdline_client; | ||
mod known_hosts; | ||
|
||
#[cfg(unix)] | ||
mod fdio; | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -67,3 +67,5 @@ pub enum ChanFail { | |
SSH_OPEN_RESOURCE_SHORTAGE = 4, | ||
} | ||
|
||
pub const SSH_PORT: u16 = 22; | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters