759 lines
30 KiB
Python
759 lines
30 KiB
Python
#!/usr/bin/python3
|
|
|
|
import socket
|
|
import subprocess
|
|
import os
|
|
import re
|
|
import sys
|
|
import getpass
|
|
import requests
|
|
import random
|
|
import time
|
|
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
from threading import Lock
|
|
import multiprocessing
|
|
import socket
|
|
import threading
|
|
import ssl
|
|
import shutil
|
|
import re
|
|
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
from urllib.request import urlopen
|
|
SCANFOLDER=os.path.join(os.path.dirname(sys.argv[0]),"recons_scans")
|
|
KEYWORDS = [".txt", "pass", "creds", "user", ".dic", "hash", "<!--","admin","THM"]
|
|
services=[]
|
|
CRITICS_PORTS=[21,1234,4444,9000,5000,88,139,445]
|
|
CRITICS_SERVICES=["kerberos","redis","microsoft-ds","ldap","netbios-ssn"]
|
|
MID_SERVICES=["http","https","SSH"]
|
|
MID_PORTS=[80,443,8080,8000,22]
|
|
threads=[]
|
|
class Colors:
|
|
RED = "\033[0;31m"
|
|
GREEN = "\033[0;32m"
|
|
YELLOW = "\033[1;33m"
|
|
ORANGE = "\033[38;5;208m"
|
|
END = "\033[0m"
|
|
|
|
|
|
def clear():
|
|
subprocess.run("clear" if os.name == "posix" else "cls")
|
|
|
|
wordlists = [
|
|
f"/home/{getpass.getuser()}/code/dirb.txt"
|
|
"/usr/share/dirb/wordlists/common.txt",
|
|
"/usr/share/wordlists/dirbuster/directory-list-2.3-small.txt",
|
|
]
|
|
TIPS = [
|
|
f"you can add some wordlists in the config file /home/{getpass.getuser()}/.config/recon/wordlists.txt",
|
|
f"\n{Colors.RED}RED{Colors.END} = CRITICAL\n{Colors.ORANGE}ORANGE{Colors.END} = MID\n{Colors.GREEN}GREEN{Colors.END} = LOW",
|
|
f"for further enumeration install the projectdiscovery.io suits (subfinder, nuclei, katana and httpx)"
|
|
]
|
|
|
|
CONFIG_FOLDER = f"/home/{getpass.getuser()}/.config/recon"
|
|
#CONFIG_FOLDER = f"/home/coder/.config/recon"
|
|
if not os.path.isdir(SCANFOLDER):
|
|
os.makedirs(SCANFOLDER)
|
|
os.chdir(SCANFOLDER)
|
|
if not os.path.isdir(CONFIG_FOLDER):
|
|
os.makedirs(CONFIG_FOLDER)
|
|
if not os.path.isfile(os.path.join(CONFIG_FOLDER, "wordlists.txt")):
|
|
with open(os.path.join(CONFIG_FOLDER, "wordlists.txt"), "w") as f:
|
|
for wordlist in wordlists:
|
|
f.write(wordlist+"\n")
|
|
else:
|
|
with open(os.path.join(CONFIG_FOLDER, "wordlists.txt"), "r") as f:
|
|
wordlists += f.readlines()
|
|
|
|
for wordlist in list(set(wordlists)):
|
|
if not os.path.isfile(wordlist):
|
|
wordlists.remove(wordlist)
|
|
if len(wordlists) == 1:
|
|
wordlist=wordlists[0]
|
|
if not len(wordlists) == 0:
|
|
for i, wordlist in enumerate(list(set(wordlists))):
|
|
print(f"{i + 1}) {wordlist}")
|
|
choice = input("enter the index of the wordlist to use > ")
|
|
try:
|
|
wordlist = list(set(wordlists))[int(choice) - 1]
|
|
except ValueError:
|
|
if choice in list(set(wordlists)):
|
|
wordlist = choice
|
|
else:
|
|
wordlist = random.choice(list(set(wordlists)))
|
|
else:
|
|
print("no wordlist can be use, downloading dirbuster list !")
|
|
if os.path.isfile(os.path.join(CONFIG_FOLDER, "dirbuster.txt")):
|
|
with open(os.path.join(CONFIG_FOLDER, "dirbuster.txt"), "w") as f:
|
|
r = requests.get(
|
|
"https://raw.githubusercontent.com/brutalgg/dirbuster-wordlist/refs/heads/master/directory-list-2.3-small.txt",
|
|
timeout=5,
|
|
)
|
|
if r.status_code == 200:
|
|
lines = r.content.decode().splitlines()
|
|
cleaned = [l for l in lines[:30] if not l.startswith("#")]
|
|
f.writelines(l + "\n" for l in cleaned)
|
|
print("dirbuster list have been downloaded successfully !")
|
|
wordlist = os.path.join(CONFIG_FOLDER, "dirbuster.txt")
|
|
else:
|
|
f.write(
|
|
"""upload\npages\nadmin\nfeed\nlogin\ndefault\nindex\ncontact\ndatabase\n0\nsecurity\nfiles\ntools\nuser\nthemes\nwp-content\nphp\nassets\njs\ntest\ndev"""
|
|
)
|
|
wordlist = os.path.join(CONFIG_FOLDER, "dirbuster.txt")
|
|
else:
|
|
wordlist = os.path.join(CONFIG_FOLDER, "dirbuster.txt")
|
|
WORDLIST = wordlist
|
|
#WORDLIST="/home/benji/code/dirb.txt"
|
|
|
|
|
|
|
|
# small helpers for extracting version-like substrings
|
|
_srv_pattern = re.compile(
|
|
r"(?P<name>[A-Za-z0-9\-_]+)(?:/| v| version)?(?P<ver>[0-9][A-Za-z0-9\.\-\_+]*)?"
|
|
)
|
|
_server_header_re = re.compile(r"^Server:\s*(.+)$", re.IGNORECASE | re.MULTILINE)
|
|
|
|
|
|
def _safe_recv(sock, bufsize=4096):
|
|
try:
|
|
return sock.recv(bufsize).decode(errors="ignore")
|
|
except Exception:
|
|
return ""
|
|
|
|
|
|
def detect_service(ip, port, timeout=3):
|
|
global services
|
|
"""
|
|
Try to detect the service running on ip:port.
|
|
Returns a dict: { 'port': port, 'service': name_hint, 'banner': banner_text, 'version': maybe_version, 'extra': {...} }
|
|
"""
|
|
info = {"port": port, "service": None, "banner": None, "version": None, "extra": {}}
|
|
|
|
# service name hint from /etc/services if available
|
|
try:
|
|
info["service"] = socket.getservbyport(port)
|
|
except Exception:
|
|
info["service"] = None
|
|
|
|
# Generic banner grabbing
|
|
try:
|
|
with socket.create_connection((ip, port), timeout=timeout) as s:
|
|
# set a small recv timeout
|
|
s.settimeout(1.0)
|
|
try:
|
|
banner = _safe_recv(s, 4096)
|
|
except Exception:
|
|
banner = ""
|
|
if banner:
|
|
info["banner"] = banner.strip()
|
|
# try to parse a version
|
|
m = _srv_pattern.search(banner)
|
|
if m:
|
|
info["version"] = m.group("ver") or info["version"]
|
|
# If banner contains "SSH-" that's SSH
|
|
if "SSH-" in banner:
|
|
info["service"] = "ssh"
|
|
# SSH banner typically: SSH-2.0-OpenSSH_8.4
|
|
m = re.search(
|
|
r"SSH-2\.\d+[-_ ]?(?P<prod>[\w\-_]+)(?:[_-]v?(?P<ver>[\d\.]+))?",
|
|
banner,
|
|
)
|
|
if m:
|
|
info["version"] = m.group("ver") or info["version"]
|
|
services.append(info)
|
|
# If no immediate banner, try small protocol-specific probes below (we reconnect per probe).
|
|
except Exception:
|
|
# connect failed, return early with whatever we have
|
|
services.append(info)
|
|
|
|
# Protocol-specific probes (reconnect for each)
|
|
# 1) HTTP probe (plain)
|
|
try:
|
|
with socket.create_connection((ip, port), timeout=timeout) as s:
|
|
s.settimeout(timeout)
|
|
http_req = f"HEAD / HTTP/1.0\r\nHost: {ip}\r\nUser-Agent: scan/1.0\r\nConnection: close\r\n\r\n"
|
|
s.sendall(http_req.encode())
|
|
resp = _safe_recv(s, 8192)
|
|
if resp and resp.startswith("HTTP/"):
|
|
info["service"] = "http"
|
|
info["banner"] = (info["banner"] or "") + "\n" + resp.splitlines()[0]
|
|
# try to extract Server header
|
|
m = _server_header_re.search(resp)
|
|
if m:
|
|
server_val = m.group(1).strip()
|
|
info["extra"]["http_server_header"] = server_val
|
|
mm = _srv_pattern.search(server_val)
|
|
if mm:
|
|
info["version"] = mm.group("ver") or info["version"]
|
|
services.append(info)
|
|
except Exception:
|
|
pass
|
|
|
|
# 2) HTTPS / TLS certificate probe
|
|
try:
|
|
ctx = ssl.create_default_context()
|
|
with socket.create_connection((ip, port), timeout=timeout) as s:
|
|
with ctx.wrap_socket(s, server_hostname=ip) as ss:
|
|
cert = ss.getpeercert()
|
|
# presence of cert => TLS-enabled service (https or other tls)
|
|
info["service"] = info["service"] or "tls"
|
|
info["extra"]["tls_subject"] = cert.get("subject")
|
|
info["extra"]["tls_issuer"] = cert.get("issuer")
|
|
# sometimes certificate commonName contains hostname only; no version
|
|
services.append(info)
|
|
except Exception:
|
|
pass
|
|
|
|
# 3) FTP (banner on connect)
|
|
try:
|
|
with socket.create_connection((ip, port), timeout=timeout) as s:
|
|
s.settimeout(1.0)
|
|
banner = _safe_recv(s, 1024)
|
|
if banner:
|
|
if "FTP" in banner.upper() or banner.startswith("220"):
|
|
info["service"] = "ftp"
|
|
info["banner"] = (info["banner"] or "") + "\n" + banner.strip()
|
|
m = _srv_pattern.search(banner)
|
|
if m:
|
|
info["version"] = m.group("ver") or info["version"]
|
|
services.append(info)
|
|
except Exception:
|
|
pass
|
|
|
|
# 4) SMTP probe (HELO)
|
|
try:
|
|
with socket.create_connection((ip, port), timeout=timeout) as s:
|
|
s.settimeout(1.0)
|
|
banner = _safe_recv(s, 1024)
|
|
if banner and ("SMTP" in banner.upper() or banner.startswith("220")):
|
|
info["service"] = "smtp"
|
|
info["banner"] = (info["banner"] or "") + "\n" + banner.strip()
|
|
# send EHLO to potentially get server id
|
|
try:
|
|
s.sendall(b"EHLO example.com\r\n")
|
|
eh = _safe_recv(s, 2048)
|
|
if eh:
|
|
info["extra"]["smtp_ehlo"] = eh.strip()
|
|
m = _srv_pattern.search(eh)
|
|
if m:
|
|
info["version"] = m.group("ver") or info["version"]
|
|
except Exception:
|
|
pass
|
|
services.append(info)
|
|
except Exception:
|
|
pass
|
|
|
|
# 5) POP3 / IMAP banners
|
|
try:
|
|
with socket.create_connection((ip, port), timeout=timeout) as s:
|
|
s.settimeout(1.0)
|
|
banner = _safe_recv(s, 1024)
|
|
if banner and (banner.startswith("+OK") or "POP3" in banner.upper()):
|
|
info["service"] = "pop3"
|
|
info["banner"] = (info["banner"] or "") + "\n" + banner.strip()
|
|
services.append(info)
|
|
if banner and ("IMAP" in banner.upper() or banner.startswith("* OK")):
|
|
info["service"] = "imap"
|
|
info["banner"] = (info["banner"] or "") + "\n" + banner.strip()
|
|
services.append(info)
|
|
|
|
except Exception:
|
|
pass
|
|
|
|
# 6) Fallback: return whatever banner/hint we have
|
|
services.append(info)
|
|
|
|
|
|
|
|
def scan_services(ip, ports, timeout=3, max_workers=32):
|
|
"""
|
|
Run detect_service concurrently on a list of ports.
|
|
Returns a list of info dicts.
|
|
"""
|
|
results = []
|
|
with ThreadPoolExecutor(max_workers=max_workers) as executor:
|
|
futures = {executor.submit(detect_service, ip, p, timeout): p for p in ports}
|
|
for fut in as_completed(futures):
|
|
try:
|
|
res = fut.result()
|
|
results.append(res)
|
|
except Exception as e:
|
|
results.append({"port": futures[fut], "error": str(e)})
|
|
|
|
return sorted(results, key=lambda x: x.get("port", 0))
|
|
|
|
|
|
def scan_port(ip, port, timeout, open_ports, lock,tcp=True):
|
|
try:
|
|
if tcp:
|
|
|
|
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
|
sock.settimeout(timeout)
|
|
result = sock.connect_ex((ip, port))
|
|
print(f"Scanning port: {port}", end="\r")
|
|
if result == 0:
|
|
with lock:
|
|
open_ports.append(port)
|
|
if port in CRITICS_PORTS:
|
|
print(f"[+] {ip}:{Colors.RED}{port}{Colors.END}/TCP Open" if tcp else f"[+] {ip}:{Colors.RED}{port}{Colors.END}/UDP Open")
|
|
elif port in MID_PORTS:
|
|
print(f"[+] {ip}:{Colors.ORANGE}{port}{Colors.END}/TCP Open" if tcp else f"[+] {ip}:{Colors.ORANGE}{port}{Colors.END}/UDP Open")
|
|
else:
|
|
print(f"[+] {ip}:{port}{Colors.END}/TCP Open" if tcp else f"[+] {ip}:{port}{Colors.END}/UDP Open")
|
|
|
|
if tcp:
|
|
threading.Thread(target=detect_service,args=(ip,port)).start()
|
|
else:
|
|
try:
|
|
sock.sendto(b'', (ip, port))
|
|
sock.settimeout(timeout)
|
|
data, _ = sock.recvfrom(1024)
|
|
# If we get here, something answered! Definitely open.
|
|
is_open = True
|
|
except socket.timeout:
|
|
# This is the tricky part: is it filtered or just a quiet open port?
|
|
is_open = False
|
|
except ConnectionResetError:
|
|
# This usually means the port is CLOSED (received ICMP Unreachable)
|
|
is_open = False
|
|
if is_open:
|
|
with lock:
|
|
open_ports.append(port)
|
|
if port in CRITICS_PORTS:
|
|
print(f"[+] {ip}:{Colors.RED}{port}{Colors.END}/TCP Open" if tcp else f"[+] {ip}:{Colors.RED}{port}{Colors.END}/UDP Open")
|
|
elif port in MID_PORTS:
|
|
print(f"[+] {ip}:{Colors.ORANGE}{port}{Colors.END}/TCP Open" if tcp else f"[+] {ip}:{Colors.ORANGE}{port}{Colors.END}/UDP Open")
|
|
else:
|
|
print(f"[+] {ip}:{port}{Colors.END}/TCP Open" if tcp else f"[+] {ip}:{port}{Colors.END}/UDP Open")
|
|
|
|
except Exception:
|
|
pass
|
|
|
|
def ping_check(ip, count=3, timeout=2):
|
|
try:
|
|
result = subprocess.run(
|
|
["ping", "-c", str(count), "-W", str(timeout), ip],
|
|
capture_output=True, text=True, timeout=count * timeout + 5,
|
|
)
|
|
if result.returncode == 0:
|
|
match = re.search(r"(?:time|temps)[=:]?([\d.]+)\s*ms", result.stdout)
|
|
if match:
|
|
latency = float(match.group(1))
|
|
print(f"[+] {ip} is reachable (avg latency: {latency}ms)")
|
|
return latency
|
|
except Exception:
|
|
pass
|
|
print(f"[-] Ping check for {ip} failed or unreachable, using higher timeout")
|
|
return 2000.0
|
|
|
|
def tcp_scan(
|
|
ip, start_port=1, end_port=65535, timeout=0.5, max_threads=os.cpu_count() * 50
|
|
):
|
|
open_ports = []
|
|
lock = Lock()
|
|
|
|
latency = ping_check(ip)
|
|
if latency > 500:
|
|
effective_timeout = max(timeout, latency / 1000)
|
|
print(f"[!] High latency detected ({latency}ms), using timeout={effective_timeout}s")
|
|
else:
|
|
effective_timeout = timeout
|
|
|
|
print(f"\n[+] Starting multi-threaded TCP scan on {ip} (ports {start_port}-{end_port})\n")
|
|
|
|
with ThreadPoolExecutor(max_workers=max_threads) as executor:
|
|
futures = [
|
|
executor.submit(scan_port, ip, port, effective_timeout, open_ports, lock)
|
|
for port in range(start_port, end_port + 1)
|
|
]
|
|
|
|
for future in as_completed(futures):
|
|
future.result()
|
|
|
|
print(f"\n[!] Scan complete. Found {len(open_ports)} open ports.")
|
|
return sorted(open_ports)
|
|
def udp_scan(
|
|
ip, start_port=1, end_port=65535, timeout=0.4, max_threads=os.cpu_count() * 50
|
|
):
|
|
open_ports = []
|
|
lock = Lock()
|
|
|
|
latency = ping_check(ip)
|
|
if latency > 500:
|
|
effective_timeout = max(timeout, latency / 1000)
|
|
print(f"[!] High latency detected ({latency}ms), using timeout={effective_timeout}s")
|
|
else:
|
|
effective_timeout = timeout
|
|
|
|
print(f"\n[+] Starting multi-threaded UDP scan on {ip} (ports {start_port}-{end_port})\n")
|
|
|
|
with ThreadPoolExecutor(max_workers=max_threads) as executor:
|
|
futures = [
|
|
executor.submit(scan_port, ip, port, effective_timeout, open_ports, lock, False)
|
|
for port in range(start_port, end_port + 1)
|
|
]
|
|
|
|
for future in as_completed(futures):
|
|
future.result()
|
|
|
|
print(f"\n[!] Scan complete. Found {len(open_ports)} open ports.")
|
|
return sorted(open_ports)
|
|
|
|
|
|
def _gobuster_probe(args):
|
|
"""
|
|
Worker for multiprocessing pool.
|
|
Args: (target,port, directory, ssl)
|
|
Returns: tuple (url, matches, short_content) or None
|
|
"""
|
|
target,port, directory, ssl = args
|
|
directory = directory.strip()
|
|
if not directory:
|
|
return None
|
|
scheme = "https" if ssl else "http"
|
|
if (ssl and port == 443) or (not ssl and port == 80):
|
|
url = f"{scheme}://{target}/{directory}"
|
|
else:
|
|
url = f"{scheme}://{target}:{port}/{directory}"
|
|
try:
|
|
# Each process creates its own short-lived request
|
|
r = requests.get(url, timeout=5)
|
|
if r.status_code == 200:
|
|
matches = []
|
|
# search for keywords in the response text
|
|
blacklist = ["california", "<div", "<a"]
|
|
for keyword in KEYWORDS:
|
|
for line in r.text.splitlines():
|
|
if keyword in line:
|
|
start = 0
|
|
while True:
|
|
pos = line.find(keyword, start)
|
|
if pos == -1:
|
|
break
|
|
ctx_start = max(0, pos - 32)
|
|
ctx_end = min(len(line), pos + len(keyword) + 32)
|
|
snippet = line[ctx_start:ctx_end].strip()
|
|
if not any(b in snippet for b in blacklist) and snippet not in matches:
|
|
matches.append(snippet)
|
|
start = pos + 1
|
|
# return short content when small to avoid huge memory transfer
|
|
short_content = r.text if len(r.text) < 1000 else None
|
|
return (url, matches, short_content)
|
|
except Exception:
|
|
return None
|
|
return None
|
|
|
|
|
|
def gobuster(
|
|
target,
|
|
port=None,
|
|
ssl=False,
|
|
rapport=None,
|
|
wordlist_path=WORDLIST,
|
|
processes=None,
|
|
):
|
|
"""
|
|
Gobuster-like directory probe using multiprocessing.
|
|
- target: host or domain (string)
|
|
- ssl: if True, use https
|
|
- rapport: list to append human-readable findings (optional)
|
|
- wordlist_path: path to wordlist file
|
|
- processes: number of worker processes (defaults to cpu_count())
|
|
"""
|
|
if port is None:
|
|
port = 443 if ssl else 80
|
|
print("[*] Starting Gobuster scan (multiprocessing)...")
|
|
safe_target = re.sub(r"[^a-zA-Z0-9_.-]", "_", target)
|
|
output_file = f"gobuster_{safe_target}.txt"
|
|
|
|
try:
|
|
with open(wordlist_path, "r", encoding="utf-8", errors="ignore") as fh:
|
|
dirs = [line.strip() for line in fh if line.strip()]
|
|
except FileNotFoundError:
|
|
print(f"Wordlist not found at {wordlist_path}")
|
|
return
|
|
|
|
# decide worker count
|
|
cpu = os.cpu_count() or 1
|
|
worker_count = processes if (processes and processes > 0) else max(2, cpu)
|
|
|
|
# build args for pool
|
|
tasks = [(target,port, d, ssl) for d in dirs]
|
|
|
|
results = []
|
|
try:
|
|
with multiprocessing.Pool(processes=worker_count) as pool:
|
|
# map_unordered keeps throughput high
|
|
for res in pool.imap_unordered(_gobuster_probe, tasks, chunksize=16):
|
|
if res:
|
|
results.append(res)
|
|
url, matches, short_content = res
|
|
# write URL to output file incrementally
|
|
with open(output_file, "a", encoding="utf-8") as out:
|
|
out.write(url + "\n")
|
|
# print and add to rapport
|
|
print(f"[FOUND] {url}")
|
|
if rapport is not None:
|
|
rapport.append(url)
|
|
if matches:
|
|
for m in matches:
|
|
msg = f"{url} contains: {m}"
|
|
print(msg)
|
|
if rapport is not None:
|
|
rapport.append(msg)
|
|
if short_content:
|
|
# small content included in rapport for convenience
|
|
if rapport is not None:
|
|
rapport.append(f"\n{url} content:\n{short_content}")
|
|
except KeyboardInterrupt:
|
|
print("\n[*] Interrupted by user, terminating worker pool...")
|
|
pool.terminate()
|
|
pool.join()
|
|
except Exception as e:
|
|
print(f"[*] Unexpected error during gobuster multiprocessing: {e}")
|
|
|
|
print("[*] Gobuster scan finished!")
|
|
return results # optional: return list of (url, matches, short_content)
|
|
|
|
|
|
def fetch_robots_txt(ip):
|
|
url = f"http://{ip}/robots.txt"
|
|
try:
|
|
result = subprocess.run(["curl", url], capture_output=True)
|
|
content = result.stdout or result.stderr
|
|
if not "Failed to connect" in content and not "404 Not Found" in content and not "The document has moved" in content and not "Hôte injoignable" in content and not "301 Moved" in content:
|
|
print(f"\nContents of {url}:\n{content}")
|
|
return content
|
|
else:
|
|
print(f"Failed to fetch {url}")
|
|
except Exception as e:
|
|
print(f"An error occurred while fetching robots.txt: {e}")
|
|
return None
|
|
|
|
|
|
def analyze_entries(target, entries, rapport):
|
|
for entry in entries:
|
|
entry = entry.strip()
|
|
if not entry:
|
|
continue
|
|
for keyword in KEYWORDS:
|
|
if keyword in entry:
|
|
try:
|
|
url = f"http://{target}/{entry}"
|
|
r = requests.get(url, timeout=5)
|
|
if r.status_code == 200:
|
|
content = r.text
|
|
rapport.append(f"\n{url}\ncontent:\n{content}")
|
|
if len(content) < 100:
|
|
print(f"{url}\ncontent:\n{content}")
|
|
except Exception as e:
|
|
print(f"Error fetching {entry}: {e}")
|
|
|
|
|
|
def analyze_directories(target, output_file, use_https, rapport):
|
|
if not os.path.exists(output_file):
|
|
return
|
|
with open(output_file, "r") as f:
|
|
dirs = [line.strip() for line in f if line.strip()]
|
|
rapport.append("\n\nDIRECTORY CONTENT\n")
|
|
for directory in dirs:
|
|
url = (
|
|
f"https://{target}/{directory}"
|
|
if use_https
|
|
else f"http://{target}/{directory}"
|
|
)
|
|
try:
|
|
r = requests.get(url, timeout=5)
|
|
if r.status_code == 200:
|
|
content = r.text
|
|
rapport.append(f"\n{url}\ncontent:\n{content}")
|
|
if len(content) < 100:
|
|
print(f"{url}\ncontent:\n{content}")
|
|
except Exception as e:
|
|
print(f"Error fetching {url}: {e}")
|
|
os.remove(output_file)
|
|
|
|
def subdnsfind(target):
|
|
global rapport
|
|
dnsoutput=f"domains_{target}.txt"
|
|
check = subprocess.run(f"subfinder -d {target} -o {dnsoutput}",shell=True,capture_output=False,check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
|
if check and os.path.isfile(dnsoutput):
|
|
print(f"SUBDNS find run correctly and saved to {dnsoutput}")
|
|
if shutil.which("nuclei") is not None:
|
|
ncoutput=f"nuclei_{target}.txt"
|
|
check = subprocess.run(f"nuclei -o {ncoutput}",shell=True,capture_output=False,check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
|
if check and os.path.isfile(ncoutput):
|
|
print(f"Nuclei Scan run correctly and saved to {ncoutput}")
|
|
subdomains=list(set(open(dnsoutput,'r').readlines()))
|
|
print(f"\n[+] found {Colors.ORANGE}{len(subdomains)}{Colors.END} !")
|
|
for subdomain in subdomains:
|
|
subdomain=subdomain.strip()
|
|
print(f"-> {Colors.ORANGE}{subdomain}{Colors.END}")
|
|
for subdomain in subdomains:
|
|
subdomain=subdomain.strip()
|
|
|
|
open_ports_tcp = tcp_scan(subdomain)
|
|
threads.append([threading.Thread(target=nmap_full_scan,args=(subdomain,open_ports_tcp,True)),f" {subdomain} NMAP FULL SCAN "])
|
|
threads[-1][0].start()
|
|
rapport.append(f"\n {subdomain} TCP OPEN PORTS:")
|
|
rapport += [f"{port}/TCP" for port in open_ports_tcp]
|
|
print("\n\n")
|
|
open_ports = udp_scan(subdomain)
|
|
rapport.append(f"\n {subdomain} UDP OPEN PORTS:")
|
|
rapport += [f"{port}/UDP" for port in open_ports]
|
|
|
|
for service in services:
|
|
if service['port'] in CRITICS_PORTS or service['service'] in CRITICS_SERVICES:
|
|
print(f"port: {Colors.RED}{service['port']}{Colors.END} | service: {Colors.RED}{service['service']}{Colors.END} | version: {service['version']}\n")
|
|
elif service['port'] in MID_PORTS or service['service'] in MID_SERVICES:
|
|
print(f"port: {Colors.ORANGE}{service['port']}{Colors.END} | service: {Colors.ORANGE}{service['service']}{Colors.END} | version: {service['version']}\n")
|
|
else:
|
|
print(f"port: {service['port']} | service: {service['service']} | version: {service['version']}\n")
|
|
if not service['service'] == None:
|
|
if "http" in service['service']:
|
|
gobuster(target,service['port'],ssl=False,rapport=rapport)
|
|
if "https" in service['service']:
|
|
gobuster(target,service['port'],ssl=True,rapport=rapport)
|
|
|
|
safe_target = re.sub(r"[^a-zA-Z0-9_.-]", "_", subdomain)
|
|
output_file = f"gobuster_{safe_target}.txt"
|
|
|
|
if 443 in open_ports_tcp or 80 in open_ports_tcp:
|
|
|
|
use_https = 443 in open_ports_tcp
|
|
|
|
robots_content = fetch_robots_txt(target)
|
|
if robots_content:
|
|
rapport.append(f"\n {subdomain} ROBOTS.txt content:\n{robots_content}")
|
|
analyze_entries(target, robots_content.splitlines(), rapport)
|
|
|
|
gobuster(target, ssl=use_https, rapport=rapport)
|
|
rapport.append("\n\nGOBUSTER DIRECTORY SCAN")
|
|
if os.path.exists(output_file):
|
|
with open(output_file, "r") as f:
|
|
rapport += [line.strip() for line in f if line.strip()]
|
|
analyze_directories(target, output_file, use_https, rapport)
|
|
|
|
|
|
use_https = 443 in open_ports_tcp
|
|
|
|
robots_content = fetch_robots_txt(target)
|
|
if robots_content:
|
|
rapport.append(f"\n {subdomain} ROBOTS.txt content:\n{robots_content}")
|
|
analyze_entries(target, robots_content.splitlines(), rapport)
|
|
|
|
rapport.append(f"\n\n {subdomain} GOBUSTER DIRECTORY SCAN")
|
|
if os.path.exists(output_file):
|
|
with open(output_file, "r") as f:
|
|
rapport += [line.strip() for line in f if line.strip()]
|
|
analyze_directories(target, output_file, use_https, rapport)
|
|
|
|
def nmap_full_scan(target,open_ports,subdomain=False):
|
|
if shutil.which("nmap") is not None:
|
|
output=f"scan_{target}.txt"
|
|
ports = ",".join(str(p) for p in open_ports)
|
|
if subdomain:
|
|
print(f"running : nmap -A -T5 -oN {output} -p {ports} {target}")
|
|
check = subprocess.run(f"nmap -A -T5 -oN {output} -p {ports} {target}",shell=True,capture_output=False,check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
|
else:
|
|
print(f"running : nmap -A -T5 -oN {output} -p {ports} --script http-title --script-args http.max-redirects=3 {target}")
|
|
check = subprocess.run(f"nmap -A -T5 -oN {output} -p {ports} --script http-title --script-args http.max-redirects=3 {target}",shell=True,capture_output=False,check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
|
|
|
if check and os.path.isfile(output):
|
|
print(f"nmap scan run correctly and saved to {output}")
|
|
else:
|
|
print("Install Nmap for a more detailed scan !")
|
|
|
|
def main():
|
|
global services,threads,rapport
|
|
rapport = []
|
|
|
|
print(rf"""{Colors.RED}
|
|
'||'''|, ,'''|, .|'''', .''', '||\ ||`
|
|
|| || || || | | ||\\ ||
|
|
||...|' '''|| || | | || \\ ||
|
|
|| \\ || || | | || \\||
|
|
.|| \\. '...|' `|....' `,,,' .|| \||.
|
|
{Colors.END}
|
|
{Colors.YELLOW}[+] Created by NOTRUNIT{Colors.END}
|
|
""")
|
|
|
|
|
|
data = str(urlopen('http://checkip.dyndns.com/').read())
|
|
ip = re.compile(r'Address: (\d+\.\d+\.\d+\.\d+)').search(data).group(1)
|
|
|
|
print("Your Public IP Address is:", ip)
|
|
print("Tips : " + random.choice(TIPS))
|
|
if len(sys.argv) > 1:
|
|
target = sys.argv[1]
|
|
else:
|
|
target = input("Enter the target IP or domain name > ").strip()
|
|
|
|
try:
|
|
ip = socket.gethostbyname(target)
|
|
result = re.compile(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b').match(target)
|
|
if not result:
|
|
isdomain=True
|
|
print("\nDomain mode detected ")
|
|
|
|
else:
|
|
isdomain=False
|
|
print("\nIp address mode detected ")
|
|
except socket.error:
|
|
print("Unable to resolve target.")
|
|
sys.exit(1)
|
|
if not os.path.isdir(target):
|
|
os.makedirs(target)
|
|
os.chdir(target)
|
|
print(f"IP: {ip}")
|
|
rapport.append(f"Scanning {ip}")
|
|
open_ports_tcp = tcp_scan(target)
|
|
if len(open_ports_tcp) > 0:
|
|
threads.append([threading.Thread(target=nmap_full_scan,args=(target,open_ports_tcp)),"NMAP FULL SCAN"])
|
|
threads[-1][0].start()
|
|
|
|
rapport.append("\nTCP OPEN PORTS:")
|
|
rapport += [f"{port}/TCP" for port in open_ports_tcp]
|
|
print("\n\n")
|
|
open_ports = udp_scan(target)
|
|
rapport.append("\nUDP OPEN PORTS:")
|
|
rapport += [f"{port}/UDP" for port in open_ports]
|
|
|
|
for service in services:
|
|
if service['port'] in CRITICS_PORTS or service['service'] in CRITICS_SERVICES:
|
|
print(f"port: {Colors.RED}{service['port']}{Colors.END} | service: {Colors.RED}{service['service']}{Colors.END} | version: {service['version']}\n")
|
|
elif service['port'] in MID_PORTS or service['service'] in MID_SERVICES:
|
|
print(f"port: {Colors.ORANGE}{service['port']}{Colors.END} | service: {Colors.ORANGE}{service['service']}{Colors.END} | version: {service['version']}\n")
|
|
else:
|
|
print(f"port: {service['port']} | service: {service['service']} | version: {service['version']}\n")
|
|
if not service["service"] == None:
|
|
if "http" in service['service']:
|
|
gobuster(target,service['port'],ssl=False,rapport=rapport)
|
|
if "https" in service['service']:
|
|
gobuster(target,service['port'],ssl=True,rapport=rapport)
|
|
|
|
|
|
safe_target = re.sub(r"[^a-zA-Z0-9_.-]", "_", target)
|
|
output_file = f"gobuster_{safe_target}.txt"
|
|
|
|
if 443 in open_ports_tcp or 80 in open_ports_tcp:
|
|
|
|
if isdomain and shutil.which("subfinder") is not None:
|
|
print("\nrunning subdomain scan in a different thread because time waste isn't an option\n")
|
|
threads.append([threading.Thread(target=subdnsfind,args=(target,)),"SUBDNS SCAN"])
|
|
threads[-1][0].start()
|
|
|
|
|
|
|
|
with open(f"R3C0N_{safe_target}.txt", "w") as f:
|
|
f.write("\n".join(rapport))
|
|
print("\nwaiting for all the threads to finish !")
|
|
for thread in threads:
|
|
print(f"waiting for {Colors.YELLOW}{thread[1]}{Colors.END} ",end="\r")
|
|
thread[0].join()
|
|
os.chdir("../")
|
|
|
|
if __name__ == "__main__":
|
|
main()
|
|
|
|
|