Coder Social home page Coder Social logo

geerlingguy / ansible-role-firewall Goto Github PK

View Code? Open in Web Editor NEW
505.0 34.0 208.0 83 KB

Ansible Role - iptables Firewall configuration.

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

License: MIT License

Shell 96.27% Jinja 3.73%
ansible role firewall iptables linux security rules centos ubuntu rhel

ansible-role-firewall's Introduction

Ansible Role: Firewall (iptables)

CI

Installs an iptables-based firewall for Linux. Supports both IPv4 (iptables) and IPv6 (ip6tables).

This firewall aims for simplicity over complexity, and only opens a few specific ports for incoming traffic (configurable through Ansible variables). If you have a rudimentary knowledge of iptables and/or firewalls in general, this role should be a good starting point for a secure system firewall.

After the role is run, a firewall init service will be available on the server. You can use service firewall [start|stop|restart|status] to control the firewall.

Requirements

None.

Role Variables

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

firewall_state: started
firewall_enabled_at_boot: true

Controls the state of the firewall service; whether it should be running (firewall_state) and/or enabled on system boot (firewall_enabled_at_boot).

firewall_flush_rules_and_chains: true

Whether to flush all rules and chains whenever the firewall is restarted. Set this to false if there are other processes managing iptables (e.g. Docker).

firewall_template: firewall.bash.j2

The template to use when generating firewall rules.

firewall_allowed_tcp_ports:
  - "22"
  - "80"
  ...
firewall_allowed_udp_ports: []

A list of TCP or UDP ports (respectively) to open to incoming traffic.

firewall_forwarded_tcp_ports:
  - { src: "22", dest: "2222" }
  - { src: "80", dest: "8080" }
firewall_forwarded_udp_ports: []

Forward src port to dest port, either TCP or UDP (respectively).

firewall_additional_rules: []
firewall_ip6_additional_rules: []

Any additional (custom) rules to be added to the firewall (in the same format you would add them via command line, e.g. iptables [rule]/ip6tables [rule]). A few examples of how this could be used:

# Allow only the IP 167.89.89.18 to access port 4949 (Munin).
firewall_additional_rules:
  - "iptables -A INPUT -p tcp --dport 4949 -s 167.89.89.18 -j ACCEPT"

# Allow only the IP 214.192.48.21 to access port 3306 (MySQL).
firewall_additional_rules:
  - "iptables -A INPUT -p tcp --dport 3306 -s 214.192.48.21 -j ACCEPT"

See Iptables Essentials: Common Firewall Rules and Commands for more examples.

firewall_log_dropped_packets: true

Whether to log dropped packets to syslog (messages will be prefixed with "Dropped by firewall: ").

firewall_disable_firewalld: false
firewall_disable_ufw: false

Set to true to disable firewalld (installed by default on RHEL/CentOS) or ufw (installed by default on Ubuntu), respectively.

firewall_enable_ipv6: true

Set to false to disable configuration of ip6tables (for example, if your GRUB_CMDLINE_LINUX contains ipv6.disable=1).

Dependencies

None.

Example Playbook

- hosts: server
  vars_files:
    - vars/main.yml
  roles:
    - { role: geerlingguy.firewall }

Inside vars/main.yml:

firewall_allowed_tcp_ports:
  - "22"
  - "25"
  - "80"

License

MIT / BSD

Author Information

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

ansible-role-firewall's People

Contributors

daisydomergue avatar danielkoster avatar dmitry-a-l avatar emmetog avatar flomko avatar geerlingguy avatar gillg avatar jyaworski avatar mtpereira avatar oxyc avatar schoeppe avatar seanf 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ansible-role-firewall's Issues

Python six/jinja2 cookiecutter dependency version conflict causing CI builds to fail

Failed build: https://travis-ci.org/github/geerlingguy/ansible-role-firewall/jobs/677476167

$ molecule test
Failed to load driver entry point Traceback (most recent call last):
  File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/pluggy/manager.py", line 267, in load_setuptools_entrypoints
    plugin = ep.load()
  File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2410, in load
    self.require(*args, **kwargs)
  File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2433, in require
    items = working_set.resolve(reqs, env, installer, extras=self.extras)
  File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/pkg_resources/__init__.py", line 791, in resolve
    raise VersionConflict(dist, req).with_context(dependent_req)
