Exemplo n.º 1
0
def logwatch(EMAIL):
    # logwatch - system log analyzer and reporter

    f_logwatch = '/etc/cron.daily/00logwatch'

    if not General.answer('Do you want to install and configure logwatch?'):
        return

    General.run_cmd('apt install logwatch -y')
    with open(f_logwatch, 'w') as file:
        file.write(f'''
    #!/bin/bash

    #Check if removed-but-not-purged
    test -x /usr/share/logwatch/scripts/logwatch.pl || exit 0

    #execute
    /usr/sbin/logwatch --output mail --format html --mailto {EMAIL} --range yesterday --service all
    ''')

    General.warning_message(
        'Restarting firewall Maybe existing ssh connections will be stopped\n')
    General.run_cmd('ufw --force enable')
Exemplo n.º 2
0
def psad(EMAIL):
    # iptables Intrusion Detection And Prevention with

    f_psad_conf = '/etc/psad/psad.conf'
    f_before_rules = '/etc/ufw/before.rules'
    f_before6_rules = '/etc/ufw/before6.rules'

    if not General.answer('Do you want to install and configure psad?'): return

    General.run_cmd('apt install psad -y')
    homenet = General.input_message('Type your Home net: ex(192.168.1.1/24) ')
    General.output_message('Configuring psad')
    General.change_lines(
        f_psad_conf,
        _1=[
            'EMAIL_ADDRESSES             root@localhost;',
            f'EMAIL_ADDRESSES             {EMAIL};\n'
        ],
        _2=[
            'HOSTNAME                     _CHANGEME_;',
            f'HOSTNAME                   {General.HOSTNAME};\n'
        ],
        _3=[
            'ENABLE_AUTO_IDS             N;',
            'ENABLE_AUTO_IDS             Y;\n'
        ],
        _4=[
            'HOME_NET                    any;',
            f'HOME_NET                    {homenet};\n'
        ],
        _5=[
            'PORT_RANGE_SCAN_THRESHOLD   1;',
            'PORT_RANGE_SCAN_THRESHOLD   2;\n'
        ],
        _6=[
            'ENABLE_MAC_ADDR_REPORTING   N;',
            'ENABLE_MAC_ADDR_REPORTING   Y;\n'
        ],
        _7=[
            'ALERT_ALL                   Y;',
            'ALERT_ALL                   N;\n'
        ])

    General.output_message(f'''
These changes have been made to the config '/etc/psad/psad.conf'.
If u need more advanced options feel free to modify it.
    - EMAIL_ADDRESSES             {EMAIL};
    - HOSTNAME                   {General.HOSTNAME};
    - ENABLE_AUTO_IDS             Y;
    - HOME_NET                    {homenet};
    - PORT_RANGE_SCAN_THRESHOLD   2;
    - ENABLE_MAC_ADDR_REPORTING   Y;
    - ALERT_ALL                   N;

                ''')

    with open(f_before_rules, 'r') as file:
        lines = file.readlines()
        text = file.read()
        if not (General.check_lines_in_file(
                f_before_rules, '# log all traffic so psad can analyze',
                '-A INPUT -j LOG --log-tcp-options --log-prefix "[IPTABLES]"',
                '-A FORWARD -j LOG --log-tcp-options --log-prefix "[IPTABLES]"'
        )):

            for index, line in enumerate(lines):
                if line.strip() == "COMMIT":
                    lines.insert(
                        index - 2,
                        '# log all traffic so psad can analyze\n-A INPUT -j LOG --log-tcp-options --log-prefix "[IPTABLES]"\n-A FORWARD -j LOG --log-tcp-options --log-prefix "[IPTABLES]"'
                    )
                    break
            with open(f_before_rules, 'w') as file:
                for line in lines:
                    file.write(line)

    with open(f_before6_rules, 'r') as file:
        lines = file.readlines()
        text = file.read()
        if not (General.check_lines_in_file(
                f_before_rules, '# log all traffic so psad can analyze',
                '-A INPUT -j LOG --log-tcp-options --log-prefix "[IPTABLES]"',
                '-A FORWARD -j LOG --log-tcp-options --log-prefix "[IPTABLES]"'
        )):
            for index, line in enumerate(lines):
                if line.strip() == "COMMIT":
                    lines.insert(
                        index - 2,
                        '# log all traffic so psad can analyze\n-A INPUT -j LOG --log-tcp-options --log-prefix "[IPTABLES]"\n-A FORWARD -j LOG --log-tcp-options --log-prefix "[IPTABLES]"'
                    )
                    break
            with open(f_before6_rules, 'w') as file:
                for line in lines:
                    file.write(line)

    General.warning_message('Restarting psad and Firewall..\n')
    General.warning_message('Maybe existing ssh connections will be stopped\n')
    General.run_cmd('ufw --force enable')
    General.run_cmd('ufw reload')
    subprocess.check_call(['psad', '-R'],
                          stdout=subprocess.PIPE,
                          stderr=subprocess.STDOUT)
    General.run_cmd('psad --sig-update')
    General.run_cmd('psad -H')
    General.output_message('Done')
