Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add platform uuid information. #270

Merged
merged 4 commits into from
Mar 27, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions lib/train/platforms.rb
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
# encoding: utf-8

require 'train/platforms/common'
require 'train/platforms/family'
require 'train/platforms/platform'
require 'train/platforms/detect'
require 'train/platforms/detect/scanner'
require 'train/platforms/detect/specifications/os'
require 'train/platforms/detect/specifications/api'
require 'train/platforms/detect/uuid'
require 'train/platforms/family'
require 'train/platforms/platform'

module Train::Platforms
class << self
Expand Down
56 changes: 55 additions & 1 deletion lib/train/platforms/detect/helpers/os_common.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
require 'rbconfig'

module Train::Platforms::Detect::Helpers
module OSCommon
module OSCommon # rubocop:disable Metrics/ModuleLength
include Train::Platforms::Detect::Helpers::Linux
include Train::Platforms::Detect::Helpers::Windows

Expand Down Expand Up @@ -87,5 +87,59 @@ def cisco_show_version

@cache[:cisco] = nil
end

def unix_uuid
uuid = unix_uuid_from_chef
uuid = unix_uuid_from_machine_file if uuid.nil?
uuid = uuid_from_command if uuid.nil?
raise Train::TransportError, 'Cannot find a UUID for your node.' if uuid.nil?
uuid
end

def unix_uuid_from_chef
file = @backend.file('/var/chef/cache/data_collector_metadata.json')
if file.exist? && !file.size.zero?
json = ::JSON.parse(file.content)
return json['node_uuid'] if json['node_uuid']
end
end

def unix_uuid_from_machine_file
%W(
/etc/chef/chef_guid
#{ENV['HOME']}/.chef/chef_guid
/etc/machine-id
/var/lib/dbus/machine-id
/var/db/dbus/machine-id
).each do |path|
file = @backend.file(path)
next unless file.exist? && !file.size.zero?
return file.content.chomp if path =~ /guid/
return uuid_from_string(file.content.chomp)
end
nil
end

# This takes a command from the platform detect block to run.
# We expect the command to return a unique identifier which
# we turn into a UUID.
def uuid_from_command
return unless @platform[:uuid_command]
result = @backend.run_command(@platform[:uuid_command])
uuid_from_string(result.stdout.chomp) if result.exit_status.zero? && !result.stdout.empty?
end

# This hashes the passed string into SHA1.
# Then it downgrades the 160bit SHA1 to a 128bit
# then we format it as a valid UUIDv5.
def uuid_from_string(string)
hash = Digest::SHA1.new
hash.update(string)
ary = hash.digest.unpack('NnnnnN')
ary[2] = (ary[2] & 0x0FFF) | (5 << 12)
ary[3] = (ary[3] & 0x3FFF) | 0x8000
# rubocop:disable Style/FormatString
'%08x-%04x-%04x-%04x-%04x%08x' % ary
end
end
end
41 changes: 41 additions & 0 deletions lib/train/platforms/detect/helpers/os_windows.rb
Original file line number Diff line number Diff line change
Expand Up @@ -75,5 +75,46 @@ def read_wmic_cpu
arch_number = sys_info[:Architecture].to_i
arch_map[arch_number]
end

# This method scans the target os for a unique uuid to use
def windows_uuid
uuid = windows_uuid_from_chef
uuid = windows_uuid_from_machine_file if uuid.nil?
uuid = windows_uuid_from_wmic if uuid.nil?
uuid = windows_uuid_from_registry if uuid.nil?
raise Train::TransportError, 'Cannot find a UUID for your node.' if uuid.nil?
uuid
end

def windows_uuid_from_machine_file
%W(
#{ENV['SYSTEMDRIVE']}\\chef\\chef_guid
#{ENV['HOMEDRIVE']}#{ENV['HOMEPATH']}\\.chef\\chef_guid
).each do |path|
file = @backend.file(path)
return file.content.chomp if file.exist? && !file.size.zero?
end
nil
end

def windows_uuid_from_chef
file = @backend.file("#{ENV['SYSTEMDRIVE']}\\chef\\cache\\data_collector_metadata.json")
return if !file.exist? || file.size.zero?
json = JSON.parse(file.content)
json['node_uuid'] if json['node_uuid']
end

def windows_uuid_from_wmic
result = @backend.run_command('wmic csproduct get UUID')
return unless result.exit_status.zero?
result.stdout.split("\r\n")[-1].strip
end

