Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Emilien Kenler committed Jun 4, 2015
0 parents commit 0eb1f16
Show file tree
Hide file tree
Showing 9 changed files with 315 additions and 0 deletions.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2014 Wizcorp

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
31 changes: 31 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
Firewall
========

This role manages the iptables rules.

Usage
-----

You role must contains a `templates/iptables.j2` file with your iptables rules.

In your role's meta, add a dependency to this role using the syntax described below.

```yaml
# my_role/meta/main.yml
- role: firewall
role_name: my_role
```
When you will run the playbook, the rules will be applied.
Rules template example
----------------------
```
# Firewall rules for the 'nginx' role
*filter
:nginx_in - [0:0]
-I INPUT -j nginx_in
-A nginx_in -p tcp -m tcp --dport 80 -j ACCEPT
COMMIT
```
2 changes: 2 additions & 0 deletions handlers/main.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
# handlers file for firewall
127 changes: 127 additions & 0 deletions library/firewall.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-

import os


def generate_docker_rules(save):
rules = []
for line in save.split('\n'):
line = line.strip()
if not line:
continue

if line.lower().find('docker') == -1:
continue

# Skip lines which don't add a new rule
if not line.startswith('-A'):
continue

# ignore custom rules
for chain in ['PREROUTING', 'POSTROUTING', 'OUTPUT', 'DOCKER',
'FORWARD']:
if line.startswith('-A ' + chain):
break
else:
continue

# Add it to the nat table if required
for chain in ['PREROUTING', 'POSTROUTING', 'OUTPUT', 'DOCKER']:
if line.startswith('-A ' + chain):
line = '-t nat ' + line

rules.append(line)

if rules:
rules.insert(0, '-t nat -N DOCKER')
return rules


def main():
global module
module = AnsibleModule(
argument_spec=dict(
state=dict(default='reloaded', choices=['reloaded'])
)
)
facts = ansible_facts(module)

state = module.params['state']

if state != 'reloaded':
module.fail_json(msg="unsupported state '%s'" % state)

rules_directory = '/etc/iptables.d'

if not os.path.exists(rules_directory):
module.fail_json(
msg="the rules directory (%s) doesn't exist" % rules_directory)

def is_common(a, b):
if a == 'common':
return -1
elif b == 'common':
return 1
else:
return 0

rules = sorted(os.listdir(rules_directory), cmp=is_common)
if not rules:
module.exit_json(changed=False, msg="no rules to apply")

_, save_out, _ = module.run_command("iptables-save", check_rc=True)
save_out = re.sub(r'(?m)^[#:].*', '', save_out)

docker_rules = generate_docker_rules(save_out)

_, global_stdout, global_stderr = module.run_command(
"/sbin/iptables-restore -v"
" < /etc/iptables.d/%s" % rules[0],
check_rc=True,
use_unsafe_shell=True)

if len(rules) > 1:
for rule in rules[1:]:
_, stdout, stderr = module.run_command(
"/sbin/iptables-restore -v --noflush"
" < /etc/iptables.d/%s" % rule,
check_rc=True,
use_unsafe_shell=True)
global_stdout = '\n'.join([global_stdout.strip(), stdout.strip()])
global_stderr = '\n'.join([global_stderr.strip(), stderr.strip()])

cmd = None
if facts['distribution'] in ['CentOS', 'RedHat']:
cmd = "service iptables save"
elif facts['distribution'] == 'Debian':
cmd = "service iptables-persistent save"

if cmd:
_, stdout, stderr = module.run_command(cmd, check_rc=True)
global_stdout = '\n'.join([global_stdout.strip(), stdout.strip()])
global_stderr = '\n'.join([global_stderr.strip(), stderr.strip()])
else:
module.fail_json(
msg="the rules are not persistent because '%s' is not supported"
% facts['distribution'])

for docker_rule in docker_rules:
_, stdout, stderr = module.run_command("iptables " + docker_rule,
check_rc=True)
global_stdout = '\n'.join([global_stdout.strip(), stdout.strip()])
global_stderr = '\n'.join([global_stderr.strip(), stderr.strip()])

_, save_end_out, _ = module.run_command("iptables-save", check_rc=True)
save_end_out = re.sub(r'(?m)^[#:].*', '', save_end_out)

module.exit_json(changed=(save_out != save_end_out),
stdout=global_stdout.strip(),
stderr=global_stderr.strip(),
msg="the rules '%s' have been applied" % ', '.join(rules))


from ansible.module_utils.basic import *
from ansible.module_utils.facts import *

main()
18 changes: 18 additions & 0 deletions meta/main.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
galaxy_info:
author: Emilien Kenler <[email protected]>
description: Manage the iptables rules.
company: Wizcorp K.K.
license: MIT
min_ansible_version: 1.8.1
platforms:
- name: EL
versions:
- all
- name: Debian
versions:
- all
categories:
- system
- networking
dependencies:
- role: aeriscloud.yum
45 changes: 45 additions & 0 deletions tasks/centos.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
- name: "Install iptables-services"
yum: >
name=iptables-services
state=present
when: ansible_distribution_major_version|int == 7
tags:
- firewall
- pkgs

- name: "Disable firewalld"
service: >
name=firewalld
enabled=no
state=stopped
when: ansible_distribution_major_version|int == 7
tags:
- firewall

- name: "Enable iptables"
service: >
name=iptables
enabled=yes
state=started
when: ansible_distribution_major_version|int == 7
tags:
- firewall

- name: "Install ip6tables rules"
template: >
src=ip6tables.j2
dest=/etc/sysconfig/ip6tables
owner=root
group=root
mode=0600
register: ip6tables_template
tags:
- firewall
- files

- name: "Reload ip6tables rules"
shell: |
[ -e /sbin/ip6tables-restore ] && /sbin/ip6tables-restore < /etc/sysconfig/ip6tables
when: ip6tables_template|changed
tags:
- firewall
26 changes: 26 additions & 0 deletions tasks/debian.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
- name: "Install iptables-persistent"
apt: >
name=iptables-persistent
state=present
tags:
- firewall
- pkgs

- name: "Install ip6tables rules"
template: >
src=ip6tables.j2
dest=/etc/iptables/rules.v6
owner=root
group=root
mode=0600
register: ip6tables_template
tags:
- firewall
- files

- name: "Reload ip6tables rules"
shell: |
[ -e /sbin/ip6tables-restore ] && /sbin/ip6tables-restore < /etc/iptables/rules.v6
when: ip6tables_template|changed
tags:
- firewall
35 changes: 35 additions & 0 deletions tasks/main.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
- include: centos.yml
when: ansible_distribution == 'CentOS'

- include: debian.yml
when: ansible_distribution == 'Debian'

- name: "Ensure the iptables.d directory exists"
file: >
path=/etc/iptables.d
state=directory
mode=0700
owner=root
group=root
tags:
- firewall

- name: "Add the {{ role_name }} firewall rules file"
template: >
src=../../{{ role_name }}/templates/iptables.j2
dest=/etc/iptables.d/{{ role_name }}
mode=0600
backup=no
owner=root
group=root
register: firewall_rule
tags:
- firewall
- files

- name: "Reload the firewall"
firewall: >
state=reloaded
when: firewall_rule|changed
tags:
- firewall
10 changes: 10 additions & 0 deletions templates/ip6tables.j2
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p ipv6-icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -j REJECT --reject-with icmp6-adm-prohibited
-A FORWARD -j REJECT --reject-with icmp6-adm-prohibited
COMMIT

0 comments on commit 0eb1f16

Please sign in to comment.