Crate smb

Crate smb 

Source
Expand description

§SMB

the smb crate is a pure rust SMB client, supports the SMB2 protocol (including SMB3).

§Basic usage

The most basic functionality that an SMB client should provide is the ability to connect to an SMB server, authenticate, and perform simple file operations.

The Client struct provides a simple interface for interacting with an SMB server. Let’s see how we use it.

use smb::{Client, ClientConfig, UncPath, FileCreateArgs, FileAccessMask};
use std::str::FromStr;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // instantiate the client
    let client = Client::new(ClientConfig::default());

    // Connect to a share
    let target_path = UncPath::from_str(r"\\server\share").unwrap();
    client.share_connect(&target_path, "username", "password".to_string()).await?;

    // And open a file on the server
    let file_to_open = target_path.with_path("file.txt");
    let file_open_args = FileCreateArgs::make_open_existing(FileAccessMask::new().with_generic_read(true));
    let file = client.create_file(&file_to_open, &file_open_args).await?;
    // now, you can do a bunch of operations against `file`, and close it at the end.
    Ok(())
}

Cool! we got ourselves a live connection to an SMB server, and we also got a file open.

But wait… How do we know it’s actually a file? Well, we don’t. The Client::create_file method returns the Resource struct, which is a union to a file, directory, or a pipe - the supported SMB resources in this crate (printers are currently not implemented specifically). What we need to do next, is to find out what type of resource we’ve got:

match &file {
    Resource::File(file) => {
        // We have a file
    }
    Resource::Directory(dir) => {
        // We have a directory
    }
    Resource::Pipe(pipe) => {
        // We have a pipe
    }
}
// Note: we could also use `.unwrap_file()` here,
// or similar method provided by Resource to find out what kind of resource this is!

Cool! Let’s assume we got ourselves a file. Then, we can do the obvious operation of reading or writing a block of data from or to the file:

let file: File = file.unwrap_file();

let mut data: [u8; 1024] = [0; 1024];
file.read_at(&mut data, 0).await?;
file.write_at(&data, 0).await?;

At the end, close the file.

file.close().await?;

§Feature flags

TypeAlgorithmAsyncMulti-threadedSingle-threadedFeature Name
AuthenticationKerberoskerberos
TransportQUICquic
Signing*sign
SigningHMAC_SHA256sign_hmac
SigningAES-128-GCMsign_gmac
SigningAES-128-CCMsign_cmac
Encryption*encrypt
EncryptionAES-128-CCMencrypt_aes128ccm
EncryptionAES-128-GCMencrypt_aes128gcm
EncryptionAES-256-CCMencrypt_aes256ccm
EncryptionAES-256-GCMencrypt_aes256gcm
Compression*compress
CompressionLZ4compress_lz4
CompressionPattern_V1🟡🟡🟡compress_pattern_v1*
CompressionLZNT1/LZ77/+Huffman-
  • The Pattern_V1 compression algorithm currently supports in-bound decompression only.

§Advanced documentation

Re-exports§

pub use client::Client;
pub use client::ClientConfig;
pub use client::UncPath;
pub use connection::Connection;
pub use connection::ConnectionConfig;
pub use error::Error;
pub use resource::Directory;
pub use resource::File;
pub use resource::FileCreateArgs;
pub use resource::GetLen;
pub use resource::Pipe;
pub use resource::PipeRpcConnection;
pub use resource::ReadAt;
pub use resource::ReadAtChannel;
pub use resource::Resource;
pub use resource::ResourceHandle;
pub use resource::WriteAt;
pub use resource::WriteAtChannel;
pub use session::Session;
pub use tree::DfsRootTreeRef;
pub use tree::Tree;
pub use smb_transport as transport;

Modules§

