#!/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.


# It checks -p optoin first and use it as profile, if not -p provided then
# check environment variables and if not, it checks and loads credentials from
# instance profile (metadata server) if runs in an EC2 instance

aws_profile_loader() {
    INSTANCE_PROFILE=$(curl -s -m 1 http://169.254.169.254/latest/meta-data/iam/security-credentials/)
    if echo "$INSTANCE_PROFILE" | grep -q '404 - Not Found'; then
        INSTANCE_PROFILE=
    fi

    if [[ $PROFILE ]]; then
    PROFILE_OPT="--profile $PROFILE"
    elif [[ $AWS_ACCESS_KEY_ID && $AWS_SECRET_ACCESS_KEY || $AWS_SESSION_TOKEN || $AWS_PROFILE ]];then
        PROFILE="$AWS_PROFILE"
        PROFILE_OPT=""
    # AWS_CONTAINER_CREDENTIALS_RELATIVE_URI is set by default https://docs.aws.amazon.com/sdkref/latest/guide/feature-container-credentials.html
    elif [[ -n $AWS_CONTAINER_CREDENTIALS_RELATIVE_URI ]] && [[ -z $INSTANCE_PROFILE ]]
    then
        PROFILE="INSTANCE-PROFILE"
        set_metadata_credentials "169.254.170.2${AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}"
    elif [[ $AWS_WEB_IDENTITY_TOKEN_FILE ]]; then
        PROFILE=""
        PROFILE_OPT=""
    elif [[ $INSTANCE_PROFILE ]]
    then
        PROFILE="INSTANCE-PROFILE"
        set_metadata_credentials "http://169.254.169.254/latest/meta-data/iam/security-credentials/${INSTANCE_PROFILE}"
    elif [[ $AWS_EXECUTION_ENV == "CloudShell" ]]
    then
        PROFILE_OPT=""
    else
        PROFILE="default"
        PROFILE_OPT="--profile $PROFILE"
    fi
    # Backing up $PROFILE_OPT needed to renew assume_role
    PROFILE_OPT_BAK=$PROFILE_OPT
    # Set default region by aws config, fall back to us-east-1
    REGION_CONFIG=$(aws configure get region)
    if [[ $REGION_OPT ]]; then
        REGION="$REGION_OPT"
    elif [[ $REGION_CONFIG ]]; then
        REGION="$REGION_CONFIG"
    else
        REGION="us-east-1"
    fi
}

# Function to get all regions
get_regions() {
  # Get list of regions based on include/whoami
  if ! REGIONS=$($AWSCLI ec2 describe-regions \
            --query 'Regions[].RegionName' \
            --output text ${PROFILE_OPT} \
            --region "${REGION_FOR_STS}" \
            --region-names ${FILTERREGION//[,]/ } 2>&1)
  then
    echo "$OPTRED Access Denied trying to describe regions! Review permissions as described here: https://github.com/prowler-cloud/prowler/#requirements-and-installation $OPTNORMAL"
    EXITCODE=1
    exit $EXITCODE
  fi
}

# Function to set metadata credentials
set_metadata_credentials() {
    INSTANCE_METADATA_URI="${1}"
    INSTANCE_METADATA=$(curl -s "${INSTANCE_METADATA_URI}")
    AWS_ACCESS_KEY_ID=$(jq -r '.AccessKeyId' <<< "${INSTANCE_METADATA}")
    export AWS_ACCESS_KEY_ID
    AWS_SECRET_ACCESS_KEY=$(jq -r '.SecretAccessKey' <<< "${INSTANCE_METADATA}")
    export AWS_SECRET_ACCESS_KEY
    AWS_SESSION_TOKEN=$(jq -r '.Token' <<< "${INSTANCE_METADATA}")
    export AWS_SESSION_TOKEN
    ASSUME_AWS_SESSION_EXPIRATION=$(jq -r '.Expiration | sub("\\+00:00";"Z") | fromdateiso8601' <<< "${INSTANCE_METADATA}")
    export AWS_SESSION_EXPIRATION=$ASSUME_AWS_SESSION_EXPIRATION
}
