Giter Site home page Giter Site logo

geerlingguy / ansible-role-security Goto Github PK

View Code? Open in Web Editor NEW
792.0 25.0 200.0 83 KB

Ansible Role - Security

Home Page: https://galaxy.ansible.com/geerlingguy/security/

License: MIT License

Jinja 100.00%
ansible role security centos rhel linux ubuntu debian fedora redhat

ansible-role-security's Introduction

Ansible Role: Security (Basics)

CI

First, a major, MAJOR caveat: the security of your servers is YOUR responsibility. If you think simply including this role and adding a firewall makes a server secure, then you're mistaken. Read up on Linux, network, and application security, and know that no matter how much you know, you can always make every part of your stack more secure.

That being said, this role performs some basic security configuration on RedHat and Debian-based linux systems. It attempts to:

  • Install software to monitor bad SSH access (fail2ban)
  • Configure SSH to be more secure (disabling root login, requiring key-based authentication, and allowing a custom SSH port to be set)
  • Set up automatic updates (if configured to do so)

There are a few other things you may or may not want to do (which are not included in this role) to make sure your servers are more secure, like:

  • Use logwatch or a centralized logging server to analyze and monitor log files
  • Securely configure user accounts and SSH keys (this role assumes you're not using password authentication or logging in as root)
  • Have a well-configured firewall (check out the geerlingguy.firewall role on Ansible Galaxy for a flexible example)

Again: Your servers' security is your responsibility.

Requirements

For obvious reasons, sudo must be installed if you want to manage the sudoers file with this role.

On RedHat/CentOS systems, make sure you have the EPEL repository installed (you can include the geerlingguy.repo-epel role to get it installed).

No special requirements for Debian/Ubuntu systems.

Role Variables

Available variables are listed below, along with default values (see defaults/main.yml):

security_ssh_port: 22

The port through which you'd like SSH to be accessible. The default is port 22, but if you're operating a server on the open internet, and have no firewall blocking access to port 22, you'll quickly find that thousands of login attempts per day are not uncommon. You can change the port to a nonstandard port (e.g. 2849) if you want to avoid these thousands of automated penetration attempts.

security_ssh_password_authentication: "no"
security_ssh_permit_root_login: "no"
security_ssh_usedns: "no"
security_ssh_permit_empty_password: "no"
security_ssh_challenge_response_auth: "no"
security_ssh_gss_api_authentication: "no"
security_ssh_x11_forwarding: "no"

Security settings for SSH authentication. It's best to leave these set to "no", but there are times (especially during initial server configuration or when you don't have key-based authentication in place) when one or all may be safely set to 'yes'. NOTE: It is very important that you quote the 'yes' or 'no' values. Failure to do so may lock you out of your server.

security_ssh_allowed_users: []
# - alice
# - bob
# - charlie

A list of users allowed to connect to the host over SSH. If no user is defined in the list, the task will be skipped.

security_ssh_allowed_groups: []
# - admins
# - devs

A list of groups allowed to connect to the host over SSH. If no group is defined in the list, the task will be skipped.

security_sshd_state: started

The state of the SSH daemon. Typically this should remain started.

security_ssh_restart_handler_state: restarted

The state of the restart ssh handler. Typically this should remain restarted.

security_sudoers_passwordless: []
security_sudoers_passworded: []

A list of users who should be added to the sudoers file so they can run any command as root (via sudo) either without a password or requiring a password for each command, respectively.

security_autoupdate_enabled: true

Whether to install/enable yum-cron (RedHat-based systems) or unattended-upgrades (Debian-based systems). System restarts will not happen automatically in any case, and automatic upgrades are no excuse for sloppy patch and package management, but automatic updates can be helpful as yet another security measure.

security_autoupdate_blacklist: []

(Debian/Ubuntu only) A listing of packages that should not be automatically updated.

security_autoupdate_additional_origins: []
# - "${distro_id}ESM:${distro_codename}-infra-security"
# - "Docker:${distro_codename}"

(Debian/Ubuntu only) A listing of origins to reference.

security_autoupdate_reboot: false

(Debian/Ubuntu only) Whether to reboot when needed during unattended upgrades.

security_autoupdate_reboot_time: "03:00"

(Debian/Ubuntu only) The time to trigger a reboot, when needed, if security_autoupdate_reboot is set to true. In 24h "hh:mm" clock format.

security_autoupdate_mail_to: ""
security_autoupdate_mail_on_error: true

(Debian/Ubuntu only) If security_autoupdate_mail_to is set to an non empty value, unattended upgrades will send an e-mail to that address when some error occurs. You may either set this to a full email: [email protected] or to something like root, which will use /etc/aliases to route the message. If you set security_autoupdate_mail_on_error to false you'll get an email after every package install.

security_fail2ban_enabled: true

Whether to install/enable fail2ban. You might not want to use fail2ban if you're already using some other service for login and intrusion detection (e.g. ConfigServer).

security_fail2ban_custom_configuration_template: "jail.local.j2"

The name of the template file used to generate fail2ban's configuration.

Dependencies

None.

Example Playbook

- hosts: servers
  vars_files:
    - vars/main.yml
  roles:
    - geerlingguy.security

Inside vars/main.yml:

