Spaces:
Sleeping

File size: 34,004 Bytes
4123eec
3065513
4123eec
 
 
 
 
 
3065513
 
4123eec
 
 
8da3dbe
3065513
 
 
4123eec
3065513
 
 
 
4123eec
 
 
3065513
8da3dbe
4123eec
 
 
 
 
 
35a6406
4123eec
 
 
 
 
 
3065513
 
 
 
 
 
 
 
 
 
 
 
 
 
d0bec05
 
3065513
 
 
 
 
 
 
 
 
 
 
 
 
4123eec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07a9842
4123eec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3065513
4123eec
 
 
 
 
 
 
 
 
 
 
 
3065513
 
 
 
 
 
4123eec
3065513
4123eec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3065513
 
 
 
4123eec
 
 
 
 
3065513
4123eec
3065513
4123eec
35a6406
4123eec
 
3065513
4123eec
 
 
 
3065513
4123eec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bafc131
4123eec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3065513
4123eec
 
 
 
 
 
 
 
 
 
3065513
 
 
 
 
4123eec
 
 
 
 
 
3065513
4123eec
 
 
 
 
 
 
 
 
 
3065513
4123eec
3065513
 
4123eec
 
 
 
 
 
3065513
4123eec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3065513
4123eec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bafc131
4123eec
 
 
 
3065513
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4123eec
3065513
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bafc131
3065513
 
bafc131
3065513
4123eec
3065513
 
4123eec
 
 
 
 
 
 
3065513
 
4123eec
 
 
 
3065513
 
 
 
 
4123eec
 
 
3065513
4123eec
 
 
 
 
 
 
3065513
4123eec
3065513
 
 
 
 
4123eec
3065513
 
 
4123eec
3065513
4123eec
 
 
3065513
 
35a6406
4123eec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3065513
4123eec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3065513
4123eec
3065513
 
 
 
 
4123eec
 
 
3065513
4123eec
3065513
 
 
 
 
 
4123eec
 
 
 
 
3065513
 
4123eec
3065513
 
 
 
4123eec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3065513
 
4123eec
 
 
 
3065513
4123eec
 
 
3065513
 
 
4123eec
 
 
 
3065513
4123eec
 
 
3065513
 
4123eec
3065513
 
4123eec
 
 
3065513
 
4123eec
3065513
4123eec
3065513
4123eec
 
 
 
 
 
 
 
 
 
 
3065513
300eac0
bafc131
4123eec
 
 
 
 
 
 
 
 
 
 
 
 
3065513
4123eec
 
3065513
4123eec
 
 
 
 
3065513
4123eec
 
 
 
 
3065513
4123eec
 
 
 
 
3065513
 
4123eec
3065513
 
 
 
 
4123eec
 
 
 
 
 
 
 
 
8da3dbe
4123eec
 
3065513
4123eec
3065513
 
 
4123eec
 
3065513
 
4123eec
 
3065513
 
 
 
 
 
4123eec
3065513
 
 
 
 
4123eec
 
 
 
 
 
 
3065513
 
 
 
 
 
 
 
4123eec
3065513
4123eec
3065513
 
 
4123eec
3065513
 
 
 
 
 
 
 
 
 
4123eec
 
3065513
 
 
 
 
 
 
 
 
 
 
 
4123eec
 
 
 
 
 
 
 
 
bafc131
 
4123eec
 
 
 
35a6406
4123eec
35a6406
4123eec
 
 
d0bec05
 
 
4123eec
 
35a6406
d0bec05
 
 
 
 
 
3065513
d0bec05
35a6406
4123eec
 
 
 
 
35a6406
d0bec05
4123eec
d0bec05
 
4123eec
d0bec05
 
8da3dbe
4123eec
 
 
 
 
d1c0215
d0bec05
 
 
3065513
d0bec05
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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
import re
import sys
import requests
import socket
import whois
import json
from urllib.parse import urlparse
from datetime import datetime

# Import for email parsing and BeautifulSoup for HTML parsing
from email import policy
from email.parser import BytesParser
from bs4 import BeautifulSoup

# Gradio import
import gradio as gr

