#!/usr/bin/env bash

# Prowler - the handy cloud security tool (copyright 2018) by Toni de la Fuente
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed
# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.

# Remediation:
#
#   https://docs.aws.amazon.com/AmazonECR/latest/userguide/lp_creation.html
#
#   aws ecr put-lifecycle-policy \
#      --repository-name repository-name \
#      --lifecycle-policy-text file://policy.json

CHECK_ID_extra7194="7.194"
CHECK_TITLE_extra7194="[extra7194] Check if ECR repositories have lifecycle policies enabled"
CHECK_SCORED_extra7194="NOT_SCORED"
CHECK_CIS_LEVEL_extra7194="EXTRA"
CHECK_SEVERITY_extra7194="Low"
CHECK_ALTERNATE_check776="extra7194"
CHECK_SERVICENAME_extra7194="ecr"
CHECK_ASFF_RESOURCE_TYPE_extra7194="AwsEcrRepository"
CHECK_RISK_extra7194='Amazon ECR repositories run the risk of retaining huge volumes of images, increasing unnecessary cost.'
CHECK_REMEDIATION_extra7194='Open the Amazon ECR console. Create an ECR lifecycle policy.'
CHECK_DOC_extra7194='https://docs.aws.amazon.com/AmazonECR/latest/userguide/LifecyclePolicies.html'
CHECK_CAF_EPIC_extra7194=''

extra7194(){
  for region in ${REGIONS}; do
    # List ECR repositories
    LIST_ECR_REPOS=$(${AWSCLI} ecr describe-repositories ${PROFILE_OPT} --region "${region}" --query "repositories[*].[repositoryName]" --output text 2>&1)
    # Handle authorization errors
    if grep -q -E 'AccessDenied|UnauthorizedOperation|AuthorizationError|Could not connect to the endpoint URL' <<< "${LIST_ECR_REPOS}"; then
      textInfo "${region}: Access Denied trying to describe ECR repositories" "${region}"
      continue
    fi
    if [[ -n "${LIST_ECR_REPOS}" ]]; then
      for repo in ${LIST_ECR_REPOS}; do
        # Check if a lifecycle policy exists
        LIFECYCLE_POLICY=$($AWSCLI ecr get-lifecycle-policy ${PROFILE_OPT} --region "${region}" --repository-name "${repo}" --query "repositoryName" --output text 2>&1)
        if grep -q -E 'AccessDenied|UnauthorizedOperation|AuthorizationError|Could not connect to the endpoint URL' <<< "${LIFECYCLE_POLICY}"; then
          textInfo "${region}: Access Denied trying to get lifecycle policy from repository: ${repo}" "${region}"
          continue
        elif grep -q -E 'LifecyclePolicyNotFoundException' <<< "$LIFECYCLE_POLICY"; then
          textFail "${region}: ECR repository ${repo} has no lifecycle policy" "${region}" "${repo}"
        else
          textPass "${region}: ECR repository ${repo} has a lifecycle policy" "${region}" "${repo}"
        fi
      done
    else
      textPass "${region}: No ECR repositories found" "${region}"
    fi
  done
}