pkg_resources.ContextualVersionConflict: (six 1.11.0 (/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages), Requirement.parse('six>=1.14'), {'cookiecutter'})

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/molecule/api.py", line 44, in drivers
    pm.load_setuptools_entrypoints("molecule.driver")
  File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/pluggy/manager.py", line 273, in load_setuptools_entrypoints
    message="Plugin %r could not be loaded: %s!" % (ep.name, e),
pluggy.manager.PluginValidationError: Plugin 'delegated' could not be loaded: (six 1.11.0 (/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages), Requirement.parse('six>=1.14'), {'cookiecutter'})!

Failed to load verifier entry point Traceback (most recent call last):
  File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/pluggy/manager.py", line 267, in load_setuptools_entrypoints
    plugin = ep.load()
  File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2410, in load
    self.require(*args, **kwargs)
  File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2433, in require
    items = working_set.resolve(reqs, env, installer, extras=self.extras)
  File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/pkg_resources/__init__.py", line 791, in resolve
    raise VersionConflict(dist, req).with_context(dependent_req)
pkg_resources.ContextualVersionConflict: (six 1.11.0 (/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages), Requirement.parse('six>=1.14'), {'cookiecutter'})

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/molecule/api.py", line 65, in verifiers
    pm.load_setuptools_entrypoints("molecule.verifier")
  File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/pluggy/manager.py", line 273, in load_setuptools_entrypoints
    message="Plugin %r could not be loaded: %s!" % (ep.name, e),
pluggy.manager.PluginValidationError: Plugin 'ansible' could not be loaded: (six 1.11.0 (/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages), Requirement.parse('six>=1.14'), {'cookiecutter'})!

---
dependency:
  name: galaxy
driver:
  name: docker
lint: 'set -e

  yamllint .

  ansible-lint

  '
platforms:
  - command: ${MOLECULE_DOCKER_COMMAND:-""}
    image: geerlingguy/docker-${MOLECULE_DISTRO:-centos7}-ansible:latest
    name: instance
    pre_build_image: true
    privileged: true
    volumes:
      - /sys/fs/cgroup:/sys/fs/cgroup:ro
provisioner:
  name: ansible
  playbooks:
    converge: ${MOLECULE_PLAYBOOK:-converge.yml}
scenario:
  test_sequence:
    - lint
    - destroy
    - dependency
    - syntax
    - create
    - prepare
    - converge
    - idempotence
    - check
    - side_effect
    - verify
    - destroy

ERROR: Failed to pre-validate.

{'driver': [{'name': ['unallowed value docker']}]}
The command "molecule test" exited with 1.

ip6tables rule is allowing wrong version of ICMP

A rule exists to allow ICMP for IPv6. That's necessary and is OK.
However, it's allowing ICMP for IPv4.

In file firewall.bash.j2:

# Accept icmp ping requests.
ip6tables -A INPUT -p icmp -j ACCEPT

It should be -p icmpv6 or -p ipv6-icmp. Not sure, it seems both forms are acceptable (and worked for me).

Failing with "AnsibleUndefinedVariable: 'ansible_enp0s6' is undefined"

I'm having some weird behavior with the firewall.bash template getting generated, and I'm not sure why. The guest is bento/ubuntu-16.04, latest version at the time of writing.

TASK [geerlingguy.firewall : Ensure iptables is present.] ****************************************************************************************************
task path: /media/ubuntu/home/kevin/code/DevOps/ansible/nl3.fillpdf.io/roles/geerlingguy.firewall/tasks/main.yml:2
ok: [default] => {"cache_update_time": 1572894200, "cache_updated": false, "changed": false}

TASK [geerlingguy.firewall : Flush iptables the first time playbook runs.] ***********************************************************************************
task path: /media/ubuntu/home/kevin/code/DevOps/ansible/nl3.fillpdf.io/roles/geerlingguy.firewall/tasks/main.yml:5
changed: [default] => {"changed": true, "cmd": ["iptables", "-F"], "delta": "0:00:00.001695", "end": "2019-11-04 19:14:43.912068", "rc": 0, "start": "2019-11-04 19:14:43.910373", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}

TASK [geerlingguy.firewall : Copy firewall script into place.] ***********************************************************************************************
task path: /media/ubuntu/home/kevin/code/DevOps/ansible/nl3.fillpdf.io/roles/geerlingguy.firewall/tasks/main.yml:10
fatal: [default]: FAILED! => {"changed": false, "msg": "AnsibleUndefinedVariable: 'ansible_enp0s6' is undefined"}