# === API KEYS ===
# IMPORTANT: For a production environment or public Hugging Face Space,
# it's HIGHLY recommended to use Space Secrets or environment variables
# instead of hardcoding API keys here.
# Example: VT_API_KEY = os.environ.get("VT_API_KEY")
VT_API_KEY = "b1864873c7f95ad72571b43046dfa93f272e215f0b70fcd36cc24cff1b6615db"
ABUSE_API_KEY = "cac95a6835b86d31809d5a6e3b61a38a66dcfee67cb003723164f7588cc4a2102162d308a63b4ab9"
URLSCAN_API_KEY = "0197bb8c-bdc6-703f-967e-5d06e44d93ed"
GOOGLE_API_KEY = "AIzaSyD7SxO7MSifebAnKNgsTIaLhL7LBFTzNA" # Double-check this key and API enablement

# === 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"
]

# === Configuration for Scoring ===
# Points assigned for each suspicious indicator. Higher points mean more suspicious.
# Negative points can be assigned for strong positive indicators (e.g., very old domain),
# but are not implemented in this version for simplicity.
SCORE_CONFIG = {
    "POINTS_VT_DETECTED": 10,       # Any VirusTotal detection (domain, URL, or IP)
    "POINTS_ABUSEIPDB_HIGH": 15,    # AbuseIPDB score >= 70
    "POINTS_ABUSEIPDB_MEDIUM": 5,   # AbuseIPDB score >= 30 (but <70)
    "POINTS_DNSBL_LISTED": 8,       # Base points for being on any DNSBL
    "POINTS_DNSBL_MULTIPLE": 5,     # Additional points per extra DNSBL list (if >1)
    "POINTS_YOUNG_DOMAIN": 5,       # Domain less than 2 years old (730 days)
    "POINTS_VERY_YOUNG_DOMAIN": 10, # Domain less than 90 days old
    "POINTS_UNKNOWN_DOMAIN_AGE": 3, # WHOIS info unavailable/failed
    "POINTS_SUSPICIOUS_TLD": 7,
    "POINTS_GOOGLE_SAFE_BROWSE_FLAGGED": 25, # Strong indicator
    "POINTS_GOOGLE_SAFE_BROWSE_ERROR": 0, # API errors shouldn't cause FPs, score is 0
    "POINTS_SUSPICIOUS_BODY_CONTENT": 7, # For email body keywords
    "POINTS_HEADER_AUTH_FAIL": 12,  # SPF/DKIM/DMARC fail
    "POINTS_SPAM_CATEGORY": 4,      # Lower points for general spam classification
    "POINTS_IP_IN_HEADERS_BAD": 10, # If an IP from headers is malicious
}

# Thresholds for final verdict based on total score
VERDICT_THRESHOLDS = {
    "PHISHING": 25,  # Score >= 25 is Phishing
    "SUSPICIOUS": 10 # Score >= 10 is Suspicious
    # Below 10 is LEGIT
}

# --- 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_to_check):
    """Checks a URL against VirusTotal and returns malicious/suspicious count.
       Note: VirusTotal API v3 /urls endpoint often expects base64 URL-safe encoded URLs for direct lookup.
       This implementation sends it directly which might return 0 if not previously analyzed or if API
       expects encoded form for specific lookup. For a submission, it's different.
    """
    headers = {"x-apikey": VT_API_KEY}
    url_v3_api = f"https://www.virustotal.com/api/v3/urls/{url_to_check}" # Direct string lookup (might be unreliable)
    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']
        elif r.status_code == 429: # Rate limit exceeded
            pass
        elif r.status_code == 403: # Forbidden (e.g., API key issue)
            pass
    except requests.exceptions.RequestException:
        pass
    return 0