security_sudoers_passworded:
  - johndoe
  - deployacct

License

MIT (Expat) / BSD

Author Information

This role was created in 2014 by Jeff Geerling, author of Ansible for DevOps.

ansible-role-security's People

Contributors

a-fro avatar brutalbirdie avatar bruvv avatar bvansomeren avatar ckng avatar f-lopes avatar fapdash avatar fwilhe avatar geerlingguy avatar githuberik avatar hkcomori avatar joestewart avatar jonpugh avatar macavirus avatar niftymist avatar opdavies avatar oxyc avatar sjugge avatar staticdev avatar stepanbaghdasaryan avatar wizonesolutions avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ansible-role-security's Issues

Optionally disable auditd (for raspberry pi)

I am trying to use this role for setting up my raspberry pi(s). All seems to work except auditd.

...", "Errors were encountered while processing:", " auditd"]}

After looking into it, it seems that raspbian is compiled without auditd support (raspberrypi/linux#1352). Is it possible to create a variable with which auditd support can be disabled?

10periodic vs 20auto-upgrades

Any particular reason you put APT::Periodic::Unattended-Upgrade in 10periodic and not in 20auto-upgrades? 20auto-upgrades also has this setting and since it comes after alphabetically, it will overwrite 10periodic setting I believe.

Could be wrong on this but was digging into why auto-upgrades haven't been happening on my personal server after using this role and I think this is why.

Add validation to sshd_config update

Any plans to add validation using the equivalent of sshd -f /etc/ssh/sshd_config -t when updating the sshd_config file?

This will prevent this role from breaking SSH, which can happen without validation - for example if someone has made an invalid change to the config without restarting sshd, or if a modified version of this role includes invalid config.

It could work in similar way to the sudoers config validation, using the validate: feature of lineinfile.

SSH regexp not handling all situations.

Currently the regular expressions use something like the following ^PasswordAuthentication but it will not handle default situations

#PasswordAuthentication: yes

the expressions should really be something like ^[#]?PasswordAuthentication so that it will handle commented out lines, and maybe add in a \s+ to allow for a spaces to be added.

Thanks.

Destination /etc/fail2ban not writable

I just build a playbook using this role and I am running into an issue when trying to update the fail2ban config. I am getting the following error.

TASK [geerlingguy.security : Copy fail2ban custom configuration file into place.] **********************************************************************************************************************************************************
fatal: [minecraftchest1-matrix.eastus.cloudapp.azure.com]: FAILED! => {"changed": false, "checksum": "ce41e7269276a49e2c26a78403b2cd3d75985d0c", "msg": "Destination /etc/fail2ban not writable"}

unattended-upgrades config is broken in Debian

http://security.ubuntu.com/ubuntu/dists/precise-security/Release

Origin: Ubuntu
Label: Ubuntu
Suite: precise-security
Version: 12.04
Codename: precise

vs
http://security.debian.org/debian-security/dists/stretch/updates/Release

Origin: Debian
Label: Debian-Security
Suite: stable
Version: 9
Codename: stretch

templates/50unattended-upgrades.j2 has:

Unattended-Upgrade::Allowed-Origins {                                          
        "${distro_id} ${distro_codename}-security";                            
//      "${distro_id} ${distro_codename}-updates";                             
};                                                                             

which works for ubuntu's precise-security but not Debian's stable.

unattended-upgrade's README.md has the following:

Allowed-Origins is a simple list of patterns of the form
"origin:archive".

Origins-Pattern allows you to give a list of
(glob-style) patterns to match against. For example:

 Unattended-Upgrade::Origins-Pattern {                                       
        "origin=Google\, Inc.,suite=contrib";                                
        "site=www.example.com,component=main";                               
 };                                                                          

Again per the README.md, ${distro_codename} contains the output of lsb_release -c, which is stretch, xenial, etc.
The archive is based on the Suite which is percise-updates for ubuntu and stable for Debian.

As such, the default config means that no packages are matched by unattended-upgrades in Debian.
One fix is to add "${distro_id} stable"; to Allowed-Origins, but even better would to use the upstream 50unattended-upgrades which is created in the unattended-upgrades postinst.

In Debian:

Unattended-Upgrade::Origins-Pattern {
        "origin=Debian,codename=${distro_codename},label=Debian-Security";
};

and in Ubuntu:

Unattended-Upgrade::Allowed-Origins {
        "${distro_id}:${distro_codename}";
        "${distro_id}:${distro_codename}-security";
        "${distro_id}ESM:${distro_codename}";
};

I'm not sure the best method for a fix. I think a template for 50unattended-upgrades is not ideal, and instead this role should switch to using lineinfile for

security_autoupdate_blacklist: []                                              
security_autoupdate_mail_to: ""                                                
security_autoupdate_mail_on_error: true                                        

That doesn't explain what to do with other systems which already have a nonworking config. I'm not sure how much retroactive fixing is appropriate for this role, but on my systems I found that I can restore the upstream 50unattended-upgrades by:

  # UCF has some weirdness where even if you set FORCE_CONFFNEW, if the file   
  # is user modified, it uses a hash calculated when the conf file was last    
  # touched by a package. To workaround, delete and then rely on CONFFMISS.    
  - name: Remove bad unattended-upgrades                                       
    file:                                                                      
      path: /etc/apt/apt.conf.d/50unattended-upgrades                          
      state: absent                                                            
                                                                               
  - name: Set back to default unattended-upgrades configuration                
    command: dpkg-reconfigure --default-priority unattended-upgrades           
    environment:                                                               
      UCF_FORCE_CONFFMISS: True                                                

(or in the shell:

sudo rm /etc/apt/apt.conf.d/sudo rm 50unattended-upgrades
env UCF_FORCE_CONFFMISS=1 sudo -E dpkg-reconfigure --default-priority unattended-upgrades

)

CentOS 7 Docker test gets stuck starting Fail2Ban

During the Travis tests, CentOS 7 gets stuck on:

TASK [role_under_test : Ensure fail2ban is running and enabled on boot.] *******

No output has been received in the last 10m0s, this potentially indicates a stalled build or something wrong with the build itself.

The build has been terminated

I can reproduce the issue on Docker for Mac 1.12.0/.1, and if I run journalctl --no-pager, I notice a lot of the following:

Sep 16 15:33:54 1b08686e974b systemd[1]: Looping too fast. Throttling execution a little.
Sep 16 15:33:56 1b08686e974b systemd[1]: Looping too fast. Throttling execution a little.
Sep 16 15:33:57 1b08686e974b systemd[1]: Looping too fast. Throttling execution a little.
Sep 16 15:33:58 1b08686e974b systemd[1]: Looping too fast. Throttling execution a little.
Sep 16 15:34:00 1b08686e974b systemd[1]: Looping too fast. Throttling execution a little.
Sep 16 15:34:01 1b08686e974b systemd[1]: Looping too fast. Throttling execution a little.
Sep 16 15:34:02 1b08686e974b systemd[1]: Looping too fast. Throttling execution a little.

It seems these messages occur after I install fail2ban, which triggers an update to systemd (with yum install -y fail2ban):

Sep 16 15:39:31 7c6e69e84968 yum[201]: Installed: python-decorator-3.4.0-3.el7.noarch
Sep 16 15:39:31 7c6e69e84968 yum[201]: Updated: systemd-libs-219-19.el7_2.13.x86_64
Sep 16 15:39:31 7c6e69e84968 systemd[1]: Closed udev Control Socket.
Sep 16 15:39:31 7c6e69e84968 systemd[1]: Closed udev Kernel Socket.
Sep 16 15:39:31 7c6e69e84968 systemd[1]: Stopped udev Kernel Device Manager.
Sep 16 15:39:32 7c6e69e84968 systemd[1]: Reexecuting.
Sep 16 15:39:32 7c6e69e84968 systemd[1]: systemd 219 running in system mode. (+PAM +AUDIT +SELINUX +IMA -APPARMOR +SMACK +SYSVINIT +UTMP +LIBCRYPTSETUP +GCRYPT +GNUTLS +ACL +XZ -LZ4 -SECCOMP +BLKID +ELFUTILS +KMOD +IDN)
Sep 16 15:39:32 7c6e69e84968 systemd[1]: Detected virtualization docker.
Sep 16 15:39:32 7c6e69e84968 systemd[1]: Detected architecture x86-64.
Sep 16 15:39:32 7c6e69e84968 systemd[1]: Failed to install release agent, ignoring: File exists
Sep 16 15:39:57 7c6e69e84968 systemd[1]: Failed to register match for Disconnected message: Connection timed out
Sep 16 15:40:22 7c6e69e84968 systemd[1]: Failed to register match for Disconnected message: Connection timed out
Sep 16 15:40:22 7c6e69e84968 systemd[1]: Looping too fast. Throttling execution a little.
Sep 16 15:40:22 7c6e69e84968 yum[201]: Updated: systemd-219-19.el7_2.13.x86_64
Sep 16 15:40:23 7c6e69e84968 systemd[1]: Configuration file /usr/lib/systemd/system/ebtables.service is marked executable. Please remove executable permission bits. Proceeding anyway.
Sep 16 15:40:23 7c6e69e84968 systemd[1]: Configuration file /usr/lib/systemd/system/ebtables.service is marked executable. Please remove executable permission bits. Proceeding anyway.
Sep 16 15:40:23 7c6e69e84968 systemd[1]: Reloading.
Sep 16 15:40:23 7c6e69e84968 yum[201]: Installed: ebtables-2.0.10-13.el7.x86_64
Sep 16 15:40:24 7c6e69e84968 yum[201]: Installed: systemd-python-219-19.el7_2.13.x86_64
Sep 16 15:40:24 7c6e69e84968 yum[201]: Installed: grubby-8.28-17.el7.x86_64
Sep 16 15:40:24 7c6e69e84968 systemd[1]: Looping too fast. Throttling execution a little.
Sep 16 15:40:24 7c6e69e84968 yum[201]: Installed: ssmtp-2.64-14.el7.x86_64
Sep 16 15:40:24 7c6e69e84968 yum[201]: Installed: libselinux-python-2.2.2-6.el7.x86_64
Sep 16 15:40:24 7c6e69e84968 yum[201]: Installed: python-slip-0.4.0-2.el7.noarch
Sep 16 15:40:24 7c6e69e84968 yum[201]: Installed: python-slip-dbus-0.4.0-2.el7.noarch
Sep 16 15:40:25 7c6e69e84968 systemd[1]: Configuration file /usr/lib/systemd/system/ebtables.service is marked executable. Please remove executable permission bits. Proceeding anyway.
Sep 16 15:40:25 7c6e69e84968 systemd[1]: Reloading.
Sep 16 15:40:25 7c6e69e84968 systemd[1]: Configuration file /usr/lib/systemd/system/ebtables.service is marked executable. Please remove executable permission bits. Proceeding anyway.
Sep 16 15:40:25 7c6e69e84968 yum[201]: Installed: firewalld-0.3.9-14.el7.noarch
Sep 16 15:40:25 7c6e69e84968 systemd[1]: Looping too fast. Throttling execution a little.
Sep 16 15:40:26 7c6e69e84968 systemd[1]: Looping too fast. Throttling execution a little.
Sep 16 15:40:27 7c6e69e84968 systemd[1]: Looping too fast. Throttling execution a little.
Sep 16 15:40:28 7c6e69e84968 yum[201]: Installed: linux-firmware-20150904-43.git6ebf5d5.el7.noarch
Sep 16 15:40:29 7c6e69e84968 systemd[1]: Looping too fast. Throttling execution a little.
Sep 16 15:40:30 7c6e69e84968 systemd[1]: Looping too fast. Throttling execution a little.
Sep 16 15:40:31 7c6e69e84968 systemd[1]: Looping too fast. Throttling execution a little.
Sep 16 15:40:32 7c6e69e84968 systemd[1]: Looping too fast. Throttling execution a little.

Some references that could be helpful:

Insecure SSH algorithms present

The role gives a false impression that SSH is more secure by applying this role.

In order to make sure that SSH service only allows secure (as of today) algorithms, a line with specific algorithms needs to be specified. Otherwise service will use all available cipher suites etc.
Add the following stuff wherever appropriate:
security_ssh_ciphers: "aes128-ctr,aes192-ctr,aes256-ctr"
security_ssh_host_key_algorithms: "ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-rsa,ssh-dss"
security_ssh_macs: "hmac-sha2-256,hmac-sha2-512"
security_ssh_kex_algorithms: "ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256"

CentOS 8 doesn't have a default package for fail2ban

On CentOS 8:

TASK [geerlingguy.security : Install fail2ban.] ********************************
fatal: [kube2]: FAILED! => {"changed": false, "failures": ["No package fail2ban available."], "msg": "Failed to install some of the specified packages", "rc": 1, "results": []}
fatal: [kube1]: FAILED! => {"changed": false, "failures": ["No package fail2ban available."], "msg": "Failed to install some of the specified packages", "rc": 1, "results": []}
fatal: [kube3]: FAILED! => {"changed": false, "failures": ["No package fail2ban available."], "msg": "Failed to install some of the specified packages", "rc": 1, "results": []}

Unattended upgrades seems broken on Debian-10

Hi,

The unattended-upgrades process seems to never find candidates to applay security upgrades.

Looking at the template 50unattended-upgrades.j2, the Allowed-Origin block looks outdated:

Unattended-Upgrade::Allowed-Origins {
        "${distro_id} ${distro_codename}-security";
//      "${distro_id} ${distro_codename}-updates";
};

The Debian-10 default file comes with:

Unattended-Upgrade::Origins-Pattern {
        // Codename based matching:
        // This will follow the migration of a release through different
        // archives (e.g. from testing to stable and later oldstable).
        // Software will be the latest available for the named release,
        // but the Debian release itself will not be automatically upgraded.
//      "origin=Debian,codename=${distro_codename}-updates";
//      "origin=Debian,codename=${distro_codename}-proposed-updates";
        "origin=Debian,codename=${distro_codename},label=Debian";
        "origin=Debian,codename=${distro_codename},label=Debian-Security";

        // Archive or Suite based matching:
        // Note that this will silently match a different release after
        // migration to the specified archive (e.g. testing becomes the
        // new stable).
//      "o=Debian,a=stable";
//      "o=Debian,a=stable-updates";
//      "o=Debian,a=proposed-updates";
//      "o=Debian Backports,a=${distro_codename}-backports,l=Debian Backports";
};

Logs wiped on Centos 6.4 host

I've tried running this role on a few different hosts, and I've just noticed that all the logs in /var/log/secure were empty on one of them.

I think this might be due to an issue with fail2ban's log rotation on Centos 6 fail2ban/fail2ban#44

Permission Denied on sudoers file?

Thanks for all of the great work you do in the Ansible realm!

Today, randomly, I started getting this error:

    amazon-ebs: failed: [default] (item=ubuntu) => changed=false
    amazon-ebs:   item: ubuntu
    amazon-ebs:   module_stderr: |-
    amazon-ebs:     Shared connection to 127.0.0.1 closed.
    amazon-ebs:   module_stdout: |-
    amazon-ebs:     Traceback (most recent call last):
    amazon-ebs:       File "/home/ubuntu/.ansible/tmp/ansible-tmp-1569859033.2080152-69441553871837/AnsiballZ_lineinfile.py", line 113, in <module>
    amazon-ebs:         _ansiballz_main()
    amazon-ebs:       File "/home/ubuntu/.ansible/tmp/ansible-tmp-1569859033.2080152-69441553871837/AnsiballZ_lineinfile.py", line 105, in _ansiballz_main
    amazon-ebs:         invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)
    amazon-ebs:       File "/home/ubuntu/.ansible/tmp/ansible-tmp-1569859033.2080152-69441553871837/AnsiballZ_lineinfile.py", line 48, in invoke_module
    amazon-ebs:         imp.load_module('__main__', mod, module, MOD_DESC)
    amazon-ebs:       File "/usr/lib/python3.6/imp.py", line 235, in load_module
    amazon-ebs:         return load_source(name, filename, file)
    amazon-ebs:       File "/usr/lib/python3.6/imp.py", line 170, in load_source
    amazon-ebs:         module = _exec(spec, sys.modules[name])
    amazon-ebs:       File "<frozen importlib._bootstrap>", line 618, in _exec
    amazon-ebs:       File "<frozen importlib._bootstrap_external>", line 678, in exec_module
    amazon-ebs:       File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
    amazon-ebs:       File "/tmp/ansible_lineinfile_payload_sj_er2a2/__main__.py", line 524, in <module>
    amazon-ebs:       File "/tmp/ansible_lineinfile_payload_sj_er2a2/__main__.py", line 515, in main
    amazon-ebs:       File "/tmp/ansible_lineinfile_payload_sj_er2a2/__main__.py", line 257, in present
    amazon-ebs:     PermissionError: [Errno 13] Permission denied: b'/etc/sudoers'
    amazon-ebs:   msg: |-
    amazon-ebs:     MODULE FAILURE
    amazon-ebs:     See stdout/stderr for the exact error
    amazon-ebs:   rc: 1
    amazon-ebs:

I'm provisioning remotely with Ansible, through packer.

This has worked a ton of times before, and today, out of the blue, it stopped working. I'm kind of confused.

I'm assuming nothing's changed, but I wonder if maybe you've seen this before?

Fail2ban still failing on Travis CI

I have hangout still with fail2ban even if I have the latest version of your centos7 docker image where this was fixed: #21

TASK [geerlingguy.security : Ensure fail2ban is running and enabled on boot.] **

syntax error near line 28: deploy ALL=(ALL)

Hi, and thanks for sharing this very useful unusable role!

I'm getting the folling errror:

## vars:
security_sudoers_passworded: 
  - deploy

## running Ansible:
TASK: [geerlingguy.security | Add configured user accounts to passworded sudoers.] ***
failed: [89.163.212.62] => (item=deploy) => {"failed": true, "item": "deploy"}
msg: failed to validate: rc:1 error:>>> /tmp/tmps8viv2: syntax error near line 28 <<<

## Debian Jessie on the server:
$ cat /tmp/tmps8viv2
##...line 28: ...
deploy ALL=(ALL)

$ visudo -cf /tmp/tmps8viv2
>>> /tmp/tmps8viv2: syntax error near line 28 <<<
parse error in /tmp/tmps8viv2 near line 28

It works when changing the line to deploy ALL=(ALL) ALL, which is the syntax I'm familiar with.

Visudo doesn't seem to like your syntax in ssh.yml line 31

Chris

The module does not work on bare metal machines with libvirt-bin installed.

When I use the module on certain bare metal machines, the SSH setup gets completely smashed. This is about my MAAS server and my KVM host machines. Common to all of them is that they have libvit-bin installed. It seems that the module considers them as virtual machines, which they are not.

Yours sincerely
Søren Sjøstrøm
Unitynet

Fix deprecation warning for security_fail2ban_enabled usage

For example:

TASK [geerlingguy.security : Ensure fail2ban is running and enabled on boot.] ******************************************
[DEPRECATION WARNING]: evaluating security_fail2ban_enabled as a bare variable, this behaviour will go away and you 
might need to add |bool to the expression in the future. Also see CONDITIONAL_BARE_VARS configuration toggle.. This 
feature will be removed in version 2.12. Deprecation warnings can be disabled by setting deprecation_warnings=False in 
ansible.cfg.
ok: [10.0.100.103]

Configure Fail2ban sshd port, if enabled

This role gives the possibility (and encourages) to change SSH port number.

If the SSH port number is customized (not 22), the sshd Fail2ban jail will not work without providing the ssh port to block through a /etc/fail2ban/jail.local file.

I will submit a PR to fix this and provide a way to customize jails as well.

molecule test doesn't seem to work?

I'm having the same problem in my projects and I'm not sure what changed. I can run your molecule test if I change the role name in converge.yml form 'geerlingguy.security' to 'ansible-role-security'. It seems to be ignoring the meta naming and only using the project directory name

The use of 'include' for tasks has been deprecated

On Ansible 2.4.2 I get this deprecation warning:

[DEPRECATION WARNING]: The use of 'include' for tasks has been deprecated. Use 'import_tasks' for static inclusions or 'include_tasks' for dynamic inclusions. This
 feature will be removed in a future release. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.
[DEPRECATION WARNING]: include is kept for backwards compatibility but usage is discouraged. The module documentation details page may explain more about this
rationale.. This feature will be removed in a future release. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.

I see this warning with at least geerlingguy.docker, geerlingguy.git as well.

Debian autoupdates not working.

Debian 10 buster autoupdates not working, the Unattended-Upgrade::Allowed-Origins is configured incorrectly.

Unattended-Upgrade::Allowed-Origins {
"${distro_id} ${distro_codename}-security";
};
buster-security origin does not find any updates:

2020-05-13 06:48:44,955 INFO Initial blacklist :
2020-05-13 06:48:44,956 INFO Initial whitelist:
2020-05-13 06:48:44,956 INFO Starting unattended upgrades script
2020-05-13 06:48:44,957 INFO Allowed origins are: o=Debian,a=buster-security
2020-05-13 06:48:45,712 INFO No packages found that can be upgraded unattended and no pending auto-removals

But following is found manually. Origin should be configured with label "Debian-security":
apt-get upgrade -s | grep -i security
Inst openssl [1.1.1d-0+deb10u2] (1.1.1d-0+deb10u3 Debian:10.4/stable, Debian-Security:10/stable [amd64])
Conf openssl (1.1.1d-0+deb10u3 Debian:10.4/stable, Debian-Security:10/stable [amd64])

Log from another server without ansible role setup:
2020-05-07 06:18:43,609 INFO Initial blacklist :
2020-05-07 06:18:43,610 INFO Initial whitelist:
2020-05-07 06:18:43,610 INFO Starting unattended upgrades script
2020-05-07 06:18:43,610 INFO Allowed origins are: origin=Debian,codename=buster,label=Debian-Security
2020-05-07 06:18:44,866 INFO Packages that will be upgraded: libcurl3-gnutls libgnutls30 libicu63 libldap-2.4-2 libldap-common linux-image-4.19.0-8-amd64 openssl
2020-05-07 06:18:44,866 INFO Writing dpkg log to /var/log/unattended-upgrades/unattended-upgrades-dpkg.log
2020-05-07 06:19:08,804 INFO All upgrades installed

Configuration should match the Debian-Security label:
Unattended-Upgrade::Origins-Pattern {
"origin=Debian,codename=${distro_codename},label=Debian-Security";
};

SSH Allow Users and Groups

Should add 2 additional tasks to tasks/ssh.yml that configures allowed users or groups to the ssh config as an additional layer of security.

Install fail2ban: "Could not find aptitude. Using apt-get instead"

Hi Jeff! :)

