Skip to content
Threats Guide

av_config.py

Antivirus Configuration for Trojan Prevention This script configures and optimizes antivirus software for maximum protection against trojans and other malware.

  • prevention
  • python
  • 527 lines

Run security tools only on systems you own or have written permission to test.

Run it

From the repository root, after pip install -r tools/requirements.txt
cd 03-malware-analysis/trojans/prevention
python3 av_config.py --help

Source

View on GitHub
#!/usr/bin/env python3"""Antivirus Configuration for Trojan PreventionThis script configures and optimizes antivirus software for maximumprotection against trojans and other malware.""" import osimport sysimport jsonimport timeimport argparseimport subprocessimport platformimport shutilfrom datetime import datetimefrom pathlib import Pathfrom colorama import init, Fore, Style init(autoreset=True) class AntivirusConfig:    """    Antivirus Configuration and Optimization Tool    """        def __init__(self, config_file="av_config.json"):        """        Initialize Antivirus Configuration                Args:            config_file: Configuration file path        """        self.config_file = config_file        self.config = self.load_config()        self.system = platform.system()                # Default configuration        self.default_config = {            'scan_settings': {                'real_time_protection': True,                'heuristic_analysis': True,                'cloud_lookup': True,                'behavior_monitor': True,                'script_scanning': True,                'email_scanning': True,                'network_scanning': True,                'removable_drive_scan': True            },            'scan_schedule': {                'quick_scan': 'daily',                'full_scan': 'weekly',                'custom_scan': 'never'            },            'scan_paths': [                str(Path.home()),                'C:\\' if os.name == 'nt' else '/'            ],            'exclusions': {                'paths': [],                'extensions': [],                'processes': []            },            'detection_settings': {                'heuristic_level': 'medium',  # low, medium, high                'pup_detection': True,                'suspicious_behavior': True,                'potential_threats': True            },            'update_settings': {                'auto_update': True,                'update_interval': 3600,  # 1 hour                'update_source': 'official'            },            'quarantine_settings': {                'auto_quarantine': True,                'quarantine_days': 30,                'max_quarantine_size': 1024  # MB            },            'logging': {                'enabled': True,                'log_level': 'info',                'max_log_size': 10,  # MB                'log_retention': 30  # days            },            'performance': {                'scan_priority': 'normal',  # low, normal, high                'cpu_limit': 50,  # percent                'io_limit': 50,  # percent                'scan_on_idle': True            },            'notifications': {                'show_popups': True,                'email_alerts': False,                'email_address': '',                'sound_alerts': True            }        }        def load_config(self):        """Load configuration from file"""        if os.path.exists(self.config_file):            try:                with open(self.config_file, 'r') as f:                    return json.load(f)            except Exception as e:                print(f"{Fore.YELLOW}[!] Error loading config: {e}{Style.RESET_ALL}")                return self.default_config.copy()        def save_config(self):        """Save configuration to file"""        try:            with open(self.config_file, 'w') as f:                json.dump(self.config, f, indent=2)            print(f"{Fore.GREEN}[✓] Configuration saved to {self.config_file}{Style.RESET_ALL}")            return True        except Exception as e:            print(f"{Fore.RED}[✗] Error saving config: {e}{Style.RESET_ALL}")            return False        def configure_windows_defender(self):        """Configure Windows Defender"""        if self.system != 'Windows':            print(f"{Fore.YELLOW}[!] Windows Defender only available on Windows{Style.RESET_ALL}")            return False                print(f"\n{Fore.CYAN}[*] Configuring Windows Defender...{Style.RESET_ALL}")                try:            # Enable real-time protection            subprocess.run([                'powershell', '-Command',                'Set-MpPreference -DisableRealtimeMonitoring $false'            ], check=True)                        # Enable cloud-delivered protection            subprocess.run([                'powershell', '-Command',                'Set-MpPreference -MAPSReporting Advanced'            ], check=True)                        # Enable sample submission            subprocess.run([                'powershell', '-Command',                'Set-MpPreference -SubmitSamplesConsent SendAllSamples'            ], check=True)                        # Set heuristic level            levels = {'low': 1, 'medium': 2, 'high': 3}            level = levels.get(self.config['detection_settings']['heuristic_level'], 2)            subprocess.run([                'powershell', '-Command',                f'Set-MpPreference -PUAProtection Enabled -CloudBlockLevel High'            ], check=True)                        # Configure scan settings            subprocess.run([                'powershell', '-Command',                'Set-MpPreference -DisableArchiveScanning $false'            ], check=True)                        subprocess.run([                'powershell', '-Command',                'Set-MpPreference -DisableBehaviorMonitoring $false'            ], check=True)                        # Set scan schedule            if self.config['scan_schedule']['quick_scan'] == 'daily':                subprocess.run([                    'powershell', '-Command',                    'Set-MpPreference -ScanScheduleDay Everyday -ScanScheduleTime 1200'                ], check=True)                        # Configure exclusions            for path in self.config['exclusions']['paths']:                subprocess.run([                    'powershell', '-Command',                    f'Add-MpPreference -ExclusionPath "{path}"'                ], check=True)                        # Update signatures            subprocess.run(['powershell', '-Command', 'Update-MpSignature'], check=True)                        print(f"{Fore.GREEN}[✓] Windows Defender configured successfully{Style.RESET_ALL}")            return True                    except subprocess.CalledProcessError as e:            print(f"{Fore.RED}[✗] Error configuring Windows Defender: {e}{Style.RESET_ALL}")            return False        def configure_clamav(self):        """Configure ClamAV (cross-platform)"""        print(f"\n{Fore.CYAN}[*] Configuring ClamAV...{Style.RESET_ALL}")                # Check if ClamAV is installed        if not shutil.which('clamscan'):            print(f"{Fore.YELLOW}[!] ClamAV not found. Installing...{Style.RESET_ALL}")            self.install_clamav()                try:            # Create ClamAV config directory            if self.system == 'Windows':                conf_dir = 'C:\\Program Files\\ClamAV'            else:                conf_dir = '/etc/clamav'                        os.makedirs(conf_dir, exist_ok=True)                        # Generate freshclam.conf            freshclam_conf = os.path.join(conf_dir, 'freshclam.conf')            with open(freshclam_conf, 'w') as f:                f.write("""# freshclam configurationDatabaseMirror database.clamav.netDatabaseMirror db.local.clamav.netUpdateLogFile /var/log/freshclam.logLogTime yesLogVerbose noDatabaseOwner clamavDatabaseDirectory /var/lib/clamavNotifyClamd /etc/clamav/clamd.conf""")                        # Generate clamd.conf            clamd_conf = os.path.join(conf_dir, 'clamd.conf')            with open(clamd_conf, 'w') as f:                f.write("""# clamd configurationLogFile /var/log/clamd.logLogTime yesLogVerbose noLogRotate yesExtendedDetectionInfo yesPidFile /var/run/clamd.pidTemporaryDirectory /tmpDatabaseDirectory /var/lib/clamavLocalSocket /var/run/clamav/clamd.ctlFixStaleSocket yesTCPSocket 3310TCPAddr 127.0.0.1MaxConnectionQueueLength 30StreamMaxLength 100MScanPE yesScanELF yesScanMail yesScanOLE2 yesScanHTML yesScanPDF yesMaxScanSize 100MMaxFileSize 25MMaxRecursion 10MaxFiles 10000""")                        print(f"{Fore.GREEN}[✓] ClamAV configured successfully{Style.RESET_ALL}")            return True                    except Exception as e:            print(f"{Fore.RED}[✗] Error configuring ClamAV: {e}{Style.RESET_ALL}")            return False        def install_clamav(self):        """Install ClamAV"""        if self.system == 'Linux':            try:                if os.path.exists('/etc/debian_version'):                    subprocess.run(['sudo', 'apt-get', 'update'], check=True)                    subprocess.run(['sudo', 'apt-get', 'install', '-y', 'clamav', 'clamav-daemon'], check=True)                elif os.path.exists('/etc/redhat-release'):                    subprocess.run(['sudo', 'yum', 'install', '-y', 'clamav', 'clamavd'], check=True)                                print(f"{Fore.GREEN}[✓] ClamAV installed{Style.RESET_ALL}")            except Exception as e:                print(f"{Fore.RED}[✗] Error installing ClamAV: {e}{Style.RESET_ALL}")                elif self.system == 'Windows':            print(f"{Fore.YELLOW}[!] Please download ClamAV from: https://www.clamav.net/downloads{Style.RESET_ALL}")        def create_scan_script(self):        """Create custom scan script"""        script_content = """#!/bin/bash# Custom Antivirus Scan ScriptSCAN_LOG="/var/log/av_scan.log"SCAN_DATE=$(date "+%Y-%m-%d %H:%M:%S")echo "[$SCAN_DATE] Starting antivirus scan..." >> $SCAN_LOG# Scan with ClamAVif command -v clamscan &> /dev/null; then    clamscan -r --bell -i /home/$USER >> $SCAN_LOG 2>&1fi# Check Windows Defender on Windowsif [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "cygwin" ]]; then    powershell -Command "Start-MpScan -ScanType QuickScan" >> $SCAN_LOG 2>&1fiecho "[$SCAN_DATE] Scan completed" >> $SCAN_LOG"""                script_path = 'av_scan.sh'        with open(script_path, 'w') as f:            f.write(script_content)                os.chmod(script_path, 0o755)        print(f"{Fore.GREEN}[✓] Scan script created: {script_path}{Style.RESET_ALL}")                return script_path        def configure_cron_job(self):        """Configure scheduled scans using cron"""        if self.system != 'Linux':            print(f"{Fore.YELLOW}[!] Cron jobs only available on Linux{Style.RESET_ALL}")            return False                script_path = self.create_scan_script()                # Create crontab entry        cron_line = f"0 2 * * * {os.path.abspath(script_path)}"                try:            # Get existing crontab            result = subprocess.run(['crontab', '-l'], capture_output=True, text=True)            current_cron = result.stdout                        # Add new line if not exists            if cron_line not in current_cron:                new_cron = current_cron + cron_line + '\n'                                # Save to temp file                with open('/tmp/crontab.txt', 'w') as f:                    f.write(new_cron)                                # Install new crontab                subprocess.run(['crontab', '/tmp/crontab.txt'], check=True)                os.remove('/tmp/crontab.txt')                                print(f"{Fore.GREEN}[✓] Scheduled scan configured (daily at 2 AM){Style.RESET_ALL}")                    except Exception as e:            print(f"{Fore.RED}[✗] Error configuring cron: {e}{Style.RESET_ALL}")        def configure_windows_task(self):        """Configure scheduled scan using Windows Task Scheduler"""        if self.system != 'Windows':            print(f"{Fore.YELLOW}[!] Task Scheduler only available on Windows{Style.RESET_ALL}")            return False                try:            # Create scheduled task for daily scan            subprocess.run([                'schtasks', '/create', '/tn', 'AVScan', '/tr',                 'powershell -Command "Start-MpScan -ScanType QuickScan"',                '/sc', 'daily', '/st', '02:00', '/f'            ], check=True)                        print(f"{Fore.GREEN}[✓] Scheduled scan configured (daily at 2 AM){Style.RESET_ALL}")                    except subprocess.CalledProcessError as e:            print(f"{Fore.RED}[✗] Error configuring task: {e}{Style.RESET_ALL}")        def add_exclusion(self, path):        """Add exclusion path"""        if path not in self.config['exclusions']['paths']:            self.config['exclusions']['paths'].append(path)            self.save_config()            print(f"{Fore.GREEN}[✓] Added exclusion: {path}{Style.RESET_ALL}")                        # Apply to Windows Defender if on Windows            if self.system == 'Windows':                try:                    subprocess.run([                        'powershell', '-Command',                        f'Add-MpPreference -ExclusionPath "{path}"'                    ], check=True)                    print(f"{Fore.GREEN}[✓] Applied to Windows Defender{Style.RESET_ALL}")                except Exception as e:                    print(f"{Fore.RED}[✗] Error applying to Defender: {e}{Style.RESET_ALL}")        def run_quick_scan(self):        """Run quick system scan"""        print(f"\n{Fore.CYAN}[*] Running quick scan...{Style.RESET_ALL}")                if self.system == 'Windows':            try:                subprocess.run([                    'powershell', '-Command',                    'Start-MpScan -ScanType QuickScan'                ], check=True)                print(f"{Fore.GREEN}[✓] Quick scan completed{Style.RESET_ALL}")            except Exception as e:                print(f"{Fore.RED}[✗] Error running scan: {e}{Style.RESET_ALL}")                elif shutil.which('clamscan'):            try:                subprocess.run([                    'clamscan', '-r', '--bell', '-i', str(Path.home())                ], check=True)                print(f"{Fore.GREEN}[✓] Quick scan completed{Style.RESET_ALL}")            except Exception as e:                print(f"{Fore.RED}[✗] Error running scan: {e}{Style.RESET_ALL}")        def update_signatures(self):        """Update antivirus signatures"""        print(f"\n{Fore.CYAN}[*] Updating virus definitions...{Style.RESET_ALL}")                if self.system == 'Windows':            try:                subprocess.run(['powershell', '-Command', 'Update-MpSignature'], check=True)                print(f"{Fore.GREEN}[✓] Windows Defender signatures updated{Style.RESET_ALL}")            except Exception as e:                print(f"{Fore.RED}[✗] Error updating signatures: {e}{Style.RESET_ALL}")                elif shutil.which('freshclam'):            try:                subprocess.run(['sudo', 'freshclam'], check=True)                print(f"{Fore.GREEN}[✓] ClamAV signatures updated{Style.RESET_ALL}")            except Exception as e:                print(f"{Fore.RED}[✗] Error updating signatures: {e}{Style.RESET_ALL}")        def show_status(self):        """Show current protection status"""        print(f"\n{Fore.CYAN}{'='*50}{Style.RESET_ALL}")        print(f"{Fore.CYAN}📊 PROTECTION STATUS{Style.RESET_ALL}")        print(f"{Fore.CYAN}{'='*50}{Style.RESET_ALL}")                # Show configuration        print(f"\n{Fore.GREEN}Scan Settings:{Style.RESET_ALL}")        for setting, value in self.config['scan_settings'].items():            status = f"{Fore.GREEN}Enabled{Style.RESET_ALL}" if value else f"{Fore.RED}Disabled{Style.RESET_ALL}"            print(f"  {setting}: {status}")                print(f"\n{Fore.GREEN}Detection Settings:{Style.RESET_ALL}")        print(f"  Heuristic Level: {self.config['detection_settings']['heuristic_level']}")        print(f"  PUP Detection: {self.config['detection_settings']['pup_detection']}")                print(f"\n{Fore.GREEN}Exclusions:{Style.RESET_ALL}")        print(f"  Paths: {len(self.config['exclusions']['paths'])}")        print(f"  Extensions: {len(self.config['exclusions']['extensions'])}")        print(f"  Processes: {len(self.config['exclusions']['processes'])}")                # Show Windows Defender status if available        if self.system == 'Windows':            try:                result = subprocess.run([                    'powershell', '-Command',                    'Get-MpComputerStatus | Select-Object -Property *'                ], capture_output=True, text=True)                print(f"\n{Fore.GREEN}Windows Defender Status:{Style.RESET_ALL}")                print(result.stdout)            except:                pass                print(f"\n{Fore.CYAN}{'='*50}{Style.RESET_ALL}")        def interactive_menu(self):        """Interactive configuration menu"""        while True:            print(f"\n{Fore.CYAN}{'='*50}{Style.RESET_ALL}")            print(f"{Fore.CYAN}ANTIVIRUS CONFIGURATION MENU{Style.RESET_ALL}")            print(f"{Fore.CYAN}{'='*50}{Style.RESET_ALL}")            print("1. Configure Windows Defender")            print("2. Configure ClamAV")            print("3. Run Quick Scan")            print("4. Update Signatures")            print("5. Add Exclusion Path")            print("6. Configure Scheduled Scans")            print("7. View Status")            print("8. Save Configuration")            print("9. Reset to Defaults")            print("0. Exit")                        choice = input(f"\n{Fore.YELLOW}Enter choice: {Style.RESET_ALL}")                        if choice == '1':                self.configure_windows_defender()            elif choice == '2':                self.configure_clamav()            elif choice == '3':                self.run_quick_scan()            elif choice == '4':                self.update_signatures()            elif choice == '5':                path = input("Enter path to exclude: ")                self.add_exclusion(path)            elif choice == '6':                if self.system == 'Windows':                    self.configure_windows_task()                else:                    self.configure_cron_job()            elif choice == '7':                self.show_status()            elif choice == '8':                self.save_config()            elif choice == '9':                self.config = self.default_config.copy()                self.save_config()                print(f"{Fore.GREEN}[✓] Reset to defaults{Style.RESET_ALL}")            elif choice == '0':                break def main():    parser = argparse.ArgumentParser(description='Antivirus Configuration Tool')    parser.add_argument('--config', default='av_config.json', help='Configuration file')    parser.add_argument('--scan', action='store_true', help='Run quick scan')    parser.add_argument('--update', action='store_true', help='Update signatures')    parser.add_argument('--status', action='store_true', help='Show protection status')    parser.add_argument('--interactive', action='store_true', help='Interactive mode')        args = parser.parse_args()        av = AntivirusConfig(config_file=args.config)        if args.scan:        av.run_quick_scan()    elif args.update:        av.update_signatures()    elif args.status:        av.show_status()    elif args.interactive:        av.interactive_menu()    else:        print("Use --interactive for menu or --help for options") if __name__ == "__main__":    main()