Exemplo n.º 3
0
def ssh(SSH_ENABLE, EMAIL_ENABLE, SSH_PORT, EMAIL):

    f_ssh_config = '/etc/ssh/sshd_config'
    if not SSH_ENABLE or not EMAIL_ENABLE: return
    General.run_cmd("apt install ssh -y")
    options_list = [
        'Port', 'ClientAliveCountMax', 'ClientAliveInterval', 'LoginGraceTime',
        'MaxAuthTries', 'MaxSessions', 'MaxStartups', 'PasswordAuthentication',
        'AllowGroups', 'PermitRootLogin'
    ]

    for option in options_list:
        status1 = General.check_lines_in_file(f_ssh_config, option)
        status2 = General.check_lines_in_file(f_ssh_config, '#' + option)
        if not status1 and not status2:
            with open(f_ssh_config, 'a') as file:
                file.write(option + '\n')

    generate_key = General.answer('Do you want enable ssh for some users?')
    if generate_key:
        generate_root_key = General.answer(
            f'Do you also want to enable ssh for Current user [{General.USER}] ? '
        )
        if generate_root_key:
            key_path = f'/{General.USER}/.ssh/id_rsa'
            if not os.path.exists(key_path):
                key_pass = General.input_message(
                    'Enter a passphrase for the key (empty for no passphrase):'
                )
                General.run_cmd(
                    f'ssh-keygen -C "{EMAIL}" -b 2048 -t rsa -f {key_path} -q -N "{key_pass}"'
                )
                General.warning_message(
                    f'[ALERT] your private key has been sent by email to {EMAIL}, please retrieve and save it, after destroy the email\n'
                )
                time.sleep(3)
                General.run_cmd(
                    f'echo " DANGER here you will find your private key attached for your device, destroy this mail and its contents instantly." | mail -s "Private key for: {General.USER} on {General.HOSTNAME}" {EMAIL} -A {key_path}'
                )
            else:
                General.error_message(
                    'A key pair for the current user yet exists')
        else:
            General.change_lines(
                f_ssh_config,
                _19=['#PermitRootLogin yes', 'PermitRootLogin no\n'],
                _20=['PermitRootLogin yes', 'PermitRootLogin no\n'])

        General.run_cmd('groupadd sshusers')
        General.output_message("which user do you want to have ssh enabled?")
        while True:
            user = General.input_message("User to enable ssh  [S to skip]: ")
            if user.upper() in ['S', 'SKIP']: break

            if not UsersConfig.user_exists(user):
                General.error_message("User doesn't exists")
            else:
                General.run_cmd(f'usermod -a -G sshusers {user}')
                generate_key_for_user = General.answer(
                    f'[{user}] Do you want a ssh key pair for this user?')
                if generate_key_for_user:
                    key_path = f'/home/{user}/.ssh/id_rsa'
                    if not os.path.exists(f'/home/{user}/.ssh'):
                        os.mkdir(f'/home/{user}/.ssh')
                    if not os.path.exists(key_path):
                        key_pass = General.input_message(
                            'Enter a passphrase for the key (empty for no passphrase):'
                        )
                        General.run_cmd(
                            f'ssh-keygen -C "{EMAIL}" -b 2048 -t rsa -f {key_path} -q -N "{key_pass}"'
                        )
                        General.warning_message(
                            f'[ALERT] your private key has been sent by email to {EMAIL}, please retrieve and save it, after destroy the email\n'
                        )
                        time.sleep(3)
                        General.run_cmd(
                            f'echo " DANGER here you will find your private key attached for your device, destroy this mail and its contents instantly." | mail -s "Private key for: {user} on {General.HOSTNAME}" {EMAIL} -A {key_path}'
                        )
                    else:
                        General.error_message(
                            f'A key pair for the user "{user}" yet exists')

        General.change_lines(
            f_ssh_config,
            _1=['Port', f"Port {SSH_PORT}\n"],
            _2=['#Port', f"Port {SSH_PORT}\n"],
            _3=['ClientAliveCountMax', "ClientAliveCountMax 0\n"],
            _4=['#ClientAliveCountMax', "ClientAliveCountMax 0\n"],
            _5=['ClientAliveInterval', "ClientAliveInterval 300\n"],
            _6=['#ClientAliveInterval', "ClientAliveInterval 300\n"],
            _7=['LoginGraceTime', "LoginGraceTime 30\n"],
            _8=['#LoginGraceTime', "LoginGraceTime 30\n"],
            _9=['MaxAuthTries', "MaxAuthTries 2\n"],
            _10=['#MaxAuthTries', "MaxAuthTries 2\n"],
            _11=['MaxSessions', "MaxSessions 2\n"],
            _12=['#MaxSessions', "MaxSessions 2\n"],
            _13=['MaxStartups', "MaxStartups 2\n"],
            _14=['#MaxStartups', "MaxStartups 2\n"],
            _15=['PasswordAuthentication', "PasswordAuthentication no\n"],
            _16=['#PasswordAuthentication', "PasswordAuthentication no\n"],
            _17=['AllowGroups', "AllowGroups sshusers\n"],
            _18=['#AllowGroups', "AllowGroups sshusers\n"],
        )

        General.output_message('These changes have been made to the config')
        General.warning_message('/etc/ssh/sshd_config')
        General.output_message(
            f'''If u need more advanced options feel free to modify it.
    - Port                      {SSH_PORT};
    - ClientAliveCountMax                0;
    - ClientAliveInterval              300;
    - LoginGraceTime                    30;
    - MaxAuthTries                       2;
    - MaxSessions                        2;
    - MaxStartups                        2;
    - PasswordAuthentication            no;
    - AllowGroups                 sshusers;
    - PermitRootLogin                   no;
''')

        General.output_message(
            'removing all Diffie-Hellman keys that are less than 3072 bits long'
        )
        General.run_cmd(
            "awk '$5 >= 3071' /etc/ssh/moduli | sudo tee /etc/ssh/moduli.tmp")
        General.run_cmd('mv /etc/ssh/moduli.tmp /etc/ssh/moduli')

        response = General.answer('do you want to enable 2FA/MFA for SSH?')
        if response:
            General.warning_message(
                'Note: a user will only need to enter their 2FA/MFA code if they are logging on with their password but not if they are using SSH public/private keys.\n'
            )
            General.run_cmd('apt install libpam-google-authenticator -y')
            General.warning_message(
                '\n[ALERT]  Notice this can not run as root, at the next machine restart RUN "google-authenticator"\n'
            )
            time.sleep(5)
            General.output_message(
                'Select default option (y in most cases) for all the questions it asks and remember to save the emergency scratch codes.'
            )
            time.sleep(2)
            General.run_cmd(
                'echo -e "\nauth       required     pam_google_authenticator.so nullok         # added by $(whoami) on $(date +"%Y-%m-%d @ %H:%M:%S")" | tee -a /etc/pam.d/sshd'
            )
