This repository has no description
TypeScript 99%
JavaScript 1%

README.md

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 #

  1. Clone the repository
  2. Install dependencies: npm install
  3. Start development server: npm run dev
  4. 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:

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/your-feature
  3. Make your changes with proper tests
  4. Run the test suite: npm test
  5. Lint your code: npm run lint
  6. 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.