I'm getting an annoying ansible warning with this role when it tries to install fail2ban:

[WARNING]: Could not find aptitude. Using apt-get instead

There's an easy workaround I use in my playbooks to avoid this by setting force_apt_get: yes.

Would you be open to adding a setting to this ansible role which lets us configure this? I'm honestly not sure what the best solution is.

[Ubuntu 20.04.1] Problems installing fail2ban

Hello,

We are using this security role (version 2.0.1.), in a new server with Ubuntu focal version 20.04.1, and we get this:

TASK [geerlingguy.security : Install fail2ban (Debian).] *******************************************************************************************************
fatal: []: FAILED! => {"changed": false, "msg": "No package matching 'fail2ban' is available"}

We've realized that the problem is that the package is not found on the 20.04.1 version of Ubuntu (apt search fail2ban gives 0 results, whereas in Ubuntu 20.04 it is found).

Is anyone else having this problem, or does anyone already know how to solve it?

Thank you,

Emphasize that /etc/ssh/sshd_config values must be quoted

I set security_ssh_permit_root_login to yes today, and I got locked out of SSH. This is because it casted it to True when writing the file. That is not a valid value, and it causes SSH to fail starting.

It should cast it to yes instead.

I'm thinking about how to do this most elegantly and will probably send a PR.

