#!/usr/bin/env bash

# Prowler - the handy cloud security tool (copyright 2020) 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_extra786="7.86"
CHECK_TITLE_extra786="[extra786] Check if EC2 Instance Metadata Service Version 2 (IMDSv2) is Enabled and Required "
CHECK_SCORED_extra786="NOT_SCORED"
CHECK_CIS_LEVEL_extra786="EXTRA"
CHECK_SEVERITY_extra786="Medium"
CHECK_ASFF_RESOURCE_TYPE_extra786="AwsEc2Instance"
CHECK_ALTERNATE_check786="extra786"
CHECK_SERVICENAME_extra786="ec2"
CHECK_RISK_extra786='Using IMDSv2 will protect from misconfiguration and SSRF vulnerabilities. IMDSv1 will not.'
CHECK_REMEDIATION_extra786='If you don’t need IMDS you can turn it off. Using aws-cli you can force the instance to use only IMDSv2.'
CHECK_DOC_extra786='https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html#configuring-instance-metadata-options'
CHECK_CAF_EPIC_extra786='Infrastructure Security'

extra786(){
  for regx in $REGIONS; do
    TEMP_EXTRA786_FILE=$(mktemp -t prowler-${ACCOUNT_NUM}-es-domain.EXTRA786.XXXXXXXXXX)
    $AWSCLI ec2 describe-instances $PROFILE_OPT --region $regx \
      --query 'Reservations[*].Instances[*].{HttpTokens:MetadataOptions.HttpTokens,HttpEndpoint:MetadataOptions.HttpEndpoint,InstanceId:InstanceId}' \
      --output text --max-items $MAXITEMS > $TEMP_EXTRA786_FILE 2>&1
    if [[ $(cat $TEMP_EXTRA786_FILE | grep -E 'AccessDenied|UnauthorizedOperation|AuthorizationError') ]]; then
        textInfo "$regx: Access Denied trying to describe instances" "$regx"
        continue
    fi
    # if the file contains data, there are instances in that region
    if [[ -s "$TEMP_EXTRA786_FILE" ]];then
      # here we read content from the file fields instanceid httptokens_status httpendpoint
      while read httpendpoint httptokens_status instanceid  ; do
        #echo i:$instanceid tok:$httptokens_status end:$httpendpoint
        if [[ "$httpendpoint" == "enabled" &&  "$httptokens_status" == "required" ]];then
          textPass "$regx: EC2 Instance $instanceid has IMDSv2 enabled and required" "$regx" "$instanceid"
        elif [[ "$httpendpoint" == "disabled" ]];then
          textInfo "$regx: EC2 Instance $instanceid has HTTP endpoint access to metadata service disabled" "$regx"
        else
          textFail "$regx: EC2 Instance $instanceid has IMDSv2 disabled or not required" "$regx" "$instanceid"
        fi
      done < <(cat $TEMP_EXTRA786_FILE)
    else
     textInfo "$regx: no EC2 Instances found" "$regx"
    fi
    rm -fr $TEMP_EXTRA786_FILE
  done
}

# Remediation:

# aws ec2 modify-instance-metadata-options \
#     --instance-id i-1234567898abcdef0 \
#     --http-tokens required \
#     --http-endpoint enabled

# More information here https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html
