PageRenderTime 53ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/rex/socket/range_walker.rb

https://bitbucket.org/technopunk2099/metasploit-framework
Ruby | 393 lines | 232 code | 46 blank | 115 comment | 50 complexity | 6a5766363be395335e4eddac7be8482c MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0, LGPL-2.1, GPL-2.0, MIT
  1. # -*- coding: binary -*-
  2. require 'rex/socket'
  3. module Rex
  4. module Socket
  5. ###
  6. #
  7. # This class provides an interface to enumerating an IP range
  8. #
  9. # This class uses start,stop pairs to represent ranges of addresses. This
  10. # is very efficient for large numbers of consecutive addresses, and not
  11. # show-stoppingly inefficient when storing a bunch of non-consecutive
  12. # addresses, which should be a somewhat unusual case.
  13. #
  14. ###
  15. class RangeWalker
  16. #
  17. # Initializes a walker instance using the supplied range
  18. #
  19. def initialize(parseme)
  20. if parseme.is_a? RangeWalker
  21. @ranges = parseme.ranges.dup
  22. else
  23. @ranges = parse(parseme)
  24. end
  25. reset
  26. end
  27. #
  28. # Calls the instance method
  29. #
  30. # This is basically only useful for determining if a range can be parsed
  31. #
  32. def self.parse(parseme)
  33. self.new.parse(parseme)
  34. end
  35. #
  36. # Turn a human-readable range string into ranges we can step through one address at a time.
  37. #
  38. # Allow the following formats:
  39. # "a.b.c.d e.f.g.h"
  40. # "a.b.c.d, e.f.g.h"
  41. # where each chunk is CIDR notation, (e.g. '10.1.1.0/24') or a range in nmap format (see expand_nmap)
  42. #
  43. # OR this format
  44. # "a.b.c.d-e.f.g.h"
  45. # where a.b.c.d and e.f.g.h are single IPs and the second must be
  46. # bigger than the first.
  47. #
  48. def parse(parseme)
  49. return nil if not parseme
  50. ranges = []
  51. parseme.split(', ').map{ |a| a.split(' ') }.flatten.each { |arg|
  52. opts = {}
  53. # Handle IPv6 first (support ranges, but not CIDR)
  54. if arg.include?(":")
  55. addrs = arg.split('-', 2)
  56. # Handle a single address
  57. if addrs.length == 1
  58. addr, scope_id = addrs[0].split('%')
  59. opts[:scope_id] = scope_id if scope_id
  60. return false unless Rex::Socket.is_ipv6?(addr)
  61. addr = Rex::Socket.addr_atoi(addr)
  62. ranges.push [addr, addr, true, opts]
  63. next
  64. end
  65. addr1, scope_id = addrs[0].split('%')
  66. opts[:scope_id] = scope_id if scope_id
  67. addr2, scope_id = addrs[0].split('%')
  68. ( opts[:scope_id] ||= scope_id ) if scope_id
  69. return false if not (Rex::Socket.is_ipv6?(addr1) and Rex::Socket.is_ipv6?(addr2))
  70. # Handle IPv6 ranges in the form of 2001::1-2001::10
  71. addr1 = Rex::Socket.addr_atoi(addr1)
  72. addr2 = Rex::Socket.addr_atoi(addr2)
  73. ranges.push [addr1, addr2, true, opts]
  74. next
  75. # Handle IPv4 CIDR
  76. elsif arg.include?("/")
  77. # Then it's CIDR notation and needs special case
  78. return false if arg =~ /[,-]/ # Improper CIDR notation (can't mix with 1,3 or 1-3 style IP ranges)
  79. return false if arg.scan("/").size > 1 # ..but there are too many slashes
  80. ip_part,mask_part = arg.split("/")
  81. return false if ip_part.nil? or ip_part.empty? or mask_part.nil? or mask_part.empty?
  82. return false if mask_part !~ /^[0-9]{1,2}$/ # Illegal mask -- numerals only
  83. return false if mask_part.to_i > 32 # This too -- between 0 and 32.
  84. begin
  85. Rex::Socket.addr_atoi(ip_part) # This allows for "www.metasploit.com/24" which is fun.
  86. rescue Resolv::ResolvError
  87. return false # Can't resolve the ip_part, so bail.
  88. end
  89. expanded = expand_cidr(arg)
  90. if expanded
  91. ranges.push(expanded)
  92. else
  93. return false
  94. end
  95. # Handle hostnames
  96. elsif arg =~ /[^-0-9,.*]/
  97. # Then it's a domain name and we should send it on to addr_atoi
  98. # unmolested to force a DNS lookup.
  99. Rex::Socket.addr_atoi_list(arg).each { |addr| ranges.push [addr, addr, false, opts] }
  100. # Handle IPv4 ranges
  101. elsif arg =~ /^([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})-([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})$/
  102. # Then it's in the format of 1.2.3.4-5.6.7.8
  103. # Note, this will /not/ deal with DNS names, or the fancy/obscure 10...1-10...2
  104. begin
  105. addrs = [Rex::Socket.addr_atoi($1), Rex::Socket.addr_atoi($2)]
  106. return false if addrs[0] > addrs[1] # The end is greater than the beginning.
  107. ranges.push [addrs[0], addrs[1], false, opts]
  108. rescue Resolv::ResolvError # Something's broken, forget it.
  109. return false
  110. end
  111. else
  112. # Returns an array of ranges
  113. expanded = expand_nmap(arg)
  114. if expanded
  115. expanded.each { |r| ranges.push(r) }
  116. end
  117. end
  118. }
  119. # Remove any duplicate ranges
  120. ranges = ranges.uniq
  121. return ranges
  122. end
  123. #
  124. # Resets the subnet walker back to its original state.
  125. #
  126. def reset
  127. return false if not valid?
  128. @curr_range = 0
  129. @curr_addr = @ranges[0][0]
  130. @length = 0
  131. @ranges.each { |r| @length += r[1] - r[0] + 1 }
  132. end
  133. #
  134. # Returns the next IP address.
  135. #
  136. def next_ip
  137. return false if not valid?
  138. if (@curr_addr > @ranges[@curr_range][1])
  139. if (@curr_range >= @ranges.length - 1)
  140. return nil
  141. end
  142. @curr_range += 1
  143. @curr_addr = @ranges[@curr_range][0]
  144. end
  145. addr = Rex::Socket.addr_itoa(@curr_addr, @ranges[@curr_range][2])
  146. if @ranges[@curr_range][3][:scope_id]
  147. addr = addr + '%' + @ranges[@curr_range][3][:scope_id]
  148. end
  149. @curr_addr += 1
  150. return addr
  151. end
  152. def valid?
  153. (@ranges and not @ranges.empty?)
  154. end
  155. #
  156. # Returns true if the argument is an ip address that falls within any of
  157. # the stored ranges.
  158. #
  159. def include?(addr)
  160. return false if not @ranges
  161. if (addr.is_a? String)
  162. addr = Rex::Socket.addr_atoi(addr)
  163. end
  164. @ranges.map { |r|
  165. if r[0] <= addr and addr <= r[1]
  166. return true
  167. end
  168. }
  169. return false
  170. end
  171. #
  172. # Returns true if this RangeWalker includes all of the addresses in the
  173. # given RangeWalker
  174. #
  175. def include_range?(range_walker)
  176. return false if ((not @ranges) or @ranges.empty?)
  177. return false if not range_walker.ranges
  178. range_walker.ranges.all? do |start, stop|
  179. ranges.any? do |self_start, self_stop|
  180. r = (self_start..self_stop)
  181. r.include?(start) and r.include?(stop)
  182. end
  183. end
  184. end
  185. #
  186. # Calls the given block with each address. This is basically a wrapper for
  187. # #next_ip
  188. #
  189. def each(&block)
  190. while (ip = next_ip)
  191. block.call(ip)
  192. end
  193. end
  194. #
  195. # Returns an array with one element, a Range defined by the given CIDR
  196. # block.
  197. #
  198. def expand_cidr(arg)
  199. start,stop = Rex::Socket.cidr_crack(arg)
  200. if !start or !stop
  201. return false
  202. end
  203. range = Range.new
  204. range.start = Rex::Socket.addr_atoi(start)
  205. range.stop = Rex::Socket.addr_atoi(stop)
  206. range.ipv6 = (arg.include?(":"))
  207. range.options = {}
  208. return range
  209. end
  210. #
  211. # Expands an nmap-style host range x.x.x.x where x can be simply "*" which
  212. # means 0-255 or any combination and repitition of:
  213. # i,n
  214. # n-m
  215. # i,n-m
  216. # n-m,i
  217. # ensuring that n is never greater than m.
  218. #
  219. # non-unique elements will be removed
  220. # e.g.:
  221. # 10.1.1.1-3,2-2,2 => ["10.1.1.1", "10.1.1.2", "10.1.1.3"]
  222. # 10.1.1.1-3,7 => ["10.1.1.1", "10.1.1.2", "10.1.1.3", "10.1.1.7"]
  223. #
  224. # Returns an array of Ranges
  225. #
  226. def expand_nmap(arg)
  227. # Can't really do anything with IPv6
  228. return false if arg.include?(":")
  229. # nmap calls these errors, but it's hard to catch them with our
  230. # splitting below, so short-cut them here
  231. return false if arg.include?(",-") or arg.include?("-,")
  232. bytes = []
  233. sections = arg.split('.')
  234. if sections.length != 4
  235. # Too many or not enough dots
  236. return false
  237. end
  238. sections.each { |section|
  239. if section.empty?
  240. # pretty sure this is an unintentional artifact of the C
  241. # functions that turn strings into ints, but it sort of makes
  242. # sense, so why not
  243. # "10...1" => "10.0.0.1"
  244. section = "0"
  245. end
  246. if section == "*"
  247. # I think this ought to be 1-254, but this is how nmap does it.
  248. section = "0-255"
  249. elsif section.include?("*")
  250. return false
  251. end
  252. # Break down the sections into ranges like so
  253. # "1-3,5-7" => ["1-3", "5-7"]
  254. ranges = section.split(',', -1)
  255. sets = []
  256. ranges.each { |r|
  257. bounds = []
  258. if r.include?('-')
  259. # Then it's an actual range, break it down into start,stop
  260. # pairs:
  261. # "1-3" => [ 1, 3 ]
  262. # if the lower bound is empty, start at 0
  263. # if the upper bound is empty, stop at 255
  264. #
  265. bounds = r.split('-', -1)
  266. return false if (bounds.length > 2)
  267. bounds[0] = 0 if bounds[0].nil? or bounds[0].empty?
  268. bounds[1] = 255 if bounds[1].nil? or bounds[1].empty?
  269. bounds.map!{|b| b.to_i}
  270. return false if bounds[0] > bounds[1]
  271. else
  272. # Then it's a single value
  273. bounds[0] = r.to_i
  274. end
  275. return false if bounds[0] > 255 or (bounds[1] and bounds[1] > 255)
  276. return false if bounds[1] and bounds[0] > bounds[1]
  277. if bounds[1]
  278. bounds[0].upto(bounds[1]) do |i|
  279. sets.push(i)
  280. end
  281. elsif bounds[0]
  282. sets.push(bounds[0])
  283. end
  284. }
  285. bytes.push(sets.sort.uniq)
  286. }
  287. #
  288. # Combinitorically squish all of the quads together into a big list of
  289. # ip addresses, stored as ints
  290. #
  291. # e.g.:
  292. # [[1],[1],[1,2],[1,2]]
  293. # =>
  294. # [atoi("1.1.1.1"),atoi("1.1.1.2"),atoi("1.1.2.1"),atoi("1.1.2.2")]
  295. addrs = []
  296. for a in bytes[0]
  297. for b in bytes[1]
  298. for c in bytes[2]
  299. for d in bytes[3]
  300. ip = (a << 24) + (b << 16) + (c << 8) + d
  301. addrs.push ip
  302. end
  303. end
  304. end
  305. end
  306. addrs.sort!
  307. addrs.uniq!
  308. rng = Range.new
  309. rng.ipv6 = false
  310. rng.options = {}
  311. rng.start = addrs[0]
  312. ranges = []
  313. 1.upto(addrs.length - 1) do |idx|
  314. if addrs[idx - 1] + 1 == addrs[idx]
  315. # Then this address is contained in the current range
  316. next
  317. else
  318. # Then this address is the upper bound for the current range
  319. rng.stop = addrs[idx - 1]
  320. ranges.push(rng.dup)
  321. rng.start = addrs[idx]
  322. end
  323. end
  324. rng.stop = addrs[addrs.length - 1]
  325. ranges.push(rng.dup)
  326. return ranges
  327. end
  328. #
  329. # The total number of IPs within the range
  330. #
  331. attr_reader :length
  332. # for backwards compatibility
  333. alias :num_ips :length
  334. attr_reader :ranges
  335. end
  336. class Range < Array # :nodoc: all
  337. def start; self[0]; end
  338. def stop; self[1]; end
  339. def ipv6; self[2]; end
  340. def options; self[3]; end
  341. def start=(val); self[0] = val; end
  342. def stop=(val); self[1] = val; end
  343. def ipv6=(val); self[2] = val; end
  344. def options=(val); self[3] = val; end
  345. end
  346. end
  347. end