agentmux_srv/server/
local_session_file.rs1use std::path::{Path, PathBuf};
21use std::time::Duration;
22
23use hmac::{Hmac, Mac};
24use sha2::{Digest, Sha256};
25
26pub(crate) type Digest32 = [u8; 32];
27
28pub(crate) const FILE_NAME: &str = "sessions.bin";
30pub(crate) const SAVE_EVERY: Duration = Duration::from_secs(5 * 60);
33
34const MAGIC: &[u8; 8] = b"AMXSESS1";
35const HEADER_LEN: usize = 8 + 1 + 8 + 4;
36const RECORD_LEN: usize = 32 + 32 + 8 + 8;
37const TRAILER_LEN: usize = 32;
38pub(crate) const MAX_SESSIONS: usize = 4096;
40
41#[derive(Clone)]
43pub(crate) enum KeyBinding {
44 Generated,
45 Provided(Vec<u8>),
46}
47
48impl KeyBinding {
49 fn mode(&self) -> u8 {
50 match self {
51 KeyBinding::Generated => 0,
52 KeyBinding::Provided(_) => 1,
53 }
54 }
55
56 fn check(&self, body: &[u8]) -> Digest32 {
57 match self {
58 KeyBinding::Generated => Sha256::digest(body).into(),
59 KeyBinding::Provided(key) => {
60 let mut m = Hmac::<Sha256>::new_from_slice(key).expect("hmac takes any key length");
61 m.update(b"amx-sessions-file-v1");
62 m.update(body);
63 m.finalize().into_bytes().into()
64 }
65 }
66 }
67}
68
69#[derive(Debug, Clone, PartialEq, Eq)]
71pub(crate) struct Record {
72 pub cookie: Digest32,
73 pub token: Digest32,
74 pub born_secs: u64,
75 pub last_seen_secs: u64,
76}
77
78#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub(crate) enum Refused {
81 TooOpen,
83 Damaged,
86 ClockMovedBack,
88 Inconsistent,
90}
91
92impl Refused {
93 pub(crate) fn why(self) -> &'static str {
94 match self {
95 Refused::TooOpen => "the file or its folder can be opened by someone else",
96 Refused::Damaged => "the file is damaged, or the sign-in key it was made under has changed",
97 Refused::ClockMovedBack => "the clock is earlier than when the file was saved",
98 Refused::Inconsistent => "the file holds a time that cannot be",
99 }
100 }
101}
102
103pub(crate) fn encode(binding: &KeyBinding, saved_secs: u64, records: &[Record]) -> Vec<u8> {
105 let records = &records[..records.len().min(MAX_SESSIONS)];
106 let mut out = Vec::with_capacity(HEADER_LEN + records.len() * RECORD_LEN + TRAILER_LEN);
107 out.extend_from_slice(MAGIC);
108 out.push(binding.mode());
109 out.extend_from_slice(&saved_secs.to_be_bytes());
110 out.extend_from_slice(&(records.len() as u32).to_be_bytes());
111 for r in records {
112 out.extend_from_slice(&r.cookie);
113 out.extend_from_slice(&r.token);
114 out.extend_from_slice(&r.born_secs.to_be_bytes());
115 out.extend_from_slice(&r.last_seen_secs.to_be_bytes());
116 }
117 let check = binding.check(&out);
118 out.extend_from_slice(&check);
119 out
120}
121
122pub(crate) fn decode(binding: &KeyBinding, now_secs: u64, bytes: &[u8]) -> Result<Vec<Record>, Refused> {
124 if bytes.len() < HEADER_LEN + TRAILER_LEN || &bytes[..8] != MAGIC {
125 return Err(Refused::Damaged);
126 }
127 let count = u32::from_be_bytes(bytes[17..21].try_into().expect("four bytes")) as usize;
128 if count > MAX_SESSIONS || bytes.len() != HEADER_LEN + count * RECORD_LEN + TRAILER_LEN {
129 return Err(Refused::Damaged);
130 }
131 let (body, trailer) = bytes.split_at(bytes.len() - TRAILER_LEN);
132 if bytes[8] != binding.mode() || !agentmux_common::secret_eq::secret_eq(&binding.check(body), trailer) {
133 return Err(Refused::Damaged);
134 }
135 let saved = u64::from_be_bytes(bytes[9..17].try_into().expect("eight bytes"));
136 if saved > now_secs {
137 return Err(Refused::ClockMovedBack);
138 }
139 let mut out = Vec::with_capacity(count);
140 for chunk in body[HEADER_LEN..].chunks_exact(RECORD_LEN) {
141 let r = Record {
142 cookie: chunk[..32].try_into().expect("32 bytes"),
143 token: chunk[32..64].try_into().expect("32 bytes"),
144 born_secs: u64::from_be_bytes(chunk[64..72].try_into().expect("eight bytes")),
145 last_seen_secs: u64::from_be_bytes(chunk[72..80].try_into().expect("eight bytes")),
146 };
147 if r.born_secs > r.last_seen_secs || r.last_seen_secs > saved {
148 return Err(Refused::Inconsistent);
149 }
150 out.push(r);
151 }
152 Ok(out)
153}
154
155pub(crate) fn private_enough(path: &Path) -> Result<(), Refused> {
158 #[cfg(windows)]
159 {
160 let folder = path.parent().ok_or(Refused::TooOpen)?;
161 for p in [path, folder] {
162 match agentmux_common::owner_only::others_who_can_open(p) {
163 Ok(others) if others.is_empty() => {}
164 _ => return Err(Refused::TooOpen),
165 }
166 }
167 Ok(())
168 }
169 #[cfg(unix)]
170 {
171 use std::os::unix::fs::PermissionsExt;
172 let file = std::fs::metadata(path).map_err(|_| Refused::TooOpen)?;
173 let folder = std::fs::metadata(path.parent().ok_or(Refused::TooOpen)?).map_err(|_| Refused::TooOpen)?;
174 if file.permissions().mode() & 0o077 != 0 || folder.permissions().mode() & 0o022 != 0 {
176 return Err(Refused::TooOpen);
177 }
178 Ok(())
179 }
180}
181
182pub(crate) fn load(path: &Path, binding: &KeyBinding, now_secs: u64) -> Result<Option<Vec<Record>>, Refused> {
185 let bytes = match std::fs::read(path) {
186 Ok(b) => b,
187 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
188 Err(_) => {
189 let _ = clear(path, binding, now_secs);
190 return Err(Refused::TooOpen);
191 }
192 };
193 let result = private_enough(path).and_then(|()| decode(binding, now_secs, &bytes));
194 if result.is_err() {
195 let _ = clear(path, binding, now_secs);
196 }
197 result.map(Some)
198}
199
200pub(crate) fn save(path: &Path, binding: &KeyBinding, saved_secs: u64, records: &[Record]) -> std::io::Result<()> {
203 let folder = path.parent().ok_or_else(|| std::io::Error::other("the sessions file has no folder"))?;
204 let mut tmp: PathBuf = folder.to_path_buf();
205 tmp.push(format!(".{FILE_NAME}.{}.tmp", std::process::id()));
206 let _ = std::fs::remove_file(&tmp);
207 let mut opts = std::fs::OpenOptions::new();
208 opts.write(true).create_new(true);
209 #[cfg(unix)]
210 {
211 use std::os::unix::fs::OpenOptionsExt;
212 opts.mode(0o600);
213 }
214 use std::io::Write;
215 let written = opts.open(&tmp).and_then(|mut f| {
216 f.write_all(&encode(binding, saved_secs, records))?;
217 f.sync_all()
218 });
219 #[cfg(windows)]
220 let written = written.and_then(|()| agentmux_common::owner_only::restrict_to_user(&tmp).map_err(std::io::Error::other));
221 let renamed = written.and_then(|()| std::fs::rename(&tmp, path));
222 if renamed.is_err() {
223 let _ = std::fs::remove_file(&tmp);
224 }
225 renamed
226}
227
228pub(crate) fn clear(path: &Path, binding: &KeyBinding, now_secs: u64) -> std::io::Result<()> {
232 match std::fs::remove_file(path) {
233 Ok(()) => Ok(()),
234 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
235 Err(_) => save(path, binding, now_secs, &[]),
236 }
237}
238
239#[cfg(test)]
240#[path = "tests/local_session_file_tests.rs"]
241mod tests;