fix: parse GlobalKnownHostsFile from ssh_config instead of hardcoding #55
+42
-4
@@ -649,7 +649,39 @@ fn ssh_callbacks(key_path: &Path) -> git2::RemoteCallbacks<'static> {
|
|||||||
callbacks
|
callbacks
|
||||||
}
|
}
|
||||||
|
|
||||||
const KNOWN_HOSTS_PATH: &str = "/etc/ssh/ssh_known_hosts";
|
static KNOWN_HOSTS_FILES: std::sync::OnceLock<Vec<std::path::PathBuf>> = std::sync::OnceLock::new();
|
||||||
|
|
||||||
|
fn get_known_hosts_files() -> &'static Vec<std::path::PathBuf> {
|
||||||
|
KNOWN_HOSTS_FILES.get_or_init(|| {
|
||||||
|
parse_known_hosts_files_from_ssh_config()
|
||||||
|
.unwrap_or_else(|| vec![std::path::PathBuf::from("/etc/ssh/ssh_known_hosts")])
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_known_hosts_files_from_ssh_config() -> Option<Vec<std::path::PathBuf>> {
|
||||||
|
let contents = fs::read_to_string("/etc/ssh/ssh_config").ok()?;
|
||||||
|
|
||||||
|
for line in contents.lines() {
|
||||||
|
let line = line.trim();
|
||||||
|
if line.is_empty() || line.starts_with('#') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut parts = line.split_whitespace();
|
||||||
|
let Some(keyword) = parts.next() else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
|
||||||
|
if keyword.eq_ignore_ascii_case("GlobalKnownHostsFile") {
|
||||||
|
let paths: Vec<std::path::PathBuf> = parts.map(std::path::PathBuf::from).collect();
|
||||||
|
if !paths.is_empty() {
|
||||||
|
return Some(paths);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
fn check_known_hosts(
|
fn check_known_hosts(
|
||||||
cert: &git2::cert::Cert<'_>,
|
cert: &git2::cert::Cert<'_>,
|
||||||
@@ -665,8 +697,13 @@ fn check_known_hosts(
|
|||||||
.hostkey()
|
.hostkey()
|
||||||
.ok_or_else(|| git2::Error::from_str("no host key data"))?;
|
.ok_or_else(|| git2::Error::from_str("no host key data"))?;
|
||||||
|
|
||||||
let contents = fs::read_to_string(KNOWN_HOSTS_PATH)
|
let known_hosts_files = get_known_hosts_files();
|
||||||
.map_err(|e| git2::Error::from_str(&format!("failed to read {KNOWN_HOSTS_PATH}: {e}")))?;
|
|
||||||
|
for known_hosts_path in known_hosts_files {
|
||||||
|
let contents = match fs::read_to_string(known_hosts_path) {
|
||||||
|
Ok(c) => c,
|
||||||
|
Err(_) => continue,
|
||||||
|
};
|
||||||
|
|
||||||
for line in contents.lines() {
|
for line in contents.lines() {
|
||||||
let line = line.trim();
|
let line = line.trim();
|
||||||
@@ -695,9 +732,10 @@ fn check_known_hosts(
|
|||||||
return Ok(git2::CertificateCheckStatus::CertificateOk);
|
return Ok(git2::CertificateCheckStatus::CertificateOk);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Err(git2::Error::from_str(&format!(
|
Err(git2::Error::from_str(&format!(
|
||||||
"host key for {host} not found in {KNOWN_HOSTS_PATH}"
|
"host key for {host} not found in known hosts files"
|
||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user