def windows_uuid_from_registry
cmd = '(Get-ItemProperty "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography" -Name "MachineGuid")."MachineGuid"'
result = @backend.run_command(cmd)
return unless result.exit_status.zero?
result.stdout.chomp
end
end
end
1 change: 1 addition & 0 deletions lib/train/platforms/detect/specifications/os.rb
Original file line number Diff line number Diff line change
Expand Up @@ -449,6 +449,7 @@ def self.load
plat.name('mac_os_x').title('macOS X').in_family('darwin')
.detect {
cmd = unix_file_contents('/System/Library/CoreServices/SystemVersion.plist')
@platform[:uuid_command] = "system_profiler SPHardwareDataType | awk '/UUID/ { print $3; }'"
true if cmd =~ /Mac OS X/i
}
plat.name('darwin').title('Darwin').in_family('darwin')
Expand Down
34 changes: 34 additions & 0 deletions lib/train/platforms/detect/uuid.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# encoding: utf-8

require 'digest/sha1'
require 'securerandom'
require 'json'

module Train::Platforms::Detect
class UUID
include Train::Platforms::Detect::Helpers::OSCommon

def initialize(platform)
@platform = platform
@backend = @platform.backend
end

def find_or_create_uuid
# for api transports uuid is defined on the connection
if defined?(@backend.unique_identifier)
uuid_from_string(@backend.unique_identifier)
elsif @platform.unix?
unix_uuid
elsif @platform.windows?
windows_uuid
else
if @platform[:uuid_command]
result = @backend.run_command(@platform[:uuid_command])
return uuid_from_string(result.stdout.chomp) if result.exit_status.zero? && !result.stdout.empty?
end

raise 'Could not find platform uuid! Please set a uuid_command for your platform.'
end
end
end
end
4 changes: 4 additions & 0 deletions lib/train/platforms/platform.rb
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ def clean_name(force: false)
end
end

def uuid
@uuid ||= Train::Platforms::Detect::UUID.new(self).find_or_create_uuid.downcase
end

# This is for backwords compatability with
# the current inspec os resource.
def[](name)
Expand Down
7 changes: 7 additions & 0 deletions lib/train/transports/aws.rb
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,13 @@ def connect
def uri
"aws://#{@options[:region]}"
end

def unique_identifier
# use aws account id
client = aws_client(::Aws::IAM::Client)
arn = client.get_user.user.arn
arn.split(':')[4]
end
end
end
end
6 changes: 6 additions & 0 deletions lib/train/transports/azure.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ def connection(_ = nil)
end

class Connection < BaseConnection
attr_reader :options

def initialize(options)
@apis = {}

Expand Down Expand Up @@ -118,6 +120,10 @@ def get_api_version(resource_type, options)
@apis[resource_type]
end

def unique_identifier
options[:subscription_id] || options[:tenant_id]
end

private

def parse_credentials_file # rubocop:disable Metrics/AbcSize
Expand Down
2 changes: 2 additions & 0 deletions lib/train/transports/mock.rb
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ def trace_calls

class Train::Transports::Mock
class Connection < BaseConnection
attr_reader :options

def initialize(conf = nil)
super(conf)
mock_os
Expand Down
133 changes: 133 additions & 0 deletions test/unit/platforms/detect/uuid_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
# encoding: utf-8

require 'helper'
require 'train/transports/mock'
require 'securerandom'

class TestFile
def initialize(string)
@string = string
end

def exist?
true
end

def size
@string.length
end

def content
@string
end
end

describe 'uuid' do
def mock_platform(name, commands = {}, files = {}, plat_options = {})
Train::Platforms.list[name] = nil
mock = Train::Transports::Mock::Connection.new
commands.each do |command, data|
mock.mock_command(command, data)
end

file_objects = {}
files.each do |path, content|
file_objects[path] = TestFile.new(content)
end

mock.files = file_objects
mock.direct_platform(name, plat_options)
end

it 'finds a linux uuid from chef entity_uuid' do
files = { '/var/chef/cache/data_collector_metadata.json' => '{"node_uuid":"d400073f-0920-41aa-8dd3-2ea59b18f5ce"}' }
plat = mock_platform('linux', {}, files)
plat.uuid.must_equal 'd400073f-0920-41aa-8dd3-2ea59b18f5ce'
end

it 'finds a windows uuid from chef entity_uuid' do
ENV['SYSTEMDRIVE'] = 'C:'
files = { 'C:\chef\cache\data_collector_metadata.json' => '{"node_uuid":"d400073f-0920-41aa-8dd3-2ea59b18f5ce"}' }
plat = mock_platform('windows', {}, files)
plat.uuid.must_equal 'd400073f-0920-41aa-8dd3-2ea59b18f5ce'
end

