#!/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_extra742="7.42"
CHECK_TITLE_extra742="[extra742] Find secrets in CloudFormation outputs"
CHECK_SCORED_extra742="NOT_SCORED"
CHECK_CIS_LEVEL_extra742="EXTRA"
CHECK_SEVERITY_extra742="Critical"
CHECK_ASFF_RESOURCE_TYPE_extra742="AwsCloudFormationStack"
CHECK_ALTERNATE_check742="extra742"
CHECK_SERVICENAME_extra742="cloudformation"
CHECK_RISK_extra742='Secrets hardcoded into CloudFormation outputs can be used by malware and bad actors to gain lateral access to other services.'
CHECK_REMEDIATION_extra742='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_extra742='https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-secretsmanager-secret-generatesecretstring.html'
CHECK_CAF_EPIC_extra742='IAM'

extra742(){
  SECRETS_TEMP_FOLDER="$PROWLER_DIR/secrets-$ACCOUNT_NUM"
  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
      CFN_STACKS=$("${AWSCLI}" cloudformation describe-stacks $PROFILE_OPT --region "${regx}" --output json 2>&1)
      if grep -q -E 'AccessDenied|UnauthorizedOperation|AuthorizationError' <<< "$CFN_STACKS" ; then
          textInfo "$regx: Access Denied trying to describe stacks" "$regx"
          continue
      fi
      LIST_OF_CFN_STACKS=$(jq -r '.Stacks[].StackName' <<< "${CFN_STACKS}")
      if [[ $LIST_OF_CFN_STACKS ]];then
        for stackName in $LIST_OF_CFN_STACKS; do
          CFN_OUTPUTS_FILE="$SECRETS_TEMP_FOLDER/extra742-${stackName}-${regx}-outputs.txt"
          # OutputKey and OutputValue are separated by a colon because secrets-detector needs a way to link both values
          jq --arg stackName "$stackName" -r '.Stacks[] | select( .StackName == $stackName ) | .Outputs[]? | "\(.OutputKey):\(.OutputValue)"' <<< "${CFN_STACKS}" > "${CFN_OUTPUTS_FILE}"
          if [ -s "${CFN_OUTPUTS_FILE}" ];then
            FINDINGS=$(secretsDetector file "${CFN_OUTPUTS_FILE}")
              if [[ $FINDINGS -eq 0 ]]; then
                textPass "$regx: No secrets found in stack ${stackName} Outputs" "$regx" "${stackName}"
                # Delete file if nothing interesting is there
                rm -f "${CFN_OUTPUTS_FILE}"
              else
                textFail "$regx: Potential secret found in stack ${stackName} Outputs" "$regx" "${stackName}"
                # Delete file to not leave trace, user must look at the CFN Stack
                rm -f "${CFN_OUTPUTS_FILE}"
              fi
          else
            textInfo "$regx: CloudFormation stack ${stackName} has no Outputs" "$regx"
          fi
        done
      else
        textInfo "$regx: No CloudFormation stacks found" "$regx"
      fi
    fi
  done

  # Cleanup temporary folder
  if [[ -d $SECRETS_TEMP_FOLDER ]]
  then
    rm -rf "${SECRETS_TEMP_FOLDER}"
  fi
}
