#!/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.
CHECK_ID_extra77="7.7,7.07"
CHECK_TITLE_extra77="[extra77] Ensure there are no ECR repositories set as Public (Not Scored) (Not part of CIS benchmark)"
CHECK_SCORED_extra77="NOT_SCORED"
CHECK_TYPE_extra77="EXTRA"
CHECK_ALTERNATE_extra707="extra77"
CHECK_ALTERNATE_check77="extra77"
CHECK_ALTERNATE_check707="extra77"

extra77(){
  # "Ensure there are no ECR repositories set as Public (Not Scored) (Not part of CIS benchmark)"
  textInfo "Looking for ECR repos in all regions...  "
  for regx in $REGIONS; do
    LIST_OF_ECR_REPOS=$($AWSCLI ecr describe-repositories $PROFILE_OPT --region $regx --query 'repositories[*].{Name:repositoryName}' --output text)
    for ecr_repo in $LIST_OF_ECR_REPOS; do
      TEMP_POLICY_FILE=$(mktemp -t prowler-${ACCOUNT_NUM}-ecr-repo.policy.XXXXXXXXXX)
      $AWSCLI ecr get-repository-policy --repository-name $ecr_repo $PROFILE_OPT --region $regx --output text > $TEMP_POLICY_FILE 2> /dev/null
      # check if the policy has Principal as *
      CHECK_ECR_REPO_ALLUSERS_POLICY=$(cat $TEMP_POLICY_FILE | awk -v k="text" '{n=split($0,a,","); for (i=1; i<=n; i++) print a[i]}' | awk '/Principal/ && !skip { print } { skip = /Deny/} '|grep \"Principal|grep \*)
      if [[ $CHECK_ECR_REPO_ALLUSERS_POLICY ]];then
        textFail "$regx: $ecr_repo policy \"may\" allow Anonymous users to perform actions (Principal: \"*\")" "$regx"
      else
        textPass "$regx: $ecr_repo is not open" "$regx"
      fi
    done
    rm -fr $TEMP_POLICY_FILE
  done
}
