Skip to content

Commit

Permalink
fix examples
Browse files Browse the repository at this point in the history
Signed-off-by: Nikita Pivkin <[email protected]>
  • Loading branch information
nikpivkin committed Sep 23, 2024
1 parent 5631ba6 commit 12c64dd
Show file tree
Hide file tree
Showing 10 changed files with 231 additions and 130 deletions.
4 changes: 2 additions & 2 deletions checks/cloud/aws/apigateway/no_public_access.rego
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,11 @@ deny contains res if {
isManaged(api)
some method in api.resources[_].methods
not method_is_option(method)
not is_apikey_required(api)
not is_apikey_required(method)
method.authorizationtype.value == authorization_none
res := result.new("Authorization is not enabled for this method.", method.authorizationtype)
}

method_is_option(method) := method.httpmethod.value == "OPTION"

is_apikey_required(api) := api.apikeyrequired.value
is_apikey_required(method) := method.apikeyrequired.value
2 changes: 1 addition & 1 deletion checks/cloud/aws/apigateway/no_public_access_test.rego
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ test_allow_get_method_with_auth if {
}

test_allow_if_api_required if {
test.assert_empty(check.deny) with input as input_with_method({"httpmethod": {"value": "GET"}, "authorizationtype": {"value": "AWS_IAM"}})
test.assert_empty(check.deny) with input as input_with_method({"httpmethod": {"value": "GET"}, "authorizationtype": {"value": "AWS_IAM"}, "apikeyrequired": {"value": true}})
}

input_with_method(method) = {"aws": {"apigateway": {"v1": {"apis": [{"resources": [{"methods": [method]}]}]}}}}
11 changes: 10 additions & 1 deletion checks/cloud/aws/cloudtrail/encryption_customer_key.tf.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,19 @@ package cloudtrail

