Rework IP range filtering for clarity, add 172.16/12

Signed-off-by: Clinton Wolfe <clintoncwolfe@gmail.com>
This commit is contained in:
Clinton Wolfe 2020-06-01 16:38:58 -04:00 committed by Mary Jinglewski
parent d9007588a6
commit 502509aa5a

View file

@ -24,32 +24,33 @@ module Inspec::Resources
.install_filter_methods_on_resource(self, :scan_interfaces) .install_filter_methods_on_resource(self, :scan_interfaces)
def ipv4_address def ipv4_address
require "ipaddr"
# Loop over interface names # Loop over interface names
# Select those that are up and have an ipv4 address # Select those that are up and have an ipv4 address
interfaces = names.map { |n| inspec.interface(n) }.select do |i| interfaces = names.map { |n| inspec.interface(n) }.select do |i|
i.ipv4_address? && i.up? i.ipv4_address? && i.up?
end end
all_addrs = interfaces.map(&:ipv4_addresses).flatten addrs = interfaces.map(&:ipv4_addresses).flatten.map { |a| IPAddr.new(a) }
# Look for progressively "better" IP addresses # Look for progressively "better" IP addresses
[
# Loopback and private IP ranges
IPAddr.new("127.0.0.0/8"),
IPAddr.new("192.168.0.0/16"),
IPAddr.new("172.16.0.0/12"),
IPAddr.new("10.0.0.0/8"),
].each do |private_range|
filtered_addrs = addrs.reject { |a| private_range.include?(a) }
if filtered_addrs.empty?
# Everything we had was a private or loopback IP. Return the "best" thing we were left with.
return addrs.first.to_s
end
# Reject anything that looks loopback-ish addrs = filtered_addrs
non_loopback_addrs = all_addrs.reject { |a| a =~ /^127/ } end
return all_addrs.first if non_loopback_addrs.empty? addrs.first.to_s
# OK, we have something that isn't loopbackish.
# Try to filter out management networks.
non_management_addrs = non_loopback_addrs.reject { |a| a =~ /^10\./ }
return non_loopback_addrs.first if non_management_addrs.empty?
# OK, we have something that isn't management.
# Check for local networks.
non_local_addrs = non_management_addrs.reject { |a| a =~ /^192\.168/ }
return non_management_addrs.first if non_local_addrs.empty?
# Whatever is left is the best guess
non_local_addrs.first
end end
private private