I looked at the template, but I have no clue where in the template that variable is coming from. It happens even if I comment out all of my firewall_* settings.

firewall.unit is not supported on RedHat

The task Ensure the firewall is enabled and will start on boot. fails on RedHat because the previous step Copy firewall systemd unit file into place (for systemd systems) does not copy the firewall.unit file.

Following is the output I get for RHEL7:

TASK [geerlingguy.firewall : Copy firewall systemd unit file into place (for systemd systems).] ***
skipping: [192.168.99.100]

TASK [geerlingguy.firewall : Ensure the firewall is enabled and will start on boot.] ***
fatal: [192.168.99.100]: FAILED! => {"changed": false, "failed": true, "msg": "Could not find the requested service \"'firewall'\": "}

Empty allowed ports list leads to all the ports open

Hello @geerlingguy ,

The /etc/firewall.bash script sets a ACCEPT policy for all the default chains before setting any rules. This will cause it to have all ports opened by default:

$ sudo iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere
ACCEPT     icmp --  anywhere             anywhere
ACCEPT     udp  --  anywhere             anywhere             udp spt:ntp
ACCEPT     all  --  anywhere             anywhere             state RELATED,ESTABLISHED
DROP       all  --  anywhere             anywhere

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     udp  --  anywhere             anywhere             udp dpt:ntp

 $ sudo iptables -S
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -p udp -m udp --sport 123 -j ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -j DROP
-A OUTPUT -p udp -m udp --dport 123 -j ACCEPT

In general, it is a good practice to start an iptables setup by DROPping everything on INPUT and FORWARD and then whitelist whatever you need to, instead of ACCEPTing everything and then blacklisting what you want, because the first is safer by default.

Do you agree with this? I'll PR my changes for this if you agree with this perspective.

Thank you.

Error on Debian on first check_mode run

Hello,

This role fails on Debian when playing the following tasks in check_mode on a fresh server :

- name: Configure the firewall service.
  service:
    name: firewall
    state: "{{ firewall_state }}"
    enabled: "{{ firewall_enabled_at_boot }}"

with the following error message :

fatal: [xxx]: FAILED! => {"changed": false, "msg": "Could not find the requested service firewall: host"}

because the firewall service unit file is not installed and therefore the service step fails.

I suggest adding the following line to this task to ignore check_mode errors :

  ignore_errors: "{{ ansible_check_mode }}"

Allow user-provided templates

I need certain modifications to the standard rules, including but not limited to:

  • drop ip6tables input rule for NTP
  • add ip6tables input rule to allow DHCPv6

And apart from the service-related rules, I'd also like to customize the behavior of the whitelisting by switching from DROP to REJECT.

Therefore, it would be nice to have the option of specifying a custom template file without the need to fork the project.

Custom rules are not logged

Hi there,

I'm having a few specifc iptables rules in the firewall_additional_rules but they are not logged because the firewall_log_dropped_packets line is below it, therefore not triggerd.

I think the two blocks should be swapped.

Ansible 2.5 shows deprecation warning for state=installed

TASK [geerlingguy.firewall : Ensure iptables is installed.] ************************************************************
[DEPRECATION WARNING]: State 'installed' is deprecated. Using state 'present' instead.. This feature will be removed in
 version 2.9. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.

docker rules are flushed on each run

Hello, forgive me for my bad english.

First, special thanks for your ansible roles. I use them everyday in my pipelines for all servers (dev, prod, etc.).
I'm trying this role to manage iptables rules over a ci/cd pipeline. On each run, all rules are removed on all servers and new rules are applied.

My servers have docker installed and all iptables rules added by docker are flushed and docker needs to be restarted.

Is there a way to apply new rules dynamically ?

Thanks.

specific rules for specific IP address

i want to edit this role to allow me to block or allow ports for several IPs. For example , allow 22 for 192.168.1.2 but block 22 for 1.3 etc

any tips ?
thanks

Docker role causes Docker's first start to fail with 'Couldn't load target DOCKER'

I have installed both this role and the docker role on the same server. After running both when trying to use Docker after this has run I get the following.

