forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.7 MiBdcdcd27Tahinli1 month ago240 commits

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