def check_dnsbl(ip):
    """Checks an IP address against common DNS blacklists and returns count of lists it's on."""
    blacklists = ["zen.spamhaus.org", "bl.spamcop.net", "dnsbl.sorbs.net"]
    listed_count = 0
    for bl in blacklists:
        try:
            query = ".".join(reversed(ip.split("."))) + "." + bl
            socket.gethostbyname(query)
            listed_count += 1
        except socket.gaierror:  # Host not found means not listed
            continue
        except Exception:
            continue
    return listed_count

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): # Renamed to match the SCORE_CONFIG key (consistency)
    """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() # Raises HTTPError for bad responses (4xx or 5xx)
        matches = response.json().get("matches", [])
        return "Yes" if len(matches) > 0 else "No"
    except requests.exceptions.RequestException as e:
        return f"Error: {e}"
    except Exception as e:
        return f"Error: {e}"

# --- Unified Analysis Function for URL/Domain/IP ---

def analyze_input_string(input_string):
    """Analyzes a single URL, domain, or IP and returns its results as a formatted string and raw verdict."""

    output = [] # To capture print statements for Gradio or return
    total_score = 0
    indicators = [] # List to track what contributed to the score

    url = ""
    domain = ""
    ip = ""
    is_raw_ip_analysis = False

    # --- Input Type Determination ---
    if is_ip_address(input_string):
        is_raw_ip_analysis = True
        ip = input_string
        output.append(f"\n🔍 Analyzing IP: {input_string}")
        output.append(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: # Missing scheme, but looks like a domain with path
            url = f"http://{input_string}"  # Add default scheme for checks
            domain = parsed_url.netloc
        elif "." in input_string: # Looks like a domain without scheme or path
            domain = input_string
            url = f"http://{input_string}"  # Add default scheme for URL-specific checks
        else:
            output.append(f"\n🔍 Analyzing: {input_string}")
            output.append("🌐 Invalid URL or Domain format. Cannot proceed with full analysis.")
            output.append("🔎 FINAL VERDICT: ⚠️ SUSPICIOUS - Invalid Input")
            return "\n".join(output), "SUSPICIOUS", total_score # Return verdict and score

        output.append(f"\n🔍 Analyzing: {input_string}")
        output.append(f"🌐 Domain: {domain or 'N/A'}")

        if domain:
            ip = get_ip_from_domain(domain)
            output.append(f"🌐 Resolved IP: {ip or 'Unavailable'}")
        else:
            output.append(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_count = 0 # Now counts how many blacklists
    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) # Corrected function call

    if ip:
        vt_score_ip_check = check_virustotal_ip(ip)
        abuse_score = check_abuseipdb(ip)
        listed_dnsbl_count = check_dnsbl(ip)

    # --- Score Calculation ---

    if vt_score_domain >= 1: # Assuming 1 or more detections is suspicious
        total_score += SCORE_CONFIG["POINTS_VT_DETECTED"]
        indicators.append(f"VirusTotal (Domain) detections: {vt_score_domain}")
    if vt_score_url >= 1:
        total_score += SCORE_CONFIG["POINTS_VT_DETECTED"]
        indicators.append(f"VirusTotal (URL) detections: {vt_score_url}")
    if vt_score_ip_check >= 1:
        total_score += SCORE_CONFIG["POINTS_VT_DETECTED"]
        indicators.append(f"VirusTotal (IP) detections: {vt_score_ip_check}")

    if abuse_score >= SCORE_CONFIG["ABUSEIPDB_HIGH_CONFIDENCE_THRESHOLD"]:
        total_score += SCORE_CONFIG["POINTS_ABUSEIPDB_HIGH"]
        indicators.append(f"AbuseIPDB score: {abuse_score} (HIGH CONFIDENCE)")
    elif abuse_score >= SCORE_CONFIG["ABUSEIPDB_MEDIUM_CONFIDENCE_THRESHOLD"]:
        total_score += SCORE_CONFIG["POINTS_ABUSEIPDB_MEDIUM"]
        indicators.append(f"AbuseIPDB score: {abuse_score} (MEDIUM CONFIDENCE)")

    if listed_dnsbl_count > 0:
        total_score += SCORE_CONFIG["POINTS_DNSBL_LISTED"]
        if listed_dnsbl_count > 1:
            total_score += SCORE_CONFIG["POINTS_DNSBL_MULTIPLE"] * (listed_dnsbl_count - 1)
        indicators.append(f"Listed on {listed_dnsbl_count} DNSBL(s)")

    if days_old is not None:
        TWO_YEARS_IN_DAYS = 2 * 365
        NINETY_DAYS = 90
        if days_old < NINETY_DAYS:
            total_score += SCORE_CONFIG["POINTS_VERY_YOUNG_DOMAIN"]
            indicators.append(f"Domain age: {days_old} days (VERY Young)")
        elif days_old < TWO_YEARS_IN_DAYS:
            total_score += SCORE_CONFIG["POINTS_YOUNG_DOMAIN"]
            indicators.append(f"Domain age: {days_old} days (Young)")
    else:
        total_score += SCORE_CONFIG["POINTS_UNKNOWN_DOMAIN_AGE"]
        indicators.append("Domain age: Unknown (WHOIS info unavailable/failed)")

    if tld_suspicious:
        total_score += SCORE_CONFIG["POINTS_SUSPICIOUS_TLD"]
        indicators.append(f"Suspicious TLD: {matched_tld}")

    if google_flagged_status == "Yes":
        total_score += SCORE_CONFIG["POINTS_GOOGLE_SAFE_BROWSE_FLAGGED"] # Corrected key
        indicators.append("Google Safe Browse flagged URL")
    elif "Error" in google_flagged_status:
        total_score += SCORE_CONFIG["POINTS_GOOGLE_SAFE_BROWSE_ERROR"] # (This is 0, just for clarity) (Corrected key)
        indicators.append(f"Google Safe Browse: {google_flagged_status}") # Still report the error


    # --- Print Results in the desired format ---
    if domain and not is_raw_ip_analysis:
        output.append(f"🦠 VirusTotal detections (Domain): {vt_score_domain}" + (" ⚠️" if vt_score_domain > 0 else ""))
    if url and not is_raw_ip_analysis:
        output.append(f"🦠 VirusTotal detections (URL): {vt_score_url}" + (" ⚠️" if vt_score_url > 0 else ""))
    if ip:
        output.append(f"🦠 VirusTotal detections (IP): {vt_score_ip_check}" + (" ⚠️" if vt_score_ip_check > 0 else ""))

    output.append(f"🚨 AbuseIPDB score: {abuse_score}" + (" ⚠️" if abuse_score >= SCORE_CONFIG["ABUSEIPDB_MEDIUM_CONFIDENCE_THRESHOLD"] else ""))
    output.append(f"🧱 DNSBL listed: {listed_dnsbl_count} lists" + (" ⚠️" if listed_dnsbl_count > 0 else ""))

    domain_age_status = ""
    if days_old is not None:
        TWO_YEARS_IN_DAYS = 2 * 365
        NINETY_DAYS = 90
        if days_old < NINETY_DAYS:
             domain_age_status = f"{days_old} days (VERY Young) ⚠️"
        elif days_old < TWO_YEARS_IN_DAYS:
            domain_age_status = f"{days_old} days (Young) ⚠️"
        else:
            domain_age_status = f"{days_old} days"
    else:
        domain_age_status = "Unknown ⚠️ (WHOIS error/privacy)"
    output.append(f"📅 Domain creation date: {creation_str}")
    output.append(f"📅 Domain age: {domain_age_status}")

    output.append(f"❗ Suspicious TLD: {'Yes (' + matched_tld + ') ⚠️' if tld_suspicious else 'No'}")

    output.append(f"🔎 URLScan result: {urlscan_result_text}")

    output.append(f"🛑 Google Safe Browse flagged: {google_flagged_status}" + (" ⚠️" if google_flagged_status == "Yes" else (" ❓" if "Error" in google_flagged_status else "")))

    output.append(f"\n📊 Total Suspicion Score: {total_score}")
    if indicators:
        output.append("💡 Contributing Indicators:")
        for ind in indicators:
            output.append(f"  - {ind}")

    # --- Determine Verdict based on Score ---
    verdict_raw = "LEGIT"
    if total_score >= VERDICT_THRESHOLDS["PHISHING"]:
        verdict_raw = "PHISHING"
    elif total_score >= VERDICT_THRESHOLDS["SUSPICIOUS"]:
        verdict_raw = "SUSPICIOUS"

    output.append(f"\n🔎 FINAL VERDICT: {format_verdict(verdict_raw)}")
    return "\n".join(output), verdict_raw, total_score


# --- 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, email_total_score_ref, email_indicators_list):
    """Analyzes 'From' and 'Reply-To' domains from headers using unified analysis."""
    analysis_output = []
    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:
        analysis_output.append("\n--- DOMAIN ANALYSIS (FROM HEADER 'FROM') ---")
        verdict_str, verdict_raw, domain_score = analyze_input_string(from_domain_raw)
        analysis_output.append(verdict_str)
        email_total_score_ref[0] += domain_score
        if domain_score >= VERDICT_THRESHOLDS["PHISHING"]:
            email_indicators_list.append(f"Header Domain (From) highly suspicious: {from_domain_raw}")
        elif domain_score >= VERDICT_THRESHOLDS["SUSPICIOUS"]:
            email_indicators_list.append(f"Header Domain (From) suspicious: {from_domain_raw}")

    if reply_domain_raw and reply_domain_raw != from_domain_raw:
        analysis_output.append("\n--- DOMAIN ANALYSIS (FROM HEADER 'REPLY-TO') ---")
        verdict_str, verdict_raw, domain_score = analyze_input_string(reply_domain_raw)
        analysis_output.append(verdict_str)
        email_total_score_ref[0] += domain_score
        if domain_score >= VERDICT_THRESHOLDS["PHISHING"]:
            email_indicators_list.append(f"Header Domain (Reply-To) highly suspicious: {reply_domain_raw}")
        elif domain_score >= VERDICT_THRESHOLDS["SUSPICIOUS"]:
            email_indicators_list.append(f"Header Domain (Reply-To) suspicious: {reply_domain_raw}")

    return "\n".join(analysis_output)

def extract_ips_from_headers(headers):
    """Extracts IP addresses from email headers."""
    ips = set()
    # Broadened IP extraction regex to catch more patterns
    ip_pattern = re.compile(r'\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b')
    for key, value in headers.items():
        # Specifically look for IP in common headers where it indicates origin
        if key.lower() in ["received", "x-originating-ip", "client-ip", "x-forwarded-for"]:
            matches = ip_pattern.findall(value)
            ips.update(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)

    # Exclude mailto links from general URL analysis
    urls.update(re.findall(r"https?://[^\s\"'<>,]+", body_text))

    return body_text[:2000], html[:2000], list(urls)

def analyze_body_content(body):
    """Analyzes the email body for suspicious words and returns the score added."""
    analysis_output = []
    analysis_output.append("\n--- BODY CONTENT ANALYSIS ---")
    red_flags = []
    verdict_raw = "LEGIT" # Verdict internal to body analysis
    score_added = 0

    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"
        score_added = SCORE_CONFIG["POINTS_SUSPICIOUS_BODY_CONTENT"]

    for flag in red_flags:
        analysis_output.append(f"  - {flag}")
    analysis_output.append(f"  Verdict (Body only): {format_verdict(verdict_raw)}")
    return "\n".join(analysis_output), score_added

def run_email_analysis(file_path):
    """Analyzes an email file and returns a detailed report and final verdict."""
    try:
        with open(file_path, "rb") as f:
            msg = BytesParser(policy=policy.default).parse(f)
    except FileNotFoundError:
        return f"Error: File not found at {file_path}", "Error", ""
    except Exception as e:
        return f"Error parsing email file: {e}", "Error", ""

    email_total_score = [0] # Use a list to allow modification within functions
    final_phishing_indicators = []
    analysis_report = []

    analysis_report.append("\n" + "=" * 70)
    analysis_report.append("                 EMAIL PHISHING ANALYSIS REPORT")
    analysis_report.append("=" * 70)

    # --- Header Analysis ---
    analysis_report.append("\n👀========== EMAIL HEADER ANALYSIS ==========👀")
    headers = extract_all_headers(msg)
    for k, v in headers.items():
        # Clean up multi-line headers for better display
        cleaned_value = v.replace('\n', ' ').strip()
        analysis_report.append(f'  {k}: {cleaned_value}') # FIX APPLIED HERE

    analysis_report.append("\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")
                email_total_score[0] += SCORE_CONFIG["POINTS_HEADER_AUTH_FAIL"]
            else:
                status_icon = "❓"
        elif k == "cat": # Spam Category
            if v and v.lower() == "clean":
                status_icon = "✔️"
            elif v:
                status_icon = "⚠️"
                final_phishing_indicators.append(f"Header: Spam category {v}")
                email_total_score[0] += SCORE_CONFIG["POINTS_SPAM_CATEGORY"]
            else:
                status_icon = "❓"
        analysis_report.append(f"  {status_icon} {k.upper()}: {status_text}")

    analysis_report.append("\n--- DOMAIN REPUTATION FROM HEADERS ---")
    analysis_report.append(analyze_header_domains(headers, email_total_score, final_phishing_indicators))

    analysis_report.append("\n--- IP ADDRESS ANALYSIS FROM HEADERS ---")
    ips_from_headers = extract_ips_from_headers(headers)
    if not ips_from_headers:
        analysis_report.append("  No IP addresses found in headers.")
    for ip_addr in ips_from_headers:
        verdict_str, ip_verdict_raw, ip_score = analyze_input_string(ip_addr)
        analysis_report.append(verdict_str)
        email_total_score[0] += ip_score
        if ip_score >= VERDICT_THRESHOLDS["PHISHING"]:
            final_phishing_indicators.append(f"IP in header highly suspicious: {ip_addr}")
        elif ip_score >= VERDICT_THRESHOLDS["SUSPICIOUS"]:
            final_phishing_indicators.append(f"IP in header suspicious: {ip_addr}")
    analysis_report.append("=" * 70)

    # --- Body Content Analysis ---
    analysis_report.append("\n👀========== BODY CONTENT ANALYSIS ==========👀")
    body_text, html_content, urls_found = extract_body_and_urls(msg)

    analysis_report.append("\n--- BODY TEXT PREVIEW (FIRST 1000 CHARACTERS): ---")
    if body_text:
        analysis_report.append(body_text[:1000] + ("..." if len(body_text) > 1000 else ""))
    else:
        analysis_report.append("  No plain text body found.")

    body_verdict_str, body_score_added = analyze_body_content(body_text)
    analysis_report.append(body_verdict_str)
    email_total_score[0] += body_score_added
    if body_score_added > 0:
        final_phishing_indicators.append("Body: Suspicious content (keywords detected)")
    analysis_report.append("=" * 70)

    # --- URL Analysis from Body ---
    analysis_report.append("\n👀========== URL CLASSIFICATION FROM BODY ==========👀")
    if not urls_found:
        analysis_report.append("  No URLs found in the email body.")
    for url_found in urls_found:
        if url_found.startswith("mailto:"): # Skip mailto links for web URL analysis
            analysis_report.append(f"Skipping mailto link: {url_found}")
            continue

        verdict_str, url_verdict_raw, url_score = analyze_input_string(url_found)
        analysis_report.append(verdict_str)
        email_total_score[0] += url_score
        if url_score >= VERDICT_THRESHOLDS["PHISHING"]:
            final_phishing_indicators.append(f"URL from body highly suspicious: {url_found}")
        elif url_score >= VERDICT_THRESHOLDS["SUSPICIOUS"]:
            final_phishing_indicators.append(f"URL from body suspicious: {url_found}")
    analysis_report.append("=" * 70)

    # --- Final Email Classification ---
    analysis_report.append("\n" + "=" * 70)
    analysis_report.append("               FINAL EMAIL CLASSIFICATION")
    analysis_report.append("=" * 70)

    final_email_verdict_raw = "LEGIT"

    if email_total_score[0] >= VERDICT_THRESHOLDS["PHISHING"]:
        final_email_verdict_raw = "PHISHING"
    elif email_total_score[0] >= VERDICT_THRESHOLDS["SUSPICIOUS"]:
        final_email_verdict_raw = "SUSPICIOUS"

    analysis_report.append(f"\n📊 Total Email Suspicion Score: {email_total_score[0]}")
    if final_phishing_indicators:
        analysis_report.append("💡 Contributing Email Indicators:")
        for indicator in sorted(list(set(final_phishing_indicators))):
            analysis_report.append(f"- {indicator}")

    final_email_verdict_text = f"🔎 FINAL VERDICT: {format_verdict(final_email_verdict_raw)}"
    analysis_report.append(final_email_verdict_text)

    if final_email_verdict_raw == "PHISHING":
        analysis_report.append(
            "\nACTION REQUIRED: Exercise extreme caution. Do not click on any links, open attachments, or reply to this email.")
    elif final_email_verdict_raw == "SUSPICIOUS":
        analysis_report.append(
            "\nCAUTION: This email shows suspicious signs. Proceed with caution. Verify sender and links before interacting.")
    else:
        analysis_report.append(
            "\nWhile no definitive phishing signs were found, always remain vigilant with unsolicited emails.")
    analysis_report.append("=" * 70 + "\n")

    return "\n".join(analysis_report), final_email_verdict_text, html_content # Return html_content too

# --- Gradio Functions (adaptations for new return values) ---

def run_email_analysis_gradio(email_file):
    if email_file is None:
        return "Please upload an .eml file.", "", ""

    file_path = email_file.name # Gradio passes a NamedTemporaryFile

    report, verdict_text, html = run_email_analysis(file_path)
    return report, verdict_text # Can add html as a third output if a gr.HTML component is used

def run_interactive_analysis_gradio(user_input_string):
    if not user_input_string:
        return "Please enter a URL, Domain, or IP address."

    inputs_to_analyze = [item.strip() for item in user_input_string.split(',')]
    full_report = []
    for item in inputs_to_analyze:
        if item:
            # We only need the first return value (the formatted report string)
            report_segment, _, _ = analyze_input_string(item)
            full_report.append(report_segment)
            full_report.append("\n" + "=" * 70 + "\n") # Separator for multiple analyses
    return "\n".join(full_report)


# --- Gradio Interface ---

with gr.Blocks(title="Phishing Analysis Tool") as demo:
    gr.Markdown(
        """
        # 🎣 Herramienta de Análisis de Phishing
        Esta herramienta te ayuda a analizar correos electrónicos o URLs/Dominios/IPs en busca de posibles indicadores de phishing.
        Elige entre Análisis de Correo Electrónico o Análisis Interactivo de URL/Dominio/IP.
        """
    )

    with gr.Tab("Análisis de Correo Electrónico"):
        # FIX APPLIED HERE: Changed type="file" to type="filepath" as required by Gradio
        email_file_input = gr.File(label="Subir archivo .eml", type="filepath")
        email_analyze_button = gr.Button("Analizar Correo")
        email_output_report = gr.Textbox(label="Reporte de Análisis de Correo", lines=20, max_lines=50, interactive=False)
        email_final_verdict = gr.Textbox(label="Veredicto Final del Correo", interactive=False)
        # Uncomment the line below and add to outputs if you want to display HTML content
        # email_html_output = gr.HTML(label="Vista Previa de Contenido HTML del Correo (podría no renderizar perfectamente o ser seguro para todo el contenido)")

        email_analyze_button.click(
            fn=run_email_analysis_gradio,
            inputs=email_file_input,
            outputs=[email_output_report, email_final_verdict] #, email_html_output]
        )

    with gr.Tab("Análisis Interactivo de URL/Dominio/IP"):
        url_input = gr.Textbox(
            label="Introduce URL(s), Dominio(s) o Dirección(es) IP (separadas por comas)",
            placeholder="Ej: example.com, 192.168.1.1, https://phishingsite.net"
        )
        url_analyze_button = gr.Button("Analizar Entrada(s)")
        url_output_report = gr.Textbox(label="Reporte de Análisis", lines=20, max_lines=50, interactive=False)

        url_analyze_button.click(
            fn=run_interactive_analysis_gradio,
            inputs=url_input,
            outputs=url_output_report
        )

# --- Main execution block ---
# When deployed on Hugging Face Spaces, this block will simply launch the Gradio app.
# The interactive command-line menu is for local development/testing only.
if __name__ == "__main__":
    demo.launch()