binrw_util
This module contains utility types for the binrw crate.
cancel
Cancel Request
client
High-level SMB client interface.
compressed
Compressed messages
compression
Implements (de)compression logic.
connection
create
Create & Close (files) requests and responses.
crypto
dfsc
dialects
Implements SMB-dialect-specific types and functions.
docs
Additional crate docs are submodules.
echo
Echo request and response messages
encrypted
Encrypted messages
error
file
File-related messages: Flush, Read, Write.
guid
header
info
SMB2 Query and Set Info messages.
ioctl
SMB2 IOCTL packet implementation
lock
message
msg_handler
negotiate
notify
SMB2 Change Notify Request and Response, and Server to Client Notification
oplock
plain
query_dir
Directory-related messages.
resource
security
MS-DTYP 2.4
session
SMB Session logic module.
session_setup
smb1
SMBv1 negotiation packet support.
sync_helpers
This is a helper module that allows easy access and usage of Async/Multi-threaded features in the library, according to the features enabled.
tree
tree_connect
util

Macros§

access_mask
Macro for defining a bitfield for an access mask.
guid
A macro to create a Guid from a string literal at compile time.
make_guid
A macro to create a Guid from a string literal at compile time.
query_info_data
Internal helper macro to easily generate fields & methods for QueryInfoData.

Structs§

