GithubHelp home page GithubHelp logo

sous-chefs / firewall Goto Github PK

View Code? Open in Web Editor NEW
96.0 54.0 150.0 660 KB

Development repository for the firewall cookbook

Home Page: https://supermarket.chef.io/cookbooks/firewall

License: Apache License 2.0

Ruby 99.57% HTML 0.38% Shell 0.05%
firewall chef hacktoberfest chef-cookbook chef-resource managed-by-terraform

firewall's Introduction

firewall Cookbook

Cookbook Version CI State OpenCollective OpenCollective License

Provides a set of primitives for managing firewalls and associated rules.

PLEASE NOTE - The resource/providers in this cookbook are under heavy development. An attempt is being made to keep the resource simple/stupid by starting with less sophisticated firewall implementations first and refactor/vet the resource definition with each successive provider.

Maintainers

This cookbook is maintained by the Sous Chefs. The Sous Chefs are a community of Chef cookbook maintainers working together to maintain important cookbooks. If you’d like to know more please visit sous-chefs.org or come chat with us on the Chef Community Slack in #sous-chefs.

Requirements

  • Chef Infra Client 15.5+
depends 'firewall'

Supported firewalls and platforms

  • UFW - Ubuntu, Debian (except 9)
  • IPTables - Red Hat & CentOS, Ubuntu
  • FirewallD - Red Hat & CentOS >= 7.0 (IPv4 only support, needs contributions/testing)
  • Windows Advanced Firewall - 2012 R2
  • nftables

Tested on:

  • Ubuntu 16.04 with iptables, ufw
  • Debian 9 with iptables
  • Debian 11 with nftables
  • Debian 11 with new resources for firewalld
  • CentOS 6 with iptables
  • CentOS 7.1 with firewalld
  • Oracle 8 with nftables
  • Windows Server 2012r2 with Windows Advanced Firewall

By default, Ubuntu chooses ufw. To switch to iptables, set this in an attribute file:

default['firewall']['ubuntu_iptables'] = true

By default, Red Hat & CentOS >= 7.0 chooses firewalld. To switch to iptables, set this in an attribute file:

default['firewall']['redhat7_iptables'] = true

In order to use nftables, just use the resource nftables and nftables_rule. These resources are written in more modern design styles and are not configurable by node attributes.

Considerations that apply to all firewall providers and resources

This cookbook comes with two resources, firewall and firewall rule. The typical usage scenario is as follows:

  • run the :install action on the firewall resource named 'default', which installs appropriate packages and configures services to start on boot and starts them
  • run the :create action on every firewall_rule resource, which adds to the list of rules that should be configured on the firewall. firewall_rule then automatically sends a delayed notification to the firewall['default'] resource to run the :restart action.
  • run the delayed notification with action :restart on the firewall resource. if any rules are different than the last run, the provider will update the current state of the firewall rules to match the expected rules.

There is a fundamental mismatch between the idea of a chef action and the action that should be taken on a firewall rule. For this reason, the chef action for a firewall_rule may be :nothing (the rule should not be present in the firewall) or :create (the rule should be present in the firewall), but the action taken on a packet in a firewall (DROP, ACCEPT, etc) is denoted as a command parameter on the firewall_rule resource.

The same points hold for the nftables- and nftables_rule-resources.

iptables considerations

If you need to use a table other than *filter, the best way to do so is like so:

node.default['firewall']['iptables']['defaults'][:ruleset] = {
  '*filter' => 1,
  ':INPUT DROP' => 2,
  ':FORWARD DROP' => 3,
  ':OUTPUT ACCEPT_FILTER' => 4,
  'COMMIT_FILTER' => 100,
  '*nat' => 101,
  ':PREROUTING DROP' => 102,
  ':POSTROUTING DROP' => 103,
  ':OUTPUT ACCEPT_NAT' => 104,
  'COMMIT_NAT' => 200
}

Note -- in order to support multiple hash keys containing the same rule, anything found after the underscore will be stripped for: :OUTPUT :INPUT :POSTROUTING :PREROUTING COMMIT. This allows an example like the above to be reduced to just repeated lines of COMMIT and :OUTPUT ACCEPT while still avoiding duplication of other things.

Then it's trivial to add additional rules to the *nat table using the raw parameter:

firewall_rule "postroute" do
  raw "-A POSTROUTING -o eth1 -p tcp -d 172.28.128.21 -j SNAT --to-source 172.28.128.6"
  position 150
end

Note that any line starting with COMMIT will become just COMMIT, as hash keys must be unique but we need multiple commit lines.

nftables

Please read the documentation for the nftables resource and the nftables_rule resource

default

The default recipe creates a firewall resource with action install.

disable_firewall

Used to disable platform specific firewall. Many clouds have their own firewall configured outside of the OS instance such as AWS Security Groups.

firewalld

A firewalld specific recipe creates a firewall resource with action install with the default zone (default: drop)

