TypeScript SMB2/3 Server #
A complete SMB2/3 (Server Message Block) protocol server implementation written entirely in TypeScript. This project provides a modern, type-safe, and extensible SMB file server that can be used for creating network file shares compatible with Windows, macOS, and Linux clients.
π Features #
- Full SMB2/3 Protocol Support: Implements SMB 2.0.2, 2.1.0, 3.0.0, 3.0.2, and 3.1.1 dialects
- Type-Safe Implementation: Written entirely in TypeScript with comprehensive type definitions
- Modern Architecture: Clean, modular design with separation of concerns
- Cross-Platform: Runs on Windows, macOS, and Linux
- Extensible: Plugin-based architecture for custom authentication and file system providers
- Comprehensive Logging: Structured logging with multiple levels and formats
- Performance Optimized: Efficient buffer handling and async operations
- Standards Compliant: Based on Microsoft's official SMB2/3 specifications
π Supported Operations #
Core Operations #
- β Negotiate: Protocol version negotiation with clients
- β Session Setup: User authentication (anonymous, guest, NTLM stub)
- β Tree Connect: Share connection and access control
- β Create: File and directory creation/opening
- β Close: File and directory closing
- β Read: File data reading with range support
- β Write: File data writing with various flags
- β Echo: Connection keep-alive and health checks
Information Operations #
- β Query Directory: Directory enumeration with multiple information classes
- β Query Info: File/directory metadata retrieval
- β Set Info: File/directory metadata modification (basic timestamps, attributes)
Session Management #
- β Logoff: Session termination and cleanup
- β Tree Disconnect: Share disconnection and resource cleanup
π οΈ Installation #
Prerequisites #
- Node.js: Version 18.0.0 or higher
- npm: Comes with Node.js
- Administrator/Root privileges: Required for binding to port 445
Install Dependencies #
cd crypt/smb-server
npm install
Build the Project #
npm run build
π Quick Start #
Basic Usage #
# Start the server with default configuration
npm start
# Start with debug logging
LOG_LEVEL=debug npm start
# Start on a custom port (doesn't require admin privileges)
SMB_PORT=8445 npm start
# Start with custom share path
SMB_SHARE_PATH=/path/to/your/files npm start
Programmatic Usage #
import { SMB2Server } from './src/server';
import { SMB2_DIALECTS, SHARE_TYPE, SHARE_FLAGS, ACCESS_MASK } from './src/protocol/constants';
const server = new SMB2Server({
serverName: 'My-SMB-Server',
supportedDialects: [SMB2_DIALECTS.SMB3_0_2],
requireMessageSigning: false,
enableEncryption: false,
shares: [{
name: 'Documents',
path: '/home/user/documents',
shareType: SHARE_TYPE.DISK,
shareFlags: SHARE_FLAGS.AUTO_CACHING,
maximalAccess: ACCESS_MASK.GENERIC_ALL,
encryptData: false,
description: 'Document share'
}]
});
// Set up event handlers
server.onEvent('connection:established', (event) => {
console.log(`Client connected: ${event.data.connection.clientAddress}`);
});
server.onEvent('session:established', (event) => {
console.log(`User authenticated: ${event.data.userId}`);
});
// Start the server
await server.start(445);
console.log('SMB2 Server started on port 445');
βοΈ Configuration #
The server can be configured through environment variables or programmatically:
Environment Variables #
| Variable | Description | Default |
|---|---|---|
LOG_LEVEL |
Logging level (error, warn, info, debug) | info |
SMB_PORT |
Server port | 445 |
SMB_HOST |
Server hostname/IP | 0.0.0.0 |
SMB_SERVER_NAME |
Server name | TypeScript-SMB-Server |
SMB_DOMAIN_NAME |
Domain name | undefined |
SMB_WORKGROUP_NAME |
Workgroup name | WORKGROUP |
SMB_REQUIRE_SIGNING |
Require message signing | false |
SMB_ENABLE_ENCRYPTION |
Enable SMB encryption | false |
SMB_MAX_CONNECTIONS |
Maximum concurrent connections | 100 |
SMB_MAX_SESSIONS_PER_CONNECTION |
Max sessions per connection | 16 |
SMB_SESSION_TIMEOUT |
Session timeout in ms | 300000 |
SMB_MAX_TRANSACT_SIZE |
Maximum transaction size | 65536 |
SMB_MAX_READ_SIZE |
Maximum read size | 65536 |
SMB_MAX_WRITE_SIZE |
Maximum write size | 65536 |
SMB_SHARE_PATH |
Default share path | ./shared |
Programmatic Configuration #
const config = {
serverGuid: 'your-server-guid',
serverName: 'Custom-Server',
supportedDialects: [
SMB2_DIALECTS.SMB2_1_0,
SMB2_DIALECTS.SMB3_0_0
],
requireMessageSigning: true,
enableEncryption: true,
maxConnections: 50,
shares: [
{
name: 'Public',
path: '/srv/public',
shareType: SHARE_TYPE.DISK,
shareFlags: SHARE_FLAGS.AUTO_CACHING,
capabilities: SHARE_CAPABILITIES.DFS,
maximalAccess: ACCESS_MASK.GENERIC_READ,
encryptData: true,
description: 'Public read-only share',
accessControl: [
{
principal: 'guest',
accessMask: ACCESS_MASK.GENERIC_READ,
allowDeny: 'allow'
}
]
}
],
users: [
{
username: 'testuser',
passwordHash: 'sha256-hash-of-password',
isGuest: false,
isAdmin: false,
allowedShares: ['Public']
}
]
};
ποΈ Architecture #
The server is built with a modular architecture:
src/
βββ server.ts # Main server class
βββ protocol/ # SMB2/3 protocol implementation
β βββ constants.ts # Protocol constants and enums
β βββ types.ts # TypeScript type definitions
β βββ parser.ts # Message parsing logic
β βββ serializer.ts # Message serialization logic
βββ commands/ # SMB2 command handlers
β βββ negotiate.ts # Protocol negotiation
β βββ session-setup.ts # Authentication
β βββ tree-connect.ts # Share connection
β βββ create.ts # File/directory operations
β βββ read.ts # File reading
β βββ write.ts # File writing
β βββ ... # Other command handlers
βββ auth/ # Authentication providers
β βββ authentication.ts # Authentication manager
βββ filesystem/ # File system providers
β βββ provider.ts # File system abstraction
βββ utils/ # Utility functions
βββ logger.ts # Logging utilities
βββ helpers.ts # Common helper functions
Key Components #
- SMB2Server: Main server class that handles connections and message routing
- Protocol Layer: Handles SMB2/3 message parsing and serialization
- Command Handlers: Process specific SMB2 commands
- Authentication Manager: Handles user authentication and session security
- File System Provider: Abstracts file system operations
- Logger: Provides structured logging with multiple output formats
π§ Development #
Scripts #
# Development with auto-reload
npm run dev
# Build the project
npm run build
# Run tests
npm test
# Run tests in watch mode
npm run test:watch
# Lint the code
npm run lint
# Fix linting issues
npm run lint:fix
# Clean build artifacts
npm run clean
Testing #
The project includes comprehensive tests for all major components:
# Run all tests
npm test
# Run tests with coverage
npm run test:coverage
# Run specific test file
npm test -- --testPathPattern=server.test.ts
Development Setup #
- Clone the repository
- Install dependencies:
npm install - Start development server:
npm run dev - The server will restart automatically when files change
π Monitoring and Logging #
The server provides comprehensive logging and monitoring capabilities:
Logging Levels #
- error: Critical errors that require immediate attention
- warn: Warning conditions that should be investigated
- info: General operational information
- debug: Detailed debugging information
Log Formats #
- detailed: Human-readable format with timestamps and context
- json: Machine-readable JSON format for log aggregation
- simple: Minimal format for development
Metrics and Events #
The server emits events for monitoring:
server.onEvent('connection:established', (event) => {
// Track new connections
});
server.onEvent('file:opened', (event) => {
// Monitor file access
});
server.onEvent('error', (event) => {
// Handle errors
});
π Security Considerations #
Authentication #
- Anonymous Access: Enabled by default for development
- Guest Access: Limited access for unauthenticated users
- NTLM Authentication: Stub implementation (not production-ready)
- Custom Authentication: Extensible authentication providers
Access Control #
- Share-Level Security: Control access to individual shares
- User-Based Permissions: Configure per-user access rights
- File-Level Security: Respect underlying file system permissions
Network Security #
- Message Signing: Optional SMB message signing
- Encryption: SMB3 encryption support (basic implementation)
- TLS Support: Future enhancement planned
π€ Contributing #
Contributions are welcome! Please read our contributing guidelines:
- Fork the repository
- Create a feature branch:
git checkout -b feature/your-feature - Make your changes with proper tests
- Run the test suite:
npm test - Lint your code:
npm run lint - Submit a pull request
Development Guidelines #
- Follow TypeScript best practices
- Maintain comprehensive test coverage
- Use conventional commit messages
- Update documentation for new features
- Ensure cross-platform compatibility
π Known Issues and Limitations #
Current Limitations #
- NTLM Authentication: Only stub implementation
- Kerberos Support: Not implemented
- SMB Encryption: Basic implementation only
- Opportunistic Locks: Not fully implemented
- Durable Handles: Stub implementation
- Multi-Channel: Not implemented
- Compression: Not implemented
Performance Notes #
- Designed for development and testing use
- Not optimized for high-concurrency production use
- Large file operations may require optimization
- Memory usage scales with concurrent connections
π License #
This project is licensed under the MIT License - see the LICENSE file for details.
π Acknowledgments #
- Microsoft's SMB2/3 Protocol Specifications
- The Node.js and TypeScript communities
- Contributors and testers
π Support #
For questions, issues, or contributions:
- Open an issue on GitHub
- Check existing documentation
- Review the test files for usage examples
Note: This is a development/educational implementation of the SMB2/3 protocol. For production use, additional security hardening, performance optimization, and feature completeness may be required.