ACE
ACL
AccessAce
AccessCallbackAce
AccessMask
This struct was partially generated by the smb_dtyp::access_mask! macro. Read more about generic access rights and standard access rights
AccessObjectAce
AccessObjectCallbackAce
AceFlags
AdditionalInfo
AllocationSize
AppInstanceId
AppInstanceVersion
ArrayData
BlobData
CancelRequest
ChainedItemList
Implements a chained item list.
ChangeNotifyRequest
ChangeNotifyResponse
ClaimSecurityAttributeRelativeV1
CloseFlags
CloseRequest
CloseResponse
CompressedChainedItem
CompressedChainedMessage
CompressedData
CompressedUnchainedMessage
CompressionCapabilities
CompressionCapsFlags
CreateContext
This is meant to be used within a ChainedItemList<T>!
CreateOptions
CreateRequest
CreateResponse
CreateResponseFlags
DH2QResp
DfsRequestData
RequestData is part of the REQ_GET_DFS_REFERRAL_EX message (section 2.2.3).
DfsRequestFlags
DirAccessMask
Directory Access Mask
DurableHandleReconnect
DurableHandleReconnectV2
DurableHandleRequest
DurableHandleRequestV2
DurableHandleResponse
DurableHandleV2Flags
EaFlags
Extended Attribute (EA) Flags
EchoMesasge
EncryptedHeader
EncryptedMessage
EncryptionCapabilities
EntryV3DCRefs
2.2.5.3.2 NameListReferral Flag Set to 1
EntryV3V4DfsPaths
2.2.5.3.1 NameListReferral Flag Set to 0
ErrorResponse
ErrorResponseContext
FciClaimSecurityAttributes
FileAccessInformation
Query the access rights of a file that were granted when the file was opened.
FileAccessMask
File Access Mask
FileAllInformation
Query a collection of file information structures.
FileAllocationInformation
Set the allocation size for a file.
FileAlternateNameInformation
Query the alternate name (8.3 short name) of a file.
FileAttributeTagInformation
Query file attribute and reparse tag information for a file.
FileAttributes
Attributes of a file or directory.
FileBasicInformation
Query or Set file information.
FileBothDirectoryInformation
Query detailed information for the files in a directory.
FileCompressionInformation
Query compression information for a file.
FileDirectoryInformation
Query detailed information for the files in a directory.
FileDispositionInformation
Mark a file for deletion.
FileEaInformation
Query the size of the extended attributes (EA) for a file.
FileEndOfFileInformation
Set end-of-file information for a file.
FileFsAttributeInformation
Query attribute information for a file system.
FileFsControlInformation
Query or Set quota and content indexing control information for a file system volume.
FileFsDeviceInformation
FileFsFullSizeInformation
Query sector size information for a file system volume.
FileFsObjectIdInformation
Query or Set the object ID for a file system data element. The operation MUST fail if the file system does not support object IDs.
FileFsSectorSizeInformation
Query for the extended sector size and alignment information for a volume.
FileFsSizeInformation
Query sector size information for a file system volume.
FileFsVolumeInformation
Query information on a volume on which a file system is mounted.
FileFullDirectoryInformation
Query detailed information for the files in a directory.
FileFullEaInformationInner
Query or Set extended attribute (EA) information for a file.
FileGetEaInformation
Query extended attributes for a file.
FileGetQuotaInformation
This structure is used to provide the list of SIDs for which quota query information is requested.
FileId
2.2.14.1: SMB2_FILEID
FileId64ExtdBothDirectoryInformation
Query detailed information for the files in a directory.
FileId64ExtdDirectoryInformation
Query detailed information for the files in a directory.
FileIdAllExtdBothDirectoryInformation
Query detailed information for the files in a directory.
FileIdAllExtdDirectoryInformation
Query detailed information for the files in a directory.
FileIdBothDirectoryInformation
Query detailed information for the files in a directory.
FileIdExtdDirectoryInformation
Query detailed information for the files in a directory.
FileIdFullDirectoryInformation
Query detailed information for the files in a directory.
FileIdInformation
Query the file system’s 8-byte file reference number for a file.
FileInternalInformation
Query the file system’s 8-byte file reference number for a file.
FileLevelTrimRange
MSDN
FileLevelTrimRequest
FileLevelTrimResponse
MS-FSCC 2.3.14
FileLinkInformation
Create a hard link to an existing file via the SMB Version 2 Protocol, as specified in [MS-SMB2].
FileModeInformation
Query or Set file mode information.
FileNameInformation
Query the name of a file.
FileNamesInformation
Query the names of the files in a directory.
FileNetworkOpenInformation
Query network file open information for a file.
FileNormalizedNameInformation
Query the normalized name of a file.
FileNotifyInformation
FILE_NOTIFY_INFORMATION - MS-FSCC 2.7.1
FilePipeInformation
Query or Set named pipe information.
FilePipeLocalInformation
Query information associated with a named pipe that is not specific to one end of the pipe or another.
FilePipeRemoteInformation
Query information that is associated with the remote end of a named pipe.
FilePositionInformation
Query or Set the current byte offset of the file pointer.
FileQuotaInformation
Query or to set file quota information for a volume.
FileRenameInformation
Rename a file within the SMB2 protocol.
FileShortNameInformation
change a file’s short name.
FileStandardInformation
Query standard information for a file.
FileStreamInformationInner
Enumerate the data streams for a file.
FileSystemAttributes
File system attributes.
FileSystemControlFlags
File system control flags.
FileValidDataLengthInformation
set the valid data length information for a file.
FlushRequest
FlushResponse
FsDeviceCharacteristics
Characteristics of a file system volume.
GetEaInfoList
GlobalCapabilities
Guid
Represents a standard, 16-byte GUID.
Header
Sync and Async SMB2 Message header.
HeaderFlags
IoctlBuffer
IoctlRequest
IoctlRequestFlags
IoctlResponse
LeaseBreakAckResponse
LeaseBreakNotify
LeaseState
LmrRequestResiliencyResponse
LockElement
LockFlag
LockRequest
LockResponse
LockSequence
LogoffRequest
LogoffResponse
LuidAttrData
MandatoryLabelAccessMask
This struct was partially generated by the smb_dtyp::access_mask! macro. Read more about generic access rights and standard access rights
NegotiateCapabilities
NegotiateContext
NegotiateRequest
NegotiateResponse
NegotiateSecurityMode
NetnameNegotiateContextId
NetworkInterfaceCapability
NetworkInterfaceInfo
NetworkResiliencyRequest
Sent to request resiliency for a specified open file. This request is not valid for the SMB 2.0.2 dialect.
NotifyFilter
NotifyFlags
NotifySessionClosed
NullByte
ObjectAccessMask
This struct was partially generated by the smb_dtyp::access_mask! macro. Read more about generic access rights and standard access rights
ObjectAceFlags
OffloadReadRequest
MS-FSCC 2.3.41
OffloadReadResponse
MS-FSCC 2.3.42
OplockBreakMsg
PipePeekRequest
PipePeekResponse
MS-FSCC 2.3.46
PipeTransceiveRequest
PipeTransceiveResponse
PipeWaitRequest
The FSCTL_PIPE_WAIT Request requests that the server wait until either a time-out interval elapses, or an instance of the specified named pipe is available for connection.
PipeWaitResponse
PlainRequest
A plain, single, SMB2 message.
PlainResponse
A plain, single, SMB2 message.
PreauthIntegrityCapabilities
QueryAllocRangesItem
QueryAllocRangesResult
QueryDirectoryFlags
QueryDirectoryRequest
QueryDirectoryResponse
QueryInfoFlags
QueryInfoRequest
QueryInfoResponse
QueryInfoResponseData
A helpers struct that contains the raw data of a query info response or a set info request, and can be parsed using the QueryInfoResponseData::parse method, to a specific info type.
QueryMaximalAccessRequest
QueryMaximalAccessResponse
QueryNetworkInterfaceInfoRequest
QueryOnDiskIdReq
QueryOnDiskIdResp
QueryQuotaInfo
RawQueryInfoData
RawSetInfoData
RdmaTransformCapabilities
ReadFlags
ReadRequest
ReadResponse
ReferralEntry
ReferralEntryFlags
ReferralEntryValueV1
ReferralEntryValueV2
DO NOT use this struct directly when bin read/writing. Use an instance of ReferralEntry instead.
ReferralEntryValueV3
ReferralEntryValueV4
ReferralHeaderFlags
RemotedIdentityTreeConnect
ReqGetDfsReferral
MS-DFSC 2.2.2: DFS referral requests are sent in the form of an REQ_GET_DFS_REFERRAL message, by using an appropriate transport as specified in section 2.1.
ReqGetDfsReferralEx
RequestLeaseV1
RequestLeaseV2
RespGetDfsReferral
SID
SID (Security identifier)
SectorSizeInfoFlags
File system sector flags.
SecurityDescriptor
Security Descriptor - MS-DTYP 2.4.6
SecurityDescriptorControl
ServerToClientNotification
SessionFlags
SessionSecurityMode
SessionSetupRequest
SessionSetupResponse
SetInfoRequest
SetInfoResponse
SetReparsePointRequest
Stores data for a reparse point.
SetReparsePointResponse
SetupRequestFlags
ShareAccessFlags
ShareFlags
SidAttrData
SidAttrSeGroup
SigningCapabilities
SocketAddrStorageV4
SocketAddrStorageV6
SrvCopyChunkCopyWrite
SrvCopychunkCopy
The Length of source/dest keys in SrvCopyChunk* FSCTLs contents. MS-SMB 2.2.31.1
SrvCopychunkItem
SrvCopychunkResponse
SrvEnumerateSnapshotsRequest
SrvEnumerateSnapshotsResponse
MS-SMB 2.2.7.2.2.1
SrvHashRetrieveFileBased
SrvHashRetrieveHashBased
SrvReadHashReq
SrvReadHashRes
SrvRequestResumeKey
SrvRequestResumeKeyRequest
SrvSnapshotArray
SvhdxOpenDeviceContextV1
MS-RSVD sections 2.2.4.12 and 2.2.4.32.
SvhdxOpenDeviceContextV2
SystemMandatoryLabelAce
SystemResourceAttributeAce
TimewarpToken
TransportCapabilities
TreeCapabilities
TreeConnectContext
TreeConnectRequest
Tree Connect Request
TreeConnectRequestFlags
TreeConnectResponse
TreeDisconnectRequest
TreeDisconnectResponse
ValidateNegotiateInfoRequest
ValidateNegotiateInfoResponse
WriteFlags
WriteRequest
Zero-copy write request.
WriteResponse

