Class: IpTables

Inherits:
Object
  • Object
show all
Defined in:
lib/resources/iptables.rb

Overview

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

Note: Docker containers normally do not have iptables installed

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ IpTables

Returns a new instance of IpTables.



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/resources/iptables.rb', line 33

def initialize(params = {})
  @table = params[:table] || nil
  @chain = params[:chain] || nil

  # we're done if we are on linux
  return if inspec.os.linux?

  # ensures, all calls are aborted for non-supported os
  @iptables_cache = []
  skip_resource 'The `iptables` resource is not supported on your OS yet.'
end

Instance Method Details

#has_rule?(rule = nil, _table = nil, _chain = nil) ⇒ Boolean

Returns:

  • (Boolean)


45
46
47
48
49
50
51
52
53
# File 'lib/resources/iptables.rb', line 45

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.casecmp(rule) == 0
  }
  found
end

#retrieve_rulesObject



55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/resources/iptables.rb', line 55

def retrieve_rules
  return @iptables_cache if defined?(@iptables_cache)

  # construct iptables command to read all rules
  @table.nil? ? table_cmd = '' : table_cmd = " -t #{@table} "
  @chain.nil? ? chain_cmd = '' : chain_cmd = " #{@chain}"
  cmd = inspec.command(format('iptables %s -S %s', table_cmd, chain_cmd).strip)
  return [] if cmd.exit_status.to_i != 0

  # split rules, returns array or rules
  @iptables_cache = cmd.stdout.chomp.split("\n")
end

#to_sObject



68
69
70
# File 'lib/resources/iptables.rb', line 68

def to_s
  format('Iptables %s %s', @table.nil? ? '' : "table: #{@table}", @chain.nil? ? '' : "chain: #{@chain}").strip
end