Skip to content

Infrastructure‐as‐Code Scanning

Nuthan Munaiah edited this page Mar 29, 2024 · 2 revisions

The advancedsecurity.iac-tasks extension to Azure DevOps contributes custom tasks to install the following infrastructure-as-code scanning tools, analyze infrastructure-as-code repositories with the tools, and publish any issues found to Advanced Security.

  1. Template Analyzer
  2. Terrascan
  3. Trivy

Tasks Configuration

The extension contains three custom tasks: TemplateAnalyzerSarif, TerrascanSarif, and TrivySarif. The subsections that follow describe the configuration for these three tasks.

A minimal pipeline that uses all three of these custom tasks is shown below.

trigger:
- main

pool:
  name: Default
  vmImage: 'windows-latest'

jobs:
- job: 'AdvancedSecurity'
  displayName: IaC Scanning with Advanced Security
  steps:
    - task: TemplateAnalyzerSarif@1
      displayName: Run Template Analyzer
    - task: TerrascanSarif@1
      displayName: Run Terrascan
    - task: TrivySarif@1
      displayName: Run Trivy
    - task: AdvancedSecurity-Publish@1
      displayName: Publish IaC Scanning Results to Advanced Security

TemplateAnalyzerSarif Configuration

 - task: TemplateAnalyzerSarif@1
   inputs:
   #  ConfigurationFilePath: string. Optional. Path to `*.gdnconfig` file to configure the behavior of Template Analyzer.
   #  FailStepOnErrors: boolean. Optional. If true, the build step is marked are failed if Template Analyzer finds any error-level issues. Default: false.
   env:
   #  Optional. Environment variable configuration.

TerrascanSarif Configuration

 - task: TerrascanSarif@1
   inputs:
   #  ConfigurationFilePath: string. Optional. Path to `*.gdnconfig` file to configure the behavior of Terrascan.
   #  FailStepOnErrors: boolean. Optional. If true, the build step is marked are failed if Terrascan finds any error-level issues. Default: false.
   env:
   #  Optional. Environment variable configuration.

TrivySarif Configuration

 - task: TrivySarif@1
   inputs:
   #  ConfigurationFilePath: string. Optional. Path to `*.gdnconfig` file to configure the behavior of Trivy.
   #  FailStepOnErrors: boolean. Optional. If true, the build step is marked are failed if Trivy finds any error-level issues. Default: false.
   env:
   #  Optional. Environment variable configuration.

Tool Configuration

The three infrastructure-as-code scanning tools that the tasks run may be configured using environment variables or by specifying the path to a *.gdnconfig containing the configurations. In the subsections that follow, both the environment variables that may be used to configure each tool and a sample *.gdnconfig file are presented.

Template Analyzer

The environment variables that may be used to configure Template Analyzer as listed in the table shown below.

Argument name Environment variable name Description
AnalyzeDirectory GDN_TEMPLATEANALYZER_ANALYZEDIRECTORY Recursively searches for and analyzes all ARM templates in a directory with the set of preconfigured rules
AnalyzeTemplate GDN_TEMPLATEANALYZER_ANALYZETEMPLATE Analyzes an ARM template with the set of preconfigured rules
ParametersFilePath GDN_TEMPLATEANALYZER_PARAMETERSFILEPATH File path of parameters file to use when scanning a template (optional)
Verbose GDN_TEMPLATEANALYZER_VERBOSE Shows details about the analysis
ReportFormat GDN_TEMPLATEANALYZER_REPORTFORMAT Report format (console, sarif)
IncludeNonSecurityRules GDN_TEMPLATEANALYZER_INCLUDENONSECURITYRULES Run all the rules against the templates, including non-security rules
Help GDN_TEMPLATEANALYZER_HELP Output command line help information for the Template BPA CLI

A sample *.gdnconfig file to configure Template Analyzer is shown below.

{
  "tools": [
    {
      "tool": {
        "name": "TemplateAnalyzer",
        "version": "Latest"
      },
      "arguments": {
        "AnalyzeDirectory": "$(WorkingDirectory)",
        "AnalyzeTemplate": "",
        "ParametersFilePath": "",
        "Verbose": "true",
        "ReportFormat": "sarif",
        "IncludeNonSecurityRules": "true",
        "Help": ""
      }
    }
  ]
}

Terrascan

The environment variables that may be used to configure Terrascan as listed in the table shown below.

