#!/bin/bash

# LockKnife Malware Analysis Module
# Provides malware detection and analysis capabilities

# Malware scan types
MALWARE_SCAN_QUICK=1
MALWARE_SCAN_FULL=2
MALWARE_SCAN_DEEP=3

# Suspicious indicators
SUSPICIOUS_PERMISSIONS=(
    "android.permission.RECEIVE_BOOT_COMPLETED"
    "android.permission.SYSTEM_ALERT_WINDOW"
    "android.permission.BIND_DEVICE_ADMIN"
    "android.permission.REQUEST_INSTALL_PACKAGES"
    "android.permission.PACKAGE_USAGE_STATS"
    "android.permission.READ_SMS"
    "android.permission.SEND_SMS"
    "android.permission.RECORD_AUDIO"
    "android.permission.CAMERA"
    "android.permission.ACCESS_FINE_LOCATION"
    "android.permission.READ_CONTACTS"
    "android.permission.WRITE_EXTERNAL_STORAGE"
)

# Known suspicious package name patterns
SUSPICIOUS_PACKAGE_PATTERNS=(
    ".*hack.*"
    ".*spy.*"
    ".*keylog.*"
    ".*trojan.*"
    ".*malware.*"
    ".*virus.*"
    ".*root.*"
    ".*exploit.*"
    ".*backdoor.*"
    ".*rat.*"
    ".*botnet.*"
)

