1use bytes::{BufMut, BytesMut};
28use fynx_platform::{FynxError, FynxResult};
29use sha2::{Digest, Sha256};
30use subtle::ConstantTimeEq;
31use zeroize::Zeroize;
32
33#[derive(Debug, Clone, PartialEq, Eq)]
35pub enum AuthMethod {
36 None,
38 Password(String),
40 PublicKey {
42 algorithm: String,
44 public_key: Vec<u8>,
46 signature: Option<Vec<u8>>,
48 },
49}
50
51impl AuthMethod {
52 pub fn name(&self) -> &str {
54 match self {
55 AuthMethod::None => "none",
56 AuthMethod::Password(_) => "password",
57 AuthMethod::PublicKey { .. } => "publickey",
58 }
59 }
60}
61
62impl Drop for AuthMethod {
63 fn drop(&mut self) {
64 if let AuthMethod::Password(ref mut password) = self {
66 password.zeroize();
67 }
68 }
69}
70
71#[derive(Debug, Clone, PartialEq, Eq)]
75pub struct AuthRequest {
76 user_name: String,
78 service_name: String,
80 method: AuthMethod,
82}
83
84impl AuthRequest {
85 pub fn new(user_name: &str, service_name: &str, method: AuthMethod) -> Self {
105 Self {
106 user_name: user_name.to_string(),
107 service_name: service_name.to_string(),
108 method,
109 }
110 }
111
112 pub fn user_name(&self) -> &str {
114 &self.user_name
115 }
116
117 pub fn service_name(&self) -> &str {
119 &self.service_name
120 }
121
122 pub fn method(&self) -> &AuthMethod {
124 &self.method
125 }
126
127 pub fn to_bytes(&self) -> Vec<u8> {
138 let mut buf = BytesMut::new();
139
140 buf.put_u8(50);
142
143 write_string(&mut buf, &self.user_name);
145
146 write_string(&mut buf, &self.service_name);
148
149 write_string(&mut buf, self.method.name());
151
152 match &self.method {
154 AuthMethod::None => {
155 }
157 AuthMethod::Password(password) => {
158 buf.put_u8(0);
160 write_string(&mut buf, password);
162 }
163 AuthMethod::PublicKey {
164 algorithm,
165 public_key,
166 signature,
167 } => {
168 buf.put_u8(if signature.is_some() { 1 } else { 0 });
170 write_string(&mut buf, algorithm);
172 write_bytes(&mut buf, public_key);
174 if let Some(sig) = signature {
176 write_bytes(&mut buf, sig);
177 }
178 }
179 }
180
181 buf.to_vec()
182 }
183
184 pub fn from_bytes(data: &[u8]) -> FynxResult<Self> {
190 if data.is_empty() {
191 return Err(FynxError::Protocol(
192 "USERAUTH_REQUEST message is empty".to_string(),
193 ));
194 }
195
196 if data[0] != 50 {
198 return Err(FynxError::Protocol(format!(
199 "Invalid message type: expected 50 (SSH_MSG_USERAUTH_REQUEST), got {}",
200 data[0]
201 )));
202 }
203
204 let mut offset = 1;
205
206 let user_name = read_string(data, &mut offset)?;
208
209 let service_name = read_string(data, &mut offset)?;
211
212 let method_name = read_string(data, &mut offset)?;
214
215 let method = match method_name.as_str() {
217 "none" => AuthMethod::None,
218 "password" => {
219 if offset >= data.len() {
221 return Err(FynxError::Protocol(
222 "USERAUTH_REQUEST truncated (missing password change flag)".to_string(),
223 ));
224 }
225 let _changing = data[offset] != 0;
226 offset += 1;
227
228 let password = read_string(data, &mut offset)?;
230 AuthMethod::Password(password)
231 }
232 "publickey" => {
233 if offset >= data.len() {
235 return Err(FynxError::Protocol(
236 "USERAUTH_REQUEST truncated (missing publickey signature flag)".to_string(),
237 ));
238 }
239 let has_signature = data[offset] != 0;
240 offset += 1;
241
242 let algorithm = read_string(data, &mut offset)?;
244
245 let public_key = read_bytes(data, &mut offset)?;
247
248 let signature = if has_signature {
250 Some(read_bytes(data, &mut offset)?)
251 } else {
252 None
253 };
254
255 AuthMethod::PublicKey {
256 algorithm,
257 public_key,
258 signature,
259 }
260 }
261 _ => {
262 return Err(FynxError::Protocol(format!(
263 "Unsupported authentication method: '{}'",
264 method_name
265 )))
266 }
267 };
268
269 Ok(Self {
270 user_name,
271 service_name,
272 method,
273 })
274 }
275}
276
277#[derive(Debug, Clone, PartialEq, Eq)]
281pub struct AuthFailure {
282 methods_can_continue: Vec<String>,
284 partial_success: bool,
286}
287
288impl AuthFailure {
289 pub fn new(methods: Vec<String>, partial_success: bool) -> Self {
307 Self {
308 methods_can_continue: methods,
309 partial_success,
310 }
311 }
312
313 pub fn methods_can_continue(&self) -> &[String] {
315 &self.methods_can_continue
316 }
317
318 pub fn partial_success(&self) -> bool {
320 self.partial_success
321 }
322
323 pub fn to_bytes(&self) -> Vec<u8> {
325 let mut buf = BytesMut::new();
326
327 buf.put_u8(51);
329
330 let methods_str = self.methods_can_continue.join(",");
332 write_string(&mut buf, &methods_str);
333
334 buf.put_u8(if self.partial_success { 1 } else { 0 });
336
337 buf.to_vec()
338 }
339
340 pub fn from_bytes(data: &[u8]) -> FynxResult<Self> {
342 if data.is_empty() {
343 return Err(FynxError::Protocol(
344 "USERAUTH_FAILURE message is empty".to_string(),
345 ));
346 }
347
348 if data[0] != 51 {
349 return Err(FynxError::Protocol(format!(
350 "Invalid message type: expected 51 (SSH_MSG_USERAUTH_FAILURE), got {}",
351 data[0]
352 )));
353 }
354
355 let mut offset = 1;
356
357 let methods_str = read_string(data, &mut offset)?;
359 let methods_can_continue: Vec<String> = if methods_str.is_empty() {
360 vec![]
361 } else {
362 methods_str.split(',').map(String::from).collect()
363 };
364
365 if offset >= data.len() {
367 return Err(FynxError::Protocol(
368 "USERAUTH_FAILURE truncated (missing partial success flag)".to_string(),
369 ));
370 }
371 let partial_success = data[offset] != 0;
372
373 Ok(Self {
374 methods_can_continue,
375 partial_success,
376 })
377 }
378}
379
380#[derive(Debug, Clone, Copy, PartialEq, Eq)]
384pub struct AuthSuccess;
385
386impl AuthSuccess {
387 pub fn new() -> Self {
389 Self
390 }
391
392 pub fn to_bytes(&self) -> Vec<u8> {
394 vec![52] }
396
397 pub fn from_bytes(data: &[u8]) -> FynxResult<Self> {
399 if data.is_empty() || data[0] != 52 {
400 return Err(FynxError::Protocol(
401 "Invalid USERAUTH_SUCCESS message".to_string(),
402 ));
403 }
404 Ok(Self)
405 }
406}
407
408impl Default for AuthSuccess {
409 fn default() -> Self {
410 Self::new()
411 }
412}
413
414#[derive(Debug, Clone, PartialEq, Eq)]
418pub struct AuthBanner {
419 message: String,
421 language_tag: String,
423}
424
425impl AuthBanner {
426 pub fn new(message: String) -> Self {
428 Self {
429 message,
430 language_tag: String::new(),
431 }
432 }
433
434 pub fn message(&self) -> &str {
436 &self.message
437 }
438
439 pub fn to_bytes(&self) -> Vec<u8> {
441 let mut buf = BytesMut::new();
442
443 buf.put_u8(53);
445
446 write_string(&mut buf, &self.message);
448
449 write_string(&mut buf, &self.language_tag);
451
452 buf.to_vec()
453 }
454
455 pub fn from_bytes(data: &[u8]) -> FynxResult<Self> {
457 if data.is_empty() {
458 return Err(FynxError::Protocol(
459 "USERAUTH_BANNER message is empty".to_string(),
460 ));
461 }
462
463 if data[0] != 53 {
464 return Err(FynxError::Protocol(format!(
465 "Invalid message type: expected 53 (SSH_MSG_USERAUTH_BANNER), got {}",
466 data[0]
467 )));
468 }
469
470 let mut offset = 1;
471
472 let message = read_string(data, &mut offset)?;
473 let language_tag = read_string(data, &mut offset)?;
474
475 Ok(Self {
476 message,
477 language_tag,
478 })
479 }
480}
481
482#[derive(Debug, Clone, PartialEq, Eq)]
487pub struct AuthPkOk {
488 algorithm: String,
490 public_key: Vec<u8>,
492}
493
494impl AuthPkOk {
495 pub fn new(algorithm: impl Into<String>, public_key: Vec<u8>) -> Self {
510 Self {
511 algorithm: algorithm.into(),
512 public_key,
513 }
514 }
515
516 pub fn algorithm(&self) -> &str {
518 &self.algorithm
519 }
520
521 pub fn public_key(&self) -> &[u8] {
523 &self.public_key
524 }
525
526 pub fn to_bytes(&self) -> Vec<u8> {
535 let mut buf = BytesMut::new();
536
537 buf.put_u8(60);
539
540 write_string(&mut buf, &self.algorithm);
542
543 write_bytes(&mut buf, &self.public_key);
545
546 buf.to_vec()
547 }
548
549 pub fn from_bytes(data: &[u8]) -> FynxResult<Self> {
555 if data.is_empty() {
556 return Err(FynxError::Protocol(
557 "USERAUTH_PK_OK message is empty".to_string(),
558 ));
559 }
560
561 if data[0] != 60 {
562 return Err(FynxError::Protocol(format!(
563 "Invalid message type: expected 60 (SSH_MSG_USERAUTH_PK_OK), got {}",
564 data[0]
565 )));
566 }
567
568 let mut offset = 1;
569
570 let algorithm = read_string(data, &mut offset)?;
572
573 let public_key = read_bytes(data, &mut offset)?;
575
576 Ok(Self {
577 algorithm,
578 public_key,
579 })
580 }
581}
582
583pub fn construct_signature_data(
610 session_id: &[u8],
611 user_name: &str,
612 service_name: &str,
613 algorithm: &str,
614 public_key_blob: &[u8],
615) -> Vec<u8> {
616 let mut buf = BytesMut::new();
617
618 write_bytes(&mut buf, session_id);
620
621 buf.put_u8(50);
623
624 write_string(&mut buf, user_name);
626
627 write_string(&mut buf, service_name);
629
630 write_string(&mut buf, "publickey");
632
633 buf.put_u8(1);
635
636 write_string(&mut buf, algorithm);
638
639 write_bytes(&mut buf, public_key_blob);
641
642 buf.to_vec()
643}
644
645pub fn constant_time_compare(a: &str, b: &str) -> bool {
670 let hash_a = Sha256::digest(a.as_bytes());
673 let hash_b = Sha256::digest(b.as_bytes());
674
675 hash_a.ct_eq(&hash_b).into()
677}
678
679fn write_string(buf: &mut BytesMut, s: &str) {
682 let bytes = s.as_bytes();
683 buf.put_u32(bytes.len() as u32);
684 buf.put_slice(bytes);
685}
686
687fn write_bytes(buf: &mut BytesMut, bytes: &[u8]) {
688 buf.put_u32(bytes.len() as u32);
689 buf.put_slice(bytes);
690}
691
692fn read_string(data: &[u8], offset: &mut usize) -> FynxResult<String> {
693 let bytes = read_bytes(data, offset)?;
694 String::from_utf8(bytes)
695 .map_err(|_| FynxError::Protocol("String contains invalid UTF-8".to_string()))
696}
697
698fn read_bytes(data: &[u8], offset: &mut usize) -> FynxResult<Vec<u8>> {
699 if *offset + 4 > data.len() {
700 return Err(FynxError::Protocol(format!(
701 "Cannot read length at offset {}",
702 offset
703 )));
704 }
705
706 let length = u32::from_be_bytes([
707 data[*offset],
708 data[*offset + 1],
709 data[*offset + 2],
710 data[*offset + 3],
711 ]) as usize;
712 *offset += 4;
713
714 if *offset + length > data.len() {
715 return Err(FynxError::Protocol(format!(
716 "Data truncated: expected {} bytes at offset {}",
717 length, offset
718 )));
719 }
720
721 let bytes = data[*offset..*offset + length].to_vec();
722 *offset += length;
723
724 Ok(bytes)
725}
726
727#[cfg(test)]
728mod tests {
729 use super::*;
730
731 #[test]
732 fn test_auth_request_password() {
733 let auth = AuthRequest::new(
734 "alice",
735 "ssh-connection",
736 AuthMethod::Password("secret".to_string()),
737 );
738
739 assert_eq!(auth.user_name(), "alice");
740 assert_eq!(auth.service_name(), "ssh-connection");
741 assert_eq!(auth.method().name(), "password");
742
743 let bytes = auth.to_bytes();
744 let parsed = AuthRequest::from_bytes(&bytes).unwrap();
745
746 assert_eq!(parsed.user_name(), "alice");
747 assert_eq!(parsed.service_name(), "ssh-connection");
748 if let AuthMethod::Password(pw) = parsed.method() {
749 assert_eq!(pw, "secret");
750 } else {
751 panic!("Expected Password method");
752 }
753 }
754
755 #[test]
756 fn test_auth_request_publickey() {
757 let public_key = vec![1, 2, 3, 4];
758 let auth = AuthRequest::new(
759 "bob",
760 "ssh-connection",
761 AuthMethod::PublicKey {
762 algorithm: "ssh-ed25519".to_string(),
763 public_key: public_key.clone(),
764 signature: None,
765 },
766 );
767
768 let bytes = auth.to_bytes();
769 let parsed = AuthRequest::from_bytes(&bytes).unwrap();
770
771 if let AuthMethod::PublicKey {
772 algorithm,
773 public_key: pk,
774 signature,
775 } = parsed.method()
776 {
777 assert_eq!(algorithm, "ssh-ed25519");
778 assert_eq!(pk, &public_key);
779 assert!(signature.is_none());
780 } else {
781 panic!("Expected PublicKey method");
782 }
783 }
784
785 #[test]
786 fn test_auth_request_none() {
787 let auth = AuthRequest::new("test", "ssh-connection", AuthMethod::None);
788
789 let bytes = auth.to_bytes();
790 let parsed = AuthRequest::from_bytes(&bytes).unwrap();
791
792 assert_eq!(parsed.method(), &AuthMethod::None);
793 }
794
795 #[test]
796 fn test_auth_failure() {
797 let failure =
798 AuthFailure::new(vec!["publickey".to_string(), "password".to_string()], false);
799
800 assert_eq!(
801 failure.methods_can_continue(),
802 &["publickey".to_string(), "password".to_string()]
803 );
804 assert!(!failure.partial_success());
805
806 let bytes = failure.to_bytes();
807 let parsed = AuthFailure::from_bytes(&bytes).unwrap();
808
809 assert_eq!(
810 parsed.methods_can_continue(),
811 failure.methods_can_continue()
812 );
813 assert_eq!(parsed.partial_success(), failure.partial_success());
814 }
815
816 #[test]
817 fn test_auth_success() {
818 let success = AuthSuccess::new();
819 let bytes = success.to_bytes();
820 let parsed = AuthSuccess::from_bytes(&bytes).unwrap();
821 assert_eq!(parsed, success);
822 }
823
824 #[test]
825 fn test_auth_banner() {
826 let banner = AuthBanner::new("Welcome to SSH Server".to_string());
827 assert_eq!(banner.message(), "Welcome to SSH Server");
828
829 let bytes = banner.to_bytes();
830 let parsed = AuthBanner::from_bytes(&bytes).unwrap();
831 assert_eq!(parsed.message(), banner.message());
832 }
833
834 #[test]
835 fn test_constant_time_compare() {
836 assert!(constant_time_compare("password123", "password123"));
837 assert!(!constant_time_compare("password123", "password124"));
838 assert!(!constant_time_compare("short", "verylongpassword"));
839 }
840
841 #[test]
842 fn test_auth_method_zeroize() {
843 let method = AuthMethod::Password("secret".to_string());
844 drop(method);
845 }
847
848 #[test]
849 fn test_auth_pk_ok() {
850 let public_key = vec![1, 2, 3, 4, 5, 6, 7, 8];
851 let pk_ok = AuthPkOk::new("ssh-ed25519", public_key.clone());
852
853 assert_eq!(pk_ok.algorithm(), "ssh-ed25519");
854 assert_eq!(pk_ok.public_key(), &public_key);
855
856 let bytes = pk_ok.to_bytes();
857 assert_eq!(bytes[0], 60); let parsed = AuthPkOk::from_bytes(&bytes).unwrap();
860 assert_eq!(parsed.algorithm(), "ssh-ed25519");
861 assert_eq!(parsed.public_key(), &public_key);
862 }
863
864 #[test]
865 fn test_auth_pk_ok_invalid_message_type() {
866 let data = vec![50, 0, 0, 0, 0]; let result = AuthPkOk::from_bytes(&data);
868 assert!(result.is_err());
869 }
870
871 #[test]
872 fn test_construct_signature_data() {
873 let session_id = vec![1, 2, 3, 4];
874 let user_name = "alice";
875 let service_name = "ssh-connection";
876 let algorithm = "ssh-ed25519";
877 let public_key_blob = vec![5, 6, 7, 8];
878
879 let data = construct_signature_data(
880 &session_id,
881 user_name,
882 service_name,
883 algorithm,
884 &public_key_blob,
885 );
886
887 assert!(!data.is_empty());
889
890 let sid_len = u32::from_be_bytes([data[0], data[1], data[2], data[3]]) as usize;
892 assert_eq!(sid_len, session_id.len());
893 assert_eq!(&data[4..4 + sid_len], &session_id[..]);
894
895 let msg_type_offset = 4 + sid_len;
897 assert_eq!(data[msg_type_offset], 50);
898 }
899}