SSH getting file not found errors.

I am getting the following errors.

failed: [x.x.x.x] (item={u'regexp': u'^PasswordAuthentication', u'line': u'PasswordAuthentication no'}) => {"ansible_loop_var": "item", "changed": false, "cmd": "sshd -T -f /tmp/tmpbALBAx", "item": {"line": "PasswordAuthentication no", "regexp": "^PasswordAuthentication"}, "msg": "[Errno 2] No such file or directory", "rc": 2} failed: [x.x.x.x] (item={u'regexp': u'^PasswordAuthentication', u'line': u'PasswordAuthentication no'}) => {"ansible_loop_var": "item", "changed": false, "cmd": "sshd -T -f /tmp/tmpAGtMcq", "item": {"line": "PasswordAuthentication no", "regexp": "^PasswordAuthentication"}, "msg": "[Errno 2] No such file or directory", "rc": 2} failed: [x.x.x.x] (item={u'regexp': u'^PermitRootLogin', u'line': u'PermitRootLogin no'}) => {"ansible_loop_var": "item", "changed": false, "cmd": "sshd -T -f /tmp/tmp4W8JFX", "item": {"line": "PermitRootLogin no", "regexp": "^PermitRootLogin"}, "msg": "[Errno 2] No such file or directory", "rc": 2} failed: [x.x.x.x] (item={u'regexp': u'^PermitRootLogin', u'line': u'PermitRootLogin no'}) => {"ansible_loop_var": "item", "changed": false, "cmd": "sshd -T -f /tmp/tmpNO0KfI", "item": {"line": "PermitRootLogin no", "regexp": "^PermitRootLogin"}, "msg": "[Errno 2] No such file or directory", "rc": 2}

