Commit 45af744d22cf3eb661a7644b75f505989b25109d

  • Tree SHA1: 6b02f0e
  • Parent SHA1: c2458d2 (Add method to grammar to return a hash of the parsed data. Add tests to make sure we're interpreting things correctly.)
  • raw diff | raw patch
Added "all" protocol to the grammar, reworked some of the tests and started adding tests for converting ript rules to actual iptables rules.
  
4343 end
4444
4545 rule proto
46 ( "tcp" / "udp" / "icmp" ) s?
46 ( "tcp" / "udp" / "icmp" / "all" ) s?
4747 end
4848
4949 rule state
ript.rb
(41 / 0)
  
1require 'treetop'
2
3module IPTables
4 class Ript
5 def initialize
6 Treetop.load "iptables"
7 @parser = IPTablesParser.new
8 end
9
10 def parse(str)
11 @parser.parse(str).eval
12 end
13
14 def convert(str)
15 data = self.parse str
16
17 string = String.new
18 string << "iptables" << " "
19
20 string << "-A "
21 string << data['target'].upcase << " "
22
23 action_map = {
24 'allow' => 'ACCEPT',
25 'deny' => 'DROP',
26 'reject' => 'REJECT',
27 'log' => 'LOG',
28 }
29
30 action = action_map[ data['action'] ]
31
32 string << "-j " << action << " "
33
34 string << "-s " << data['src_ip'] << " "
35
36 string << "-d " << data['dst_ip']
37
38 string
39 end
40 end
41end
test.rb
(23 / 6)
  
11require 'test/unit'
22require 'treetop'
3Treetop.load "iptables"
3require 'ript'
44
55class IPTablesParserTest < Test::Unit::TestCase
66 def setup
7 @parser = IPTablesParser.new
7 @ript = IPTables::Ript.new
88
99 @test_data = Hash.new
1010
2727 end
2828
2929 def test_parses_okay
30 assert_not_nil @parser.parse "forward allow 10.0.0.0/8 to 192.168.0.1:8080 udp tcp state"
31 assert_not_nil @parser.parse "forward log 10.0.0.0:8 to 192.168.0.1/32 udp icmp tcp"
32 assert_not_nil @parser.parse "forward log 10.0.0.0:8 to 192.168.0.1 tcp state"
30 assert_not_nil @ript.parse "forward allow 10.0.0.0/8 to 192.168.0.1:8080 udp tcp state"
31 assert_not_nil @ript.parse "forward log 10.0.0.0:8 to 192.168.0.1/32 udp icmp tcp"
32 assert_not_nil @ript.parse "forward log 10.0.0.0:8 to 192.168.0.1 tcp state"
33 assert_not_nil @ript.parse "forward deny 10.0.0.0 to 192.168.0.1 all"
34 assert_not_nil @ript.parse "forward allow 10.0.0.0 to 192.168.0.1 all"
3335 end
3436
3537 def test_results
3638 @test_data.each_key do |t|
37 assert_equal @test_data[t], @parser.parse(t).eval
39 assert_equal @test_data[t], @ript.parse(t)
3840 end
41 end
42
43 def test_convert
44 assert_equal "iptables -A FORWARD -j ACCEPT -s 10.0.0.0 -d 192.168.0.1",
45 @ript.convert("forward allow 10.0.0.0 to 192.168.0.1 all")
46
47 assert_equal "iptables -A FORWARD -j DROP -s 10.0.0.0 -d 192.168.0.1",
48 @ript.convert("forward deny 10.0.0.0 to 192.168.0.1 all")
49
50 assert_equal "iptables -A FORWARD -j REJECT -s 10.0.0.0 -d 192.168.0.1",
51 @ript.convert("forward reject 10.0.0.0 to 192.168.0.1 all")
52
53 assert_equal "iptables -A FORWARD -j LOG -s 10.0.0.0 -d 192.168.0.1",
54 @ript.convert("forward log 10.0.0.0 to 192.168.0.1 all")
55
3956 end
4057end