Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
134 changes: 132 additions & 2 deletions pkg/iac/adapters/terraform/azure/storage/adapt.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package storage

import (
"strings"

"github.com/aquasecurity/trivy/pkg/iac/providers/azure/storage"
"github.com/aquasecurity/trivy/pkg/iac/terraform"
iacTypes "github.com/aquasecurity/trivy/pkg/iac/types"
Expand Down Expand Up @@ -30,6 +32,13 @@ func Adapt(modules terraform.Modules) storage.Storage {
},
AccountReplicationType: iacTypes.StringDefault("", iacTypes.NewUnmanagedMetadata()),
InfrastructureEncryptionEnabled: iacTypes.BoolDefault(false, iacTypes.NewUnmanagedMetadata()),
DiagnosticLogging: storage.DiagnosticLogging{
Metadata: iacTypes.NewUnmanagedMetadata(),
Blob: iacTypes.BoolDefault(false, iacTypes.NewUnmanagedMetadata()),
File: iacTypes.BoolDefault(false, iacTypes.NewUnmanagedMetadata()),
Queue: iacTypes.BoolDefault(false, iacTypes.NewUnmanagedMetadata()),
Table: iacTypes.BoolDefault(false, iacTypes.NewUnmanagedMetadata()),
},
CustomerManagedKey: storage.CustomerManagedKey{
Metadata: iacTypes.NewUnmanagedMetadata(),
KeyVaultKeyId: iacTypes.StringDefault("", iacTypes.NewUnmanagedMetadata()),
Expand Down Expand Up @@ -87,7 +96,7 @@ func adaptAccounts(modules terraform.Modules) ([]storage.Account, []string, []st

for _, module := range modules {
for _, resource := range module.GetResourcesByType("azurerm_storage_account") {
account := adaptAccount(resource)
account := adaptAccount(resource, module)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Containers are looked up in adaptAccounts, and the diagnostic settings could be found there too instead of passing module to adaptAccount.

containerResource := module.GetReferencingResources(resource, "azurerm_storage_container", "storage_account_id")

if len(containerResource) == 0 {
Expand Down Expand Up @@ -161,7 +170,7 @@ func adaptAccounts(modules terraform.Modules) ([]storage.Account, []string, []st
return accounts, accountedForContainers, accountedForNetworkRules
}

func adaptAccount(resource *terraform.Block) storage.Account {
func adaptAccount(resource *terraform.Block, module *terraform.Module) storage.Account {
account := storage.Account{
Metadata: resource.GetMetadata(),
NetworkRules: nil,
Expand All @@ -182,13 +191,22 @@ func adaptAccount(resource *terraform.Block) storage.Account {
},
AccountReplicationType: resource.GetAttribute("account_replication_type").AsStringValueOrDefault("", resource),
InfrastructureEncryptionEnabled: resource.GetAttribute("infrastructure_encryption_enabled").AsBoolValueOrDefault(false, resource),
DiagnosticLogging: storage.DiagnosticLogging{
Metadata: resource.GetMetadata(),
Blob: iacTypes.BoolDefault(false, resource.GetMetadata()),
File: iacTypes.BoolDefault(false, resource.GetMetadata()),
Queue: iacTypes.BoolDefault(false, resource.GetMetadata()),
Table: iacTypes.BoolDefault(false, resource.GetMetadata()),
},
CustomerManagedKey: storage.CustomerManagedKey{
Metadata: resource.GetMetadata(),
KeyVaultKeyId: iacTypes.StringDefault("", resource.GetMetadata()),
UserAssignedIdentityId: iacTypes.StringDefault("", resource.GetMetadata()),
},
}

adaptDiagnosticLogging(module, resource, &account)

networkRulesBlocks := resource.GetBlocks("network_rules")
for _, networkBlock := range networkRulesBlocks {
account.NetworkRules = append(account.NetworkRules, adaptNetworkRule(networkBlock))
Expand Down Expand Up @@ -250,6 +268,118 @@ func adaptAccount(resource *terraform.Block) storage.Account {
return account
}

// diagnosticLogCategories are the Azure Monitor log categories that record
// storage requests. A diagnostic setting logs requests for a service when it
// enables one of these categories, or the allLogs category group.
var diagnosticLogCategories = []string{"StorageRead", "StorageWrite", "StorageDelete"}

// adaptDiagnosticLogging marks the storage services that log requests through
// an azurerm_monitor_diagnostic_setting resource, so the storage logging

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The part starting with "so the storage logging checks" is about the checks, not this function, and could be removed.

// checks can see logging configured via Azure Monitor instead of only
// Storage Analytics logging.
func adaptDiagnosticLogging(module *terraform.Module, accountResource *terraform.Block, account *storage.Account) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The other helpers here return a value and do not change the account through a pointer. This one could take the found settings and return storage.DiagnosticLogging. If diagnosticSettingService returned a pointer to the field, or nil, the string constants and the mark closure would not be needed.

for _, setting := range diagnosticSettingsForAccount(module, accountResource) {
if !diagnosticSettingLogsRequests(setting) {
continue
}
mark := func(dst *iacTypes.BoolValue) {
*dst = iacTypes.Bool(true, setting.GetMetadata())
}
switch diagnosticSettingService(setting) {
case "blob":
mark(&account.DiagnosticLogging.Blob)
case "file":
mark(&account.DiagnosticLogging.File)
case "queue":
mark(&account.DiagnosticLogging.Queue)
case "table":
mark(&account.DiagnosticLogging.Table)
case "account":
// A setting targeting the account itself applies to all its services.
mark(&account.DiagnosticLogging.Blob)
mark(&account.DiagnosticLogging.File)
mark(&account.DiagnosticLogging.Queue)
mark(&account.DiagnosticLogging.Table)
}
}
}

// diagnosticSettingsForAccount returns the diagnostic settings targeting the
// given storage account, either by referencing it in target_resource_id or by
// naming it in a literal target resource ID.
func diagnosticSettingsForAccount(module *terraform.Module, accountResource *terraform.Block) terraform.Blocks {
seen := make(map[string]bool)
var settings terraform.Blocks
add := func(block *terraform.Block) {
if block == nil || seen[block.ID()] {
return
}
seen[block.ID()] = true
settings = append(settings, block)
}

for _, setting := range module.GetReferencingResources(accountResource, "azurerm_monitor_diagnostic_setting", "target_resource_id") {
add(setting)
}

// A setting in another file may target the account with a literal resource

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

References work across files of one module. The literal ID is needed when the setting has no reference to the account at all.

// ID instead of a reference to the account block.
if name := accountResource.GetAttribute("name").AsStringValueOrDefault("", accountResource).Value(); name != "" {
accountID := "/storageaccounts/" + strings.ToLower(name)
for _, setting := range module.GetResourcesByType("azurerm_monitor_diagnostic_setting") {
target := strings.ToLower(setting.GetAttribute("target_resource_id").AsStringValueOrDefault("", setting).Value())
if strings.Contains(target, accountID+"/") || strings.HasSuffix(target, accountID) {
add(setting)
}
}
}

return settings
}

// diagnosticSettingService returns which storage service a diagnostic setting
// targets: blob, file, queue, table, or the account itself. An empty string
// means the target could not be determined and the setting is ignored.
func diagnosticSettingService(setting *terraform.Block) string {
target := setting.GetAttribute("target_resource_id").AsStringValueOrDefault("", setting).Value()
if target == "" {
return ""
}
target = strings.ToLower(strings.TrimRight(target, "/"))
switch {
case strings.HasSuffix(target, "/blobservices/default"):
return "blob"
case strings.HasSuffix(target, "/fileservices/default"):
return "file"
case strings.HasSuffix(target, "/queueservices/default"):
return "queue"
case strings.HasSuffix(target, "/tableservices/default"):
return "table"
default:
return "account"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Log categories like StorageRead and the allLogs group work only on service targets such as .../blobServices/default. A setting on the account itself supports only metrics, so Azure rejects it, but here it marks all four services as logging. A target that is not a service could be ignored.

}
}

// diagnosticSettingLogsRequests reports whether a diagnostic setting enables
// request logging: an enabled_log block with a StorageRead, StorageWrite or
// StorageDelete category, or with the allLogs category group. Metric blocks
// and other log categories do not count.
func diagnosticSettingLogsRequests(setting *terraform.Block) bool {
for _, logBlock := range setting.GetBlocks("enabled_log") {
if category := logBlock.GetAttribute("category"); category.IsNotNil() {
for _, want := range diagnosticLogCategories {
if category.Equals(want) {
return true
}
}
}
if group := logBlock.GetAttribute("category_group"); group.IsNotNil() && group.Equals("allLogs") {
return true
}
}
return false
}

func adaptContainer(resource *terraform.Block) storage.Container {
accessTypeAttr := resource.GetAttribute("container_access_type")
publicAccess := iacTypes.StringDefault(storage.PublicAccessOff, resource.GetMetadata())
Expand Down
Loading