inspec/lib/resources/os_env.rb

77 lines
1.8 KiB
Ruby
Raw Normal View History

2015-07-15 15:15:18 +02:00
# encoding: utf-8
# copyright: 2015, Vulcano Security GmbH
2015-10-06 18:55:44 +02:00
# author: Christoph Hartmann
# author: Dominik Richter
2015-07-15 15:15:18 +02:00
2015-09-05 20:09:55 +02:00
# Usage:
#
2015-10-30 14:37:00 +01:00
# describe os_env('PATH') do
# its('split') { should_not include('') }
# its('split') { should_not include('.') }
2015-09-05 20:09:55 +02:00
# end
2015-11-13 11:53:21 +01:00
require 'utils/simpleconfig'
module Inspec::Resources
class OsEnv < Inspec.resource(1)
name 'os_env'
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-15 00:47:04 +02:00
attr_reader :content
def initialize(env = nil)
@osenv = env
end
2015-07-15 00:47:04 +02: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) unless @osenv.nil?
end
2015-07-15 00:47:04 +02:00
def to_s
if @osenv.nil?
'Environment variables'
else
"Environment variable #{@osenv}"
end
2015-11-13 11:53:21 +01:00
end
private
2015-11-13 11:53:21 +01:00
def value_for(env)
command = if inspec.os.windows?
"${Env:#{env}}"
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 11:53:21 +01:00
if inspec.os.windows?
out.stdout.strip
else
params = SimpleConfig.new(out.stdout).params
params[env]
end
end
2015-07-15 00:47:04 +02:00
end
2015-07-26 12:30:12 +02:00
end