refactor iptables recipe and knockd to use iptables cookbook, which auto-provides persistence.

This commit is contained in:
Dave Eargle 2019-10-29 17:31:25 -06:00
parent 6a17501824
commit 5bb3dbf353
18 changed files with 832 additions and 15 deletions

View File

@ -0,0 +1,171 @@
# iptables Cookbook CHANGELOG
This file is used to list changes made in each version of the iptables cookbook.
## 4.5.0 (2018-11-24)
- Add sensitive option to resources
- Added filemode property to generated rule files
## 4.4.1 (2018-09-11)
- Remove mention of matchers in the readme
- Add back support for RHEL 6 + fix Amazon Linux 2 support
- Add additional specs for the package installs so we don't break this in the future
## 4.4.0 (2018-09-10)
- Use persistent iptables package for Debian config
- Add IPv6 support to iptables_rule and Add iptables_rule6
- Extend disabled recipe for Fedora and Amazon distros
## 4.3.4 (2018-02-15)
- Fix converge failures in the custom resource introduced in 4.3.3
- Remove stove and tomlrb from the Gemfile
- use apt_update not apt cookbook in testing
- Add Amazon Linux to test kitchen
- Simplify the platform family check using our helpers
## 4.3.3 (2018-02-15)
- Don't use kind_of in the custom resource (FC117)
## 4.3.2 (2018-02-07)
- Fix FC108 to resolve test failures
- Switch from ServerSpec to InSpec
- Resolve ChefSpec warnings
- Remove ChefSpec matchers that are no longer needed since ChefSpec autogenerates these
## 4.3.1 (2017-11-06)
- Updating namespace for attribute-based rules in the readme
## 4.3.0 (2017-10-28)
- Add Amazon Linux support on Chef 13
## 4.2.1 (2017-09-08)
- Resolve deprecation warning
## 4.2.0 (2017-04-14)
- [GH-69] - Clearing out iptables rule files on RHEL with the iptables::disabled recipe
## 4.1.0 (2017-04-11)
- specify optional table property for use with lines
## 4.0.1 (2017-03-29)
- Update metadata to require Chef 12.10+ due to use of with_run_context
## 4.0.0 (2017-02-27)
- Remove EOL platforms from testing
- Require Chef 12.5 and remove compat_resource dependency
## 3.1.0 (2017-01-16)
- Update readme to include new attribute
- Check subcmd exit codes in rebuild-iptables script
- fixed iptables disabled recipe to flush iptables after disabling the service
## 3.0.1 (2016-10-10)
- Fix rules resource so rebuild-iptables only runs once
- Add tests for nested resources
- Add system ruby attribute so that it can be overridden
## 3.0.0 (2016-09-16)
- Remove kitchen cloud config
- Fix default specs to work properly on RHEL and other general spec cleanup
- Simplify testing and fix failing tests on RHEL
- allow using a file provider instead of a template
- rename 'content' to 'lines' and add documentation
- make the attributes example a bit more useful
- using iptables-restore logic for rhel - same as debian
- copy new config to default location in case of iptables restart
- refactored rebuild-iptables script
- Update supported os
- Use compat_resource to restore Chef 12.1 - 12.4 compatibility
## v2.2.0 (2016-02-17)
- Remove the dependency on compat_resource cookbook. This fixes RHEL systems, but increases the required Chef version to 12.5 or later
## v2.1.1 (2016-01-26)
- Fixed failures on RHEL in the disabled recipe
## v2.1.0 (2016-01-25)
- Improved compatbility with Fedora
- Added management of the iptables sysconfig files using 2 new attributes. See the readme for more information
## v2.0.2 (2016-01-15)
- Fixed rules not being rebuilt when using the disable action in the custom resource
## v2.0.1 (2015-11-16)
- Added Chefspec matchers
## v2.0.0 (2015-10-21)
- Migrated LWRP to Chef 12.5 custom resources format with backwards compatibility provided via compat_resource cookbook to 12.X family
- Added Start / enable of iptables service in the default recipe when on RHEL based systems and the management of /etc/sysconfig/iptables so the service can start
- Added removal of /etc/iptables.d/ to the disabled recipe to allow for reenabling later on
- Modified the iptables service disable in the disable recipe to only run when on RHEL based systems
- Expanded the serverspec tests and test kitchen suites to better test rules custom resource and disable recipe
## v1.1.0 (2015-10-05)
- Fixed metadata description of the default recipe
- Added Kitchen CI config
- Added Chefspec unit tests
- Updated to our standard Rubocop config and resolve all warnings
- Added Travis CI config for lint / unit testing on Ruby 2/2.1/2.2
- Updated Contributing and Testing docs
- Added a maintainers doc
- Added a Gemfile with development and testing dependencies
- Added cookbook version and Travis CI badges to the readme
- Clarified in the readme that the minimum supported Chef release is 11.0
- Added a Rakefile easier testing
- Added a chefignore file to limit files that are uploaded to the Chef server
- Update to modern notification format to resolve Foodcritic warnings
- Added source_url and issues_url to the metadata for Supermarket
- Removed pre-Ruby 1.9 hash rockets
## v1.0.0 (2015-04-29)
NOTE: This release includes breaking changes to the behavior of this cookbook. The iptables_rule definition was converted to a LWRP. This changes the behavior of disabling iptables rules. Previously a rule could be disabled by specifying `enable false`. You must now specify `action :disable`. Additionally the cookbook no longer installs the out of the box iptables rules. These were rules made assumptions about the operating environment and should not have been installed out of the box. This makes this recipe a library cookbook that can be better wrapped to meet the needs or your particular environment.
- Definition converted to a LWRP to providing why-run support and
- The out of the box iptables rules are no longer installed. If you need these rules you'll need to wrap the cookbook and use the LWRP to define these same rules.
- Removed all references to the roadmap and deprecation of the cookbook. It's not going anywhere any time soon
- Use platform_family to better support Debian derivatives
- Converted file / directory modes to strings to preserve the leading 0
- Added additional RHEL derivitive distributions to the metadata
- Expanded excluded files in the gitignore and chefignore files
- Included the latest contributing documentation to match the current process
## v0.14.1 (2015-01-01)
- Fixing File.exists is deprecated for File.exist
## v0.14.0 (2014-08-31)
- [#14] Adds basic testing suite including Berksfile
- [#14] Adds basic integration/post-converge tests
- [#14] Adds default prefix and postfix rules to disalow traffic
## v0.13.2 (2014-04-09)
- [COOK-4496] Added Amazon Linux support
## v0.13.0 (2014-03-19)
- [COOK-3927] Substitute Perl version of rebuild-iptables with Ruby version
## v0.12.2 (2014-03-18)
- [COOK-4411] - Add newling to iptables.snat
## v0.12.0
- [COOK-2213] - iptables disabled recipe
## v0.11.0
- [COOK-1883] - add perl package so rebuild script works
## v0.10.0
- [COOK-641] - be able to save output on rhel-family
- [COOK-655] - use a template from other cookbooks
## v0.9.3
- Current public release.

View File

@ -0,0 +1,2 @@
Please refer to
https://github.com/chef-cookbooks/community_cookbook_documentation/blob/master/CONTRIBUTING.MD

View File

@ -0,0 +1,156 @@
# iptables Cookbook
[![Build Status](https://travis-ci.org/chef-cookbooks/iptables.svg?branch=master)](https://travis-ci.org/chef-cookbooks/iptables) [![Cookbook Version](https://img.shields.io/cookbook/v/iptables.svg)](https://supermarket.chef.io/cookbooks/iptables)
Installs iptables and provides a custom resource for adding and removing iptables rules
## Requirements
### Platforms
- Ubuntu/Debian
- RHEL/CentOS and derivatives
- Amazon Linux
### Chef
- Chef 12.10+
### Cookbooks
- none
## Recipes
### default
The default recipe will install iptables and provides a ruby script (installed in `/usr/sbin/rebuild-iptables`) to manage rebuilding firewall rules from files dropped off in `/etc/iptables.d`.
### disabled
The disabled recipe will install iptables, disable the `iptables` service (on RHEL platforms), and delete the rules directory `/etc/iptables.d`.
## Attributes
`default['iptables']['iptables_sysconfig']` and `default['iptables']['ip6tables_sysconfig']` are hashes that are used to template /etc/sysconfig/iptables-config and /etc/sysconfig/ip6tables-config. The keys must be upper case and any key / value pair included will be added to the config file.
`default['iptables']['system_ruby']` allows users to override the system ruby path if ruby is installed into a non standard location and Chef has been installed without an embedded ruby (eg. from the Gem).
## Custom Resource
### rule
The custom resource drops off a template in `/etc/iptables.d` after the `name` parameter. The rule will get added to the local system firewall through notifying the `rebuild-iptables` script. See **Examples** below.
NOTE: In the 1.0 release of this cookbook the iptables_rule definition was converted to a custom resource. This changes the behavior of disabling iptables rules. Previously a rule could be disabled by specifying `enable false`. You must now specify `action :disable`
## Usage
Add `recipe[iptables]` to your runlist to ensure iptables is installed / running and to ensure that the `rebuild-iptables` script is on the system. Then create use iptables_rule to add individual rules. See **Examples**.
Since certain chains can be used with multiple tables (e.g., _PREROUTING_), you might have to include the name of the table explicitly (i.e., _*nat_, _*mangle_, etc.), so that the `/usr/sbin/rebuild-iptables` script can infer how to assemble final ruleset file that is going to be loaded. Please note, that unless specified otherwise, rules will be added under the **filter** table by default.
### Examples
To enable port 80, e.g. in an `my_httpd` cookbook, create the following template:
```text
# Port 80 for http
-A FWR -p tcp -m tcp --dport 80 -j ACCEPT
```
This template would be located at: `my_httpd/templates/default/http.erb`. Then within your recipe call:
```ruby
iptables_rule 'http' do
action :enable
end
```
To redirect port 80 to local port 8080, e.g., in the aforementioned `my_httpd` cookbook, create the following template:
```text
*nat
# Redirect anything on eth0 coming to port 80 to local port 8080
-A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080
```
Please note, that we explicitly add name of the table (being _*nat_ in this example above) where the rules should be added.
This would most likely go in the cookbook, `my_httpd/templates/default/http_8080.erb`. Then to use it in `recipe[httpd]`:
```ruby
iptables_rule 'http_8080' do
action :enable
end
```
To create a rule without using a template resource use the `lines` property (you can optionally specify `table` when using `lines`):
```ruby
iptables_rule 'http_8080' do
lines '-A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080'
table :nat
end
```
Additionally, a rule can be marked as sensitive so it's contents does not get output to the the console or logged with the sensitive property set to `true`. The mode of the generated rule file can be set with the filemode property:
```ruby
iptables_rule 'http_8080' do
lines '-A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080'
table :nat
sensitive true
end
```
```ruby
iptables_rule 'http_8080' do
lines '-A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080'
table :nat
sensitive true
filemode '0600'
end
```
To get attribute-driven rules you can (for example) feed a hash of attributes into named iptables.d files like this:
```ruby
node.default['iptables']['rules']['http_80'] = '-A FWR -p tcp -m tcp --dport 80 -j ACCEPT'
node.default['iptables']['rules']['http_443'] = [
'# an example with multiple lines',
'-A FWR -p tcp -m tcp --dport 443 -j ACCEPT',
]
node['iptables']['rules'].map do |rule_name, rule_body|
iptables_rule rule_name do
lines [ rule_body ].flatten.join("\n")
end
end
```
## IPv6 supports
The `iptables_rule6` provides IPv6 support with the same behavior as the original `iptable_rule`.
A `/usr/sbin/rebuild-ip6tables` script perform iptables configuration and the IPv6 rules are stored in `/etc/ip6tables.d`
## License & Authors
**Author:** Cookbook Engineering Team ([cookbooks@chef.io](mailto:cookbooks@chef.io))
**Copyright:** 2008-2018, Chef Software, Inc.
```
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
```

View File

@ -0,0 +1,41 @@
#
# Cookbook:: iptables
# Attribute:: default
#
# Copyright:: 2016, Chef Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
default['iptables']['iptables_sysconfig'] = {
'IPTABLES_MODULES' => '',
'IPTABLES_MODULES_UNLOAD' => 'yes',
'IPTABLES_SAVE_ON_STOP' => 'no',
'IPTABLES_SAVE_ON_RESTART' => 'no',
'IPTABLES_SAVE_COUNTER' => 'no',
'IPTABLES_STATUS_NUMERIC' => 'yes',
'IPTABLES_STATUS_VERBOSE' => 'no',
'IPTABLES_STATUS_LINENUMBERS' => 'yes',
}
default['iptables']['ip6tables_sysconfig'] = {
'IP6TABLES_MODULES' => '',
'IP6TABLES_MODULES_UNLOAD' => 'yes',
'IP6TABLES_SAVE_ON_STOP' => 'no',
'IP6TABLES_SAVE_ON_RESTART' => 'no',
'IP6TABLES_SAVE_COUNTER' => 'no',
'IP6TABLES_STATUS_NUMERIC' => 'yes',
'IP6TABLES_STATUS_VERBOSE' => 'no',
'IP6TABLES_STATUS_LINENUMBERS' => 'yes',
}
default['iptables']['system_ruby'] = '/usr/bin/ruby'

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,31 @@
#
# Cookbook:: iptables
# Recipe:: _package
#
# Copyright:: 2008-2016, Chef Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# amazon linux, any fedora, and amazon linux 2
if (platform_family?('rhel') && node['platform_version'].to_i == 7) ||
(platform_family?('amazon') && node['platform_version'].to_i < 2013) ||
platform_family?('fedora')
package 'iptables-services'
else
package 'iptables'
if platform_family?('debian')
# Since Ubuntu 10.04LTS and Debian6, this package takes over the automatic loading of the saved iptables rules
package 'iptables-persistent'
end
end

View File

@ -0,0 +1,83 @@
#
# Cookbook:: iptables
# Recipe:: default
#
# Copyright:: 2008-2016, Chef Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
system_ruby = node['iptables']['system_ruby']
case node['platform_family']
when 'rhel', 'fedora', 'amazon'
node.default['iptables']['persisted_rules_iptables'] =
'/etc/sysconfig/iptables'
node.default['iptables']['persisted_rules_ip6tables'] =
'/etc/sysconfig/ip6tables'
when 'debian'
node.default['iptables']['persisted_rules_iptables'] =
'/etc/iptables/rules.v4'
node.default['iptables']['persisted_rules_ip6tables'] =
'/etc/iptables/rules.v6'
end
include_recipe 'iptables::_package'
%w(iptables ip6tables).each do |ipt|
execute "rebuild-#{ipt}" do
command "/usr/sbin/rebuild-#{ipt}"
action :nothing
end
directory "/etc/#{ipt}.d" do
action :create
end
template "/usr/sbin/rebuild-#{ipt}" do
source 'rebuild-iptables.erb'
mode '0755'
variables(
ipt: ipt,
hashbang: ::File.exist?(system_ruby) ? system_ruby : '/opt/chef/embedded/bin/ruby',
persisted_file: node['iptables']["persisted_rules_#{ipt}"]
)
end
if platform_family?('debian')
# debian based systems load iptables during the interface activation
template "/etc/network/if-pre-up.d/#{ipt}_load" do
source 'iptables_load.erb'
mode '0755'
variables iptables_save_file: "/etc/#{ipt}/general",
iptables_restore_binary: "/sbin/#{ipt}-restore"
end
elsif platform_family?('rhel', 'fedora', 'amazon')
# iptables service exists only on RHEL based systems
file "/etc/sysconfig/#{ipt}" do
content '# Chef managed placeholder to allow iptables service to start'
action :create_if_missing
end
template "/etc/sysconfig/#{ipt}-config" do
source 'iptables-config.erb'
mode '600'
variables config: node['iptables']["#{ipt}_sysconfig"]
end
service ipt do
action [:enable, :start]
supports status: true, start: true, stop: true, restart: true
end
end
end

View File

@ -0,0 +1,51 @@
#
# Cookbook:: iptables
# Recipe:: default
#
# Copyright:: 2008-2016, Chef Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
include_recipe 'iptables::_package'
%w(iptables ip6tables).each do |ipt|
service ipt do
action [:disable, :stop]
delayed_action :stop
supports status: true, start: true, stop: true, restart: true
only_if { %w(rhel fedora amazon).include?(node['platform_family']) }
end
# Necessary so that if iptables::disable is used and then later
# it is re-enabled without any rules changes, the templates will run the rebuilt script
directory "/etc/#{ipt}.d" do
action :delete
recursive true
notifies :run, "execute[#{ipt}Flush]", :immediately
end
["/etc/sysconfig/#{ipt}", "/etc/sysconfig/#{ipt}.fallback"].each do |f|
file f do
content '# iptables rules files cleared by chef via iptables::disabled'
only_if { %w(rhel fedora amazon).include?(node['platform_family']) }
notifies :run, "execute[#{ipt}Flush]", :immediately
end
end
# Flush and delete iptables rules
execute "#{ipt}Flush" do
command "#{ipt} -F"
action :nothing
end
end

View File

@ -0,0 +1,79 @@
#
# Author:: Tim Smith <tsmith84@gmail.com>
# Cookbook:: iptables
# Resource:: rule
#
# Copyright:: 2015-2018, Tim Smith
# Copyright:: 2017-2018, Chef Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
property :source, String
property :cookbook, String
property :variables, Hash, default: {}
property :lines, String
property :table, Symbol
property :ipv6, [TrueClass, FalseClass], default: false
property :filemode, [String, Integer], default: '0644'
action :enable do
ipt = new_resource.ipv6 ? 'ip6tables' : 'iptables'
# ensure we have execute[rebuild-iptables] in the outer run_context
with_run_context :root do
find_resource(:execute, "rebuild-#{ipt}") do
command "/usr/sbin/rebuild-#{ipt}"
action :nothing
end
end
if new_resource.lines.nil?
template "/etc/#{ipt}.d/#{new_resource.name}" do
source new_resource.source ? new_resource.source : "#{new_resource.name}.erb"
mode new_resource.filemode
cookbook new_resource.cookbook if new_resource.cookbook
variables new_resource.variables
backup false
sensitive new_resource.sensitive
notifies :run, "execute[rebuild-#{ipt}]", :delayed
end
else
new_resource.lines = "*#{new_resource.table}\n" + new_resource.lines if new_resource.table
file "/etc/#{ipt}.d/#{new_resource.name}" do
content new_resource.lines
mode new_resource.filemode
backup false
sensitive new_resource.sensitive
notifies :run, "execute[rebuild-#{ipt}]", :delayed
end
end
end
action :disable do
ipt = new_resource.ipv6 ? 'ip6tables' : 'iptables'
# ensure we have execute[rebuild-iptables] in the outer run_context
with_run_context :root do
find_resource(:execute, "rebuild-#{ipt}") do
command "/usr/sbin/rebuild-#{ipt}"
action :nothing
end
end
file "/etc/#{ipt}.d/#{new_resource.name}" do
action :delete
backup false
sensitive new_resource.sensitive
notifies :run, "execute[rebuild-#{ipt}]", :delayed
end
end

View File

@ -0,0 +1,53 @@
#
# Author:: Julien 'Lta' BALLET <contact@lta.io>
# Cookbook:: iptables
# Resource:: rule6
#
# Copyright:: 2018, Chef Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
property :source, String
property :cookbook, String
property :variables, Hash, default: {}
property :lines, String
property :table, Symbol
property :filemode, [String, Integer], default: '0644'
action :enable do
iptables_rule new_resource.name do
ipv6 true
source new_resource.source
cookbook new_resource.cookbook
variables new_resource.variables
lines new_resource.lines
table new_resource.table
sensitive new_resource.sensitive
filemode new_resource.filemode
action :enable
end
end
action :disable do
iptables_rule new_resource.name do
ipv6 true
source new_resource.source
cookbook new_resource.cookbook
variables new_resource.variables
lines new_resource.lines
table new_resource.table
sensitive new_resource.sensitive
filemode new_resource.filemode
action :disable
end
end

View File

@ -0,0 +1,4 @@
# This file managed by Chef. Do not hand edit
<% @config.each do |k,v| -%>
<%= k %>="<%= v %>"
<% end -%>

View File

@ -0,0 +1,3 @@
#!/bin/sh
<%= @iptables_restore_binary %> < <%= @iptables_save_file %>
exit 0

View File

@ -0,0 +1,139 @@
#!<%= @hashbang %> -w
#
# rebuild-<%= @ipt %>.rb -- Construct an iptables rules file from fragments.
#
# Written by Phil Cohen <github@phlippers.net>
# Copyright 2011, Phil Cohen
#
# Constructs an iptables rules file from the prefix, standard, and suffix
# files in the iptables configuration area, adding any additional modules
# specified in the command line, and prints the resulting iptables rules to
# standard output (suitable for saving into /var/lib/iptables or some other
# appropriate location on the system).
##############################################################################
# Modules and declarations
##############################################################################
# Path to the iptables template area.
TEMPLATE_PATH = "/etc/<%= @ipt %>.d"
##############################################################################
# Installation
##############################################################################
# Read in a file, processing includes as required.
def read_iptables(file, table = :filter)
file = File.join(TEMPLATE_PATH, file) unless File.dirname(file).include?("<%= @ipt %>.d")
rule = File.readlines(file).map{ |line| line.chomp }
rule.each do |line|
if line =~ /^\s*include\s+(\S+)$/
read_iptables($1, table)
elsif line =~ /^\s*\*([a-z]+)\s*$/
table = $1.to_sym
elsif line =~ /^\s*:([-a-zA-Z0-9_]+)(?:\s+([A-Z]+(?:\s*\[.*?\])))?$/
@data[table][:chains][$1] = $2 || '-'
elsif line !~ /^\s*COMMIT\s*$/
#detect new chains
if chain = line.match(/\-[ADRILFZN]\s+([-a-zA-Z0-9_]+)\s/)
@data[table][:chains][chain[1]] ||= '-'
end
@data[table][:rules].push line
end
end
end
# Write a file carefully.
def write_iptables(file, data)
File.open("#{file}.new", "w") { |f| f.write(data) }
File.rename("#{file}.new", file)
end
# Install iptables on a Red Hat or Debian system. Takes the new iptables data.
def install_rules(data)
Dir.mkdir('/etc/<%= @ipt %>') unless File.directory?('/etc/<%= @ipt %>')
write_iptables("<%= @persisted_file %>", data)
return false unless system("/sbin/<%= @ipt %>-restore < <%= @persisted_file %>")
true
end
##############################################################################
# Main routine
##############################################################################
@data = {
:filter => {
:chains => {
'INPUT' => 'ACCEPT [0,0]',
'FORWARD' => 'ACCEPT [0,0]',
'OUTPUT' => 'ACCEPT [0,0]'
},
:rules => []
},
:mangle => {
:chains => {
'PREROUTING' => 'ACCEPT [0,0]',
'INPUT' => 'ACCEPT [0,0]',
'FORWARD' => 'ACCEPT [0,0]',
'OUTPUT' => 'ACCEPT [0,0]',
'POSTROUTING' => 'ACCEPT [0,0]'
},
:rules => []
},
:nat => {
:chains => {
'PREROUTING' => 'ACCEPT [0,0]',
'POSTROUTING' => 'ACCEPT [0,0]',
'OUTPUT' => 'ACCEPT [0,0]'
},
:rules => [],
},
:raw => {
:chains => {
'PREROUTING' => 'ACCEPT [0,0]',
'OUTPUT' => 'ACCEPT [0,0]'
},
:rules => [],
},
:security => {
:chains => {
'INPUT' => 'ACCEPT [0,0]',
'FORWARD' => 'ACCEPT [0,0]',
'OUTPUT' => 'ACCEPT [0,0]'
},
:rules => []
}
}
templates = Dir["#{TEMPLATE_PATH}/*"].sort.delete_if do |template|
%w[prefix suffix postfix].include?(File.basename(template))
end
templates.unshift 'prefix' if File.exist? "#{TEMPLATE_PATH}/prefix"
templates.push 'suffix' if File.exist? "#{TEMPLATE_PATH}/suffix"
templates.push 'postfix' if File.exist? "#{TEMPLATE_PATH}/postfix"
templates.each { |template| read_iptables(template) }
iptables_rules = ""
@data.each do |table, table_data|
if table_data[:rules].any?
iptables_rules << "*#{table.to_s}\n"
table_data[:chains].each do |chain, rule|
iptables_rules << ":#{chain} #{rule}\n"
end
iptables_rules << table_data[:rules].join("\n")
iptables_rules << "\nCOMMIT\n"
end
end
system_files = %w(/etc/debian_version /etc/redhat-release /etc/system-release)
if system_files.any? { |file| File.exist?(file) }
success = install_rules(iptables_rules)
raise "#{$0}: failed to install iptables rules" unless success
else
raise "#{$0}: cannot figure out whether this is Red Hat or Debian\n";
end
exit 0

View File

@ -18,5 +18,6 @@ default[:metasploitable][:ports] = { :cups => 631,
:chatbot_nodejs => 3000,
:readme_app => 3500,
:sinatra => 8181,
:samba => 445
:samba => 445,
:ssh => 22
}

View File

@ -21,3 +21,4 @@ version '0.1.0'
depends 'apt', '~> 7.2'
depends 'docker', '~> 4.9'
depends 'mysql', '~> 8.3'
depends 'iptables', '~> 4.5'

View File

@ -4,23 +4,19 @@
#
# Copyright:: 2017, Rapid7, All Rights Reserved.
bash 'setup for knockd, used for flag' do
code_to_execute = ""
code_to_execute << "iptables -A FORWARD 1 -p tcp -m tcp --dport 8989 -j DROP\n"
code_to_execute << "iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT\n"
node[:metasploitable][:ports].keys.each do |service|
code_to_execute << "iptables -A INPUT -p tcp --dport #{node[:metasploitable][:ports][service.to_sym]} -j ACCEPT\n"
iptables_rule 'established' do
lines '-I INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT'
end
node[:metasploitable][:ports].keys.each do |service|
iptables_rule service do
lines "-I INPUT -p tcp --dport #{node[:metasploitable][:ports][service.to_sym]} -j ACCEPT"
end
code_to_execute << "iptables -A INPUT -p tcp --dport 22 -j ACCEPT\n"
code_to_execute << "iptables -A INPUT -j DROP\n"
code code_to_execute
end
package 'iptables-persistent' do
action :install
iptables_rule 'drop_all' do
lines '-A INPUT -j DROP'
end
service 'iptables-persistent' do
action [:enable, :start]
end

View File

@ -22,6 +22,10 @@ execute 'remove_carriage_returns' do
command "sed -i -e 's/\r//g' /etc/default/knockd"
end
iptables_rule 'knockd' do
lines "-I FORWARD 1 -p tcp -m tcp --dport #{node[:flags][:five_of_diamonds][:vuln_port]} -j DROP"
end
service 'knockd' do
action [:enable, :start]
end

View File

@ -19,6 +19,7 @@ Vagrant.configure("2") do |config|
chef.cookbooks_path = [ '../../cookbooks' ]
chef.add_recipe "apt::default"
chef.add_recipe "iptables::default"
chef.add_recipe "metasploitable::users"
chef.add_recipe "metasploitable::mysql"
chef.add_recipe "metasploitable::apache_continuum"