-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
3943 lines (3454 loc) · 159 KB
/
app.py
File metadata and controls
3943 lines (3454 loc) · 159 KB
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
#!/usr/bin/env python3
"""
Mail Tester - A mail-tester.com analog
Generates dynamic email addresses, receives emails via SMTP, and analyzes them.
"""
import asyncio
import uuid
import json
import socket
import re
import os
import ssl
import smtplib
import aiohttp
from datetime import datetime, timedelta
from email import policy
from email.parser import BytesParser
from threading import Thread
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor
from flask import Flask, render_template, jsonify, request
from aiosmtpd.controller import Controller
from aiosmtpd.smtp import SMTP as SMTPServer
from pymongo import MongoClient
import requests
from requests.auth import HTTPBasicAuth
try:
from requests_ntlm import HttpNtlmAuth
NTLM_AVAILABLE = True
except ImportError:
NTLM_AVAILABLE = False
import xml.etree.ElementTree as ET
# Try to import optional analysis libraries
try:
import dns.resolver
import dns.query
import dns.message
import dns.rdatatype
import dns.name
DNS_AVAILABLE = True
except ImportError:
DNS_AVAILABLE = False
try:
import dkim
DKIM_AVAILABLE = True
except ImportError:
DKIM_AVAILABLE = False
def create_resolver(use_cache=False):
"""Create a DNS resolver with optional caching disabled."""
resolver = dns.resolver.Resolver()
resolver.cache = dns.resolver.Cache() if use_cache else dns.resolver.LRUCache(0)
resolver.lifetime = 10 # 10 second timeout
return resolver
def get_authoritative_nameservers(domain):
"""Get the authoritative nameservers for a domain."""
try:
resolver = create_resolver()
# Get the zone's NS records
# First try to get NS for the exact domain
try:
ns_answers = resolver.resolve(domain, 'NS')
nameservers = []
for ns in ns_answers:
ns_name = str(ns.target).rstrip('.')
try:
# Resolve NS to IP
a_answers = resolver.resolve(ns_name, 'A')
for a in a_answers:
nameservers.append({'name': ns_name, 'ip': str(a)})
break # Just need one IP per NS
except:
pass
return nameservers
except dns.resolver.NoAnswer:
# Try parent domain
parts = domain.split('.')
if len(parts) > 2:
parent = '.'.join(parts[1:])
return get_authoritative_nameservers(parent)
except dns.resolver.NXDOMAIN:
return []
except Exception as e:
print(f"[DNS] Error getting authoritative NS: {e}")
return []
return []
def query_authoritative(domain, rdtype, nameserver_ip):
"""Query a specific nameserver directly for DNS records."""
try:
qname = dns.name.from_text(domain)
request = dns.message.make_query(qname, rdtype)
response = dns.query.udp(request, nameserver_ip, timeout=5)
records = []
for rrset in response.answer:
if rrset.rdtype == dns.rdatatype.from_text(rdtype):
for rdata in rrset:
records.append({
'value': str(rdata),
'ttl': rrset.ttl
})
return records
except Exception as e:
return {'error': str(e)}
def compare_dns_results(public_records, auth_records):
"""Compare public DNS results with authoritative NS results."""
differences = []
# Normalize records for comparison
def normalize(records):
if isinstance(records, dict) and 'error' in records:
return set()
return set(r.get('value', r.get('host', r.get('ip', str(r)))) for r in records if isinstance(r, dict))
public_set = normalize(public_records) if public_records else set()
auth_set = normalize(auth_records) if auth_records else set()
only_in_public = public_set - auth_set
only_in_auth = auth_set - public_set
if only_in_public:
differences.append({
'type': 'public_only',
'message': 'Records in public DNS but not in authoritative NS',
'records': list(only_in_public)
})
if only_in_auth:
differences.append({
'type': 'auth_only',
'message': 'Records in authoritative NS but not in public DNS (propagation pending)',
'records': list(only_in_auth)
})
return differences
# Configuration from environment variables
SMTP_PORT = int(os.environ.get('SMTP_PORT', 25))
WEB_PORT = int(os.environ.get('WEB_PORT', 5000))
DOMAIN = os.environ.get('DOMAIN', 'localhost')
# SMTP Server hostname (shown in EHLO greeting)
SMTP_HOSTNAME = os.environ.get('SMTP_HOSTNAME', DOMAIN)
# TLS Certificate paths
TLS_CERT_PATH = os.environ.get('TLS_CERT_PATH', '/app/certs/cert.pem')
TLS_KEY_PATH = os.environ.get('TLS_KEY_PATH', '/app/certs/key.pem')
TLS_ENABLED = os.environ.get('TLS_ENABLED', 'true').lower() == 'true'
# Rate limiting configuration (emails per minute)
RATE_LIMIT_PER_IP = int(os.environ.get('RATE_LIMIT_PER_IP', 5))
RATE_LIMIT_PER_EMAIL = int(os.environ.get('RATE_LIMIT_PER_EMAIL', 2))
RATE_LIMIT_PER_DOMAIN = int(os.environ.get('RATE_LIMIT_PER_DOMAIN', 10))
RATE_LIMIT_WINDOW = 60 # seconds
# Smarthost configuration (mail gateway/relay for outbound email)
SMARTHOST_ENABLED = os.environ.get('SMARTHOST_ENABLED', 'false').lower() == 'true'
SMARTHOST_HOST = os.environ.get('SMARTHOST_HOST', '')
SMARTHOST_PORT = int(os.environ.get('SMARTHOST_PORT', 587))
SMARTHOST_USERNAME = os.environ.get('SMARTHOST_USERNAME', '')
SMARTHOST_PASSWORD = os.environ.get('SMARTHOST_PASSWORD', '')
SMARTHOST_TLS = os.environ.get('SMARTHOST_TLS', 'starttls').lower()
SMARTHOST_FROM = os.environ.get('SMARTHOST_FROM', '')
# Rate limiting storage
rate_limit_store = {
'by_ip': defaultdict(list),
'by_email': defaultdict(list),
'by_domain': defaultdict(list),
}
# Callback test storage
callback_tests = {}
# Allowed domains for receiving emails (comma-separated, defaults to DOMAIN)
# This prevents the SMTP server from being an open relay
ALLOWED_DOMAINS_ENV = os.environ.get('ALLOWED_DOMAINS', DOMAIN)
ALLOWED_DOMAINS = set(d.strip().lower() for d in ALLOWED_DOMAINS_ENV.split(',') if d.strip())
def generate_tls_certificate():
"""Generate a self-signed TLS certificate for SMTP STARTTLS."""
import subprocess
cert_dir = os.path.dirname(TLS_CERT_PATH)
if cert_dir and not os.path.exists(cert_dir):
os.makedirs(cert_dir, exist_ok=True)
if os.path.exists(TLS_CERT_PATH) and os.path.exists(TLS_KEY_PATH):
print(f"[TLS] Using existing certificate: {TLS_CERT_PATH}")
return True
try:
cmd = ['openssl', 'req', '-x509', '-newkey', 'rsa:2048', '-keyout', TLS_KEY_PATH, '-out', TLS_CERT_PATH,
'-days', '365', '-nodes', '-subj', f'/CN={DOMAIN}/O=MXLab/C=US']
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0:
print(f"[TLS] Generated self-signed certificate for {DOMAIN}")
return True
print(f"[TLS] Failed to generate certificate: {result.stderr}")
return False
except Exception as e:
print(f"[TLS] Error generating certificate: {e}")
return False
def get_ssl_context():
"""Create SSL context for SMTP STARTTLS."""
if not TLS_ENABLED:
return None
if not os.path.exists(TLS_CERT_PATH) or not os.path.exists(TLS_KEY_PATH):
if not generate_tls_certificate():
return None
try:
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.load_cert_chain(TLS_CERT_PATH, TLS_KEY_PATH)
return context
except Exception as e:
print(f"[TLS] Failed to create SSL context: {e}")
return None
def check_rate_limit(ip, email, domain):
"""Check if request exceeds rate limits."""
now = datetime.now()
window_start = now - timedelta(seconds=RATE_LIMIT_WINDOW)
rate_limit_store['by_ip'][ip] = [t for t in rate_limit_store['by_ip'][ip] if t > window_start]
if len(rate_limit_store['by_ip'][ip]) >= RATE_LIMIT_PER_IP:
return False, f'Rate limit exceeded: max {RATE_LIMIT_PER_IP} emails/min per IP'
rate_limit_store['by_email'][email] = [t for t in rate_limit_store['by_email'][email] if t > window_start]
if len(rate_limit_store['by_email'][email]) >= RATE_LIMIT_PER_EMAIL:
return False, f'Rate limit exceeded: max {RATE_LIMIT_PER_EMAIL} emails/min per sender'
rate_limit_store['by_domain'][domain] = [t for t in rate_limit_store['by_domain'][domain] if t > window_start]
if len(rate_limit_store['by_domain'][domain]) >= RATE_LIMIT_PER_DOMAIN:
return False, f'Rate limit exceeded: max {RATE_LIMIT_PER_DOMAIN} emails/min per domain'
return True, None
def record_rate_limit(ip, email, domain):
"""Record a successful email for rate limiting."""
now = datetime.now()
rate_limit_store['by_ip'][ip].append(now)
rate_limit_store['by_email'][email].append(now)
rate_limit_store['by_domain'][domain].append(now)
def generate_callback_id():
"""Generate unique callback test ID."""
return f"cb_{uuid.uuid4().hex[:10]}"
def send_callback_email(to_email, callback_id, original_subject, smtp_logs, request_delivery_receipt=False, request_read_receipt=False):
"""Send callback email back to the sender. Uses smarthost if configured."""
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
logs = []
result = {'success': False, 'smtp_log': [], 'error': None, 'tls_used': False, 'sent_at': None, 'smarthost_used': False}
try:
logs.append(f"[CALLBACK] Starting callback to {to_email}")
from_addr = SMARTHOST_FROM if SMARTHOST_FROM else f"callback@{DOMAIN}"
msg = MIMEMultipart('alternative')
msg['From'] = from_addr
msg['To'] = to_email
msg['Subject'] = f"[MXLab Callback] Re: {original_subject}"
msg['X-MXLab-Callback-ID'] = callback_id
# Add receipt request headers if requested
if request_delivery_receipt:
msg['Return-Receipt-To'] = from_addr
msg['X-Confirm-Reading-To'] = from_addr # Legacy header
logs.append(f"[CALLBACK] Requesting delivery receipt to {from_addr}")
if request_read_receipt:
msg['Disposition-Notification-To'] = from_addr
logs.append(f"[CALLBACK] Requesting read receipt (MDN) to {from_addr}")
body_text = f"MXLab Callback Test Result\n{'='*32}\n\nCallback ID: {callback_id}\nOriginal Subject: {original_subject}\nTested at: {datetime.now().isoformat()}\n\nSMTP Transaction Log:\n{chr(10).join(smtp_logs)}\n\n---\nMXLab"
msg.attach(MIMEText(body_text, 'plain'))
smtp_conversation = []
if SMARTHOST_ENABLED and SMARTHOST_HOST:
logs.append(f"[CALLBACK] Using smarthost: {SMARTHOST_HOST}:{SMARTHOST_PORT} (TLS: {SMARTHOST_TLS})")
result['smarthost_used'] = True
try:
if SMARTHOST_TLS == 'ssl':
smtp = smtplib.SMTP_SSL(SMARTHOST_HOST, SMARTHOST_PORT, timeout=30)
smtp_conversation.append(f"CONNECT (SSL) -> {SMARTHOST_HOST}:{SMARTHOST_PORT}")
result['tls_used'] = True
else:
smtp = smtplib.SMTP(timeout=30)
smtp_conversation.append(f"CONNECT -> {SMARTHOST_HOST}:{SMARTHOST_PORT}")
code, msg_resp = smtp.connect(SMARTHOST_HOST, SMARTHOST_PORT)
smtp_conversation.append(f"SERVER -> {code} {msg_resp.decode() if isinstance(msg_resp, bytes) else msg_resp}")
# Send EHLO and capture response
code, msg_resp = smtp.ehlo(SMTP_HOSTNAME)
smtp_conversation.append(f"EHLO {SMTP_HOSTNAME} -> {code}")
if code != 250:
raise Exception(f"EHLO failed: {code} {msg_resp}")
if SMARTHOST_TLS == 'starttls':
code, msg_resp = smtp.starttls()
smtp_conversation.append(f"STARTTLS -> {code}")
code, msg_resp = smtp.ehlo(SMTP_HOSTNAME)
smtp_conversation.append(f"EHLO (after TLS) -> {code}")
result['tls_used'] = True
if SMARTHOST_USERNAME and SMARTHOST_PASSWORD:
smtp.login(SMARTHOST_USERNAME, SMARTHOST_PASSWORD)
smtp_conversation.append("AUTH -> OK")
# Use low-level commands for better control with error checking
logs.append(f"[CALLBACK] Sending from: {from_addr}")
code, msg_resp = smtp.mail(from_addr)
smtp_conversation.append(f"MAIL FROM:<{from_addr}> -> {code} {msg_resp.decode() if isinstance(msg_resp, bytes) else msg_resp}")
if code != 250:
raise Exception(f"MAIL FROM rejected: {code} {msg_resp}")
code, msg_resp = smtp.rcpt(to_email)
smtp_conversation.append(f"RCPT TO:<{to_email}> -> {code} {msg_resp.decode() if isinstance(msg_resp, bytes) else msg_resp}")
if code not in (250, 251):
raise Exception(f"RCPT TO rejected: {code} {msg_resp}")
code, msg_resp = smtp.data(msg.as_bytes())
smtp_conversation.append(f"DATA -> {code} {msg_resp.decode() if isinstance(msg_resp, bytes) else msg_resp}")
if code != 250:
raise Exception(f"DATA rejected: {code} {msg_resp}")
smtp.quit()
smtp_conversation.append("QUIT -> OK")
result['success'] = True
result['smtp_log'] = smtp_conversation
result['sent_at'] = datetime.now().isoformat()
result['relay_used'] = SMARTHOST_HOST
except Exception as e:
logs.append(f"[CALLBACK] Smarthost failed: {str(e)}")
smtp_conversation.append(f"ERROR: {str(e)}")
result['error'] = str(e)
result['smtp_log'] = smtp_conversation
else:
domain = to_email.split('@')[1]
mx_records = []
try:
answers = dns.resolver.resolve(domain, 'MX')
for rdata in answers:
mx_records.append((rdata.preference, str(rdata.exchange).rstrip('.')))
mx_records.sort(key=lambda x: x[0])
except:
mx_records = [(0, domain)]
result['mx_records'] = mx_records
for priority, mx_host in mx_records:
try:
smtp = smtplib.SMTP(timeout=30)
smtp.connect(mx_host, 25)
smtp.ehlo(SMTP_HOSTNAME)
if smtp.has_extn('STARTTLS'):
try:
smtp.starttls()
smtp.ehlo(SMTP_HOSTNAME)
result['tls_used'] = True
except:
pass
smtp.mail(from_addr)
smtp.rcpt(to_email)
smtp.data(msg.as_bytes())
smtp.quit()
result['success'] = True
result['sent_at'] = datetime.now().isoformat()
result['mx_used'] = mx_host
break
except Exception as e:
result['error'] = str(e)
continue
except Exception as e:
result['error'] = str(e)
result['logs'] = logs
return result
# Telegram notification configuration (optional - set via environment variables)
TELEGRAM_BOT_TOKEN = os.environ.get('TELEGRAM_BOT_TOKEN', '')
TELEGRAM_CHAT_ID = os.environ.get('TELEGRAM_CHAT_ID', '')
# MongoDB configuration
MONGO_URI = os.environ.get('MONGO_URI', 'mongodb://localhost:27017/')
try:
mongo_client = MongoClient(MONGO_URI, serverSelectionTimeoutMS=5000)
mongo_client.server_info() # Test connection
db = mongo_client.mxlab
reports_collection = db.reports
MONGO_AVAILABLE = True
print(f"[MONGO] Connected to MongoDB at {MONGO_URI}")
except Exception as e:
MONGO_AVAILABLE = False
reports_collection = None
print(f"[MONGO] MongoDB not available: {e}")
async def send_telegram_notification(test_id, email_data, analysis):
"""Send silent notification to Telegram about received email."""
if not TELEGRAM_BOT_TOKEN or not TELEGRAM_CHAT_ID:
return # Telegram notifications disabled
try:
score = analysis.get('score', 0)
sender = email_data.get('from', 'Unknown')
subject = email_data.get('subject', '(No Subject)')
peer = email_data.get('peer', [])
sender_ip = peer[0] if peer else 'Unknown'
sender_port = peer[1] if len(peer) > 1 else ''
# Emoji based on score
if score >= 9:
emoji = "✅"
status = "EXCELLENT"
elif score >= 7:
emoji = "👍"
status = "GOOD"
elif score >= 5:
emoji = "⚠️"
status = "FAIR"
else:
emoji = "❌"
status = "POOR"
# Count headers
headers = email_data.get('headers', {})
headers_count = len(headers)
message = f"""{emoji} <b>MXtest Email Analysis</b>
<b>Score:</b> {score:.1f}/10 — {status}
<b>From:</b> <code>{sender}</code>
<b>Subject:</b> {subject}
<b>Sender IP:</b> <code>{sender_ip}</code>{f' (port {sender_port})' if sender_port else ''}
<b>Headers:</b> {headers_count} headers captured
🔗 <a href="https://{DOMAIN}/report/{test_id}">View Full Report</a>
<i>(includes headers + raw message)</i>"""
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
payload = {
'chat_id': TELEGRAM_CHAT_ID,
'text': message,
'parse_mode': 'HTML',
'disable_notification': True,
'disable_web_page_preview': True
}
async with aiohttp.ClientSession() as session:
async with session.post(url, json=payload) as response:
if response.status == 200:
print(f"[TELEGRAM] Notification sent for test_id: {test_id}")
else:
print(f"[TELEGRAM] Failed to send notification: {response.status}")
except Exception as e:
print(f"[TELEGRAM] Error sending notification: {e}")
async def send_telegram_report_notification(domain, summary, client_ip, report_id=None):
"""Send silent notification to Telegram about MXlab Lookup."""
if not TELEGRAM_BOT_TOKEN or not TELEGRAM_CHAT_ID:
return # Telegram notifications disabled
try:
score = summary.get('score', 0)
passed = summary.get('passed', 0)
warnings = summary.get('warnings', 0)
errors = summary.get('errors', 0)
# Emoji and status based on score
if score >= 90:
emoji = "✅"
status = "EXCELLENT"
elif score >= 75:
emoji = "👍"
status = "GOOD"
elif score >= 60:
emoji = "👌"
status = "FAIR"
elif score >= 40:
emoji = "⚠️"
status = "POOR"
else:
emoji = "❌"
status = "CRITICAL"
message = f"""{emoji} <b>MXlab Domain Report</b>
<b>Domain:</b> <code>{domain}</code>
<b>Score:</b> {score}/100 — {status}
<b>Results:</b> ✅ {passed} | ⚠️ {warnings} | ❌ {errors}
<b>Client IP:</b> <code>{client_ip}</code>"""
if report_id:
message += f"\n\n🔗 <a href=\"https://{DOMAIN}/report/{report_id}\">View Report</a>"
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
payload = {
'chat_id': TELEGRAM_CHAT_ID,
'text': message,
'parse_mode': 'HTML',
'disable_notification': True,
'disable_web_page_preview': True
}
async with aiohttp.ClientSession() as session:
async with session.post(url, json=payload) as response:
if response.status == 200:
print(f"[TELEGRAM] Report notification sent for domain: {domain}")
else:
print(f"[TELEGRAM] Failed to send report notification: {response.status}")
except Exception as e:
print(f"[TELEGRAM] Error sending report notification: {e}")
# Storage for emails and test addresses
emails_store = {} # {test_id: {email_data, analysis, timestamp}}
test_addresses = {} # {test_id: {email, created, expires}}
# Thread pool for async operations
executor = ThreadPoolExecutor(max_workers=10)
# RFC Tips and References
RFC_TIPS = {
'mx': {
'rfc': 'RFC 5321',
'title': 'Simple Mail Transfer Protocol',
'tip': 'MX records specify mail servers for your domain. Without MX records, mail servers will fall back to A records.',
'fix': 'Add MX records pointing to your mail server(s) with appropriate priorities (lower = higher priority).'
},
'spf': {
'rfc': 'RFC 7208',
'title': 'Sender Policy Framework (SPF)',
'tip': 'SPF allows domain owners to specify which mail servers are authorized to send email on behalf of their domain.',
'fix': 'Add a TXT record starting with "v=spf1" listing authorized sending IPs/domains. End with "-all" (hard fail) or "~all" (soft fail).'
},
'dkim': {
'rfc': 'RFC 6376',
'title': 'DomainKeys Identified Mail (DKIM)',
'tip': 'DKIM adds a digital signature to emails that receiving servers can verify using DNS public key.',
'fix': 'Configure your mail server to sign outgoing emails and publish the public key as a TXT record at selector._domainkey.domain.'
},
'dmarc': {
'rfc': 'RFC 7489',
'title': 'Domain-based Message Authentication (DMARC)',
'tip': 'DMARC builds on SPF and DKIM, telling receivers how to handle authentication failures.',
'fix': 'Add a TXT record at _dmarc.domain with policy (p=none/quarantine/reject) and reporting addresses (rua/ruf).'
},
'ptr': {
'rfc': 'RFC 1912',
'title': 'Reverse DNS (PTR Record)',
'tip': 'PTR records map IP addresses to hostnames. Many mail servers reject mail from IPs without valid PTR.',
'fix': 'Contact your ISP/hosting provider to set up reverse DNS for your mail server IP.'
},
'a': {
'rfc': 'RFC 1035',
'title': 'Domain Names - A Records',
'tip': 'A records map domain names to IPv4 addresses.',
'fix': 'Add A records pointing your domain/subdomain to the correct IP address.'
},
'aaaa': {
'rfc': 'RFC 3596',
'title': 'DNS Extensions for IPv6 (AAAA)',
'tip': 'AAAA records map domain names to IPv6 addresses for dual-stack connectivity.',
'fix': 'Add AAAA records if your server supports IPv6. Not mandatory but recommended.'
},
'ns': {
'rfc': 'RFC 1035',
'title': 'Name Server Records',
'tip': 'NS records delegate a DNS zone to authoritative name servers.',
'fix': 'Ensure NS records point to reliable, geographically distributed name servers.'
},
'smtp': {
'rfc': 'RFC 5321',
'title': 'SMTP Protocol',
'tip': 'SMTP servers should respond to EHLO/HELO commands, support standard ports (25, 587, 465), and NOT be open relays.',
'fix': 'Ensure your mail server is accessible on port 25, responds to EHLO, has valid SSL/TLS on port 465/587, and rejects relay attempts from unauthorized senders.'
},
'open_relay': {
'rfc': 'RFC 5321 Section 7.1',
'title': 'Open Mail Relay',
'tip': 'An open relay allows anyone to send email through your server, which will be abused by spammers and get your IP blacklisted.',
'fix': 'Configure your mail server to require authentication or only accept mail for local domains. Check Postfix: smtpd_relay_restrictions, Sendmail: relay-domains, Exchange: receive connectors.'
},
'starttls': {
'rfc': 'RFC 3207',
'title': 'SMTP STARTTLS Extension',
'tip': 'STARTTLS upgrades plain SMTP connections to encrypted TLS.',
'fix': 'Configure your mail server to advertise and support STARTTLS on port 25 and 587.'
},
'autodiscover': {
'rfc': 'MS-OXDSCLI',
'title': 'Outlook Autodiscover',
'tip': 'Autodiscover helps email clients automatically configure account settings.',
'fix': 'Configure autodiscover.domain.com or SRV record _autodiscover._tcp.domain pointing to your autodiscover service.'
},
'blacklist': {
'rfc': 'RFC 5782',
'title': 'DNS-Based Blacklists',
'tip': 'Being listed on blacklists causes email delivery failures.',
'fix': 'Check each blacklist for delisting procedures. Fix underlying issues (spam, open relay, compromised accounts).'
},
'headers': {
'rfc': 'RFC 5322',
'title': 'Internet Message Format',
'tip': 'Email headers must include From, To, Date, and Message-ID for proper delivery.',
'fix': 'Ensure your mail server adds all required headers with correct formatting.'
}
}
app = Flask(__name__)
def generate_test_id():
"""Generate a unique test ID."""
return uuid.uuid4().hex[:12]
def get_hostname():
"""Get the server hostname from DOMAIN env var."""
return DOMAIN
class MailHandler:
"""Handle incoming emails."""
async def handle_RCPT(self, server, session, envelope, address, rcpt_options):
"""Validate recipient address - only accept mail for configured domains."""
# Parse the recipient address
if '@' not in address:
return '550 Invalid address format'
local_part, domain = address.rsplit('@', 1)
domain = domain.lower().rstrip('>')
# Security: Only accept emails for allowed domains (prevents open relay)
if domain not in ALLOWED_DOMAINS:
print(f'[SMTP] Relay rejected: {address} (domain {domain} not allowed)')
return '550 Relay is prohibited'
# Accept the recipient
envelope.rcpt_tos.append(address)
return '250 OK'
async def handle_DATA(self, server, session, envelope):
"""Process received email."""
# Rate limiting check
sender_ip = session.peer[0] if session.peer else 'unknown'
sender_email = envelope.mail_from or 'unknown'
sender_domain = sender_email.split('@')[1] if '@' in sender_email else 'unknown'
allowed, reason = check_rate_limit(sender_ip, sender_email, sender_domain)
if not allowed:
print(f'[SMTP] Rate limit: {reason} from {sender_ip}')
return f'451 {reason}'
record_rate_limit(sender_ip, sender_email, sender_domain)
test_id = None
# Extract test_id from recipient
for rcpt in envelope.rcpt_tos:
local_part = rcpt.split('@')[0]
if local_part in test_addresses or len(local_part) == 12:
test_id = local_part
break
if not test_id:
test_id = generate_test_id()
# Parse email
parser = BytesParser(policy=policy.default)
msg = parser.parsebytes(envelope.content)
# Extract email data
email_data = {
'from': envelope.mail_from,
'to': envelope.rcpt_tos,
'subject': msg.get('Subject', '(No Subject)'),
'date': msg.get('Date', ''),
'message_id': msg.get('Message-ID', ''),
'headers': dict(msg.items()),
'body_plain': '',
'body_html': '',
'raw': envelope.content.decode('utf-8', errors='replace'),
'peer': session.peer,
'received_at': datetime.now().isoformat(),
}
# Extract body
if msg.is_multipart():
for part in msg.walk():
content_type = part.get_content_type()
if content_type == 'text/plain':
email_data['body_plain'] = part.get_content()
elif content_type == 'text/html':
email_data['body_html'] = part.get_content()
else:
content_type = msg.get_content_type()
content = msg.get_content()
if content_type == 'text/html':
email_data['body_html'] = content
else:
email_data['body_plain'] = content
# Perform analysis
analysis = await analyze_email(envelope, msg, session)
# Store email and analysis
emails_store[test_id] = {
'email': email_data,
'analysis': analysis,
'timestamp': datetime.now().isoformat()
}
# Persist to MongoDB
if MONGO_AVAILABLE and reports_collection is not None:
try:
reports_collection.update_one(
{'_id': test_id},
{'$set': {
'email': email_data,
'analysis': analysis,
'timestamp': datetime.now(),
'type': 'email_test'
}},
upsert=True
)
print(f"[MONGO] Saved report for test_id: {test_id}")
except Exception as e:
print(f"[MONGO] Error saving report: {e}")
print(f"[SMTP] Received email for test_id: {test_id}")
# Send async Telegram notification (non-blocking)
asyncio.create_task(send_telegram_notification(test_id, email_data, analysis))
# Check if this is a callback test - send email back to sender
if test_id.startswith('cb_') and envelope.mail_from:
callback_id = test_id
smtp_receive_logs = [
f"CONNECT from {session.peer}",
f"MAIL FROM: {envelope.mail_from}",
f"RCPT TO: {', '.join(envelope.rcpt_tos)}",
f"DATA received ({len(envelope.content)} bytes)",
f"Accepted at {datetime.now().isoformat()}"
]
if callback_id in callback_tests:
callback_tests[callback_id]['status'] = 'received'
callback_tests[callback_id]['receive_logs'] = smtp_receive_logs
callback_tests[callback_id]['received_at'] = datetime.now().isoformat()
def send_callback_async():
try:
# Get receipt options from callback test settings
cb_test = callback_tests.get(callback_id, {})
req_delivery = cb_test.get('request_delivery_receipt', False)
req_read = cb_test.get('request_read_receipt', False)
result = send_callback_email(
envelope.mail_from, callback_id, email_data.get('subject', ''),
smtp_receive_logs, req_delivery, req_read
)
if callback_id in callback_tests:
callback_tests[callback_id]['status'] = 'completed' if result['success'] else 'send_failed'
callback_tests[callback_id]['send_result'] = result
except Exception as e:
if callback_id in callback_tests:
callback_tests[callback_id]['status'] = 'error'
callback_tests[callback_id]['error'] = str(e)
Thread(target=send_callback_async, daemon=True).start()
print(f"[SMTP] Callback test {callback_id} - will respond to {envelope.mail_from}")
return '250 Message accepted for delivery'
async def analyze_email(envelope, msg, session):
"""Analyze email for deliverability factors."""
analysis = {
'score': 10.0, # Start with perfect score
'checks': [],
'warnings': [],
'errors': []
}
sender_domain = envelope.mail_from.split('@')[-1] if '@' in envelope.mail_from else ''
# 1. Check basic headers
required_headers = ['From', 'To', 'Subject', 'Date', 'Message-ID']
for header in required_headers:
if msg.get(header):
analysis['checks'].append({
'name': f'{header} Header',
'status': 'pass',
'message': f'{header} header is present'
})
else:
analysis['score'] -= 0.5
analysis['warnings'].append(f'Missing {header} header')
analysis['checks'].append({
'name': f'{header} Header',
'status': 'warning',
'message': f'{header} header is missing'
})
# 2. Check SPF (if DNS available)
if DNS_AVAILABLE and sender_domain:
spf_result = await check_spf(sender_domain, session.peer[0])
analysis['checks'].append(spf_result)
if spf_result['status'] == 'fail':
analysis['score'] -= 2.0
analysis['errors'].append('SPF check failed')
elif spf_result['status'] == 'warning':
analysis['score'] -= 1.0
analysis['warnings'].append('SPF record not found')
# 3. Check DKIM
dkim_result = check_dkim(envelope.content, msg)
analysis['checks'].append(dkim_result)
if dkim_result['status'] == 'fail':
analysis['score'] -= 2.0
analysis['errors'].append('DKIM verification failed')
elif dkim_result['status'] == 'warning':
analysis['score'] -= 1.0
analysis['warnings'].append('No DKIM signature found')
# 4. Check DMARC (if DNS available)
if DNS_AVAILABLE and sender_domain:
dmarc_result = await check_dmarc(sender_domain)
analysis['checks'].append(dmarc_result)
if dmarc_result['status'] == 'warning':
analysis['score'] -= 0.5
analysis['warnings'].append('No DMARC record found')
# 5. Check reverse DNS
if session.peer:
rdns_result = await check_reverse_dns(session.peer[0])
analysis['checks'].append(rdns_result)
if rdns_result['status'] == 'fail':
analysis['score'] -= 1.0
analysis['warnings'].append('No reverse DNS for sender IP')
# 6. Check for spam-like content
spam_check = check_spam_content(msg)
analysis['checks'].append(spam_check)
if spam_check['status'] == 'warning':
analysis['score'] -= spam_check.get('deduction', 0.5)
analysis['warnings'].append('Potential spam indicators found')
# 7. Check HTML/Plain text ratio
html_check = check_html_content(msg)
analysis['checks'].append(html_check)
if html_check['status'] == 'warning':
analysis['score'] -= 0.5
analysis['warnings'].append(html_check['message'])
# 8. Check for internal IP leaks in headers
ip_leak_check = check_internal_ips(msg)
analysis['checks'].append(ip_leak_check)
if ip_leak_check['status'] == 'warning':
analysis['score'] -= ip_leak_check.get('deduction', 0.5)
analysis['warnings'].append('Internal IP addresses exposed in headers')
# 9. Check for obsolete server versions
version_check = check_server_versions(msg)
analysis['checks'].append(version_check)
if version_check['status'] == 'warning':
analysis['score'] -= version_check.get('deduction', 0.5)
analysis['warnings'].append('Outdated mail software detected')
# Ensure score doesn't go below 0
analysis['score'] = max(0, analysis['score'])
return analysis
async def check_spf(domain, sender_ip):
"""Check SPF record for the sender domain."""
try:
answers = dns.resolver.resolve(domain, 'TXT')
spf_record = None
for rdata in answers:
txt = str(rdata).strip('"')
if txt.startswith('v=spf1'):
spf_record = txt
break
if spf_record:
return {
'name': 'SPF Record',
'status': 'pass',
'message': f'SPF record found',
'record': spf_record
}
else:
return {
'name': 'SPF Record',
'status': 'warning',
'message': 'No SPF record found for sender domain'
}
except Exception as e:
return {
'name': 'SPF Record',
'status': 'warning',
'message': f'Could not check SPF: {str(e)}'
}
def check_dkim(raw_email, msg):
"""Check DKIM signature."""
dkim_header = msg.get('DKIM-Signature')
if not dkim_header:
return {
'name': 'DKIM Signature',
'status': 'warning',
'message': 'No DKIM signature found'
}
# Parse DKIM signature to extract selector and domain
def parse_dkim_sig(sig):
result = {}
# Normalize: remove line breaks and extra spaces
sig = ' '.join(sig.split())
for part in sig.split(';'):
part = part.strip()
if '=' in part:
key, value = part.split('=', 1)
result[key.strip()] = value.strip()
return result
def diagnose_dkim_dns(selector, domain):
"""Fetch and validate DKIM DNS record to diagnose issues."""
try:
dkim_domain = f'{selector}._domainkey.{domain}'
resolver = dns.resolver.Resolver()
resolver.timeout = 5
resolver.lifetime = 5
answers = resolver.resolve(dkim_domain, 'TXT')
for rdata in answers:
raw_parts = [s.decode() if isinstance(s, bytes) else str(s) for s in rdata.strings]
raw_txt = ''.join(raw_parts)
parsed = parse_dkim_record(raw_txt)
validation = validate_dkim_record(raw_txt, parsed)
return {
'dns_found': True,
'domain': dkim_domain,
'raw_record': raw_txt[:200] + '...' if len(raw_txt) > 200 else raw_txt,
'validation': validation
}
except dns.resolver.NXDOMAIN:
return {'dns_found': False, 'error': f'No DNS record at {selector}._domainkey.{domain}'}
except dns.resolver.NoAnswer:
return {'dns_found': False, 'error': f'No TXT record at {selector}._domainkey.{domain}'}
except Exception as e:
return {'dns_found': False, 'error': str(e)}
if DKIM_AVAILABLE:
try:
valid = dkim.verify(raw_email)
if valid:
return {
'name': 'DKIM Signature',
'status': 'pass',
'message': 'DKIM signature is valid',
'record': dkim_header[:100] + '...' if len(dkim_header) > 100 else dkim_header
}
else:
# Verification failed - diagnose why
sig_parts = parse_dkim_sig(dkim_header)
selector = sig_parts.get('s', '')
domain = sig_parts.get('d', '')
diagnosis = None
diagnosis_msg = ''
if selector and domain:
diagnosis = diagnose_dkim_dns(selector, domain)
if diagnosis.get('dns_found'):
validation = diagnosis.get('validation', {})
if validation.get('errors'):
diagnosis_msg = ' | DNS record issues: ' + '; '.join(validation['errors'])
elif validation.get('warnings'):
diagnosis_msg = ' | DNS warnings: ' + '; '.join(validation['warnings'])
else:
diagnosis_msg = f" | {diagnosis.get('error', 'DNS lookup failed')}"
return {
'name': 'DKIM Signature',
'status': 'fail',
'message': f'DKIM signature verification failed{diagnosis_msg}',
'record': dkim_header[:100] + '...' if len(dkim_header) > 100 else dkim_header,
'selector': selector,
'domain': domain,
'diagnosis': diagnosis
}