From 502509aa5a8cb6399108fa06c199cb3d8b9ed9b6 Mon Sep 17 00:00:00 2001 From: Clinton Wolfe Date: Mon, 1 Jun 2020 16:38:58 -0400 Subject: [PATCH] Rework IP range filtering for clarity, add 172.16/12 Signed-off-by: Clinton Wolfe --- lib/inspec/resources/interfaces.rb | 35 +++++++++++++++--------------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/lib/inspec/resources/interfaces.rb b/lib/inspec/resources/interfaces.rb index 580303ef4..6d2d45c01 100644 --- a/lib/inspec/resources/interfaces.rb +++ b/lib/inspec/resources/interfaces.rb @@ -24,32 +24,33 @@ module Inspec::Resources .install_filter_methods_on_resource(self, :scan_interfaces) def ipv4_address + require "ipaddr" + # Loop over interface names # Select those that are up and have an ipv4 address interfaces = names.map { |n| inspec.interface(n) }.select do |i| i.ipv4_address? && i.up? 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 + [ + # 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 - non_loopback_addrs = all_addrs.reject { |a| a =~ /^127/ } - return all_addrs.first if non_loopback_addrs.empty? - - # 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 + addrs = filtered_addrs + end + addrs.first.to_s end private