Class: Rex::Socket::RangeWalker

Inherits:
Object
  • Object
show all
Defined in:
lib/rex/socket/range_walker.rb

Overview

This class provides an interface to enumerating an IP range

This class uses start,stop pairs to represent ranges of addresses. This is very efficient for large numbers of consecutive addresses, and not show-stoppingly inefficient when storing a bunch of non-consecutive addresses, which should be a somewhat unusual case.

Examples:

r = RangeWalker.new("10.1,3.1-7.1-255")
r.include?("10.3.7.255") #=> true
r.length #=> 3570
r.each do |addr|
  # do something with the address
end

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parseme) ⇒ RangeWalker

Initializes a walker instance using the supplied range

Parameters:



44
45
46
47
48
49
50
51
# File 'lib/rex/socket/range_walker.rb', line 44

def initialize(parseme)
  if parseme.is_a? RangeWalker
    @ranges = parseme.ranges.dup
  else
    @ranges = parse(parseme)
  end
  reset
end

Instance Attribute Details

#lengthFixnum (readonly) Also known as: num_ips

The total number of IPs within the range

Returns:

  • (Fixnum)


32
33
34
# File 'lib/rex/socket/range_walker.rb', line 32

def length
  @length
end

#rangesArray (readonly)

A list of the ranges held in this RangeWalker

Returns:

  • (Array)


39
40
41
# File 'lib/rex/socket/range_walker.rb', line 39

def ranges
  @ranges
end

Class Method Details

.parse(parseme) ⇒ self, false

Calls the instance method

This is basically only useful for determining if a range can be parsed

Returns:

  • (self)
  • (false)

    if parseme cannot be parsed



59
60
61
# File 'lib/rex/socket/range_walker.rb', line 59

def self.parse(parseme)
  self.new.parse(parseme)
end

Instance Method Details

#each_host(&block) ⇒ Object



232
233
234
235
236
237
238
239
# File 'lib/rex/socket/range_walker.rb', line 232

def each_host(&block)
  while (host_hash = next_host)
    block.call(host_hash)
  end
  reset

  self
end

#each_ip(&block) ⇒ self Also known as: each

Calls the given block with each address. This is basically a wrapper for #next_ip

Returns:

  • (self)


221
222
223
224
225
226
227
228
# File 'lib/rex/socket/range_walker.rb', line 221

def each_ip(&block)
  while (ip = next_ip)
    block.call(ip)
  end
  reset

  self
end

#expand_cidr(arg) ⇒ Range, false

Returns an Array with one element, a Rex::Socket::Range defined by the given CIDR block.

Parameters:

  • arg (String)

    A CIDR range

Returns:

  • (Range)
  • (false)

    if arg is not valid CIDR notation

See Also:



249
250
251
252
253
254
255
256
257
258
259
260
# File 'lib/rex/socket/range_walker.rb', line 249

def expand_cidr(arg)
  start,stop = Rex::Socket.cidr_crack(arg)
  if !start or !stop
    return
  end
  range = Range.new
  range.start = Rex::Socket.addr_atoi(start)
  range.stop = Rex::Socket.addr_atoi(stop)
  range.options = { :ipv6 => (arg.include?(":")) }

  return range
end

#expand_nmap(arg) ⇒ Object

Expands an nmap-style host range x.x.x.x where x can be simply “*” which means 0-255 or any combination and repitition of:

i,n
n-m
i,n-m
n-m,i

ensuring that n is never greater than m.

non-unique elements will be removed

e.g.:
  10.1.1.1-3,2-2,2 =>  ["10.1.1.1", "10.1.1.2", "10.1.1.3"]
  10.1.1.1-3,7 =>  ["10.1.1.1", "10.1.1.2", "10.1.1.3", "10.1.1.7"]

Returns an array of Ranges



278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
# File 'lib/rex/socket/range_walker.rb', line 278

