inspec/lib/resources/os_env.rb

87 lines
2.2 KiB
Ruby
Raw Normal View History

2015-07-15 13:15:18 +00:00
# encoding: utf-8
# copyright: 2015, Vulcano Security GmbH
2015-09-05 18:09:55 +00:00
# Usage:
#
2015-10-30 13:37:00 +00:00
# describe os_env('PATH') do
# its('split') { should_not include('') }
# its('split') { should_not include('.') }
2015-09-05 18:09:55 +00:00
# end
2015-11-13 10:53:21 +00:00
require 'utils/simpleconfig'
module Inspec::Resources
class OsEnv < Inspec.resource(1)
name 'os_env'
supports platform: 'unix'
supports platform: 'windows'
desc 'Use the os_env InSpec audit resource to test the environment variables for the platform on which the system is running.'
example "
describe os_env('VARIABLE') do
its('matcher') { should eq 1 }
end
"
2015-07-14 22:47:04 +00:00
def initialize(env = nil, target = nil)
@osenv = env
@target = unless target.nil?
if target.casecmp('system') == 0
'Machine'
else
'User'
end
end
end
2015-07-14 22:47:04 +00:00
def split
# we can't take advantage of `File::PATH_SEPARATOR` as code is
# evaluated on the host machine
path_separator = inspec.os.windows? ? ';' : ':'
# -1 is required to catch cases like dir1::dir2:
# where we have a trailing :
content.nil? ? [] : content.split(path_separator, -1)
end
def content
return @content if defined?(@content)
@content = value_for(@osenv, @target) unless @osenv.nil?
end
2015-07-14 22:47:04 +00:00
def to_s
if @osenv.nil?
'Environment variables'
else
"Environment variable #{@osenv}"
end
2015-11-13 10:53:21 +00:00
end
private
2015-11-13 10:53:21 +00:00
def value_for(env, target = nil)
command = if inspec.os.windows?
if target.nil?
"${Env:#{env}}"
else
"[System.Environment]::GetEnvironmentVariable('#{env}', [System.EnvironmentVariableTarget]::#{target})"
end
else
'env'
end
out = inspec.command(command)
unless out.exit_status == 0
skip_resource "Can't read environment variables on #{inspec.os.name}. "\
"Tried `#{command}` which returned #{out.exit_status}"
end
2015-11-13 10:53:21 +00:00
if inspec.os.windows?
out.stdout.strip
else
params = SimpleConfig.new(out.stdout).params
params[env]
end
end
2015-07-14 22:47:04 +00:00
end
2015-07-26 10:30:12 +00:00
end