forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.4 MiBe587be7Tahinli11 hours ago323 commits

server.rs569 lines, 16.8 KiBHistoryRawDownload
1use std::borrow::Cow;
2use std::collections::HashMap;
3use std::fs::OpenOptions;
4use std::io::{self, Write};
5use std::net::SocketAddr;
6use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
7use std::os::unix::process::ExitStatusExt;
8use std::path::{Path, PathBuf};
9use std::process::ExitStatus;
10use std::sync::Arc;
11use std::sync::atomic::{AtomicBool, Ordering};
12use std::time::Duration;
13
14use bytes::Bytes;
15use russh::keys::ssh_key::LineEnding;
16use russh::keys::ssh_key::private::{Ed25519Keypair, KeypairData};
17use russh::keys::{Algorithm, EcdsaCurve, PrivateKey, PublicKey};
18use russh::server::{
19 Auth, Config, Handle, Handler, Msg, PublicKeyOffer, Session, VerifiedPublicKey, run_stream,
20};
21use russh::{Channel, ChannelId, ChannelOpenFailure, Disconnect, MethodKind, MethodSet, Preferred};
22use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt};
23use tokio::net::TcpListener;
24use tokio::process::{Child, ChildStdin};
25use tokio::sync::{Notify, Semaphore, mpsc};
26
27use crate::backend::GitBackend;
28use crate::error::{Error, Result};
29use crate::parse::{LFS_AUTHENTICATE_PREFIX, parse_exec, parse_lfs_authenticate};
30
31const PUMP_CHUNK: usize = 32 * 1024;
32const STDIN_QUEUE: usize = 8;
33const MAX_AUTH_ATTEMPTS: usize = 6;
34const MAX_CONNECTIONS: usize = 256;
35const AUTH_TIMEOUT: Duration = Duration::from_secs(30);
36const INACTIVITY_TIMEOUT: Duration = Duration::from_secs(10 * 60);
37
38#[derive(Debug, Clone)]
39pub struct SshConfig {
40 pub listen: SocketAddr,
41 pub host_key_path: PathBuf,
42 pub auth_rejection_time: Duration,
43}
44
45pub async fn run<B: GitBackend>(config: SshConfig, backend: Arc<B>) -> Result<()> {
46 let host_key = load_or_create_host_key(&config.host_key_path)?;
47 let russh_config = Arc::new(Config {
48 keys: vec![host_key],
49 methods: publickey_only(),
50 auth_rejection_time: config.auth_rejection_time,
51 max_auth_attempts: MAX_AUTH_ATTEMPTS,
52 inactivity_timeout: Some(INACTIVITY_TIMEOUT),
53 preferred: preferred_algorithms(),
54 ..Config::default()
55 });
56
57 let listener = TcpListener::bind(config.listen).await?;
58 tracing::info!(addr = %config.listen, "ssh server listening");
59
60 let connection_slots = Arc::new(Semaphore::new(MAX_CONNECTIONS));
61 loop {
62 let (stream, peer) = match listener.accept().await {
63 Ok(v) => v,
64 Err(e) => {
65 tracing::warn!(error = %e, "ssh accept failed");
66 tokio::time::sleep(Duration::from_millis(100)).await;
67 continue;
68 }
69 };
70 let Ok(permit) = connection_slots.clone().try_acquire_owned() else {
71 tracing::warn!(%peer, "ssh connection limit reached, dropping connection");
72 continue;
73 };
74 let authed = Arc::new(AtomicBool::new(false));
75 let client = Client {
76 backend: Arc::clone(&backend),
77 peer,
78 authed: Arc::clone(&authed),
79 user_id: None,
80 git_protocol: None,
81 channels: HashMap::new(),
82 };
83 let russh_config = Arc::clone(&russh_config);
84 tokio::spawn(async move {
85 let _permit = permit;
86 let running = match tokio::time::timeout(
87 AUTH_TIMEOUT,
88 run_stream(russh_config, stream, client),
89 )
90 .await
91 {
92 Ok(Ok(running)) => running,
93 Ok(Err(e)) => {
94 tracing::debug!(%peer, error = %e, "ssh handshake failed");
95 return;
96 }
97 Err(_) => {
98 tracing::debug!(%peer, "ssh handshake timed out");
99 return;
100 }
101 };
102 let handle = running.handle();
103 tokio::spawn(async move {
104 tokio::time::sleep(AUTH_TIMEOUT).await;
105 if !authed.load(Ordering::Acquire) {
106 let _ = handle
107 .disconnect(
108 Disconnect::ByApplication,
109 "authentication timeout".into(),
110 String::new(),
111 )
112 .await;
113 }
114 });
115 if let Err(e) = running.await {
116 tracing::debug!(%peer, error = %e, "ssh session ended with error");
117 }
118 });
119 }
120}
121
122fn publickey_only() -> MethodSet {
123 let mut methods = MethodSet::empty();
124 methods.push(MethodKind::PublicKey);
125 methods
126}
127
128fn preferred_algorithms() -> Preferred {
129 Preferred {
130 key: Cow::Owned(vec![
131 Algorithm::Ed25519,
132 Algorithm::SkEd25519,
133 Algorithm::SkEcdsaSha2NistP256,
134 Algorithm::Ecdsa {
135 curve: EcdsaCurve::NistP256,
136 },
137 Algorithm::Ecdsa {
138 curve: EcdsaCurve::NistP384,
139 },
140 Algorithm::Ecdsa {
141 curve: EcdsaCurve::NistP521,
142 },
143 ]),
144 ..Preferred::default()
145 }
146}
147
148fn key_type_allowed(algorithm: &Algorithm) -> bool {
149 matches!(
150 algorithm,
151 Algorithm::Ed25519
152 | Algorithm::SkEd25519
153 | Algorithm::SkEcdsaSha2NistP256
154 | Algorithm::Ecdsa { .. }
155 )
156}
157
158fn valid_git_protocol(value: &str) -> bool {
159 let bytes = value.as_bytes();
160 bytes.len() == 9 && value.starts_with("version=") && bytes[8].is_ascii_digit()
161}
162
163fn load_or_create_host_key(path: &Path) -> Result<PrivateKey> {
164 if path.exists() {
165 let key = PrivateKey::read_openssh_file(path)
166 .map_err(|e| Error::Ssh(format!("host key: {e}")))?;
167 if key.algorithm() != Algorithm::Ed25519 {
168 return Err(Error::Ssh("host key must be ed25519".into()));
169 }
170 return Ok(key);
171 }
172
173 let mut seed = [0u8; 32];
174 getrandom::fill(&mut seed).map_err(|e| Error::Ssh(format!("host key entropy: {e}")))?;
175 let key = PrivateKey::new(KeypairData::Ed25519(Ed25519Keypair::from_seed(&seed)), "")
176 .map_err(|e| Error::Ssh(format!("host key generation: {e}")))?;
177 let pem = key
178 .to_openssh(LineEnding::LF)
179 .map_err(|e| Error::Ssh(format!("host key encoding: {e}")))?;
180
181 if let Some(parent) = path.parent() {
182 std::fs::create_dir_all(parent)?;
183 }
184 let mut file = OpenOptions::new()
185 .write(true)
186 .create_new(true)
187 .mode(0o600)
188 .open(path)?;
189 file.write_all(pem.as_bytes())?;
190 file.sync_all()?;
191 std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
192 tracing::info!(path = %path.display(), "generated ssh host key");
193 Ok(key)
194}
195
196struct Client<B> {
197 backend: Arc<B>,
198 peer: SocketAddr,
199 authed: Arc<AtomicBool>,
200 user_id: Option<String>,
201 git_protocol: Option<String>,
202 channels: HashMap<ChannelId, mpsc::Sender<Bytes>>,
203}
204
205impl<B: GitBackend> Client<B> {
206 async fn lookup(&self, key: &PublicKey) -> Option<String> {
207 if !key_type_allowed(&key.algorithm()) {
208 return None;
209 }
210 let blob = key.to_bytes().ok()?;
211 self.backend
212 .authenticate_key(key.algorithm().as_str(), &blob)
213 .await
214 }
215
216 async fn exec_lfs_authenticate(
217 &self,
218 session: &mut Session,
219 channel: ChannelId,
220 user_id: &str,
221 command: &str,
222 ) -> std::result::Result<(), russh::Error> {
223 let (path, operation) = match parse_lfs_authenticate(command) {
224 Ok(parsed) => parsed,
225 Err(e) => return reject_exec(session, channel, &e.to_string()),
226 };
227 let reply = match self
228 .backend
229 .lfs_authenticate(user_id, &path, operation)
230 .await
231 {
232 Ok(reply) => reply,
233 Err(msg) => return reject_exec(session, channel, &msg),
234 };
235 session.channel_success(channel)?;
236 session.data(channel, reply)?;
237 session.exit_status_request(channel, 0)?;
238 session.eof(channel)?;
239 session.close(channel)?;
240 Ok(())
241 }
242}
243
244impl<B: GitBackend> Handler for Client<B> {
245 type Error = russh::Error;
246
247 async fn auth_publickey_offered(
248 &mut self,
249 _user: &str,
250 offer: PublicKeyOffer<'_>,
251 ) -> std::result::Result<Auth, Self::Error> {
252 if self.lookup(offer.public_key).await.is_some() {
253 Ok(Auth::Accept)
254 } else {
255 Ok(Auth::reject())
256 }
257 }
258
259 async fn auth_publickey(
260 &mut self,
261 _user: &str,
262 verified: VerifiedPublicKey<'_>,
263 ) -> std::result::Result<Auth, Self::Error> {
264 match self.lookup(verified.public_key).await {
265 Some(user_id) => {
266 tracing::info!(peer = %self.peer, %user_id, "ssh publickey auth accepted");
267 self.user_id = Some(user_id);
268 self.authed.store(true, Ordering::Release);
269 Ok(Auth::Accept)
270 }
271 None => Ok(Auth::reject()),
272 }
273 }
274
275 async fn channel_open_session(
276 &mut self,
277 _channel: Channel<Msg>,
278 reply: russh::server::ChannelOpenHandle,
279 _session: &mut Session,
280 ) -> std::result::Result<(), Self::Error> {
281 if self.user_id.is_none() {
282 reply
283 .reject(ChannelOpenFailure::AdministrativelyProhibited)
284 .await;
285 } else {
286 reply.accept().await;
287 }
288 Ok(())
289 }
290
291 async fn env_request(
292 &mut self,
293 _channel: ChannelId,
294 variable_name: &str,
295 variable_value: &str,
296 _session: &mut Session,
297 ) -> std::result::Result<(), Self::Error> {
298 if variable_name == "GIT_PROTOCOL" && valid_git_protocol(variable_value) {
299 self.git_protocol = Some(variable_value.to_owned());
300 }
301 Ok(())
302 }
303
304 async fn exec_request(
305 &mut self,
306 channel: ChannelId,
307 data: &[u8],
308 session: &mut Session,
309 ) -> std::result::Result<(), Self::Error> {
310 if self.channels.contains_key(&channel) {
311 session.channel_failure(channel)?;
312 return Ok(());
313 }
314 let Some(user_id) = self.user_id.clone() else {
315 session.channel_failure(channel)?;
316 return Ok(());
317 };
318 let command = match std::str::from_utf8(data) {
319 Ok(command) => command,
320 Err(_) => return reject_exec(session, channel, "invalid command"),
321 };
322 if command.starts_with(LFS_AUTHENTICATE_PREFIX) {
323 return self
324 .exec_lfs_authenticate(session, channel, &user_id, command)
325 .await;
326 }
327 let (service, path) = match parse_exec(command) {
328 Ok(parsed) => parsed,
329 Err(e) => return reject_exec(session, channel, &e.to_string()),
330 };
331
332 let mut cmd = match self
333 .backend
334 .prepare(&user_id, service, &path, self.git_protocol.as_deref())
335 .await
336 {
337 Ok(cmd) => cmd,
338 Err(msg) => return reject_exec(session, channel, &msg),
339 };
340 cmd.stdin(std::process::Stdio::piped())
341 .stdout(std::process::Stdio::piped())
342 .stderr(std::process::Stdio::piped())
343 .kill_on_drop(true);
344
345 let child = match cmd.spawn() {
346 Ok(child) => child,
347 Err(e) => {
348 tracing::error!(error = %e, "failed to spawn git");
349 return reject_exec(session, channel, "failed to start git");
350 }
351 };
352
353 session.channel_success(channel)?;
354 let (tx, rx) = mpsc::channel(STDIN_QUEUE);
355 self.channels.insert(channel, tx);
356 tokio::spawn(run_child(session.handle(), channel, child, rx));
357 Ok(())
358 }
359
360 async fn data(
361 &mut self,
362 channel: ChannelId,
363 data: &[u8],
364 _session: &mut Session,
365 ) -> std::result::Result<(), Self::Error> {
366 if let Some(tx) = self.channels.get(&channel) {
367 let _ = tx.send(Bytes::copy_from_slice(data)).await;
368 }
369 Ok(())
370 }
371
372 async fn channel_eof(
373 &mut self,
374 channel: ChannelId,
375 _session: &mut Session,
376 ) -> std::result::Result<(), Self::Error> {
377 self.channels.remove(&channel);
378 Ok(())
379 }
380
381 async fn channel_close(
382 &mut self,
383 channel: ChannelId,
384 _session: &mut Session,
385 ) -> std::result::Result<(), Self::Error> {
386 self.channels.remove(&channel);
387 Ok(())
388 }
389
390 async fn pty_request(
391 &mut self,
392 channel: ChannelId,
393 _term: &str,
394 _col_width: u32,
395 _row_height: u32,
396 _pix_width: u32,
397 _pix_height: u32,
398 _modes: &[(russh::Pty, u32)],
399 session: &mut Session,
400 ) -> std::result::Result<(), Self::Error> {
401 session.channel_failure(channel)?;
402 Ok(())
403 }
404
405 async fn shell_request(
406 &mut self,
407 channel: ChannelId,
408 session: &mut Session,
409 ) -> std::result::Result<(), Self::Error> {
410 session.channel_failure(channel)?;
411 Ok(())
412 }
413
414 async fn subsystem_request(
415 &mut self,
416 channel: ChannelId,
417 _name: &str,
418 session: &mut Session,
419 ) -> std::result::Result<(), Self::Error> {
420 session.channel_failure(channel)?;
421 Ok(())
422 }
423
424 async fn x11_request(
425 &mut self,
426 channel: ChannelId,
427 _single_connection: bool,
428 _x11_auth_protocol: &str,
429 _x11_auth_cookie: &str,
430 _x11_screen_number: u32,
431 session: &mut Session,
432 ) -> std::result::Result<(), Self::Error> {
433 session.channel_failure(channel)?;
434 Ok(())
435 }
436}
437
438fn reject_exec(
439 session: &mut Session,
440 channel: ChannelId,
441 msg: &str,
442) -> std::result::Result<(), russh::Error> {
443 session.channel_success(channel)?;
444 session.extended_data(channel, 1, format!("{msg}\n"))?;
445 session.exit_status_request(channel, 1)?;
446 session.eof(channel)?;
447 session.close(channel)?;
448 Ok(())
449}
450
451async fn run_child(
452 handle: Handle,
453 channel: ChannelId,
454 mut child: Child,
455 stdin_rx: mpsc::Receiver<Bytes>,
456) {
457 let abort = Arc::new(Notify::new());
458 let (Some(stdin), Some(stdout), Some(stderr)) =
459 (child.stdin.take(), child.stdout.take(), child.stderr.take())
460 else {
461 return;
462 };
463
464 let feeder = tokio::spawn(feed_stdin(stdin, stdin_rx));
465 let stdout_task = tokio::spawn(pump(
466 stdout,
467 handle.clone(),
468 channel,
469 None,
470 Arc::clone(&abort),
471 ));
472 let stderr_task = tokio::spawn(pump(
473 stderr,
474 handle.clone(),
475 channel,
476 Some(1),
477 Arc::clone(&abort),
478 ));
479
480 let status = tokio::select! {
481 status = child.wait() => status,
482 () = abort.notified() => {
483 let _ = child.start_kill();
484 child.wait().await
485 }
486 };
487
488 let _ = stdout_task.await;
489 let _ = stderr_task.await;
490 feeder.abort();
491
492 let _ = handle.exit_status_request(channel, exit_code(status)).await;
493 let _ = handle.eof(channel).await;
494 let _ = handle.close(channel).await;
495}
496
497async fn feed_stdin(mut stdin: ChildStdin, mut rx: mpsc::Receiver<Bytes>) {
498 while let Some(chunk) = rx.recv().await {
499 if stdin.write_all(&chunk).await.is_err() {
500 break;
501 }
502 }
503 let _ = stdin.shutdown().await;
504}
505
506async fn pump<R>(
507 mut reader: R,
508 handle: Handle,
509 channel: ChannelId,
510 ext: Option<u32>,
511 abort: Arc<Notify>,
512) where
513 R: AsyncRead + Unpin + Send + 'static,
514{
515 let mut buf = vec![0u8; PUMP_CHUNK];
516 loop {
517 let n = match reader.read(&mut buf).await {
518 Ok(0) | Err(_) => break,
519 Ok(n) => n,
520 };
521 let chunk = Bytes::copy_from_slice(&buf[..n]);
522 let sent = match ext {
523 None => handle.data(channel, chunk).await.is_ok(),
524 Some(kind) => handle.extended_data(channel, kind, chunk).await.is_ok(),
525 };
526 if !sent {
527 abort.notify_one();
528 break;
529 }
530 }
531}
532
533fn exit_code(status: io::Result<ExitStatus>) -> u32 {
534 match status {
535 Ok(status) => status
536 .code()
537 .and_then(|c| u32::try_from(c).ok())
538 .or_else(|| {
539 status
540 .signal()
541 .map(|sig| 128 + u32::try_from(sig).unwrap_or(0))
542 })
543 .unwrap_or(1),
544 Err(_) => 1,
545 }
546}
547
548#[cfg(test)]
549mod tests {
550 use super::*;
551
552 #[test]
553 fn git_protocol_is_strict() {
554 assert!(valid_git_protocol("version=2"));
555 assert!(valid_git_protocol("version=1"));
556 assert!(!valid_git_protocol("version=10"));
557 assert!(!valid_git_protocol("version=x"));
558 assert!(!valid_git_protocol("version=2\n"));
559 assert!(!valid_git_protocol("version=2;x"));
560 assert!(!valid_git_protocol(""));
561 }
562
563 #[test]
564 fn key_types_exclude_dsa_and_rsa() {
565 assert!(key_type_allowed(&Algorithm::Ed25519));
566 assert!(!key_type_allowed(&Algorithm::Rsa { hash: None }));
567 assert!(!key_type_allowed(&Algorithm::Dsa));
568 }
569}