#!/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_extra790="7.90"
CHECK_TITLE_extra790="[extra790] Find trust boundaries in VPC endpoint services whitelisted principles"
CHECK_SCORED_extra790="NOT_SCORED"
CHECK_CIS_LEVEL_extra790="EXTRA"
CHECK_SEVERITY_extra790="Medium"
CHECK_ASFF_RESOURCE_TYPE_extra790="AwsEc2Vpc"
CHECK_ALTERNATE_extra790="extra790"
CHECK_SERVICENAME_extra790="vpc"
CHECK_RISK_extra790='Account VPC could be linked to other accounts.'
CHECK_REMEDIATION_extra790='In multi Account environments identify untrusted links. Check trust chaining and dependencies between accounts.'
CHECK_DOC_extra790='https://github.com/toniblyx/prowler/#trust-boundaries-checks'
CHECK_CAF_EPIC_extra790='Infrastructure Security'

extra790(){
    TRUSTED_ACCOUNT_IDS=$( echo "${ACCOUNT_NUM} ${GROUP_TRUSTBOUNDARIES_TRUSTED_ACCOUNT_IDS}" | xargs )

    for regx in ${REGIONS}; do
        ENDPOINT_SERVICES_IDS=$(${AWSCLI} ec2 describe-vpc-endpoint-services \
                                ${PROFILE_OPT} \
                                --query "ServiceDetails[?Owner=='${ACCOUNT_NUM}'].ServiceId" \
                                --region ${regx} \
                                --output text | xargs 2>&1)
    if [[ $(echo "$ENDPOINT_SERVICES_IDS" | grep -E 'AccessDenied|UnauthorizedOperation|AuthorizationError') ]]; then
        textInfo "$regx: Access Denied trying to describe VPC endpoint services" "$regx"
        continue
    fi

        for ENDPOINT_SERVICE_ID in ${ENDPOINT_SERVICES_IDS}; do
            ENDPOINT_PERMISSIONS_LIST=$(${AWSCLI} ec2 describe-vpc-endpoint-service-permissions \
                                        ${PROFILE_OPT} \
                                        --service-id ${ENDPOINT_SERVICE_ID} \
                                        --query "AllowedPrincipals[*].Principal" \
                                        --region ${regx} \
                                        --output text | xargs
                                        )

            for ENDPOINT_PERMISSION in ${ENDPOINT_PERMISSIONS_LIST}; do
                # Take only account id from ENDPOINT_PERMISSION: arn:aws:iam::965406151242:root
                ENDPOINT_PERMISSION_ACCOUNT_ID=$(echo ${ENDPOINT_PERMISSION} | cut -d':' -f5 | xargs)

                for ACCOUNT_ID in ${TRUSTED_ACCOUNT_IDS}; do
                    if [[ "${ACCOUNT_ID}" == "${ENDPOINT_PERMISSION_ACCOUNT_ID}" ]]; then
                        textPass "${regx}: Found trusted account in VPC endpoint service permission ${ENDPOINT_PERMISSION}" "${regx}"
                        # Algorithm:
                        # Remove all trusted ACCOUNT_IDs from ENDPOINT_PERMISSIONS_LIST.
                        # As a result, the ENDPOINT_PERMISSIONS_LIST finally contains only unknown/untrusted account ids.
                        ENDPOINT_PERMISSIONS_LIST=("${ENDPOINT_PERMISSIONS_LIST[@]/$ENDPOINT_PERMISSION}")
                    fi
                done
            done

            for UNTRUSTED_PERMISSION in ${ENDPOINT_PERMISSIONS_LIST}; do
                textFail "${regx}: Found untrusted account in VPC endpoint service permission ${UNTRUSTED_PERMISSION}" "${regx}" "${UNTRUSTED_PERMISSION}"
            done
        done
    done
}