it 'finds a linux uuid from /etc/chef/chef_guid' do
files = { '/etc/chef/chef_guid' => '5e430326-b5aa-56f8-975f-c3ca1c21df91' }
plat = mock_platform('linux', {}, files)
plat.uuid.must_equal '5e430326-b5aa-56f8-975f-c3ca1c21df91'
end

it 'finds a linux uuid from /home/testuser/.chef/chef_guid' do
ENV['HOME'] = '/home/testuser'
files = { '/home/testuser/.chef/chef_guid' => '5e430326-b5aa-56f8-975f-c3ca1c21df91' }
plat = mock_platform('linux', {}, files)
plat.uuid.must_equal '5e430326-b5aa-56f8-975f-c3ca1c21df91'
end

it 'finds a linux uuid from /etc/machine-id' do
files = { '/etc/machine-id' => '123141dsfadf' }
plat = mock_platform('linux', {}, files)
plat.uuid.must_equal '5e430326-b5aa-56f8-975f-c3ca1c21df91'
end

it 'finds a linux uuid from /var/lib/dbus/machine-id' do
files = {
'/etc/machine-id' => '',
'/var/lib/dbus/machine-id' => '123141dsfadf',
}
plat = mock_platform('linux', {}, files)
plat.uuid.must_equal '5e430326-b5aa-56f8-975f-c3ca1c21df91'
end

it 'finds a linux uuid from /etc/machine-id' do
files = { '/etc/machine-id' => '123141dsfadf' }
plat = mock_platform('linux', {}, files)
plat.uuid.must_equal '5e430326-b5aa-56f8-975f-c3ca1c21df91'
end

it 'finds a windows uuid from wmic' do
commands = { 'wmic csproduct get UUID' => "UUID\r\nd400073f-0920-41aa-8dd3-2ea59b18f5ce\r\n" }
plat = mock_platform('windows', commands)
plat.uuid.must_equal 'd400073f-0920-41aa-8dd3-2ea59b18f5ce'
end

it 'finds a windows uuid from registry' do
commands = { '(Get-ItemProperty "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography" -Name "MachineGuid")."MachineGuid"' => "d400073f-0920-41aa-8dd3-2ea59b18f5ce\r\n" }
plat = mock_platform('windows', commands)
plat.uuid.must_equal 'd400073f-0920-41aa-8dd3-2ea59b18f5ce'
end

it 'finds a windows uuid from C:\chef\chef_guid' do
ENV['SYSTEMDRIVE'] = 'C:'
files = { 'C:\chef\chef_guid' => '5e430326-b5aa-56f8-975f-c3ca1c21df91' }
plat = mock_platform('windows', {}, files)
plat.uuid.must_equal '5e430326-b5aa-56f8-975f-c3ca1c21df91'
end

it 'finds a windows uuid from C:\Users\test\.chef\chef_guid' do
ENV['HOMEDRIVE'] = 'C:\\'
ENV['HOMEPATH'] = 'Users\test'
files = { 'C:\Users\test\.chef\chef_guid' => '5e430326-b5aa-56f8-975f-c3ca1c21df91' }
plat = mock_platform('windows', {}, files)
plat.uuid.must_equal '5e430326-b5aa-56f8-975f-c3ca1c21df91'
end

it 'generates a uuid from a string' do
plat = mock_platform('linux')
uuid = Train::Platforms::Detect::UUID.new(plat)
uuid.uuid_from_string('123141dsfadf').must_equal '5e430326-b5aa-56f8-975f-c3ca1c21df91'
end

it 'finds a aws uuid' do
plat = mock_platform('aws')
plat.backend.stubs(:unique_identifier).returns('158551926027')
plat.uuid.must_equal '1d74ce61-ac15-5c48-9ee3-5aa8207ac37f'
end

it 'finds an azure uuid' do
plat = mock_platform('azure')
plat.backend.stubs(:unique_identifier).returns('1d74ce61-ac15-5c48-9ee3-5aa8207ac37f')
plat.uuid.must_equal '2c2e4fa9-7287-5dee-85a3-6527face7b7b'
end
end
24 changes: 24 additions & 0 deletions test/unit/transports/aws_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -96,4 +96,28 @@ def initialize(hash)
ENV['AWS_REGION'].must_equal 'xyz'
end
end

describe 'unique_identifier' do
class AwsArn
def arn
'arn:aws:iam::158551926027:user/test-fixture-maker'
end
end

class AwsUser
def user
AwsArn.new
end
end

class AwsClient
def get_user
AwsUser.new
end
end
it 'returns an account id' do
connection.stubs(:aws_client).returns(AwsClient.new)
connection.unique_identifier.must_equal '158551926027'
end
end
end
Loading