-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscanner.py
1542 lines (1341 loc) · 59.4 KB
/
scanner.py
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
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import aiohttp
import requests
import whois
import ssl
import socket
import re
import logging
import os
import json
import base64
import subprocess
import io
from datetime import datetime
from typing import List, Dict, Tuple, Optional
from bs4 import BeautifulSoup
from urllib.parse import urlparse
import tldextract
from cryptography.fernet import Fernet
from concurrent.futures import ThreadPoolExecutor
import joblib
import pandas as pd
from dotenv import load_dotenv
import dns.resolver
import urllib3
from urllib3.exceptions import InsecureRequestWarning
from PIL import Image
import pytesseract
from sqlalchemy import create_engine, Column, String, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import nmap
from shodan import Shodan
from censys.search import CensysHosts
from wafw00f.main import WAFW00F
from OTXv2 import OTXv2, IndicatorTypes
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.pipeline import Pipeline
from sklearn.model_selection import cross_val_score, GridSearchCV
import sublist3r
urllib3.disable_warnings(InsecureRequestWarning)
load_dotenv()
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("scanner.log"),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
KEY_FILE = 'secret.key'
def load_or_create_key() -> Fernet:
if os.path.exists(KEY_FILE):
with open(KEY_FILE, 'rb') as key_file:
key = key_file.read()
else:
key = Fernet.generate_key()
with open(KEY_FILE, 'wb') as key_file:
key_file.write(key)
return Fernet(key)
fernet = load_or_create_key()
Base = declarative_base()
class Cache(Base):
__tablename__ = 'cache'
url = Column(String, primary_key=True)
data = Column(String)
timestamp = Column(DateTime)
last_checked = Column(DateTime)
DATABASE_URL = 'sqlite:///cache.db'
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(bind=engine)
def init_cache_db():
try:
Base.metadata.create_all(engine)
logger.info("Database initialized successfully.")
except Exception as e:
logger.error(f"Error initializing database: {e}")
init_cache_db()
from contextlib import contextmanager
@contextmanager
def get_db_session():
session = SessionLocal()
try:
yield session
except Exception as e:
logger.error(f"Database session error: {e}")
session.rollback()
raise
finally:
session.close()
def load_cache() -> Dict[str, dict]:
cache = {}
with get_db_session() as session:
cache_entries = session.query(Cache).all()
for entry in cache_entries:
try:
decrypted_data = fernet.decrypt(entry.data.encode()).decode()
cache[entry.url] = json.loads(decrypted_data)
except Exception as e:
logger.error(f"Error decrypting cache entry for {entry.url}: {e}")
logger.info(f"Loaded {len(cache)} entries from cache.")
return cache
def save_cache_entry(url: str, data: dict):
encrypted_data = fernet.encrypt(json.dumps(data).encode()).decode()
with get_db_session() as session:
cache_entry = Cache(
url=url,
data=encrypted_data,
timestamp=datetime.now(),
last_checked=datetime.now()
)
session.merge(cache_entry)
session.commit()
logger.info(f"Cache entry saved for {url}.")
cache = load_cache()
MODEL_FILE = 'models/scam_detector_model.pkl'
def train_model(data_path: str = 'scam_dataset.csv', model_path: str = MODEL_FILE):
try:
if not os.path.exists(data_path):
logger.warning("Training dataset not found. Skipping training.")
return
data = pd.read_csv(data_path)
X = data['url']
y = data['label']
pipeline = Pipeline([
('tfidf', TfidfVectorizer()),
('clf', RandomForestClassifier(random_state=42))
])
param_grid = {
'clf__n_estimators': [100, 200],
'clf__max_depth': [None, 10, 20],
'clf__min_samples_split': [2, 5],
}
grid_search = GridSearchCV(pipeline, param_grid, cv=5, scoring='accuracy', n_jobs=-1)
grid_search.fit(X, y)
best_model = grid_search.best_estimator_
scores = cross_val_score(best_model, X, y, cv=5)
logger.info(f"Cross-validation Accuracy: {scores.mean():.2f} ± {scores.std():.2f}")
os.makedirs(os.path.dirname(model_path), exist_ok=True)
joblib.dump(best_model, model_path)
logger.info("Model trained and saved successfully.")
except Exception as e:
logger.error(f"Error training model: {e}")
def load_model() -> Optional[Pipeline]:
try:
if not os.path.exists(MODEL_FILE):
logger.info("Model file not found. Training new model...")
train_model()
return joblib.load(MODEL_FILE)
except Exception as e:
logger.error(f"Error loading model: {e}")
return None
model = load_model()
def predict(url: str, model: Pipeline) -> str:
try:
return model.predict([url])[0]
except Exception as e:
logger.error(f"Error during prediction: {e}")
return 'Error'
def validate_url(url: str) -> bool:
try:
result = urlparse(url)
is_valid = all([result.scheme in ['http', 'https'], result.netloc])
logger.debug(f"Validating URL '{url}': {is_valid}")
return is_valid
except Exception as e:
logger.error(f"URL validation error for '{url}': {e}")
return False
async def analyze_ssl_certificate(url: str) -> Tuple[bool, str, Optional[dict]]:
try:
parsed_url = urlparse(url)
host = parsed_url.hostname
context = ssl.create_default_context()
context.set_ciphers('HIGH:!aNULL:!eNULL:!MD5:!RC4')
context.minimum_version = ssl.TLSVersion.TLSv1_2
loop = asyncio.get_event_loop()
ssl_check = await loop.run_in_executor(None, _ssl_check_detailed, host, context, url)
return ssl_check
except Exception as e:
logger.error(f"SSL certificate analysis failed: {str(e)}")
return (False, f"SSL certificate analysis error: {str(e)}", None)
def _ssl_check_detailed(host: str, context: ssl.SSLContext, url: str) -> Tuple[bool, str, Optional[dict]]:
try:
with socket.create_connection((host, 443), timeout=10) as sock:
with context.wrap_socket(sock, server_hostname=host) as ssock:
cert = ssock.getpeercert()
cipher = ssock.cipher()
protocol = ssock.version()
not_before = datetime.strptime(cert['notBefore'], '%b %d %H:%M:%S %Y %Z')
not_after = datetime.strptime(cert['notAfter'], '%b %d %H:%M:%S %Y %Z')
now = datetime.utcnow()
if now < not_before or now > not_after:
return (False, f"SSL certificate expired or not yet valid (Valid from {not_before} to {not_after}).", None)
supported_protocols = ['TLSv1.2', 'TLSv1.3']
if protocol not in supported_protocols:
return (False, f"Unsupported SSL protocol: {protocol}. Supported protocols: {supported_protocols}", None)
hsts = False
try:
response = requests.get(url, timeout=10, verify=True)
if 'Strict-Transport-Security' in response.headers:
hsts = True
except:
pass
if not hsts:
return (False, "HSTS is not enabled.", None)
issuer = dict(x[0] for x in cert['issuer'])
subject = dict(x[0] for x in cert['subject'])
details = {
'issuer': issuer.get('commonName', ''),
'subject': subject.get('commonName', ''),
'protocol': protocol,
'cipher': cipher,
'valid_from': not_before.isoformat(),
'valid_to': not_after.isoformat(),
'hsts_enabled': hsts
}
return (True, "SSL certificate is valid.", details)
except ssl.SSLError as e:
return (False, f"SSL error: {e}", None)
except Exception as e:
return (False, f"Error in SSL check: {e}", None)
async def check_domain_age(url: str) -> Tuple[bool, str]:
try:
loop = asyncio.get_event_loop()
result = await loop.run_in_executor(None, _check_domain_age, url)
return result
except Exception as e:
return (False, f"Error checking domain age: {e}")
def _check_domain_age(url: str) -> Tuple[bool, str]:
try:
domain = urlparse(url).hostname
whois_info = whois.whois(domain)
creation_date = whois_info.creation_date
if isinstance(creation_date, list):
creation_date = creation_date[0]
if not creation_date:
message = "Unable to determine domain creation date."
logger.warning(message)
return (False, message)
age_days = (datetime.now() - creation_date).days
logger.debug(f"Domain age for {domain}: {age_days} days")
if age_days < 365:
message = f"Domain age is {age_days} days, which is relatively new."
return (False, message)
else:
message = f"Domain age is {age_days} days."
return (True, message)
except Exception as e:
message = f"Error checking domain age: {e}"
logger.error(message)
return (False, message)
async def check_malware(url: str) -> Tuple[bool, str]:
try:
loop = asyncio.get_event_loop()
result = await loop.run_in_executor(None, _check_malware, url)
return result
except Exception as e:
return (False, f"Error checking malware: {e}")
def _check_malware(url: str) -> Tuple[bool, str]:
try:
response = requests.get(url, timeout=10, verify=False)
if response.status_code == 200:
soup = BeautifulSoup(response.text, 'html.parser')
suspicious_links = soup.find_all('a', href=True)
for link in suspicious_links:
href = link['href']
if ('malware' in href.lower() or 'virus' in href.lower()):
message = f"Suspicious link detected: {href}"
logger.warning(message)
return (False, message)
scripts = soup.find_all('script', src=True)
for script in scripts:
src = script['src']
if ('malware' in src.lower() or 'virus' in src.lower()):
message = f"Suspicious script detected: {src}"
logger.warning(message)
return (False, message)
return (True, "No malware detected.")
else:
message = f"HTTP status code {response.status_code} received."
logger.warning(message)
return (False, message)
except requests.RequestException as e:
message = f"Request error during malware check: {e}"
logger.error(message)
return (False, message)
except Exception as e:
message = f"Error checking malware: {e}"
logger.error(message)
return (False, message)
async def check_suspicious_tld(url: str) -> Tuple[bool, str]:
try:
tld = tldextract.extract(url).suffix
suspicious_tlds = {'xyz', 'top', 'club', 'tk', 'ga', 'ml', 'cf'}
logger.debug(f"Domain TLD: {tld}")
if tld in suspicious_tlds:
message = f"Suspicious TLD detected: .{tld}"
logger.warning(message)
return (False, message)
else:
message = f"TLD '.{tld}' is considered safe."
return (True, message)
except Exception as e:
message = f"Error checking TLD: {e}"
logger.error(message)
return (False, message)
async def check_phishing_keywords(url: str) -> Tuple[bool, str]:
try:
phishing_keywords = {'login', 'update', 'account', 'secure', 'bank', 'verify', 'signin', 'confirm'}
parsed_url = urlparse(url)
path = parsed_url.path.lower()
query = parsed_url.query.lower()
for keyword in phishing_keywords:
if (keyword in path or keyword in query):
message = f"Phishing keyword detected in URL: '{keyword}'."
logger.warning(message)
return (False, message)
return (True, "No phishing keywords found in URL.")
except Exception as e:
message = f"Error checking phishing keywords: {e}"
logger.error(message)
return (False, message)
async def analyze_form_security(url: str) -> Tuple[bool, str]:
try:
response = requests.get(url, timeout=10, verify=False)
if response.status_code == 200:
soup = BeautifulSoup(response.text, 'html.parser')
forms = soup.find_all('form')
if not forms:
message = "No forms found on the website."
logger.info(message)
return (True, message)
insecure_forms = 0
for form in forms:
action = form.get('action', '').lower()
if action and not action.startswith('https'):
insecure_forms += 1
logger.warning(f"Insecure form action detected: {action}")
if insecure_forms > 0:
message = f"{insecure_forms} insecure form(s) detected."
return (False, message)
else:
message = "All forms are secured with HTTPS."
return (True, message)
else:
message = f"HTTP status code {response.status_code} received."
logger.warning(message)
return (False, message)
except requests.RequestException as e:
message = f"Request error during form security check: {e}"
logger.error(message)
return (False, message)
except Exception as e:
message = f"Error analyzing form security: {e}"
logger.error(message)
return (False, message)
async def check_persian_content(url: str) -> Tuple[bool, str]:
try:
response = requests.get(url, timeout=10, verify=False)
if response.status_code == 200:
persian_pattern = re.compile(r'[\u0600-\u06FF]')
if persian_pattern.search(response.text):
scam_keywords = ['کلاهبرداری', 'دروغ', 'فریب', 'تقلب', 'هک', 'سرقت']
scam_detected = any(keyword in response.text for keyword in scam_keywords)
if scam_detected:
message = "Persian content detected with potential scam keywords."
logger.info(message)
return (False, message)
else:
message = "Persian content detected without scam keywords."
logger.info(message)
return (True, message)
else:
message = "No Persian content found on the website."
logger.info(message)
return (False, message)
else:
message = f"HTTP status code {response.status_code} received."
logger.warning(message)
return (False, message)
except requests.RequestException as e:
message = f"Request error during Persian content check: {e}"
logger.error(message)
return (False, message)
except Exception as e:
message = f"Error checking Persian content: {e}"
logger.error(message)
return (False, message)
async def check_contact_privacy_pages(url: str) -> Tuple[bool, str]:
try:
response = requests.get(url, timeout=10, verify=False)
if response.status_code == 200:
soup = BeautifulSoup(response.text, 'html.parser')
contact = soup.find('a', href=re.compile(r'contact', re.I))
privacy = soup.find('a', href=re.compile(r'privacy', re.I))
if (contact and privacy):
return (True, "Contact and Privacy pages found.")
else:
message = "Missing Contact or Privacy pages."
logger.warning(message)
return (False, message)
else:
message = f"HTTP status code {response.status_code} received."
logger.warning(message)
return (False, message)
except Exception as e:
message = f"Error checking contact/privacy pages: {e}"
logger.error(message)
return (False, message)
async def check_dnssec(url: str) -> Tuple[bool, str]:
try:
domain = urlparse(url).hostname
resolver = dns.resolver.Resolver()
resolver.timeout = 5
resolver.lifetime = 5
try:
answers = resolver.resolve(domain, 'DNSKEY')
for rdata in answers:
if rdata.flags & 0x0100:
return (True, "DNSSEC is enabled.")
except dns.resolver.NoAnswer:
return (True, "No DNSSEC records found (common for many domains).")
except dns.resolver.NXDOMAIN:
return (False, "Domain does not exist.")
return (True, "Domain exists but DNSSEC status unclear.")
except Exception as e:
return (True, f"DNSSEC check skipped: {str(e)}")
async def check_robots_txt(url: str) -> Tuple[bool, str]:
try:
parsed_url = urlparse(url)
robots_url = f"{parsed_url.scheme}://{parsed_url.netloc}/robots.txt"
response = requests.get(robots_url, timeout=10, verify=True)
if response.status_code == 200:
return (True, "robots.txt found.")
else:
return (False, "robots.txt not found.")
except Exception as e:
return (False, f"Error checking robots.txt: {e}")
async def check_redirect_chain(url: str) -> Tuple[bool, str]:
try:
response = requests.get(url, timeout=10, verify=True, allow_redirects=True)
if len(response.history) > 3:
return (False, f"Excessive redirects detected: {len(response.history)}")
return (True, "No excessive redirects.")
except Exception as e:
return (False, f"Error checking redirects: {e}")
async def check_http_security_headers(url: str) -> Tuple[bool, str]:
try:
response = requests.get(url, timeout=10, verify=True)
headers = response.headers
missing_headers = []
required_headers = [
'Strict-Transport-Security', 'Content-Security-Policy', 'X-Content-Type-Options',
'X-Frame-Options', 'X-XSS-Protection'
]
for header in required_headers:
if header not in headers:
missing_headers.append(header)
if missing_headers:
return (False, f"Missing security headers: {', '.join(missing_headers)}")
return (True, "All important security headers are present.")
except Exception as e:
return (False, f"Error checking HTTP security headers: {e}")
async def check_js_obfuscation(url: str) -> Tuple[bool, str]:
try:
response = requests.get(url, timeout=10, verify=True)
soup = BeautifulSoup(response.text, 'html.parser')
scripts = soup.find_all('script')
obfuscated_scripts = 0
for script in scripts:
if script.string and re.search(r'[a-zA-Z]{30,}', script.string):
obfuscated_scripts += 1
if obfuscated_scripts > 0:
return (False, f"Obfuscated JavaScript detected: {obfuscated_scripts} scripts")
return (True, "No obfuscated JavaScript detected.")
except Exception as e:
return (False, f"Error checking JavaScript obfuscation: {e}")
async def analyze_html_structure(url: str) -> Tuple[bool, str]:
try:
response = requests.get(url, timeout=10, verify=False)
soup = BeautifulSoup(response.text, 'html.parser')
suspicious_patterns = {
'hidden_elements': len(soup.find_all(style=re.compile(r'display:\s*none|visibility:\s*hidden'))),
'iframe_count': len(soup.find_all('iframe')),
'external_scripts': len(soup.find_all('script', src=re.compile(r'^https?://'))),
'form_actions': [form.get('action') for form in soup.find_all('form')],
'base_tag': bool(soup.find('base')),
'meta_redirects': len(soup.find_all('meta', attrs={'http-equiv': 'refresh'}))
}
warnings = []
if suspicious_patterns['hidden_elements'] > 5:
warnings.append(f"Found {suspicious_patterns['hidden_elements']} hidden elements")
if suspicious_patterns['iframe_count'] > 3:
warnings.append(f"High number of iframes: {suspicious_patterns['iframe_count']}")
if suspicious_patterns['base_tag']:
warnings.append("Base tag detected - possible URL manipulation")
if suspicious_patterns['meta_redirects']:
warnings.append("Meta refresh redirects detected")
return (len(warnings) == 0, "\n".join(warnings) if warnings else "HTML structure appears safe")
except Exception as e:
return (False, f"Error analyzing HTML: {e}")
async def perform_local_ssl_check(url: str) -> Tuple[bool, str]:
try:
parsed_url = urlparse(url)
host = parsed_url.hostname
context = ssl.create_default_context()
with socket.create_connection((host, 443), timeout=10) as sock:
with context.wrap_socket(sock, server_hostname=host) as ssock:
cert = ssock.getpeercert()
cipher = ssock.cipher()
version = ssock.version()
ssl.match_hostname(cert, host)
if 'publicKey' in cert:
key_size = cert['publicKey']['bits']
if key_size < 2048:
return (False, f"Weak key size detected: {key_size} bits")
if version not in ['TLSv1.2', 'TLSv1.3']:
return (False, f"Outdated SSL/TLS version: {version}")
if cipher[2] < 128:
return (False, f"Weak cipher strength: {cipher[2]} bits")
return (True, f"Strong SSL configuration detected. Protocol: {version}, Cipher: {cipher[0]}")
except ssl.CertificateError as e:
return (False, f"Certificate validation failed: {str(e)}")
except Exception as e:
return (False, f"SSL check error: {str(e)}")
async def analyze_network_security(url: str) -> Tuple[bool, str]:
try:
parsed_url = urlparse(url)
host = parsed_url.hostname
common_ports = [21, 22, 23, 25, 80, 443, 445, 3389, 8080, 8443]
open_ports = []
for port in common_ports:
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(1)
result = s.connect_ex((host, port))
if result == 0:
open_ports.append(port)
except:
continue
dns_issues = []
try:
answers = dns.resolver.resolve(host, 'MX')
if not answers:
dns_issues.append("No MX records found")
except:
dns_issues.append("MX record lookup failed")
try:
spf = dns.resolver.resolve(host, 'TXT')
has_spf = any('spf' in str(r).lower() for r in spf)
if not has_spf:
dns_issues.append("No SPF record found")
except:
dns_issues.append("SPF lookup failed")
try:
dmarc = dns.resolver.resolve(f"_dmarc.{host}", 'TXT')
has_dmarc = any('dmarc' in str(r).lower() for r in dmarc)
if not has_dmarc:
dns_issues.append("No DMARC record found")
except:
dns_issues.append("DMARC lookup failed")
security_issues = []
if len(open_ports) > 3:
security_issues.append(f"Multiple open ports detected: {open_ports}")
if dns_issues:
security_issues.append(f"DNS security issues: {', '.join(dns_issues)}")
return (len(security_issues) == 0, "\n".join(security_issues) if security_issues else "Network security looks good")
except Exception as e:
return (False, f"Network security check error: {e}")
async def check_htaccess(url: str) -> Tuple[bool, str]:
try:
parsed_url = urlparse(url)
htaccess_url = f"{parsed_url.scheme}://{parsed_url.netloc}/.htaccess"
response = requests.get(htaccess_url, timeout=10, verify=True)
if response.status_code == 200:
content = response.text.lower()
security_directives = ['deny from all', 'options -indexes', 'header set x-frame-options']
missing_directives = [directive for directive in security_directives if directive not in content]
if missing_directives:
return (False, f"Missing security directives in .htaccess: {', '.join(missing_directives)}")
return (True, "All essential security directives are present in .htaccess.")
else:
return (False, ".htaccess file not found.")
except Exception as e:
return (False, f"Error checking .htaccess: {e}")
async def check_secure_cookies(url: str) -> Tuple[bool, str]:
try:
response = requests.get(url, timeout=10, verify=True)
cookies = response.cookies
insecure_cookies = [cookie.name for cookie in cookies if not cookie.secure]
if insecure_cookies:
return (False, f"Insecure cookies detected: {', '.join(insecure_cookies)}")
return (True, "All cookies are secured with Secure flag.")
except Exception as e:
return (False, f"Error checking secure cookies: {e}")
async def check_content_security_policy(url: str) -> Tuple[bool, str]:
try:
response = requests.get(url, timeout=10, verify=True)
csp = response.headers.get('Content-Security-Policy')
if csp:
return (True, f"CSP is set: {csp}")
else:
return (False, "Content Security Policy (CSP) is not set.")
except Exception as e:
return (False, f"Error checking CSP: {e}")
async def check_http_methods(url: str) -> Tuple[bool, str]:
try:
allowed_methods = []
methods_to_check = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'HEAD', 'PATCH']
for method in methods_to_check:
try:
response = requests.request(method, url, timeout=10, verify=True)
if response.status_code != 405:
allowed_methods.append(method)
except:
continue
if 'DELETE' in allowed_methods or 'PUT' in allowed_methods:
return (False, f"Potentially dangerous HTTP methods allowed: {', '.join(allowed_methods)}")
return (True, f"Allowed HTTP methods: {', '.join(allowed_methods)}")
except Exception as e:
return (False, f"Error checking HTTP methods: {e}")
async def check_ml_model(url: str, model: Pipeline) -> Tuple[bool, str]:
try:
prediction = predict(url, model)
if prediction.lower() == 'scam':
message = "Machine Learning Model: Scam detected."
logger.warning(message)
return (False, message)
else:
message = "Machine Learning Model: URL appears safe."
logger.info(message)
return (True, message)
except Exception as e:
message = f"Error with ML model: {e}"
logger.error(message)
return (False, message)
async def check_image_content(url: str) -> Tuple[bool, str]:
try:
response = requests.get(url, timeout=10)
if response.status_code == 200:
soup = BeautifulSoup(response.text, 'html.parser')
images = soup.find_all('img', src=True)
for img in images:
img_url = img['src']
if not img_url.startswith('http'):
img_url = urlparse(url)._replace(path=img_url).geturl()
img_response = requests.get(img_url, timeout=10)
img_bytes = io.BytesIO(img_response.content)
text = pytesseract.image_to_string(Image.open(img_bytes))
if re.search(r'login|password|secure', text, re.I):
return (False, "Suspicious text detected in images.")
return (True, "No suspicious text found in images.")
else:
return (False, f"HTTP status code {response.status_code} received when accessing URL.")
except Exception as e:
return (False, f"Error checking image content: {e}")
MAX_CONCURRENT_SCANS = 5
semaphore = asyncio.Semaphore(MAX_CONCURRENT_SCANS)
class HTTPSessionManager:
def __init__(self, max_sessions: int = 10):
self.pool = []
self.max_sessions = max_sessions
async def get_session(self) -> aiohttp.ClientSession:
if not self.pool:
self.pool.append(aiohttp.ClientSession())
session = self.pool[len(self.pool) % self.max_sessions]
return session
async def close_all(self):
for session in self.pool:
await session.close()
self.pool.clear()
session_manager = HTTPSessionManager()
class ScanManager:
def __init__(self):
self.running_tasks = set()
self.is_stopping = False
def add_task(self, task: asyncio.Task):
self.running_tasks.add(task)
task.add_done_callback(self.running_tasks.discard)
def stop_all(self):
self.is_stopping = True
for task in self.running_tasks:
task.cancel()
self.running_tasks.clear()
def reset(self):
self.is_stopping = False
self.running_tasks.clear()
scan_manager = ScanManager()
def should_stop() -> bool:
return scan_manager.is_stopping
class ScanProgress:
def __init__(self, total_checks: int, callback=None):
self.total_checks = total_checks
self.current_progress = 0
self.callback = callback
self.weights = {
'initialization': 5,
'primary_checks': 60,
'api_checks': 30,
'finalization': 5
}
def update(self, phase: str, step_progress: float, message: str):
if phase not in self.weights:
return
base_progress = {
'initialization': 0,
'primary_checks': 5,
'api_checks': 65,
'finalization': 95
}.get(phase, 0)
phase_weight = self.weights[phase]
progress = base_progress + (phase_weight * step_progress)
self.current_progress = min(99, progress)
if self.callback:
self.callback(int(self.current_progress), f"{message} ({int(self.current_progress)}%)")
def complete(self):
if self.callback:
self.callback(100, "Scan complete (100%)")
primary_checks = [
analyze_ssl_certificate,
check_domain_age,
check_malware,
check_suspicious_tld,
check_phishing_keywords,
analyze_form_security,
check_persian_content,
check_contact_privacy_pages,
check_dnssec,
check_robots_txt,
check_redirect_chain,
check_http_security_headers,
check_js_obfuscation,
analyze_html_structure,
perform_local_ssl_check,
analyze_network_security,
check_htaccess,
check_secure_cookies,
check_content_security_policy,
check_http_methods,
check_ml_model,
check_image_content
]
async def check_with_google_safe_browsing(session: aiohttp.ClientSession, url: str) -> bool:
GOOGLE_SAFE_BROWSING_API_KEY = os.getenv('SAFE_BROWSING_KEY')
try:
if not GOOGLE_SAFE_BROWSING_API_KEY:
logger.warning("Google Safe Browsing API key not configured")
return True
except Exception as e:
logger.error(f"Error checking Google Safe Browsing API key: {e}")
return True
try:
api_url = f"https://safebrowsing.googleapis.com/v4/threatMatches:find?key={GOOGLE_SAFE_BROWSING_API_KEY}"
payload = {
"client": {
"clientId": "scam_detector",
"clientVersion": "1.0"
},
"threatInfo": {
"threatTypes": ["MALWARE", "SOCIAL_ENGINEERING"],
"platformTypes": ["ANY_PLATFORM"],
"threatEntryTypes": ["URL"],
"threatEntries": [{"url": url}]
}
}
async with session.post(api_url, json=payload) as response:
if response.status == 401:
logger.warning("Invalid Google Safe Browsing API key")
return True
response.raise_for_status()
result = await response.json()
return "matches" not in result
except aiohttp.ClientResponseError as e:
logger.error(f"Error with Google Safe Browsing API: {e.status}, message='{e.message}', url='{e.request_info.url}'")
return True
except Exception as e:
logger.error(f"Error with Google Safe Browsing API: {e}")
return True
async def check_with_virustotal(session: aiohttp.ClientSession, url: str) -> bool:
VIRUSTOTAL_API_KEY = os.getenv('VIRUSTOTAL_API_KEY')
try:
if not VIRUSTOTAL_API_KEY:
logger.warning("VirusTotal API key not configured")
return True
except Exception as e:
logger.error(f"Error checking VirusTotal API key: {e}")
return True
try:
api_url = "https://www.virustotal.com/api/v3/urls"
url_id = base64.urlsafe_b64encode(url.encode()).decode().rstrip('=')
headers = {
'x-apikey': VIRUSTOTAL_API_KEY
}
async with session.get(f"{api_url}/{url_id}", headers=headers) as response:
if response.status == 401:
logger.warning("Invalid VirusTotal API key")
return True
elif response.status == 404:
return True
elif response.status == 200:
result = await response.json()
stats = result.get('data', {}).get('attributes', {}).get('last_analysis_stats', {})
return stats.get('malicious', 0) == 0
else:
logger.warning(f"Unexpected status code {response.status} from VirusTotal")
return True
except aiohttp.ClientResponseError as e:
logger.error(f"Error with VirusTotal API: {e.status}, message='{e.message}', url='{e.request_info.url}'")
return True
except Exception as e:
logger.error(f"Error with VirusTotal API: {e}")
return True
async def check_phishtank(session: aiohttp.ClientSession, url: str) -> Tuple[bool, str]:
PHISHTANK_API_KEY = os.getenv('PHISHTANK_API_KEY')
if not PHISHTANK_API_KEY:
logger.warning("PhishTank API key not configured")
return (True, "PhishTank API key not configured")
try:
api_url = "https://checkurl.phishtank.com/checkurl/"
payload = {
'url': url,
'format': 'json',
'app_key': PHISHTANK_API_KEY
}
async with session.post(api_url, data=payload) as response:
if response.status == 403:
logger.warning("PhishTank API returned status code 403")
return (True, "PhishTank API returned status code 403")
response.raise_for_status()
result = await response.json()
if result.get('results', {}).get('in_database'):
if result['results'].get('valid'):
return (False, "URL is listed in PhishTank as a phishing site.")
return (True, "URL is not listed in PhishTank.")
except aiohttp.ClientResponseError as e:
logger.error(f"Error with PhishTank API: {e.status}, message='{e.message}', url='{e.request_info.url}'")
return (True, f"Error with PhishTank API: {e}")
except Exception as e:
logger.error(f"Error with PhishTank API: {e}")
return (True, f"Error with PhishTank API: {e}")
async def perform_nmap_scan(domain: str) -> Tuple[bool, str, Optional[dict]]:
try:
nm = nmap.PortScanner()
loop = asyncio.get_event_loop()
with ThreadPoolExecutor() as executor:
await loop.run_in_executor(
executor,
nm.scan,
domain,
'21-25,80,443,8080,8443',
'-sV --version-intensity 5 -T4'
)
results = {
'open_ports': [],
'services': {},
'vulnerabilities': []
}
for host in nm.all_hosts():
for proto in nm[host].all_protocols():
ports = nm[host][proto].keys()
for port in ports:
service = nm[host][proto][port]
if service['state'] == 'open':
results['open_ports'].append(port)
results['services'][port] = {
'name': service.get('name', 'unknown'),
'version': service.get('version', 'unknown'),
'product': service.get('product', 'unknown')
}
message = f"Found {len(results['open_ports'])} open ports"
return (True, message, results)
except Exception as e:
return (False, f"Nmap scan error: {str(e)}", None)