AWS_EN

Enable image scanning at ECR registry level

スポンサーリンク
Enable image scanning at ECR registry level AWS_EN
スポンサーリンク
スポンサーリンク

Enable image scanning at ECR registry level

One of the features provided by the ECR repository is image scanning.

Amazon ECR image scanning helps in identifying software vulnerabilities in your container images.

Image scanning

In this case, we will enable image scanning at the ECR registry level.

The recommended procedure for activating image scanning is the one described in this article.
You can also enable image scanning at the ECR repository level as described in the following page, but this method is currently deprecated.

Environment

Diagram of enable image scanning at ECR registry level.

Create a CloudFormation stack and define two resources inside it.

The first is the ECR.
Push images to this repository.

The second is a Lambda function.
This function is configured as a CloudFormation custom resource.
The function’s job is to enable image scanning at the registry level.
The runtime for the function is Python 3.8.
By setting up a CloudFormation custom resource, this function can be run when the CloudFormation stack is created.

CloudFormation template files

Build the above configuration with CloudFormation.
The CloudFormation templates are located at the following URL

https://github.com/awstut-an-r/awstut-fa/tree/main/083

Explanation of key points of template files

This page focuses on how to enable scanning during image push at the registry level.

For basic information on CloudFormation custom resources, please refer to the following page

For information on how to use CloudFormation custom resources to automatically delete images in the ECR repository upon CloudFormation stack deletion, please check the following page

ECR

Resources:
  ECRRepository:
    Type: AWS::ECR::Repository
    Properties: 
      RepositoryName: !Ref Prefix
Code language: YAML (yaml)

Create an ECR repository.
No special configuration is required.

CloudFormation Custom Resources

Custom Resources

Resources:
  CustomResource:
    Type: Custom::CustomResource
    Properties:
      ServiceToken: !GetAtt ECRFunction.Arn
Code language: YAML (yaml)

The ARN of the Lambda function described below is specified in the ServiceToken property.
This setting will cause the function to be invocated each time the CloudFormation stack is operated.

Lambda function

Resources:
  ECRFunction:
    Type: AWS::Lambda::Function
    Properties:
      Code:
        ZipFile: |
          import boto3
          import cfnresponse
          import os
          
          account_id = os.environ['ACCOUNT_ID']
          ecr_repository_name = os.environ['ECR_REPOSITORY_NAME']
          
          ecr_client = boto3.client('ecr')
           
          CREATE = 'Create'
          DELETE = 'Delete'
          response_data = {}
          
          def lambda_handler(event, context):
            try:
              if event['RequestType'] == CREATE:
                put_response = ecr_client.put_registry_scanning_configuration(
                  scanType='BASIC',
                  rules=[
                    {
                      'scanFrequency': 'SCAN_ON_PUSH',
                      'repositoryFilters': [
                        {
                          'filter': ecr_repository_name,
                          'filterType': 'WILDCARD'
                        }
                      ]
                    }
                  ]
                )
                print(put_response)
            
              ...
              
              cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data)
              
            except Exception as e:
              print(e)
              cfnresponse.send(event, context, cfnresponse.FAILED, response_data)
      Environment:
        Variables:
          ACCOUNT_ID: !Ref AWS::AccountId
          ECR_REPOSITORY_NAME: !Ref ECRRepository
      FunctionName: !Sub "${Prefix}-function-ecr"
      Handler: !Ref Handler
      Runtime: !Ref Runtime
      Role: !GetAtt ECRFunctionRole.Arn
Code language: YAML (yaml)

There are no special settings for the function itself.
The environment variable is the key point.
The necessary parameters (repository name and account ID) are passed to the function as environment variables.

Refer to the value of event[‘RequestType’] to implement the processing according to the stack operation.
In this case, this process is executed when the stack is created.
So we will use an if statement so that the following process will be executed when this value is “Create”.

  • Create a client object for ECR with boto3.
  • Enable image scanning of the ECR registry in the put_registry_scanning_configuration method.

For more information on the put_registry_scanning_configuration method, please see the following

ECR - Boto3 1.28.57 documentation

This time, we will configure the aforementioned ECR repository to perform a basic scan when pushing images.
Please also refer to the API Reference for the parameters in executing this method.

GetRegistryScanningConfiguration - Amazon Elastic Container Registry
Retrieves the scanning configuration for a registry.

Here is a quick rundown of the parameters.
scanType is set to “BASIC” to perform a basic scan.
Set the target and frequency of scans to be performed in rules.
Set scanFrequency to “SCAN_ON_PUSH” to perform a scan when an image is pushed.
Set the scan target in repositoryFilters.
Specify the name of the repository to be scanned in “filter”. In this case, set the aforementioned ECR repository name.
For filterType, set “WILDCARD”. This value is fixed.

Check the IAM role for this Lambda function.

Resources:
  ECRFunctionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action: sts:AssumeRole
            Principal:
              Service:
                - lambda.amazonaws.com
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
      Policies:
        - PolicyName: !Sub "${Prefix}-ECRDeleteImagesPolicy"
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - ecr:PutRegistryScanningConfiguration
                Resource: "*"
              ...
Code language: YAML (yaml)

Allow ecr:PutRegistryScanningConfiguration.

(Reference) Dockerfile

FROM amazonlinuxCode language: Dockerfile (dockerfile)

Create your own image based on Amazon Linux 2.

Architecting

Use CloudFormation to build this environment and check the actual behavior.

Create CloudFormation stacks and check resources in stacks

Create a CloudFormation stacks.
For information on how to create stacks and check each stack, please refer to the following page

After checking the resources in each stack, information on the main resources created this time is as follows

  • ECR repository: fa-083

Check the created resources from the AWS Management Console.
Check the execution result of the Lambda function for the CloudFormation custom resource.

Detail of Custom Resource Lambda Function Invocation 1.

You can see that the put_registry_scanning_configuration method was executed when the stack was created.

Next, check the ECR registry.

Detail of ECR Registry 1.

Scan configuration shows that basic scan has been enabled for the fa-083 repository.

Next, check the ECR repository.

Detail of ECR Registry 2.

The Scan frequency item is listed as “Scan on push”.
We can see that image scanning is enabled.

Next, check the repository details.

Detail of ECR Registry 3.

Looking at the Image scan settings, we see that this item is set to Disabled.
This means that image scanning is disabled at the repository level, but enabled at the registry level.

Check Action

Now that we are ready, we can push the image to this repository.
To push, execute the following command

Detail of ECR Registry 4.

After pushing the image, check the repository again.

Detail of ECR Registry 5.

The Scan status item is “Complete.
This indicates that the scan was performed automatically when the image was pushed.

Check the “details” under Vulnerabilities.

Detail of ECR Registry 6.

The detected vulnerabilities are displayed with their severity.

Thus, we have confirmed that by enabling scan on push at the ECR registry level, images can be scanned automatically.

Summary

We have confirmed how to enable scan on push at the ECR registry level and its effectiveness.

タイトルとURLをコピーしました