#!/usr/bin/env bash
# Prowler - the handy cloud security tool (copyright 2019) 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_extra7140="7.140"
CHECK_TITLE_extra7140="[extra7140] Check if there are SSM Documents set as public"
CHECK_SCORED_extra7140="NOT_SCORED"
CHECK_CIS_LEVEL_extra7140="EXTRA"
CHECK_SEVERITY_extra7140="High"
CHECK_ASFF_RESOURCE_TYPE_extra7140="AwsSsmDocument"
CHECK_ALTERNATE_check7140="extra7140"
CHECK_SERVICENAME_extra7140="ssm"
CHECK_RISK_extra7140='SSM Documents may contain private information or even secrets and tokens.'
CHECK_REMEDIATION_extra7140='Carefully review the contents of the document before is shared. Enable SSM Block public sharing for documents.'
CHECK_DOC_extra7140='https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-before-you-share.html'
CHECK_CAF_EPIC_extra7140='Data Protection'
extra7140(){
  
  for regx in $REGIONS; do
    SSM_DOCS=$($AWSCLI $PROFILE_OPT --region $regx ssm list-documents --filters Key=Owner,Values=Self --query DocumentIdentifiers[].Name --output text 2>&1)
    if [[ $(echo "$SSM_DOCS" | grep -E 'AccessDenied|UnauthorizedOperation|AuthorizationError') ]]; then
        textInfo "$regx: Access Denied trying to list documents" "$regx"
        continue
    fi 
    if [[ $SSM_DOCS ]];then
      for ssmdoc in $SSM_DOCS; do 
        SSM_DOC_SHARED_ALL=$($AWSCLI $PROFILE_OPT --region $regx ssm describe-document-permission --name "$ssmdoc" --permission-type "Share" --query AccountIds[] --output text | grep all)
        if [[ $SSM_DOC_SHARED_ALL ]];then
          textFail "$regx: SSM Document $ssmdoc is public." "$regx" "$ssmdoc"
        else
          textPass "$regx: SSM Document $ssmdoc is not public." "$regx" "$ssmdoc"
        fi
      done
    else
      textInfo "$regx: No SSM Document found." "$regx"
    fi
  done
}