25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
|
# File 'lib/dcmgr/models/security_group_rule.rb', line 25
def self.parse_rule(rule)
rule = rule.strip.gsub(/[\s\t]+/, '')
from_group = false
from_pair, ip_tport, source_pair = rule.split(',')
next if from_pair.nil?
next if ip_tport.nil?
next if source_pair.nil?
ip_protocol, ip_fport = from_pair.split(':')
protocol, ip_source = source_pair.split(':')
s = StringScanner.new(protocol)
until s.eos?
case
when s.scan(/ip6/)
next
when s.scan(/ip4/)
ip_addr, prefix = ip_source.split('/', 2)
if prefix.to_i == 0
ip_source = ip_addr
end
when s.scan(/sg-\w+/)
from_group = true
else
raise "Unexpected protocol '#{s.peep(20)}'"
end
end
if from_group == false
ip = IPAddress(ip_source)
ip_source = case ip.u32
when 0
"#{ip.address}/0"
else
"#{ip.address}/#{ip.prefix}"
end
else
ip_source = protocol
protocol = nil
end
case ip_protocol
when 'tcp', 'udp'
ip_fport = ip_fport.to_i
ip_tport = ip_tport.to_i
[ ip_fport, ip_tport ].each do |port|
raise "Out of range port number: #{port}" unless port >= 1 && port <= 65535
end
if !(ip_fport <= ip_tport)
raise "Invalid IP port range: #{ip_fport} <= #{ip_tport}"
end
{
:ip_protocol => ip_protocol,
:ip_fport => ip_fport,
:ip_tport => ip_tport,
:protocol => protocol,
:ip_source => ip_source,
}
when 'icmp'
icmp_type = ip_fport.to_i
icmp_code = ip_tport.to_i
case icmp_type
when -1
when 0, 3, 5, 8, 11, 12, 13, 14, 15, 16, 17, 18
else
raise "Unsupported ICMP type number: #{icmp_type}"
end
case icmp_code
when -1
when 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
next if icmp_type == -1
else
raise "Unsupported ICMP code number: #{icmp_code}"
end
{
:ip_protocol => ip_protocol,
:icmp_type => ip_tport.to_i, :icmp_code => ip_fport.to_i, :protocol => protocol,
:ip_source => ip_source,
}
end
end
|