Spaces:
Sleeping

phishing / script.py
delenter's picture
Update script.py
20d368d verified
Raw History Blame Contribute Delete
22.6 kB
import re
import sys
import requests
import socket
import whois
import json
from urllib.parse import urlparse
from datetime import datetime
from email import policy
from email.parser import BytesParser
from bs4 import BeautifulSoup
# === API KEYS ===
VT_API_KEY = "b1864873c7f95ad72571b43046dfa93f272e215f0b70fcd36cc24cff1b6615db"
ABUSE_API_KEY = "cac95a6835b86d31809d5a6e3b61a38a66dcfee67cb003723164f7588cc4a2102162d308a63b4ab9"
URLSCAN_API_KEY = "0197bb8c-bdc6-703f-967e-5d06e44d93ed"
GOOGLE_API_KEY = "AIzaSyD7SxO7MSifebAnKNgsTIaLhL7LBFTnNA"
# === Suspicious TLDs ===
suspicious_tlds = {
".zip", ".review", ".country", ".stream", ".download", ".xin", ".gq", ".ml", ".ga", ".cf",
".tk", ".top", ".work", ".party", ".click", ".link", ".men", ".loan", ".date", ".faith",
".science", ".online", ".xyz", ".buzz", ".rest", ".host", ".space", ".website", ".pw", ".bid"
}
# === Suspicious Words for Body Analysis ===
suspicious_words = [
"document", "verify", "account", "login", "urgent", "password", "security", "update",
"suspend", "click", "here", "reset", "confirm", "bank", "invoice", "payment", "alert"
]
# --- Formatting and Utility Functions ---
def format_verdict(verdict_raw):
"""Formats the raw verdict string with emojis."""
if verdict_raw == "PHISHING":
return "❗️PHISHING❗️"
elif verdict_raw == "SUSPICIOUS":
return "⚠️SUSPICIOUS⚠️"
else: # "LEGIT"
return "βœ… LEGIT βœ…"
def get_domain_from_url(url):
"""Extracts the domain (netloc) from a URL."""
try:
parsed = urlparse(url)
return parsed.netloc
except:
return ""
def get_ip_from_domain(domain):
"""Resolves a domain to an IP address."""
try:
return socket.gethostbyname(domain)
except:
return ""
def is_ip_address(input_string):
"""Checks if a string is a valid IPv4 or IPv6 address."""
try:
socket.inet_pton(socket.AF_INET, input_string)
return True
except socket.error:
try:
socket.inet_pton(socket.AF_INET6, input_string)
return True
except socket.error:
return False
def is_suspicious_tld(domain):
"""Checks if a domain uses a suspicious TLD."""
for tld in suspicious_tlds:
if domain.endswith(tld):
return True, tld
return False, None
# --- External API Check Functions ---
def check_virustotal_domain(domain):
"""Checks a domain against VirusTotal and returns malicious/suspicious count."""
headers = {"x-apikey": VT_API_KEY}
url = f"https://www.virustotal.com/api/v3/{'domains'}/{domain}"
try:
r = requests.get(url, headers=headers, timeout=10)
if r.status_code == 200:
data = r.json()
stats = data["data"]["attributes"]["last_analysis_stats"]
malicious = stats.get("malicious", 0)
suspicious = stats.get("suspicious", 0)
return malicious + suspicious
except requests.exceptions.RequestException:
pass
return 0
def check_virustotal_url(url):
"""Checks a URL against VirusTotal and returns malicious/suspicious count."""
headers = {"x-apikey": VT_API_KEY}
url_v3_api = f"https://www.virustotal.com/api/v3/urls/{url}"
try:
r = requests.get(url_v3_api, headers=headers, timeout=10)
if r.status_code == 200:
data = r.json()
stats = data["data"]["attributes"]["last_analysis_stats"]
malicious = stats.get("malicious", 0)
suspicious = stats.get("suspicious", 0)
return malicious + suspicious
except requests.exceptions.RequestException:
pass
return 0
def check_virustotal_ip(ip):
"""Checks an IP against VirusTotal and returns malicious/suspicious count."""
headers = {"x-apikey": VT_API_KEY}
url = f"https://www.virustotal.com/api/v3/ip_addresses/{ip}"
try:
r = requests.get(url, headers=headers, timeout=10)
if r.status_code == 200:
data = r.json()
stats = data["data"]["attributes"]["last_analysis_stats"]
malicious = stats.get("malicious", 0)
suspicious = stats.get("suspicious", 0)
return malicious + suspicious
except requests.exceptions.RequestException:
pass
return 0
def check_abuseipdb(ip):
"""Checks an IP address against AbuseIPDB and returns abuse confidence score."""
url = f"https://api.abuseipdb.com/api/v2/check?ipAddress={ip}"
headers = {"Key": ABUSE_API_KEY, "Accept": "application/json"}
try:
r = requests.get(url, headers=headers, timeout=10)
if r.status_code == 200:
data = r.json()
return data['data']['abuseConfidenceScore']
except requests.exceptions.RequestException:
pass
return 0
def check_dnsbl(ip):
"""Checks an IP address against common DNS blacklists."""
blacklists = ["zen.spamhaus.org", "bl.spamcop.net", "dnsbl.sorbs.net"]
for bl in blacklists:
try:
query = ".".join(reversed(ip.split("."))) + "." + bl
socket.gethostbyname(query)
return True
except socket.gaierror: # Host not found means not listed
continue
except Exception:
continue
return False
def check_whois_info(domain):
"""Performs WHOIS lookup for domain creation date and age."""
try:
info = whois.whois(domain)
creation_date = info.creation_date
if isinstance(creation_date, list):
creation_date = creation_date[0] # Take the first date if multiple
if creation_date and isinstance(creation_date, datetime):
days_old = (datetime.now() - creation_date).days
return days_old, creation_date.strftime("%Y-%m-%d")
except Exception:
pass
return None, None
def check_urlscan_search(domain):
"""Searches for existing scans of a domain on URLScan.io."""
headers = {"API-Key": URLSCAN_API_KEY, "Content-Type": "application/json"}
try:
r = requests.get(f"https://urlscan.io/api/v1/search/?q=domain:{domain}", headers=headers, timeout=10)
if r.status_code == 200:
data = r.json()
results_count = len(data.get("results", []))
return f"{results_count} entries" if results_count > 0 else "No entries"
except requests.exceptions.RequestException:
pass
return "Unavailable"
def check_google_safe_Browse(url_to_check):
"""Checks a URL against Google Safe Browse API."""
if not GOOGLE_API_KEY:
return "N/A - API Key missing"
endpoint = f"https://safeBrowse.googleapis.com/v4/threatMatches:find?key={GOOGLE_API_KEY}"
body = {
"client": {"clientId": "phishing-checker", "clientVersion": "1.0"},
"threatInfo": {
"threatTypes": ["MALWARE", "SOCIAL_ENGINEERING", "UNWANTED_SOFTWARE", "POTENTIALLY_UNWANTED_APPLICATION"],
"platformTypes": ["ANY_PLATFORM"],
"threatEntryTypes": ["WEB_URI"],
"threatEntries": [{"url": url_to_check}]
}
}
try:
response = requests.post(endpoint, json=body, timeout=10)
response.raise_for_status()
matches = response.json().get("matches", [])
return "Yes" if len(matches) > 0 else "No"
except requests.exceptions.RequestException as e:
return "Error"
except Exception as e:
return "Error"
# --- Unified Analysis Function for URL/Domain/IP ---
def analyze_input_string(input_string):
"""Analyzes a single URL, domain, or IP and prints its results."""
url = ""
domain = ""
ip = ""
is_raw_ip_analysis = False
if is_ip_address(input_string):
is_raw_ip_analysis = True
ip = input_string
print(f"\nπŸ” Analyzing IP: {input_string}")
print(f"🌐 IP Address: {ip}")
else:
parsed_url = urlparse(input_string)
if parsed_url.scheme and parsed_url.netloc:
url = input_string
domain = parsed_url.netloc
elif parsed_url.netloc:
url = f"http://{input_string}" # Add default scheme for checks
domain = parsed_url.netloc
elif "." in input_string:
domain = input_string
url = f"http://{input_string}" # Add default scheme for URL-specific checks
else:
print(f"\nπŸ” Analyzing: {input_string}")
print("🌐 Invalid URL or Domain format. Cannot proceed with full analysis.")
print("πŸ”Ž FINAL VERDICT: ⚠️ SUSPICIOUS - Invalid Input")
return "SUSPICIOUS"
print(f"\nπŸ” Analyzing: {input_string}")
print(f"🌐 Domain: {domain or 'N/A'}")
if domain:
ip = get_ip_from_domain(domain)
print(f"🌐 Resolved IP: {ip or 'Unavailable'}")
else:
print(f"🌐 Resolved IP: N/A (No domain)")
# Perform all checks
vt_score_domain = 0
vt_score_url = 0
vt_score_ip_check = 0
abuse_score = 0
listed_dnsbl = False
days_old = None
creation_str = "Unknown"
urlscan_result_text = "N/A"
google_flagged_status = "N/A"
tld_suspicious = False
matched_tld = None
if domain and not is_raw_ip_analysis:
vt_score_domain = check_virustotal_domain(domain)
days_old, creation_str = check_whois_info(domain)
urlscan_result_text = check_urlscan_search(domain)
tld_suspicious, matched_tld = is_suspicious_tld(domain)
if url and not is_raw_ip_analysis:
vt_score_url = check_virustotal_url(url)
google_flagged_status = check_google_safe_Browse(url)
if ip:
vt_score_ip_check = check_virustotal_ip(ip)
abuse_score = check_abuseipdb(ip)
listed_dnsbl = check_dnsbl(ip)
# --- Print Results in the desired format ---
if domain and not is_raw_ip_analysis:
print(f"🦠 VirusTotal detections (Domain): {vt_score_domain}" + (" ⚠️" if vt_score_domain > 0 else ""))
if url and not is_raw_ip_analysis:
print(f"🦠 VirusTotal detections (URL): {vt_score_url}" + (" ⚠️" if vt_score_url > 0 else ""))
if ip:
print(f"🦠 VirusTotal detections (IP): {vt_score_ip_check}" + (" ⚠️" if vt_score_ip_check > 0 else ""))
print(f"🚨 AbuseIPDB score: {abuse_score}" + (" ⚠️" if abuse_score >= 70 else ""))
print(f"🧱 DNSBL listed: {'Yes' if listed_dnsbl else 'No'}" + (" ⚠️" if listed_dnsbl else ""))
domain_age_status = ""
if days_old is not None:
TWO_YEARS_IN_DAYS = 2 * 365
if days_old < TWO_YEARS_IN_DAYS:
domain_age_status = f"{days_old} days (less than 2 years) ⚠️"
else:
domain_age_status = f"{days_old} days"
else:
domain_age_status = "Unknown ⚠️"
print(f"πŸ“… Domain creation date: {creation_str}")
print(f"πŸ“… Domain age: {domain_age_status}")
print(f"❗ Suspicious TLD: {'Yes (' + matched_tld + ') ⚠️' if tld_suspicious else 'No'}")
print(f"πŸ”Ž URLScan result: {urlscan_result_text}")
print(f"πŸ›‘ Google Safe Browse flagged: {google_flagged_status}" + (" ⚠️" if google_flagged_status == "Yes" else ""))
# --- Determine Verdict based on simplified logic ---
verdict_raw = "LEGIT"
if (vt_score_domain >= 1 or vt_score_url >= 1 or vt_score_ip_check >= 1 or
abuse_score >= 70 or listed_dnsbl or google_flagged_status == "Yes"):
verdict_raw = "PHISHING"
elif (days_old is not None and days_old < (2 * 365)) or tld_suspicious or \
(abuse_score > 0): # MODIFIED: AbuseIPDB score > 0 (i.e., >=1) makes it SUSPICIOUS
verdict_raw = "SUSPICIOUS"
print(f"\nπŸ”Ž FINAL VERDICT: {format_verdict(verdict_raw)}")
return verdict_raw
# --- Email Analysis Specific Functions ---
def extract_all_headers(msg):
"""Extracts all headers from an email message."""
return {k: v for k, v in msg.items()}
def extract_auth_results(headers):
"""Extracts authentication results (SPF, DKIM, DMARC, CAT) from email headers."""
auth = {"spf": None, "dkim": None, "dmarc": None, "cat": None}
for k, v in headers.items():
v = " ".join(v.splitlines())
if "authentication-results" in k.lower():
spf = re.search(r"spf\s*=\s*['\"]?(\w+)['\"]?", v, re.IGNORECASE)
dkim = re.search(r"dkim\s*=\s*['\"]?(\w+)['\"]?", v, re.IGNORECASE)
dmarc = re.search(r"dmarc\s*=\s*['\"]?(\w+)['\"]?", v, re.IGNORECASE)
if spf: auth["spf"] = spf.group(1).lower()
if dkim: auth["dkim"] = dkim.group(1).lower()
if dmarc: auth["dmarc"] = dmarc.group(1).lower()
if "received-spf" in k.lower():
spf = re.search(r"(pass|fail|softfail|neutral)", v, re.IGNORECASE)
if spf: auth["spf"] = spf.group(1).lower()
if "x-forefront-antispam-report" in k.lower():
cat = re.search(r"CAT\s*:\s*([A-Z]+)", v, re.IGNORECASE)
if cat: auth["cat"] = cat.group(1)
return auth
def analyze_header_domains(headers, final_phishing_indicators_list):
"""Analyzes 'From' and 'Reply-To' domains from headers using unified analysis."""
from_domain_raw = None
reply_domain_raw = None
if "From" in headers:
m = re.search(r"@([\w.-]+)", headers["From"])
if m:
from_domain_raw = m.group(1).strip(".")
if "Reply-To" in headers:
m = re.search(r"@([\w.-]+)", headers["Reply-To"])
if m:
reply_domain_raw = m.group(1).strip(".")
if from_domain_raw:
print("\n--- DOMAIN ANALYSIS (FROM HEADER 'FROM') ---")
verdict = analyze_input_string(from_domain_raw)
if "PHISHING" in verdict:
final_phishing_indicators_list.append(f"Header Domain (From): {from_domain_raw}")
if reply_domain_raw and reply_domain_raw != from_domain_raw:
print("\n--- DOMAIN ANALYSIS (FROM HEADER 'REPLY-TO') ---")
verdict = analyze_input_string(reply_domain_raw)
if "PHISHING" in verdict:
final_phishing_indicators_list.append(f"Header Domain (Reply-To): {reply_domain_raw}")
def extract_ips_from_headers(headers):
"""Extracts IP addresses from email headers."""
ips = set()
for key, value in headers.items():
matches = re.findall(r"(?:client-ip|x-originating-ip|received):\s*\[?(\d{1,3}(?:\.\d{1,3}){3})\\]?", value,
re.IGNORECASE)
ips.update(matches)
generic_matches = re.findall(r"\b(?:\d{1,3}\.){3}\d{1,3}\b", value)
ips.update(generic_matches)
return list(ips)
def clean_body_text(text):
"""Cleans up body text by removing excessive spaces and empty lines."""
text = re.sub(r'[ \t]+', ' ', text)
text = re.sub(r'\n\s*\n', '\n\n', text)
lines = [line.strip() for line in text.splitlines()]
cleaned_lines = []
for line in lines:
if line or (cleaned_lines and cleaned_lines[-1] != ''):
cleaned_lines.append(line)
return '\n'.join(cleaned_lines).strip()
def extract_body_and_urls(msg):
"""Extracts body text, HTML content, and URLs from an email message."""
body_text, html, urls = "", "", set()
if msg.is_multipart():
for part in msg.walk():
ctype = part.get_content_type()
payload = part.get_payload(decode=True)
if payload:
try:
content = payload.decode(errors="ignore")
if ctype == "text/html":
html = content
elif ctype == "text/plain":
body_text = content
except UnicodeDecodeError:
pass
else:
payload = msg.get_payload(decode=True)
if payload:
try:
content = payload.decode(errors="ignore")
if msg.get_content_type() == "text/html":
html = content
else:
body_text = content
except UnicodeDecodeError:
pass
if html:
soup = BeautifulSoup(html, "html.parser")
urls.update([a.get("href") for a in soup.find_all("a", href=True) if a.get("href")])
if not body_text:
body_text = soup.get_text(separator="\n").strip()
body_text = clean_body_text(body_text)
urls.update(re.findall(r"https?://[^\s\"'<>]+", body_text))
urls.update(re.findall(r"mailto:[^\s\"'<>]+", body_text))
return body_text[:2000], html[:2000], list(urls)
def analyze_body_content(body):
"""Analyzes the email body for suspicious words."""
print("\n--- BODY CONTENT ANALYSIS ---")
red_flags = []
verdict_raw = "LEGIT"
found_words = [w for w in suspicious_words if re.search(rf"\b{w}\b", body, re.IGNORECASE)]
if found_words:
red_flags.append(f"⚠️ WARNING: Suspicious words detected: {', '.join(found_words)}")
verdict_raw = "SUSPICIOUS"
for flag in red_flags:
print(f" - {flag}")
print(f" Verdict: {format_verdict(verdict_raw)}")
return verdict_raw
def run_email_analysis(file_path):
try:
with open(file_path, "rb") as f:
msg = BytesParser(policy=policy.default).parse(f)
except FileNotFoundError:
print(f"Error: File not found at {file_path}")
return
except Exception as e:
print(f"Error parsing email file: {e}")
return
final_phishing_indicators = []
print("\n" + "=" * 70)
print(" EMAIL PHISHING ANALYSIS REPORT")
print("=" * 70)
# --- Header Analysis ---
print("\nπŸ‘€========== EMAIL HEADER ANALYSIS ==========πŸ‘€")
headers = extract_all_headers(msg)
for k, v in headers.items():
print(f" {k}: {v}")
print("\n--- AUTHENTICATION RESULTS ---")
auth_results = extract_auth_results(headers)
for k, v in auth_results.items():
status_icon = ""
status_text = v if v else "N/A"
if k in ["spf", "dkim", "dmarc"]:
if v == "pass":
status_icon = "βœ”οΈ"
elif v in ["fail", "softfail"]:
status_icon = "⚠️"
final_phishing_indicators.append(f"Header: {k.upper()} failure")
else:
status_icon = "❓"
elif k == "cat":
if v and v.lower() == "clean":
status_icon = "βœ”οΈ"
elif v:
status_icon = "⚠️"
final_phishing_indicators.append(f"Header: Spam category {v}")
else:
status_icon = "❓"
print(f" {status_icon} {k.upper()}: {status_text}")
print("\n--- DOMAIN REPUTATION FROM HEADERS ---")
analyze_header_domains(headers, final_phishing_indicators)
print("\n--- IP ADDRESS ANALYSIS FROM HEADERS ---")
ips_from_headers = extract_ips_from_headers(headers)
if not ips_from_headers:
print(" No IP addresses found in headers.")
for ip in ips_from_headers:
ip_verdict = analyze_input_string(ip)
if "PHISHING" in ip_verdict:
final_phishing_indicators.append(f"IP: {ip}")
print("=" * 70)
# --- Body Content Analysis ---
print("\nπŸ‘€========== BODY CONTENT ANALYSIS ==========πŸ‘€")
body_text, html_content, urls_found = extract_body_and_urls(msg)
print("\n--- BODY TEXT PREVIEW (FIRST 1000 CHARACTERS): ---")
if body_text:
print(body_text[:1000] + ("..." if len(body_text) > 1000 else ""))
else:
print(" No plain text body found.")
body_verdict = analyze_body_content(body_text)
if "SUSPICIOUS" in body_verdict or "PHISHING" in body_verdict:
final_phishing_indicators.append("Body: Suspicious content")
print("=" * 70)
# --- URL Analysis ---
print("\nπŸ‘€========== URL CLASSIFICATION ==========πŸ‘€")
if not urls_found:
print(" No URLs found in the email body.")
for url in urls_found:
url_verdict = analyze_input_string(url)
if "PHISHING" in url_verdict:
final_phishing_indicators.append(f"URL: {url}")
print("=" * 70)
# --- Final Email Classification ---
print("\n" + "=" * 70)
print(" FINAL EMAIL CLASSIFICATION")
print("=" * 70)
if final_phishing_indicators:
print("πŸ›‘ FINAL VERDICT: ❗️❗️PHISHING❗️❗️ DETECTED! TAKE CAUTION! πŸ›‘")
print("\nReasons for Phishing Detection:")
for indicator in sorted(list(set(final_phishing_indicators))):
print(f"- {indicator}")
print(
"\nACTION REQUIRED: Exercise extreme caution. Do not click on any links, open attachments, or reply to this email.")
else:
print("βœ… FINAL VERDICT: βœ… LEGIT βœ… No strong phishing indicators detected.")
print("\nWhile no definitive phishing signs were found, always remain vigilant with unsolicited emails.")
print("=" * 70 + "\n")
def run_interactive_analysis():
print("\n" + "=" * 70)
print(" INTERACTIVE URL/DOMAIN/IP ANALYSIS")
print("=" * 70)
print("Enter URLs, Domains, or IP Addresses (comma-separated). Type 'exit' to quit.")
while True:
user_input = input("\nEnter item(s) to analyze: ").strip()
if user_input.lower() == 'exit':
break
if not user_input:
continue
inputs_to_analyze = [item.strip() for item in user_input.split(',')]
for item in inputs_to_analyze:
if item:
analyze_input_string(item)
print("\n" + "=" * 70)
# --- Main execution block ---
if __name__ == "__main__":
# Present user with choices
print("\n" + "=" * 70)
print(" PHISHING ANALYSIS TOOL MENU")
print("=" * 70)
print("1. Analyze an Email (.eml file)")
print("2. Interactive URL/Domain/IP Analysis")
print("=" * 70)
choice = input("Enter your choice (1 or 2): ").strip()
if choice == '1':
file_path = None
# Check if a file path was provided as a command-line argument
if len(sys.argv) > 1:
file_path = sys.argv[1]
else:
# If not, prompt the user for it interactively
file_path = input("Enter the path to the .eml file: ").strip()
if file_path:
run_email_analysis(file_path)
else:
print("No file path provided. Exiting.")
sys.exit(1)
elif choice == '2':
run_interactive_analysis()
else:
print("Invalid choice. Exiting.")
sys.exit(1)