I am not sure why this is happening. Any ideas?

Does not work with ssh.socket activated ssh services

Recently after installing LXC container of ubuntu, I noticed that the ssh port as modified by this role in the /etc/ssh/sshd.conf was not being respected.

This is relatively recent issue. It seems that the LXC ubuntu container running on proxmox, now uses the ssh.socket to spawn ssh service sessions on demand as opposed to have the service running all the time.

This means that:

  1. Either the mask for the ssh.socket needs to be configured, so that the service starts as normal: https://forum.proxmox.com/threads/auto-start-sshd.38181/page-2#post-411369
  2. Or the port needs to be configured in a copy of /lib/systemd/system/ssh.socket placed in /etc/systemd/system directory?

I think the ssh service spawned on demand seems quite interesting, especially in an environment with low resources.

Jeff, as a fan of drupal, may find the following article interesting: http://0pointer.de/blog/projects/socket-activated-containers.html, how sporadic use drupal containers are spawned on demand using systemd sockets.

ERROR No /usr/bin/mail or /usr/sbin/sendmail, can not send mail

~ tail /var/log/unattended-upgrades/unattended-upgrades.log
...
ERROR No /usr/bin/mail or /usr/sbin/sendmail, can not send mail. You probably want to install the mailx package.
~ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 22.04 LTS
Release:        22.04
Codename:       jammy

