Skeleton resource for aws_ec2_security_groups

Signed-off-by: Clinton Wolfe <clintoncwolfe@gmail.com>
This commit is contained in:
Clinton Wolfe 2017-12-13 22:36:23 -05:00 committed by GitHub
parent e5dc4a1c29
commit 4229974e7d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 338 additions and 0 deletions

View file

@ -0,0 +1,81 @@
---
title: About the aws_ec2_security_groups Resource
---
# aws_ec2_security_groups
Use the `aws_ec2_security_groups` InSpec audit resource to test properties of some or all security groups.
Security groups are a networking construct which contain ingress and egress rules for network communications. Security groups may be attached to EC2 instances, as well as certain other AWS resources. Along with Network Access Control Lists, Security Groups are one of the two main mechanisms of enforcing network-level security.
<br>
## Syntax
An `aws_ec2_security_groups` resource block uses an optional filter to select a group of security groups and then tests that group.
# Verify you have more than the default security group
describe aws_ec2_security_groups do
its('count') { should be > 1 }
end
<br>
## Examples
The following examples show how to use this InSpec audit resource.
As this is the initial release of `aws_ec2_security_groups`, its limited functionality precludes examples.
<br>
## Matchers
### exists
The control will pass if the filter returns at least one result. Use should_not if you expect zero matches.
# You will always have at least one SG, the VPC default SG
describe aws_ec2_security_groups
it { should exist }
end
## Filter Criteria
### vpc_id
A string identifying the VPC which contains the security group.
# Look for a particular security group in just one VPC
describe aws_ec2_security_groups.where( vpc_id: 'vpc-12345678') do
its('group_ids') { should include('sg-abcdef12')}
end
### group_name
A string identifying a group. Since groups are contained in VPCs, group names are unique within the AWS account, but not across VPCs.
# Examine the default security group in all VPCs
describe aws_ec2_security_groups.where( group_name: 'default') do
it { should exist }
end
## Properties
### group_ids
Provides a list of all security group IDs matched.
describe aws_ec2_security_groups do
its('group_ids') { should include('sg-12345678') }
end
### entries
Provides access to the raw results of the query. This can be useful for checking counts and other advanced operations.
# Allow at most 100 security groups on the account
describe aws_ec2_security_groups do
its('entries.count') { should be <= 100}
end

View file

@ -0,0 +1,88 @@
class AwsEc2SecurityGroups < Inspec.resource(1)
name 'aws_ec2_security_groups'
desc 'Verifies settings for AWS Security Groups in bulk'
example '
describe aws_ec2_security_groups do
it { should exist }
end
'
# Constructor. Args are reserved for row fetch filtering.
def initialize(raw_criteria = {})
validated_criteria = validate_filter_criteria(raw_criteria)
fetch_from_backend(validated_criteria)
end
# Underlying FilterTable implementation.
filter = FilterTable.create
filter.add_accessor(:where)
.add_accessor(:entries)
.add(:exists?) { |x| !x.entries.empty? }
.add(:group_ids, field: :group_id)
filter.connect(self, :access_key_data)
def access_key_data
@table
end
def to_s
'EC2 Security Groups'
end
private
def validate_filter_criteria(raw_criteria)
unless raw_criteria.is_a? Hash
raise 'Unrecognized criteria for fetching Security Groups. ' \
"Use 'criteria: value' format."
end
# No criteria yet
recognized_criteria = check_criteria_names(raw_criteria)
recognized_criteria
end
def check_criteria_names(raw_criteria: {}, allowed_criteria: [])
# Remove all expected criteria from the raw criteria hash
recognized_criteria = {}
allowed_criteria.each do |expected_criterion|
recognized_criteria[expected_criterion] = raw_criteria.delete(expected_criterion) if raw_criteria.key?(expected_criterion)
end
# Any leftovers are unwelcome
unless raw_criteria.empty?
raise ArgumentError, "Unrecognized filter criterion '#{raw_criteria.keys.first}'. Expected criteria: #{allowed_criteria.join(', ')}"
end
recognized_criteria
end
def fetch_from_backend(criteria)
@table = []
backend = AwsEc2SecurityGroups::BackendFactory.create
# Note: should we ever implement server-side filtering
# (and this is a very good resource for that),
# we will need to reformat the criteria we are sending to AWS.
backend.describe_security_groups(criteria).security_groups.each do |sg_info|
@table.push({
group_id: sg_info.group_id,
group_name: sg_info.group_name,
vpc_id: sg_info.vpc_id,
})
end
end
class BackendFactory
extend AwsBackendFactoryMixin
end
class Backend
class AwsClientApi < Backend
AwsEc2SecurityGroups::BackendFactory.set_default_backend self
def describe_security_groups(query)
AWSConnection.new.ec2_client.describe_security_groups(query)
end
end
end
end