# Scan installed applications for malware indicators
scan_installed_apps() {
    local device_serial="$1"
    local scan_type="${2:-$MALWARE_SCAN_DEPTH}"
    local output_file="$OUTPUT_DIR/malware_scan_$(date +%Y%m%d_%H%M%S).txt"

    log "INFO" "Scanning installed applications for malware indicators (scan type: $scan_type)"

    # Get list of installed packages
    local packages
    packages=$(execute_shell_cmd "$device_serial" "pm list packages -3" "Get user-installed packages")

    if [[ -z "$packages" ]]; then
        log "WARNING" "Failed to retrieve package list"
        return 1
    fi

    local total_packages
    total_packages=$(echo "$packages" | wc -l)
    log "INFO" "Scanning $total_packages installed applications"

    {
        echo "# Malware Analysis Report - Installed Applications"
        echo "# Generated: $(date)"
        echo "# Scan Type: $scan_type"
        echo "# Total Applications: $total_packages"
        echo ""

        local suspicious_apps=()
        local high_risk_apps=()
        local scan_count=0

        echo "$packages" | while read -r package_line; do
            ((scan_count++))
            log_progress "$scan_count" "$total_packages" "Scanning applications"

            local package_name
            package_name=$(echo "$package_line" | sed 's/package://')

            # Skip system apps in quick scan
            if [[ "$scan_type" = "quick" ]] && [[ "$package_name" =~ ^com\.android\.|^com\.google\.|^com\.samsung\.|^com\.huawei\.|^com\.xiaomi\.|^com\.oneplus\. ]]; then
                continue
            fi

            # Analyze package
            analyze_package "$device_serial" "$package_name" "$scan_type"
        done

        log_progress_complete

        echo ""
        echo "## Scan Summary"
        echo "- Total applications scanned: $total_packages"
        echo "- Suspicious applications found: ${#suspicious_apps[@]}"
        echo "- High-risk applications found: ${#high_risk_apps[@]}"

        if [[ ${#suspicious_apps[@]} -gt 0 ]]; then
            echo ""
            echo "## Suspicious Applications"
            for app in "${suspicious_apps[@]}"; do
                echo "- $app"
            done
        fi

        if [[ ${#high_risk_apps[@]} -gt 0 ]]; then
            echo ""
            echo "## High-Risk Applications ⚠️"
            for app in "${high_risk_apps[@]}"; do
                echo "- $app"
            done
        fi

    } > "$output_file"

    log "SUCCESS" "Malware scan completed. Results saved to $output_file"
    return 0
}

# Analyze individual package
analyze_package() {
    local device_serial="$1"
    local package_name="$2"
    local scan_type="$3"

    # Get package information
    local package_info
    package_info=$(execute_shell_cmd "$device_serial" "pm dump $package_name" "Package info dump")

    # Get permissions
    local permissions
    permissions=$(execute_shell_cmd "$device_serial" "pm dump $package_name | grep permission" "Package permissions")

    # Get receivers (for background services)
    local receivers
    receivers=$(execute_shell_cmd "$device_serial" "pm dump $package_name | grep Receiver" "Package receivers")

    # Calculate risk score
    local risk_score=0
    local suspicious_indicators=()

    # Check package name for suspicious patterns
    for pattern in "${SUSPICIOUS_PACKAGE_PATTERNS[@]}"; do
        if [[ "$package_name" =~ $pattern ]]; then
            ((risk_score += 20))
            suspicious_indicators+=("Suspicious package name pattern: $pattern")
        fi
    done

    # Check permissions
    for perm in "${SUSPICIOUS_PERMISSIONS[@]}"; do
        if echo "$permissions" | grep -q "$perm"; then
            ((risk_score += 10))
            suspicious_indicators+=("Suspicious permission: $perm")
        fi
    done

    # Check for boot receivers (persistence mechanism)
    if echo "$receivers" | grep -q "BOOT_COMPLETED"; then
        ((risk_score += 15))
        suspicious_indicators+=("Boot receiver (persistence mechanism)")
    fi

    # Check for accessibility service (keylogging potential)
    if echo "$package_info" | grep -q "AccessibilityService"; then
        ((risk_score += 25))
        suspicious_indicators+=("Accessibility service (potential keylogger)")
    fi

    # Check for device admin (hard to remove)
    if echo "$package_info" | grep -q "DeviceAdmin"; then
        ((risk_score += 20))
        suspicious_indicators+=("Device administrator (hard to remove)")
    fi

    # Deep scan checks
    if [[ "$scan_type" = "deep" ]]; then
        # Check for native libraries
        local native_libs
        native_libs=$(execute_shell_cmd "$device_serial" "pm path $package_name" "Package path")
        if [[ -n "$native_libs" ]]; then
            local apk_path
            apk_path=$(echo "$native_libs" | head -1 | sed 's/package://')

            # Check if APK contains native code
            if execute_shell_cmd "$device_serial" "unzip -l '$apk_path' 2>/dev/null | grep -q '\.so'" "Check native libraries"; then
                ((risk_score += 5))
                suspicious_indicators+=("Contains native libraries")
            fi
        fi

        # Check for large number of permissions
        local perm_count
        perm_count=$(echo "$permissions" | wc -l)
        if [[ $perm_count -gt 15 ]]; then
            ((risk_score += 10))
            suspicious_indicators+=("Excessive permissions ($perm_count)")
        fi
    fi

    # Determine risk level
    local risk_level="Low"
    if [[ $risk_score -ge 50 ]]; then
        risk_level="High"
    elif [[ $risk_score -ge 25 ]]; then
        risk_level="Medium"
    fi

    # Output analysis if suspicious
    if [[ $risk_score -gt 0 ]] || [[ "$scan_type" = "full" ]] || [[ "$scan_type" = "deep" ]]; then
        echo "### Package: $package_name"
        echo "- Risk Level: $risk_level (Score: $risk_score)"
        echo "- Risk Score: $risk_score/100"

        if [[ ${#suspicious_indicators[@]} -gt 0 ]]; then
            echo "- Suspicious Indicators:"
            for indicator in "${suspicious_indicators[@]}"; do
                echo "  • $indicator"
            done
        fi

        echo ""
    fi

    # Track high-risk apps
    if [[ $risk_score -ge 50 ]]; then
        high_risk_apps+=("$package_name (Score: $risk_score)")
    elif [[ $risk_score -ge 25 ]]; then
        suspicious_apps+=("$package_name (Score: $risk_score)")
    fi
}

# Scan system files for malware
scan_system_files() {
    local device_serial="$1"
    local output_file="$OUTPUT_DIR/system_malware_scan_$(date +%Y%m%d_%H%M%S).txt"

    log "INFO" "Scanning system files for malware indicators"

    if ! device_supports_feature "$device_serial" "root"; then
        log "ERROR" "Root access required for system file scanning"
        return 1
    fi

    {
        echo "# System Files Malware Scan"
        echo "# Generated: $(date)"
        echo ""

        # Check for suspicious files in system directories
        local system_dirs=("/system/bin" "/system/xbin" "/system/app" "/data/app")

        for dir in "${system_dirs[@]}"; do
            echo "## Scanning $dir"

            execute_root_cmd "$device_serial" "find $dir -type f \( -name '*.so' -o -name '*.bin' -o -name '*.sh' \) 2>/dev/null | head -20" "Find executable files" | while read -r file; do
                if [[ -n "$file" ]]; then
                    # Check file properties
                    local file_info
                    file_info=$(execute_root_cmd "$device_serial" "ls -la '$file'" "File info")

                    # Check if file is suspicious
                    local suspicious=false

                    # Check file permissions
                    if echo "$file_info" | grep -q "rwx.*rwx.*rwx"; then
                        echo "⚠️  World-writable executable: $file"
                        suspicious=true
                    fi

                    # Check for hidden files
                    if [[ "$(basename "$file")" =~ ^\. ]]; then
                        echo "⚠️  Hidden executable: $file"
                        suspicious=true
                    fi

                    # Check for unusual file sizes (very small or very large)
                    local file_size
                    file_size=$(echo "$file_info" | awk '{print $5}')
                    if [[ $file_size -eq 0 ]]; then
                        echo "⚠️  Zero-byte executable: $file"
                        suspicious=true
                    elif [[ $file_size -gt 104857600 ]]; then  # 100MB
                        echo "⚠️  Very large executable: $file (${file_size} bytes)"
                        suspicious=true
                    fi

                    if [[ "$suspicious" = false ]]; then
                        echo "✓ Clean: $file"
                    fi
                fi
            done
            echo ""
        done

        # Check for rootkits and suspicious kernel modules
        echo "## Kernel Module Analysis"
        execute_root_cmd "$device_serial" "lsmod" "List kernel modules" | while read -r line; do
            local module_name
            module_name=$(echo "$line" | awk '{print $1}')

            # Check for suspicious module names
            if [[ "$module_name" =~ (rootkit|hide|hook|spy) ]]; then
                echo "⚠️  SUSPICIOUS KERNEL MODULE: $module_name"
            else
                echo "✓ Module: $module_name"
            fi
        done
        echo ""

        # Check for suspicious cron jobs or scheduled tasks
        echo "## Scheduled Tasks"
        # Android doesn't have traditional cron, but check for scheduled alarms
        execute_shell_cmd "$device_serial" "dumpsys alarm | grep -A5 -B5 'RTC\|ELAPSED'" "Check alarms" | head -20
        echo ""

    } > "$output_file"

    log "SUCCESS" "System file malware scan completed. Results saved to $output_file"
    return 0
}

# Analyze network connections for malicious activity
analyze_network_malware() {
    local device_serial="$1"
    local output_file="$OUTPUT_DIR/network_malware_analysis_$(date +%Y%m%d_%H%M%S).txt"

    log "INFO" "Analyzing network connections for malicious activity"

    # Get network connections
    local netstat_output
    netstat_output=$(execute_shell_cmd "$device_serial" "netstat -tuln 2>/dev/null || ss -tuln 2>/dev/null" "Network connections")

    # Get current network traffic
    local traffic_info
    traffic_info=$(execute_shell_cmd "$device_serial" "cat /proc/net/dev" "Network traffic")

    {
        echo "# Network Malware Analysis"
        echo "# Generated: $(date)"
        echo ""

        echo "## Active Network Connections"
        echo "$netstat_output" | while read -r line; do
            # Analyze each connection
            if echo "$line" | grep -q "LISTEN\|ESTABLISHED"; then
                local protocol port remote_ip
                protocol=$(echo "$line" | awk '{print $1}')
                port=$(echo "$line" | awk '{print $4}' | sed 's/.*://')
                remote_ip=$(echo "$line" | awk '{print $5}' | sed 's/:.*//')

                # Flag suspicious connections
                if [[ "$port" =~ ^(4444|6667|6668|31337|12345|54321)$ ]]; then
                    echo "⚠️  SUSPICIOUS PORT: $protocol port $port (remote: $remote_ip)"
                elif [[ "$remote_ip" != "127.0.0.1" && "$remote_ip" != "0.0.0.0" && "$remote_ip" != "::" ]]; then
                    # Check if remote IP is suspicious (basic check)
                    if [[ "$remote_ip" =~ ^(10\.|172\.1[6-9]\.|172\.2[0-9]\.|172\.3[0-1]\.|192\.168\.) ]]; then
                        echo "✓ Local network: $protocol port $port -> $remote_ip"
                    else
                        echo "? External connection: $protocol port $port -> $remote_ip"
                    fi
                else
                    echo "✓ Local: $protocol port $port"
                fi
            fi
        done
        echo ""

        echo "## Network Interface Statistics"
        echo "$traffic_info" | while read -r line; do
            if echo "$line" | grep -q ":"; then
                local interface rx_bytes tx_bytes
                interface=$(echo "$line" | cut -d: -f1 | xargs)
                rx_bytes=$(echo "$line" | awk '{print $2}')
                tx_bytes=$(echo "$line" | awk '{print $10}')

                if [[ "$interface" != "lo" && $rx_bytes -gt 0 ]]; then
                    echo "- $interface: RX ${rx_bytes} bytes, TX ${tx_bytes} bytes"
                fi
            fi
        done
        echo ""

        # Check for DNS queries to suspicious domains
        echo "## DNS Analysis"
        if command -v tcpdump &>/dev/null && device_supports_feature "$device_serial" "root"; then
            log "INFO" "Capturing DNS traffic for analysis..."
            # This would require tcpdump on device or host-side capture
            echo "DNS traffic analysis requires tcpdump on device or host-side capture"
        else
            echo "DNS analysis requires tcpdump (not available)"
        fi

    } > "$output_file"

    log "SUCCESS" "Network malware analysis completed. Results saved to $output_file"
    return 0
}

# YARA rule-based malware scanning
yara_malware_scan() {
    local device_serial="$1"
    local output_file="$OUTPUT_DIR/yara_malware_scan_$(date +%Y%m%d_%H%M%S).txt"

    log "INFO" "Performing YARA-based malware scanning"

    if ! command -v yara &>/dev/null; then
        log "WARNING" "YARA not found. Install YARA for advanced malware scanning."
        log "INFO" "Performing basic signature-based scan instead."

        basic_signature_scan "$device_serial" "$output_file"
        return $?
    fi

    # Create temporary directory for APK extraction
    local temp_dir="$TEMP_DIR/yara_scan"
    mkdir -p "$temp_dir"

    # Get list of APKs
    local apk_list
    apk_list=$(execute_shell_cmd "$device_serial" "pm list packages -f" "Get APK paths")

    {
        echo "# YARA Malware Scan Report"
        echo "# Generated: $(date)"
        echo ""

        echo "$apk_list" | while read -r package_line; do
            local package_info
            package_info=$(echo "$package_line" | sed 's/package://')
            local apk_path
            apk_path=$(echo "$package_info" | awk '{print $1}')
            local package_name
            package_name=$(echo "$package_info" | awk '{print $2}')

            echo "## Scanning: $package_name"
            echo "APK Path: $apk_path"

            # Pull APK for scanning
            local local_apk="$temp_dir/$(basename "$apk_path")"
            if pull_file_from_device "$device_serial" "$apk_path" "$local_apk"; then
                # Run YARA scan (would need YARA rules)
                echo "APK pulled successfully for scanning"
                # Note: Actual YARA scanning would require rule files
                echo "YARA scan: [Rules not configured - requires malware signature database]"
            else
                echo "Failed to pull APK for scanning"
            fi
            echo ""
        done

    } > "$output_file"

    # Cleanup
    secure_delete_file "$temp_dir"/*

    log "SUCCESS" "YARA malware scan completed. Results saved to $output_file"
    return 0
}

# Basic signature-based malware scanning
basic_signature_scan() {
    local device_serial="$1"
    local output_file="$2"

    log "INFO" "Performing basic signature-based malware scanning"

    {
        echo "# Basic Malware Signature Scan"
        echo "# Generated: $(date)"
        echo ""

        # Get list of installed packages
        local packages
        packages=$(execute_shell_cmd "$device_serial" "pm list packages -3" "Get user packages")

        echo "## Scanning for Known Malicious Packages"
        echo "$packages" | while read -r package_line; do
            local package_name
            package_name=$(echo "$package_line" | sed 's/package://')

            # Check against known malicious package signatures
            if [[ "$package_name" =~ (hack|spy|keylog|trojan|malware|virus) ]]; then
                echo "⚠️  SUSPICIOUS PACKAGE NAME: $package_name"
            else
                echo "✓ $package_name"
            fi
        done
        echo ""

        echo "## Signature Database Status"
        echo "- Basic pattern matching: ✓ Active"
        echo "- Known malware signatures: Basic set loaded"
        echo "- YARA rules: Not available"
        echo "- VirusTotal integration: Not configured"
        echo ""

        echo "## Recommendations"
        echo "1. Install YARA for advanced signature scanning"
        echo "2. Configure malware signature databases"
        echo "3. Enable VirusTotal API integration"
        echo "4. Set up automatic malware scanning"

    } > "$output_file"
}

# Malware analysis menu
malware_analysis() {
    local device_serial="$1"

    while true; do
        echo
        echo "Malware Analysis"
        echo "================="
        echo "1. Scan Installed Applications"
        echo "2. Scan System Files"
        echo "3. Analyze Network Connections"
        echo "4. YARA Signature Scanning"
        echo "5. Full Malware Assessment"
        echo "0. Back to Main Menu"
        echo

        read -r -p "Choice: " choice

        case $choice in
            1) scan_installed_apps "$device_serial" ;;
            2) scan_system_files "$device_serial" ;;
            3) analyze_network_malware "$device_serial" ;;
            4) yara_malware_scan "$device_serial" ;;
            5) full_malware_assessment "$device_serial" ;;
            0) return 0 ;;
            *) log "ERROR" "Invalid choice" ;;
        esac
    done
}

# Full malware assessment
full_malware_assessment() {
    local device_serial="$1"
    local output_dir="$OUTPUT_DIR/full_malware_assessment_$(date +%Y%m%d_%H%M%S)"

    log "INFO" "Performing full malware assessment"

    mkdir -p "$output_dir"

    # Run all malware scans
    scan_installed_apps "$device_serial"
    mv "$OUTPUT_DIR/malware_scan_"* "$output_dir/" 2>/dev/null

    scan_system_files "$device_serial"
    mv "$OUTPUT_DIR/system_malware_scan_"* "$output_dir/" 2>/dev/null

    analyze_network_malware "$device_serial"
    mv "$OUTPUT_DIR/network_malware_analysis_"* "$output_dir/" 2>/dev/null

    # Create comprehensive report
    local report_file="$output_dir/comprehensive_report.txt"
    {
        echo "# Comprehensive Malware Assessment Report"
        echo "# Generated: $(date)"
        echo ""

        echo "## Assessment Summary"
        echo ""

        # Aggregate findings from all reports
        local total_findings=0

        # Count findings from app scan
        local app_scan_file
        app_scan_file=$(find "$output_dir" -name "malware_scan_*.txt" | head -1)
        if [[ -f "$app_scan_file" ]]; then
            local app_suspicious
            app_suspicious=$(grep -c "suspicious\|high-risk\|SUSPICIOUS\|HIGH-RISK" "$app_scan_file" 2>/dev/null || echo "0")
            echo "- Application scan: $app_suspicious suspicious apps found"
            ((total_findings += app_suspicious))
        fi

        # Count findings from system scan
        local sys_scan_file
        sys_scan_file=$(find "$output_dir" -name "system_malware_scan_*.txt" | head -1)
        if [[ -f "$sys_scan_file" ]]; then
            local sys_suspicious
            sys_suspicious=$(grep -c "⚠️" "$sys_scan_file" 2>/dev/null || echo "0")
            echo "- System file scan: $sys_suspicious suspicious files found"
            ((total_findings += sys_suspicious))
        fi

        # Count findings from network scan
        local net_scan_file
        net_scan_file=$(find "$output_dir" -name "network_malware_analysis_*.txt" | head -1)
        if [[ -f "$net_scan_file" ]]; then
            local net_suspicious
            net_suspicious=$(grep -c "⚠️\|SUSPICIOUS" "$net_scan_file" 2>/dev/null || echo "0")
            echo "- Network analysis: $net_suspicious suspicious connections found"
            ((total_findings += net_suspicious))
        fi

        echo "- Total suspicious indicators: $total_findings"
        echo ""

        echo "## Risk Assessment"
        if [[ $total_findings -eq 0 ]]; then
            echo "✓ LOW RISK: No suspicious indicators detected"
        elif [[ $total_findings -lt 5 ]]; then
            echo "⚠️  MEDIUM RISK: Some suspicious indicators found"
        else
            echo "🚨 HIGH RISK: Multiple suspicious indicators detected"
        fi
        echo ""

        echo "## Recommendations"
        echo ""

        if [[ $total_findings -gt 0 ]]; then
            echo "### Immediate Actions"
            echo "1. Review all flagged applications and files"
            echo "2. Remove any identified malicious software"
            echo "3. Change passwords and security credentials"
            echo "4. Run full system scan with updated signatures"
            echo ""

            echo "### Preventive Measures"
            echo "1. Install reputable antivirus software"
            echo "2. Keep system and applications updated"
            echo "3. Be cautious with app permissions"
            echo "4. Use official app stores only"
            echo "5. Enable Google Play Protect"
            echo ""
        fi

        echo "### Ongoing Security"
        echo "1. Regular malware scanning"
        echo "2. Monitor network connections"
        echo "3. Review app permissions periodically"
        echo "4. Keep security patches current"
        echo "5. Use strong authentication"

    } > "$report_file"

    log "SUCCESS" "Full malware assessment completed. $total_findings suspicious indicators found."
    log "INFO" "Results saved to $output_dir"
}