Creating network "digitalhub_default" with the default driver
ERROR: Failed to program FILTER chain: COMMAND_FAILED: '/usr/sbin/iptables -w2 -I FORWARD -o br-919bc7916019 -j DOCKER' failed: iptables v1.4.21: Couldn't load target `DOCKER':No such file or directory

Try `iptables -h' or 'iptables --help' for more information.

Restarting the Docker service puts the rules back into place and Docker starts working again.

I think from this module either having a flag to ignore the Docker rules or a post change command to allow the Docker service to be restarted would be useful.

stopping service on systemd doesnt flush ip6tables

When you use systemctl stop firewall to flush the chains, only IPv4 rules are flushed. This is because in firewall.unit.j2 in line 8 only /sbin/iptables -F is called.

I would prefer to either add the old init script and use it here or pass start/stop to the firewall.bash.j2

iptables fails to install if apt cache is outdated

When applying this role on fresh instance, it may happen that the package will not be found since apt cache was not updated and the playbook will fail at this point.

TASK [geerlingguy.firewall : Ensure iptables is present.] *******************************************************
fatal: [test-host]: FAILED! => {"changed": false, "msg": "No package matching 'iptables' is available"}

Ansible 2.x role cleanup

One warning appears when running the playbook under Ansible 2.x (which will be released soon):

RUNNING HANDLER [geerlingguy.firewall : restart firewall] **********************
changed: [drupalvm]
 [WARNING]: Consider using service module rather than running service

Script running after network up

As far as I can tell the init script does not specify when to start relative to the network, and the systemd unit specifies to start after network. Seems to me that it should start before network so as to avoid the (admittedly nominally tiny) time between network up and iptables rules being restored.
This seems to be the approach taken by iptables-persistent and ufw in any case.

Firewall override by different ansible projects

We devided our ansible project in different parts:

  • One Part for dns
  • And another Part for netdata

This works pretty well, but each part has a role to add specific firewall settings.
Sadly the configuration is always overwritten so only the last firewall settings will be configured.
Is it possible not to override the whole iptables?

Add option to disable dropped packet logging

For local dev environments (e.g. Drupal VM), it's a little annoying to have a bunch of 'Dropped by firewall' messages in syslog, so it would be nice to have an option to disable these messages through a firewall_log_dropped_connections variable.

This is most annoying when you're running Dropbox, and there are dozens of dropped connections to port 7500 (I think) on all running VMs on a local machine.

Role doesn't work in check mode when firewall_disable_* is true

For example, when running this role on an Ubuntu server with firewall_disable_ufw: true:

TASK [geerlingguy.firewall : Configure the firewall service.] **********************************************************
ok: [f1.acquia-ps.com]

TASK [geerlingguy.firewall : Check if firewalld package is installed (on RHEL).] ***************************************
skipping: [f1.acquia-ps.com]

TASK [geerlingguy.firewall : Disable the firewalld service (on RHEL, if configured).] **********************************
skipping: [f1.acquia-ps.com]

TASK [geerlingguy.firewall : Check if ufw package is installed (on Ubuntu).] *******************************************
skipping: [f1.acquia-ps.com]

TASK [geerlingguy.firewall : Disable the ufw firewall (on Ubuntu, if configured).] *************************************
fatal: [f1.acquia-ps.com]: FAILED! => {"msg": "The conditional check 'ansible_distribution == \"Ubuntu\" and firewall_disable_ufw and ufw_installed.rc == 0' failed. The error was: error while evaluating conditional (ansible_distribution == \"Ubuntu\" and firewall_disable_ufw and ufw_installed.rc == 0): 'dict object' has no attribute 'rc'\n\nThe error appears to have been in '/Users/jeff.geerling/Sites/acquia/F1/roles/geerlingguy.firewall/tasks/disable-other-firewalls.yml': line 27, 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: Disable the ufw firewall (on Ubuntu, if configured).\n  ^ here\n"}

how to open port for OUTPUT dns ?

hi!

firstable, I love your job with Ansible, I think is very helpful.

About this role, I don't know how to tell firewalls to open port for OUTPUT chain and port 53...

The problem is my machine can resolv domain names with the firewall activated.

Thanks!

Backup the generated rules file

Could you add "backup: yes" in the template tasks, so that a backup copy of the generated rules would still be available after a modification ?

[FEATURE REQUEST] add variable for default rules / add variable for blacklisted IPs

Would be nice to have a list of IP's we can explicitly block through the iptable configuration. There are some known IP's which are known for being evil.

Also it would be nice to set some default rules like with firewall_additional_rules. For example call it firewall_default_rules.
This way I can set some global defaults for all hosts like dropping all INPUT/FORWARD requests by default and allowing loopback and ping replice but using firewall_additional_rules to create host specific rules.

Disabling firewalls fails on my Ubuntu server

On an Ubuntu server of mine, I get the following error running this role:
fatal: [0.0.0.0]: FAILED! => {"changed": false, "failed": true, "msg": "Could not find the requested service ufw: host"}

Output for dpkg -l ufw (which this role uses to check if it's installed):

$ sudo dpkg -l ufw
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name                               Version                Architecture           Description
+++-==================================-======================-======================-=========================================================================
un  ufw                                <none>                 <none>                 (no description available)

This gives a return code of 0, but I don't have the package installed. It seems that the dpkg cache is queried, resulting in the response being true, as the packed is available for install.

Maybe a better way to check this is to see if the service itself is installed?

$ service ufw status
โ— ufw.service
   Loaded: not-found (Reason: No such file or directory)
   Active: inactive (dead)

This correctly returns 1 if not installed, and 0 if it is.

As this is checking the status, it's obviously possible that the service crashed, which may also return 1, thus being a false result. Not totally sure about this though.

EDIT: Of course I can leave firewall_disable_ufw to the default false, but I have that variable set for all hosts to make it easier.

nat rules are not flushed on stop

Hi,

If you add a nat rule inside firewall_additional_rules and specify -t nat, when you stop the firewall service using systemctl stop firewall - the rule is still present.

I checked the systemd file, it uses ExecStop=/sbin/iptables -F and in order to flush the nat rules too, we also need iptables -t nat -F

Example of rule that is not deleted after a stop :

firewall_additional_rules:
  - "iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -j MASQUERADE"

Regards,
Julien

In redhat7.4, firewalld_installed don't have rc field.

https://github.com/geerlingguy/ansible-role-firewall/blob/b0c686d3fe9e7f45ac840b64881410ba2702f8d8/tasks/disable-other-firewalls.yml#L22jjjjjj
This is what returned:
"firewalld_installed": {
"changed": false,
"failed": false,
"msg": "skipped, running in check mode",
"skipped": true
}
Ansible version: 2.7.10
This piece of code will break

  • name: Disable the firewalld service (on RHEL, if configured).
    service:
    name: firewalld
    state: stopped
    enabled: false
    when:
    • ansible_os_family == "RedHat"
    • firewall_disable_firewalld
    • firewalld_installed.rc == 0

Can't get firewall working with allowed tcp ports

hI
this is my vars/main.yml

cat vars/main.yml
firewall_allowed_tcp_ports:

  • "22"
  • "25"
  • "80"
  • "443"
  • "5000"

i added 2 ports

and this is the defaults/main.yml

cat defaults/main.yml

firewall_allowed_tcp_ports:

  • "22"
  • "80"
  • "443"
  • "5000"

this is inside the playbook

  • hosts: lan
    remote_user: root
    vars_files:
    • vars/main.yml
      roles:
    • { role: geerlingguy.firewall }

it is my understand that the above ports will be allowed , correct?
The play completes fine with no errors but if i nmap one host like this

nmap 192.168.1.2

Starting Nmap 7.01 ( https://nmap.org ) at 2016-11-26 00:41 EET
Nmap scan report for 192.168.1.2 Host is up (0.00063s latency).
Not shown: 997 filtered ports
PORT STATE SERVICE
22/tcp open ssh
25/tcp closed smtp
80/tcp open http

Nmap done: 1 IP address (1 host up) scanned in 4.67 seconds

it does not list the ports i previously added

can you explain why ?
thank you

Move related,established rule to top.

Quick testing on my part shows that having the "related,established" rule at the bottom can introduce a large delay in connection time if you have reject rules in the "additional rules" section. With no rules (FW completely open), no reject rule (FW mostly closed), or the "established,related" rule at the top (right before open section) in my tests shows a connection time of just over 1 second, with that rule at the bottom and reject rules I have connection times of just over 21 seconds.

Use ansible_port if defined instead of always 22

Hello,

This is currently the default:

firewall_allowed_tcp_ports:
  - "22"
  - "25"
  - "80"
  - "443"

Whenever ansible_port is not 22... this variable must be redefined. Wouldn't it be more flexible to have something like?:

firewall_allowed_tcp_ports:
  - "'{% if ansible_port is defined %}{{ ansible_port }}{% else %}22{% endif %}'"
  - "25"
  - "80"
  - "443"

I'm not sure the jinja2 syntax is correct but the idea is there.

Let me know if this is considered a good idea so I can implement it a issue a PR.

Thanks!

setup a network interface with different port settings

I try to set it up in the vps cloud, which has 2 network interfaces, where I will provide port access for a certain one according to eth0 or eth1 and the others.

how do you suggest, regarding the above?

thank you in advance

Add Default Policy Option

Hi,

I really like this role but one thing I feel missing is that you can't set the default policy for a given table and interface (you'd have to do so custom additional_rules). It's be great if this was an option without requiring custom iptables rules. Thanks

EL6 defaults into an error

running this on EL6 with the option firewall_disable_firewalld: true results in the task to fail (but continues):

fatal: [server.fqdn.de]: FAILED! => {"changed": false, "cmd": ["yum", "list", "installed", "firewalld"], "delta": "0:00:01.996548", "end": "2019-03-27 15:06:27.999980", "msg": "non-zero return code", "rc": 1, "start": "2019-03-27 15:06:26.003432", "stderr": "Error: No matching Packages to list", "stderr_lines": ["Error: No matching Packages to list"], "stdout": "Loaded plugins: enabled_repos_upload, package_upload, product-id, search-\n : disabled-repos, security, subscription-manager\nUploading Enabled Repositories Report\nLoaded plugins: product-id, subscription-manager", "stdout_lines": ["Loaded plugins: enabled_repos_upload, package_upload, product-id, search-", " : disabled-repos, security, subscription-manager", "Uploading Enabled Repositories Report", "Loaded plugins: product-id, subscription-manager"]}

UDP Rules are not working

In firewall.bash.j2 for UDP rules it has:

{% for port in firewall_allowed_udp_ports %}
iptables -A INPUT -p tcp -m udp --dport {{ port }} -j ACCEPT
{% endfor %}

It should be:

{% for port in firewall_allowed_udp_ports %}
iptables -A INPUT -p udp -m udp --dport {{ port }} -j ACCEPT
{% endfor %}

Once I changed -p to udp it worked.

Thanks.

Host loses connectivity after flushing iptables

Controlling an Ubuntu 14.04 box, all connectivity was lost after the step which flushed iptables. The firewall had previously been configured through UFW. Perhaps the default rule was DROP rather than ACCEPT?

$ ansible-playbook -v zanata-wildfly.yml -i inventory

PLAY [zanata] ***************************************************************** 

GATHERING FACTS ***************************************************************
ok: [xx.xx.xx.xx]

TASK: [geerlingguy.firewall | Ensure iptables is installed (RedHat).] *********
skipping: [xx.xx.xx.xx]

TASK: [geerlingguy.firewall | Ensure iptables is installed (Debian).] *********
ok: [xx.xx.xx.xx] => {"changed": false}

TASK: [geerlingguy.firewall | Flush iptables the first time playbook runs.] ***
changed: [xx.xx.xx.xx] => {"changed": true, "cmd": ["iptables", "-F"], "delta": "0:00:00.002802", "end": "2014-08-21 03:11:54.650421", "rc": 0, "start": "2014-08-21 03:11:54.647619", "stderr": "", "stdout": ""}

TASK: [geerlingguy.firewall | Copy firewall script into place.] ***************
fatal: [xx.xx.xx.xx] => {'msg': 'FAILED: timed out', 'failed': True}

FATAL: all hosts have already failed -- aborting

PLAY RECAP ********************************************************************
           to retry, use: --limit @/home/sflaniga/zanata-wildfly.retry

xx.xx.xx.xx             : ok=3    changed=1    unreachable=1    failed=0

sflaniga:ansible (master*) $ cat zanata-wildfly.yml

---
- hosts: zanata
  sudo: yes
#  accelerate: true
  vars_files:
    - vars/main.yml
  roles:
    - { role: geerlingguy.firewall }
  tasks:

  - name: Add group "wildfly"
    group: name=wildfly

  - name: Add user "wildfly"
    user: name=wildfly group=wildfly home=/home/wildfly

  - name: Change ownership of WildFly directories
    file: path=/opt/wildfly owner=wildfly group=wildfly state=directory recurse=yes

sflaniga:ansible (master*) $ cat vars/main.yml
firewall_allowed_tcp_ports:
  - "22"
  - "80"
  - "443"
  - "5099" # for Ansible accelerated mode
  - "8080"

firewall_forwarded_tcp_ports:
  - { src: "80", dest: "8080" }

# firewall_forwarded_udp_ports: []


# firewall_additional_rules: []%
sflaniga:ansible (master*) $

Cosmetic improve

Hello all,

The template firewall.bash.j2 contains the comment "# 123: DNS". I think the port 123 has relationship to ntp ?

fatal error on "firewall: Check if ufw package is installed (on Ubuntu)."

Hello,

I decided to set firewall_disable_ufw flag to disable UFW, but repeating task causes fatal error.
I was wondering, could service_facts module be used to determine if ufw exists, and to disable it if so?
I'm Ansible beginner, but it seems a bit ugly to have fatal fails, even though they are ignored.
Am I missing something here?
I'm using Ansible 2.9.7

TASK [firewall : Check if ufw package is installed (on Ubuntu).] 
....
....
....
fatal: [iaac-playground]: FAILED! => {
    "changed": false,
    "cmd": [
        "service",
        "ufw",
        "status"
    ],
    "delta": "0:00:00.019206",
    "end": "2020-04-23 20:44:32.425996",
    "invocation": {
        "module_args": {
            "_raw_params": "service ufw status",
            "_uses_shell": false,
            "argv": null,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "stdin": null,
            "stdin_add_newline": true,
            "strip_empty_ends": true,
            "warn": false
        }
    },
    "msg": "non-zero return code",
    "rc": 3,
    "start": "2020-04-23 20:44:32.406790",
    "stderr": "",
    "stderr_lines": [],
    "stdout": "* ufw.service - Uncomplicated firewall\n   Loaded: loaded (/lib/systemd/system/ufw.service; disabled; vendor preset: enabled)\n   Active: inactive (dead)\n     Docs: man:ufw(8)\n\nApr 22 22:28:06 iaac-playgound systemd[1]: Stopping Uncomplicated firewall...\nApr 22 22:28:06 iaac-playgound ufw-init[13566]: Skip stopping firewall: ufw (not enabled)\nApr 22 22:28:06 iaac-playgound systemd[1]: Stopped Uncomplicated firewall.",
    "stdout_lines": [
        "* ufw.service - Uncomplicated firewall",
        "   Loaded: loaded (/lib/systemd/system/ufw.service; disabled; vendor preset: enabled)",
        "   Active: inactive (dead)",
        "     Docs: man:ufw(8)",
        "",
        "Apr 22 22:28:06 iaac-playgound systemd[1]: Stopping Uncomplicated firewall...",
        "Apr 22 22:28:06 iaac-playgound ufw-init[13566]: Skip stopping firewall: ufw (not enabled)",
        "Apr 22 22:28:06 iaac-playgound systemd[1]: Stopped Uncomplicated firewall."
    ]
}
...ignoring

Fails on install at "Flush iptables the first time playbook runs."

Using Ansible 1.8.2 from Fedora 19 to set up Centos 6.6.

I found when I tried to run a playbook with this role it would fail on the "Flush iptables the first time playbook runs" task with a file not found error, and then not go on to actually install the service. My fix was to add "ignore_errors: yes" for that task.

I am very new to Ansible, so it may be something to do with my setup. Hope this is of some use to someone.

Failing without reboot on Ubuntu 16.04 LTS

TASK [geerlingguy.firewall : Ensure the firewall is enabled and will start on boot.] ***
fatal: [ansible-dev-ubuntu]: FAILED! => {"changed": false, "failed": true, "msg": "Could not find the requested service \"'firewall'\": "}

It runs fine after a reboot.

Port forwarding fails if destination is not in firewall_allowed_tcp_ports

Hi @geerlingguy

I am not sure if it is intended behavior or not, therefore I open this issue.

With the following configuration it is not possible to access port 80 and 443 possibly because they are forwarding to non allowed tcp ports:

firewall_forwarded_tcp_ports:
  - { src: "80", dest: "8080" }
  - { src: "443", dest: "8443" }

firewall_allowed_tcp_ports:
  - "22"
  - "80"
  - "443"

Instead I have to add 8443 and 8080 to the list of allowed tcp ports:

firewall_forwarded_tcp_ports:
  - { src: "80", dest: "8080" }
  - { src: "443", dest: "8443" }

firewall_allowed_tcp_ports:
  - "22"
  - "80"
  - "443"
  - "8080"
  - "8443"

Is this behavior intended? If yes, it would be nice to add this to the readme.

Regards,
Daniel

Make all default rules (NTP, DNS, etc.) configurable

I use this role in my project. I find it adding a ntp rule on output chain. I ignored it at first.

Lately, my memcache get slowly on the server. I spent lots of hours and finally I find it is because of the rule on the iptables' output chain.

I haven't dig out why the rule has such effect. But I am sure it is because of it. Please remove it.

Allow other default-installed firewalls to be disabled.

Ubuntu now installs ufw by default, while RHEL/CentOS 7 installs firewalld. While these firewalls are fine in their own right, they interfere with the simpler iptables-only approach this role uses. And I realized on one of my servers that a reboot where firewalld and this role's firewall conflict, it can cause strange behavior.

Therefore I'd like to add the ability (turned off by default, for backwards compatibility and safety) to disable system-supplied firewalls, mostly for convenience.

firewall.service breaks fail2ban in ansible-role-security

I am using ansible-role-security with ansible-role-firewall. There seems to be a problem with the firewall.service script which clobbers fail2ban rules in the firewall after a systemctl restart firewall.service

My main.yml is bringing in the roles in this order:

  roles:
    - { role: geerlingguy.security }
    - { role: geerlingguy.firewall }

Iptables handler isn't flushed after task leaving ports closed until end of playbook

So this role currently has a notify section for restarting the firewall once iptables has been setup, if you're running this role to open certain ports in a playbook that also has services that rely on those same ports being open then the playbook will fail because the firewall isn't restarted until the end of the playbook as the handlers aren't flushed after the task.

In my case I ran this against a server that had every port locked down except for SSH, I was setting up letsencrypt and it wasn't able to run the acme challenge as it complained that port 80 wasn't open which was odd because I have this role set to open 22, 80, and 443. Color me surprised when I checked the current iptables config and I saw that nothing had been changed.

need to run it twice

Hi,

I run this role with the following vars:

firewall_state: stopped
firewall_enabled_at_boot: false
firewall_disable_firewalld: true

Before the first run, the fireall is off (freshly installed) and after the run, the firewall is up and running (and blocking):

[root@el8-test user]# iptables -S
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 25 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -p udp -m udp --sport 123 -j ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -m limit --limit 15/min -j LOG --log-prefix "Dropped by firewall: " --log-level 7
-A INPUT -j DROP
-A OUTPUT -p udp -m udp --dport 123 -j ACCEPT

If I run the playbook again it chagnes the "Configure the firewall service." and then the firewall is actually stopped:

iptables -S
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT

Locks me out of server

When using this role, I get to TASK [geerlingguy.firewall : Copy firewall script into place.] and I have been locked out of the server on port 22 which ansible is using to run tasks.

It seems that TASK [geerlingguy.firewall : Flush iptables the first time playbook runs.] is locking the server down to no open ports.

Scope of this role regarding plugins

Hi,
I am currently enjoying your jenkins role, and was wondering whether you would regard to provide basic configurations for plugins in scope for this role?

Consider this example (of a vars file):

jenkins_plugins:
  - { id: ssh-credentials }
  - { id: credentials, configSrc: files/credentials.xml, configDest: credentials.xml }
  - { id: email-ext, configTemplate: templates/hudson.plugins.emailext.ExtendedEmailPublisher.xml.jj2, configDest: hudson.plugins.emailext.ExtendedEmailPublisher.xml }

The point is the initial installation of the plugins is not the problem compared to configuring them.

Using "firewall_flush_rules_and_chains"

When "firewall_flush_rules_and_chains:" is false

"Iptables.bash.js" template is missing "iptables -F"

But in "firewall.unit.j2" there is "ExecStop = /sbin/iptables -F"

And when the service restarts, all additional chains and rules are deleted

Flushing iptables on first run is causing ssh lockdown

When I run this role on my remote servers, the first task of flushing iptables is causing ssh lockdown and disconnection. I had to add the default rules task before flushing to make it work. Is this normal behavior or am I doing something wrong?

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.