Attributes

  • default['firewall']['allow_ssh'] = false, set true to open port 22 for SSH when the default recipe runs
  • default['firewall']['allow_mosh'] = false, set to true to open UDP ports 60000 - 61000 for Mosh when the default recipe runs
  • default['firewall']['allow_winrm'] = false, set true to open port 5989 for WinRM when the default recipe runs
  • default['firewall']['allow_loopback'] = false, set to true to allow all traffic on the loopback interface
  • default['firewall']['allow_icmp'] = false, set true to allow icmp protocol on supported OSes (note: ufw and windows implementations don't support this)
  • default['firewall']['ubuntu_iptables'] = false, set to true to use iptables on Ubuntu / Debian when using the default recipe
  • default['firewall']['redhat7_iptables'] = false, set to true to use iptables on Red Hat / CentOS 7 when using the default recipe
  • default['firewall']['ufw']['defaults'] hash for template /etc/default/ufw
  • default['firewall']['iptables']['defaults'] hash for default policies for 'filter' table's chains`
  • default['firewall']['windows']['defaults'] hash to define inbound / outbound firewall policy on Windows platform
  • default['firewall']['allow_established'] = true, set to false if you don't want a related/established default rule on iptables
  • default['firewall']['ipv6_enabled'] = true, set to false if you don't want IPv6 related/established default rule on iptables (this enables ICMPv6, which is required for much of IPv6 communication)
  • default['firewall']['firewalld']['permanent'] = false, set to true if you want firewalld rules to be added with --permanent so they survive a reboot. This will be changed to true by default in a future major version release.
  • default['firewall']['firewalld']['permanent'] = false, set to true if you want firewalld rules to be added with --permanent so they survive a reboot. This will be changed to true by default in a future major version release.
  • default['firewall']['firewalld']['zone'] = 'drop', Default zone for firewall
  • default['firewall']['firewalld']['loopback_zone'] = 'trusted', zone for loopback to be enabled (using allow_loopback)
  • default['firewall']['firewalld']['icmp_zone'] = 'public', zone for icmp to be enabled (using allow_icmp)
  • default['firewall']['firewalld']['ssh_zone'] = 'public', zone for ssh to be enabled (using allow_ssh)
  • default['firewall']['firewalld']['mosh_zone'] = 'public', zone for mosh to be enabled (using allow_mosh)
  • default['firewall']['firewalld']['established_zone'] = 'public', zone for loopback to be enabled (using allow_established)

Resources

There is a separate folder for firewalld resources.

firewall

NB: The name 'default' of this resource is important as it is used for firewall_rule providers to locate the firewall resource. If you change it, you must also supply the same value to any firewall_rule resources using the firewall_name parameter.

Actions

  • :install (default action): Install and Enable the firewall. This will ensure the appropriate packages are installed and that any services have been started.
  • :disable: Disable the firewall. Drop any rules and put the node in an unprotected state. Flush all current rules. Also erase any internal state used to detect when rules should be applied.
  • :flush: Flush all current rules. Also erase any internal state used to detect when rules should be applied.
  • :save: Ensure all rules are added permanently under firewalld using --permanent. Not supported on ufw, iptables. You must notify this action at the end of the chef run if you want permanent firewalld rules (they are not persistent by default).

Parameters

  • disabled (default to false): If set to true, all actions will no-op on this resource. This is a way to prevent included cookbooks from configuring a firewall.
  • ipv6_enabled (default to true): If set to false, firewall will not perform any ipv6 related work. Currently only supported in iptables.
  • log_level: UFW only. Level of verbosity the firewall should log at. valid values are: :low, :medium, :high, :full, :off. default is :low.
  • rules: This is used internally for firewall_rule resources to append their rules. You should NOT touch this value unless you plan to supply an entire firewall ruleset at once, and skip using firewall_rule resources.
  • disabled_zone (firewalld only): The zone to set on firewalld when the firewall should be disabled. Can be any string in symbol form, e.g. :public, :drop, etc. Defaults to :public.
  • enabled_zone (firewalld only): The zone to set on firewalld when the firewall should be enabled. Can be any string in symbol form, e.g. :public, :drop, etc. Defaults to :drop.
  • package_options: Used to pass options to the package install of firewall
# all defaults
firewall 'default'

# enable platform default firewall
firewall 'default' do
  action :install
end

# increase logging past default of 'low'
firewall 'default' do
  log_level :high
  action    :install
end

firewall_rule

Actions

  • :create (default action): If a firewall_rule runs this action, the rule will be recorded in a chef resource's internal state, and applied when providers automatically notify the firewall resource with action :reload. The notification happens automatically.

Parameters

  • firewall_name: the matching firewall resource that this rule applies to. Default value: default
  • raw: Used to pass an entire rule as a string, omitting all other parameters. This line will be directly loaded by iptables-restore, fed directly into ufw on the command line, or run using firewall-cmd.
  • description (default: same as rule name): Used to provide a comment that will be included when adding the firewall rule.
  • include_comment (default: true): Used to optionally exclude the comment in the rule.
  • position (default: 50): relative position to insert rule at. Position may be any integer between 0 < n < 100 (exclusive), and more than one rule may specify the same position.
  • command: What action to take on a particular packet
    • :allow (default action): the rule should allow matching packets
    • :deny: the rule should deny matching packets
    • :reject: the rule should reject matching packets
    • :masquerade: Masquerade the matching packets
    • :redirect: Redirect the matching packets
    • :log: Configure logging
  • stateful: a symbol or array of symbols, such as ``[:related, :established]` that will be passed to the state module in iptables or firewalld.
  • zone: (firewalld only), a string, such as public that the rule will be applied.
  • protocol: :tcp (default), :udp, :icmp, :none or protocol number. Using protocol numbers is not supported using the ufw provider (default for debian/ubuntu systems).
  • direction: For ufw, direction of the rule. valid values are: :in (default), :out, :pre, :post.
  • source (Default is 0.0.0.0/0 or Anywhere): source ip address or subnet to filter.
  • source_port (Default is nil): source port for filtering packets.
  • destination: ip address or subnet to filter on packet destination, must be a valid IP
  • port or dest_port: target port number (ie. 22 to allow inbound SSH), or an array of incoming port numbers (ie. [80,443] to allow inbound HTTP & HTTPS). NOTE: protocol attribute is required with multiple ports, or a range of incoming port numbers (ie. 60000..61000 to allow inbound mobile-shell. NOTE: protocol, or an attribute is required with a range of ports.
  • interface: (source) interface to apply rule (ie. eth0).
  • dest_interface: interface where packets may be destined to go
  • redirect_port: redirected port for rules with command :redirect
  • logging: may be added to enable logging for a particular rule. valid values are: :connections, :packets. In the ufw provider, :connections logs new connections while :packets logs all packets.
# open standard ssh port
firewall_rule 'ssh' do
  port     22
  command  :allow
end

# open standard http port to tcp traffic only; insert as first rule
firewall_rule 'http' do
  port     80
  protocol :tcp
  position 1
  command   :allow
end

# restrict port 13579 to 10.0.111.0/24 on eth0
firewall_rule 'myapplication' do
  port      13579
  source    '10.0.111.0/24'
  direction :in
  interface 'eth0'
  command    :allow
end

# specify a protocol number (supported on centos/redhat)
firewall_rule 'vrrp' do
  protocol    112
  command      :allow
end

# use the iptables provider to specify protocol number on debian/ubuntu
firewall_rule 'vrrp' do
  provider    Chef::Provider::FirewallRuleIptables
  protocol    112
  command      :allow
end

# can use :raw command with UFW provider for VRRP
firewall_rule "VRRP" do
  command   :allow
  raw "allow to 224.0.0.18"
end

# open UDP ports 60000..61000 for mobile shell (mosh.org), note
# that the protocol attribute is required when using port_range
firewall_rule 'mosh' do
  protocol   :udp
  port       60000..61000
  command     :allow
end

# open multiple ports for http/https, note that the protocol
# attribute is required when using ports
firewall_rule 'http/https' do
  protocol :tcp
  port     [80, 443]
  command   :allow
end

# firewalld example of opening port 22 on public zone
firewall_rule 'ssh' do
  port    22
  zone    "public"
  command :allow
end

firewall 'default' do
  enabled false
  action :nothing
end

Providers

  • See libraries/z_provider_mapping.rb for a full list of providers for each platform and version.

Different providers will determine the current state of the rules differently -- parsing the output of a command, maintaining the state in a file, or some other way. If the firewall is adjusted from outside of chef (non-idempotent), it's possible that chef may be caught unaware of the current state of the firewall. The best workaround is to add a :flush action to the firewall resource as early as possible in the chef run, if you plan to modify the firewall state outside of chef.

Troubleshooting

To figure out what the position values are for current rules, print the hash that contains the weights:

require pp
default_firewall = resources(:firewall, 'default')
pp default_firewall.rules

Development

This section details "quick development" steps. For a detailed explanation, see [[Contributing.md]].

  1. Clone this repository from GitHub:

$ git clone [email protected]:chef-cookbooks/firewall.git

  1. Create a git branch

$ git checkout -b my_bug_fix

  1. Install dependencies:

$ bundle install

  1. Make your changes/patches/fixes, committing appropiately
  2. Write tests
  3. Run the tests:
  • bundle exec foodcritic -f any .
  • bundle exec rspec
  • bundle exec rubocop
  • bundle exec kitchen test

In detail:

  • Foodcritic will catch any Chef-specific style errors
  • RSpec will run the unit tests
  • Rubocop will check for Ruby-specific style errors
  • Test Kitchen will run and converge the recipes

Contributors

This project exists thanks to all the people who contribute.

Backers

Thank you to all our backers!

https://opencollective.com/sous-chefs#backers

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website.

https://opencollective.com/sous-chefs/sponsor/0/website https://opencollective.com/sous-chefs/sponsor/1/website https://opencollective.com/sous-chefs/sponsor/2/website https://opencollective.com/sous-chefs/sponsor/3/website https://opencollective.com/sous-chefs/sponsor/4/website https://opencollective.com/sous-chefs/sponsor/5/website https://opencollective.com/sous-chefs/sponsor/6/website https://opencollective.com/sous-chefs/sponsor/7/website https://opencollective.com/sous-chefs/sponsor/8/website https://opencollective.com/sous-chefs/sponsor/9/website

firewall's People

Contributors

a7b81a9086 avatar agperson avatar athiede-vendavo avatar blt04 avatar chaim1221 avatar cwebberops avatar damacus avatar davidalpert avatar gene1wood avatar glenjamin avatar gravitystorm avatar kitchen-porter avatar lmunro avatar martinb3 avatar mattray avatar nathenharvey avatar paulustm avatar powerkiki avatar pwelch avatar ramereth avatar rdoorn avatar renovate[bot] avatar schisamo avatar sethvargo avatar strawhatboy avatar stromweld avatar tas50 avatar tg90nor avatar williamsjj avatar xorimabot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

firewall's Issues

"No parent found for firewall_rule" error being thrown by Poise during compile

I'm seeing this error while running in DigitalOcean, but only after a number of successful Chef runs. I can't figure out how to recover, short of building a new droplet... This doesn't happen in Vagrant/VirtualBox at all, and it doesn't happen on initial compile/converge or the first few runs.

Any ideas? I'm running Chef 12.2.1 on Ubuntu 14.04.2 LTS, and I'm using v1.0.1 of the firewall cookbook. Thanks much!

================================================================================
Recipe Compile Error in /var/chef/cache/cookbooks/my-tuning/recipes/default.rb
================================================================================

RuntimeError
------------
No parent found for firewall_rule[rule-name-here]

Cookbook Trace:
---------------
  /var/chef/cache/cookbooks/poise/libraries/subresources.rb:168:in `parent'
  /var/chef/cache/cookbooks/poise/libraries/subresources.rb:176:in `after_created'
  /var/chef/cache/cookbooks/my-tuning/recipes/firewall.rb:18:in `block in from_file'
  /var/chef/cache/cookbooks/my-tuning/recipes/firewall.rb:17:in `each'
  /var/chef/cache/cookbooks/my-tuning/recipes/firewall.rb:17:in `from_file'
  /var/chef/cache/cookbooks/my-tuning/recipes/default.rb:43:in `from_file'

Relevant File Content:
----------------------
/var/chef/cache/cookbooks/poise/libraries/subresources.rb:

161:          elsif !@parent
162:            # Find the last instance of the parent class as the default parent
163:            @run_context.resource_collection.each do |r|
164:              if r.is_a?(self.class.parent_type)
165:                @parent = ParentRef.new(r)
166:              end
167:            end
168>>           raise "No parent found for #{self}" unless @parent || self.class.parent_optional
169:          end
170:          @parent && @parent.resource
171:        end
172:  
173:        def after_created
174:          super
175:          begin
176:            parent.subresources.lookup(self) if parent
177:          rescue Chef::Exceptions::ResourceNotFound


Running handlers:
[2015-04-03T18:49:18-04:00] ERROR: Running exception handlers
Running handlers complete
[2015-04-03T18:49:18-04:00] ERROR: Exception handlers complete
[2015-04-03T18:49:18-04:00] FATAL: Stacktrace dumped to /var/chef/cache/chef-stacktrace.out
Chef Client failed. 0 resources updated in 11.561637599 seconds
[2015-04-03T18:49:18-04:00] ERROR: No parent found for firewall_rule[rule-name-here]
[2015-04-03T18:49:18-04:00] FATAL: Chef::Exceptions::ChildConvergeError: Chef run process exited unsuccessfully (exit code 1)

My firewall rule (basically) is as follows:

firewall_rule "rule-name-here" do
    source "1.1.1.1"
    position 1
    action :reject
  end

Thanks!

release 1.2.1 to supermarket

Hello,

Please could the version be bumped and pushed to the Supermarket to support IP protocol numbers?

Thanks in advance!

IPV6

We should write tests and ensure we support ipv6.

Build failures in Travis

Build is currently failing.

$ bundle exec foodcritic -f any .

FC002: Avoid string interpolation where not required: ./providers/rule_ufw.rb:151

The command "bundle exec foodcritic -f any ." exited with 3.

$ bundle exec rubocop

Inspecting 8 files

...CC.CC

Offences:

resources/default.rb:31:1: C: Keep a blank line before and after private.

private

^^^^^^^

resources/rule.rb:43:1: C: Keep a blank line before and after private.

private

^^^^^^^

providers/rule_ufw.rb:57:1: C: Keep a blank line before and after private.

private

^^^^^^^

providers/rule_ufw.rb:86:1: C: Cyclomatic complexity for rule is too high. [11/6]

def rule

^^^

providers/rule_ufw.rb:120:1: C: Cyclomatic complexity for rule_exists? is too high. [10/6]

def rule_exists?

^^^

providers/rule_ufw.rb:142:3: C: Favor modifier if usage when you have a single-line body. Another good alternative is the usage of control flow &&/||.

if to.empty?

^^

providers/ufw.rb:47:1: C: Keep a blank line before and after private.

private

^^^^^^^

8 files inspected, 7 offences detected

The command "bundle exec rubocop" exited with 1.

Done. Your build exited with 1.

Relief from "warning: already initialized constant" in supermarket release?

/var/.../cookbooks/firewall/libraries/provider_firewall_rule_firewalld.rb:60: warning: already initialized constant Chef::Provider::FirewallRuleFirewalld::CHAIN
/var/.../cookbooks/firewall/libraries/provider_firewall_rule_firewalld.rb:60: warning: previous definition of CHAIN was here

ad infinitum

This seems fixed in c9240b8 but with the most recent supermarket version, all the warnings are still making my test output useless.

It looks like there are a lot of balls in the air right now and it may be inappropriate for a new release at this time, but any tips on avoiding this problem? Would it be reasonable to "depend" a previous version?

Separate ipv4 and ip6 functionality

It's becoming harder and harder to guess which rules will apply cleanly to ip6tables-restore, so we probably just need to make an explicit way to let firewall_rule indicate if it should apply to ipv4, ipv6, or both. This would take a lot of guesswork out of the process, and cleanup the logic in the cookbook tremendously.

TypeError when trying to use position in a ufw firewall_rule

When trying to use position in a ufw firewall_rule, Chef is failing with a TypeError: no implicit conversion from nil to integer. Full details of the run are below, but I was able to work around this by forcing the position attribute to a string in the apply_rule function on line 69 of provider_firewall_rule_ufw.rb as follows:

ufw_command << 'insert' << new_resource.position.to_s if new_resource.position

With this change in place, the Chef run succeeds and the rules (all of them) are applied correctly.

Has anyone else seen this? Thanks!

==> web: ==========================================================================
==> web: Error executing action `reject` on resource 'firewall_rule[block-1.1.1.1]'
==> web: ==========================================================================
==> web: 
==> web: 
==> web: TypeError
==> web: ---------
==> web: no implicit conversion from nil to integer
==> web: 
==> web: 
==> web: Cookbook Trace:
==> web: ---------------
==> web: /tmp/vagrant-chef-2/chef-solo-1/cookbooks/firewall/libraries/provider_firewall_rule_ufw.rb:78:in `block (2 levels) in apply_rule'
==> web: 
==> web: /tmp/vagrant-chef-2/chef-solo-1/cookbooks/poise/libraries/subcontext_block.rb:82:in `instance_eval'
==> web: 
==> web: /tmp/vagrant-chef-2/chef-solo-1/cookbooks/poise/libraries/subcontext_block.rb:82:in `subcontext_block'
==> web: 
==> web: /tmp/vagrant-chef-2/chef-solo-1/cookbooks/poise/libraries/notifying_block.rb:33:in `notifying_block'
==> web: 
==> web: /tmp/vagrant-chef-2/chef-solo-1/cookbooks/firewall/libraries/provider_firewall_rule_ufw.rb:76:in `block in apply_rule'
==> web: /tmp/vagrant-chef-2/chef-solo-1/cookbooks/firewall/libraries/provider_firewall_rule_ufw.rb:75:in `apply_rule'
==> web: /tmp/vagrant-chef-2/chef-solo-1/cookbooks/firewall/libraries/provider_firewall_rule_ufw.rb:46:in `action_reject'
==> web: 
==> web: Resource Declaration:
==> web: ---------------------
==> web: # In /tmp/vagrant-chef-2/chef-solo-1/cookbooks/mycookbook/recipes/firewall.rb
==> web: 
==> web:   9:   firewall_rule "block-#{bad_ip}" do
==> web:  10:     source bad_ip
==> web:  11:     position 1
==> web:  12:     action :reject
==> web:  13:   end
==> web:  14: end
==> web: 
==> web: Compiled Resource:
==> web: ------------------
==> web: # Declared in /tmp/vagrant-chef-2/chef-solo-1/cookbooks/mycookbook/recipes/firewall.rb:9:in `block in from_file'
==> web: 
==> web: firewall_rule("block-1.1.1.1") do
==> web:   action [:reject]
==> web:   retries 0
==> web:   retry_delay 2
==> web:   default_guard_interpreter :default
==> web:   declared_type :firewall_rule
==> web:   cookbook_name :"mycookbook"
==> web:   recipe_name "firewall"
==> web:   parent firewall[ufw]
==> web:   source "1.1.1.1"
==> web:   position 1
==> web:   protocol :tcp
==> web:   direction :in
==> web: end
==> web: 
==> web: [2015-03-28T16:13:27+00:00] INFO: Running queued delayed notifications before re-raising exception
==> web: [2015-03-28T16:13:27+00:00] ERROR: Running exception handlers
==> web: [2015-03-28T16:13:27+00:00] ERROR: Exception handlers complete
==> web: [2015-03-28T16:13:27+00:00] FATAL: Stacktrace dumped to /var/chef/cache/chef-stacktrace.out
==> web: [2015-03-28T16:13:27+00:00] ERROR: firewall_rule[block-1.1.1.1] (mycookbook::firewall line 9) had an error: TypeError: no implicit conversion from nil to integer
==> web: [2015-03-28T16:13:27+00:00] FATAL: Chef::Exceptions::ChildConvergeError: Chef run process exited unsuccessfully (exit code 1)

source getting list of ip addresses

Hello,

Is it possible for the 'source' to be list of ip addresses instead of a single ip? UFW seems to allow only one IP but it would be great to have a list of ips here in the cookbook.
Thanks

Intermittent ProviderNotFound Exception

I have the firewall cookbook in my base cookbook repo and a resource that configures the firewall for my centos nodes. I've been getting these at random points, usually when the base cookbook is specified in the run list before the node's recipes. If I reverse the order and have the base last in the order in the run list, I don't get this Exception. I want to be able to specify the base cookbook first in the run list for obvious reasons. What's going on with this?

       ================================================================================
       Error executing action `enable` on resource 'firewall[centos-firewall]'
       ================================================================================

       Chef::Exceptions::ProviderNotFound
       ----------------------------------
       Cannot find a provider for firewall[centos-firewall] on centos version 7.0.1406

       Resource Declaration:
       ---------------------
       # In /tmp/kitchen/cache/cookbooks/discogs-base/recipes/default.rb

        91:   firewall 'centos-firewall' do
        92:     action :enable
        93:   end
        94:

       Compiled Resource:
       ------------------
       # Declared in /tmp/kitchen/cache/cookbooks/discogs-base/recipes/default.rb:91:in `from_file'

       firewall("centos-firewall") do
         action [:enable]
         retries 0
         retry_delay 2
         default_guard_interpreter :default
         subresources [firewall_rule[consul], firewall_rule[consul400], firewall_rule[consul500], firewall_rule[consul600], firewall_rule[nrpe], firewall_rule[ssh], firewall_rule[mysql], firewall_rule[app], firewall_rule[http]]
         declared_type :firewall
         cookbook_name "discogs-base"
         recipe_name "default"
       end

[support] How to set firewall_rule in multiple cookbooks

I'm using elkstack::acl, but when also try to add some rules in a base cookbook for all servers, it's not picked up. The poise setup really confuses me, to be honest. I don't understand what's going on at this giant abstractions layer, but I'm not used to resources getting swallowed and failing to be acted upon

This is what I have in base::firewall:

firewall 'iptables' do
  action :nothing
  provider Chef::Provider::FirewallIptables
end

firewall_rule "allow ssh entries inbound" do
  provider    Chef::Provider::FirewallRuleIptables
  protocol    :tcp
  port        22  
  action      :allow
end

I have base::firewall in the runlist before elkstack::acl. When I go to check out the rules at the of the run with iptables -L, only the elkstack rules are there. If I put my own recipe after the elkstack one in the runlist, then only its ssh rule shows up EDIT: it does get appended.

Any suggestions? fwiw, my experience with this cookbook has not been wonderful, and I've spent lots of cycles trying to sort it out :(

EDIT: Ok, so it seems that if my recipe is placed before the elkstack::acl one, then it's ignored. If place afterward, it's added. This is pretty unexpected behaviour

Add purge and ignore attribute parameter to resource 'firewall'

The resource 'firewall' is missing a key feature, handle the unmanaged firewall rules.
Chef should ensure that the only firewall rules present are the ones explicitly declared in the recipes.

Example:

  1. Add fw rule to enable port 123
firewall 'ufw' do
  action :enable
end

firewall_rule 'http/https' do
  port        123
  action   :allow
end
  1. Change port number to 1234
firewall 'ufw' do
  action :enable
end

firewall_rule 'http/https' do
  port        1234
  action   :allow
end

Expected behavior: The firewall rule to allow traffic on the port 123 should be removed and a new rule will allow traffic on the port 1234.
Actual behavior: A new rule is added allowing traffic on the port 1234, but the old rule allowing traffic on the port 123 is still active.

Proposed solution:

  1. Add attribute purge: If enabled it will remove the rules not declared with chef. Default disabled
  2. Add attribute ignore: Array of regex to ignore unmanaged rules.
firewall 'ufw' do
  action :enable
  purge :enable
  ignore ['-j fail2ban-ssh' ]
end

Please apologies if there is already a way to accomplish this, I couldn't find it.

firewall_rule does not accept array as argument to port if argument is a node attribute

I'm declaring firewall_rule resources like so, where node['cub_monitoring']['tcp_ports'] and node['cub_monitoring']['udp_ports'] are Arrays:

node['cub_monitoring']['monitoring_hosts'].each do |h|
  firewall_rule "allow #{h} on tcp ports" do
    port node['cub_monitoring']['tcp_ports']
    source h
  end
  firewall_rule "allow #{h} on udp ports" do
    port node['cub_monitoring']['udp_ports']
    source h
  end
end

This results in the following exception at converge time:

================================================================================
Error executing action `restart` on resource 'firewall[default]'
================================================================================

Chef::Exceptions::ImmutableAttributeModification
------------------------------------------------
Node attributes are read-only when you do not specify which precedence level to set. To set an attribute use code like `node.default["key"] = "value"' 

Cookbook Trace:
---------------
/tmp/kitchen/cache/cookbooks/firewall/libraries/helpers.rb:13:in `port_to_s'
/tmp/kitchen/cache/cookbooks/firewall/libraries/helpers_iptables.rb:37:in `build_firewall_rule'/tmp/kitchen/cache/cookbooks/firewall/libraries/provider_firewall_iptables.rb:84:in `block (3 levels) in <class:FirewallIptables>'
/tmp/kitchen/cache/cookbooks/firewall/libraries/provider_firewall_iptables.rb:82:in `each'
/tmp/kitchen/cache/cookbooks/firewall/libraries/provider_firewall_iptables.rb:82:in `block (2 levels) in <class:FirewallIptables>'
/tmp/kitchen/cache/cookbooks/firewall/libraries/provider_firewall_iptables.rb:71:in `each'
/tmp/kitchen/cache/cookbooks/firewall/libraries/provider_firewall_iptables.rb:71:in `block in <class:FirewallIptables>'

Resource Declaration:
---------------------
# In /tmp/kitchen/cache/cookbooks/firewall/recipes/default.rb

 22: firewall 'default' do
 23:   ipv6_enabled node['firewall']['ipv6_enabled']
 24:   action :install
 25: end
 26: 

Compiled Resource:
------------------
# Declared in /tmp/kitchen/cache/cookbooks/firewall/recipes/default.rb:22:in `from_file'

firewall("default") do
  action [:install] 
  updated true
  retries 0
  retry_delay 2
  default_guard_interpreter :default
  declared_type :firewall
  cookbook_name "firewall"
  recipe_name "default"
  ipv6_enabled true
  enabled true
  rules {"iptables"=>{"*filter"=>1, ":INPUT DROP"=>2, ":FORWARD DROP"=>3, ":OUTPUT ACCEPT"=>4, "COMMIT_FILTER"=>100, "-A INPUT -p tcp -m tcp -m multiport --dports 22 -m comment --comment \"allow world to ssh\" -j ACCEPT"=>50, "-A INPUT -m state --state RELATED,ESTABLISHED -m comment --comment \"established\" -j ACCEPT"=>50}, "ip6tables"=>{"*filter"=>1, ":INPUT DROP"=>2, ":FORWARD DROP"=>3, ":OUTPUT ACCEPT"=>4, "COMMIT_FILTER"=>100, "-A INPUT -m state --state RELATED,ESTABLISHED -m comment --comment \"established\" -j ACCEPT"=>50, "-A INPUT -p ipv6-icmp -m comment --comment \"ipv6_icmp\" -j ACCEPT"=>50}}
end

It appears that this error can be reproduced by passing an array stored as a node attribute to the port attribute of the firewall_rule resource. I believe the exception is due to the following code in the port_to_s method defined in libraries/helpers.rb:

      elsif p && p.is_a?(Array)
        p.map! { |o| port_to_s(o) }
        p.sort.join(',')

This code is attempting to perform an in-place modification of the port attribute. This fails if the port attribute is a node attribute.

However, if I declare my firewall rules like this (note the addition of the .dup method to copy the array to a new object)...

node['cub_monitoring']['monitoring_hosts'].each do |h|
  firewall_rule "allow #{h} on tcp ports" do
    port node['cub_monitoring']['tcp_ports'].dup
    source h
  end
  firewall_rule "allow #{h} on udp ports" do
    port node['cub_monitoring']['udp_ports'].dup
    source h
  end
end

...then no exception is thrown.

iptables ipv6 support toggle

If you disable ipv6 support on your node by removing the kernel module (recommended if you're not using ipv6), this coookbook will fail to operate as it blindly executes both iptables and ip6tables without checking to see if ipv6 is enabled.

Example error message from CentOS 6.6...

ip6tables v1.4.7: can't initialize ip6tables table `filter': Address family not supported by protocol.

Cookbook trace...

/var/chef/cache/cookbooks/firewall/libraries/provider_firewall_iptables.rb:71:in `action_flush'

I think it would be great if this cookbook could either detect if ipv6 is enabled or not, or provide an attribute to toggle ipv6 support on or off.

Port ranges don't match due to extra space

A space is added after port ranges in https://github.com/opscode-cookbooks/firewall/blob/7d37d91d48d31906cf0306b2bcabba01d67fda0d/libraries/helpers.rb#L9, which results in firewall rules not matching:

[2015-07-24T16:18:06+00:00] DEBUG: matching: [3 -A INPUT -p tcp -m tcp -m multiport --dports 8000:8003  -m comment --comment "*Allow some ports"* -j ACCEPT] to [3 -A INPUT -p tcp -m tcp -m multiport --dports 8000:8003 -m comment --comment "Allow some ports" -j ACCEPT]

The regex does not match because of an extra space here:

--dports 8000:8003  -m comment
--dports 8000:8003 -m comment

Duplicate firewall rules are added on every Chef run as a result.

Working on a PR for this now.

Redirect firewall_rule misses '--to-ports' on CentOS 7

The following:

firewall_rule "smserver-forward" do
  protocol      :tcp
  direction     :pre
  command       :redirect
  port          443
  redirect_port 8911
end

Produces the following output in /etc/sysconfig/firewalld-chef.rules:

firewall-cmd --direct --add-rule ipv4 filter PREROUTING 50 -t nat -p tcp -m tcp -m multiport --dports 443 -m comment --comment 'smserver-forward' -j REDIRECT 
firewall-cmd --direct --add-rule ipv6 filter PREROUTING 50 -t nat -p tcp -m tcp -m multiport --dports 443 -m comment --comment 'smserver-forward' -j REDIRECT

The --to-ports is missing, one would expect the following:

firewall-cmd --direct --add-rule ipv4 filter PREROUTING 50 -t nat -p tcp -m tcp -m multiport --dports 443 -m comment --comment 'smserver-forward' -j REDIRECT --to-ports 8911
firewall-cmd --direct --add-rule ipv6 filter PREROUTING 50 -t nat -p tcp -m tcp -m multiport --dports 443 -m comment --comment 'smserver-forward' -j REDIRECT --to-ports 8911

Platform details are as follows:

[root@vm-splunk-svr-01 ~]# ohai | grep platform
  "platform": "centos",
  "platform_version": "7.1.1503",
  "platform_family": "rhel",
[root@vm-splunk-svr-01 ~]# cat /etc/redhat-release
CentOS Linux release 7.1.1503 (Core)
[root@vm-splunk-svr-01 ~]# chef-client -version
Chef: 12.4.1

Rewrite iptables provider to move most logic into the firewall provider

It would be nice if the firewall provider could one-shot the firewall configuration, using firewall_rule resources as input data. This would also:

  • remove most logic from the firewall_rule provider for iptables
  • allow for relative positioning of rules
  • allow us to remove rules that should not exist anymore (optionally, so we can still support fail2ban)

We could look into this for ufw and firewalld as well.

Add firewall rules to resource in compile phase?

Hello!

We've been bitten a few times lately by a failing chef run applying the restart action on the firewall resource - which modifies the list of rules to only include the firewall_rule resources that have run so far.

If something early in the run fails, but after the firewall resource init, then a bunch of rules get wiped out!

One thing that occurred to me was that because the firewall_rule providers don't actually do anything - they just append data to a hash and let firewall do the real work - then this could actually be done during the compile phase.

This way whenever the firewall resource updates, all of the expected rules will always be created.

This could be done via the after_created hook perhaps https://github.com/chef/chef/blob/master/lib/chef/resource.rb#L915 - maybe only if the action is set to :compile or something?

multiple ports are never up to date

The current syntax for multiple ports:

firewall_rule 'http/https' do
  protocol :tcp
  ports    [80, 443]
  action   :allow
end

Does not seem to detect properly it is up to date. The rule is triggered on every single run. Splitting the ports into single port rules work OK

Default firewall install with attribute allowing SSH to work fails on CentOS 7

On a clean CentOS 7.1.1503 box with nothing else applied, the firewall log shows that the rule:
allow world to ssh
is applied to the server. However, it appears that the firewall is turned on and SSH is NOT allowed. The only file I see is /etc/sysconfig/firewalld-chef.rules - the main /etc/sysconfig/firewalld has not been modified. The output of:
firewall-cmd --list-all:

drop (default, active)
 interfaces: eno1234567
 sources:
 services:
 ports:
 masquerade: no
 forward-ports:
 icmp-blocks:
 rich-rules:

node attributes for firewall:

firewall
allow_ssh: true
allow_winrm: false
ubuntu_iptables: false
allow_established: true
ipv6_enabled: true
iptables
ufw

enable/disable attribute feature

Hi, I am considering an usage where 'base' cookbook for the nodes may or may not deploy+enable firewall. As it might be different use-case for different environments.

Then any dependant application cookbook will try to set firewall rules (but only if 'iptables' or 'firewall' cookbook were deployed + enabled. In such case I am missing an general attribute that would handle the 'OS Firewall' state (aka a services should start etc).

Step 1:
on 'base' cookbook the 'firewall cookbook' may or may not bee deployed

Step 2:
on application cookbook

if node['firewall']['enabled']
   firewall_rule "http" do
      ...
    end
end

Actually, the nice behaviour would be to skip the "if node['firewall'] ... " line and firewall_rule would run it'saction enable/disable based on the status of the node attribute node['firewall']['enabled'].

That drives the question of best practice. Should the user of this cookbook, introduce attribute such node['firewall']['enabled'] or node['MYORG']['firewall_policy']on it's own in wrapper or no-the-fly and then bind resource attribute parameteraction = node['MYORG']['firewall_policy']` ?

Firewall cookbook cannot be used in LWRPs

The cookbook looks up the firewall in the current run context:

firewall = run_context.resource_collection.find(firewall: new_resource.firewall_name)

However, inside a LWRP, we're not in the same run context as the main recipe, so the firewall resource cannot be found. It also doesn't help defining a new firewall resource in the LWRP, because then we have multiple firewall resources, one per run context, stomping on each others feet.

This really narrows the field of application for this cookbook.

1.6.1 incompatible with poise

When I try to use firewall 1.6.1 cookbook on Chef 11 I get:

[2015-10-28T09:37:44-07:00] ERROR: Halite is not compatible with no_lazy_load false, please set no_lazy_load true in your Chef configuration file.

But in poise/poise#12 (comment) @coderanger says that poise is not compatible with Chef 11.

How does this all square? Surely this combination worked at some point.

firewall_rule actions in Readme examples

In https://github.com/chef-cookbooks/firewall#examples-1 there is still :allow used as the action but the provider changed to :create

e.g.

# open multiple ports for http/https, note that the protocol
# attribute is required when using ports
firewall_rule 'http/https' do
  protocol :tcp
  port     [80, 443]
  action   :allow
end

should probably be

# open multiple ports for http/https, note that the protocol
# attribute is required when using ports
firewall_rule 'http/https' do
  protocol :tcp
  port     [80, 443]
  command :allow
  action   :create
end

Unable to rate limit with ufw

The cookbook doesn’t support the limit command, so that you can’t rate limit connections, e. g. a simple ufw limit 22/tcp won’t work. The raw parameter is only used for other firewalls.

The firewall cookbook should support this kind of rule.

Windows firewall port range

Seems like the method port_to_s causes the netsh advfirewall firewall command to be incorrectly formatted.

Example:
netsh advfirewall firewall add rule name="The Traffic" description="The Traffic" dir=in service=any protocol=tcp localip=any localport=1000:1500 interfacetype=any remoteip=any remoteport=any action=allow

when it should be

netsh advfirewall firewall add rule name="The Traffic" description="The Traffic" dir=in service=any protocol=tcp localip=any localport=1000-1500 interfacetype=any remoteip=any remoteport=any action=allow

notice the dash between the port range first port and last port instead of the colon. This colon causes this error
STDOUT: A specified port value is not valid.

I would do a Pull-Request, but I'm not sure exactly how to change the code. We could add an if windows check in the port_to_s method, or is there a way to say if using windows firewall, or maybe a way to override the method...?

Test iptables on Ubuntu

In case someone is using iptables on Ubuntu, we should at least test that it works as part of our kitchen tests.

please release version on the supermarket

Hello,

One last request ;-)

Would you be so kind as to release the latest version on the supermarket? then our chef guard will allow me to use it.

Thanks,
Ronald

Chef::Provider::FirewallRuleIptables does not work as advertised in README for allowing specific protocols

The README shows the ability to specify a raw protocol when using UFW via a specified provider as excepted here:

# use the iptables provider to specify protocol number on debian/ubuntu
firewall_rule 'vrrp' do
  provider    Chef::Provider::FirewallRuleIptables
  protocol    112
  command      :allow
end

This does not work and throws a compile-time error saying that only :tcp, :udp, :icmp or :none are valid protocol options.

I've had to drop down to using the 'execute' resource to specify iptables commands to allow VRRP (protocol 112) multicast. If this functionality could exist, I would be very happy.

Re-factor to allow chef actions different than firewall actions

INPUT, DROP, etc are firewall chains, while :append, :delete, etc are chef actions. Should we make the firewall chains be an attribute instead of a chef action? And then the chef action could support things like :delete from a chain?

Alternately, if we convert this to make the firewall provider do the work, we could just make it idempotent, write out the entire state, and then there'd be no need to :delete rules.

ipv6 disable issues

I'm working on CentOS 6.6 with iptables and ipv6 disabled (kernel module not loaded) and have encountered two issues.

First, the new "ipv6_enabled" parameter to the firewall resource precludes including the default recipe, if you need to set it to false. This is due to the firewall resource being called with the install action in default.rb. Maybe this could be a feature request to have an attribute to turn on/off ipv6 support rather then having to include it as a parameter to the firewall resource.

Second, I'm getting undefined method `key?' for nil:NilClass with the example below. This only occurs when disabling ipv6 via the firewall resource.

My wrapper...

firewall 'default' do
  action :install
  ipv6_enabled false
end

firewall_rule 'allow world to ssh' do
  port 22
  source '0.0.0.0/0'
end

# allow established connections
firewall_rule 'established' do
  stateful [:related, :established]
  protocol :none # explicitly don't specify protocol
  command :allow
end
[snip]

Log output...

[snip]
Compiling Cookbooks...
       Converging 8 resources
       Recipe: efx_firewall::default

           - install iptables and enable/start services
        (up to date)
         * file[create empty /etc/sysconfig/iptables] action create (skipped due to not_if)
        (up to date)
        (up to date)
         * firewall_rule[allow world to ssh] action create

         * firewall_rule[established] action create

           ================================================================================
           Error executing action `create` on resource 'firewall_rule[established]'
           ================================================================================

           NoMethodError
           -------------
           undefined method `key?' for nil:NilClass

           Cookbook Trace:
           ---------------
           /tmp/kitchen/cache/cookbooks/firewall/libraries/provider_firewall_rule_iptables.rb:51:in `block (2 levels) in <class:FirewallRuleIptables>'
           /tmp/kitchen/cache/cookbooks/firewall/libraries/provider_firewall_rule_iptables.rb:45:in `each'
           /tmp/kitchen/cache/cookbooks/firewall/libraries/provider_firewall_rule_iptables.rb:45:in `block in <class:FirewallRuleIptables>'

           Resource Declaration:
           ---------------------
           # In /tmp/kitchen/cache/cookbooks/efx_firewall/recipes/default.rb

            22: firewall_rule 'established' do
            23:   stateful [:related, :established]
            24:   protocol :none # explicitly don't specify protocol
            25:   command :allow
            26: end
            27:
            28: # Allow all loopback traffic
            29: firewall_rule 'loopback' do
            30:     interface 'lo'
            31:     command :allow
            32: end
            33:
            34: execute 'dummy-delay-iptables-save' do
            35:     command '/bin/true'
            36:     notifies :run, 'execute[iptables-save]', :delayed
            37: end
            38:
            39: execute 'iptables-save' do
            40:   command 'service iptables save'
            41:   action :nothing
            42: end

           Compiled Resource:
           ------------------
           # Declared in /tmp/kitchen/cache/cookbooks/efx_firewall/recipes/default.rb:22:in `from_file'

           firewall_rule("established") do
             action [:create]
             updated true
             updated_by_last_action true
             retries 0
             retry_delay 2
             default_guard_interpreter :default
             declared_type :firewall_rule
             cookbook_name "efx_firewall"
             recipe_name "default"
             stateful [:related, :established]
             protocol :none
             command :allow
             firewall_name "default"
             direction :in
             description "established"
             position 50
           end


           * file[/etc/sysconfig/iptables] action create (up to date)
            (up to date)

       Running handlers:
       [2015-09-11T14:54:40+00:00] ERROR: Running exception handlers
       Running handlers complete
       [2015-09-11T14:54:40+00:00] ERROR: Exception handlers complete
       Chef Client failed. 2 resources updated in 4.527059018 seconds
       [2015-09-11T14:54:40+00:00] FATAL: Stacktrace dumped to /tmp/kitchen/cache/chef-stacktrace.out
       [2015-09-11T14:54:40+00:00] ERROR: firewall_rule[established] (efx_firewall::default line 22) had an error: NoMethodError: undefined method `key?' for nil:NilClass
       [2015-09-11T14:54:40+00:00] FATAL: Chef::Exceptions::ChildConvergeError: Chef run process exited unsuccessfully (exit code 1)

Firewalld ipv6 support

Currently, the firewalld contribution contains some commands that hardcode ipv4 in their arguments. It would be nice to support and test against ipv6 on firewalld.

Clarify filtering functionality

We should do a pass through this cookbook focused on unifying behavior.

For iptables, I'd like to only support *filter and expose anything beyond that table via raw rules and allowing users to specify a default set of rules for other tables and chains.

If possible, I'd like to do the same with ufw, firewalld, and the Windows firewall -- focus on the common case of filtering packets, and give folks raw rules to go outside those bounds. It's becoming overly complicated to support every feature in every firewall technology, while still maintaining the semantics of the firewall and firewall_rule resources.

Support chains other than *filter in iptables

For comprehensive iptables support, in addition to the filter chain, also support raw, nat, and mangle.

There is an attempt in helpers_iptables.rb (#L24) to support NAT, but this isn't actually compatible with iptables-restore. This change is going to require a bit of restructuring.

direction :pre does not work on CentOS6 with iptables.

I define a resource to redirect 80 to 8080 like so:

# redirect 80 -> 8080
firewall_rule 'http-reditect' do 
   direction        :pre
   protocol         :tcp
   command          :redirect
   port             80
   redirect_port    8080
end

This works fine on CentOS7 using firewalld, however testing on 6, it fails to converge, erroring out with


           Mixlib::ShellOut::ShellCommandFailed
           ------------------------------------
           Expected process to exit with [0], but received '1'
           ---- Begin output of /sbin/service iptables start ----
           STDOUT: iptables: Applying firewall rules: [FAILED]
           STDERR: iptables-restore v1.4.7: Line 12 seems to have a -t table option.

           Error occurred at line: 12
           Try `iptables-restore -h' or 'iptables-restore --help' for more information.
           ---- End output of /sbin/service iptables start ----
           Ran /sbin/service iptables start returned 1

And the generated file causing the error

[root@default-centos-67 vagrant]# cat /etc/sysconfig/iptables
# position 1
*filter
-A INPUT -p tcp -m tcp -m multiport --dports 80 -m comment --comment "http" -j ACCEPT
-A INPUT -p tcp -m tcp -m multiport --dports 8080 -m comment --comment "http-alt" -j ACCEPT
# position 2
:INPUT DROP
# position 3
:FORWARD DROP
# position 4
:OUTPUT ACCEPT
# position 50
-A PREROUTING -t nat -p tcp -m tcp -m multiport --dports 80 -m comment --comment "http-reditect" -j REDIRECT
-A INPUT -p tcp -m tcp -m multiport --dports 22 -m comment --comment "ssh" -j ACCEPT
# position 100
COMMIT

It's my understanding that this is complaining because the -t nat is in contradiction to the *filter and should be in a separate section. Furthermore there is no --to-port 8080 on that line, so moving it to

*nat
-A PREROUTING -t nat -p tcp -m tcp -m multiport --dports 80 -m comment --comment "http-reditect" -j REDIRECT

while it does not error out it does not successfully redirect the port.

I believe I am using firewall-2.2.0 ,
Chef Development Kit Version: 0.9.0
chef-client version: 12.5.1
berks version: 4.0.1
kitchen version: 1.4.2

and am testing this with test-kitchen using vagrant.

Build broken on chefspec with chef-sugar

Looks like chef-sugar got removed from the Gemfile in 6c87861.

LoadError
---------
cannot load such file -- chef/sugar
Cookbook Trace:
---------------
  /tmp/d20150909-2457-1ro2ple/cookbooks/chef-sugar/recipes/default.rb:34:in `require'
  /tmp/d20150909-2457-1ro2ple/cookbooks/chef-sugar/recipes/default.rb:34:in `from_file'
  /tmp/d20150909-2457-1ro2ple/cookbooks/firewall/recipes/default.rb:20:in `from_file'

/cc @tas50

Chooses wrong firewall package

OS: CentOS 6.6.

Just pulled in the new version of firewall and am seeing the following...

I think iptables should be the default choice for this OS and version, eh?

Compiling Cookbooks...
       [2015-09-10T17:17:32+00:00] WARN: You declared a new resource Chef::Provider::FirewallIptables for resource firewall, but it comes alphabetically after Chef::Provider::FirewallFirewalld and has the same filters ({:platform_family=>["rhel", "fedora"], :os=>"linux"}), so it will not be used. Use override: true if you want to use it for firewall.
       [2015-09-10T17:17:32+00:00] WARN: You declared a new resource Chef::Provider::FirewallRuleIptables for resource firewall_rule, but it comes alphabetically after Chef::Provider::FirewallRuleFirewalld and has the same filters ({:platform_family=>["rhel", "fedora"], :os=>"linux"}), so it will not be used. Use override: true if you want to use it for firewall_rule.
       [2015-09-10T17:17:32+00:00] WARN: You declared a new resource Chef::Provider::FirewallRuleUfw for resource firewall_rule, but it comes alphabetically after Chef::Provider::FirewallRuleIptablesUbuntu and has the same filters ({:platform_family=>["debian"], :os=>"linux"}), so it will not be used. Use override: true if you want to use it for firewall_rule.
       [2015-09-10T17:17:32+00:00] WARN: You declared a new resource Chef::Provider::FirewallUfw for resource firewall, but it comes alphabetically after Chef::Provider::FirewallIptablesUbuntu and has the same filters ({:platform_family=>["debian"], :os=>"linux"}), so it will not be used. Use override: true if you want to use it for firewall.
       Recipe: chef-sugar::default
        (up to date)
         Converging 11 resources
         * chef_gem[chef-sugar] action install (up to date)
       Recipe: firewall::default


         * yum_package[firewalld] action install
           * No candidate version available for firewalld
           ================================================================================
           Error executing action `install` on resource 'yum_package[firewalld]'
           ================================================================================

           Chef::Exceptions::Package
           -------------------------
           No candidate version available for firewalld

           Resource Declaration:
           ---------------------
           # In /tmp/kitchen/cache/cookbooks/firewall/libraries/provider_firewall_firewalld.rb

            32:         package 'firewalld' do
            33:           action :install
            34:         end
            35:

iptables nat rule prevents iptables-restore from working

I'm running on Ubuntu 14.04. I've got my attributes/recipe set up like this:

default['firewall']['ubuntu_iptables'] = true
default['firewall']['iptables']['defaults']['policy']['input'] = 'ACCEPT'

firewall 'default'

firewall_rule 'nat rule' do
    command :masquerade
    dest_interface 'eth0'
    direction :post
    protocol :none
    source '10.10.0.0/24'
end

Unfortunately this doesn't work. I get this in the Chef run:

* service[iptables-persistent] action restart

  ================================================================================
  Error executing action `restart` on resource 'service[iptables-persistent]'
  ================================================================================

  Mixlib::ShellOut::ShellCommandFailed
  ------------------------------------
  Expected process to exit with [0], but received '1'
  ---- Begin output of /etc/init.d/iptables-persistent start ----
  STDOUT: * Loading iptables rules...
   *  IPv4...
   *  IPv6...
     ...fail!
  STDERR:
  ---- End output of /etc/init.d/iptables-persistent start ----
  Ran /etc/init.d/iptables-persistent start returned 1

  Resource Declaration:
  ---------------------
  # In /var/chef/cache/cookbooks/firewall/libraries/provider_firewall_iptables_ubuntu.rb

  113:         service_affected = service 'iptables-persistent' do
  114:           action :nothing
  115:         end
  116:

  Compiled Resource:
  ------------------
  # Declared in /var/chef/cache/cookbooks/firewall/libraries/provider_firewall_iptables_ubuntu.rb:113:in `block (2 levels) in <css:FirewallIptablesUbuntu>'

  service("iptables-persistent") do
    action [:nothing]
    updated true
    supports {:restart=>nil, :reload=>nil, :status=>nil}
    retries 0
    retry_delay 2
    default_guard_interpreter :default
    service_name "iptables-persistent"
    enabled true
    running true
    pattern "iptables-persistent"
    declared_type :service
    cookbook_name "xxx"
  end

In trying to debug this, I tried running iptables-restore on /etc/iptables/rules.v4 and got this:

root@ec2-instance:~# iptables-restore < /etc/iptables/rules.v4
iptables-restore v1.4.21: The -t option (seen in line 10) cannot be used in iptables-restore.

Error occurred at line: 10
Try `iptables-restore -h' or 'iptables-restore --help' for more information.

It seems we can't put rules with -t nat in there.

Test-kitchen suite references unknown cookbook

Hello! It seems .kitchen.ymn references a firewall-test cookbook:

suites:
- name: default
  run_list:
  - recipe[firewall::default]
  - recipe[firewall-test::default]

Is that the same as the cookbook named fake in the test fixtures? Or is that some cookbook from elsewhere? I don't see an entry in Berksfile for it, so I'm assuming firewall-test should really be fake?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.