#!/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_extra7112="7.112"
CHECK_TITLE_extra7112="[extra7112] Check if Amazon SageMaker Notebook instances have data encryption enabled"
CHECK_SCORED_extra7112="NOT_SCORED"
CHECK_CIS_LEVEL_extra7112="EXTRA"
CHECK_ASFF_RESOURCE_TYPE_extra7112="AwsSageMakerNotebookInstance"
CHECK_ALTERNATE_check7112="extra7112"
CHECK_SEVERITY_extra7112="Medium"
CHECK_SERVICENAME_extra7112="sagemaker"
CHECK_RISK_extra7112='Data exfiltration could happen if information is not protected. KMS keys provide additional security level to IAM policies.'
CHECK_REMEDIATION_extra7112='Specify AWS KMS keys to use for input and output from S3 and EBS.'
CHECK_DOC_extra7112='https://docs.aws.amazon.com/sagemaker/latest/dg/key-management.html'
CHECK_CAF_EPIC_extra7112='Data Protection'

extra7112(){
    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_KMSKEY=$($AWSCLI $PROFILE_OPT --region $regx sagemaker describe-notebook-instance --notebook-instance-name $nb_instance --query 'KmsKeyId' --output text)
                if [[ "${SM_NB_KMSKEY}" == "None" ]]; then
                    textFail "${regx}: Sagemaker Notebook instance $nb_instance has data encryption disabled" "${regx}" "$nb_instance"
                else
                    textPass "${regx}: Sagemaker Notebook instance $nb_instance has data encryption enabled" "${regx}" "$nb_instance"
                fi 
            done
        else 
            textInfo "${regx}: No Sagemaker Notebook instances found" "${regx}"
        fi 
    done
}