Enums§

AceType
AceValue
AclRevision
ClaimSecurityAttributeType
Command
CommunicationChannel
CompressedMessage
CompressionAlgorithm
CreateAction
CreateContextReqData
The Req Create Context data enum. This contains all the possible context types for Req
CreateContextRespData
The Resp Create Context data enum. This contains all the possible context types for Resp
CreateContextType
CreateDisposition
DfsServerType
Type of server hosting the target
Dialect
EncryptionCipher
EntryV3Value
ErrorId
FileAlignmentInformation
Query the buffer alignment required by the underlying device.
FileCompressionFormat
Compression format values for file compression.
FsDeviceType
FsctlCodes
GetInfoRequestData
This struct describes the payload to be added in the QueryInfoRequest when asking for information about Quota or Extended Attributes. In other cases, it is empty.
HashAlgorithm
ImpersonationLevel
InfoType
IoctlReqData
NamedPipeConfiguration
Named pipe configuration values.
NamedPipeEnd
Named pipe end values.
NamedPipeState
Named pipe state values.
NamedPipeType
Named pipe type values.
NegotiateContextType
NegotiateContextValue
NegotiateDialect
Dialects that may be used in the SMB Negotiate Request. The same as Dialect but with a wildcard for SMB 2.0.
Notification
NotificationType
NotifyAction
See FileNotifyInformation
OplockLevel
PipeCompletionMode
Named pipe completion mode values.
PipeReadMode
Named pipe read mode values.
QueryDirectoryInfo
Query (list) directory information classes.
QueryDirectoryInfoClass
Information class IDs for QueryDirectoryInfo
QueryFileInfo
Query file information classes.
QueryFileInfoClass
Information class IDs for QueryFileInfo
QueryFileSystemInfo
Query file system information classes.
QueryFileSystemInfoClass
Information class IDs for QueryFileSystemInfo
QueryInfoClass
QueryInfoData
Enum to hold the different info types for QueryInfoData, that are used within SMB requests for querying or setting information.
RdmaTransformId
ReferralEntryValue
ReferralLevel
The DFS referral version supported by the client. See ReqGetDfsReferral::max_referral_level.
ReparseTag
Reparse Tag Values
Request
RequestContent
RequestLease
Response
ResponseContent
SetFileInfo
Set file information classes.
SetFileInfoClass
Information class IDs for SetFileInfo
SetFileSystemInfo
Set file system information classes.
SetFileSystemInfoClass
Information class IDs for SetFileSystemInfo
SetInfoClass
A helper class for SetInfoRequest to contain the information class to set. In cases of no class, it will be set to a null byte (0u8).
SetInfoData
Enum to hold the different info types for SetInfoData, that are used within SMB requests for querying or setting information.
ShareCacheMode
ShareType
SigningAlgorithmId
SmbFsccError
Errors specific to the smb-fscc crate.
SmbMsgError
SMB Message related errors
SocketAddrStorage
SrvHashRetrievalType
Status
NT Status codes.
SvhdxOpenDeviceContext

