#!/bin/bash

apt update
unattended-upgrade
systemctl enable apt-daily.timer 
systemctl enable apt-daily-upgrade.timer 
systemctl restart apt-daily.timer 
systemctl restart apt-daily-upgrade.timer 

# Get the SSH banner version using a Python script
ssh_banner=$(python3 - << 'EOF'
import socket

def get_ssh_banner():
    try:
        # Connect to localhost SSH server
        sock = socket.create_connection(('localhost', 22), timeout=2)
        banner = sock.recv(1024).decode(errors='ignore').strip()
        sock.close()
        return banner
    except Exception as e:
        return str(e)

banner = get_ssh_banner()
print(banner)
EOF
)

# Check if SSH banner extraction was successful
if [[ -z "$ssh_banner" ]]; then
    echo "Unable to determine OpenSSH version."
    exit 1
fi

# Define vulnerable and patched versions
vulnerable_versions=(
    'SSH-2.0-OpenSSH_1'
    'SSH-2.0-OpenSSH_2'
    'SSH-2.0-OpenSSH_3'
    'SSH-2.0-OpenSSH_4.0'
    'SSH-2.0-OpenSSH_4.1'
    'SSH-2.0-OpenSSH_4.2'
    'SSH-2.0-OpenSSH_4.3'
    'SSH-2.0-OpenSSH_4.4'
    'SSH-2.0-OpenSSH_8.5'
    'SSH-2.0-OpenSSH_8.6'
    'SSH-2.0-OpenSSH_8.7'
    'SSH-2.0-OpenSSH_8.8'
    'SSH-2.0-OpenSSH_8.9'
    'SSH-2.0-OpenSSH_9.0'
    'SSH-2.0-OpenSSH_9.1'
    'SSH-2.0-OpenSSH_9.2'
    'SSH-2.0-OpenSSH_9.3'
    'SSH-2.0-OpenSSH_9.4'
    'SSH-2.0-OpenSSH_9.5'
    'SSH-2.0-OpenSSH_9.6'
    'SSH-2.0-OpenSSH_9.7'
)

patched_versions=(
    'SSH-2.0-OpenSSH_8.9p1 Ubuntu-3ubuntu0.10'
    'SSH-2.0-OpenSSH_9.3p1 Ubuntu-3ubuntu3.6'
    'SSH-2.0-OpenSSH_9.6p1 Ubuntu-13.3'
    'SSH-2.0-OpenSSH_9.3p1 Ubuntu-1ubuntu3.6'
    'SSH-2.0-OpenSSH_9.2p1 Debian-2+deb12u3'
    'SSH-2.0-OpenSSH_8.4p1 Debian-5+deb11u3'
    'SSH-2.0-OpenSSH_9.7p1 Debian-7'
)


# Check if the current version is in the vulnerable list
for version in "${vulnerable_versions[@]}"; do
    if echo "$ssh_banner" | grep -q "$version"; then
        # If it matches a vulnerable version, check if it's patched
        for patched_version in "${patched_versions[@]}"; do
            if [[ "$ssh_banner" == "$patched_version" ]]; then
                echo "Your OpenSSH version $ssh_banner is not vulnerable to CVE-2024-6387."
                exit 0
            fi
        done
        echo "Your OpenSSH version $ssh_banner is vulnerable to CVE-2024-6387."
        exit 0
    fi
done

# If no matches found in vulnerable versions
echo "Your OpenSSH version $ssh_banner is not vulnerable."