1use crate::cmd;
2use crate::environment::get_uid;
3use anyhow::anyhow;
4use anyhow::Result;
5use log::{debug, info};
6use ssh_agent_client_rs::Identity;
7use ssh_agent_client_rs::Identity::{Certificate, PublicKey};
8use ssh_key::public::KeyData;
9use ssh_key::AuthorizedKeys;
10use std::collections::HashSet;
11use std::fs;
12use std::path::Path;
13use std::time::Duration;
14use uzers::uid_t;
15
16pub struct IdentityFilter {
20 keys: HashSet<KeyData>,
21 ca_keys: HashSet<KeyData>,
22}
23
24impl IdentityFilter {
25 pub fn new(
29 authorized_keys_file: &Path,
30 ca_keys_file: Option<&Path>,
31 authorized_keys_command: Option<&str>,
32 authorized_keys_command_user: Option<&str>,
33 calling_user: &str,
34 ) -> Result<Self> {
35 let mut identities = Vec::new();
36 if authorized_keys_file.exists() {
37 identities.extend(from_file(authorized_keys_file, false)?);
38 } else if ca_keys_file.is_none() && authorized_keys_command.is_none() {
39 info!("No valid keys for authentication, {authorized_keys_file:?} does not exist");
40 }
41
42 if let Some(ca_keys_file) = ca_keys_file {
43 identities.extend(from_file(ca_keys_file, true)?);
44 }
45
46 if let Some(cmd) = authorized_keys_command {
47 let user = authorized_keys_command_user.map(get_uid).transpose()?;
48 identities.extend(from_command(cmd, user, calling_user)?);
49 }
50 Self::from(identities)
51 }
52
53 pub fn from_authorized_file(authorized_keys_file: &Path) -> Result<Self> {
54 Self::new(authorized_keys_file, None, None, None, "")
55 }
56
57 fn from(authorized: Vec<Authorized>) -> Result<Self> {
58 let mut keys: HashSet<KeyData> = HashSet::new();
59 let mut ca_keys: HashSet<KeyData> = HashSet::new();
60
61 for item in authorized {
62 match item {
63 Authorized::Key(key) => keys.insert(key),
64 Authorized::CAKey(ca_key) => ca_keys.insert(ca_key),
65 };
66 }
67
68 Ok(Self { keys, ca_keys })
69 }
70
71 pub fn filter(&self, identity: &Identity) -> bool {
75 match identity {
76 PublicKey(key) => {
77 if self.keys.contains(key.key_data()) {
78 debug!(
79 "found a matching key: {}",
80 key.fingerprint(Default::default())
81 );
82 return true;
83 }
84 }
85 Certificate(cert) => {
86 let ca_key = cert.signature_key();
87 if self.ca_keys.contains(ca_key) {
88 debug!(
89 "found a matching cert-authority key: {}",
90 ca_key.fingerprint(Default::default())
91 );
92 return true;
93 }
94 }
95 }
96 false
97 }
98}
99
100enum Authorized {
101 Key(KeyData),
102 CAKey(KeyData),
103}
104
105fn from_command(command: &str, uid: Option<uid_t>, arg: &str) -> Result<Vec<Authorized>> {
106 debug!("Invoking command '{command} {arg}' to obtain public keys for user {arg}");
107 let buf = cmd::run(&[command, arg], Duration::from_secs(10), uid)?;
108 from_str(&buf, &format!("{command}:(output):"), false)
109}
110
111fn from_file(filename: &Path, ca_keys: bool) -> Result<Vec<Authorized>> {
112 let contents = fs::read_to_string(filename)?;
113 from_str(
114 &contents,
115 filename.to_str().ok_or(anyhow!("invalid filename"))?,
116 ca_keys,
117 )
118}
119
120fn from_str(buf: &str, what: &str, ca_keys: bool) -> Result<Vec<Authorized>> {
121 let keys: AuthorizedKeys = AuthorizedKeys::new(buf);
122 let iter = keys.enumerate().filter_map(move |(i, ak)| match ak {
123 Ok(entry) => {
124 let key_data = entry.public_key().key_data().to_owned();
125 if !ca_keys && !entry.config_opts().iter().any(|o| o == "cert-authority") {
126 return Some(Authorized::Key(key_data));
127 }
128 Some(Authorized::CAKey(key_data))
129 }
130 Err(e) => {
131 info!("Failed to parse line {what}:{i}': {e}");
132 None
133 }
134 });
135 Ok(iter.collect())
136}
137
138#[cfg(test)]
139mod tests {
140 use crate::filter::IdentityFilter;
141 use crate::test::{data, CERT_STR};
142 use ssh_agent_client_rs::Identity;
143 use ssh_key::{Certificate, PublicKey};
144 use std::path::Path;
145
146 #[test]
147 fn test_read_public_keys() -> anyhow::Result<()> {
148 let path = Path::new(data!("authorized_keys"));
149
150 let filter = IdentityFilter::from_authorized_file(path)?;
151
152 let cert = Certificate::from_openssh(CERT_STR)?;
154 let identity: Identity = cert.into();
155 assert!(filter.filter(&identity));
156
157 let filter = IdentityFilter::new(
160 Path::new("/dev/null"),
162 Some(Path::new(data!("ca_key.pub"))),
163 None,
164 None,
165 "",
166 )?;
167 assert!(filter.filter(&identity));
168
169 let filter = IdentityFilter::new(
171 Path::new("/does/not/exist"),
173 Some(Path::new(data!("ca_key.pub"))),
174 None,
175 None,
176 "",
177 )?;
178 assert!(filter.filter(&identity));
179
180 let filter = IdentityFilter::new(
181 Path::new("/dev/null"),
182 None,
183 Some(data!("test.sh")),
184 None,
185 "user",
186 )?;
187 let identity: Identity =
188 PublicKey::from_openssh(include_str!(data!("id_ed25519.pub")))?.into();
189 assert!(filter.filter(&identity));
190
191 let Err(e) = IdentityFilter::new(
193 Path::new("/dev/null"),
194 None,
195 Some(data!("test.sh")),
196 None,
197 "not_user",
198 ) else {
199 panic!("test.sh should have failed");
200 };
201 assert!(format!("{:?}", e).contains("Non-zero exit status"));
202
203 Ok(())
204 }
205}