Repository navigation
Expand file tree
/
Copy pathAVRPS.py
More file actions
6675 lines (5660 loc) · 274 KB
/
Copy pathAVRPS.py
File metadata and controls
6675 lines (5660 loc) · 274 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
"""
Advanced Vulnerability Remediation and Patching System (AVRPS)
Enterprise-Grade Cross-Platform Vulnerability Management Tool
Features:
- Automated CVE detection and vulnerability scanning
- Intelligent patch management with rollback capability
- Multi-platform support (Linux, Windows, macOS)
- Comprehensive reporting and analytics
- Progress tracking with real-time updates
- Database-backed historical tracking
- API integration for CVE databases
- Configuration management
- Security compliance checking
"""
import os
import sys
import json
import time
import logging
import hashlib
import sqlite3
import argparse
import tempfile
import platform
import threading
import subprocess
import configparser
from abc import ABC, abstractmethod
from typing import Dict, List, Tuple, Optional, Any, Set, Union, Callable
from dataclasses import dataclass, field, asdict
from datetime import datetime, timedelta
from enum import Enum, IntEnum
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed
from pathlib import Path
from collections import defaultdict, OrderedDict
import signal
import traceback
import zipfile
import tarfile
import gzip
import shutil
import urllib.request
import urllib.error
import ssl
import random
import string
from xml.etree import ElementTree
import csv
import pickle
import re
# Third-party imports with graceful fallbacks
THIRD_PARTY_IMPORTS = {}
try:
import requests
from requests.adapters import HTTPAdapter
Retry = None
try:
# Newer versions of requests don't bundle urllib3
from urllib3.util.retry import Retry
except ImportError:
try:
# Fallback for older requests versions
import sys
if 'requests.packages.urllib3' in sys.modules or hasattr(requests, 'packages'):
from requests.packages.urllib3.util.retry import Retry # type: ignore
except (ImportError, AttributeError):
# Last resort: Retry will remain None
pass
THIRD_PARTY_IMPORTS['requests'] = True
except ImportError:
THIRD_PARTY_IMPORTS['requests'] = False
Retry = None
print("[WARNING] 'requests' module not available. Network features limited.")
try:
import yaml
THIRD_PARTY_IMPORTS['yaml'] = True
except ImportError:
THIRD_PARTY_IMPORTS['yaml'] = False
try:
from packaging import version
THIRD_PARTY_IMPORTS['packaging'] = True
except ImportError:
THIRD_PARTY_IMPORTS['packaging'] = False
try:
import psutil
THIRD_PARTY_IMPORTS['psutil'] = True
except ImportError:
THIRD_PARTY_IMPORTS['psutil'] = False
try:
import tqdm
THIRD_PARTY_IMPORTS['tqdm'] = True
except ImportError:
THIRD_PARTY_IMPORTS['tqdm'] = False
try:
import colorama
from colorama import Fore, Back, Style
colorama.init(autoreset=True)
THIRD_PARTY_IMPORTS['colorama'] = True
except ImportError:
# Create mock color classes if colorama is not available
class Fore:
BLACK = RED = GREEN = YELLOW = BLUE = MAGENTA = CYAN = WHITE = RESET = ''
class Back:
BLACK = RED = GREEN = YELLOW = BLUE = MAGENTA = CYAN = WHITE = RESET = ''
class Style:
DIM = NORMAL = BRIGHT = RESET_ALL = ''
THIRD_PARTY_IMPORTS['colorama'] = False
# Constants
VERSION = "3.0.0"
AUTHOR = "Security Operations Team"
DEFAULT_CONFIG_FILE = "avrps_config.ini"
DEFAULT_DB_FILE = "vulnerability_database.db"
DEFAULT_LOG_FILE = "avrps.log"
MAX_WORKERS = 5
TIMEOUT = 300 # 5 minutes
CHUNK_SIZE = 8192
# Logging configuration
def setupLogging(logLevel: str = "INFO", logFile: str = DEFAULT_LOG_FILE) -> logging.Logger:
"""Configure comprehensive logging system"""
logFormatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(module)s:%(lineno)d - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger('AVRPS')
logger.setLevel(getattr(logging, logLevel.upper(), logging.INFO))
# File handler with rotation
try:
fileHandler = logging.FileHandler(logFile, encoding='utf-8')
fileHandler.setFormatter(logFormatter)
logger.addHandler(fileHandler)
except Exception as e:
print(f"Warning: Could not set up file logging: {e}")
# Console handler with colored output
consoleHandler = logging.StreamHandler(sys.stdout)
if THIRD_PARTY_IMPORTS['colorama']:
class ColoredFormatter(logging.Formatter):
"""Custom formatter with colors"""
COLORS = {
'DEBUG': Fore.CYAN,
'INFO': Fore.GREEN,
'WARNING': Fore.YELLOW,
'ERROR': Fore.RED,
'CRITICAL': Fore.RED + Back.WHITE + Style.BRIGHT
}
def format(self, record):
if record.levelname in self.COLORS:
color = self.COLORS[record.levelname]
record.levelname = f"{color}{record.levelname}{Style.RESET_ALL}"
record.msg = f"{color}{record.msg}{Style.RESET_ALL}"
return super().format(record)
consoleHandler.setFormatter(ColoredFormatter(
'%(asctime)s - %(levelname)s - %(message)s',
datefmt='%H:%M:%S'
))
else:
consoleHandler.setFormatter(logging.Formatter(
'%(asctime)s - %(levelname)s - %(message)s',
datefmt='%H:%M:%S'
))
logger.addHandler(consoleHandler)
# Suppress third-party library logs
logging.getLogger('urllib3').setLevel(logging.WARNING)
logging.getLogger('requests').setLevel(logging.WARNING)
return logger
logger = setupLogging()
# Enums
class SeverityLevel(IntEnum):
"""Vulnerability severity levels with numeric values for sorting"""
CRITICAL = 4
HIGH = 3
MEDIUM = 2
LOW = 1
INFO = 0
UNKNOWN = -1
@classmethod
def fromString(cls, severityStr: str) -> 'SeverityLevel':
"""Convert string to SeverityLevel"""
severityMap = {
'critical': cls.CRITICAL,
'high': cls.HIGH,
'medium': cls.MEDIUM,
'low': cls.LOW,
'info': cls.INFO
}
return severityMap.get(severityStr.lower(), cls.UNKNOWN)
class OperatingSystem(Enum):
"""Supported operating systems"""
LINUX = "Linux"
WINDOWS = "Windows"
MACOS = "Darwin"
BSD = "BSD"
SOLARIS = "SunOS"
UNKNOWN = "Unknown"
@classmethod
def detect(cls) -> 'OperatingSystem':
"""Detect current operating system"""
system = platform.system()
for osType in cls:
if osType.value == system:
return osType
return cls.UNKNOWN
class PatchStatus(Enum):
"""Patch application status"""
PENDING = "pending"
IN_PROGRESS = "in_progress"
SUCCESS = "success"
FAILED = "failed"
SKIPPED = "skipped"
ROLLED_BACK = "rolled_back"
MANUAL_INTERVENTION_REQUIRED = "manual_intervention_required"
@property
def isTerminal(self) -> bool:
"""Check if status is terminal (no further processing needed)"""
return self in [self.SUCCESS, self.FAILED, self.SKIPPED, self.ROLLED_BACK]
class PackageManager(Enum):
"""Package manager types"""
APT = "apt" # Debian, Ubuntu
YUM = "yum" # RHEL, CentOS
DNF = "dnf" # Fedora, RHEL 8+
ZYPPER = "zypper" # openSUSE
PACMAN = "pacman" # Arch
APK = "apk" # Alpine
PIP = "pip" # Python
NPM = "npm" # Node.js
GEM = "gem" # Ruby
CHOCOLATEY = "chocolatey" # Windows
WINGET = "winget" # Windows
BREW = "brew" # macOS
UNKNOWN = "unknown"
class Architecture(Enum):
"""System architectures"""
X86 = "x86"
X64 = "x64"
ARM = "arm"
ARM64 = "arm64"
PPC = "ppc"
PPC64 = "ppc64"
MIPS = "mips"
SPARC = "sparc"
UNKNOWN = "unknown"
# Data Classes
@dataclass
class SystemPackage:
"""Detailed system package information"""
name: str
version: str
architecture: Architecture
vendor: str = ""
installDate: Optional[datetime] = None
packageManager: PackageManager = PackageManager.UNKNOWN
filePath: Optional[str] = None
dependencies: List[str] = field(default_factory=list)
description: str = ""
license: str = ""
size: int = 0
hashValue: str = ""
def toDict(self) -> Dict[str, Any]:
"""Convert to dictionary for serialization"""
data = asdict(self)
if self.installDate:
data['installDate'] = self.installDate.isoformat()
data['architecture'] = self.architecture.value
data['packageManager'] = self.packageManager.value
return data
@classmethod
def fromDict(cls, data: Dict[str, Any]) -> 'SystemPackage':
"""Create from dictionary"""
data = data.copy()
if 'installDate' in data and data['installDate']:
data['installDate'] = datetime.fromisoformat(data['installDate'])
data['architecture'] = Architecture(data.get('architecture', 'unknown'))
data['packageManager'] = PackageManager(data.get('packageManager', 'unknown'))
return cls(**data)
@dataclass
class Vulnerability:
"""Comprehensive vulnerability information"""
cveId: str
description: str
severity: SeverityLevel
cvssScore: float
cvssVector: str = ""
affectedPackages: List[str] = field(default_factory=list)
affectedVersions: Dict[str, List[str]] = field(default_factory=dict)
fixedVersion: Optional[str] = None
exploitAvailable: bool = False
exploitMaturity: str = ""
publishedDate: datetime = field(default_factory=datetime.now)
lastModifiedDate: datetime = field(default_factory=datetime.now)
references: List[str] = field(default_factory=list)
mitigation: str = ""
workaround: str = ""
impact: str = ""
advisory: str = ""
credits: str = ""
def toDict(self) -> Dict[str, Any]:
"""Convert to dictionary for serialization"""
data = asdict(self)
data['severity'] = self.severity.value
data['publishedDate'] = self.publishedDate.isoformat()
data['lastModifiedDate'] = self.lastModifiedDate.isoformat()
return data
@classmethod
def fromDict(cls, data: Dict[str, Any]) -> 'Vulnerability':
"""Create from dictionary"""
data = data.copy()
data['severity'] = SeverityLevel(data.get('severity', -1))
data['publishedDate'] = datetime.fromisoformat(data['publishedDate'])
data['lastModifiedDate'] = datetime.fromisoformat(data['lastModifiedDate'])
return cls(**data)
@dataclass
class ScanResult:
"""Vulnerability scan result with confidence scoring"""
vulnerability: Vulnerability
detectedPackage: SystemPackage
evidence: str
confidence: float # 0.0 to 1.0
timestamp: datetime = field(default_factory=datetime.now)
scannerVersion: str = VERSION
falsePositive: bool = False
notes: str = ""
def toDict(self) -> Dict[str, Any]:
"""Convert to dictionary for serialization"""
data = asdict(self)
data['vulnerability'] = self.vulnerability.toDict()
data['detectedPackage'] = self.detectedPackage.toDict()
data['timestamp'] = self.timestamp.isoformat()
return data
@dataclass
class PatchResult:
"""Detailed patch application result"""
cveId: str
status: PatchStatus
operation: str
details: str
timestamp: datetime = field(default_factory=datetime.now)
rollbackPoint: Optional[str] = None
executionTime: float = 0.0
errorMessage: Optional[str] = None
systemChanges: List[str] = field(default_factory=list)
verificationStatus: bool = False
patchVersion: Optional[str] = None
def toDict(self) -> Dict[str, Any]:
"""Convert to dictionary for serialization"""
data = asdict(self)
data['status'] = self.status.value
data['timestamp'] = self.timestamp.isoformat()
return data
@dataclass
class SystemInfo:
"""Comprehensive system information"""
osType: OperatingSystem
osVersion: str
kernelVersion: str
hostname: str
architecture: Architecture
cpuInfo: Dict[str, Any] = field(default_factory=dict)
memoryInfo: Dict[str, Any] = field(default_factory=dict)
diskInfo: Dict[str, Any] = field(default_factory=dict)
networkInterfaces: List[Dict[str, Any]] = field(default_factory=list)
installedPackages: List[SystemPackage] = field(default_factory=list)
runningServices: List[str] = field(default_factory=list)
openPorts: List[int] = field(default_factory=list)
users: List[str] = field(default_factory=list)
securityPolicies: Dict[str, Any] = field(default_factory=dict)
environmentVariables: Dict[str, str] = field(default_factory=dict)
systemUptime: float = 0.0
lastBootTime: Optional[datetime] = None
timezone: str = ""
locale: str = ""
def toDict(self) -> Dict[str, Any]:
"""Convert to dictionary for serialization"""
data = asdict(self)
data['osType'] = self.osType.value
data['architecture'] = self.architecture.value
data['installedPackages'] = [pkg.toDict() for pkg in self.installedPackages]
if self.lastBootTime:
data['lastBootTime'] = self.lastBootTime.isoformat()
return data
def generateFingerprint(self) -> str:
"""Generate a unique fingerprint for the system"""
fingerprintData = {
'hostname': self.hostname,
'osType': self.osType.value,
'osVersion': self.osVersion,
'kernelVersion': self.kernelVersion,
'architecture': self.architecture.value,
'cpuModel': self.cpuInfo.get('model', ''),
'totalMemory': self.memoryInfo.get('total', 0)
}
# Add package fingerprints
packageFingerprints = []
for pkg in self.installedPackages[:100]: # Limit to first 100 packages
packageFingerprints.append(f"{pkg.name}:{pkg.version}:{pkg.architecture.value}")
fingerprintData['packages'] = sorted(packageFingerprints)
# Create hash
fingerprintStr = json.dumps(fingerprintData, sort_keys=True)
return hashlib.sha256(fingerprintStr.encode()).hexdigest()
# Configuration Manager
class ConfigurationManager:
"""Manages configuration with validation and defaults"""
DEFAULT_CONFIG = {
'general': {
'log_level': 'INFO',
'max_workers': '5',
'timeout': '300',
'database_path': DEFAULT_DB_FILE,
'cache_ttl': '3600',
'backup_enabled': 'true',
'backup_count': '5'
},
'scanning': {
'deep_scan': 'false',
'scan_timeout': '600',
'max_packages': '0', # 0 = unlimited
'cve_check_enabled': 'true',
'config_check_enabled': 'true',
'privilege_escalation_check': 'true'
},
'patching': {
'auto_patch': 'false',
'dry_run_default': 'true',
'create_snapshots': 'true',
'rollback_enabled': 'true',
'max_rollback_points': '10',
'confirmation_required': 'true',
'whitelist': '',
'blacklist': ''
},
'reporting': {
'report_format': 'all', # json, html, txt, all
'save_reports': 'true',
'report_dir': 'reports',
'email_reports': 'false',
'webhook_enabled': 'false'
},
'api': {
'nvd_api_key': '',
'nvd_rate_limit': '10',
'use_local_cache': 'true',
'cache_dir': 'cache'
},
'ai_models': {
'cve_model': 'securebert',
'network_model': 'gcn',
'device': 'cpu',
'quantize': 'false',
'model_dir': 'models'
},
'notifications': {
'enabled': 'false',
'email_server': '',
'email_port': '587',
'email_username': '',
'email_password': '',
'email_recipients': '',
'webhook_url': '',
'slack_webhook': ''
}
}
def __init__(self, configFile: str = DEFAULT_CONFIG_FILE):
self.configFile = Path(configFile)
self.config = configparser.ConfigParser()
self.loadConfiguration()
def loadConfiguration(self) -> None:
"""Load configuration from file or create default"""
if self.configFile.exists():
try:
self.config.read(self.configFile, encoding='utf-8')
logger.info(f"Loaded configuration from {self.configFile}")
except Exception as e:
logger.error(f"Failed to load configuration: {e}")
self.createDefaultConfig()
else:
logger.info("Configuration file not found, creating default")
self.createDefaultConfig()
def createDefaultConfig(self) -> None:
"""Create default configuration file"""
try:
self.config.read_dict(self.DEFAULT_CONFIG)
with open(self.configFile, 'w', encoding='utf-8') as f:
self.config.write(f)
logger.info(f"Created default configuration at {self.configFile}")
except Exception as e:
logger.error(f"Failed to create configuration file: {e}")
# Use defaults in memory
self.config.read_dict(self.DEFAULT_CONFIG)
def get(self, section: str, key: str, defaultValue: Any = None) -> Any:
"""Get configuration value with type conversion and validation.
Args:
section: Configuration section name
key: Configuration key name
defaultValue: Value to return if key not found
Returns:
Configuration value with automatic type conversion
"""
try:
if not section or not key:
logger.warning("Invalid section or key: %s.%s", section, key)
return defaultValue
value = self.config.get(section, key)
if value is None or value == '':
return defaultValue
# Type conversion based on default value type
if defaultValue is not None:
try:
if isinstance(defaultValue, bool):
return self.config.getboolean(section, key)
elif isinstance(defaultValue, int):
try:
return self.config.getint(section, key)
except ValueError as e:
logger.warning("Type conversion failed for %s.%s: %s", section, key, e)
return defaultValue
elif isinstance(defaultValue, float):
try:
return self.config.getfloat(section, key)
except ValueError:
return defaultValue
elif isinstance(defaultValue, list):
return [item.strip() for item in value.split(',') if item.strip()]
except (configparser.NoSectionError, configparser.NoOptionError):
pass
return value
except (configparser.NoSectionError, configparser.NoOptionError):
logger.debug("Configuration key not found: %s.%s", section, key)
return defaultValue
except Exception as e:
logger.warning("Error reading configuration %s.%s: %s", section, key, e)
return defaultValue
def set(self, section: str, key: str, value: Any) -> None:
"""Set configuration value"""
if not self.config.has_section(section):
self.config.add_section(section)
if isinstance(value, list):
value = ','.join(str(item) for item in value)
else:
value = str(value)
self.config.set(section, key, value)
def save(self) -> None:
"""Save configuration to file"""
try:
with open(self.configFile, 'w', encoding='utf-8') as f:
self.config.write(f)
logger.info(f"Configuration saved to {self.configFile}")
except Exception as e:
logger.error(f"Failed to save configuration: {e}")
def validate(self) -> List[str]:
"""Validate configuration and return list of issues"""
issues = []
# Check required sections
requiredSections = ['general', 'scanning', 'patching']
for section in requiredSections:
if not self.config.has_section(section):
issues.append(f"Missing section: {section}")
# Validate values
maxWorkers = self.get('general', 'max_workers', 5)
if maxWorkers <= 0 or maxWorkers > 50:
issues.append("max_workers must be between 1 and 50")
timeout = self.get('general', 'timeout', 300)
if timeout <= 0:
issues.append("timeout must be positive")
return issues
# Database Manager with connection pooling and transaction support
class DatabaseManager:
"""Advanced database manager with connection pooling and transactions"""
def __init__(self, dbPath: str = DEFAULT_DB_FILE):
self.dbPath = Path(dbPath)
self.connectionPool = []
self.maxConnections = 5
self.lock = threading.Lock()
self.initializeDatabase()
def getConnection(self) -> sqlite3.Connection:
"""Get a database connection from pool or create new one"""
with self.lock:
if self.connectionPool:
conn = self.connectionPool.pop()
try:
# Test if connection is still valid
conn.execute("SELECT 1")
return conn
except sqlite3.Error:
conn.close()
# Create new connection
conn = sqlite3.connect(self.dbPath, timeout=30)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA foreign_keys = ON")
conn.execute("PRAGMA journal_mode = WAL")
conn.execute("PRAGMA synchronous = NORMAL")
conn.execute("PRAGMA cache_size = -2000") # 2MB cache
return conn
def returnConnection(self, conn: sqlite3.Connection) -> None:
"""Return connection to pool"""
with self.lock:
if len(self.connectionPool) < self.maxConnections:
self.connectionPool.append(conn)
else:
conn.close()
def executeInTransaction(self, query: str, params: Tuple = (), commit: bool = True) -> sqlite3.Cursor:
"""Execute query in transaction with automatic connection management.
Args:
query: SQL query string
params: Query parameters (tuple or list)
commit: Whether to commit transaction
Returns:
sqlite3.Cursor with query results
Raises:
ValueError: If query is invalid
sqlite3.DatabaseError: On database error
"""
if not query or not isinstance(query, str):
raise ValueError(f"Invalid query: {query}")
if params is None:
params = ()
elif not isinstance(params, (tuple, list)):
params = (params,)
conn = None
try:
conn = self.getConnection()
if conn is None:
raise sqlite3.DatabaseError("Failed to obtain database connection")
cursor = conn.cursor()
cursor.execute(query, params)
if commit:
conn.commit()
logger.debug(f"Committed transaction: {query[:80]}...")
return cursor
except sqlite3.IntegrityError as e:
if conn:
try:
conn.rollback()
except:
pass
logger.error(f"Database integrity error: {e} (query: {query[:80]}...)")
raise
except sqlite3.OperationalError as e:
if conn:
try:
conn.rollback()
except:
pass
logger.error(f"Database operational error: {e}")
raise
except Exception as e:
if conn:
try:
conn.rollback()
except:
pass
logger.error(f"Database error: {e}")
raise
finally:
if conn:
self.returnConnection(conn)
def initializeDatabase(self) -> None:
"""Initialize database with all required tables and indexes"""
tables = [
# Scan history
"""
CREATE TABLE IF NOT EXISTS scan_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
system_fingerprint TEXT,
scanner_version TEXT,
total_vulnerabilities INTEGER DEFAULT 0,
critical_count INTEGER DEFAULT 0,
high_count INTEGER DEFAULT 0,
medium_count INTEGER DEFAULT 0,
low_count INTEGER DEFAULT 0,
scan_duration REAL DEFAULT 0,
UNIQUE(system_fingerprint, timestamp)
)
""",
# Vulnerability results
"""
CREATE TABLE IF NOT EXISTS vulnerability_results (
id INTEGER PRIMARY KEY AUTOINCREMENT,
scan_id INTEGER NOT NULL,
cve_id TEXT NOT NULL,
package_name TEXT NOT NULL,
package_version TEXT NOT NULL,
package_architecture TEXT,
fixed_version TEXT,
severity INTEGER NOT NULL,
cvss_score REAL DEFAULT 0,
confidence REAL DEFAULT 0,
evidence TEXT,
false_positive BOOLEAN DEFAULT 0,
status TEXT DEFAULT 'detected',
FOREIGN KEY (scan_id) REFERENCES scan_history (id) ON DELETE CASCADE,
UNIQUE(scan_id, cve_id, package_name)
)
""",
# Patch history
"""
CREATE TABLE IF NOT EXISTS patch_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
cve_id TEXT NOT NULL,
package_name TEXT NOT NULL,
operation TEXT NOT NULL,
status TEXT NOT NULL,
details TEXT,
rollback_point TEXT,
execution_time REAL DEFAULT 0,
error_message TEXT,
verification_status BOOLEAN DEFAULT 0,
patch_version TEXT,
UNIQUE(cve_id, package_name, timestamp)
)
""",
# System snapshots
"""
CREATE TABLE IF NOT EXISTS system_snapshots (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
snapshot_type TEXT DEFAULT 'full',
snapshot_data BLOB NOT NULL,
snapshot_hash TEXT NOT NULL,
description TEXT,
UNIQUE(snapshot_hash, timestamp)
)
""",
# CVE cache
"""
CREATE TABLE IF NOT EXISTS cve_cache (
cve_id TEXT PRIMARY KEY,
cve_data BLOB NOT NULL,
last_updated DATETIME DEFAULT CURRENT_TIMESTAMP,
ttl INTEGER DEFAULT 86400, -- 24 hours in seconds
source TEXT DEFAULT 'unknown'
)
""",
# Network graphs (generated by NetworkGraphModel)
"""
CREATE TABLE IF NOT EXISTS network_graphs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
graph_json BLOB NOT NULL,
svg BLOB,
summary TEXT,
model_version TEXT,
UNIQUE(timestamp, model_version)
)
""",
# Package inventory
"""
CREATE TABLE IF NOT EXISTS package_inventory (
id INTEGER PRIMARY KEY AUTOINCREMENT,
system_fingerprint TEXT NOT NULL,
package_name TEXT NOT NULL,
package_version TEXT NOT NULL,
package_architecture TEXT,
package_manager TEXT,
install_date DATETIME,
last_seen DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE(system_fingerprint, package_name, package_version)
)
""",
# Settings
"""
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
description TEXT
)
"""
]
indexes = [
"CREATE INDEX IF NOT EXISTS idx_scan_history_fingerprint ON scan_history(system_fingerprint)",
"CREATE INDEX IF NOT EXISTS idx_scan_history_timestamp ON scan_history(timestamp)",
"CREATE INDEX IF NOT EXISTS idx_vuln_results_scan_id ON vulnerability_results(scan_id)",
"CREATE INDEX IF NOT EXISTS idx_vuln_results_cve_id ON vulnerability_results(cve_id)",
"CREATE INDEX IF NOT EXISTS idx_vuln_results_severity ON vulnerability_results(severity)",
"CREATE INDEX IF NOT EXISTS idx_patch_history_cve_id ON patch_history(cve_id)",
"CREATE INDEX IF NOT EXISTS idx_patch_history_status ON patch_history(status)",
"CREATE INDEX IF NOT EXISTS idx_patch_history_timestamp ON patch_history(timestamp)",
"CREATE INDEX IF NOT EXISTS idx_cve_cache_updated ON cve_cache(last_updated)",
"CREATE INDEX IF NOT EXISTS idx_package_inventory_fingerprint ON package_inventory(system_fingerprint)",
"CREATE INDEX IF NOT EXISTS idx_package_inventory_name ON package_inventory(package_name)"
]
conn = self.getConnection()
try:
cursor = conn.cursor()
# Create tables
for tableSql in tables:
cursor.execute(tableSql)
# Create indexes
for indexSql in indexes:
try:
cursor.execute(indexSql)
except sqlite3.OperationalError as e:
logger.warning(f"Index creation failed (may already exist): {e}")
# Insert default settings
defaultSettings = [
('database_version', VERSION, 'Database schema version'),
('last_maintenance', datetime.now().isoformat(), 'Last maintenance run'),
('retention_days', '90', 'Days to keep records'),
('auto_vacuum', 'true', 'Enable auto vacuum')
]
cursor.executemany(
"INSERT OR IGNORE INTO settings (key, value, description) VALUES (?, ?, ?)",
defaultSettings
)
conn.commit()
logger.info("Database initialized successfully")
except Exception as e:
conn.rollback()
logger.error(f"Database initialization failed: {e}")
raise
finally:
self.returnConnection(conn)
def saveScanResults(self, scanId: int, results: List[ScanResult]) -> None:
"""Save scan results to database"""
if not results:
return
batchData = []
for result in results:
batchData.append((
scanId,
result.vulnerability.cveId,
result.detectedPackage.name,
result.detectedPackage.version,
result.detectedPackage.architecture.value,
result.vulnerability.fixedVersion,
result.vulnerability.severity.value,
result.vulnerability.cvssScore,
result.confidence,
result.evidence,
1 if result.falsePositive else 0,
'detected'
))
query = """
INSERT OR REPLACE INTO vulnerability_results
(scan_id, cve_id, package_name, package_version, package_architecture,
fixed_version, severity, cvss_score, confidence, evidence,
false_positive, status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
"""
conn = self.getConnection()
try:
cursor = conn.cursor()
cursor.executemany(query, batchData)
# Update scan summary
cursor.execute("""
UPDATE scan_history
SET total_vulnerabilities = (
SELECT COUNT(*) FROM vulnerability_results
WHERE scan_id = ? AND false_positive = 0
),
critical_count = (
SELECT COUNT(*) FROM vulnerability_results
WHERE scan_id = ? AND severity = ? AND false_positive = 0
),
high_count = (
SELECT COUNT(*) FROM vulnerability_results
WHERE scan_id = ? AND severity = ? AND false_positive = 0
),
medium_count = (
SELECT COUNT(*) FROM vulnerability_results
WHERE scan_id = ? AND severity = ? AND false_positive = 0
),
low_count = (
SELECT COUNT(*) FROM vulnerability_results
WHERE scan_id = ? AND severity = ? AND false_positive = 0
)
WHERE id = ?
""", (scanId, scanId, SeverityLevel.CRITICAL.value,
scanId, SeverityLevel.HIGH.value,
scanId, SeverityLevel.MEDIUM.value,
scanId, SeverityLevel.LOW.value,
scanId))
conn.commit()
logger.debug(f"Saved {len(results)} scan results for scan ID {scanId}")
except Exception as e:
conn.rollback()
logger.error(f"Failed to save scan results: {e}")
raise
finally:
self.returnConnection(conn)
def createScanRecord(self, systemInfo: SystemInfo, scannerVersion: str = VERSION) -> int:
"""Create a new scan record and return scan ID"""
fingerprint = systemInfo.generateFingerprint()
query = """
INSERT INTO scan_history
(system_fingerprint, scanner_version, timestamp)
VALUES (?, ?, ?)
RETURNING id
"""
conn = self.getConnection()
try: