diff --git a/.rustfmt.toml b/.rustfmt.toml index e775cae..01d19c3 100644 --- a/.rustfmt.toml +++ b/.rustfmt.toml @@ -1,10 +1,6 @@ -chain_split_single_child = true -closure_block_indent_threshold = 1 -fn_args_density = "Compressed" + wrap_comments = true control_brace_style = "ClosingNextLine" max_width = 80 -reorder_imported_names = true reorder_imports = true -reorder_imports_in_group = true use_try_shorthand = true \ No newline at end of file diff --git a/src/algorithm.rs b/src/algorithm.rs index becd6e0..f8bbba4 100644 --- a/src/algorithm.rs +++ b/src/algorithm.rs @@ -5,16 +5,15 @@ use crate::error::{ConnectionError, ConnectionResult}; use crate::key_exchange::{self, KeyExchange}; /// Slice of implemented key exchange algorithms, ordered by preference -pub static KEY_EXCHANGE: &[KeyExchangeAlgorithm] = - &[ +pub static KEY_EXCHANGE: &[KeyExchangeAlgorithm] = &[ KeyExchangeAlgorithm::CURVE25519_SHA256, -// KeyExchangeAlgorithm::DH_GROUP_EXCHANGE_SHA1, + // KeyExchangeAlgorithm::DH_GROUP_EXCHANGE_SHA1, ]; /// Slice of implemented host key algorithms, ordered by preference pub static HOST_KEY: &[PublicKeyAlgorithm] = &[ PublicKeyAlgorithm::SSH_ED25519, -// PublicKeyAlgorithm::SSH_RSA, + // PublicKeyAlgorithm::SSH_RSA, ]; /// Slice of implemented encryption algorithms, ordered by preference @@ -29,8 +28,10 @@ pub static COMPRESSION: &[CompressionAlgorithm] = &[CompressionAlgorithm::None, CompressionAlgorithm::Zlib]; /// Find the best matching algorithm -pub fn negotiate(server: &[A], client: &[A]) - -> ConnectionResult { +pub fn negotiate( + server: &[A], + client: &[A], +) -> ConnectionResult { for algorithm in client.iter() { if server.iter().any(|a| a == algorithm) { return Ok(*algorithm); @@ -59,11 +60,10 @@ pub enum KeyExchangeAlgorithm { impl KeyExchangeAlgorithm { pub fn instance(&self) -> Option> { use self::KeyExchangeAlgorithm::*; - match self - { - &CURVE25519_SHA256 => Some( - Box::new(key_exchange::Curve25519::new()), - ), + match self { + &CURVE25519_SHA256 => { + Some(Box::new(key_exchange::Curve25519::new())) + } _ => None, } } @@ -73,15 +73,14 @@ impl FromStr for KeyExchangeAlgorithm { type Err = (); fn from_str(s: &str) -> Result { use self::KeyExchangeAlgorithm::*; - match s - { + match s { "curve25519-sha256" => Ok(CURVE25519_SHA256), "ecdh-sha2-nistp256" => Ok(ECDH_SHA2_NISTP256), "ecdh-sha2-nistp384" => Ok(ECDH_SHA2_NISTP384), "ecdh-sha2-nistp521" => Ok(ECDH_SHA2_NISTP521), - "diffie-hellman-group-exchange-sha256" => Ok( - DH_GROUP_EXCHANGE_SHA256, - ), + "diffie-hellman-group-exchange-sha256" => { + Ok(DH_GROUP_EXCHANGE_SHA256) + } "diffie-hellman-group-exchange-sha1" => Ok(DH_GROUP_EXCHANGE_SHA1), "diffie-hellman-group16-sha512" => Ok(DH_GROUP16_SHA512), "diffie-hellman-group18-sha512" => Ok(DH_GROUP18_SHA512), @@ -99,8 +98,7 @@ impl FromStr for KeyExchangeAlgorithm { impl fmt::Display for KeyExchangeAlgorithm { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::KeyExchangeAlgorithm::*; - f.write_str(match *self - { + f.write_str(match *self { CURVE25519_SHA256 => "curve25519-sha256", ECDH_SHA2_NISTP256 => "ecdh-sha2-nistp256", ECDH_SHA2_NISTP384 => "ecdh-sha2-nistp384", @@ -132,8 +130,7 @@ impl FromStr for PublicKeyAlgorithm { type Err = (); fn from_str(s: &str) -> Result { use self::PublicKeyAlgorithm::*; - match s - { + match s { "ssh-rsa" => Ok(SSH_RSA), "rsa-sha2-256" => Ok(RSA_SHA2_256), "rsa-sha2-512" => Ok(RSA_SHA2_512), @@ -152,8 +149,7 @@ impl FromStr for PublicKeyAlgorithm { impl fmt::Display for PublicKeyAlgorithm { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::PublicKeyAlgorithm::*; - f.write_str(match *self - { + f.write_str(match *self { SSH_RSA => "ssh-rsa", RSA_SHA2_256 => "rsa-sha2-256", RSA_SHA2_512 => "rsa-sha2-512", @@ -181,8 +177,7 @@ impl FromStr for EncryptionAlgorithm { type Err = (); fn from_str(s: &str) -> Result { use self::EncryptionAlgorithm::*; - match s - { + match s { "aes128-ctr" => Ok(AES128_CTR), "aes128-cbc" => Ok(AES128_CBC), "aes192-ctr" => Ok(AES192_CTR), @@ -201,8 +196,7 @@ impl FromStr for EncryptionAlgorithm { impl fmt::Display for EncryptionAlgorithm { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::EncryptionAlgorithm::*; - f.write_str(match *self - { + f.write_str(match *self { AES128_CTR => "aes128-ctr", AES128_CBC => "aes128-cbc", AES192_CTR => "aes192-ctr", @@ -227,8 +221,7 @@ impl FromStr for MacAlgorithm { type Err = (); fn from_str(s: &str) -> Result { use self::MacAlgorithm::*; - match s - { + match s { "hmac-sha1" => Ok(HMAC_SHA1), "hmac-sha2-256" => Ok(HMAC_SHA2_256), "hmac-sha2-512" => Ok(HMAC_SHA2_512), @@ -244,8 +237,7 @@ impl FromStr for MacAlgorithm { impl fmt::Display for MacAlgorithm { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::MacAlgorithm::*; - f.write_str(match *self - { + f.write_str(match *self { HMAC_SHA1 => "hmac-sha1", HMAC_SHA2_256 => "hmac-sha2-256", HMAC_SHA2_512 => "hmac-sha2-512", @@ -263,8 +255,7 @@ pub enum CompressionAlgorithm { impl FromStr for CompressionAlgorithm { type Err = (); fn from_str(s: &str) -> Result { - match s - { + match s { "zlib" => Ok(CompressionAlgorithm::Zlib), "none" => Ok(CompressionAlgorithm::None), _ => { @@ -277,8 +268,7 @@ impl FromStr for CompressionAlgorithm { impl fmt::Display for CompressionAlgorithm { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.write_str(match *self - { + f.write_str(match *self { CompressionAlgorithm::Zlib => "zlib", CompressionAlgorithm::None => "none", }) diff --git a/src/bin/sshd.rs b/src/bin/sshd.rs index 77a398f..df2fb84 100644 --- a/src/bin/sshd.rs +++ b/src/bin/sshd.rs @@ -1,5 +1,5 @@ -extern crate ssh; extern crate log; +extern crate ssh; use std::env; use std::fs::File; @@ -8,8 +8,8 @@ use std::str::FromStr; use log::{LevelFilter, Metadata, Record}; -use ssh::{Server, ServerConfig}; use ssh::public_key::ED25519; +use ssh::{Server, ServerConfig}; struct StdErrLogger; @@ -23,7 +23,7 @@ impl log::Log for StdErrLogger { eprintln!("{} - {}", record.level(), record.args()); } } - + fn flush(&self) { todo!() } @@ -33,9 +33,8 @@ pub fn main() { let mut verbosity = LevelFilter::Warn; let mut foreground = false; - let key_pair = File::open("server.key").and_then( - |mut f| (ED25519.import)(&mut f), - ); + let key_pair = + File::open("server.key").and_then(|mut f| (ED25519.import)(&mut f)); if let Some(ref err) = key_pair.as_ref().err() { eprintln!("sshd: failed to open server.key: {}", err); @@ -50,17 +49,16 @@ pub fn main() { let mut args = env::args().skip(1); while let Some(arg) = args.next() { - match arg.as_ref() - { + match arg.as_ref() { "-v" => verbosity = LevelFilter::Info, "-vv" => verbosity = LevelFilter::Debug, "-vvv" => verbosity = LevelFilter::Trace, "-f" => foreground = true, "-p" => { - config.port = - u16::from_str( - &args.next().expect("sshd: no argument to -p option"), - ).expect("sshd: invalid port number to -p option"); + config.port = u16::from_str( + &args.next().expect("sshd: no argument to -p option"), + ) + .expect("sshd: invalid port number to -p option"); } _ => (), } diff --git a/src/channel.rs b/src/channel.rs index e6b6fdd..d53d175 100644 --- a/src/channel.rs +++ b/src/channel.rs @@ -114,8 +114,7 @@ impl Channel { /// Reads data **from** this channel and writes it **to** the buffer/. pub fn read_stdout(&mut self, buf: &mut String) -> io::Result { if let Some(pipes) = &mut self.pipes { - let res_len = pipes.stdout.read_line(buf); - res_len + pipes.stdout.read_line(buf) } else { Ok(0) @@ -124,8 +123,7 @@ impl Channel { pub fn read_stderr(&mut self, buf: &mut String) -> io::Result { if let Some(pipes) = &mut self.pipes { - let res_len = pipes.stderr.read_line(buf); - res_len + pipes.stderr.read_line(buf) } else { Ok(0) diff --git a/src/channel/pty.rs b/src/channel/pty.rs index f45833d..dadde7a 100644 --- a/src/channel/pty.rs +++ b/src/channel/pty.rs @@ -1,4 +1,9 @@ -use std::{fs::File, io::{Read, Write}, os::fd::FromRawFd, thread}; +use std::{ + fs::File, + io::{Read, Write}, + os::fd::FromRawFd, + thread, +}; use crate::sys; @@ -53,7 +58,7 @@ impl Channel { Err(e) => { warn!("Error occured, ignoring: {}", e); 1 // TODO - }, + } }; // This is weird. diff --git a/src/channel/shell.rs b/src/channel/shell.rs index 18538f7..645fe68 100644 --- a/src/channel/shell.rs +++ b/src/channel/shell.rs @@ -1,8 +1,12 @@ use std::{ - fs::OpenOptions, io::{stdin, BufReader}, os::{ + fs::OpenOptions, + io::{stdin, BufReader}, + os::{ fd::{FromRawFd, IntoRawFd, RawFd}, unix::process::CommandExt, - }, path::PathBuf, process::{self, ChildStderr, ChildStdin, ChildStdout, Stdio} + }, + path::PathBuf, + process::{self, ChildStderr, ChildStdin, ChildStdout, Stdio}, }; use crate::sys; @@ -27,7 +31,7 @@ impl Channel { non_blockify_reader(pipes.stdout.get_ref()); non_blockify_reader(pipes.stderr.get_ref()); self.pipes = Some(pipes); - }, + } } } @@ -72,6 +76,8 @@ fn with_tty(tty_path: &PathBuf) { } .spawn() .unwrap(); + + // TODO: TTY is broken } fn open_tty(tty_path: &PathBuf, read: bool, write: bool) -> RawFd { diff --git a/src/connection.rs b/src/connection.rs index 463cc62..11cfb74 100644 --- a/src/connection.rs +++ b/src/connection.rs @@ -1,5 +1,6 @@ use std::collections::{BTreeMap, VecDeque}; use std::io::{self, BufReader, Read, Write}; +use std::os::fd::AsRawFd; use std::sync::Arc; use rand::distributions::Standard; @@ -62,7 +63,10 @@ impl Connection { } } - pub fn run(&mut self, stream: &mut S) -> Result<()> { + pub fn run( + &mut self, + stream: &mut S, + ) -> Result<()> { self.send_id(stream)?; self.read_id(stream)?; @@ -73,7 +77,11 @@ impl Connection { std::thread::sleep(std::time::Duration::from_millis(1)); // TODO: REMOVE: debugging let response = match self.recv(&mut reader) { Ok(packet) => self.process_packet(packet)?, - Err(ConnectionError::Io(ref io_err)) if io_err.kind() == io::ErrorKind::WouldBlock => None, + Err(ConnectionError::Io(ref io_err)) + if io_err.kind() == io::ErrorKind::WouldBlock => + { + None + } Err(err) => return Err(err), }; // let response = self.process_packet(packet)?; @@ -91,7 +99,11 @@ impl Connection { // TODO: Consider pushing to `tx_queue`? for (_, channel) in self.channels.iter_mut() { let mut buf = String::with_capacity(1024); - if channel.read_pty_master(unsafe { buf.as_mut_vec() }).unwrap_or(0) != 0 { + if channel + .read_pty_master(unsafe { buf.as_mut_vec() }) + .unwrap_or(0) + != 0 + { let mut packet = Packet::new(MessageType::ChannelData); packet.write_uint32(channel.id())?; packet.write_string(&buf)?; @@ -105,7 +117,8 @@ impl Connection { packets.push(packet) } if channel.read_stderr(&mut buf).unwrap_or(0) != 0 { - let mut packet = Packet::new(MessageType::ChannelExtendedData); + let mut packet = + Packet::new(MessageType::ChannelExtendedData); packet.write_uint32(channel.id())?; packet.write_uint32(1)?; // Data Type Code for stderr packet.write_string(&buf)?; @@ -123,7 +136,8 @@ impl Connection { let packet = if let Some((ref mut c2s, _)) = self.encryption { let mut decryptor = Decryptor::new(&mut **c2s, &mut stream); Packet::read_from(&mut decryptor) - } else { + } + else { Packet::read_from(&mut stream) }?; @@ -147,8 +161,11 @@ impl Connection { Ok(packet) } - fn send(&mut self, mut stream: &mut dyn Write, packet: Packet) - -> io::Result<()> { + fn send( + &mut self, + mut stream: &mut dyn Write, + packet: Packet, + ) -> io::Result<()> { debug!("Sending packet {}: {:?}", self.seq.1, packet); let packet = packet.into_raw()?; @@ -202,7 +219,8 @@ impl Connection { info!("Peer identifies as {:?}", id); self.hash_data.client_id = Some(id.to_owned()); Ok(()) - } else { + } + else { Err(io::Error::new(io::ErrorKind::InvalidData, "invalid id")) } } @@ -212,17 +230,12 @@ impl Connection { let kex = self.key_exchange.take().ok_or(KeyGeneration)?; - let key = kex.hash( - &[ - kex.shared_secret().ok_or(KeyGeneration)?, - kex.exchange_hash().ok_or(KeyGeneration)?, - id, - self.session_id - .as_ref() - .ok_or(KeyGeneration)? - .as_slice(), - ], - ); + let key = kex.hash(&[ + kex.shared_secret().ok_or(KeyGeneration)?, + kex.exchange_hash().ok_or(KeyGeneration)?, + id, + self.session_id.as_ref().ok_or(KeyGeneration)?.as_slice(), + ]); self.key_exchange = Some(kex); @@ -256,11 +269,10 @@ impl Connection { let mac_c2s = self.generate_key(b"E", 256)?; let mac_s2c = self.generate_key(b"F", 256)?; - self.encryption = - Some(( - Box::new(AesCtr::new(enc_c2s.as_slice(), iv_c2s.as_slice())), - Box::new(AesCtr::new(enc_s2c.as_slice(), iv_s2c.as_slice())), - )); + self.encryption = Some(( + Box::new(AesCtr::new(enc_c2s.as_slice(), iv_c2s.as_slice())), + Box::new(AesCtr::new(enc_s2c.as_slice(), iv_s2c.as_slice())), + )); self.mac = Some(( Box::new(Hmac::new(mac_c2s.as_slice())), @@ -295,7 +307,8 @@ impl Connection { assert!(!(reader.read_bool()?)); let pass = reader.read_utf8()?; pass == "hunter2" - } else { + } + else { false }; @@ -303,7 +316,8 @@ impl Connection { if success { Ok(Some(Packet::new(MessageType::UserAuthSuccess))) - } else { + } + else { let mut res = Packet::new(MessageType::UserAuthFailure); res.write_string("password")?; res.write_bool(false)?; @@ -321,7 +335,8 @@ impl Connection { let id = if let Some((id, chan)) = self.channels.iter().next_back() { id + 1 - } else { + } + else { 0 }; @@ -357,17 +372,20 @@ impl Connection { })), "shell" => Some(ChannelRequest::Shell), "env" => Some(ChannelRequest::Env( - String::from_utf8(reader.read_string()?).unwrap(), // TODO: error handling + String::from_utf8(reader.read_string()?).unwrap(), /* TODO: error handling */ + String::from_utf8(reader.read_string()?).unwrap(), + )), + "exec" => Some(ChannelRequest::Exec( String::from_utf8(reader.read_string()?).unwrap(), )), - "exec" => Some(ChannelRequest::Exec(String::from_utf8(reader.read_string()?).unwrap())), _ => None, }; if let Some(request) = request { let channel = self.channels.get_mut(&channel_id).unwrap(); channel.handle_request(request); - } else { + } + else { warn!("Unkown channel request {}", name); } @@ -375,7 +393,8 @@ impl Connection { let mut res = Packet::new(MessageType::ChannelSuccess); res.write_uint32(0)?; Ok(Some(res)) - } else { + } + else { Ok(None) } } diff --git a/src/encryption/aes_ctr_new.rs b/src/encryption/aes_ctr_new.rs index c4efeb6..1d03df4 100644 --- a/src/encryption/aes_ctr_new.rs +++ b/src/encryption/aes_ctr_new.rs @@ -11,9 +11,11 @@ pub struct AesCtr { impl AesCtr { pub fn new(key: &[u8], iv: &[u8]) -> Self { - let key: [u8; 32] = key.try_into().expect("slice with incorrect length"); + let key: [u8; 32] = + key.try_into().expect("slice with incorrect length"); let key = GenericArray::from_slice(&key); - let iv: [u8; 16] = iv[..16].try_into().expect("slice with incorrect length"); + let iv: [u8; 16] = + iv[..16].try_into().expect("slice with incorrect length"); let iv = GenericArray::from_slice(&iv); let cipher = ThisCipher::new(key, iv); Self { cipher } diff --git a/src/encryption/mod.rs b/src/encryption/mod.rs index b24a5f4..7f31b71 100644 --- a/src/encryption/mod.rs +++ b/src/encryption/mod.rs @@ -17,23 +17,20 @@ pub struct Decryptor<'a> { } impl<'a> Decryptor<'a> { - pub fn new(encryption: &'a mut dyn Encryption, stream: &'a mut dyn Read) - -> Decryptor<'a> { - Decryptor { - encryption, - stream, - } + pub fn new( + encryption: &'a mut dyn Encryption, + stream: &'a mut dyn Read, + ) -> Decryptor<'a> { + Decryptor { encryption, stream } } } -impl<'a> Read for Decryptor<'a> { +impl Read for Decryptor<'_> { fn read(&mut self, buf: &mut [u8]) -> io::Result { let mut tmp = vec![0; buf.len()]; let count = self.stream.read(tmp.as_mut_slice())?; - self.encryption.decrypt( - &tmp.as_slice()[0..count], - &mut buf[0..count], - ); + self.encryption + .decrypt(&tmp.as_slice()[0..count], &mut buf[0..count]); Ok(count) } } diff --git a/src/error.rs b/src/error.rs index a8025aa..cd6fa6e 100644 --- a/src/error.rs +++ b/src/error.rs @@ -16,15 +16,18 @@ pub enum ConnectionError { impl fmt::Display for ConnectionError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::ConnectionError::*; - write!(f, "connection error: {}", (match &self - { - Io(err) => format!("io error: {}", err), - Protocol => "protocol error".to_owned(), - Negotiation => "negotiation error".to_owned(), - KeyExchange => "key exchange error".to_owned(), - KeyGeneration => "key generation error".to_owned(), - Integrity => "integrity error".to_owned(), - })) + write!( + f, + "connection error: {}", + (match &self { + Io(err) => format!("io error: {}", err), + Protocol => "protocol error".to_owned(), + Negotiation => "negotiation error".to_owned(), + KeyExchange => "key exchange error".to_owned(), + KeyGeneration => "key generation error".to_owned(), + Integrity => "integrity error".to_owned(), + }) + ) } } diff --git a/src/key_exchange/curve25519.rs b/src/key_exchange/curve25519.rs index 8b0588d..3dfb591 100644 --- a/src/key_exchange/curve25519.rs +++ b/src/key_exchange/curve25519.rs @@ -50,14 +50,12 @@ impl KeyExchange for Curve25519 { } fn process(&mut self, conn: &mut Connection, packet: Packet) -> KexResult { - match packet.msg_type() - { + match packet.msg_type() { MessageType::KeyExchange(ECDH_KEX_INIT) => { let mut reader = packet.reader(); let client_public = reader.read_string().unwrap(); - let config = match &conn.conn_type - { + let config = match &conn.conn_type { ConnectionType::Server(config) => config.clone(), _ => return KexResult::Error, }; @@ -83,27 +81,38 @@ impl KeyExchange for Curve25519 { secret }; - // let server_public = crypto::curve25519::curve25519_base(&server_secret); + // let server_public = + // crypto::curve25519::curve25519_base(&server_secret); // let shared_secret = { // let mut buf = Vec::new(); // buf.write_mpint(BigInt::from_bytes_be( // Sign::Plus, - // &crypto::curve25519::curve25519(&server_secret, &client_public), - // )).ok(); + // &crypto::curve25519::curve25519(&server_secret, + // &client_public), )).ok(); // buf // }; // ------------------------------------- - let server_secret_scalar = Scalar::from_bytes_mod_order(server_secret); - let server_public = MontgomeryPoint::mul_base(&server_secret_scalar); + let server_secret_scalar = + Scalar::from_bytes_mod_order(server_secret); + let server_public = + MontgomeryPoint::mul_base(&server_secret_scalar); let shared_secret = { let mut buf = Vec::new(); - let client_public_array: [u8; 32] = client_public.clone().try_into().unwrap(); // TODO - let client_public_point = MontgomeryPoint(client_public_array); - let server_secret_scalar = Scalar::from_bytes_mod_order(server_secret); - let shared_secret_point = client_public_point * server_secret_scalar; - buf.write_mpint(BigInt::from_bytes_be(Sign::Plus, &shared_secret_point.to_bytes())).ok(); + let client_public_array: [u8; 32] = + client_public.clone().try_into().unwrap(); // TODO + let client_public_point = + MontgomeryPoint(client_public_array); + let server_secret_scalar = + Scalar::from_bytes_mod_order(server_secret); + let shared_secret_point = + client_public_point * server_secret_scalar; + buf.write_mpint(BigInt::from_bytes_be( + Sign::Plus, + &shared_secret_point.to_bytes(), + )) + .ok(); buf }; @@ -113,16 +122,15 @@ impl KeyExchange for Curve25519 { let mut buf = Vec::new(); let data = &conn.hash_data; - let items = - [ - data.client_id.as_ref().unwrap().as_bytes(), - data.server_id.as_ref().unwrap().as_bytes(), - data.client_kexinit.as_ref().unwrap().as_slice(), - data.server_kexinit.as_ref().unwrap().as_slice(), - public_key.as_slice(), - client_public.as_slice(), - &server_public.to_bytes(), - ]; + let items = [ + data.client_id.as_ref().unwrap().as_bytes(), + data.server_id.as_ref().unwrap().as_bytes(), + data.client_kexinit.as_ref().unwrap().as_slice(), + data.server_kexinit.as_ref().unwrap().as_slice(), + public_key.as_slice(), + client_public.as_slice(), + &server_public.to_bytes(), + ]; for item in items.iter() { buf.write_bytes(item).ok(); diff --git a/src/lib.rs b/src/lib.rs index d4882ea..0484040 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -9,15 +9,15 @@ extern crate log; #[cfg(not(target_os = "redox"))] extern crate libc; -mod error; mod algorithm; -mod packet; -mod message; -mod connection; -mod key_exchange; -mod encryption; -mod mac; mod channel; +mod connection; +mod encryption; +mod error; +mod key_exchange; +mod mac; +mod message; +mod packet; pub mod public_key; pub mod server; diff --git a/src/mac/mod.rs b/src/mac/mod.rs index f499f6f..2f503d2 100644 --- a/src/mac/mod.rs +++ b/src/mac/mod.rs @@ -1,4 +1,3 @@ - // mod hmac; mod hmac_new; diff --git a/src/message.rs b/src/message.rs index 246e7f6..ceb80ac 100644 --- a/src/message.rs +++ b/src/message.rs @@ -34,8 +34,7 @@ pub enum MessageType { impl From for MessageType { fn from(id: u8) -> Self { use self::MessageType::*; - match id - { + match id { 1 => Disconnect, 2 => Ignore, 3 => Unimplemented, @@ -72,8 +71,7 @@ impl From for MessageType { impl From for u8 { fn from(val: MessageType) -> Self { use self::MessageType::*; - match val - { + match val { Disconnect => 1, Ignore => 2, Unimplemented => 3, diff --git a/src/packet.rs b/src/packet.rs index b1aa6af..429037e 100644 --- a/src/packet.rs +++ b/src/packet.rs @@ -18,11 +18,11 @@ impl Packet { } pub fn msg_type(&self) -> MessageType { - match self - { + match self { Packet::Raw(data, _) => data[5], Packet::Payload(data) => data[0], - }.into() + } + .into() } pub fn read_from(stream: &mut R) -> Result { @@ -48,8 +48,7 @@ impl Packet { } pub fn write_to(&self, stream: &mut W) -> Result<()> { - match self - { + match self { Packet::Raw(data, _) => { stream.write_all(data)?; stream.flush() @@ -69,24 +68,21 @@ impl Packet { } pub fn payload(self) -> Vec { - match self - { + match self { Packet::Raw(data, payload_len) => data[5..payload_len + 5].to_vec(), Packet::Payload(payload) => payload, } } pub fn data(&self) -> &[u8] { - match self - { + match self { Packet::Raw(data, _) => data, Packet::Payload(payload) => payload, } } pub fn into_raw(self) -> Result { - match self - { + match self { Packet::Raw(_, _) => Ok(self), Packet::Payload(ref payload) => { let mut buf = Vec::with_capacity(payload.len()); @@ -97,8 +93,7 @@ impl Packet { } pub fn reader(&self) -> BufReader<&[u8]> { - match self - { + match self { &Packet::Raw(ref data, payload_len) => { BufReader::new(&data.as_slice()[6..payload_len + 5]) } @@ -109,8 +104,7 @@ impl Packet { } pub fn payload_len(&self) -> usize { - match self - { + match self { &Packet::Raw(_, payload_len) => payload_len, Packet::Payload(payload) => payload.len(), } @@ -134,8 +128,7 @@ impl Packet { impl Write for Packet { fn write(&mut self, buf: &[u8]) -> Result { - match *self - { + match *self { Packet::Payload(ref mut payload) => payload.write(buf), Packet::Raw(ref mut data, ref mut payload_len) => { let count = data.write(buf)?; @@ -186,12 +179,10 @@ pub trait ReadPacketExt: ReadBytesExt { fn read_enum_list(&mut self) -> Result> { let string = self.read_utf8()?; - Ok( - string - .split(",") - .filter_map(|l| T::from_str(l).ok()) - .collect(), - ) + Ok(string + .split(",") + .filter_map(|l| T::from_str(l).ok()) + .collect()) } fn read_name_list(&mut self) -> Result> { diff --git a/src/public_key/ed25519.rs b/src/public_key/ed25519.rs index e377db0..8b5f5ee 100644 --- a/src/public_key/ed25519.rs +++ b/src/public_key/ed25519.rs @@ -20,7 +20,7 @@ pub static ED25519: CryptoSystem = CryptoSystem { struct Ed25519KeyPair { // This should be 32 bytes as mandated for [ed25519](https://www.rfc-editor.org/rfc/rfc8032#section-5.1.5) private: Option, //[u8; 64]>, - public: VerifyingKey, // [u8; 32], + public: VerifyingKey, // [u8; 32], } impl Ed25519KeyPair { @@ -39,7 +39,10 @@ impl Ed25519KeyPair { use crate::packet::ReadPacketExt; if r.read_utf8()? != "ssh-ed25519" { - return Err(io::Error::new(InvalidData, "Not a ED25519 key (in custom format), invalid header")); + return Err(io::Error::new( + InvalidData, + "Not a ED25519 key (in custom format), invalid header", + )); } if r.read_uint32()? != 32 { @@ -74,8 +77,7 @@ impl Ed25519KeyPair { let mut public = [0u8; 32]; r.read_exact(&mut public)?; - let public = VerifyingKey::from_bytes(&public) - .unwrap(); // TODO + let public = VerifyingKey::from_bytes(&public).unwrap(); // TODO Ok(Box::new(Ed25519KeyPair { private: None, @@ -107,12 +109,17 @@ impl KeyPair for Ed25519KeyPair { let received_id = reader.read_string().unwrap_or_default(); if received_id == EXPECTED_ID { - if let Ok(sig) = reader.read_string() { // TODO: .read_string() { - let sig_array: &[u8; 64] = sig.as_slice().try_into().expect("slice with incorrect length"); // TODO + if let Ok(sig) = reader.read_string() { + // TODO: .read_string() { + let sig_array: &[u8; 64] = sig + .as_slice() + .try_into() + .expect("slice with incorrect length"); // TODO let sig = Signature::from_bytes(sig_array); // TODO let res = self.public.verify_strict(data, &sig); return Ok(res.is_ok()); - // return Ok(ed25519::verify(data, &self.public, sig.as_slice())); + // return Ok(ed25519::verify(data, &self.public, + // sig.as_slice())); } } Err(KeyPairIdValidationError { @@ -130,7 +137,8 @@ impl KeyPair for Ed25519KeyPair { result.write_string("ssh-ed25519")?; result.write_bytes(&sig.to_bytes())?; Ok(result) - } else { + } + else { Err(SigningError::NoPrivateKey) } } diff --git a/src/public_key/mod.rs b/src/public_key/mod.rs index d60eae1..496a8be 100644 --- a/src/public_key/mod.rs +++ b/src/public_key/mod.rs @@ -11,7 +11,11 @@ pub trait KeyPair: Sync + Send { fn has_private(&self) -> bool; - fn verify(&self, data: &[u8], signature: &[u8]) -> Result; + fn verify( + &self, + data: &[u8], + signature: &[u8], + ) -> Result; fn sign(&self, data: &[u8]) -> Result, SigningError>; fn write_public(&self, w: &mut dyn Write) -> io::Result<()>; diff --git a/src/server.rs b/src/server.rs index f46b362..ba8872e 100644 --- a/src/server.rs +++ b/src/server.rs @@ -18,7 +18,9 @@ pub struct Server { impl Server { pub fn with_config(config: ServerConfig) -> Server { - Server { config: Arc::new(config) } + Server { + config: Arc::new(config), + } } pub fn run(&self) -> io::Result<()> { diff --git a/src/sys/redox.rs b/src/sys/redox.rs index a4ad00c..631f2be 100644 --- a/src/sys/redox.rs +++ b/src/sys/redox.rs @@ -1,6 +1,6 @@ use std::io::Result; -use std::os::unix::io::RawFd; use std::os::fd::AsRawFd; +use std::os::unix::io::RawFd; use std::path::PathBuf; pub fn before_exec() -> Result<()> { @@ -8,7 +8,9 @@ pub fn before_exec() -> Result<()> { } pub fn fork() -> usize { - todo!("You must specify -f, the old forking for Redox doesn't work anyway."); + todo!( + "You must specify -f, the old forking for Redox doesn't work anyway." + ); // The following on't work anyway // but will panic due to missing implementation // extern crate syscall; @@ -20,8 +22,7 @@ pub fn set_winsize(fd: RawFd, row: u16, col: u16, xpixel: u16, ypixel: u16) {} pub fn getpty() -> (RawFd, PathBuf) { use libredox::{call, flag}; - let master = call::open("pty:", flag::O_RDWR | flag::O_CREAT, 777) - .unwrap(); + let master = call::open("pty:", flag::O_RDWR | flag::O_CREAT, 777).unwrap(); let mut buf: [u8; 4096] = [0; 4096]; diff --git a/tests/public_key.rs b/tests/public_key.rs index ea04638..fdd4008 100644 --- a/tests/public_key.rs +++ b/tests/public_key.rs @@ -1,5 +1,5 @@ -extern crate ssh; extern crate rand; +extern crate ssh; use std::io::Cursor;