Skip to content

Commit 05d4a1a

Browse files
committed
Land rapid7#3342, Support negation in portspec
2 parents 61f4c76 + 2b75a53 commit 05d4a1a

File tree

2 files changed

+50
-5
lines changed

2 files changed

+50
-5
lines changed

lib/rex/socket.rb

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -505,26 +505,40 @@ def self.portspec_crack(pspec)
505505
end
506506

507507
#
508-
# Converts a port specification like "80,21-23,443" into a sorted,
509-
# unique array of valid port numbers like [21,22,23,80,443]
508+
# Converts a port specification like "80,21-25,!24,443" into a sorted,
509+
# unique array of valid port numbers like [21,22,23,25,80,443]
510510
#
511511
def self.portspec_to_portlist(pspec)
512512
ports = []
513+
remove = []
513514

514515
# Build ports array from port specification
515516
pspec.split(/,/).each do |item|
517+
target = ports
518+
519+
item.strip!
520+
521+
if item.start_with? '!'
522+
item.delete! '!'
523+
target = remove
524+
end
525+
516526
start, stop = item.split(/-/).map { |p| p.to_i }
517527

518528
start ||= 0
519529
stop ||= item.match(/-/) ? 65535 : start
520530

521531
start, stop = stop, start if stop < start
522532

523-
start.upto(stop) { |p| ports << p }
533+
start.upto(stop) { |p| target << p }
534+
end
535+
536+
if ports.empty? and not remove.empty? then
537+
ports = 0.upto 65535
524538
end
525539

526540
# Sort, and remove dups and invalid ports
527-
ports.sort.uniq.delete_if { |p| p < 1 or p > 65535 }
541+
ports.sort.uniq.delete_if { |p| p < 0 or p > 65535 or remove.include? p }
528542
end
529543

530544
#
@@ -537,7 +551,7 @@ def self.portlist_to_portspec(parr)
537551
lastp = nil
538552

539553
parr.uniq.sort{|a,b| a<=>b}.map{|a| a.to_i}.each do |n|
540-
next if (n < 1 or n > 65535)
554+
next if (n < 0 or n > 65535)
541555
if not lastp
542556
range = [n]
543557
lastp = n

spec/lib/rex/socket_spec.rb

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,4 +163,35 @@
163163

164164
end
165165
end
166+
167+
describe '.portspec_to_portlist' do
168+
169+
portspec = '-1,0-10,!2-5,!7,65530-,65536'
170+
context "'#{portspec}'" do
171+
172+
subject { described_class.portspec_to_portlist portspec }
173+
174+
it { should be_a(Array) }
175+
176+
not_included = []
177+
not_included << -1
178+
not_included << 65536
179+
not_included.concat (2..5).to_a
180+
not_included << 7
181+
not_included.each do |item|
182+
it { should_not include item }
183+
end
184+
185+
included = []
186+
included << -1
187+
included.concat (0..10).to_a
188+
included.concat (65530..65535).to_a
189+
included << 65536
190+
included = included - not_included
191+
included.each do |item|
192+
it { should include item }
193+
end
194+
end
195+
end
196+
166197
end

0 commit comments

Comments
 (0)