def expand_nmap(arg)
  # Can't really do anything with IPv6
  return if arg.include?(":")

  # nmap calls these errors, but it's hard to catch them with our
  # splitting below, so short-cut them here
  return if arg.include?(",-") or arg.include?("-,")

  bytes = []
  sections = arg.split('.')
  return unless sections.length == 4  # Too many or not enough dots

  sections.each { |section|
    if section.empty?
      # pretty sure this is an unintentional artifact of the C
      # functions that turn strings into ints, but it sort of makes
      # sense, so why not
      #   "10...1" => "10.0.0.1"
      section = "0"
    end

    if section == "*"
      # I think this ought to be 1-254, but this is how nmap does it.
      section = "0-255"
    elsif section.include?("*")
      return
    end

    # Break down the sections into ranges like so
    # "1-3,5-7" => ["1-3", "5-7"]
    ranges = section.split(',', -1)
    sets = []
    ranges.each { |r|
      bounds = []
      if r.include?('-')
        # Then it's an actual range, break it down into start,stop
        # pairs:
        #   "1-3" => [ 1, 3 ]
        # if the lower bound is empty, start at 0
        # if the upper bound is empty, stop at 255
        #
        bounds = r.split('-', -1)
        return if (bounds.length > 2)

        bounds[0] = 0   if bounds[0].nil? or bounds[0].empty?
        bounds[1] = 255 if bounds[1].nil? or bounds[1].empty?
        bounds.map!{|b| b.to_i}
        return if bounds[0] > bounds[1]
      else
        # Then it's a single value
        bounds[0] = r.to_i
      end
      return if bounds[0] > 255 or (bounds[1] and bounds[1] > 255)
      return if bounds[1] and bounds[0] > bounds[1]
      if bounds[1]
        bounds[0].upto(bounds[1]) do |i|
          sets.push(i)
        end
      elsif bounds[0]
        sets.push(bounds[0])
      end
    }
    bytes.push(sets.sort.uniq)
  }

  #
  # Combinitorically squish all of the quads together into a big list of
  # ip addresses, stored as ints
  #
  # e.g.:
  #  [[1],[1],[1,2],[1,2]]
  #  =>
  #  [atoi("1.1.1.1"),atoi("1.1.1.2"),atoi("1.1.2.1"),atoi("1.1.2.2")]
  addrs = []
  for a in bytes[0]
    for b in bytes[1]
      for c in bytes[2]
        for d in bytes[3]
          ip = (a << 24) + (b << 16) + (c << 8) + d
          addrs.push ip
        end
      end
    end
  end

  addrs.sort!
  addrs.uniq!

  rng = Range.new
  rng.options = { :ipv6 => false }
  rng.start = addrs[0]

  ranges = []
  1.upto(addrs.length - 1) do |idx|
    if addrs[idx - 1] + 1 == addrs[idx]
      # Then this address is contained in the current range
      next
    else
      # Then this address is the upper bound for the current range
      rng.stop = addrs[idx - 1]
      ranges.push(rng.dup)
      rng.start = addrs[idx]
    end
  end
  rng.stop = addrs[addrs.length - 1]
  ranges.push(rng.dup)
  return ranges
end

#include?(addr) ⇒ true, false

Returns true if the argument is an ip address that falls within any of the stored ranges.

Returns:

  • (true)

    if this RangeWalker contains addr

  • (false)

    if not



185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/rex/socket/range_walker.rb', line 185

def include?(addr)
  return false if not @ranges
  if (addr.is_a? String)
    addr = Rex::Socket.addr_atoi(addr)
  end
  @ranges.map { |r|
    if addr.between?(r.start, r.stop)
      return true
    end
  }
  return false
end

#include_range?(other) ⇒ Boolean

Returns true if this RangeWalker includes all of the addresses in the given RangeWalker

Parameters:

Returns:

  • (Boolean)


203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/rex/socket/range_walker.rb', line 203

def include_range?(other)
  return false if (!@ranges || @ranges.empty?)
  return false if !other.ranges || other.ranges.empty?

  # Check that all the ranges in +other+ fall within at least one of
  # our ranges.
  other.ranges.all? do |other_range|
    ranges.any? do |range|
      other_range.start.between?(range.start, range.stop) && other_range.stop.between?(range.start, range.stop)
    end
  end
