> For the complete documentation index, see [llms.txt](https://www.impacket.wiki/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.impacket.wiki/reference/library-api/smb-and-netbios/smb.md).

# SMB Protocol Internals

> SMB protocol implementation for file sharing and network communication

## Overview

The `smb` module provides a complete implementation of the SMB (Server Message Block) protocol version 1. This module handles low-level SMB packet construction, authentication, file operations, and named pipe communication.

## Key Classes

### SMB

Main class for SMB protocol implementation.

```python
from impacket import smb

conn = smb.SMB(remote_name, remote_host)
conn.login(user, password, domain)
```

* **Parameter `remote_name`** **`str`:** The NetBIOS name of the remote host. Use `'*SMBSERVER'` for auto-detection.
* **Parameter `remote_host`** **`str`:** IP address or hostname of the remote server
* **Parameter `my_name`** **`str`:** Local NetBIOS name. Defaults to local hostname if not specified.
* **Parameter `sess_port`** **`int`:** Port number for NetBIOS session service
* **Parameter `timeout`** **`int`:** Connection timeout in seconds

### Methods

#### login()

Authenticate to the SMB server using NTLM.

```python
conn.login(user, password, domain='', lmhash='', nthash='')
```

* **Parameter `user`** **`str`:** Username for authentication
* **Parameter `password`** **`str`:** Password for authentication (not used if hashes provided)
* **Parameter `domain`** **`str`:** Domain name for authentication
* **Parameter `lmhash`** **`str`:** LM hash for pass-the-hash authentication
* **Parameter `nthash`** **`str`:** NT hash for pass-the-hash authentication
* **Returns `return`** **`None`:** Raises `SessionError` if authentication fails

#### connect\_tree()

Connect to a shared resource on the server.

```python
tid = conn.connect_tree(share)
```

* **Parameter `share`** **`str`:** UNC path to the share (e.g., `'\\\\server\\share'`)
* **Returns `return`** **`int`:** Tree ID (TID) used for subsequent file operations

#### list\_path()

List files and directories in a share.

```python
files = conn.list_path(shareName, path, password=None)
```

* **Parameter `shareName`** **`str`:** Name of the share to list
* **Parameter `path`** **`str`:** Path relative to the share root (e.g., `'*'` for all files)
* **Parameter `password`** **`str`:** Password for password-protected shares
* **Returns `return`** **`list[SharedFile]`:** List of `SharedFile` objects containing file information

#### open()

Open or create a file on the share.

```python
fid = conn.open(tid, path, desired_access, share_mode,
                creation_options, creation_disposition,
                file_attributes)
```

* **Parameter `tid`** **`int`:** Tree ID from `connect_tree()`
* **Parameter `path`** **`str`:** Path to the file relative to share root
* **Parameter `desired_access`** **`int`:** Access mask specifying desired operations (e.g., `FILE_READ_DATA`, `FILE_WRITE_DATA`)
* **Parameter `share_mode`** **`int`:** Share mode flags (e.g., `FILE_SHARE_READ`, `FILE_SHARE_WRITE`)
* **Parameter `creation_options`** **`int`:** Creation options (e.g., `FILE_NON_DIRECTORY_FILE`)
* **Parameter `creation_disposition`** **`int`:** Creation disposition (e.g., `FILE_OPEN`, `FILE_CREATE`, `FILE_OVERWRITE_IF`)
* **Parameter `file_attributes`** **`int`:** File attributes (e.g., `ATTR_NORMAL`, `ATTR_READONLY`)
* **Returns `return`** **`int`:** File ID (FID) used for read/write operations

#### read\_andx()

Read data from an open file.

```python
data = conn.read_andx(tid, fid, offset=0, max_size=None)
```

* **Parameter `tid`** **`int`:** Tree ID
* **Parameter `fid`** **`int`:** File ID from `open()`
* **Parameter `offset`** **`int`:** Byte offset to start reading from
* **Parameter `max_size`** **`int`:** Maximum bytes to read. Defaults to server's max buffer size.
* **Returns `return`** **`bytes`:** Data read from the file

#### write\_andx()

Write data to an open file.

```python
bytes_written = conn.write_andx(tid, fid, data, offset=0)
```

* **Parameter `tid`** **`int`:** Tree ID
* **Parameter `fid`** **`int`:** File ID from `open()`
* **Parameter `data`** **`bytes`:** Data to write to the file
* **Parameter `offset`** **`int`:** Byte offset to start writing at
* **Returns `return`** **`int`:** Number of bytes written

#### close()

Close an open file.

```python
conn.close(tid, fid)
```

* **Parameter `tid`** **`int`:** Tree ID
* **Parameter `fid`** **`int`:** File ID to close

#### logoff()

Log off from the SMB server.

```python
conn.logoff()
```

## Constants

### File Attributes

```python
ATTR_READONLY = 0x001    # Read-only file
ATTR_HIDDEN = 0x002      # Hidden file
ATTR_SYSTEM = 0x004      # System file
ATTR_DIRECTORY = 0x010   # Directory
ATTR_ARCHIVE = 0x020     # Archive flag
ATTR_NORMAL = 0x080      # Normal file
ATTR_TEMPORARY = 0x100   # Temporary file
ATTR_COMPRESSED = 0x800  # Compressed file
```

### Access Masks

```python
FILE_READ_DATA = 0x00000001       # Read file data
FILE_WRITE_DATA = 0x00000002      # Write file data
FILE_APPEND_DATA = 0x00000004     # Append to file
FILE_READ_EA = 0x00000008         # Read extended attributes
FILE_WRITE_EA = 0x00000010        # Write extended attributes
FILE_EXECUTE = 0x00000020         # Execute file
FILE_READ_ATTRIBUTES = 0x00000080 # Read file attributes
FILE_WRITE_ATTRIBUTES = 0x00000100 # Write file attributes
DELETE = 0x00010000               # Delete file
GENERIC_READ = 0x80000000         # Generic read access
GENERIC_WRITE = 0x40000000        # Generic write access
GENERIC_ALL = 0x10000000          # All access rights
```

### Share Access Modes

```python
FILE_SHARE_READ = 0x00000001      # Allow concurrent read access
FILE_SHARE_WRITE = 0x00000002     # Allow concurrent write access
FILE_SHARE_DELETE = 0x00000004    # Allow concurrent delete access
```

### Creation Disposition

```python
FILE_SUPERSEDE = 0x00000000    # Replace file if exists, create if not
FILE_OPEN = 0x00000001         # Open existing file only
FILE_CREATE = 0x00000002       # Create new file only
FILE_OPEN_IF = 0x00000003      # Open if exists, create if not
FILE_OVERWRITE = 0x00000004    # Overwrite existing file only
FILE_OVERWRITE_IF = 0x00000005 # Overwrite if exists, create if not
```

## Supporting Classes

### SharedFile

Represents file information returned by `list_path()`.

* **Returns `get_longname()`** **`str`:** Returns the full filename
* **Returns `get_shortname()`** **`str`:** Returns the 8.3 short filename
* **Returns `get_filesize()`** **`int`:** Returns file size in bytes
* **Returns `is_directory()`** **`bool`:** Returns True if item is a directory
* **Returns `is_readonly()`** **`bool`:** Returns True if file is read-only
* **Returns `is_hidden()`** **`bool`:** Returns True if file is hidden
* **Returns `get_ctime_epoch()`** **`int`:** Returns creation time as Unix timestamp
* **Returns `get_mtime_epoch()`** **`int`:** Returns modification time as Unix timestamp
* **Returns `get_atime_epoch()`** **`int`:** Returns access time as Unix timestamp

### SessionError

Exception raised when SMB operations fail.

```python
try:
    conn.login(user, password)
except smb.SessionError as e:
    print(f"Error: {e}")
    error_code = e.get_error_code()
```

* **Returns `get_error_code()`** **`int`:** Returns the SMB error code
* **Returns `get_error_class()`** **`int`:** Returns the error class

## Usage Examples

### Basic File Operations

```python
from impacket import smb
from impacket.smb import FILE_OPEN, FILE_SHARE_READ

# Connect to server
conn = smb.SMB('*SMBSERVER', '192.168.1.100')
conn.login('user', 'password', 'DOMAIN')

# Connect to share
tid = conn.connect_tree('\\\\192.168.1.100\\share')

# List files
files = conn.list_path('share', '*')
for f in files:
    print(f"{f.get_longname()} - {f.get_filesize()} bytes")

# Read a file
fid = conn.open(tid, 'example.txt', smb.FILE_READ_DATA,
                FILE_SHARE_READ, smb.FILE_NON_DIRECTORY_FILE,
                FILE_OPEN, smb.ATTR_NORMAL)
data = conn.read_andx(tid, fid)
conn.close(tid, fid)

print(data.decode('utf-8'))

# Clean up
conn.logoff()
```

### Writing Files

```python
from impacket import smb

conn = smb.SMB('*SMBSERVER', '192.168.1.100')
conn.login('user', 'password')
tid = conn.connect_tree('\\\\192.168.1.100\\share')

# Create and write to file
fid = conn.open(tid, 'output.txt',
                smb.FILE_WRITE_DATA | smb.FILE_READ_DATA,
                smb.FILE_SHARE_READ, smb.FILE_NON_DIRECTORY_FILE,
                smb.FILE_OVERWRITE_IF, smb.ATTR_NORMAL)

data = b"Hello, SMB World!"
conn.write_andx(tid, fid, data)
conn.close(tid, fid)

conn.logoff()
```

### Pass-the-Hash Authentication

```python
from impacket import smb
import hashlib

conn = smb.SMB('*SMBSERVER', '192.168.1.100')

# Authenticate using NTLM hash
lmhash = 'aad3b435b51404eeaad3b435b51404ee'
nthash = '8846f7eaee8fb117ad06bdd830b7586c'

conn.login('admin', '', domain='CORP', lmhash=lmhash, nthash=nthash)
tid = conn.connect_tree('\\\\192.168.1.100\\C$')

# Now you can perform operations
files = conn.list_path('C$', '*')
conn.logoff()
```

## Error Handling

```python
from impacket import smb
from impacket.nt_errors import STATUS_ACCESS_DENIED, STATUS_OBJECT_NAME_NOT_FOUND

try:
    conn = smb.SMB('*SMBSERVER', '192.168.1.100')
    conn.login('user', 'wrongpassword')
except smb.SessionError as e:
    if e.get_error_code() == STATUS_ACCESS_DENIED:
        print("Access denied - check credentials")
    else:
        print(f"SMB Error: {e}")
```

## Helper Functions

### Time Conversion

```python
from impacket import smb
import time

# Convert POSIX timestamp to Windows FILETIME
posix_time = int(time.time())
filetime = smb.POSIXtoFT(posix_time)

# Convert FILETIME to POSIX timestamp
posix_time = smb.FTtoPOSIX(filetime)
```

## See Also

* [SMBConnection](/reference/library-api/smb-and-netbios/smbconnection.md) - High-level SMB client wrapper
* [SMB3](/reference/library-api/smb-and-netbios/smbconnection.md) - SMB2/SMB3 protocol implementation
* [NTLM](/reference/library-api/auth-and-crypto/ntlm.md) - NTLM authentication helpers


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://www.impacket.wiki/reference/library-api/smb-and-netbios/smb.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
