PageRenderTime 47ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/rex/socket/range_walker.rb

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