forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.9 MiB2e29cbcTahinli6 hours ago333 commits

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