how to run this

Helo,

I'm new to ansible and just wanted to know to run this in a test server. I'm in the process of buying your book since it came recommended but, just wanted to know how to run this right away. Thank you!

Blocks SSH

Hi! I'm trying to use this role in one of my projects but I keep bumping into a problem. After provisioning it fails restarting SSH and after doing so myself I can no longer SSH into the machine.

The only configuration override I've configured is security_ssh_permit_root_login: yes, since I SSH as root.

Any idea what I could be doing wrong?

TASK: [geerlingguy.security | Include OS-specific variables.] *****************
ok: [1.2.3.4]

TASK: [geerlingguy.security | Install fail2ban.] ******************************
skipping: [1.2.3.4]

TASK: [geerlingguy.security | Install fail2ban.] ******************************
changed: [1.2.3.4]

TASK: [geerlingguy.security | Ensure fail2ban is running and enabled on boot.] ***
ok: [1.2.3.4]

TASK: [geerlingguy.security | Update SSH configuration to be more secure.] ****
changed: [1.2.3.4] => (item={'regexp': '^PasswordAuthentication', 'line': u'PasswordAuthentication False'})
changed: [1.2.3.4] => (item={'regexp': '^PermitRootLogin', 'line': u'PermitRootLogin True'})
ok: [1.2.3.4] => (item={'regexp': '^Port', 'line': u'Port 22'})

