forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.5 MiB8e56ffcTahinli1 month ago262 commits

server.rs616 lines, 19.8 KiBHistoryRawDownload
1//! russh server: host key, pubkey auth, exec and env handling, piping, timeouts.
2
3use std::borrow::Cow;
4use std::collections::HashMap;
5use std::fs::OpenOptions;
6use std::io::{self, Write};
7use std::net::SocketAddr;
8use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
9use std::os::unix::process::ExitStatusExt;
10use std::path::{Path, PathBuf};
11use std::process::ExitStatus;
12use std::sync::Arc;
13use std::sync::atomic::{AtomicBool, Ordering};
14use std::time::Duration;
15
16use bytes::Bytes;
17use russh::keys::ssh_key::LineEnding;
18use russh::keys::ssh_key::private::{Ed25519Keypair, KeypairData};
19use russh::keys::{Algorithm, EcdsaCurve, PrivateKey, PublicKey};
20use russh::server::{
21 Auth, Config, Handle, Handler, Msg, PublicKeyOffer, Session, VerifiedPublicKey, run_stream,
22};
23use russh::{Channel, ChannelId, ChannelOpenFailure, Disconnect, MethodKind, MethodSet, Preferred};
24use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt};
25use tokio::net::TcpListener;
26use tokio::process::{Child, ChildStdin};
27use tokio::sync::{Notify, Semaphore, mpsc};
28
29use crate::backend::GitBackend;
30use crate::error::{Error, Result};
31use crate::parse::{LFS_AUTHENTICATE_PREFIX, parse_exec, parse_lfs_authenticate};
32
33/// Stdout and stderr read size per message sent to the client.
34const PUMP_CHUNK: usize = 32 * 1024;
35/// Client input chunks buffered in front of the child's stdin. This bounds memory and
36/// propagates backpressure to the SSH read loop.
37const STDIN_QUEUE: usize = 8;
38/// Failed publickey attempts before the connection is dropped.
39const MAX_AUTH_ATTEMPTS: usize = 6;
40/// Connections served at once, counting unauthenticated ones. Each can hold a russh packet
41/// buffer of up to 256 KiB before auth, so this bounds that memory.
42const MAX_CONNECTIONS: usize = 256;
43
44#[derive(Debug, Clone)]
45pub struct SshConfig {
46 pub listen: SocketAddr,
47 pub host_key_path: PathBuf,
48 pub auth_timeout: Duration,
49 pub inactivity_timeout: Duration,
50 /// Delay before a failed authentication attempt is answered (forge-web: `ssh_auth_rejection_secs`).
51 pub auth_rejection_time: Duration,
52}
53
54/// Runs the SSH server until it fails. Creates the ed25519 host key on first boot.
55pub async fn run<B: GitBackend>(config: SshConfig, backend: Arc<B>) -> Result<()> {
56 let host_key = load_or_create_host_key(&config.host_key_path)?;
57 let russh_config = Arc::new(Config {
58 keys: vec![host_key],
59 methods: publickey_only(),
60 auth_rejection_time: config.auth_rejection_time,
61 max_auth_attempts: MAX_AUTH_ATTEMPTS,
62 inactivity_timeout: Some(config.inactivity_timeout),
63 preferred: preferred_algorithms(),
64 ..Config::default()
65 });
66
67 let listener = TcpListener::bind(config.listen).await?;
68 tracing::info!(addr = %config.listen, "ssh server listening");
69
70 let connection_slots = Arc::new(Semaphore::new(MAX_CONNECTIONS));
71 loop {
72 let (stream, peer) = match listener.accept().await {
73 Ok(v) => v,
74 Err(e) => {
75 // Typically EMFILE. Back off briefly instead of tearing the server down.
76 tracing::warn!(error = %e, "ssh accept failed");
77 tokio::time::sleep(Duration::from_millis(100)).await;
78 continue;
79 }
80 };
81 // At the limit the socket is dropped at once rather than queued.
82 let Ok(permit) = connection_slots.clone().try_acquire_owned() else {
83 tracing::warn!(%peer, "ssh connection limit reached, dropping connection");
84 continue;
85 };
86 let authed = Arc::new(AtomicBool::new(false));
87 let client = Client {
88 backend: Arc::clone(&backend),
89 peer: Some(peer),
90 authed: Arc::clone(&authed),
91 user_id: None,
92 git_protocol: None,
93 channels: HashMap::new(),
94 };
95 let russh_config = Arc::clone(&russh_config);
96 let auth_timeout = config.auth_timeout;
97 tokio::spawn(async move {
98 // Held until the connection ends, then the slot is free for the next client.
99 let _permit = permit;
100 let running = match run_stream(russh_config, stream, client).await {
101 Ok(running) => running,
102 Err(e) => {
103 tracing::debug!(%peer, error = %e, "ssh handshake failed");
104 return;
105 }
106 };
107 // Drop unauthenticated connections after the auth timeout.
108 let handle = running.handle();
109 tokio::spawn(async move {
110 tokio::time::sleep(auth_timeout).await;
111 if !authed.load(Ordering::Acquire) {
112 let _ = handle
113 .disconnect(
114 Disconnect::ByApplication,
115 "authentication timeout".into(),
116 String::new(),
117 )
118 .await;
119 }
120 });
121 if let Err(e) = running.await {
122 tracing::debug!(%peer, error = %e, "ssh session ended with error");
123 }
124 });
125 }
126}
127
128/// Publickey is the only accepted method.
129fn publickey_only() -> MethodSet {
130 let mut methods = MethodSet::empty();
131 methods.push(MethodKind::PublicKey);
132 methods
133}
134
135/// Host and user key algorithms this server negotiates. RSA is not listed: russh is built without it.
136fn preferred_algorithms() -> Preferred {
137 Preferred {
138 key: Cow::Owned(vec![
139 Algorithm::Ed25519,
140 Algorithm::SkEd25519,
141 Algorithm::SkEcdsaSha2NistP256,
142 Algorithm::Ecdsa {
143 curve: EcdsaCurve::NistP256,
144 },
145 Algorithm::Ecdsa {
146 curve: EcdsaCurve::NistP384,
147 },
148 Algorithm::Ecdsa {
149 curve: EcdsaCurve::NistP521,
150 },
151 ]),
152 ..Preferred::default()
153 }
154}
155
156/// Key types accepted for authentication. RSA keys are refused, as they are when a key is added.
157fn key_type_allowed(algorithm: &Algorithm) -> bool {
158 matches!(
159 algorithm,
160 Algorithm::Ed25519
161 | Algorithm::SkEd25519
162 | Algorithm::SkEcdsaSha2NistP256
163 | Algorithm::Ecdsa { .. }
164 )
165}
166
167/// Accepts exactly `version=<digit>`, e.g. `version=2`.
168fn valid_git_protocol(value: &str) -> bool {
169 let bytes = value.as_bytes();
170 bytes.len() == 9 && value.starts_with("version=") && bytes[8].is_ascii_digit()
171}
172
173fn load_or_create_host_key(path: &Path) -> Result<PrivateKey> {
174 if path.exists() {
175 let key = PrivateKey::read_openssh_file(path)
176 .map_err(|e| Error::Ssh(format!("host key: {e}")))?;
177 if key.algorithm() != Algorithm::Ed25519 {
178 return Err(Error::Ssh("host key must be ed25519".into()));
179 }
180 return Ok(key);
181 }
182
183 let mut seed = [0u8; 32];
184 getrandom::fill(&mut seed).map_err(|e| Error::Ssh(format!("host key entropy: {e}")))?;
185 let key = PrivateKey::new(KeypairData::Ed25519(Ed25519Keypair::from_seed(&seed)), "")
186 .map_err(|e| Error::Ssh(format!("host key generation: {e}")))?;
187 let pem = key
188 .to_openssh(LineEnding::LF)
189 .map_err(|e| Error::Ssh(format!("host key encoding: {e}")))?;
190
191 if let Some(parent) = path.parent() {
192 std::fs::create_dir_all(parent)?;
193 }
194 // create_new so an existing key is never overwritten. The mode applies at creation.
195 let mut file = OpenOptions::new()
196 .write(true)
197 .create_new(true)
198 .mode(0o600)
199 .open(path)?;
200 file.write_all(pem.as_bytes())?;
201 file.sync_all()?;
202 std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
203 tracing::info!(path = %path.display(), "generated ssh host key");
204 Ok(key)
205}
206
207/// Per-connection SSH handler.
208struct Client<B> {
209 backend: Arc<B>,
210 peer: Option<SocketAddr>,
211 authed: Arc<AtomicBool>,
212 user_id: Option<String>,
213 git_protocol: Option<String>,
214 /// Open exec channels. Entries are removed on channel EOF or close, which drops the
215 /// sender and closes the child's stdin.
216 channels: HashMap<ChannelId, mpsc::Sender<Bytes>>,
217}
218
219impl<B: GitBackend> Client<B> {
220 async fn lookup(&self, key: &PublicKey) -> Option<String> {
221 if !key_type_allowed(&key.algorithm()) {
222 return None;
223 }
224 let blob = key.to_bytes().ok()?;
225 self.backend
226 .authenticate_key(key.algorithm().as_str(), &blob)
227 .await
228 }
229
230 /// Answers `git-lfs-authenticate` with the JSON reply on stdout and exit status 0. Nothing is
231 /// left open afterwards: the channel is closed once the reply is queued.
232 async fn exec_lfs_authenticate(
233 &self,
234 session: &mut Session,
235 channel: ChannelId,
236 user_id: &str,
237 command: &str,
238 ) -> std::result::Result<(), russh::Error> {
239 let (path, operation) = match parse_lfs_authenticate(command) {
240 Ok(parsed) => parsed,
241 Err(e) => return reject_exec(session, channel, &e.to_string()),
242 };
243 let reply = match self
244 .backend
245 .lfs_authenticate(user_id, &path, operation)
246 .await
247 {
248 Ok(reply) => reply,
249 Err(msg) => return reject_exec(session, channel, &msg),
250 };
251 session.channel_success(channel)?;
252 session.data(channel, reply)?;
253 session.exit_status_request(channel, 0)?;
254 session.eof(channel)?;
255 session.close(channel)?;
256 Ok(())
257 }
258}
259
260impl<B: GitBackend> Handler for Client<B> {
261 type Error = russh::Error;
262
263 async fn auth_publickey_offered(
264 &mut self,
265 _user: &str,
266 offer: PublicKeyOffer<'_>,
267 ) -> std::result::Result<Auth, Self::Error> {
268 // Probe before the client signs. Reject early so unknown keys never get a signature.
269 if self.lookup(offer.public_key).await.is_some() {
270 Ok(Auth::Accept)
271 } else {
272 Ok(Auth::reject())
273 }
274 }
275
276 async fn auth_publickey(
277 &mut self,
278 _user: &str,
279 verified: VerifiedPublicKey<'_>,
280 ) -> std::result::Result<Auth, Self::Error> {
281 match self.lookup(verified.public_key).await {
282 Some(user_id) => {
283 tracing::info!(peer = ?self.peer, %user_id, "ssh publickey auth accepted");
284 self.user_id = Some(user_id);
285 self.authed.store(true, Ordering::Release);
286 Ok(Auth::Accept)
287 }
288 None => Ok(Auth::reject()),
289 }
290 }
291
292 async fn channel_open_session(
293 &mut self,
294 _channel: Channel<Msg>,
295 reply: russh::server::ChannelOpenHandle,
296 _session: &mut Session,
297 ) -> std::result::Result<(), Self::Error> {
298 if self.user_id.is_none() {
299 reply
300 .reject(ChannelOpenFailure::AdministrativelyProhibited)
301 .await;
302 } else {
303 reply.accept().await;
304 }
305 Ok(())
306 }
307
308 async fn env_request(
309 &mut self,
310 _channel: ChannelId,
311 variable_name: &str,
312 variable_value: &str,
313 _session: &mut Session,
314 ) -> std::result::Result<(), Self::Error> {
315 // Only GIT_PROTOCOL is kept. Everything else is ignored, never forwarded.
316 if variable_name == "GIT_PROTOCOL" && valid_git_protocol(variable_value) {
317 self.git_protocol = Some(variable_value.to_owned());
318 }
319 Ok(())
320 }
321
322 async fn exec_request(
323 &mut self,
324 channel: ChannelId,
325 data: &[u8],
326 session: &mut Session,
327 ) -> std::result::Result<(), Self::Error> {
328 if self.channels.contains_key(&channel) {
329 session.channel_failure(channel)?;
330 return Ok(());
331 }
332 let Some(user_id) = self.user_id.clone() else {
333 session.channel_failure(channel)?;
334 return Ok(());
335 };
336 let command = match std::str::from_utf8(data) {
337 Ok(command) => command,
338 Err(_) => return reject_exec(session, channel, "invalid command"),
339 };
340 if command.starts_with(LFS_AUTHENTICATE_PREFIX) {
341 return self
342 .exec_lfs_authenticate(session, channel, &user_id, command)
343 .await;
344 }
345 let (service, path) = match parse_exec(command) {
346 Ok(parsed) => parsed,
347 Err(e) => return reject_exec(session, channel, &e.to_string()),
348 };
349
350 let mut cmd = match self
351 .backend
352 .prepare(&user_id, service, &path, self.git_protocol.as_deref())
353 .await
354 {
355 Ok(cmd) => cmd,
356 Err(msg) => return reject_exec(session, channel, &msg),
357 };
358 cmd.stdin(std::process::Stdio::piped())
359 .stdout(std::process::Stdio::piped())
360 .stderr(std::process::Stdio::piped())
361 .kill_on_drop(true);
362
363 let child = match cmd.spawn() {
364 Ok(child) => child,
365 Err(e) => {
366 tracing::error!(error = %e, "failed to spawn git");
367 return reject_exec(session, channel, "failed to start git");
368 }
369 };
370
371 session.channel_success(channel)?;
372 let (tx, rx) = mpsc::channel(STDIN_QUEUE);
373 self.channels.insert(channel, tx);
374 tokio::spawn(run_child(session.handle(), channel, child, rx));
375 Ok(())
376 }
377
378 async fn data(
379 &mut self,
380 channel: ChannelId,
381 data: &[u8],
382 _session: &mut Session,
383 ) -> std::result::Result<(), Self::Error> {
384 if let Some(tx) = self.channels.get(&channel) {
385 // Err means the child has exited. Its output is still flushed, so this is not fatal.
386 let _ = tx.send(Bytes::copy_from_slice(data)).await;
387 }
388 Ok(())
389 }
390
391 async fn channel_eof(
392 &mut self,
393 channel: ChannelId,
394 _session: &mut Session,
395 ) -> std::result::Result<(), Self::Error> {
396 self.channels.remove(&channel);
397 Ok(())
398 }
399
400 async fn channel_close(
401 &mut self,
402 channel: ChannelId,
403 _session: &mut Session,
404 ) -> std::result::Result<(), Self::Error> {
405 self.channels.remove(&channel);
406 Ok(())
407 }
408
409 async fn pty_request(
410 &mut self,
411 channel: ChannelId,
412 _term: &str,
413 _col_width: u32,
414 _row_height: u32,
415 _pix_width: u32,
416 _pix_height: u32,
417 _modes: &[(russh::Pty, u32)],
418 session: &mut Session,
419 ) -> std::result::Result<(), Self::Error> {
420 session.channel_failure(channel)?;
421 Ok(())
422 }
423
424 async fn shell_request(
425 &mut self,
426 channel: ChannelId,
427 session: &mut Session,
428 ) -> std::result::Result<(), Self::Error> {
429 session.channel_failure(channel)?;
430 Ok(())
431 }
432
433 async fn subsystem_request(
434 &mut self,
435 channel: ChannelId,
436 _name: &str,
437 session: &mut Session,
438 ) -> std::result::Result<(), Self::Error> {
439 session.channel_failure(channel)?;
440 Ok(())
441 }
442
443 async fn x11_request(
444 &mut self,
445 channel: ChannelId,
446 _single_connection: bool,
447 _x11_auth_protocol: &str,
448 _x11_auth_cookie: &str,
449 _x11_screen_number: u32,
450 session: &mut Session,
451 ) -> std::result::Result<(), Self::Error> {
452 session.channel_failure(channel)?;
453 Ok(())
454 }
455
456 async fn tcpip_forward(
457 &mut self,
458 _address: &str,
459 _port: &mut u32,
460 _session: &mut Session,
461 ) -> std::result::Result<bool, Self::Error> {
462 Ok(false)
463 }
464
465 async fn agent_request(
466 &mut self,
467 _channel: ChannelId,
468 _session: &mut Session,
469 ) -> std::result::Result<bool, Self::Error> {
470 Ok(false)
471 }
472}
473
474/// Sends a rejection as the spec requires: the message on stderr, exit status 1, then EOF and close.
475/// The request itself is acknowledged so git reads the message instead of failing at the protocol level.
476fn reject_exec(
477 session: &mut Session,
478 channel: ChannelId,
479 msg: &str,
480) -> std::result::Result<(), russh::Error> {
481 session.channel_success(channel)?;
482 session.extended_data(channel, 1, format!("{msg}\n"))?;
483 session.exit_status_request(channel, 1)?;
484 session.eof(channel)?;
485 session.close(channel)?;
486 Ok(())
487}
488
489/// Runs one git process for an exec channel. Stdin is fed from `stdin_rx`, stdout goes to
490/// channel data and stderr to extended data 1. Exit status, EOF and close are sent last.
491async fn run_child(
492 handle: Handle,
493 channel: ChannelId,
494 mut child: Child,
495 stdin_rx: mpsc::Receiver<Bytes>,
496) {
497 // Raised by a pump when the client has gone away, so the child is killed.
498 let abort = Arc::new(Notify::new());
499
500 let feeder = tokio::spawn(feed_stdin(child.stdin.take(), stdin_rx));
501 let stdout_task = tokio::spawn(pump(
502 child.stdout.take(),
503 handle.clone(),
504 channel,
505 None,
506 Arc::clone(&abort),
507 ));
508 let stderr_task = tokio::spawn(pump(
509 child.stderr.take(),
510 handle.clone(),
511 channel,
512 Some(1),
513 Arc::clone(&abort),
514 ));
515
516 let status = tokio::select! {
517 status = child.wait() => status,
518 () = abort.notified() => {
519 let _ = child.start_kill();
520 child.wait().await
521 }
522 };
523
524 // Wait for the pumps so every byte of output is queued before exit status and EOF.
525 let _ = stdout_task.await;
526 let _ = stderr_task.await;
527 feeder.abort();
528
529 let _ = handle.exit_status_request(channel, exit_code(status)).await;
530 let _ = handle.eof(channel).await;
531 let _ = handle.close(channel).await;
532}
533
534async fn feed_stdin(stdin: Option<ChildStdin>, mut rx: mpsc::Receiver<Bytes>) {
535 let Some(mut stdin) = stdin else {
536 return;
537 };
538 while let Some(chunk) = rx.recv().await {
539 if stdin.write_all(&chunk).await.is_err() {
540 break;
541 }
542 }
543 // Dropping stdin here closes the child's input.
544 let _ = stdin.shutdown().await;
545}
546
547/// Forwards one child output stream to the client. `ext` = Some(n) sends extended data
548/// type n. Sets `abort` when the client has gone away.
549async fn pump<R>(
550 reader: Option<R>,
551 handle: Handle,
552 channel: ChannelId,
553 ext: Option<u32>,
554 abort: Arc<Notify>,
555) where
556 R: AsyncRead + Unpin + Send + 'static,
557{
558 let Some(mut reader) = reader else {
559 return;
560 };
561 let mut buf = vec![0u8; PUMP_CHUNK];
562 loop {
563 let n = match reader.read(&mut buf).await {
564 Ok(0) | Err(_) => break,
565 Ok(n) => n,
566 };
567 // A right-sized copy: a chunk queued for the client holds only the bytes read.
568 let chunk = Bytes::copy_from_slice(buf.get(..n).unwrap_or_default());
569 let sent = match ext {
570 None => handle.data(channel, chunk).await.is_ok(),
571 Some(kind) => handle.extended_data(channel, kind, chunk).await.is_ok(),
572 };
573 if !sent {
574 abort.notify_one();
575 break;
576 }
577 }
578}
579
580fn exit_code(status: io::Result<ExitStatus>) -> u32 {
581 match status {
582 Ok(status) => status
583 .code()
584 .and_then(|c| u32::try_from(c).ok())
585 .or_else(|| {
586 status
587 .signal()
588 .map(|sig| 128 + u32::try_from(sig).unwrap_or(0))
589 })
590 .unwrap_or(1),
591 Err(_) => 1,
592 }
593}
594
595#[cfg(test)]
596mod tests {
597 use super::*;
598
599 #[test]
600 fn git_protocol_is_strict() {
601 assert!(valid_git_protocol("version=2"));
602 assert!(valid_git_protocol("version=1"));
603 assert!(!valid_git_protocol("version=10"));
604 assert!(!valid_git_protocol("version=x"));
605 assert!(!valid_git_protocol("version=2\n"));
606 assert!(!valid_git_protocol("version=2;x"));
607 assert!(!valid_git_protocol(""));
608 }
609
610 #[test]
611 fn key_types_exclude_dsa_and_rsa() {
612 assert!(key_type_allowed(&Algorithm::Ed25519));
613 assert!(!key_type_allowed(&Algorithm::Rsa { hash: None }));
614 assert!(!key_type_allowed(&Algorithm::Dsa));
615 }
616}