-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsim_card_decoder.py
More file actions
2184 lines (1838 loc) · 95.5 KB
/
sim_card_decoder.py
File metadata and controls
2184 lines (1838 loc) · 95.5 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
"""
SIM Card Data Decoder - Professional Forensic Analysis Tool
This tool provides comprehensive analysis of ICCID and IMSI numbers for forensic purposes.
It includes format conversion utilities, professional reporting, and educational context.
Educational Disclaimer:
This tool is designed for educational and forensic analysis purposes only.
Users are responsible for ensuring compliance with all applicable laws and regulations.
"""
import os
import sys
import csv
import json
import time
import uuid
import logging
import argparse
from typing import Dict, List, Any, Optional, Tuple
from datetime import datetime
from pathlib import Path
class BatchProcessor:
"""
Batch processor for handling multiple ICCID/IMSI analyses.
Provides efficient processing of multiple identifiers with comprehensive
error handling and professional reporting capabilities.
"""
def __init__(self, decoder: 'SIMCardDecoder'):
"""Initialize batch processor with decoder instance."""
self.decoder = decoder
self.batch_stats = {
'total_processed': 0,
'successful_analyses': 0,
'failed_analyses': 0,
'iccid_count': 0,
'imsi_count': 0,
'start_time': time.time(),
'end_time': None
}
def process_file(self, filepath: str) -> None:
"""Process a file containing multiple ICCIDs/IMSIs."""
try:
# Read and parse input file
identifiers = self._parse_input_file(filepath)
if not identifiers:
print("❌ No valid identifiers found in batch file.")
return
# Process each identifier
for identifier in identifiers:
self._process_identifier(identifier)
# Update batch stats
self.batch_stats['end_time'] = time.time()
# Generate reports
self._generate_batch_reports()
# Display summary
self._display_batch_summary()
except Exception as e:
print(f"❌ Batch processing failed: {e}")
if self.decoder.log_level == 'DEBUG':
import traceback
traceback.print_exc()
raise
def _parse_input_file(self, filepath: str) -> List[str]:
"""Parse input file and extract valid identifiers."""
identifiers = []
try:
with open(filepath, 'r') as f:
for line in f:
identifier = line.strip()
if identifier and not identifier.startswith('#'):
if (self.decoder.validate_iccid(identifier) or
self.decoder.validate_imsi(identifier)):
identifiers.append(identifier)
except Exception as e:
print(f"❌ Error reading file: {e}")
raise
return identifiers
def _process_identifier(self, identifier: str) -> None:
"""Process a single identifier and update stats."""
self.batch_stats['total_processed'] += 1
try:
if self.decoder.validate_iccid(identifier):
self.decoder.analyze_iccid(identifier)
self.batch_stats['iccid_count'] += 1
self.batch_stats['successful_analyses'] += 1
elif self.decoder.validate_imsi(identifier):
self.decoder.analyze_imsi(identifier)
self.batch_stats['imsi_count'] += 1
self.batch_stats['successful_analyses'] += 1
else:
self.batch_stats['failed_analyses'] += 1
except Exception as e:
self.batch_stats['failed_analyses'] += 1
if self.decoder.log_level == 'DEBUG':
print(f"❌ Error processing {identifier}: {e}")
def _generate_batch_reports(self) -> None:
"""Generate professional reports for batch processing."""
try:
# Generate detailed report
self.decoder.generate_professional_report(
report_type="detailed",
export_to_file=True
)
# Generate CSV report
self.decoder.generate_professional_report(
report_type="csv",
export_to_file=True
)
except Exception as e:
print(f"❌ Error generating reports: {e}")
if self.decoder.log_level == 'DEBUG':
import traceback
traceback.print_exc()
def _display_batch_summary(self) -> None:
"""Display batch processing summary."""
duration = self.batch_stats['end_time'] - self.batch_stats['start_time']
success_rate = (self.batch_stats['successful_analyses'] /
self.batch_stats['total_processed'] * 100)
print("\n📊 Batch Processing Summary:")
print(f" Total Processed: {self.batch_stats['total_processed']}")
print(f" ICCIDs: {self.batch_stats['iccid_count']}")
print(f" IMSIs: {self.batch_stats['imsi_count']}")
print(f" Success Rate: {success_rate:.1f}%")
print(f" Duration: {duration:.2f} seconds")
print(f" Reports Generated: 2 (Detailed + CSV)")
class ForensicReportGenerator:
"""
Professional report generator for forensic analysis results.
Provides comprehensive reporting capabilities with multiple formats
and professional formatting suitable for forensic documentation.
"""
def __init__(self, session_id: str, logger: logging.Logger):
"""Initialize report generator with session ID and logger."""
self.session_id = session_id
self.logger = logger
self.reports_dir = os.path.join(os.getcwd(), "reports")
os.makedirs(self.reports_dir, exist_ok=True)
def generate_console_report(self, results: List[Dict[str, Any]],
cross_validation: Optional[Dict[str, Any]] = None) -> str:
"""Generate console-formatted report."""
report = []
report.append("\n" + "="*80)
report.append("SIM CARD DATA DECODER - FORENSIC ANALYSIS REPORT")
report.append("="*80)
report.append(f"Session ID: {self.session_id}")
report.append(f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
report.append("\n")
for result in results:
report.append("-"*80)
if result['type'] == 'ICCID':
self._add_iccid_section(report, result)
else:
self._add_imsi_section(report, result)
if cross_validation:
report.append("\n" + "="*80)
report.append("CROSS-VALIDATION ANALYSIS")
report.append("="*80)
self._add_cross_validation_section(report, cross_validation)
return "\n".join(report)
def generate_detailed_report(self, results: List[Dict[str, Any]],
cross_validation: Optional[Dict[str, Any]] = None) -> str:
"""Generate detailed forensic report."""
report = []
report.append("SIM CARD DATA DECODER - DETAILED FORENSIC ANALYSIS REPORT")
report.append("="*80)
report.append(f"Session ID: {self.session_id}")
report.append(f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
report.append("\n")
for result in results:
report.append("\n" + "="*80)
if result['type'] == 'ICCID':
self._add_detailed_iccid_section(report, result)
else:
self._add_detailed_imsi_section(report, result)
if cross_validation:
report.append("\n" + "="*80)
report.append("CROSS-VALIDATION ANALYSIS")
report.append("="*80)
self._add_detailed_cross_validation_section(report, cross_validation)
return "\n".join(report)
def generate_csv_report(self, results: List[Dict[str, Any]]) -> str:
"""Generate CSV-formatted report."""
report = []
headers = [
"Type", "Identifier", "Country", "Operator", "Confidence",
"Analysis Time", "Session ID"
]
report.append(",".join(headers))
for result in results:
if result['type'] == 'ICCID':
row = [
"ICCID",
result['input'],
result['components']['country_code']['country'],
result['components']['issuer_identifier']['operator'],
result['interpretation']['forensic_confidence'],
result['analysis_timestamp'],
self.session_id
]
else:
row = [
"IMSI",
result['input'],
result['components']['mcc']['country'],
result['components']['mnc']['operator'],
result['interpretation']['forensic_confidence'],
result['analysis_timestamp'],
self.session_id
]
report.append(",".join(row))
return "\n".join(report)
def generate_session_report(self, summary: Dict[str, Any]) -> str:
"""Generate session summary report."""
report = []
report.append("SIM CARD DATA DECODER - SESSION SUMMARY REPORT")
report.append("="*80)
report.append(f"Session ID: {self.session_id}")
report.append(f"Start Time: {summary['start_time']}")
report.append(f"End Time: {summary['end_time']}")
report.append(f"Duration: {summary['duration_seconds']:.2f} seconds")
report.append(f"Analyses Performed: {summary['analyses_performed']}")
report.append("\n")
if 'batch_stats' in summary:
report.append("Batch Processing Statistics:")
report.append(f" Total Processed: {summary['batch_stats']['total_processed']}")
report.append(f" Successful: {summary['batch_stats']['successful_analyses']}")
report.append(f" Failed: {summary['batch_stats']['failed_analyses']}")
report.append(f" ICCIDs: {summary['batch_stats']['iccid_count']}")
report.append(f" IMSIs: {summary['batch_stats']['imsi_count']}")
return "\n".join(report)
def export_to_file(self, content: str, filename: str) -> str:
"""Export report content to file."""
filepath = os.path.join(self.reports_dir, filename)
try:
with open(filepath, 'w', encoding='utf-8') as f:
f.write(content)
self.logger.info(f"Report exported to: {filepath}")
return filepath
except Exception as e:
self.logger.error(f"Error exporting report: {e}")
raise
def _add_iccid_section(self, report: List[str], result: Dict[str, Any]) -> None:
"""Add ICCID analysis section to report."""
report.append(f"ICCID Analysis: {result['input']}")
report.append(f"Country: {result['components']['country_code']['country']}")
report.append(f"Operator: {result['components']['issuer_identifier']['operator']}")
report.append(f"Confidence: {result['interpretation']['forensic_confidence']}")
def _add_imsi_section(self, report: List[str], result: Dict[str, Any]) -> None:
"""Add IMSI analysis section to report."""
report.append(f"IMSI Analysis: {result['input']}")
report.append(f"Country: {result['components']['mcc']['country']}")
report.append(f"Operator: {result['components']['mnc']['operator']}")
report.append(f"Confidence: {result['interpretation']['forensic_confidence']}")
def _add_cross_validation_section(self, report: List[str],
cross_validation: Dict[str, Any]) -> None:
"""Add cross-validation section to report."""
report.append("Cross-Validation Results:")
report.append(f"Match: {cross_validation['match']}")
report.append(f"Confidence: {cross_validation['confidence']}")
if cross_validation['notes']:
report.append("\nNotes:")
for note in cross_validation['notes']:
report.append(f"• {note}")
def _add_detailed_iccid_section(self, report: List[str], result: Dict[str, Any]) -> None:
"""Add detailed ICCID analysis section to report."""
report.append(f"ICCID Analysis: {result['input']}")
report.append("\nComponents:")
report.append(f" Country Code: {result['components']['country_code']['code']}")
report.append(f" Country: {result['components']['country_code']['country']}")
report.append(f" Issuer Identifier: {result['components']['issuer_identifier']['code']}")
report.append(f" Operator: {result['components']['issuer_identifier']['operator']}")
report.append(f" Individual Account: {result['components']['individual_account']}")
report.append(f" Checksum: {result['components']['checksum']}")
report.append("\nInterpretation:")
report.append(f" Forensic Confidence: {result['interpretation']['forensic_confidence']}")
report.append(f" Validation Status: {result['interpretation']['validation_status']}")
if result['interpretation']['notes']:
report.append("\nNotes:")
for note in result['interpretation']['notes']:
report.append(f"• {note}")
def _add_detailed_imsi_section(self, report: List[str], result: Dict[str, Any]) -> None:
"""Add detailed IMSI analysis section to report."""
report.append(f"IMSI Analysis: {result['input']}")
report.append("\nComponents:")
report.append(f" MCC: {result['components']['mcc']['code']}")
report.append(f" Country: {result['components']['mcc']['country']}")
report.append(f" MNC: {result['components']['mnc']['code']}")
report.append(f" Operator: {result['components']['mnc']['operator']}")
report.append(f" MSIN: {result['components']['msin']}")
report.append("\nInterpretation:")
report.append(f" Forensic Confidence: {result['interpretation']['forensic_confidence']}")
report.append(f" Validation Status: {result['interpretation']['validation_status']}")
if result['interpretation']['notes']:
report.append("\nNotes:")
for note in result['interpretation']['notes']:
report.append(f"• {note}")
def _add_detailed_cross_validation_section(self, report: List[str],
cross_validation: Dict[str, Any]) -> None:
"""Add detailed cross-validation section to report."""
report.append("Cross-Validation Analysis")
report.append("\nResults:")
report.append(f" Match: {cross_validation['match']}")
report.append(f" Confidence: {cross_validation['confidence']}")
if cross_validation['details']:
report.append("\nDetails:")
for key, value in cross_validation['details'].items():
report.append(f" {key}: {value}")
if cross_validation['notes']:
report.append("\nNotes:")
for note in cross_validation['notes']:
report.append(f"• {note}")
class SIMCardDecoder:
"""
Professional SIM Card Data Decoder for Digital Forensics
This class provides comprehensive analysis of ICCID and IMSI numbers commonly
encountered in mobile device forensic examinations. It breaks down these
identifiers into their constituent components and provides educational
interpretations of each part.
The tool maintains audit logs and session tracking for forensic accountability
and can operate in both interactive and batch processing modes.
"""
def __init__(self, log_level: str = "INFO", quiet_mode: bool = False):
"""
Initialize the SIM Card Decoder with logging and session management.
Args:
log_level (str): Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
quiet_mode (bool): If True, suppress console output except errors
Forensic Purpose:
Establishes audit trail and session tracking for forensic accountability.
Each decoder instance maintains its own session ID for correlation of
analysis results with examination records.
"""
self.session_id = str(uuid.uuid4())
self.session_start = datetime.now()
self.quiet_mode = quiet_mode
self.analysis_count = 0
self.analysis_results = [] # Store all analysis results for reporting
# Initialize logging system
self._setup_logging(log_level)
# Initialize reporting system
self.report_generator = ForensicReportGenerator(self.session_id, self.logger)
# Log session initialization
self.logger.info(f"SIM Card Decoder session initialized - Session ID: {self.session_id}")
self.logger.info(f"Session start time: {self.session_start.isoformat()}")
if not quiet_mode:
self._display_disclaimer()
def _setup_logging(self, log_level: str) -> None:
"""
Configure comprehensive logging system for forensic audit trail.
Args:
log_level (str): Desired logging level
Forensic Purpose:
Creates timestamped log files for audit purposes. All operations,
inputs, and results are logged to maintain chain of custody and
enable review of analysis procedures.
"""
# Create logs directory if it doesn't exist
log_dir = "logs"
if not os.path.exists(log_dir):
os.makedirs(log_dir)
# Create timestamped log file
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
log_filename = os.path.join(log_dir, f"sim_decoder_{timestamp}_{self.session_id[:8]}.log")
# Configure logger
self.logger = logging.getLogger(f"SIMDecoder_{self.session_id[:8]}")
self.logger.setLevel(getattr(logging, log_level.upper()))
# File handler for audit trail
file_handler = logging.FileHandler(log_filename)
file_handler.setLevel(logging.DEBUG)
# Console handler for user feedback
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.WARNING if self.quiet_mode else logging.INFO)
# Detailed formatter for forensic logging
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - Session:%(session_id)s - %(message)s'
)
# Add session ID to log records
file_handler.setFormatter(formatter)
console_handler.setFormatter(formatter)
# Add custom filter to inject session ID
class SessionFilter(logging.Filter):
def __init__(self, session_id):
self.session_id = session_id
def filter(self, record):
record.session_id = self.session_id[:8]
return True
session_filter = SessionFilter(self.session_id)
file_handler.addFilter(session_filter)
console_handler.addFilter(session_filter)
self.logger.addHandler(file_handler)
self.logger.addHandler(console_handler)
self.logger.info(f"Logging initialized - Log file: {log_filename}")
def _display_disclaimer(self) -> None:
"""
Display professional forensic disclaimer to user.
Forensic Purpose:
Ensures users understand the limitations and proper use of the tool
in forensic contexts. Emphasizes the need for validation through
official channels.
"""
disclaimer = """
╔══════════════════════════════════════════════════════════════════════════════╗
║ FORENSIC DISCLAIMER ║
╠══════════════════════════════════════════════════════════════════════════════╣
║ ║
║ This tool is provided for EDUCATIONAL and INVESTIGATIVE purposes only. ║
║ ║
║ ⚠️ IMPORTANT VALIDATION REQUIREMENTS: ║
║ ║
║ • All results MUST be validated through official carrier databases ║
║ • Cross-reference findings with authoritative telecommunications sources ║
║ • Verify interpretations before use in legal proceedings ║
║ • Document all validation steps in your forensic report ║
║ ║
║ This tool provides educational interpretations of SIM card data structures ║
║ but does not guarantee accuracy for evidential purposes. ║
║ ║
╚══════════════════════════════════════════════════════════════════════════════╝
"""
print(disclaimer)
def validate_iccid(self, iccid: str) -> bool:
"""
Validate ICCID format and structure.
Args:
iccid (str): ICCID number to validate
Returns:
bool: True if ICCID appears valid, False otherwise
Forensic Purpose:
Ensures input data conforms to expected ICCID format standards
before analysis. Invalid formats may indicate data corruption,
extraction errors, or non-standard implementations.
"""
if not iccid:
self.logger.error("ICCID validation failed: Empty input")
return False
# Remove spaces and convert to string
iccid_clean = str(iccid).replace(" ", "").replace("-", "")
# ICCID should be 19-20 digits
if not re.match(r'^[0-9]{19,20}$', iccid_clean):
self.logger.error(f"ICCID validation failed: Invalid format - {iccid}")
return False
# ICCID typically starts with 89 (telecommunications identifier)
if not iccid_clean.startswith('89'):
self.logger.warning(f"ICCID format warning: Does not start with standard '89' prefix - {iccid}")
self.logger.info(f"ICCID validation successful: {iccid}")
return True
def validate_imsi(self, imsi: str) -> bool:
"""
Validate IMSI format and structure.
Args:
imsi (str): IMSI number to validate
Returns:
bool: True if IMSI appears valid, False otherwise
Forensic Purpose:
Ensures input data conforms to expected IMSI format standards.
IMSI validation is critical for proper MCC/MNC extraction and
subscriber identification in forensic investigations.
"""
if not imsi:
self.logger.error("IMSI validation failed: Empty input")
return False
# Remove spaces and convert to string
imsi_clean = str(imsi).replace(" ", "").replace("-", "")
# IMSI should be typically 15 digits (can be 14-15)
if not re.match(r'^[0-9]{14,15}$', imsi_clean):
self.logger.error(f"IMSI validation failed: Invalid format - {imsi}")
return False
self.logger.info(f"IMSI validation successful: {imsi}")
return True
def _get_country_database(self) -> Dict[str, Dict[str, str]]:
"""
Get comprehensive country code database for ICCID analysis.
Returns:
Dict[str, Dict[str, str]]: Country code mappings
Forensic Purpose:
Provides authoritative country code mappings for geographic
identification of SIM card origin. Critical for determining
jurisdiction and carrier registration location.
"""
return {
# North America
"1": {"country": "United States", "region": "North America"},
"302": {"country": "Canada", "region": "North America"},
# Europe
"44": {"country": "United Kingdom", "region": "Europe"},
"49": {"country": "Germany", "region": "Europe"},
"33": {"country": "France", "region": "Europe"},
"39": {"country": "Italy", "region": "Europe"},
"34": {"country": "Spain", "region": "Europe"},
"31": {"country": "Netherlands", "region": "Europe"},
"46": {"country": "Sweden", "region": "Europe"},
"47": {"country": "Norway", "region": "Europe"},
"45": {"country": "Denmark", "region": "Europe"},
"41": {"country": "Switzerland", "region": "Europe"},
"43": {"country": "Austria", "region": "Europe"},
"32": {"country": "Belgium", "region": "Europe"},
# Asia Pacific
"81": {"country": "Japan", "region": "Asia Pacific"},
"86": {"country": "China", "region": "Asia Pacific"},
"82": {"country": "South Korea", "region": "Asia Pacific"},
"65": {"country": "Singapore", "region": "Asia Pacific"},
"61": {"country": "Australia", "region": "Asia Pacific"},
"505": {"country": "New Zealand", "region": "Asia Pacific"},
"91": {"country": "India", "region": "Asia Pacific"},
# Other regions
"7": {"country": "Russia", "region": "Europe/Asia"},
"55": {"country": "Brazil", "region": "South America"},
"52": {"country": "Mexico", "region": "North America"},
"27": {"country": "South Africa", "region": "Africa"},
"20": {"country": "Egypt", "region": "Africa/Middle East"},
"966": {"country": "Saudi Arabia", "region": "Middle East"},
}
def _get_uk_operator_database(self) -> Dict[str, Dict[str, str]]:
"""
Get UK network operator database for detailed carrier identification.
Returns:
Dict[str, Dict[str, str]]: UK operator mappings
Forensic Purpose:
Enables precise identification of UK mobile network operators
from ICCID issuer codes. Critical for UK-based investigations
and carrier liaison requirements.
"""
return {
"01": {"operator": "Vodafone UK", "type": "MNO", "network_code": "15"},
"02": {"operator": "O2 UK", "type": "MNO", "network_code": "10"},
"11": {"operator": "O2 UK", "type": "MNO", "network_code": "11"},
"20": {"operator": "Three UK", "type": "MNO", "network_code": "20"},
"30": {"operator": "EE", "type": "MNO", "network_code": "30"},
"31": {"operator": "EE", "type": "MNO", "network_code": "31"},
"32": {"operator": "EE", "type": "MNO", "network_code": "32"},
"33": {"operator": "EE", "type": "MNO", "network_code": "33"},
"34": {"operator": "EE", "type": "MNO", "network_code": "34"},
"50": {"operator": "JT (Jersey Telecom)", "type": "Regional", "network_code": "50"},
"55": {"operator": "Sure (Guernsey)", "type": "Regional", "network_code": "55"},
"58": {"operator": "Manx Telecom", "type": "Regional", "network_code": "58"},
"91": {"operator": "Vodafone UK", "type": "MNO", "network_code": "91"},
"94": {"operator": "Hutchison 3G UK", "type": "MNO", "network_code": "94"},
}
def _get_international_operator_database(self) -> Dict[str, Dict[str, str]]:
"""
Get international operator database for global carrier identification.
Returns:
Dict[str, Dict[str, str]]: International operator mappings
Forensic Purpose:
Provides identification capabilities for major international
mobile network operators. Essential for cross-border investigations
and international carrier coordination.
"""
return {
# US Operators
"015": {"operator": "AT&T", "country": "USA", "type": "MNO"},
"016": {"operator": "T-Mobile USA", "country": "USA", "type": "MNO"},
"012": {"operator": "Verizon", "country": "USA", "type": "MNO"},
"120": {"operator": "Sprint", "country": "USA", "type": "MNO"},
# German Operators
"01": {"operator": "T-Mobile Germany", "country": "Germany", "type": "MNO"},
"02": {"operator": "Vodafone Germany", "country": "Germany", "type": "MNO"},
"03": {"operator": "E-Plus", "country": "Germany", "type": "MNO"},
"07": {"operator": "O2 Germany", "country": "Germany", "type": "MNO"},
# French Operators
"01": {"operator": "Orange France", "country": "France", "type": "MNO"},
"02": {"operator": "SFR", "country": "France", "type": "MNO"},
"03": {"operator": "Bouygues Telecom", "country": "France", "type": "MNO"},
"10": {"operator": "Free Mobile", "country": "France", "type": "MNO"},
# Other major operators
"001": {"operator": "NTT DoCoMo", "country": "Japan", "type": "MNO"},
"003": {"operator": "KDDI", "country": "Japan", "type": "MNO"},
"004": {"operator": "SoftBank", "country": "Japan", "type": "MNO"},
}
def _validate_luhn_checksum(self, number: str) -> bool:
"""
Validate number using Luhn algorithm for checksum verification.
Args:
number (str): Number to validate
Returns:
bool: True if checksum is valid, False otherwise
Forensic Purpose:
Verifies mathematical integrity of ICCID using industry-standard
Luhn algorithm. Invalid checksums may indicate data corruption,
transcription errors, or potentially fraudulent identifiers.
"""
try:
# Remove any spaces or hyphens
clean_number = number.replace(" ", "").replace("-", "")
# Luhn algorithm implementation
total = 0
reverse_digits = clean_number[::-1]
for i, digit in enumerate(reverse_digits):
n = int(digit)
if i % 2 == 1: # Every second digit from the right
n = n * 2
if n > 9:
n = n // 10 + n % 10
total += n
is_valid = (total % 10) == 0
self.logger.debug(f"Luhn validation for {number}: {'VALID' if is_valid else 'INVALID'}")
return is_valid
except (ValueError, TypeError) as e:
self.logger.error(f"Luhn validation error for {number}: {e}")
return False
def _parse_iccid_components(self, iccid: str) -> Dict[str, Any]:
"""
Parse ICCID into its component parts with forensic analysis.
Args:
iccid (str): Clean ICCID number to parse
Returns:
Dict[str, Any]: Detailed component breakdown
Forensic Purpose:
Systematically breaks down ICCID structure to extract
investigatively relevant information including geographic
origin, carrier identification, and account details.
"""
clean_iccid = iccid.replace(" ", "").replace("-", "")
components = {}
# Major Industry Identifier (MII) - First 2 digits
components["mii"] = {
"value": clean_iccid[:2],
"description": "Major Industry Identifier",
"interpretation": "Telecommunications" if clean_iccid[:2] == "89" else "Non-standard MII"
}
# Variable length parsing for Country Code and Issuer
remaining = clean_iccid[2:-1] # Exclude MII and check digit
# Try to identify country code (1-3 digits)
country_info = None
country_code = ""
issuer_start_pos = 0
country_db = self._get_country_database()
# Try 3-digit country codes first, then 2-digit, then 1-digit
for cc_length in [3, 2, 1]:
if len(remaining) >= cc_length:
test_cc = remaining[:cc_length]
if test_cc in country_db:
country_code = test_cc
country_info = country_db[test_cc]
issuer_start_pos = cc_length
break
components["country_code"] = {
"value": country_code,
"description": "Country Code",
"country": country_info["country"] if country_info else "Unknown",
"region": country_info["region"] if country_info else "Unknown"
}
# Issuer Identifier - remaining digits after country code
issuer_digits = remaining[issuer_start_pos:]
# For UK, try to match operator codes
operator_info = None
if country_code == "44" and len(issuer_digits) >= 2:
uk_operators = self._get_uk_operator_database()
issuer_code = issuer_digits[:2]
if issuer_code in uk_operators:
operator_info = uk_operators[issuer_code]
components["issuer_identifier"] = {
"value": issuer_digits[:4] if len(issuer_digits) >= 4 else issuer_digits,
"description": "Issuer Identifier Number",
"operator": operator_info["operator"] if operator_info else "Unknown",
"operator_type": operator_info["type"] if operator_info else "Unknown"
}
# Individual Account Identification
account_digits = issuer_digits[4:] if len(issuer_digits) > 4 else ""
components["account_identification"] = {
"value": account_digits,
"description": "Individual Account Identification",
"length": len(account_digits)
}
# Check Digit
components["check_digit"] = {
"value": clean_iccid[-1],
"description": "Luhn Check Digit",
"valid": self._validate_luhn_checksum(clean_iccid)
}
return components
def analyze_iccid(self, iccid: str) -> Dict[str, Any]:
"""
Analyze ICCID and break down into component parts.
Args:
iccid (str): ICCID number to analyze
Returns:
Dict[str, Any]: Analysis results with component breakdown
Forensic Purpose:
Breaks down ICCID into investigatively relevant components:
- Major Industry Identifier (MII)
- Country code for geographic origin
- Issuer identifier for carrier identification
- Individual account identification
- Luhn checksum validation for integrity verification
- Detects suspicious/test patterns and provides educational notes
"""
self.analysis_count += 1
self.logger.info(f"Starting ICCID analysis #{self.analysis_count}: {iccid}")
if not self.validate_iccid(iccid):
raise ValueError("Invalid ICCID format")
# Parse ICCID components
components = self._parse_iccid_components(iccid)
# Generate validation notes
validation_notes = []
educational_notes = []
references = [
"ITU-T E.118: ICCID structure and allocation (https://www.itu.int/rec/T-REC-E.118/en)",
"GSMA Official ICCID/IMSI Database (https://www.gsma.com/)",
]
# Check MII
if components["mii"]["value"] != "89":
validation_notes.append("⚠️ Non-standard MII: Expected '89' for telecommunications")
educational_notes.append("MII (Major Industry Identifier) should be '89' for telecom SIMs. Non-standard MII may indicate a test card, non-telecom card, or data entry error.")
# Check country code recognition
if components["country_code"]["country"] == "Unknown":
validation_notes.append("⚠️ Unrecognized country code")
educational_notes.append("Country code not found in ITU/GSMA databases. This may indicate a test SIM, a new allocation, or a data entry error. Cross-check with official sources.")
# Check Luhn validation
if not components["check_digit"]["valid"]:
validation_notes.append("❌ Invalid Luhn checksum - possible data corruption")
educational_notes.append("Luhn checksum failure may indicate a corrupted, incomplete, or non-genuine ICCID. Forensic best practice: verify with original SIM or carrier records.")
else:
validation_notes.append("✅ Valid Luhn checksum")
# Check operator identification
if components["issuer_identifier"]["operator"] == "Unknown":
validation_notes.append("ℹ️ Operator not identified in database")
educational_notes.append("Operator code not found in GSMA/ITU databases. For further research, consult the GSMA online lookup or contact the suspected carrier. See: https://www.gsma.com/ for operator lists.")
else:
validation_notes.append(f"✅ Operator identified: {components['issuer_identifier']['operator']}")
# Suspicious/test ICCID patterns (e.g., all zeros, sequential, known test ranges)
suspicious_patterns = []
if iccid == "00000000000000000000":
suspicious_patterns.append("All zeros - likely test or placeholder")
if iccid == "12345678901234567890":
suspicious_patterns.append("Sequential digits - likely test or demo")
if len(set(iccid)) <= 3:
suspicious_patterns.append("Limited digit variety - potentially artificial/test ICCID")
if iccid.startswith("898600"): # Example: China test SIMs
suspicious_patterns.append("Prefix 898600 - known test SIM range (China)")
# Add more as needed
for pattern in suspicious_patterns:
validation_notes.append(f"⚠️ Suspicious pattern: {pattern}")
educational_notes.append(f"Pattern detected: {pattern}. Test/placeholder ICCIDs are common in device manufacturing, QA, and training environments.")
# Educational context
educational_notes.append("ICCID uniquely identifies a SIM card globally. It is critical for SIM provisioning, activation, and forensic chain-of-custody.")
educational_notes.append("Forensic best practice: Always cross-reference ICCID with carrier records and device IMEI for evidence integrity.")
# Generate interpretation
interpretation = {
"summary": f"ICCID from {components['country_code']['country']} issued by {components['issuer_identifier']['operator']}",
"geographic_origin": components["country_code"]["country"],
"region": components["country_code"]["region"],
"suspected_operator": components["issuer_identifier"]["operator"],
"integrity_status": "VALID" if components["check_digit"]["valid"] else "INVALID",
"forensic_confidence": "HIGH" if (
components["mii"]["value"] == "89" and
components["country_code"]["country"] != "Unknown" and
components["check_digit"]["valid"]
) else "MEDIUM" if components["check_digit"]["valid"] else "LOW",
"educational_notes": educational_notes,
"references": references
}
analysis_result = {
"input": iccid,
"type": "ICCID",
"session_id": self.session_id,
"analysis_timestamp": datetime.now().isoformat(),
"components": components,
"interpretation": interpretation,
"validation_notes": validation_notes
}
self.logger.info(f"ICCID analysis completed: {iccid} - Confidence: {interpretation['forensic_confidence']}")
# Store result for reporting
self.analysis_results.append(analysis_result)
return analysis_result
def _get_mcc_database(self) -> Dict[str, Dict[str, str]]:
"""
Get comprehensive Mobile Country Code database (ITU-T E.212 based).
Returns:
Dict[str, Dict[str, str]]: MCC mappings with country information
Forensic Purpose:
Provides authoritative Mobile Country Code mappings for identifying
subscriber's home country. Critical for determining jurisdiction,
roaming patterns, and cross-border investigations.
"""
return {
# Europe
"234": {"country": "United Kingdom", "region": "Europe", "iso": "GB"},
"235": {"country": "United Kingdom", "region": "Europe", "iso": "GB"},
"262": {"country": "Germany", "region": "Europe", "iso": "DE"},
"208": {"country": "France", "region": "Europe", "iso": "FR"},
"222": {"country": "Italy", "region": "Europe", "iso": "IT"},
"214": {"country": "Spain", "region": "Europe", "iso": "ES"},
"204": {"country": "Netherlands", "region": "Europe", "iso": "NL"},
"240": {"country": "Sweden", "region": "Europe", "iso": "SE"},
"242": {"country": "Norway", "region": "Europe", "iso": "NO"},
"238": {"country": "Denmark", "region": "Europe", "iso": "DK"},
"228": {"country": "Switzerland", "region": "Europe", "iso": "CH"},
"232": {"country": "Austria", "region": "Europe", "iso": "AT"},
"206": {"country": "Belgium", "region": "Europe", "iso": "BE"},
"244": {"country": "Finland", "region": "Europe", "iso": "FI"},
"272": {"country": "Ireland", "region": "Europe", "iso": "IE"},
"202": {"country": "Greece", "region": "Europe", "iso": "GR"},
"268": {"country": "Portugal", "region": "Europe", "iso": "PT"},
# North America
"310": {"country": "United States", "region": "North America", "iso": "US"},
"311": {"country": "United States", "region": "North America", "iso": "US"},
"312": {"country": "United States", "region": "North America", "iso": "US"},
"313": {"country": "United States", "region": "North America", "iso": "US"},
"314": {"country": "United States", "region": "North America", "iso": "US"},
"315": {"country": "United States", "region": "North America", "iso": "US"},
"316": {"country": "United States", "region": "North America", "iso": "US"},
"302": {"country": "Canada", "region": "North America", "iso": "CA"},
"334": {"country": "Mexico", "region": "North America", "iso": "MX"},
# Asia Pacific
"440": {"country": "Japan", "region": "Asia Pacific", "iso": "JP"},
"441": {"country": "Japan", "region": "Asia Pacific", "iso": "JP"},
"460": {"country": "China", "region": "Asia Pacific", "iso": "CN"},
"461": {"country": "China", "region": "Asia Pacific", "iso": "CN"},
"450": {"country": "South Korea", "region": "Asia Pacific", "iso": "KR"},
"525": {"country": "Singapore", "region": "Asia Pacific", "iso": "SG"},
"505": {"country": "Australia", "region": "Asia Pacific", "iso": "AU"},
"530": {"country": "New Zealand", "region": "Asia Pacific", "iso": "NZ"},
"404": {"country": "India", "region": "Asia Pacific", "iso": "IN"},
"405": {"country": "India", "region": "Asia Pacific", "iso": "IN"},
"520": {"country": "Thailand", "region": "Asia Pacific", "iso": "TH"},
"510": {"country": "Indonesia", "region": "Asia Pacific", "iso": "ID"},
"502": {"country": "Malaysia", "region": "Asia Pacific", "iso": "MY"},
# Other regions
"250": {"country": "Russia", "region": "Europe/Asia", "iso": "RU"},
"724": {"country": "Brazil", "region": "South America", "iso": "BR"},
"655": {"country": "South Africa", "region": "Africa", "iso": "ZA"},
"602": {"country": "Egypt", "region": "Africa/Middle East", "iso": "EG"},
"420": {"country": "Saudi Arabia", "region": "Middle East", "iso": "SA"},
"424": {"country": "United Arab Emirates", "region": "Middle East", "iso": "AE"},
# Test networks (important for forensic analysis)
"001": {"country": "Test Network", "region": "Test", "iso": "TEST"},
}
def _get_mnc_database(self) -> Dict[str, Dict[str, Dict[str, str]]]:
"""
Get comprehensive Mobile Network Code database for operator identification.
Returns:
Dict[str, Dict[str, Dict[str, str]]]: MNC mappings by country code
Forensic Purpose:
Enables precise identification of mobile network operators within
each country. Critical for determining carrier relationships,
roaming agreements, and network-specific investigation procedures.
"""
return {
# United Kingdom (234)
"234": {
"10": {"operator": "O2 UK", "type": "MNO", "network": "GSM/UMTS/LTE"},
"11": {"operator": "O2 UK", "type": "MNO", "network": "GSM/UMTS/LTE"},
"30": {"operator": "EE", "type": "MNO", "network": "GSM/UMTS/LTE"},