#!/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
    CFN_STACKS=$($AWSCLI cloudformation describe-stacks $PROFILE_OPT --region $regx --output json 2>&1)
    if [[ $(echo "$CFN_STACKS" | grep -E 'AccessDenied|UnauthorizedOperation|AuthorizationError') ]]; then
        textInfo "$regx: Access Denied trying to describe stacks" "$regx"
        continue
    fi 
    LIST_OF_CFN_STACKS=$(echo $CFN_STACKS | jq -r '.Stacks[].StackName')
    if [[ $LIST_OF_CFN_STACKS ]];then
      for stack in $LIST_OF_CFN_STACKS; do
        CFN_OUTPUTS_FILE="$SECRETS_TEMP_FOLDER/extra742-$stack-$regx-outputs.txt"
        echo $CFN_STACKS | jq --arg s "$stack" -r '.Stacks[] | select( .StackName == $s ) | .Outputs[]? | "\(.OutputKey) \(.OutputValue)"' > $CFN_OUTPUTS_FILE

        if [ -s $CFN_OUTPUTS_FILE ];then
          # This finds ftp or http URLs with credentials and common keywords
          # FINDINGS=$(egrep -i '[[:alpha:]]*://[[:alnum:]]*:[[:alnum:]]*@.*/|key|secret|token|pass' $CFN_OUTPUTS_FILE |wc -l|tr -d '\ ')
          # New implementation using https://github.com/Yelp/detect-secrets
          FINDINGS=$(secretsDetector file $CFN_OUTPUTS_FILE)
            if [[ $FINDINGS -eq 0 ]]; then
              textPass "$regx: No secrets found in stack $stack Outputs" "$regx" "$stack"
              # delete file if nothing interesting is there
              rm -f $CFN_OUTPUTS_FILE
            else
              textFail "$regx: Potential secret found in stack $stack Outputs" "$regx" "$stack"
              # delete file to not leave trace, user must look at the CFN Stack
              rm -f $CFN_OUTPUTS_FILE
            fi
        else
          textInfo "$regx: CloudFormation stack $stack has no Outputs" "$regx"
        fi
      done
    else
      textInfo "$regx: No CloudFormation stacks found" "$regx"
    fi
  done
  rm -rf $SECRETS_TEMP_FOLDER
}
