# coding: utf-8

import re
from os import path
from subprocess import call, check_output, run


# 3 levels to tests: low, medium anh high
CHECKSLIST = {}

# TIPS
# https://www.process.st/server-security/

def identifySystem():
    os = None
    with open('/etc/issue', 'r') as f:
        line = f.readline() 
        if re.search('Arch Linux', line):
            os = 'ARCHLINUX'
        elif re.search('Ubuntu', line):
            os = 'UBUNTU'
        elif re.search('Debian', line):
            os = 'DEBIAN'
        else:
            os = 'UNKNOWN'

    return os

def check_upgrade_packages():
    pass

def check_telnet_is_open():
    # check port 23 is listening
    r = run(['ss', '-atn'], capture_output=True)
    r = r.stdout.decode()
    print(r)

def check_empty_local_passwords():
    pass

def check_security_access():
    # Check in /etc/security/access
    pass

def check_hosts_allow():
    # Check in /etc/hosts.allow
    pass

def check_sshd_root():
    res = False

    if not path.exists("/etc/ssh/sshd_config"):
        print("File sshd_config doesn't exist")
        return False
    
    with open("/etc/ssh/sshd_config", "r") as f:
        for l in f.readlines():
            l = l.replace('\n', '')
            if re.search("PermitRootLogin.*root", l):
                if not re.search("^#", l):
                    res = True
    return res

def generateChecksList():
    # LOW
    CHECKSLIST['low'] = []
    CHECKSLIST['low'].append({
        'callback': check_sshd_root,
        'name': check_sshd_root.__name__,
        'resolution': 'Please, remove root auth to your server',
        'score': 100
    })
    CHECKSLIST['low'].append({
        'callback': check_upgrade_packages,
        'name': check_upgrade_packages.__name__,
        'resolution': 'Please, upgrade your packages',
        'score': 50
    })
    CHECKSLIST['low'].append({
        'callback': check_telnet_is_open,
        'name': check_telnet_is_open.__name__,
        'resolution': 'Telnet is enabled. Please, disabled this program if you could.',
        'score': 50
    })
    # MEDIUM 
    CHECKSLIST['medium'] = {}
    # HIGH
    CHECKSLIST['high'] = {}

def getTotalScore():
    score = 0
    for entry in CHECKSLIST['low']:
        score += entry['score']

    return score
    
def main():
    # Generate our checklist
    generateChecksList()

    # Get total score
    totalScore = getTotalScore()

    # Identify system
    identifySystem()

    score = totalScore 
    for entry in CHECKSLIST['low']:
        print(f'Checking {entry["name"]}...')
        res =  entry['callback']()
        if res:
            print(entry['resolution'])
            score -= entry['score']

    print(f'Your total score: {score}')

if __name__ == "__main__":
    main()