Exemplo n.º 4
0
def ufw(SSH_ENABLE, SSH_PORT):
    # Firewall With UFW

    f_ufw_smtptls = '/etc/ufw/applications.d/smtptls'

    if not General.answer('Do you want install and configure UFW?'): return

    General.run_cmd('apt install ufw -y')
    General.run_cmd(
        'ufw default deny outgoing comment "deny all outgoing traffic"',
        'ufw default deny incoming comment "deny all incoming traffic"',
        'ufw allow out 53 comment "allow DNS calls out"',
        'ufw allow out 123 comment "allow NTP out"',
        'ufw allow out http comment "allow HTTP traffic out"',
        'ufw allow out https comment "allow HTTPS traffic out"',
        'ufw allow out whois comment "allow whois"',
        'ufw allow out 25 comment "allow MAIL out"')
    with open(f_ufw_smtptls, 'w') as file:
        file.write('''
[SMTPTLS]
title=SMTP through TLS
description=This opens up the TLS port 465 for use with SMPT to send e-mails.
ports=465/tcp
            ''')
    General.run_cmd(
        'ufw allow out smtptls comment "open TLS port 465 for use with SMPT to send e-mails"'
    )
    General.output_message('''
The following ufw rules have been entered automatically:
- deny all outgoing traffic
- deny all incoming traffic
- allow DNS calls out-
- allow NTP out
- allow HTTP traffic out
- allow HTTPS traffic out
- allow whois
- allow SMPT out
- allow MAIL out
''')
    # ufw ssh rules
    if SSH_ENABLE and General.answer('(UFW) Do  you need ssh rule?'):
        General.run_cmd(
            f'ufw limit in {SSH_PORT} comment "allow SSH connections in"')
        General.output_message('Added Rules')

    # ufw ftp out rule
    if General.answer('(UFW) Do you need ftp out rule?'):
        General.run_cmd('ufw allow out ftp comment "allow FTP traffic out"')
        General.output_message('Added Rules')

    # ufw dhcp rule
    if General.answer('(UFW) Are you using DHCP?'):
        General.run_cmd(
            'ufw allow out 68 comment "allow the DHCP client to update"')
        General.output_message('Added Rules')

    # ufw http/https rule
    if General.answer(
            '(UFW) Do you nedd to allow http/https ( yes for websites servers ) ?'
    ):
        General.run_cmd('ufw allow http comment "allow http traffic update"')
        General.run_cmd('ufw allow https comment "allow https traffic update"')
        General.output_message('Added Rules')

    General.output_message('Starting Firewall')
    General.warning_message('Maybe existing ssh connections will be stopped\n')
    General.warning_message(
        'sometimes the next cmd get stuck so press ENTER after 1 minute')
    General.run_cmd('ufw --force enable')