#!/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_extra7107="7.107"
CHECK_TITLE_extra7107="[extra7107] Check if Amazon SageMaker Training jobs have intercontainer encryption enabled"
CHECK_SCORED_extra7107="NOT_SCORED"
CHECK_CIS_LEVEL_extra7107="EXTRA"
CHECK_ASFF_RESOURCE_TYPE_extra7107="AwsSageMakerNotebookInstance"
CHECK_ALTERNATE_check7107="extra7107"
CHECK_SEVERITY_extra7107="Medium"
CHECK_SERVICENAME_extra7107="sagemaker"
CHECK_RISK_extra7107='If not restricted unintended access could happen.'
CHECK_REMEDIATION_extra7107='Internetwork communications support TLS 1.2 encryption between all components and clients.'
CHECK_DOC_extra7107='https://docs.aws.amazon.com/sagemaker/latest/dg/interface-vpc-endpoint.html'
CHECK_CAF_EPIC_extra7107='Data Protection'

extra7107(){
    for regx in ${REGIONS}; do
        LIST_SM_NB_JOBS=$($AWSCLI $PROFILE_OPT --region $regx sagemaker list-training-jobs --query 'TrainingJobSummaries[*].TrainingJobName' --output text 2>&1)
        if [[ $(echo "$LIST_SM_NB_JOBS" | grep -E 'AccessDenied|UnauthorizedOperation|AuthorizationError') ]]; then
            textInfo "$regx: Access Denied trying to list training jobs" "$regx"
            continue
        fi
        if [[ $LIST_SM_NB_JOBS ]];then 
            for nb_job_name in $LIST_SM_NB_JOBS; do
                SM_NB_INTERCONTAINERENCRYPTION=$($AWSCLI $PROFILE_OPT --region $regx sagemaker describe-training-job --training-job-name $nb_job_name --query 'EnableInterContainerTrafficEncryption' --output text)
                if [[ $SM_NB_INTERCONTAINERENCRYPTION == "False" ]]; then
                    textFail "${regx}: SageMaker Training job $nb_job_name has intercontainer encryption disabled" "${regx}" "$nb_job_name"
                else
                    textPass "${regx}: SageMaker Training jobs $nb_job_name has intercontainer encryption enabled" "${regx}" "$nb_job_name"
                fi 
            done
        else 
            textInfo "${regx}: No Sagemaker Training found" "${regx}"
        fi 
    done
}
	