TASK: [geerlingguy.security | Add configured user accounts to passwordless sudoers.] ***
skipping: [1.2.3.4]

TASK: [geerlingguy.security | Add configured user accounts to passworded sudoers.] ***
skipping: [1.2.3.4]

TASK: [geerlingguy.security | Install yum-cron.] ******************************
skipping: [1.2.3.4]

TASK: [geerlingguy.security | Ensure yum-cron is running and enabled on boot.] ***
skipping: [1.2.3.4]

TASK: [geerlingguy.security | Install unattended upgrades package.] ***********
ok: [1.2.3.4]

TASK: [geerlingguy.security | Copy unattended-upgrades configuration files in place.] ***
changed: [1.2.3.4] => (item=10periodic)
changed: [1.2.3.4] => (item=50unattended-upgrades)

NOTIFIED: [geerlingguy.security | restart ssh] ********************************
failed: [1.2.3.4] => {"failed": true}

FATAL: all hosts have already failed -- aborting

How to make the `ansible_port` dynamic in a playbook including this role

This role works great and I would like to use it, among other things, to change the default ssh port. The problem is, however, when I include this role in a playbook of multiple roles that sets up a machine from scratch, the playbook cannot be reused without changing the port. When setting the machine up for the first time, ansible has to connect over port 22, but once the security role has run, the custom port should be used. This can of course be fixed by specifying ansible_port in the hosts file, for example, but this will then cause the very first run to fail. Is there a way that the playbook can be written such that it can always be used without having to change the port.

I cannot help but feel others using this role must have run into the same problem, but could not find anything in the old closed issues. Maybe I am just using this role incorrectly.

ansible linter complains about relative path in role

ansible-lint complains about relative path when templating jinja file from the role itself. It's easy to fix, we can replace:

  template:
    src: "templates/{{ item }}.j2"

by

  template:
    src: "{{ item }}.j2"

Output of ansible-lint

[404] Doesn't need a relative path in role
/home/jvb/git_repo/Perso/piweb/infra/services/vm-hosting/base-config/ansible/roles.galaxy/geerlingguy.security/tasks/autoupdate-Debian.yml:5                                 
Task/Handler: Copy unattended-upgrades configuration files in place.

Invalid sshd_config

After running the task 'Update SSH configuration to be more secure.", the ssh_config file is invalid

$ sudo sshd -T
Unsupported option False

