tis-securized-ssh-config

2-40
Enhances the security of the SSH protocol and enables logging of user connections and commands.
1740 downloads
Download
See build result See VirusTotal scan
tis-securized-ssh-config icon
  • package : tis-securized-ssh-config
  • name : Securized SSH
  • version : 2-40
  • categories : Security
  • maintainer : Kévin GUERINEAU
  • editor :
  • licence :
  • locale : all
  • target_os : linux
  • impacted_process :
  • architecture : all
  • signature_date : 2023-12-16 10:00
  • size : 9.29 Ko
package           : tis-securized-ssh-config
version           : 2-40
architecture      : all
section           : base
priority          : optional
name              : Securized SSH
categories        : Security
maintainer        : Kévin GUERINEAU
description       : Enhances the security of the SSH protocol and enables logging of user connections and commands.
depends           : 
conflicts         : 
maturity          : PROD
locale            : all
target_os         : linux
min_wapt_version  : 2.2
sources           : 
installed_size    : 
impacted_process  : 
description_fr    : Renforce la sécurité du protocole SSH et active la journalisation des connexions et commandes des utilisateurs.
description_pl    : Zwiększa bezpieczeństwo protokołu SSH i umożliwia rejestrowanie połączeń i poleceń użytkownika.
description_de    : Erhöht die Sicherheit des SSH-Protokolls und aktiviert die Protokollierung von Benutzerverbindungen und Befehlen.
description_es    : Mejora la seguridad del protocolo SSH y permite el registro de conexiones y comandos de usuario.
description_pt    : Aumenta a segurança do protocolo SSH e permite o registo das ligações e comandos do utilizador.
description_it    : Migliora la sicurezza del protocollo SSH e consente di registrare le connessioni e i comandi degli utenti.
description_nl    : Verbetert de beveiliging van het SSH-protocol en maakt het loggen van gebruikersverbindingen en commando's mogelijk.
description_ru    : Повышает безопасность протокола SSH и позволяет вести журнал соединений и команд пользователя.
audit_schedule    : 1h
editor            : 
keywords          : 
licence           : 
homepage          : 
package_uuid      : 0db4bfb9-aade-46dc-ac48-923b543f68cc
valid_from        : 
valid_until       : 
forced_install_on : 
changelog         : 
min_os_version    : 
max_os_version    : 
icon_sha256sum    : 9420721210f5d9c50c9e35c9fdbf0a088b30e165df8311c5f2176ce60e122475
signer            : Tranquil IT
signer_fingerprint: 8c5127a75392be9cc9afd0dbae1222a673072c308c14d88ab246e23832e8c6bb
signature         : rwhk3eBEUHp+FHFdZF9vbj4kzw8FWVhOT6p1RqVsbh6iVGyhFKOurpZD5RXqO5ZZ6mMxeTvgBjfGRbsfGaiseYBRGmn6Ijed94ESOo2CWiVhmIWPMmz7mp/zU9PPKiWUYwFslYXDPaNOOMCsD93aCBFhrESD8m8RrmZGzLeC+Vaof54RIXwWGEpm0GR2yNeZzzE8RcZDQJBaLSSIMTatMQAXS75yqNH8iEfgI2WO9u+j/ee85Lvjhbt1GbG5ii7Rn/gfm1rCinJEf+/pmCR9u1F10zk4lhsg25e9Gduz4wprKWIx5rtbMA/YFuFXQGuUy729PnmXPNqW356IS82tKA==
signature_date    : 2023-12-16T10:00:08.365396
signed_attributes : package,version,architecture,section,priority,name,categories,maintainer,description,depends,conflicts,maturity,locale,target_os,min_wapt_version,sources,installed_size,impacted_process,description_fr,description_pl,description_de,description_es,description_pt,description_it,description_nl,description_ru,audit_schedule,editor,keywords,licence,homepage,package_uuid,valid_from,valid_until,forced_install_on,changelog,min_os_version,max_os_version,icon_sha256sum,signer,signer_fingerprint,signature_date,signed_attributes
# -*- coding: utf-8 -*-
from setuphelpers import *
import re
import datetime
import jinja2

###################
#
# This package is inspireted by "(Open)SSH secure use recommendations" documentation
# from National Cybersecurity Agency of France / ANSSI.
# English link : https://www.ssi.gouv.fr/en/guide/openssh-secure-use-recommendations/
# Franch link : https://www.ssi.gouv.fr/guide/recommandations-pour-un-usage-securise-dopenssh/
#
###################

# If you want to recording all command, set True
trap_command = False

options_list_check = ['Protocol 2','Port 22','#HostKey /etc/ssh/ssh_host_rsa_key','#HostKey /etc/ssh/ssh_host_ecdsa_key','HostKey /etc/ssh/ssh_host_ed25519_key',
'LoginGraceTime 2m','PermitRootLogin no','StrictModes yes','PasswordAuthentication no','PermitEmptyPasswords no','ChallengeResponseAuthentication no',
'UsePAM yes','AllowTcpForwarding no','X11Forwarding no','TCPKeepAlive yes','ClientAliveInterval 600','ClientAliveCountMax 0','PermitUserEnvironment no',
'AllowAgentForwarding no','MaxAuthTries 5','PermitTunnel no','LogLevel VERBOSE']

# If some servers need other AllowUsers than define in get_allow_users().
add_allow_users = {'server':{'user':'user@server','comment':'servername'}
                }

sshd_config_file = makepath('/etc','ssh','sshd_config')
sshd_config_dir = makepath('/etc','ssh','sshd_config.d')