Constants§

CHAINED_ITEM_PREFIX_SIZE
The size of added fields to the size of each entry in ChainedItemList<T>, when bin-writing the data, before the actual T data.

Traits§

CreateContextDataReqValue
CreateContextDataRespValue
FileInfoType
Trait for file information types. This trait contains all types of all file info types and classes, specified in MS-FSCC.
FsctlRequest
This is a helper trait that defines, for a certain FSCTL request type, the response type and their matching FSCTL code.
FsctlResponseContent
A trait that helps parsing FSCTL responses by matching the FSCTL code.
IoctlRequestContent
A trait that helps calculating the size of the buffer for IOCTL requests.
QueryDirectoryInfoValue
Trait for inner values in QueryDirectoryInfo.
QueryFileInfoValue
Trait for inner values in QueryFileInfo.
QueryFileSystemInfoValue
Trait for inner values in QueryFileSystemInfo.
SetFileInfoValue
Trait for inner values in SetFileInfo.
SetFileSystemInfoValue
Trait for inner values in SetFileSystemInfo.

Type Aliases§

EchoRequest
EchoResponse
EncryptionNonce
The nonce used for encryption. Depending on the encryption algorithm, the nonce may be trimmed to a smaller size when used, or padded with zeroes to match the required size. When transmitted, the full 16 bytes are used.
FileFullEaInformation
FileStreamInformation
LeaseBreakAck
LeaseBreakResponse
NetworkInterfacesInfo
OplockBreakAck
OplockBreakNotify
OplockBreakResponse
QueryFileFullEaInformation
ReqCreateContext
RespCreateContext
Result
SMB Result type
SdBuffer