#!/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_extra7111="7.111"
CHECK_TITLE_extra7111="[extra7111] Check if Amazon SageMaker Notebook instances have direct internet access"
CHECK_SCORED_extra7111="NOT_SCORED"
CHECK_CIS_LEVEL_extra7111="EXTRA"
CHECK_ASFF_RESOURCE_TYPE_extra7111="AwsSageMakerNotebookInstance"
CHECK_ALTERNATE_check7111="extra7111"
CHECK_SEVERITY_extra7111="Medium"
CHECK_SERVICENAME_extra7111="sagemaker"
CHECK_RISK_extra7111='This could provide an avenue for unauthorized access to your data.'
CHECK_REMEDIATION_extra7111='Restrict which traffic can access by launching Studio in a Virtual Private Cloud (VPC) of your choosing.'
CHECK_DOC_extra7111='https://docs.aws.amazon.com/sagemaker/latest/dg/interface-vpc-endpoint.html'
CHECK_CAF_EPIC_extra7111='Infrastructure Security'

extra7111(){
    for regx in ${REGIONS}; do
        LIST_SM_NB_INSTANCES=$($AWSCLI $PROFILE_OPT --region $regx sagemaker list-notebook-instances --query 'NotebookInstances[*].NotebookInstanceName' --output text 2>&1)
        if [[ $(echo "$LIST_SM_NB_INSTANCES" | grep -E 'AccessDenied|UnauthorizedOperation|AuthorizationError') ]]; then
            textInfo "$regx: Access Denied trying to list notebook instances" "$regx"
            continue
        fi
        if [[ $LIST_SM_NB_INSTANCES ]];then 
            for nb_instance in $LIST_SM_NB_INSTANCES; do
                SM_NB_DIRECTINET=$($AWSCLI $PROFILE_OPT --region $regx sagemaker describe-notebook-instance --notebook-instance-name $nb_instance --query 'DirectInternetAccess' --output text)
                if [[ "${SM_NB_DIRECTINET}" == "Enabled" ]]; then
                    textFail "${regx}: Sagemaker Notebook instance $nb_instance has direct internet access enabled" "${regx}" "$nb_instance"
                else
                    textPass "${regx}: Sagemaker Notebook instance $nb_instance has direct internet access disabled" "${regx}" "$nb_instance"
                fi 
            done
        else 
            textInfo "${regx}: No Sagemaker Notebook instances found" "${regx}"
        fi 
    done
}