end

#next_hostHash<Symbol, String>

Returns the next host in the range.

Returns:

  • (Hash<Symbol, String>)

    The next host in the range



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/rex/socket/range_walker.rb', line 138

def next_host
  return unless valid?

  if (@curr_addr > @ranges[@curr_range_index].stop)
    # Then we are at the end of this range. Grab the next one.

    # Bail if there are no more ranges
    return nil if (@ranges[@curr_range_index+1].nil?)

    @curr_range_index += 1

    @curr_addr = @ranges[@curr_range_index].start
  end

  range = @ranges[@curr_range_index]
  addr = Rex::Socket.addr_itoa(@curr_addr, range.ipv6?)

  if range.options[:scope_id]
    addr = addr + '%' + range.options[:scope_id]
  end

  hostname = range.is_a?(Host) ? range.hostname : nil

  @curr_addr += 1
  return { address: addr, hostname: hostname }
end

#next_ipString Also known as: next

Returns the next IP address.

Returns:

  • (String)

    The next address in the range



168
169
170
171
# File 'lib/rex/socket/range_walker.rb', line 168

def next_ip
  return nil if (host = next_host).nil?
  host[:address]
end

#parse(parseme) ⇒ self, false

Turn a human-readable range string into ranges we can step through one address at a time.

Allow the following formats:

"a.b.c.d e.f.g.h"
"a.b.c.d, e.f.g.h"

where each chunk is CIDR notation, (e.g. '10.1.1.0/24') or a range in nmap format (see #expand_nmap)

OR this format

"a.b.c.d-e.f.g.h"

where a.b.c.d and e.f.g.h are single IPs and the second must be bigger than the first.

Parameters:

  • parseme (String)

Returns:

  • (self)
  • (false)

    if parseme cannot be parsed



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
# File 'lib/rex/socket/range_walker.rb', line 79

def parse(parseme)
  return nil unless parseme

  ranges = []
  parseme.split(', ').map{ |a| a.split(' ') }.flatten.each do |arg|
    # Remove trailing commas that may be unneeded, i.e. '1.1.1.1,'
    arg = arg.sub(/,+$/, '')

    # Handle IPv6 CIDR first
    if arg.include?(':') && arg.include?('/')
      next if (new_ranges = parse_ipv6_cidr(arg)).nil?

    # Handle plain IPv6 next (support ranges, but not CIDR)
    elsif arg.include?(':')
      next if (new_ranges = parse_ipv6(arg)).nil?

    # Handle IPv4 CIDR
    elsif arg.include?("/")
      next if (new_ranges = parse_ipv4_cidr(arg)).nil?

    # Handle hostnames
    elsif arg =~ /[^-0-9,.*]/
      next if (new_ranges = parse_hostname(arg)).nil?

    # Handle IPv4 ranges
    elsif arg =~ MATCH_IPV4_RANGE
      # Then it's in the format of 1.2.3.4-5.6.7.8
      next if (new_ranges = parse_ipv4_ranges(arg)).nil?

    else
      next if (new_ranges = expand_nmap(arg)).nil?
    end

    ranges += new_ranges
  end

  # Remove any duplicate ranges
  ranges = ranges.uniq

  return ranges
end

#resetself

Resets the subnet walker back to its original state.

Returns:

  • (self)


125
126
127
128
129
130
131
132
133
# File 'lib/rex/socket/range_walker.rb', line 125

def reset
  return false if not valid?
  @curr_range_index = 0
  @curr_addr = @ranges.first.start
  @length = 0
  @ranges.each { |r| @length += r.length }

  self
end

#valid?Boolean

Whether this RangeWalker's ranges are valid

Returns:

  • (Boolean)


176
177
178
# File 'lib/rex/socket/range_walker.rb', line 176

def valid?
  (@ranges && !@ranges.empty?)
end