Argument name Environment variable name Description
Init GDN_TERRASCAN_INIT Initializes Terrascan and clones policies from the Terrascan GitHub repository
Scan GDN_TERRASCAN_SCAN Detect compliance and security violations across Infrastructure as Code
Server GDN_TERRASCAN_SERVER Run Terrascan as an API server
Version GDN_TERRASCAN_VERSION Terrascan version
ConfigPath GDN_TERRASCAN_CONFIGPATH Format supported is *.TOML
LogLevel GDN_TERRASCAN_LOGLEVEL Log level (debug, info, warn, error, panic, fatal) (default 'info')
LogType GDN_TERRASCAN_LOGTYPE Log output type (console, json) (default 'console')
OutputType GDN_TERRASCAN_OUTPUTTYPE Output type (human, json, yaml, xml, junit-xml, sarif) (default 'sarif')
Categories GDN_TERRASCAN_CATEGORIES List of categories of violations to be reported by terrascan (example: --categories='category1,category2')
ConfigOnly GDN_TERRASCAN_CONFIGONLY Will output resource config (should only be used for debugging purposes)
FindVuln GDN_TERRASCAN_FINDVULN Fetches vulnerabilities identified in Docker images
Help GDN_TERRASCAN_HELP
IacDir GDN_TERRASCAN_IACDIR Path to a directory containing one or more IaC files (default '.'')
IacFile GDN_TERRASCAN_IACFILE Path to a single IaC file
IacType GDN_TERRASCAN_IACTYPE Iac type (arm, cft, docker, helm, k8s, kustomize, terraform, tfplan)
IacVersion GDN_TERRASCAN_IACVERSION Iac version (arm: v1, cft: v1, docker: v1, helm: v3, k8s: v1, kustomize: v2, v3, v4, terraform: v12, v13, v14, v15, tfplan: v1)
NonRecursive GDN_TERRASCAN_NONRECURSIVE Do not scan directories and modules recursively
PolicyPath GDN_TERRASCAN_POLICYPATH Policy path directory
PolicyType GDN_TERRASCAN_POLICYTYPE Policy type (all, aws, azure, gcp, github, k8s) (default [all])
RemoteType GDN_TERRASCAN_REMOTETYPE Type of remote backend (git, s3, gcs, http, terraform-registry)
RemoteUrl GDN_TERRASCAN_REMOTEURL Url pointing to remote IaC repository
ScanRules GDN_TERRASCAN_SCANRULES One or more rules to scan (example: --scan-rules='ruleID1,ruleID2')
Severity GDN_TERRASCAN_SEVERITY Minimum severity level of the policy violations to be reported by terrascan
ShowPassed GDN_TERRASCAN_SHOWPASSED Display passed rules, along with violations
SkipRules GDN_TERRASCAN_SKIPRULES One or more rules to skip while scanning (example: --skip-rules='ruleID1,ruleID2')
UseColors GDN_TERRASCAN_USECOLORS Color output (auto, t, f) (default 'auto')
UseTerraformCache GDN_TERRASCAN_USETERRAFORMCACHE Use terraform init cache for remote modules (when used directory scan will be non recursive,flag applicable only with terraform IaC provider)
Verbose GDN_TERRASCAN_VERBOSE Will show violations with details (applicable for default output)

A sample *.gdnconfig file to configure Terrascan is shown below.

{
  "tools": [
    {
      "tool": {
        "name": "Terrascan",
        "version": "Latest"
      },
      "arguments": {
        "Init": "",
        "Scan": "scan",
        "Server": "",
        "Version": "",
        "ConfigPath": "",
        "LogLevel": "",
        "LogType": "",
        "OutputType": "sarif",
        "Categories": "",
        "ConfigOnly": "",
        "FindVuln": "",
        "Help": "",
        "IacDir": "$(WorkingDirectory)",
        "IacFile": "",
        "IacType": "",
        "IacVersion": "",
        "NonRecursive": "",
        "PolicyPath": "",
        "PolicyType": "",
        "RemoteType": "",
        "RemoteUrl": "",
        "ScanRules": "",
        "Severity": "",
        "ShowPassed": "",
        "SkipRules": "",
        "UseColors": "auto",
        "UseTerraformCache": "",
        "Verbose": ""
      }
    }
  ]
}

Trivy

The environment variables that may be used to configure Trivy as listed in the table shown below.

Argument name Environment variable name Description
Action GDN_TRIVY_ACTION The type of resource you would like to scan. The default is filesystem which scans local resources. Other options include image, repository, client, server.
Target GDN_TRIVY_TARGET Target of scan. For the default action (filesystem), a directory.
ExitCode GDN_TRIVY_EXITCODE Exit code to use if errors are detected. This must stay 100.
Quiet GDN_TRIVY_QUIET Suppress progress bar and log output.
Debug GDN_TRIVY_DEBUG Enable verbose debug output.
CacheDirectory GDN_TRIVY_CACHEDIRECTORY Directory for storing Trivy cache data.
OutputTemplate GDN_TRIVY_OUTPUTTEMPLATE A template to modify the output format. Output format must be set to template for this to work. The default behavior uses this option and a provided template to produce SARIF. If providing a filename, prpend @.
TableFormat GDN_TRIVY_TABLEFORMAT Format for the results output. Template is preferred by Guardian to produce SARIF, but this requires an output template to be selected as well. Other options include JSON and text.
ImagePath GDN_TRIVY_IMAGEPATH Path to image instead of image name. This is only useful if using the image scan type. See also: https://github.com/aquasecurity/trivy#scan-an-oci-image
Severities GDN_TRIVY_SEVERITIES Severities to display. Available options are: UNKNOWN, LOW, MEDIUM, HIGH, CRITICAL. Warning: this is not a threshold and all desired severities must be listed. The default is to include all findings.
OutputPath GDN_TRIVY_OUTPUTPATH Path of output file.
SkipDBUpdate GDN_TRIVY_SKIPDBUPDATE Skip the database update step.
IgnoreUnfixed GDN_TRIVY_IGNOREUNFIXED Ignore issues that aren't known to be fixed.
RemovedPKGS GDN_TRIVY_REMOVEDPKGS detect vulnerabilities of removed packages (only for Alpine)
VulnTypes GDN_TRIVY_VULNTYPES Vulnerability types to display. Options are: os, library. The default is to display both of these.
IgnoreFile GDN_TRIVY_IGNOREFILE Path to a Trivy ignorefile. See the tool documentation at: https://github.com/aquasecurity/trivy
Timeout GDN_TRIVY_TIMEOUT Timeout for Docker operations in the format 5m0s. The default is five minutes.
LightMode GDN_TRIVY_LIGHTMODE light mode: it's faster, but vulnerability descriptions and references are not displayed.
IgnorePolicyPath GDN_TRIVY_IGNOREPOLICYPATH Path to a custom Rego file to evaluate each vulnerability. This feature is experimental. See also: https://github.com/aquasecurity/trivy#filter-the-vulnerabilities-by-open-policy-agent-policy
ListAllPackages GDN_TRIVY_LISTALLPACKAGES List all packages used, whether they have vulnerabilities or not.
SkipFiles GDN_TRIVY_SKIPFILES Paths to files to skip. If you wish to ignore entire directories, use the skip directories option. This does not support complex matching patterns.
SkipDirectories GDN_TRIVY_SKIPDIRECTORIES Paths to directories to ignore. If you wish to ignore single files while scanning others in the same directory, use the skip files option. This does not support complex matching patterns.
CacheBackend GDN_TRIVY_CACHEBACKEND Location of the cache backend resource. Does not work with client action.
ClientServerToken GDN_TRIVY_CLIENTSERVERTOKEN Token to authenticate to a server. Only works with client or server actions.
ClientServerTokenHeader GDN_TRIVY_CLIENTSERVERTOKENHEADER Header to use when sending or expecting the token to authenticate to a server. Only works with client or server actions.
ClientRemoteLocation GDN_TRIVY_CLIENTREMOTELOCATION URI of a Trivy server. Only works with client action.
ClientServerCustomHeaders GDN_TRIVY_CLIENTSERVERCUSTOMHEADERS Custom headers for a Trivy server. Only works with client or server actions.

A sample *.gdnconfig file to configure Trivy is shown below.

{
  "tools": [
    {
      "tool": {
        "name": "Trivy",
        "version": "Latest"
      },
      "arguments": {
        "Action": "filesystem",
        "Target": ".",
        "ExitCode": "100",
        "Quiet": "",
        "Debug": "",
        "CacheDirectory": "",
        "OutputTemplate": "@$(InstallDirectory)\\tools\\sarif.tpl",
        "TableFormat": "template",
        "ImagePath": "",
        "Severities": "",
        "OutputPath": "",
        "SkipDBUpdate": "",
        "IgnoreUnfixed": "",
        "RemovedPKGS": "",
        "VulnTypes": "",
        "IgnoreFile": "",
        "Timeout": "",
        "LightMode": "",
        "IgnorePolicyPath": "",
        "ListAllPackages": "",
        "SkipFiles": "",
        "SkipDirectories": "",
        "CacheBackend": "",
        "ClientServerToken": "",
        "ClientServerTokenHeader": "",
        "ClientRemoteLocation": "",
        "ClientServerCustomHeaders": ""
      }
    }
  ]
}