vars :

security_ssh_password_authentication: no
security_ssh_permit_root_login: no

Ansible output :

TASK: [geerlingguy.security | Update SSH configuration to be more secure.] ****
changed: [51.254.225.176] => (item={'regexp': '^PasswordAuthentication', 'line': u'PasswordAuthentication False'})
changed: [51.254.225.176] => (item={'regexp': '^PermitRootLogin', 'line': u'PermitRootLogin False'})

=> Apparently in some way the value of boolean var are misinterpreted (should be no instead of False)

Automatic updates not working for Fedora Server 35

Including this security role and running the Ansible Playbook on a Fedora Server 35 target produces an error regarding undefined variables.

TASK [geerlingguy.security : Install automatic update utility.] ****************
fatal: [<my-fedora35-target>]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'update_utility' is undefined\n\nThe error appears to be in '/vagrant/roles/geerlingguy.security/tasks/autoupdate-RedHat.yml': line 16, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: Install automatic update utility.\n  ^ here\n"}

I've found the origin of the issue, located on the line 8 of tasks/autoupdate-RedHat.yml. The condition is too strict and seem to only apply to RHEL targets rather than DNF-vs-YUM.

Running the playbook with those values defined:

update_utility: dnf-automatic
update_service: dnf-automatic-install.timer
update_conf_path: /etc/dnf/automatic.conf

works but it would be better if this ansible-role could support other Redhat based distributions.

Here is the output of Ansible, showing that the set_fact step is skipped:

TASK [geerlingguy.security : Set correct automatic update utility vars (RHEL 8).] ***
skipping: [<my-fedora35-target>]

TASK [geerlingguy.security : Set correct automatic update utility vars (RHEL <= 7).] ***
skipping: [<my-fedora35-target>]

Thank you for your awesome Ansible roles, they really saves me a lot of headaches!

fail2ban sshd jail is not enabled on RHEL7/CentOS7

Not sure if this would be considered a bug or a documentation issue, but the fail2ban sshd jail is not enabled by default on RHEL7/CentOS7. The role just installs the fail2ban package but does not further configure it. On Debian, the jail is automatically enabled by the file /etc/fail2ban/jail.d/defaults-debian.conf, but on RHEL7/CentoOS7, all jails are disabled by default.

Possibly a solution to #30 will address this as well?

configurable ssh hardening part

hi, I would like to use your role for fail2ban and unattended updates, but I already manage ssh-hardening via another role, so I don't need this part, could you build in a variable to configure that

thanks!

selinux ssh port change

On systems running selinux (or at least on Fedora 33) the handler to restart sshd fails if the ssh port is changed from 22. The new port must be added to the port context. For example it port 22222 is used:
semanage port -a -t ssh_port_t -p tcp 22222

It looks like setup does return some info about whether or not selinux in enabled ansible_selinux. I'm not sure if this is beyond the scope of what you are wanting to have this role achieve but I thought I would mention it.

Thanks for all the great tools btw!

ssh restart fails

hi,

I'm setting up a new Ubuntu 14.04 machine, and the playbook fails at restarting the ssh service:

NOTIFIED: [geerlingguy.security | restart ssh] ******************************** 
failed: [myserver] => {"failed": true}
FATAL: all hosts have already failed -- aborting
PLAY RECAP ******************************************************************** 
           to retry, use: --limit @/Users/aparvule/miggy.retry
myserver                      : ok=7    changed=3    unreachable=0    failed=1   

when I run it again, it looks like it went through fine (settings are indeed updated), but still the ssh service is not restarted, I can still login on the default port.

PLAY RECAP ******************************************************************** 
myserver                      : ok=7    changed=0    unreachable=0    failed=0 

what I think is missing here is running restart ssh with sudo.

Fail2ban requires apt cache update

On a fresh Ubuntu 16.04 server, the task Install fail2ban fails.

After manually updating the apt cache, it passes.

Context: provisioning a new app on a Digital Ocean droplet

Centos 7 auto update doesn't install updates

This is true at least for Centos 7, I haven't checked other RedHat based distros.

Enabling security_autoupdate_enabled doesn't install the updates. This is because the default configuration file that comes with yum and yum-cron (/etc/yum/yum-cron.conf) contains these rows:

[commands]
#  What kind of update to use:
# default                            = yum upgrade
# security                           = yum --security upgrade
# security-severity:Critical         = yum --sec-severity=Critical upgrade
# minimal                            = yum --bugfix update-minimal
# minimal-security                   = yum --security update-minimal
# minimal-security-severity:Critical =  --sec-severity=Critical update-minimal
update_cmd = default

# Whether a message should be emitted when updates are available,
# were downloaded, or applied.
update_messages = yes

# Whether updates should be downloaded when they are available.
download_updates = yes

# Whether updates should be applied when they are available.  Note
# that download_updates must also be yes for the update to be applied.
apply_updates = no

and as you can see apply_updates is no. This should probably be set to yes if security_autoupdate_enabled is enabled.

Also update_cmd would be nice to have as an option ;)

/cc @FinBoWa

Auto updates deviations

The auto updates are configured differently for RHEL based vs Debian based systems. RHEL based systems will update all. Debian based systems will only update security related packages.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.