diff --git a/smb-core/src/lib.rs b/smb-core/src/lib.rs index 9a2a732..d415362 100644 --- a/smb-core/src/lib.rs +++ b/smb-core/src/lib.rs @@ -100,7 +100,7 @@ impl SMBVecFromBytesCnt for Vec { remaining = &remaining[extra..]; let (r, val) = T::smb_from_bytes(remaining)?; pos += T::smb_byte_size(&val); - extra = if align > 0 && pos % align != 0 { + extra = if align > 0 && !pos.is_multiple_of(align) { align - (pos % align) } else { 0 @@ -125,7 +125,7 @@ impl SMBVecFromBytesLen for Vec { let (_, val) = T::smb_from_bytes(remaining)?; let size = T::smb_byte_size(&val); pos += size; - extra = if align > 0 && pos % align != 0 { + extra = if align > 0 && !pos.is_multiple_of(align) { align - (pos % align) } else { 0 diff --git a/smb-derive/src/attrs.rs b/smb-derive/src/attrs.rs index d5f4e4e..1e654ec 100644 --- a/smb-derive/src/attrs.rs +++ b/smb-derive/src/attrs.rs @@ -137,12 +137,11 @@ impl FromMeta for AttributeInfo { fn from_list(items: &[NestedMeta]) -> darling::Result { for item in items { if let NestedMeta::Meta(Meta::NameValue(meta)) = item { - if meta.path.is_ident("fixed") { - if let Expr::Lit(lit) = &meta.value { - if let Lit::Int(int) = &lit.lit { - return Ok(AttributeInfo::Fixed(int.base10_parse::()?)) - } - } + if meta.path.is_ident("fixed") + && let Expr::Lit(lit) = &meta.value + && let Lit::Int(int) = &lit.lit + { + return Ok(AttributeInfo::Fixed(int.base10_parse::()?)) } } else if let NestedMeta::Meta(Meta::List(list)) = item { if list.path.is_ident("inner") { @@ -388,7 +387,7 @@ impl Vector { let _name_str = name.to_string(); quote_spanned! { spanned.span() => #vec_count_or_len - if #align > 0 && current_pos % #align != 0 { + if #align > 0 && !current_pos.is_multiple_of(#align) { current_pos += #align - (current_pos % #align); } #offset @@ -423,7 +422,7 @@ impl Vector { quote_spanned! { spanned.span()=> #count_info let get_aligned_pos = |align: usize, current_pos: usize| { - if align > 0 && current_pos % align != 0 { + if align > 0 && !current_pos.is_multiple_of(align) { current_pos + (align - current_pos % align) } else { current_pos @@ -824,12 +823,12 @@ impl FromAttributes for Repr { if attr.path().is_ident("repr") { let nested = attr.parse_args_with(Punctuated::::parse_terminated)?; for meta in nested { - if let Meta::Path(p) = meta { - if let Some(ident) = p.get_ident() { - return Ok(Self { - ident: ident.clone() - }) - } + if let Meta::Path(p) = meta + && let Some(ident) = p.get_ident() + { + return Ok(Self { + ident: ident.clone() + }) } } } diff --git a/smb-derive/src/field.rs b/smb-derive/src/field.rs index fe533ef..60b43df 100644 --- a/smb-derive/src/field.rs +++ b/smb-derive/src/field.rs @@ -155,10 +155,10 @@ impl SMBField<'_, T> { pub(crate) fn get_smb_message_size(&self, size_tokens: TokenStream) -> TokenStream { let tmp = SMBFieldType::Skip(Skip::new(0, 0)); let (start_val, ty) = self.val_type.iter().fold((0, &tmp), |prev, val| { - if let SMBFieldType::Skip(skip) = val { - if skip.length + skip.start > prev.0 { - return (skip.length + skip.start, val); - } + if let SMBFieldType::Skip(skip) = val + && skip.length + skip.start > prev.0 + { + return (skip.length + skip.start, val); } if val.weight_of_enum() == 2 || val.find_start_val() > prev.0 { (val.find_start_val(), val) @@ -229,7 +229,7 @@ impl SMBField<'_, T> { impl<'a> SMBField<'a, Field> { pub(crate) fn from_iter>(fields: U) -> Result, SMBDeriveError> { fields.enumerate().map(|(idx, field)| { - let val_types = field.attrs.iter().map(|attr| get_field_types(field, &[attr.clone()])).collect::, SMBDeriveError>>()?; + let val_types = field.attrs.iter().map(|attr| get_field_types(field, std::slice::from_ref(attr))).collect::, SMBDeriveError>>()?; let name = if let Some(x) = &field.ident { x.clone() } else { @@ -368,5 +368,5 @@ impl FromAttributes for SMBFieldType { fn get_field_types(field: &Field, attrs: &[Attribute]) -> Result> { SMBFieldType::from_attributes(attrs) - .map_err(|_e| SMBDeriveError::TypeError(field.clone())) + .map_err(|_e| SMBDeriveError::TypeError(Box::new(field.clone()))) } \ No newline at end of file diff --git a/smb-derive/src/lib.rs b/smb-derive/src/lib.rs index 63a6555..526fe83 100644 --- a/smb-derive/src/lib.rs +++ b/smb-derive/src/lib.rs @@ -178,7 +178,7 @@ fn derive_impl_creator(input: DeriveInput, creator: impl CreatorFn) -> proc_macr let parent_attrs = parent_attrs(&input); - let parse_token = match &input.data { + match &input.data { Data::Struct(structure) => { let mapping = get_struct_field_mapping(&structure.fields, parent_attrs, vec![], None) .map(|r| vec![r]); @@ -209,9 +209,7 @@ fn derive_impl_creator(input: DeriveInput, creator: impl CreatorFn) -> proc_macr } }, _ => invalid_token - }; - - parse_token + } } @@ -220,7 +218,7 @@ fn derive_impl_creator(input: DeriveInput, creator: impl CreatorFn) -> proc_macr /// `DeriveInput` and returns them as a sorted list of [`SMBFieldType`]s. fn parent_attrs(input: &DeriveInput) -> Vec { input.attrs.iter().filter_map(|attr| { - SMBFieldType::from_attributes(&[attr.clone()]).ok() + SMBFieldType::from_attributes(std::slice::from_ref(attr)).ok() }).collect() } @@ -236,7 +234,7 @@ trait CreatorFn { /// Errors that can occur during derive-macro expansion. #[derive(Debug)] enum SMBDeriveError { - TypeError(T), + TypeError(Box), MissingField, InvalidType, } diff --git a/smb/src/lib.rs b/smb/src/lib.rs index 7f2aac7..ad019a8 100644 --- a/smb/src/lib.rs +++ b/smb/src/lib.rs @@ -1,5 +1,7 @@ // TODO: Remove once protocol implementation consumes all public types #![allow(dead_code)] +// TODO: Reduce generic params on SMBServer to eliminate need for this allow +#![allow(clippy::type_complexity)] //! # SMB Reader //! //! A Rust implementation of the **Server Message Block (SMB) Protocol Versions 2 and 3** diff --git a/smb/src/protocol/body/create/mod.rs b/smb/src/protocol/body/create/mod.rs index 5281546..6f8b8c8 100644 --- a/smb/src/protocol/body/create/mod.rs +++ b/smb/src/protocol/body/create/mod.rs @@ -112,7 +112,7 @@ impl SMBCreateRequest { // TODO make this the right error code return Err(SMBError::response_error(NTStatus::NotSupported)); } - Ok((&self.file_name(), self.disposition(), self.create_options.contains(SMBCreateOptions::DIRECTORY_FILE))) + Ok((self.file_name(), self.disposition(), self.create_options.contains(SMBCreateOptions::DIRECTORY_FILE))) } } diff --git a/smb/src/protocol/body/error/mod.rs b/smb/src/protocol/body/error/mod.rs index e1f0c4a..7e9a02b 100644 --- a/smb/src/protocol/body/error/mod.rs +++ b/smb/src/protocol/body/error/mod.rs @@ -34,6 +34,16 @@ pub struct SMBErrorResponse { error_data: PhantomData>, } +impl Default for SMBErrorResponse { + fn default() -> Self { + Self { + reserved: PhantomData, + byte_count: PhantomData, + error_data: PhantomData, + } + } +} + impl SMBErrorResponse { pub fn new() -> Self { Self { diff --git a/smb/src/protocol/body/filetime.rs b/smb/src/protocol/body/filetime.rs index 60d91c4..ac51b51 100644 --- a/smb/src/protocol/body/filetime.rs +++ b/smb/src/protocol/body/filetime.rs @@ -18,7 +18,7 @@ const TIME_SINCE_1601_AND_EPOCH: u64 = 11644473600000; impl FileTime { pub fn from_unix(unix_timestamp: u64) -> Self { - let filetype_normalized = unix_timestamp + TIME_SINCE_1601_AND_EPOCH as u64; + let filetype_normalized = unix_timestamp + TIME_SINCE_1601_AND_EPOCH; let bytes = u64_to_bytes(filetype_normalized); FileTime { low_date_time: bytes_to_u32(&bytes[0..4]), diff --git a/smb/src/protocol/body/ioctl/flags.rs b/smb/src/protocol/body/ioctl/flags.rs index c416547..26c0fcd 100644 --- a/smb/src/protocol/body/ioctl/flags.rs +++ b/smb/src/protocol/body/ioctl/flags.rs @@ -5,6 +5,7 @@ use smb_derive::{SMBByteSize, SMBFromBytes, SMBToBytes}; #[repr(u32)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TryFromPrimitive, SMBFromBytes, SMBByteSize, SMBToBytes)] +#[allow(clippy::upper_case_acronyms)] pub enum SMBIoCtlRequestFlags { IOCTL = 0x0, FSCTL = 0x1, diff --git a/smb/src/protocol/body/negotiate/mod.rs b/smb/src/protocol/body/negotiate/mod.rs index 22ffb2e..e0ad207 100644 --- a/smb/src/protocol/body/negotiate/mod.rs +++ b/smb/src/protocol/body/negotiate/mod.rs @@ -1,4 +1,3 @@ -use std::any::Any; use std::collections::HashSet; use std::marker::PhantomData; @@ -62,7 +61,7 @@ impl SMBNegotiateRequest { return Err(SMBError::response_error(NTStatus::InvalidParameter)); } let mut update = SMBConnectionUpdate::default(); - let mut received_ctxs = HashSet::new(); + let received_ctxs = HashSet::new(); // TODO: uncomment after signing is fixed + working // for context in self.negotiate_contexts.iter() { // let (change, actual) = context.validate_and_set_state(update, server)?; @@ -104,7 +103,7 @@ impl SMBNegotiateRequest { let dialect = SMBDialect::V2_1_0; let preauth_value = if dialect == SMBDialect::V3_1_1 { let mut sha = Sha512::default(); - sha.update(&self.smb_to_bytes()); + sha.update(self.smb_to_bytes()); sha.finalize().to_vec() } else { Vec::new() diff --git a/smb/src/protocol/body/session_setup/mod.rs b/smb/src/protocol/body/session_setup/mod.rs index 790a9af..253858b 100644 --- a/smb/src/protocol/body/session_setup/mod.rs +++ b/smb/src/protocol/body/session_setup/mod.rs @@ -20,7 +20,6 @@ use crate::server::preauth_session::SMBPreauthSession; use crate::server::Server; use crate::server::session::{Session, SessionState}; use crate::socket::message_stream::{SMBReadStream, SMBWriteStream}; -use crate::util::auth::AuthProvider; pub mod security_mode; pub mod flags; @@ -98,7 +97,7 @@ impl SMBSessionSetupRequest { if connection.dialect() == SMBDialect::V3_1_1 && !connection.preauth_sessions().contains_key(&session.id()) { let mut sha = Sha512::default(); sha.update(connection.preauth_integtiry_hash_value()); - sha.update(&self.smb_to_bytes()); + sha.update(self.smb_to_bytes()); let bytes = sha.finalize().to_vec(); let preauth_session = SMBPreauthSession::new(session.id(), bytes); update = update.preauth_session_table(HashMap::from([(session.id(), preauth_session)])); @@ -152,7 +151,7 @@ impl SMBSessionSetupResponse { } } - pub fn from_request(request: SMBSessionSetupRequest, token: Vec) -> Option { + pub fn from_request(_request: SMBSessionSetupRequest, token: Vec) -> Option { Some(Self { session_flags: SMBSessionFlags::empty(), buffer: token, diff --git a/smb/src/protocol/body/tree_connect/access_mask.rs b/smb/src/protocol/body/tree_connect/access_mask.rs index 131dd97..1c09d99 100644 --- a/smb/src/protocol/body/tree_connect/access_mask.rs +++ b/smb/src/protocol/body/tree_connect/access_mask.rs @@ -49,7 +49,7 @@ impl SMBAccessMask { } pub fn from_desired_access(desired: &SMBAccessMask) -> Self { - let mut mask = desired.clone(); + let mask = desired.clone(); if mask.includes_maximum_allowed() { match mask { SMBAccessMask::FilePipePrinter(mut x) => x |= SMBFilePipePrinterAccessMask::GENERIC_ALL, diff --git a/smb/src/protocol/body/tree_connect/context.rs b/smb/src/protocol/body/tree_connect/context.rs index 6ac76c0..e1f5881 100644 --- a/smb/src/protocol/body/tree_connect/context.rs +++ b/smb/src/protocol/body/tree_connect/context.rs @@ -22,7 +22,7 @@ impl SMBByteSize for SMBTreeConnectContext { impl SMBFromBytes for SMBTreeConnectContext { fn smb_from_bytes(input: &[u8]) -> SMBParseResult<&[u8], Self> where Self: Sized { - let (remaining, ctx_type) = u16::smb_from_bytes(input)?; + let (_remaining, ctx_type) = u16::smb_from_bytes(input)?; match ctx_type { 0x01 => { let (remaining, identity) = RemotedIdentity::smb_from_bytes(input)?; diff --git a/smb/src/protocol/body/tree_connect/mod.rs b/smb/src/protocol/body/tree_connect/mod.rs index 958192a..752b01d 100644 --- a/smb/src/protocol/body/tree_connect/mod.rs +++ b/smb/src/protocol/body/tree_connect/mod.rs @@ -82,7 +82,7 @@ impl Default for SMBTreeConnectResponse { } impl SMBTreeConnectResponse { - pub fn IPC() -> Self { + pub fn ipc() -> Self { Self { maximal_access: SMBAccessMask::FilePipePrinter(SMBFilePipePrinterAccessMask::from_bits_truncate(2032127)), share_type: SMBShareType::Pipe, @@ -113,19 +113,14 @@ impl SMBTreeConnectResponse { } #[repr(u8)] -#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Copy, Clone, SMBByteSize, SMBFromBytes, SMBToBytes, TryFromPrimitive)] +#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Copy, Clone, SMBByteSize, SMBFromBytes, SMBToBytes, TryFromPrimitive, Default)] pub enum SMBShareType { + #[default] Disk = 0x01, Pipe, Print, } -impl Default for SMBShareType { - fn default() -> Self { - Self::Disk - } -} - impl_smb_byte_size_for_bitflag! { SMBTreeConnectFlags SMBShareFlags diff --git a/smb/src/protocol/header/command_code.rs b/smb/src/protocol/header/command_code.rs index a5f337e..8eb68e8 100644 --- a/smb/src/protocol/header/command_code.rs +++ b/smb/src/protocol/header/command_code.rs @@ -28,9 +28,9 @@ pub enum SMBCommandCode { LegacyNegotiate } -impl Into for SMBCommandCode { - fn into(self) -> u64 { - self as u16 as u64 +impl From for u64 { + fn from(val: SMBCommandCode) -> Self { + val as u16 as u64 } } @@ -110,9 +110,9 @@ pub enum LegacySMBCommandCode { WriteBulkData } -impl Into for LegacySMBCommandCode { - fn into(self) -> u64 { - self as u8 as u64 +impl From for u64 { + fn from(val: LegacySMBCommandCode) -> Self { + val as u8 as u64 } } diff --git a/smb/src/protocol/header/mod.rs b/smb/src/protocol/header/mod.rs index fb190a8..eab268e 100644 --- a/smb/src/protocol/header/mod.rs +++ b/smb/src/protocol/header/mod.rs @@ -103,6 +103,7 @@ pub trait Header: SMBFromBytes + SMBToBytes { SMBByteSize, Clone )] +#[allow(clippy::duplicated_attributes)] #[smb_byte_tag(value = 0xFE, order = 0)] #[smb_string_tag(value = "SMB", order = 1)] #[smb_byte_tag(value = 64, order = 2)] diff --git a/smb/src/server/connection.rs b/smb/src/server/connection.rs index faef8c9..6d7616c 100644 --- a/smb/src/server/connection.rs +++ b/smb/src/server/connection.rs @@ -436,6 +436,7 @@ impl> SMBConnect } type LockedSMBConnection = Arc>>; +pub type WeakLockedSMBConnection = Weak>>; impl> InnerGetter for SMBConnection { type Upper = S; diff --git a/smb/src/server/lease.rs b/smb/src/server/lease.rs index ec59052..c06538d 100644 --- a/smb/src/server/lease.rs +++ b/smb/src/server/lease.rs @@ -9,6 +9,7 @@ use crate::server::Server; pub trait Lease: Send + Sync {} + #[derive(Debug)] pub struct SMBLeaseTable { client_guid: Uuid, diff --git a/smb/src/server/message_handler.rs b/smb/src/server/message_handler.rs index 92ffb97..50f0a2b 100644 --- a/smb/src/server/message_handler.rs +++ b/smb/src/server/message_handler.rs @@ -1,7 +1,7 @@ use std::future::Future; use smb_core::error::SMBError; -use smb_core::logging::{trace, debug, warn}; +use smb_core::logging::{trace, debug}; use smb_core::nt_status::NTStatus; use smb_core::SMBResult; @@ -75,87 +75,87 @@ pub trait SMBLockedMessageHandlerBase { SMBBody::ErrorResponse(_) => { let status = NTStatus::try_from(message.header.channel_sequence) .unwrap_or(NTStatus::NotSupported); - return Err(SMBError::response_error(status)); + Err(SMBError::response_error(status)) }, _ => Err(SMBError::server_error("Command not implemented")), } } } - fn handle_negotiate(&mut self, header: &SMBSyncHeader, message: &SMBNegotiateRequest) -> impl Future>> { + fn handle_negotiate(&mut self, _header: &SMBSyncHeader, _message: &SMBNegotiateRequest) -> impl Future>> { async { Ok(SMBHandlerState::Next(None)) } } - fn handle_session_setup(&mut self, header: &SMBSyncHeader, message: &SMBSessionSetupRequest) -> impl Future>> { + fn handle_session_setup(&mut self, _header: &SMBSyncHeader, _message: &SMBSessionSetupRequest) -> impl Future>> { async { Ok(SMBHandlerState::Next(None)) } } - fn handle_logoff(&mut self, header: &SMBSyncHeader, message: &SMBLogoffRequest) -> impl Future>> { + fn handle_logoff(&mut self, _header: &SMBSyncHeader, _message: &SMBLogoffRequest) -> impl Future>> { async { Ok(SMBHandlerState::Next(None)) } } - fn handle_tree_connect(&mut self, header: &SMBSyncHeader, message: &SMBTreeConnectRequest) -> impl Future>> { + fn handle_tree_connect(&mut self, _header: &SMBSyncHeader, _message: &SMBTreeConnectRequest) -> impl Future>> { async { Ok(SMBHandlerState::Next(None)) } } - fn handle_tree_disconnect(&mut self, header: &SMBSyncHeader, message: &SMBTreeDisconnectRequest) -> impl Future>> { + fn handle_tree_disconnect(&mut self, _header: &SMBSyncHeader, _message: &SMBTreeDisconnectRequest) -> impl Future>> { async { Ok(SMBHandlerState::Next(None)) } } - fn handle_create(&mut self, header: &SMBSyncHeader, message: &SMBCreateRequest) -> impl Future>> { + fn handle_create(&mut self, _header: &SMBSyncHeader, _message: &SMBCreateRequest) -> impl Future>> { debug!("create request, passing to next handler"); async { Ok(SMBHandlerState::Next(None)) } } - fn handle_close(&mut self, header: &SMBSyncHeader, message: &SMBCloseRequest) -> impl Future>> { + fn handle_close(&mut self, _header: &SMBSyncHeader, _message: &SMBCloseRequest) -> impl Future>> { async { Ok(SMBHandlerState::Next(None)) } } - fn handle_flush(&mut self, header: &SMBSyncHeader, message: &SMBFlushRequest) -> impl Future>> { + fn handle_flush(&mut self, _header: &SMBSyncHeader, _message: &SMBFlushRequest) -> impl Future>> { async { Ok(SMBHandlerState::Next(None)) } } - fn handle_read(&mut self, header: &SMBSyncHeader, message: &SMBReadRequest) -> impl Future>> { + fn handle_read(&mut self, _header: &SMBSyncHeader, _message: &SMBReadRequest) -> impl Future>> { async { Ok(SMBHandlerState::Next(None)) } } - fn handle_write(&mut self, header: &SMBSyncHeader, message: &SMBWriteRequest) -> impl Future>> { + fn handle_write(&mut self, _header: &SMBSyncHeader, _message: &SMBWriteRequest) -> impl Future>> { async { Ok(SMBHandlerState::Next(None)) } } - fn handle_lock(&mut self, header: &SMBSyncHeader, message: &SMBLockRequest) -> impl Future>> { + fn handle_lock(&mut self, _header: &SMBSyncHeader, _message: &SMBLockRequest) -> impl Future>> { async { Ok(SMBHandlerState::Next(None)) } } - fn handle_ioctl(&mut self, header: &SMBSyncHeader, message: &SMBIoCtlRequest) -> impl Future>> { + fn handle_ioctl(&mut self, _header: &SMBSyncHeader, _message: &SMBIoCtlRequest) -> impl Future>> { async { Ok(SMBHandlerState::Next(None)) } } - fn handle_cancel(&mut self, header: &SMBSyncHeader, message: &SMBCancelRequest) -> impl Future>> { + fn handle_cancel(&mut self, _header: &SMBSyncHeader, _message: &SMBCancelRequest) -> impl Future>> { async { Ok(SMBHandlerState::Next(None)) } } - fn handle_echo(&mut self, header: &SMBSyncHeader, message: &SMBEchoRequest) -> impl Future>> { + fn handle_echo(&mut self, _header: &SMBSyncHeader, _message: &SMBEchoRequest) -> impl Future>> { async { Ok(SMBHandlerState::Next(None)) } } - fn handle_query_directory(&mut self, header: &SMBSyncHeader, message: &SMBQueryDirectoryRequest) -> impl Future>> { + fn handle_query_directory(&mut self, _header: &SMBSyncHeader, _message: &SMBQueryDirectoryRequest) -> impl Future>> { async { Ok(SMBHandlerState::Next(None)) } } - fn handle_change_notify(&mut self, header: &SMBSyncHeader, message: &SMBChangeNotifyRequest) -> impl Future>> { + fn handle_change_notify(&mut self, _header: &SMBSyncHeader, _message: &SMBChangeNotifyRequest) -> impl Future>> { async { Ok(SMBHandlerState::Next(None)) } } - fn handle_query_info(&mut self, header: &SMBSyncHeader, message: &SMBQueryInfoRequest) -> impl Future>> { + fn handle_query_info(&mut self, _header: &SMBSyncHeader, _message: &SMBQueryInfoRequest) -> impl Future>> { async { Ok(SMBHandlerState::Next(None)) } } - fn handle_set_info(&mut self, header: &SMBSyncHeader, message: &SMBSetInfoRequest) -> impl Future>> { + fn handle_set_info(&mut self, _header: &SMBSyncHeader, _message: &SMBSetInfoRequest) -> impl Future>> { async { Ok(SMBHandlerState::Next(None)) } } - fn handle_oplock_break(&mut self, header: &SMBSyncHeader, message: &SMBOplockBreakAcknowledgement) -> impl Future>> { + fn handle_oplock_break(&mut self, _header: &SMBSyncHeader, _message: &SMBOplockBreakAcknowledgement) -> impl Future>> { async { Ok(SMBHandlerState::Next(None)) } } } diff --git a/smb/src/server/mod.rs b/smb/src/server/mod.rs index a76e1a8..0dd240a 100644 --- a/smb/src/server/mod.rs +++ b/smb/src/server/mod.rs @@ -1,7 +1,8 @@ +use std::collections::hash_map::Entry; use std::collections::HashMap; use std::fmt::Debug; use std::future::Future; -use std::sync::{Arc, Weak}; +use std::sync::Arc; use derive_builder::Builder; use tokio::net::TcpListener; @@ -16,11 +17,11 @@ use smb_core::SMBResult; use crate::protocol::body::dialect::SMBDialect; use crate::protocol::body::filetime::FileTime; use crate::server::client::SMBClient; -use crate::server::connection::{Connection, SMBConnection}; +use crate::server::connection::{Connection, SMBConnection, WeakLockedSMBConnection}; use crate::server::lease::{Lease, SMBLease, SMBLeaseTable}; -use crate::server::open::{Open, SMBOpen}; +use crate::server::open::{LockedSMBOpen, Open, SMBOpen}; use crate::server::safe_locked_getter::InnerGetter; -use crate::server::session::{Session, SMBSession}; +use crate::server::session::{LockedSMBSession, Session, SMBSession}; use crate::server::share::{ConnectAllowed, FilePerms, ResourceHandle, SharedResource}; use crate::server::share::file_system::{SMBFileSystemHandle, SMBFileSystemShare}; use crate::server::share::ipc::{SMBIPCHandle, SMBIPCShare}; @@ -81,11 +82,6 @@ pub trait StartSMBServer { } type SMBConnectionType = SMBConnection<>::ReadStream, >::WriteStream, SMBServer>; - -type LockedWeakSMBConnection = Weak>>; -type SMBSessionType = SMBSession>; -type SMBOpenType = SMBOpen>; -type SMBLeaseType = SMBLease>; type UserName = <::Context as AuthContext>::UserName; pub type DefaultShare = Box::Context as AuthContext>::UserName, Handle=DefaultHandle>>; type DefaultHandle = Box; @@ -100,17 +96,17 @@ pub struct SMBServer = TcpListene #[builder(field(type = "HashMap>"))] share_list: HashMap>, #[builder(field( - type = "HashMap>>>" + type = "HashMap>>" ))] - open_table: HashMap>>>, + open_table: HashMap>>, #[builder(field( - type = "HashMap>>>" + type = "HashMap>>" ))] - session_table: HashMap>>>, + session_table: HashMap>>, #[builder(field( - type = "HashMap>" + type = "HashMap>::ReadStream, >::WriteStream, SMBServer>>" ))] - connection_list: HashMap>, + connection_list: HashMap>::ReadStream, >::WriteStream, SMBServer>>, #[builder(default = "Uuid::new_v4()")] guid: Uuid, #[builder(default = "FileTime::default()")] @@ -126,9 +122,9 @@ pub struct SMBServer = TcpListene #[builder(default = "HashLevel::EnableAll")] hash_level: HashLevel, #[builder(field( - type = "HashMap>>" + type = "HashMap>>>" ))] - lease_table_list: HashMap>>, + lease_table_list: HashMap>>>, #[builder(default = "5000")] max_resiliency_timeout: u64, #[builder(default = "5000")] @@ -170,10 +166,10 @@ pub struct SMBServer = TcpListene impl, Auth: AuthProvider, Share: SharedResource, Handle=Handle>, Handle: ResourceHandle> Server for SMBServer { type Connection = SMBConnectionType; - type Session = SMBSessionType; + type Session = SMBSession; type Share = Share; - type Open = SMBOpenType; - type Lease = SMBLeaseType; + type Open = SMBOpen; + type Lease = SMBLease; type AuthProvider = Auth; type Handle = Handle; @@ -187,11 +183,11 @@ impl, Auth: AuthProvider, Share: async fn add_open(&mut self, open: Arc>) -> u32 { for i in 0..u32::MAX { - if self.open_table.get(&i).is_none() { + if let Entry::Vacant(e) = self.open_table.entry(i) { let mut open_wr = open.write().await; open_wr.set_global_id(i); drop(open_wr); - self.open_table.insert(i, open); + e.insert(open); return i; } } @@ -345,7 +341,7 @@ impl< Share: SharedResource, Handle=Handle> + From, Handle>>, Handle: ResourceHandle + 'static + From + TryInto > SMBServerBuilder { - pub fn add_fs_share(mut self, name: String, path: String, connect_allowed: ConnectAllowed>, file_perms: FilePerms>) -> Self { + pub fn add_fs_share(self, name: String, path: String, connect_allowed: ConnectAllowed>, file_perms: FilePerms>) -> Self { let share = SMBFileSystemShare::path(name.clone(), path, connect_allowed, file_perms); self.add_share(name, share.into()) } @@ -394,7 +390,7 @@ impl + 'static, Auth: A let mut stream = socket.lock().await; match SMBConnection::start_message_handler::(&mut stream, wrapped_connection, update_channel).await { Ok(()) => debug!("message handler completed"), - Err(ref e) => warn!(?e, "message handler exited with error"), + Err(_e) => warn!(?e, "message handler exited with error"), } }); } diff --git a/smb/src/server/open.rs b/smb/src/server/open.rs index a3df216..c75e766 100644 --- a/smb/src/server/open.rs +++ b/smb/src/server/open.rs @@ -1,6 +1,7 @@ use std::fmt::{Debug, Formatter}; use std::sync::Arc; +use tokio::sync::RwLock; use uuid::Uuid; use smb_core::SMBResult; @@ -17,6 +18,8 @@ use crate::server::Server; use crate::server::share::{ResourceHandle, SMBFileMetadata}; use crate::server::tree_connect::SMBTreeConnect; +pub type LockedSMBOpen = Arc>>; + pub trait Open: Send + Sync { type Server: Server; fn file_name(&self) -> &str; @@ -145,6 +148,11 @@ impl Open for SMBOpen { self.underlying.metadata() } } + +// TODO: From MS-FSCC section 2.6 +#[derive(Debug)] +struct FileAttributes; + #[derive(Debug)] pub enum SMBOplockState { Held, diff --git a/smb/src/server/session.rs b/smb/src/server/session.rs index 7e2cf87..719d90c 100644 --- a/smb/src/server/session.rs +++ b/smb/src/server/session.rs @@ -36,6 +36,7 @@ use crate::util::auth::spnego::{SPNEGOToken, SPNEGOTokenResponseBody}; use crate::util::crypto::sp800_108::derive_key; use crate::util::num_limits::{MaxVal, MinVal, One, Zero}; +pub type LockedSMBSession = Arc>>; type SMBMessageType = SMBMessage; const _OUTPUT_SIZE_128: usize = 128; diff --git a/smb/src/server/share/file_system.rs b/smb/src/server/share/file_system.rs index 25d4417..9441b49 100644 --- a/smb/src/server/share/file_system.rs +++ b/smb/src/server/share/file_system.rs @@ -70,7 +70,7 @@ impl ResourceHandle for SMBFileSystemHandle { } fn metadata(&self) -> SMBResult { - let metadata = fs::metadata(&self.path()) + let metadata = fs::metadata(self.path()) .map_err(|err| SMBError::server_error(format!("Failed to get metadata for path: {}, error: {}", self.path(), err)))?; let time_transform = |time: SystemTime| { time.duration_since(UNIX_EPOCH) @@ -173,7 +173,7 @@ impl + ResourceHandle + }?; let handle = SMBFileSystemHandle { resource, - path: path.into(), + path, }; debug!(?handle, "created filesystem handle"); Ok(handle.into()) diff --git a/smb/src/server/share/ipc.rs b/smb/src/server/share/ipc.rs index b7ef3cc..04e6152 100644 --- a/smb/src/server/share/ipc.rs +++ b/smb/src/server/share/ipc.rs @@ -2,7 +2,6 @@ use std::any::Any; use std::fmt::{Debug, Formatter}; use std::marker::PhantomData; -use smb_core::error::SMBError; use smb_core::SMBResult; use crate::protocol::body::create::disposition::SMBCreateDisposition; @@ -58,8 +57,8 @@ pub struct SMBIPCShare + Resou _handle: PhantomData, } -impl + ResourceHandle> SMBIPCShare { - pub fn new() -> Self { +impl + ResourceHandle> Default for SMBIPCShare { + fn default() -> Self { Self { _user_name: PhantomData, _handle: PhantomData, @@ -67,6 +66,12 @@ impl + ResourceHandle> SMBIPCS } } +impl + ResourceHandle> SMBIPCShare { + pub fn new() -> Self { + Self::default() + } +} + impl + ResourceHandle> Debug for SMBIPCShare { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.debug_struct("SMBIPCShare").finish() diff --git a/smb/src/socket/listener/mod.rs b/smb/src/socket/listener/mod.rs index f71a45f..ce1512b 100644 --- a/smb/src/socket/listener/mod.rs +++ b/smb/src/socket/listener/mod.rs @@ -1,7 +1,7 @@ use std::fmt::Debug; use std::future::Future; use std::marker::PhantomData; -use std::ops::{Add, Deref, DerefMut}; +use std::ops::{Deref, DerefMut}; use smb_core::error::SMBError; use smb_core::SMBResult; @@ -27,7 +27,7 @@ pub trait SMBSocket: Send + Sync { } #[cfg(feature = "async")] - fn new_socket(addr: T) -> impl Future> + Send where Self: Sized { + fn new_socket(_addr: T) -> impl Future> + Send where Self: Sized { async { Err(SMBError::precondition_failed("Invalid socket address type")) } diff --git a/smb/src/socket/message_stream/mod.rs b/smb/src/socket/message_stream/mod.rs index 2a257b9..da4149d 100644 --- a/smb/src/socket/message_stream/mod.rs +++ b/smb/src/socket/message_stream/mod.rs @@ -92,9 +92,11 @@ impl<'a, R: SMBReadStream> SMBMessageIterator<'a, R> { } #[cfg(feature = "async")] -#[allow(clippy::type_complexity)] +type SMBMessageStreamResult<'a, T> = (SMBResult>, SMBMessageIterator<'a, T>); + +#[cfg(feature = "async")] pub struct SMBMessageStream<'a, T: SMBReadStream> { - pub(crate) inner: ReusableBoxFuture<'a, (SMBResult>, SMBMessageIterator<'a, T>)>, + pub(crate) inner: ReusableBoxFuture<'a, SMBMessageStreamResult<'a, T>>, } #[derive(Debug)] diff --git a/smb/src/util/crypto/des.rs b/smb/src/util/crypto/des.rs index c45d4d6..005f2f8 100644 --- a/smb/src/util/crypto/des.rs +++ b/smb/src/util/crypto/des.rs @@ -32,8 +32,8 @@ fn extend_des_key(key: &[u8]) -> Vec { result[6] = ((key[5] & 0x3F) << 1) | (key[6] >> 7); result[7] = key[6] & 0x7F; - for i in 0..result.len() { - result[i] <<= 1; + for item in &mut result { + *item <<= 1; } result diff --git a/smb/src/util/crypto/ntlm_v2.rs b/smb/src/util/crypto/ntlm_v2.rs index 7ee1702..2ba3e7a 100644 --- a/smb/src/util/crypto/ntlm_v2.rs +++ b/smb/src/util/crypto/ntlm_v2.rs @@ -11,7 +11,7 @@ use crate::byte_helper::u16_to_bytes; pub fn authenticate_v2(domain: &str, account: &str, password: &str, server_challenge: &[u8], lm_response: &[u8], nt_response: &[u8]) -> SMBResult<(bool, Vec)> { // AV-pairs structure let server_name = &nt_response[44..(nt_response.len() - 4)]; - let (nt_exp, lm_exp, nt_proof) = compute_ntlm_v2_response(server_challenge, &nt_response[16..], server_name, password, account, domain)?; + let (nt_exp, lm_exp, _nt_proof) = compute_ntlm_v2_response(server_challenge, &nt_response[16..], server_name, password, account, domain)?; let resp = nt_exp == nt_response || lm_exp == lm_response; @@ -48,7 +48,7 @@ fn compute_ntlm_v2_response(server_challenge: &[u8], client_challenge: &[u8], se &[client_challenge[0]][0..], &[client_challenge[1]], &[0; 6], - &time, + time, // &[0; 8], client_challenge, &[0; 4],