#!/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_extra7141="7.141"
CHECK_TITLE_extra7141="[extra7141] Find secrets in SSM Documents"
CHECK_SCORED_extra7141="NOT_SCORED"
CHECK_CIS_LEVEL_extra7141="EXTRA"
CHECK_SEVERITY_extra7141="Critical"
CHECK_ASFF_RESOURCE_TYPE_extra7141="AwsSsmDocument"
CHECK_ALTERNATE_check7141="extra7141"
CHECK_SERVICENAME_extra7141="ssm"
CHECK_RISK_extra7141='Secrets hardcoded into SSM Documents by malware and bad actors to gain lateral access to other services.'
CHECK_REMEDIATION_extra7141='Implement automated detective control (e.g. using tools like Prowler) to scan accounts for passwords and secrets. Use Secrets Manager service to store and retrieve passwords and secrets.'
CHECK_DOC_extra7141='https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-secretsmanager-secret-generatesecretstring.html'
CHECK_CAF_EPIC_extra7141='IAM'

extra7141(){
  SECRETS_TEMP_FOLDER="$PROWLER_DIR/secrets-$ACCOUNT_NUM-$PROWLER_START_TIME"
  if [[ ! -d "${SECRETS_TEMP_FOLDER}" ]]; then
    # this folder is deleted once this check is finished
    mkdir "${SECRETS_TEMP_FOLDER}"
  fi

  for regx in ${REGIONS}; do
    CHECK_DETECT_SECRETS_INSTALLATION=$(secretsDetector)
    if [[ $? -eq 241 ]]; then
      textInfo "$regx: python library detect-secrets not found. Make sure it is installed correctly." "$regx"
    else
      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_FILE="${SECRETS_TEMP_FOLDER}/extra7141-${ssmdoc}-${regx}-content.txt"
          "${AWSCLI}" ${PROFILE_OPT} --region "${regx}" ssm get-document --name "${ssmdoc}" --output text --document-format JSON > "${SSM_DOC_FILE}" 2>&1
          if [[ $(grep -E 'AccessDenied|UnauthorizedOperation|AuthorizationError' "${SSM_DOC_FILE}") ]]; then
              textInfo "${regx}: Access Denied trying to get document" "${regx}"
              continue
          fi
          FINDINGS=$(secretsDetector file "${SSM_DOC_FILE}")
          if [[ "${FINDINGS}" -eq 0 ]]; then
            textPass "${regx}: No secrets found in SSM Document ${ssmdoc}" "${regx}" "${ssmdoc}"
            # delete file if nothing interesting is there
            rm -f "${SSM_DOC_FILE}"
          else
            textFail "${regx}: Potential secret found SSM Document ${ssmdoc}" "${regx}" "${ssmdoc}"
            # delete file to not leave trace, user must look at the CFN Stack
            rm -f "${SSM_DOC_FILE}"
          fi
        done
      else
        textInfo "${regx}: No SSM Document found." "${regx}"
      fi
    fi
  done
  rm -rf "${SECRETS_TEMP_FOLDER}"
}