def get_allow_users():
    add_user = ''
    add_comment = ''
    for server in add_allow_users:
        if get_computername().lower() == server:
            add_user = add_allow_users[server]['user']
            add_comment = add_allow_users[server]['comment']

    default_allow_users = f"""AllowUsers admin {add_user}
#                       {add_comment}
"""
    return default_allow_users


def install():
    print("Installing: %s" % control.package)

    error('This package is protect against accidental launch. To disable the protection, edit the package and remove this line')

    options_add = []
    options_in = []

    for option in options_list_check:
        pattern = re.compile("^(%s)$" % option)

        for line in open(sshd_config_file):
            for match in re.finditer(pattern, line):
                options_in.append(line.replace('\n',''))

    pattern_allow_users = re.compile("^%s$" % get_allow_users().split('\n')[0])
    for line in open(sshd_config_file):
        for match in re.finditer(pattern_allow_users,line):
            options_in.append(line.split('\n')[0])

    options_list_check.append(get_allow_users().split('\n')[0])

    print('Parameters already set : %s' % options_in)

    for option in options_list_check:
        if option in options_in:
            pass
        else:
            options_add.append(option)

    print('This parameters are to set : %s' % options_add)

    if len(options_add)>0:
        print('Backup old file config')
        backup_file = makepath('/etc','ssh','sshd_config.old')
        if isfile(backup_file):
            backup_file =  makepath('/etc','ssh','sshd_config.old%s' % datetime.datetime.now().strftime("%Y%m%d_%H%M%S"))
        filecopyto(sshd_config_file,backup_file)

        jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader('templates'))
        template = jinja_env.get_template('sshd_config.j2')

        template_variables = {
            'allow_users': get_allow_users(),
        }
        config_string = template.render(template_variables)

        print(f'Create sshd_config configuration file with allow_users {get_allow_users()}')
        with open(makepath('/etc','ssh','sshd_config'), 'wt') as dst_file:
            dst_file.write(config_string)

        print('Set 600 permission on sshd_config file')
        run('chmod 600 /etc/ssh/sshd_config')

        print('Set root ownership on sshd_config file')
        run('chown root:root /etc/ssh/sshd_config')

        print('Set permissions on /etc/ssh/sshd_config')

        run('chown root:root /etc/ssh/sshd_config')
        run('chmod og-rwx /etc/ssh/sshd_config')
        
    if not isdir(sshd_config_dir):
        mkdirs(sshd_config_dir)

    filecopyto('files/ciphers.conf',sshd_config_dir)
    run('chown -R root:root /etc/ssh/sshd_config.d/')
    run('chmod -R 600 /etc/ssh/sshd_config.d/')

    print('Restart sshd')
    run('systemctl restart sshd')


    if trap_command:

        print('Set trap login')

        trap_syslog = """function trap_to_syslog {
    printf "%s %s from %s %s" "$HOSTNAME" "$SSHCLIENTUSER" "$SSH_CLIENT" "$USER[$$]@$PWD> $BASH_COMMAND" |logger -p local3.notice
    }
    trap trap_to_syslog DEBUG

        """

        print('Check')
        enable_trap = False
        if is_debian_based():
            bashrc_path = makepath('/etc','bash.bashrc')
        else:
            bashrc_path = makepath('/etc','bashrc')

        for line in open(bashrc_path):
            for match in re.finditer('^(function trap_to_syslog {)$',line):
                enable_trap = True

        if not enable_trap:
            print('Set trap syslog')
            with open(bashrc_path, 'a') as bashrc:
                bashrc.write(trap_syslog)


def audit():

    options_add = []
    options_in = []
    for option in options_list_check:
        pattern = re.compile("^(%s)$" % option)
        for line in open(sshd_config_file):
            for match in re.finditer(pattern, line):
                options_in.append(line.replace('\n',''))

    pattern_allow_users = re.compile("^%s$" % get_allow_users().split('\n')[0])
    for line in open(sshd_config_file):
        for match in re.finditer(pattern_allow_users,line):
            options_in.append(line.split('\n')[0])

    options_list_check.append(get_allow_users().split('\n')[0])

    for option in options_list_check:
        if option in options_in:
            pass
        else:
            options_add.append(option)

    if len(options_add) > 0:
        print('Some parameters are wrongs ! %s' % options_add)
        WAPT.write_audit_data_if_changed("Securized SSH", 'Parameters in fault', options_add, keep_days=365)
        return "ERROR"
    else:
        print('All parameters are OK')
        WAPT.write_audit_data_if_changed("Securized SSH", 'Parameters in fault', "OK", keep_days=365)
        return "OK"
c0c18c4a954938ab95934ded88e4cc6d764bd2b128de31fac1da93c20162476c : files/ciphers.conf
b91ec36e779db37b255ccd9c0e11bab38babaa79b7ee04926a2b217f3d3999be : setup.py
49c144817afd0c0388b78a005e469637b8dbd922141acb348f56aaad7f8e49db : templates/sshd_config.j2
9420721210f5d9c50c9e35c9fdbf0a088b30e165df8311c5f2176ce60e122475 : WAPT/icon.png
a5a97261381e1d0ad46ee15916abec9c2631d0201f5cc50ceb0197a165a0bbbf : WAPT/certificate.crt
7e867718fa4b532a9e06a6d5bafb18356448adfa4de30fe9c0224b1481acff16 : luti.json
5efc81c0e4e99b9b2bfef38a957210d03d9261d0464f6409c78091963a610374 : WAPT/control