View file

@ -0,0 +1,21 @@
#============================================================#
# Security Groups
#============================================================#
# Look up the default VPC and the default security group for it
data "aws_vpc" "default" {
default = "true"
}
data "aws_security_group" "default" {
vpc_id = "${data.aws_vpc.default.id}"
name = "default"
}
output "ec2_security_group_default_vpc_id" {
value = "${data.aws_vpc.default.id}"
}
output "ec2_security_group_default_group_id" {
value = "${data.aws_security_group.default.id}"
}

View file

@ -0,0 +1,43 @@
fixtures = {}
[
'ec2_security_group_default_vpc_id',
'ec2_security_group_default_group_id',
].each do |fixture_name|
fixtures[fixture_name] = attribute(
fixture_name,
default: "default.#{fixture_name}",
description: 'See ../build/ec2.tf',
)
end
control "aws_security_groups client-side filtering" do
all_groups = aws_ec2_security_groups
# You should always have at least one security group
describe all_groups do
it { should exist }
end
# You should be able to find a security group in the default VPC
describe all_groups.where(vpc_id: fixtures['ec2_security_group_default_vpc_id']) do
it { should exist }
end
describe all_groups.where(vpc_id: 'vpc-12345678') do
it { should_not exist }
end
# You should be able to find the security group named default
describe all_groups.where(group_name: 'default') do
it { should exist }
end
describe all_groups.where(group_name: 'no-such-security-group') do
it { should_not exist }
end
end
control "aws_security_groups properties" do
# You should be able to find the default security group's ID.
describe aws_ec2_security_groups.where(vpc_id: fixtures['ec2_security_group_default_vpc_id']) do
its('group_ids') { should include fixtures['ec2_security_group_default_group_id'] }
end
end

View file

@ -0,0 +1,105 @@
require 'ostruct'
require 'helper'
require 'aws_ec2_security_groups'
# MESGB = MockEc2SecurityGroupBackend
# Abbreviation not used outside this file
#=============================================================================#
# Constructor Tests
#=============================================================================#
class AwsESGConstructor < Minitest::Test
def setup
AwsEc2SecurityGroups::BackendFactory.select(AwsMESGB::Empty)
end
def test_constructor_no_args_ok
AwsEc2SecurityGroups.new
end
def test_constructor_reject_unknown_resource_params
assert_raises(ArgumentError) { AwsEc2SecurityGroups.new(beep: 'boop') }
end
end
#=============================================================================#
# Filter Criteria
#=============================================================================#
class AwsESGFilterCriteria < Minitest::Test
def setup
AwsEc2SecurityGroups::BackendFactory.select(AwsMESGB::Basic)
end
def test_filter_vpc_id
hit = AwsEc2SecurityGroups.new.where(vpc_id: 'vpc-12345678')
assert(hit.exists?)
miss = AwsEc2SecurityGroups.new.where(vpc_id: 'vpc-87654321')
refute(miss.exists?)
end
def test_filter_group_name
hit = AwsEc2SecurityGroups.new.where(group_name: 'alpha')
assert(hit.exists?)
miss = AwsEc2SecurityGroups.new.where(group_name: 'nonesuch')
refute(miss.exists?)
end
end
#=============================================================================#
# Properties
#=============================================================================#
class AwsESGProperties < Minitest::Test
def setup
AwsEc2SecurityGroups::BackendFactory.select(AwsMESGB::Basic)
end
def test_property_group_ids
basic = AwsEc2SecurityGroups.new
assert_kind_of(Array, basic.group_ids)
assert(basic.group_ids.include?('sg-aaaabbbb'))
refute(basic.group_ids.include?(nil))
end
end
#=============================================================================#
# Test Fixtures
#=============================================================================#
module AwsMESGB
class Empty < AwsEc2SecurityGroups::Backend
def describe_security_groups(_query)
OpenStruct.new({
security_groups: [],
})
end
end
class Basic < AwsEc2SecurityGroups::Backend
def describe_security_groups(query)
fixtures = [
OpenStruct.new({
group_id: 'sg-aaaabbbb',
group_name: 'alpha',
vpc_id: 'vpc-aaaabbbb',
}),
OpenStruct.new({
group_id: 'sg-12345678',
group_name: 'beta',
vpc_id: 'vpc-12345678',
}),
]
selected = fixtures.select do |sg|
query.keys.all? do |criterion|
query[criterion] == sg[criterion]
end
end
OpenStruct.new({ security_groups: selected })
end
end
end