var terraformEncryptionCustomerManagedKeyGoodExamples = []string{
`
resource "aws_kms_key" "trail" {
enable_key_rotation = true
}
resource "aws_kms_alias" "trail" {
name = "alias/trail"
target_key_id = aws_kms_key.trail.key_id
}
resource "aws_cloudtrail" "good_example" {
is_multi_region_trail = true
enable_log_file_validation = true
kms_key_id = var.kms_id
kms_key_id = aws_kms_alias.trail.arn
event_selector {
read_write_type = "All"
Expand Down
11 changes: 10 additions & 1 deletion checks/cloud/aws/cloudwatch/log_group_customer_key.tf.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,19 @@ package cloudwatch

var terraformLogGroupCustomerKeyGoodExamples = []string{
`
resource "aws_kms_key" "cloudwatch" {
enable_key_rotation = true
}
resource "aws_kms_alias" "cloudwatch" {
name = "alias/cloudwatch"
target_key_id = aws_kms_key.cloudwatch.key_id
}
resource "aws_cloudwatch_log_group" "good_example" {
name = "good_example"
kms_key_id = aws_kms_key.log_key.arn
kms_key_id = aws_kms_alias.cloudwatch.arn
}
`,
}
Expand Down
4 changes: 2 additions & 2 deletions checks/cloud/aws/ec2/no_public_ingress_sgr.tf.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ var terraformNoPublicIngressSgrGoodExamples = []string{
}
`,
`
resource "aws_security_group_rule" "allow_partner_rsync" {
resource "aws_security_group_rule" "example" {
type = "ingress"
security_group_id = aws_security_group.….id
security_group_id = "sg-123456"
from_port = 22
to_port = 22
protocol = "tcp"
Expand Down
9 changes: 7 additions & 2 deletions checks/cloud/nifcloud/computing/no_public_ingress_sgr.tf.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,14 @@ var terraformNoPublicIngressSgrGoodExamples = []string{
}
`,
`
resource "nifcloud_security_group_rule" "allow_partner_rsync" {
resource "nifcloud_security_group" "example" {
group_name = "allowtcp"
availability_zone = "east-11"
}
resource "nifcloud_security_group_rule" "example" {
type = "IN"
security_group_names = [nifcloud_security_group..group_name]
security_group_names = [nifcloud_security_group.example.group_name]
from_port = 22
to_port = 22
protocol = "TCP"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ import rego.v1

deny contains res if {
some router in input.nifcloud.network.routers
router.securitygroup.value == ""
res := result.new("Router does not have a securiy group.", router.securitygroup)
not has_security_group(router)
res := result.new(
"Router does not have a securiy group.",
object.get(router, "securitygroup", router),
)
}

has_security_group(router) if router.securitygroup.value != ""
30 changes: 30 additions & 0 deletions internal/checks/checks.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package checks

import (
"sort"

"github.com/aquasecurity/trivy/pkg/iac/framework"
"github.com/aquasecurity/trivy/pkg/iac/rego"
"github.com/aquasecurity/trivy/pkg/iac/rules"
"github.com/aquasecurity/trivy/pkg/iac/scan"
)

func LoadRegoChecks() []scan.Rule {
// Clean up all Go checks
rules.Reset()

// Load Rego checks
rego.LoadAndRegister()

var res []scan.Rule

for _, metadata := range rules.GetRegistered(framework.ALL) {
res = append(res, metadata.Rule)
}

sort.Slice(res, func(i, j int) bool {
return res[i].AVDID < res[j].AVDID
})

return res
}
117 changes: 117 additions & 0 deletions internal/checks/examples.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
package checks

import (
goast "go/ast"
"go/parser"
"go/token"
"strings"

trivy_checks "github.com/aquasecurity/trivy-checks"
"github.com/aquasecurity/trivy/pkg/iac/scan"
)

type Provider string

const (
TerraformProvider Provider = "Terraform"
CloudFormationProvider Provider = "CloudFormation"
)

func providerByFileName(n string) Provider {
switch {
case strings.HasSuffix(n, "tf.go"):
return TerraformProvider
case strings.HasSuffix(n, "cf.go"):
return CloudFormationProvider
}

panic("unreachable")
}

type Example struct {
Path string
Provider Provider
GoodExample bool // bad example if false
Content string
}

func GetCheckExamples(check scan.Rule) ([]*Example, error) {
var files []string
if check.Terraform != nil {
files = append(files, check.Terraform.BadExamples...)
// files = append(files, check.Terraform.GoodExamples...)
}

if check.CloudFormation != nil {
files = append(files, check.CloudFormation.BadExamples...)
// files = append(files, check.CloudFormation.GoodExamples...)
}

var res []*Example

if check.RegoPackage != "" {
for _, path := range files {
exmpls, err := parseExamplesFromFile(path)
if err != nil {
return nil, err
}

res = append(res, exmpls...)
}
}

return res, nil
}

func parseExamplesFromFile(filename string) ([]*Example, error) {
r, err := trivy_checks.EmbeddedPolicyFileSystem.Open(filename)
if err != nil {
return nil, err
}

fset := token.NewFileSet()
f, err := parser.ParseFile(fset, filename, r, parser.AllErrors)
if err != nil {
return nil, err
}
return extractExamples(f, filename), nil
}

func extractExamples(f *goast.File, filename string) (res []*Example) {
goast.Inspect(f, func(n goast.Node) bool {
valueSpec, ok := n.(*goast.ValueSpec)
if !ok {
return true
}

for _, id := range valueSpec.Names {
if !isExampleName(id.Name) {
continue
}

if compositeLit, ok := valueSpec.Values[0].(*goast.CompositeLit); ok {
for _, e := range compositeLit.Elts {
if basicLit, ok := e.(*goast.BasicLit); ok {
res = append(res, &Example{
Path: filename,
GoodExample: strings.HasSuffix(id.Name, "GoodExamples"),
Provider: providerByFileName(filename),
Content: cleanupExample(basicLit.Value),
})
}
}
}
}
return true
})

return res
}

func isExampleName(name string) bool {
return strings.HasSuffix(name, "GoodExamples") || strings.HasSuffix(name, "BadExamples")
}

func cleanupExample(s string) string {
return strings.ReplaceAll(s, "`", "")
}
Loading

0 comments on commit 12c64dd

Please sign in to comment.