Article 5GJQX Automatic creating rules and enabling firewll

Automatic creating rules and enabling firewll

by
roffeboffe
from LinuxQuestions.org on (#5GJQX)
Hi

I thought I'd share the fruits of my labour. I have quite a lot of linux servers that has disabled firewalls. I inherited these systems and want to turn on the firewall on all servers with Ansible/AWX.

I haven't found any simple solutions to this anywhere, so I had to make it myself. :D

First I have used listen_ports_facts from community.general collection to list ports/services on all servers to make sure there are no suspicios services running. I just used the example playbook from docs.ansible.com for this and browsed through the list manually.

So I figured I'd fetch all listening ipv4 ports on the servers, add allow rules for these, then turn on default deny to block all other traffic and then enable and start the firewall.

So first, to retrieve listening ports, I ended up with this:

Quote:
# netstat -tulpn | awk '{ print $1,$4 }' | grep -v 'Ac\|Pr\|udp6\|tcp6' | sed -r 's/:/ /g' | awk '{ print $3 "/" $1 }' | uniq
This gives a result looking like this:

Quote:
3306/tcp
22/tcp
33060/tcp
68/udp
161/udp
323/udp
Then I use xargs to create allow rules for each of those lines, then turn on default deny on incoming traffic and finally enabling the firewall.

So the full command looks like this (for ufw-based systems). It should be simple to modify this for RedHat firewalld:

Quote:
# netstat -tulpn | awk '{ print $1,$4 }' | grep -v 'Ac\|Pr\|udp6\|tcp6' | sed -r 's/:/ /g' | awk '{ print $3 "/" $1 }' | uniq | xargs -L1 ufw allow && ufw default deny incoming && ufw --force enable
Then I just have to write a simple playbook to run this from AWX. Playbook will look something like this. I just need to add some more checks to make sure it will run on all flavors.

Quote:
---
- hosts: all

tasks:
- name: Get listening ports, create rules, set default deny and enable firewall
shell: netstat -tulpn | awk '{ print $1,$4 }' | grep -v 'Ac\|Pr\|udp6\|tcp6' | sed -r 's/:/ /g' | awk '{ print $3 "/" $1 }' | uniq | xargs -L1 ufw allow && ufw default deny incoming && ufw --force enable
latest?d=yIl2AUoC8zA latest?i=g2XR9b9O1fU:PYpXUpeWPL4:F7zBnMy latest?i=g2XR9b9O1fU:PYpXUpeWPL4:V_sGLiP latest?d=qj6IDK7rITs latest?i=g2XR9b9O1fU:PYpXUpeWPL4:gIN9vFwg2XR9b9O1fU
External Content
Source RSS or Atom Feed
Feed Location https://feeds.feedburner.com/linuxquestions/latest
Feed Title LinuxQuestions.org
Feed Link https://www.linuxquestions.org/questions/
Reply 0 comments