inspec/lib/resources/iptables.rb

66 lines
1.9 KiB
Ruby
Raw Normal View History

2015-10-11 22:21:11 +00:00
# encoding: utf-8
# author: Christoph Hartmann
# author: Dominik Richter
# Usage:
# describe iptables do
# it { should have_rule('-P INPUT ACCEPT') }
# end
#
# The following serverspec sytax is not implemented:
# describe iptables do
# it { should have_rule('-P INPUT ACCEPT').with_table('mangle').with_chain('INPUT') }
# end
# Please use the new sytax:
# describe iptables(table:'mangle', chain: 'input') do
# it { should have_rule('-P INPUT ACCEPT') }
# end
#
2015-10-12 08:32:46 +00:00
# Note: Docker containers normally do not have iptables installed
2015-10-11 22:21:11 +00:00
#
# @see http://ipset.netfilter.org/iptables.man.html
# @see http://ipset.netfilter.org/iptables.man.html
# @see https://www.frozentux.net/iptables-tutorial/iptables-tutorial.html
2015-10-26 03:04:18 +00:00
class IpTables < Inspec.resource(1)
2015-10-11 22:21:11 +00:00
name 'iptables'
def initialize(params = {})
2015-10-12 08:32:46 +00:00
@table = params[:table] || nil
@chain = params[:chain] || nil
# we're done if we are on linux
2015-10-26 03:04:18 +00:00
return if inspec.os.linux?
2015-10-12 08:32:46 +00:00
# ensures, all calls are aborted for non-supported os
@iptables_cache = []
skip_resource 'The `iptables` resource is not supported on your OS yet.'
2015-10-11 22:21:11 +00:00
end
def has_rule?(rule = nil, _table = nil, _chain = nil)
found = false
retrieve_rules.each { |line|
# checks if the rule is part of the ruleset
# for now, we expect an excact match
found = true if line.downcase == rule.downcase
}
found
end
def retrieve_rules
2015-10-12 08:32:46 +00:00
return @iptables_cache if defined?(@iptables_cache)
2015-10-11 22:21:11 +00:00
# construct iptables command to read all rules
2015-10-12 08:32:46 +00:00
@table.nil? ? table_cmd = '' : table_cmd = " -t #{@table} "
2015-10-11 22:21:11 +00:00
@chain.nil? ? chain_cmd = '' : chain_cmd = " #{@chain}"
2015-10-26 03:04:18 +00:00
cmd = inspec.command(format('iptables %s -S %s', table_cmd, chain_cmd).strip)
2015-10-12 08:32:46 +00:00
return [] if cmd.exit_status.to_i != 0
2015-10-11 22:21:11 +00:00
# split rules, returns array or rules
@iptables_cache = cmd.stdout.chomp.split("\n")
end
def to_s
format('Iptables %s %s', @table.nil? ? '' : "table: #{@table}", @chain.nil? ? '' : "chain: #{@chain}").strip
2015-10-11 22:21:11 +00:00
end
end