Skip to main content

fynx_proto/ssh/
server.rs

1//! SSH Server implementation.
2//!
3//! This module provides a complete SSH server implementation with full protocol support.
4//!
5//! # Example
6//!
7//! ```rust,no_run
8//! use fynx_proto::ssh::server::{SshServer, SessionHandler};
9//! use fynx_platform::FynxResult;
10//!
11//! struct MyHandler;
12//!
13//! #[async_trait::async_trait]
14//! impl SessionHandler for MyHandler {
15//!     async fn handle_exec(&mut self, command: &str) -> FynxResult<Vec<u8>> {
16//!         // Execute command and return output
17//!         Ok(format!("Executed: {}", command).into_bytes())
18//!     }
19//! }
20//!
21//! # #[tokio::main]
22//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
23//! // Create and start SSH server
24//! let server = SshServer::bind("127.0.0.1:2222").await?;
25//! println!("SSH server listening on 127.0.0.1:2222");
26//!
27//! // Accept connections (would normally loop)
28//! // let session = server.accept().await?;
29//! # Ok(())
30//! # }
31//! ```
32
33use crate::ssh::auth::{construct_signature_data, AuthMethod, AuthPkOk, AuthRequest};
34use crate::ssh::authorized_keys::AuthorizedKeysFile;
35use crate::ssh::connection::{
36    ChannelClose, ChannelData, ChannelEof, ChannelOpen, ChannelOpenConfirmation, ChannelRequest,
37    ChannelRequestType, ChannelSuccess,
38};
39use crate::ssh::hostkey::{Ed25519HostKey, HostKey};
40use crate::ssh::kex::{negotiate_algorithm, KexInit, NewKeys};
41use crate::ssh::kex_dh::Curve25519Exchange;
42use crate::ssh::message::MessageType;
43use crate::ssh::packet::Packet;
44use crate::ssh::transport::{State, TransportConfig, TransportState};
45use crate::ssh::version::Version;
46use fynx_platform::{FynxError, FynxResult};
47use std::collections::HashMap;
48use std::path::PathBuf;
49use std::sync::Arc;
50use std::time::Duration;
51use tokio::io::{AsyncReadExt, AsyncWriteExt};
52use tokio::net::{TcpListener, TcpStream};
53use tokio::sync::Mutex;
54
55/// SSH server configuration.
56///
57/// Note: This struct does not include host_key because Clone is not
58/// object-safe for trait objects. The host key is passed separately
59/// to bind_with_config().
60#[derive(Debug, Clone)]
61pub struct SshServerConfig {
62    /// Server version string.
63    pub server_version: String,
64    /// Maximum authentication attempts.
65    pub max_auth_attempts: u32,
66    /// Connection timeout.
67    pub connection_timeout: Duration,
68    /// Read timeout.
69    pub read_timeout: Duration,
70    /// Write timeout.
71    pub write_timeout: Duration,
72}
73
74impl Default for SshServerConfig {
75    fn default() -> Self {
76        Self {
77            server_version: "Fynx_0.1.0".to_string(),
78            max_auth_attempts: 3,
79            connection_timeout: Duration::from_secs(120),
80            read_timeout: Duration::from_secs(60),
81            write_timeout: Duration::from_secs(60),
82        }
83    }
84}
85
86/// Authentication callback for verifying user credentials.
87pub type AuthCallback = Arc<dyn Fn(&str, &str) -> bool + Send + Sync>;
88
89/// Session handler trait for handling SSH requests.
90///
91/// Implement this trait to define custom behavior for SSH sessions.
92#[async_trait::async_trait]
93pub trait SessionHandler: Send {
94    /// Handle exec request (execute a command).
95    ///
96    /// # Arguments
97    ///
98    /// * `command` - Command to execute
99    ///
100    /// # Returns
101    ///
102    /// Command output as bytes
103    async fn handle_exec(&mut self, command: &str) -> FynxResult<Vec<u8>>;
104
105    /// Handle shell request (interactive shell).
106    ///
107    /// This method is called when a client requests an interactive shell.
108    /// The default implementation returns an error.
109    async fn handle_shell(&mut self) -> FynxResult<()> {
110        Err(FynxError::Protocol("Shell not supported".to_string()))
111    }
112
113    /// Handle subsystem request (e.g., SFTP).
114    ///
115    /// # Arguments
116    ///
117    /// * `subsystem` - Subsystem name (e.g., "sftp")
118    ///
119    /// The default implementation returns an error.
120    async fn handle_subsystem(&mut self, subsystem: &str) -> FynxResult<()> {
121        Err(FynxError::Protocol(format!(
122            "Subsystem '{}' not supported",
123            subsystem
124        )))
125    }
126}
127
128/// SSH Server.
129///
130/// Provides complete SSH server functionality including connection acceptance,
131/// authentication, and session management.
132pub struct SshServer {
133    /// TCP listener.
134    listener: TcpListener,
135    /// Configuration.
136    config: SshServerConfig,
137    /// Server's host key for authentication.
138    host_key: Arc<dyn HostKey>,
139    /// Authentication callback.
140    auth_callback: AuthCallback,
141    /// Active sessions (for future session management).
142    _sessions: Arc<Mutex<HashMap<String, SshSession>>>,
143}
144
145impl SshServer {
146    /// Binds to an address and creates a new SSH server.
147    ///
148    /// Uses a default Ed25519 host key. For production use, call
149    /// `bind_with_config()` with a persistent host key.
150    ///
151    /// # Arguments
152    ///
153    /// * `addr` - Address to bind to (e.g., "127.0.0.1:2222")
154    ///
155    /// # Example
156    ///
157    /// ```rust,no_run
158    /// use fynx_proto::ssh::server::SshServer;
159    ///
160    /// # #[tokio::main]
161    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
162    /// let server = SshServer::bind("127.0.0.1:2222").await?;
163    /// # Ok(())
164    /// # }
165    /// ```
166    pub async fn bind(addr: &str) -> FynxResult<Self> {
167        // Generate a temporary Ed25519 host key
168        let host_key = Arc::new(Ed25519HostKey::generate()?) as Arc<dyn HostKey>;
169        Self::bind_with_config(addr, SshServerConfig::default(), host_key).await
170    }
171
172    /// Binds with custom configuration and host key.
173    ///
174    /// # Arguments
175    ///
176    /// * `addr` - Address to bind to
177    /// * `config` - Server configuration
178    /// * `host_key` - Server's host key for client authentication
179    ///
180    /// # Example
181    ///
182    /// ```rust,no_run
183    /// use fynx_proto::ssh::server::{SshServer, SshServerConfig};
184    /// use fynx_proto::ssh::hostkey::Ed25519HostKey;
185    /// use std::sync::Arc;
186    ///
187    /// # #[tokio::main]
188    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
189    /// let host_key = Arc::new(Ed25519HostKey::generate()?);
190    /// let config = SshServerConfig::default();
191    /// let server = SshServer::bind_with_config("127.0.0.1:2222", config, host_key).await?;
192    /// # Ok(())
193    /// # }
194    /// ```
195    pub async fn bind_with_config(
196        addr: &str,
197        config: SshServerConfig,
198        host_key: Arc<dyn HostKey>,
199    ) -> FynxResult<Self> {
200        let listener = TcpListener::bind(addr).await.map_err(FynxError::Io)?;
201
202        // Default auth callback: reject all (should be replaced by user)
203        let auth_callback: AuthCallback = Arc::new(|_username, _password| false);
204
205        Ok(Self {
206            listener,
207            config,
208            host_key,
209            auth_callback,
210            _sessions: Arc::new(Mutex::new(HashMap::new())),
211        })
212    }
213
214    /// Sets the authentication callback.
215    ///
216    /// # Arguments
217    ///
218    /// * `callback` - Function to verify username/password
219    ///
220    /// # Example
221    ///
222    /// ```rust,no_run
223    /// use fynx_proto::ssh::server::SshServer;
224    /// use std::sync::Arc;
225    ///
226    /// # #[tokio::main]
227    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
228    /// let mut server = SshServer::bind("127.0.0.1:2222").await?;
229    ///
230    /// // Set auth callback
231    /// server.set_auth_callback(Arc::new(|username, password| {
232    ///     username == "admin" && password == "secret"
233    /// }));
234    /// # Ok(())
235    /// # }
236    /// ```
237    pub fn set_auth_callback(&mut self, callback: AuthCallback) {
238        self.auth_callback = callback;
239    }
240
241    /// Accepts a new client connection.
242    ///
243    /// This method blocks until a client connects, then performs:
244    /// 1. Version exchange
245    /// 2. Key exchange
246    /// 3. Returns a session ready for authentication
247    ///
248    /// # Example
249    ///
250    /// ```rust,no_run
251    /// use fynx_proto::ssh::server::SshServer;
252    ///
253    /// # #[tokio::main]
254    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
255    /// let server = SshServer::bind("127.0.0.1:2222").await?;
256    ///
257    /// loop {
258    ///     let session = server.accept().await?;
259    ///     tokio::spawn(async move {
260    ///         // Handle session
261    ///     });
262    /// }
263    /// # Ok(())
264    /// # }
265    /// ```
266    pub async fn accept(&self) -> FynxResult<SshSession> {
267        let (stream, peer_addr) = self.listener.accept().await.map_err(FynxError::Io)?;
268
269        let transport_config = TransportConfig::new(false); // false = server mode
270        let transport = TransportState::new(transport_config);
271
272        let mut session = SshSession {
273            stream,
274            transport,
275            config: self.config.clone(),
276            host_key: self.host_key.clone(),
277            peer_addr: peer_addr.to_string(),
278            authenticated_user: None,
279            auth_callback: self.auth_callback.clone(),
280            next_channel_id: 0,
281            channels: HashMap::new(),
282            client_version: String::new(),
283            server_version: String::new(),
284            client_kexinit_payload: Vec::new(),
285            server_kexinit_payload: Vec::new(),
286            session_id: None,
287        };
288
289        // Perform version exchange
290        session.version_exchange().await?;
291
292        // Perform key exchange
293        session.key_exchange().await?;
294
295        Ok(session)
296    }
297
298    /// Returns the local address the server is bound to.
299    pub fn local_addr(&self) -> std::io::Result<std::net::SocketAddr> {
300        self.listener.local_addr()
301    }
302}
303
304/// SSH Session.
305///
306/// Represents an active SSH connection from a client.
307pub struct SshSession {
308    /// TCP stream.
309    stream: TcpStream,
310    /// Transport state.
311    transport: TransportState,
312    /// Configuration.
313    config: SshServerConfig,
314    /// Server's host key.
315    host_key: Arc<dyn HostKey>,
316    /// Peer address.
317    peer_addr: String,
318    /// Authenticated username (None if not authenticated).
319    authenticated_user: Option<String>,
320    /// Authentication callback.
321    auth_callback: AuthCallback,
322    /// Next channel ID.
323    next_channel_id: u32,
324    /// Active channels.
325    channels: HashMap<u32, ChannelState>,
326    /// Client version string (for exchange hash computation).
327    client_version: String,
328    /// Server version string (for exchange hash computation).
329    server_version: String,
330    /// Client KEXINIT payload (for exchange hash computation).
331    client_kexinit_payload: Vec<u8>,
332    /// Server KEXINIT payload (for exchange hash computation).
333    server_kexinit_payload: Vec<u8>,
334    /// Session identifier (exchange hash from first key exchange).
335    /// Used for public key authentication signatures (RFC 4252 Section 7).
336    session_id: Option<Vec<u8>>,
337}
338
339/// Channel state.
340struct ChannelState {
341    /// Local channel ID.
342    _local_id: u32,
343    /// Remote channel ID (for future use).
344    _remote_id: u32,
345    /// Window size.
346    _window_size: u32,
347}
348
349/// Public key authentication result.
350enum PublicKeyAuthResult {
351    /// Server accepts the key (send SSH_MSG_USERAUTH_PK_OK).
352    PkOk,
353    /// Authentication successful.
354    Success,
355    /// Authentication failed.
356    Failure,
357}
358
359impl SshSession {
360    /// Performs SSH version exchange (server side).
361    async fn version_exchange(&mut self) -> FynxResult<()> {
362        // Send our version
363        let our_version = Version::new(&self.config.server_version, None);
364        let version_line = format!("{}\r\n", our_version);
365
366        // Save server version for exchange hash
367        self.server_version = format!("{}", our_version);
368
369        self.stream
370            .write_all(version_line.as_bytes())
371            .await
372            .map_err(FynxError::Io)?;
373
374        // Read client version
375        let mut buffer = Vec::new();
376        let mut temp = [0u8; 1];
377
378        // Read until \n
379        loop {
380            self.stream
381                .read_exact(&mut temp)
382                .await
383                .map_err(FynxError::Io)?;
384            buffer.push(temp[0]);
385
386            if temp[0] == b'\n' {
387                break;
388            }
389
390            if buffer.len() > 255 {
391                return Err(FynxError::Protocol("Version string too long".to_string()));
392            }
393        }
394
395        let version_str = String::from_utf8_lossy(&buffer);
396        let client_version = Version::parse(&version_str)?;
397
398        // Save client version for exchange hash
399        self.client_version = format!("{}", client_version);
400
401        self.transport.set_peer_version(client_version);
402        self.transport.transition(State::KexInit)?;
403
404        Ok(())
405    }
406
407    /// Performs key exchange (server side).
408    async fn key_exchange(&mut self) -> FynxResult<()> {
409        // 1. Send our KEXINIT
410        let our_kexinit = self.transport.config().kex_init.clone();
411        let kexinit_payload = our_kexinit.to_bytes();
412
413        // Save server KEXINIT payload for exchange hash
414        self.server_kexinit_payload = kexinit_payload.clone();
415
416        self.send_packet(&kexinit_payload).await?;
417
418        // 2. Receive client KEXINIT
419        let client_packet = self.receive_packet().await?;
420        if client_packet.payload().is_empty()
421            || client_packet.payload()[0] != MessageType::KexInit as u8
422        {
423            return Err(FynxError::Protocol("Expected KEXINIT message".to_string()));
424        }
425
426        let client_kexinit = KexInit::from_bytes(client_packet.payload())?;
427
428        // Save client KEXINIT payload for exchange hash
429        self.client_kexinit_payload = client_packet.payload().to_vec();
430
431        self.transport.set_peer_kex_init(client_kexinit.clone());
432
433        // 3. Negotiate algorithms
434        let kex_alg = negotiate_algorithm(
435            our_kexinit.kex_algorithms(),
436            client_kexinit.kex_algorithms(),
437        )?;
438
439        self.transport.transition(State::KeyExchange)?;
440
441        // 4. Perform key exchange (Curve25519)
442        if kex_alg == "curve25519-sha256" || kex_alg == "curve25519-sha256@libssh.org" {
443            self.perform_curve25519_kex().await?;
444        } else {
445            return Err(FynxError::Protocol(format!(
446                "Unsupported KEX algorithm: {}",
447                kex_alg
448            )));
449        }
450
451        // 5. Receive NEWKEYS from client
452        let newkeys_packet = self.receive_packet().await?;
453        if newkeys_packet.payload().is_empty()
454            || newkeys_packet.payload()[0] != MessageType::NewKeys as u8
455        {
456            return Err(FynxError::Protocol("Expected NEWKEYS message".to_string()));
457        }
458
459        // 6. Send NEWKEYS
460        let newkeys = NewKeys::new();
461        self.send_packet(&newkeys.to_bytes()).await?;
462
463        self.transport.transition(State::NewKeys)?;
464        self.transport.transition(State::Encrypted)?;
465
466        Ok(())
467    }
468
469    /// Computes the exchange hash (H) for Curve25519 key exchange.
470    ///
471    /// According to RFC 4253 Section 8, the exchange hash is computed as:
472    /// H = HASH(V_C || V_S || I_C || I_S || K_S || Q_C || Q_S || K)
473    ///
474    /// Where:
475    /// - V_C: client version string
476    /// - V_S: server version string
477    /// - I_C: client KEXINIT payload
478    /// - I_S: server KEXINIT payload
479    /// - K_S: server host key blob
480    /// - Q_C: client ephemeral public key
481    /// - Q_S: server ephemeral public key
482    /// - K: shared secret (mpint format)
483    fn compute_exchange_hash_curve25519(
484        &self,
485        client_version: &str,
486        server_version: &str,
487        client_kexinit: &[u8],
488        server_kexinit: &[u8],
489        host_key_blob: &[u8],
490        client_public: &[u8],
491        server_public: &[u8],
492        shared_secret: &[u8],
493    ) -> Vec<u8> {
494        use sha2::{Digest, Sha256};
495
496        let mut hasher = Sha256::new();
497
498        // Helper to write SSH string (uint32 length + data)
499        let write_string = |h: &mut Sha256, s: &[u8]| {
500            h.update((s.len() as u32).to_be_bytes());
501            h.update(s);
502        };
503
504        // Helper to write SSH mpint (multiple precision integer)
505        let write_mpint = |h: &mut Sha256, data: &[u8]| {
506            // If high bit is set, add 0x00 prefix
507            if !data.is_empty() && (data[0] & 0x80) != 0 {
508                h.update(((data.len() + 1) as u32).to_be_bytes());
509                h.update([0x00]);
510                h.update(data);
511            } else {
512                h.update((data.len() as u32).to_be_bytes());
513                h.update(data);
514            }
515        };
516
517        // V_C (client version, without CR+LF)
518        let client_ver = client_version.trim_end_matches("\r\n");
519        write_string(&mut hasher, client_ver.as_bytes());
520
521        // V_S (server version, without CR+LF)
522        let server_ver = server_version.trim_end_matches("\r\n");
523        write_string(&mut hasher, server_ver.as_bytes());
524
525        // I_C (client KEXINIT payload)
526        write_string(&mut hasher, client_kexinit);
527
528        // I_S (server KEXINIT payload)
529        write_string(&mut hasher, server_kexinit);
530
531        // K_S (server host key blob)
532        write_string(&mut hasher, host_key_blob);
533
534        // Q_C (client ephemeral public key)
535        write_string(&mut hasher, client_public);
536
537        // Q_S (server ephemeral public key)
538        write_string(&mut hasher, server_public);
539
540        // K (shared secret as mpint)
541        write_mpint(&mut hasher, shared_secret);
542
543        hasher.finalize().to_vec()
544    }
545
546    /// Performs Curve25519 key exchange (server side).
547    async fn perform_curve25519_kex(&mut self) -> FynxResult<()> {
548        // 1. Receive SSH_MSG_KEX_ECDH_INIT from client (30)
549        let init_packet = self.receive_packet().await?;
550        if init_packet.payload().is_empty()
551            || init_packet.payload()[0] != MessageType::KexdhInit as u8
552        {
553            return Err(FynxError::Protocol(
554                "Expected KEX_ECDH_INIT message".to_string(),
555            ));
556        }
557
558        // Parse client public key
559        let payload = init_packet.payload();
560        let mut offset = 1;
561
562        if offset + 4 > payload.len() {
563            return Err(FynxError::Protocol("Invalid KEX_ECDH_INIT".to_string()));
564        }
565        let client_pub_len = u32::from_be_bytes([
566            payload[offset],
567            payload[offset + 1],
568            payload[offset + 2],
569            payload[offset + 3],
570        ]) as usize;
571        offset += 4;
572
573        if offset + client_pub_len > payload.len() {
574            return Err(FynxError::Protocol("Invalid client public key".to_string()));
575        }
576
577        // Curve25519 public keys must be exactly 32 bytes
578        if client_pub_len != 32 {
579            return Err(FynxError::Protocol(format!(
580                "Invalid Curve25519 public key length: expected 32, got {}",
581                client_pub_len
582            )));
583        }
584
585        let mut client_public = [0u8; 32];
586        client_public.copy_from_slice(&payload[offset..offset + 32]);
587
588        // 2. Generate our key pair and copy public key
589        let our_exchange = Curve25519Exchange::new()?;
590        let our_public = our_exchange.public_key().to_vec();
591
592        // 3. Compute shared secret
593        let shared_secret = our_exchange.compute_shared_secret(&client_public)?;
594
595        // 4. Get host key bytes
596        let host_key_blob = self.host_key.public_key_bytes();
597
598        // 5. Compute exchange hash (H) according to RFC 4253 Section 8
599        let exchange_hash = self.compute_exchange_hash_curve25519(
600            &self.client_version,
601            &self.server_version,
602            &self.client_kexinit_payload,
603            &self.server_kexinit_payload,
604            &host_key_blob,
605            &client_public,
606            &our_public,
607            &shared_secret,
608        );
609
610        // 6. Sign the exchange hash with host key
611        let signature_blob = self.host_key.sign(&exchange_hash)?;
612
613        // 7. Send SSH_MSG_KEX_ECDH_REPLY (31)
614        let mut reply_msg = vec![MessageType::KexdhReply as u8];
615
616        // Add host key
617        reply_msg.extend_from_slice(&(host_key_blob.len() as u32).to_be_bytes());
618        reply_msg.extend_from_slice(&host_key_blob);
619
620        // Add server public key
621        reply_msg.extend_from_slice(&(our_public.len() as u32).to_be_bytes());
622        reply_msg.extend_from_slice(&our_public);
623
624        // Add signature
625        reply_msg.extend_from_slice(&(signature_blob.len() as u32).to_be_bytes());
626        reply_msg.extend_from_slice(&signature_blob);
627
628        self.send_packet(&reply_msg).await?;
629
630        // 8. Derive encryption/MAC keys according to RFC 4253 Section 7.2
631        // Store exchange hash as session ID (first exchange hash in connection)
632        let session_id = exchange_hash.clone();
633
634        // Derive encryption/MAC keys
635        // Key derivation uses: K (shared secret), H (exchange hash), session_id
636        // IV client-to-server:  HASH(K || H || "A" || session_id)
637        // IV server-to-client:  HASH(K || H || "B" || session_id)
638        // Encryption key C->S:  HASH(K || H || "C" || session_id)
639        // Encryption key S->C:  HASH(K || H || "D" || session_id)
640        // Integrity key C->S:   HASH(K || H || "E" || session_id)
641        // Integrity key S->C:   HASH(K || H || "F" || session_id)
642
643        use crate::ssh::crypto::{CipherAlgorithm, DecryptionKey, EncryptionKey};
644        use crate::ssh::kex_dh::derive_key;
645        use crate::ssh::transport::EncryptionParams;
646
647        // Get negotiated cipher (for now, assume chacha20-poly1305)
648        let cipher_c2s = CipherAlgorithm::ChaCha20Poly1305;
649        let cipher_s2c = CipherAlgorithm::ChaCha20Poly1305;
650
651        // Derive decryption key (client-to-server) - "C"
652        // Server decrypts what client encrypts
653        let dec_key_c2s = derive_key(
654            &shared_secret,
655            &exchange_hash,
656            &session_id,
657            b'C',
658            cipher_c2s.key_size(),
659        );
660
661        // Derive encryption key (server-to-client) - "D"
662        // Server encrypts what client decrypts
663        let enc_key_s2c = derive_key(
664            &shared_secret,
665            &exchange_hash,
666            &session_id,
667            b'D',
668            cipher_s2c.key_size(),
669        );
670
671        // Create encryption/decryption keys
672        // NOTE: Server's encryption key is client's decryption key (S->C)
673        //       Server's decryption key is client's encryption key (C->S)
674        let encryption_key = EncryptionKey::new(cipher_s2c, &enc_key_s2c)?;
675        let decryption_key = DecryptionKey::new(cipher_c2s, &dec_key_c2s)?;
676
677        // Create encryption params (AEAD ciphers don't need separate MAC)
678        let mut enc_params = EncryptionParams::new(
679            CipherAlgorithm::ChaCha20Poly1305,
680            CipherAlgorithm::ChaCha20Poly1305,
681            None,
682            None,
683        );
684        enc_params.install_keys(Some(encryption_key), Some(decryption_key), None, None);
685
686        // Install encryption params into transport state
687        self.transport.set_encryption_params(enc_params);
688
689        // Store session_id for public key authentication (RFC 4253 Section 7.2)
690        // Session ID is the exchange hash H from the first key exchange
691        if self.session_id.is_none() {
692            self.session_id = Some(session_id);
693        }
694
695        Ok(())
696    }
697
698    /// Handles public key authentication (RFC 4252 Section 7).
699    ///
700    /// This implements both the try phase (query if key is acceptable) and
701    /// the sign phase (verify signature).
702    ///
703    /// # Arguments
704    ///
705    /// * `username` - User attempting to authenticate
706    /// * `algorithm` - Public key algorithm name
707    /// * `public_key` - Public key blob (SSH wire format)
708    /// * `signature` - Optional signature blob (None for try phase)
709    ///
710    /// # Returns
711    ///
712    /// Authentication result
713    async fn handle_publickey_auth(
714        &self,
715        username: &str,
716        algorithm: &str,
717        public_key: &[u8],
718        signature: Option<&[u8]>,
719    ) -> FynxResult<PublicKeyAuthResult> {
720        // Load user's authorized_keys file
721        let auth_keys_path = Self::get_authorized_keys_path(username);
722        let auth_keys_file = match AuthorizedKeysFile::from_file(&auth_keys_path) {
723            Ok(file) => file,
724            Err(_) => {
725                // authorized_keys file not found or unreadable
726                return Ok(PublicKeyAuthResult::Failure);
727            }
728        };
729
730        // Find the public key in authorized_keys
731        let _authorized_key = match auth_keys_file.find_key(algorithm, public_key) {
732            Some(key) => key,
733            None => {
734                // Public key not found in authorized_keys
735                return Ok(PublicKeyAuthResult::Failure);
736            }
737        };
738
739        // Try phase: client is querying if this key is acceptable
740        if signature.is_none() {
741            return Ok(PublicKeyAuthResult::PkOk);
742        }
743
744        // Sign phase: verify the signature
745        let signature_blob = signature.unwrap();
746
747        // Get session_id (must have completed key exchange)
748        let session_id = self.session_id.as_ref().ok_or_else(|| {
749            FynxError::Protocol("No session ID available (key exchange not completed)".to_string())
750        })?;
751
752        // Construct signature data (RFC 4252 Section 7)
753        let signature_data = construct_signature_data(
754            session_id,
755            username,
756            "ssh-connection",
757            algorithm,
758            public_key,
759        );
760
761        // Verify signature based on algorithm
762        let verified =
763            self.verify_signature(algorithm, public_key, signature_blob, &signature_data)?;
764
765        if verified {
766            Ok(PublicKeyAuthResult::Success)
767        } else {
768            Ok(PublicKeyAuthResult::Failure)
769        }
770    }
771
772    /// Verifies a public key signature.
773    ///
774    /// # Arguments
775    ///
776    /// * `algorithm` - Public key algorithm name
777    /// * `public_key_blob` - Public key in SSH wire format
778    /// * `signature_blob` - Signature in SSH wire format
779    /// * `signed_data` - Data that was signed
780    ///
781    /// # Returns
782    ///
783    /// `true` if signature is valid, `false` otherwise
784    fn verify_signature(
785        &self,
786        algorithm: &str,
787        public_key_blob: &[u8],
788        signature_blob: &[u8],
789        signed_data: &[u8],
790    ) -> FynxResult<bool> {
791        // Parse signature blob: string algorithm_name || string signature_data
792        if signature_blob.len() < 4 {
793            return Ok(false);
794        }
795
796        let sig_alg_len = u32::from_be_bytes([
797            signature_blob[0],
798            signature_blob[1],
799            signature_blob[2],
800            signature_blob[3],
801        ]) as usize;
802
803        if signature_blob.len() < 4 + sig_alg_len + 4 {
804            return Ok(false);
805        }
806
807        let mut offset = 4 + sig_alg_len;
808
809        // Read signature data
810        let sig_data_len = u32::from_be_bytes([
811            signature_blob[offset],
812            signature_blob[offset + 1],
813            signature_blob[offset + 2],
814            signature_blob[offset + 3],
815        ]) as usize;
816        offset += 4;
817
818        if offset + sig_data_len > signature_blob.len() {
819            return Ok(false);
820        }
821
822        let signature_data = &signature_blob[offset..offset + sig_data_len];
823
824        // Extract public key from blob (skip algorithm name, get key data)
825        if public_key_blob.len() < 4 {
826            return Ok(false);
827        }
828
829        let key_alg_len = u32::from_be_bytes([
830            public_key_blob[0],
831            public_key_blob[1],
832            public_key_blob[2],
833            public_key_blob[3],
834        ]) as usize;
835
836        let key_offset = 4 + key_alg_len;
837        if key_offset + 4 > public_key_blob.len() {
838            return Ok(false);
839        }
840
841        let key_data_len = u32::from_be_bytes([
842            public_key_blob[key_offset],
843            public_key_blob[key_offset + 1],
844            public_key_blob[key_offset + 2],
845            public_key_blob[key_offset + 3],
846        ]) as usize;
847
848        let key_data_offset = key_offset + 4;
849        if key_data_offset + key_data_len > public_key_blob.len() {
850            return Ok(false);
851        }
852
853        let key_data = &public_key_blob[key_data_offset..key_data_offset + key_data_len];
854
855        // Verify signature based on algorithm
856        match algorithm {
857            "ssh-ed25519" => Ed25519HostKey::verify(key_data, signed_data, signature_data),
858            "rsa-sha2-256" => {
859                // TODO: Implement RSA signature verification
860                Ok(false)
861            }
862            "rsa-sha2-512" => {
863                // TODO: Implement RSA signature verification
864                Ok(false)
865            }
866            "ecdsa-sha2-nistp256" => {
867                // TODO: Implement ECDSA P-256 signature verification
868                Ok(false)
869            }
870            "ecdsa-sha2-nistp384" => {
871                // TODO: Implement ECDSA P-384 signature verification
872                Ok(false)
873            }
874            "ecdsa-sha2-nistp521" => {
875                // TODO: Implement ECDSA P-521 signature verification
876                Ok(false)
877            }
878            _ => Ok(false),
879        }
880    }
881
882    /// Gets the authorized_keys file path for a user.
883    ///
884    /// # Arguments
885    ///
886    /// * `username` - Username to get authorized_keys for
887    ///
888    /// # Returns
889    ///
890    /// Path to the user's authorized_keys file
891    fn get_authorized_keys_path(username: &str) -> PathBuf {
892        #[cfg(unix)]
893        {
894            PathBuf::from(format!("/home/{}/.ssh/authorized_keys", username))
895        }
896        #[cfg(not(unix))]
897        {
898            PathBuf::from(format!("C:\\Users\\{}/.ssh/authorized_keys", username))
899        }
900    }
901
902    /// Handles authentication requests.
903    ///
904    /// This method should be called in a loop until authentication succeeds.
905    pub async fn authenticate(&mut self) -> FynxResult<()> {
906        let mut attempts = 0;
907
908        loop {
909            let packet = self.receive_packet().await?;
910            if packet.payload().is_empty() {
911                continue;
912            }
913
914            match packet.payload()[0] {
915                msg_type if msg_type == MessageType::ServiceRequest as u8 => {
916                    // Parse service request
917                    // For simplicity, just send SERVICE_ACCEPT for "ssh-userauth"
918                    let mut service_accept = vec![MessageType::ServiceAccept as u8];
919                    let service_name = b"ssh-userauth";
920                    service_accept.extend_from_slice(&(service_name.len() as u32).to_be_bytes());
921                    service_accept.extend_from_slice(service_name);
922                    self.send_packet(&service_accept).await?;
923                }
924                msg_type if msg_type == MessageType::UserauthRequest as u8 => {
925                    attempts += 1;
926
927                    let auth_request = AuthRequest::from_bytes(packet.payload())?;
928
929                    // Handle authentication based on method
930                    match auth_request.method() {
931                        AuthMethod::Password(password) => {
932                            let success = (self.auth_callback)(auth_request.user_name(), password);
933
934                            if success {
935                                // Send USERAUTH_SUCCESS
936                                let success_msg = vec![MessageType::UserauthSuccess as u8];
937                                self.send_packet(&success_msg).await?;
938                                self.authenticated_user =
939                                    Some(auth_request.user_name().to_string());
940                                return Ok(());
941                            } else {
942                                // Send USERAUTH_FAILURE
943                                let mut failure_msg = vec![MessageType::UserauthFailure as u8];
944                                let methods = b"password,publickey";
945                                failure_msg
946                                    .extend_from_slice(&(methods.len() as u32).to_be_bytes());
947                                failure_msg.extend_from_slice(methods);
948                                failure_msg.push(0); // partial_success = false
949                                self.send_packet(&failure_msg).await?;
950                            }
951                        }
952                        AuthMethod::None => {
953                            // Send USERAUTH_FAILURE for "none" method
954                            let mut failure_msg = vec![MessageType::UserauthFailure as u8];
955                            let methods = b"password,publickey";
956                            failure_msg.extend_from_slice(&(methods.len() as u32).to_be_bytes());
957                            failure_msg.extend_from_slice(methods);
958                            failure_msg.push(0); // partial_success = false
959                            self.send_packet(&failure_msg).await?;
960                        }
961                        AuthMethod::PublicKey {
962                            algorithm,
963                            public_key,
964                            signature,
965                        } => {
966                            // Public key authentication (RFC 4252 Section 7)
967                            let auth_result = self
968                                .handle_publickey_auth(
969                                    auth_request.user_name(),
970                                    algorithm,
971                                    public_key,
972                                    signature.as_deref(),
973                                )
974                                .await?;
975
976                            match auth_result {
977                                PublicKeyAuthResult::PkOk => {
978                                    // Try phase: send SSH_MSG_USERAUTH_PK_OK
979                                    let pk_ok =
980                                        AuthPkOk::new(algorithm.clone(), public_key.clone());
981                                    self.send_packet(&pk_ok.to_bytes()).await?;
982                                    // Don't increment attempts for try phase
983                                    attempts -= 1;
984                                }
985                                PublicKeyAuthResult::Success => {
986                                    // Sign phase: authentication succeeded
987                                    let success_msg = vec![MessageType::UserauthSuccess as u8];
988                                    self.send_packet(&success_msg).await?;
989                                    self.authenticated_user =
990                                        Some(auth_request.user_name().to_string());
991                                    return Ok(());
992                                }
993                                PublicKeyAuthResult::Failure => {
994                                    // Authentication failed
995                                    let mut failure_msg = vec![MessageType::UserauthFailure as u8];
996                                    let methods = b"password,publickey";
997                                    failure_msg
998                                        .extend_from_slice(&(methods.len() as u32).to_be_bytes());
999                                    failure_msg.extend_from_slice(methods);
1000                                    failure_msg.push(0); // partial_success = false
1001                                    self.send_packet(&failure_msg).await?;
1002                                }
1003                            }
1004                        }
1005                    }
1006
1007                    // Check max attempts
1008                    if attempts >= self.config.max_auth_attempts {
1009                        return Err(FynxError::Protocol(
1010                            "Max authentication attempts exceeded".to_string(),
1011                        ));
1012                    }
1013                }
1014                _ => {
1015                    return Err(FynxError::Protocol(format!(
1016                        "Unexpected message during auth: {}",
1017                        packet.payload()[0]
1018                    )));
1019                }
1020            }
1021        }
1022    }
1023
1024    /// Handles a session (after authentication).
1025    ///
1026    /// This method processes incoming requests using the provided handler.
1027    pub async fn handle_session<H: SessionHandler>(&mut self, handler: &mut H) -> FynxResult<()> {
1028        loop {
1029            let packet = self.receive_packet().await?;
1030            if packet.payload().is_empty() {
1031                continue;
1032            }
1033
1034            match packet.payload()[0] {
1035                msg_type if msg_type == MessageType::ChannelOpen as u8 => {
1036                    self.handle_channel_open(packet.payload()).await?;
1037                }
1038                msg_type if msg_type == MessageType::ChannelRequest as u8 => {
1039                    self.handle_channel_request(packet.payload(), handler)
1040                        .await?;
1041                }
1042                msg_type if msg_type == MessageType::ChannelClose as u8 => {
1043                    self.handle_channel_close(packet.payload()).await?;
1044                    break; // Exit after channel close
1045                }
1046                msg_type if msg_type == MessageType::Disconnect as u8 => {
1047                    break; // Client disconnected
1048                }
1049                _ => {
1050                    // Ignore unknown messages
1051                }
1052            }
1053        }
1054
1055        Ok(())
1056    }
1057
1058    /// Handles CHANNEL_OPEN request.
1059    async fn handle_channel_open(&mut self, payload: &[u8]) -> FynxResult<()> {
1060        let channel_open = ChannelOpen::from_bytes(payload)?;
1061
1062        // Assign local channel ID
1063        let local_channel = self.next_channel_id;
1064        self.next_channel_id += 1;
1065
1066        // Store channel state
1067        self.channels.insert(
1068            local_channel,
1069            ChannelState {
1070                _local_id: local_channel,
1071                _remote_id: channel_open.sender_channel(),
1072                _window_size: channel_open.initial_window_size(),
1073            },
1074        );
1075
1076        // Send CHANNEL_OPEN_CONFIRMATION
1077        let confirmation = ChannelOpenConfirmation::new(
1078            channel_open.sender_channel(), // recipient = client's sender channel
1079            local_channel,                 // our sender channel
1080            2097152,                       // initial window size (2 MB)
1081            32768,                         // max packet size (32 KB)
1082        );
1083
1084        self.send_packet(&confirmation.to_bytes()).await?;
1085
1086        Ok(())
1087    }
1088
1089    /// Handles CHANNEL_REQUEST.
1090    async fn handle_channel_request<H: SessionHandler>(
1091        &mut self,
1092        payload: &[u8],
1093        handler: &mut H,
1094    ) -> FynxResult<()> {
1095        let channel_request = ChannelRequest::from_bytes(payload)?;
1096        let channel_id = channel_request.recipient_channel();
1097
1098        match channel_request.request_type() {
1099            ChannelRequestType::Exec { command } => {
1100                // Send success
1101                if channel_request.want_reply() {
1102                    let success = ChannelSuccess::new(channel_id);
1103                    self.send_packet(&success.to_bytes()).await?;
1104                }
1105
1106                // Execute command
1107                let output = handler.handle_exec(command).await?;
1108
1109                // Send output
1110                let data = ChannelData::new(channel_id, output);
1111                self.send_packet(&data.to_bytes()).await?;
1112
1113                // Send EOF
1114                let eof = ChannelEof::new(channel_id);
1115                self.send_packet(&eof.to_bytes()).await?;
1116
1117                // Send close
1118                let close = ChannelClose::new(channel_id);
1119                self.send_packet(&close.to_bytes()).await?;
1120            }
1121            ChannelRequestType::Shell => {
1122                handler.handle_shell().await?;
1123            }
1124            ChannelRequestType::Subsystem { name } => {
1125                handler.handle_subsystem(name).await?;
1126            }
1127            _ => {
1128                // Not supported
1129            }
1130        }
1131
1132        Ok(())
1133    }
1134
1135    /// Handles CHANNEL_CLOSE.
1136    async fn handle_channel_close(&mut self, _payload: &[u8]) -> FynxResult<()> {
1137        // Just acknowledge - actual cleanup would happen here
1138        Ok(())
1139    }
1140
1141    /// Sends a packet.
1142    async fn send_packet(&mut self, payload: &[u8]) -> FynxResult<()> {
1143        let packet = Packet::new(payload.to_vec());
1144        let mut bytes = packet.to_bytes();
1145
1146        // If encryption is active, encrypt the packet
1147        if self.transport.is_encrypted() {
1148            if let Some(enc_params) = self.transport.encryption_params_mut() {
1149                if let Some(enc_key) = &mut enc_params.encryption_key {
1150                    // For AEAD ciphers (ChaCha20-Poly1305, AES-GCM), the packet format is:
1151                    // uint32 packet_length || encrypted(padding_length || payload || padding) || auth_tag
1152                    // The packet_length is sent in cleartext, the rest is encrypted
1153
1154                    // Extract packet_length (first 4 bytes) - sent in cleartext
1155                    let packet_length = bytes[0..4].to_vec();
1156
1157                    // Extract the rest (padding_length + payload + padding) to encrypt
1158                    let mut plaintext = bytes[4..].to_vec();
1159
1160                    // Encrypt in place (this will append the auth tag automatically)
1161                    // The Counter inside enc_key will manage the nonce/sequence
1162                    enc_key.encrypt(&mut plaintext)?;
1163
1164                    // Reconstruct: packet_length || ciphertext || tag
1165                    let mut encrypted_packet = Vec::new();
1166                    encrypted_packet.extend_from_slice(&packet_length);
1167                    encrypted_packet.extend_from_slice(&plaintext);
1168
1169                    bytes = encrypted_packet;
1170                }
1171            }
1172        }
1173
1174        self.stream.write_all(&bytes).await.map_err(FynxError::Io)?;
1175
1176        // Track bytes transferred for rekey
1177        self.transport.add_bytes(bytes.len() as u64);
1178
1179        Ok(())
1180    }
1181
1182    /// Receives a packet.
1183    async fn receive_packet(&mut self) -> FynxResult<Packet> {
1184        // Read packet length (first 4 bytes) - always in cleartext
1185        let mut length_bytes = [0u8; 4];
1186        self.stream
1187            .read_exact(&mut length_bytes)
1188            .await
1189            .map_err(FynxError::Io)?;
1190        let packet_length = u32::from_be_bytes(length_bytes) as usize;
1191
1192        // If encryption is active, we need to read ciphertext + auth tag
1193        let bytes_to_read = if self.transport.is_encrypted() {
1194            // For AEAD: packet_length bytes of ciphertext + 16 bytes auth tag
1195            packet_length + 16
1196        } else {
1197            // Unencrypted: just packet_length bytes
1198            packet_length
1199        };
1200
1201        // Read the packet data (or ciphertext + tag)
1202        let mut packet_data = vec![0u8; bytes_to_read];
1203        self.stream
1204            .read_exact(&mut packet_data)
1205            .await
1206            .map_err(FynxError::Io)?;
1207
1208        // If encryption is active, decrypt the packet
1209        if self.transport.is_encrypted() {
1210            if let Some(enc_params) = self.transport.encryption_params_mut() {
1211                if let Some(dec_key) = &mut enc_params.decryption_key {
1212                    // packet_data contains: ciphertext || auth_tag
1213                    // decrypt() will verify the tag and decrypt in place
1214                    dec_key.decrypt(&mut packet_data)?;
1215
1216                    // After successful decryption, packet_data contains just the plaintext
1217                    // (tag has been verified and removed by decrypt)
1218
1219                    // Reconstruct packet: packet_length || plaintext
1220                    let mut full_packet = Vec::new();
1221                    full_packet.extend_from_slice(&length_bytes);
1222                    full_packet.extend_from_slice(&packet_data);
1223
1224                    // Track bytes for rekey
1225                    self.transport.add_bytes(full_packet.len() as u64 + 16); // +16 for auth tag
1226
1227                    return Packet::from_bytes(&full_packet);
1228                }
1229            }
1230        }
1231
1232        // Unencrypted path
1233        let mut full_packet = Vec::new();
1234        full_packet.extend_from_slice(&length_bytes);
1235        full_packet.extend_from_slice(&packet_data);
1236
1237        // Track bytes for rekey
1238        self.transport.add_bytes(full_packet.len() as u64);
1239
1240        Packet::from_bytes(&full_packet)
1241    }
1242
1243    /// Returns the authenticated username.
1244    pub fn username(&self) -> Option<&str> {
1245        self.authenticated_user.as_deref()
1246    }
1247
1248    /// Returns the peer address.
1249    pub fn peer_address(&self) -> &str {
1250        &self.peer_addr
1251    }
1252
1253    /// Returns whether authenticated.
1254    pub fn is_authenticated(&self) -> bool {
1255        self.authenticated_user.is_some()
1256    }
1257}
1258
1259#[cfg(test)]
1260mod tests {
1261    use super::*;
1262    use crate::ssh::auth::construct_signature_data;
1263    use crate::ssh::privatekey::{Ed25519PrivateKey, PrivateKey};
1264
1265    #[test]
1266    fn test_config_default() {
1267        let config = SshServerConfig::default();
1268        assert_eq!(config.max_auth_attempts, 3);
1269        assert_eq!(config.server_version, "Fynx_0.1.0");
1270    }
1271
1272    #[test]
1273    fn test_auth_callback() {
1274        let callback: AuthCallback =
1275            Arc::new(|username, password| username == "test" && password == "pass");
1276
1277        assert!(callback("test", "pass"));
1278        assert!(!callback("test", "wrong"));
1279        assert!(!callback("wrong", "pass"));
1280    }
1281
1282    // Helper function to create a test Ed25519 key pair
1283    fn create_test_ed25519_keypair() -> (PrivateKey, Vec<u8>) {
1284        use rand::RngCore;
1285
1286        let mut seed = [0u8; 32];
1287        rand::thread_rng().fill_bytes(&mut seed);
1288
1289        let private_key = Ed25519PrivateKey::from_seed(seed);
1290        let public_key = private_key.public_key();
1291        let public_key_blob = public_key.to_ssh_bytes();
1292
1293        (PrivateKey::Ed25519(private_key), public_key_blob)
1294    }
1295
1296    #[test]
1297    fn test_get_authorized_keys_path() {
1298        #[cfg(unix)]
1299        {
1300            let path = SshSession::get_authorized_keys_path("alice");
1301            assert_eq!(path, PathBuf::from("/home/alice/.ssh/authorized_keys"));
1302        }
1303
1304        #[cfg(not(unix))]
1305        {
1306            let path = SshSession::get_authorized_keys_path("alice");
1307            assert_eq!(path, PathBuf::from("C:\\Users\\alice/.ssh/authorized_keys"));
1308        }
1309    }
1310
1311    #[test]
1312    fn test_public_key_auth_result_enum() {
1313        // Test that the enum variants exist
1314        let _pk_ok = PublicKeyAuthResult::PkOk;
1315        let _success = PublicKeyAuthResult::Success;
1316        let _failure = PublicKeyAuthResult::Failure;
1317    }
1318
1319    // Note: test_verify_signature_invalid_blob removed to avoid unsafe code
1320    // The verify_signature method is tested indirectly through other tests
1321
1322    // Note: Direct signature verification tests removed to avoid unsafe code.
1323    // The verify_signature and handle_publickey_auth methods will be tested
1324    // through integration tests with real server instances.
1325}