Spaces:
Sleeping

File size: 22,643 Bytes
8ce89a2
20d368d
8ce89a2
 
 
20d368d
8ce89a2
 
 
 
 
 
 
 
 
 
20d368d
8ce89a2
20d368d
8ce89a2
 
 
 
 
 
20d368d
8ce89a2
 
 
 
 
20d368d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ce89a2
 
20d368d
8ce89a2
20d368d
 
8ce89a2
20d368d
 
8ce89a2
 
 
 
 
20d368d
 
 
 
 
 
 
 
 
 
 
 
 
 
8ce89a2
20d368d
8ce89a2
 
 
 
 
20d368d
 
 
 
 
8ce89a2
20d368d
8ce89a2
 
 
 
 
 
 
20d368d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ce89a2
20d368d
 
8ce89a2
 
20d368d
8ce89a2
 
 
 
 
20d368d
 
 
8ce89a2
20d368d
 
8ce89a2
 
20d368d
8ce89a2
 
 
 
 
 
20d368d
 
 
8ce89a2
 
 
20d368d
 
 
8ce89a2
 
 
 
20d368d
 
8ce89a2
 
20d368d
8ce89a2
 
 
20d368d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ce89a2
 
 
20d368d
8ce89a2
20d368d
 
8ce89a2
 
 
20d368d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ce89a2
 
 
20d368d
8ce89a2
 
 
 
 
 
20d368d
 
 
 
 
 
 
 
8ce89a2
 
 
20d368d
 
 
 
 
 
 
 
8ce89a2
 
 
20d368d
8ce89a2
 
 
20d368d
 
 
 
 
8ce89a2
 
1acddcf
20d368d
 
 
8ce89a2
20d368d
8ce89a2
 
20d368d
 
 
 
 
 
 
 
1acddcf
20d368d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ce89a2
 
20d368d
 
 
 
 
8ce89a2
20d368d
 
 
 
8ce89a2
20d368d
 
8ce89a2
20d368d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ce89a2
20d368d
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
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)