#!/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_extra775="7.75"
CHECK_TITLE_extra775="[extra775] Find secrets in EC2 Auto Scaling Launch Configuration "
CHECK_SCORED_extra775="NOT_SCORED"
CHECK_CIS_LEVEL_extra775="EXTRA"
CHECK_SEVERITY_extra775="Critical"
CHECK_ALTERNATE_check775="extra775"
CHECK_SERVICENAME_extra775="autoscaling"
CHECK_RISK_extra775='The use of a hard-coded password increases the possibility of password guessing.  If hard-coded passwords are used; it is possible that malicious users gain access through the account in question.'
CHECK_REMEDIATION_extra775='Use Secrets Manager to securely provide database credentials to Lambda functions and secure the databases as well as use the credentials to connect and query them without hardcoding the secrets in code or passing them through environmental variables. '
CHECK_DOC_extra775='https://docs.aws.amazon.com/secretsmanager/latest/userguide/lambda-functions.html'
CHECK_CAF_EPIC_extra775='IAM'

extra775(){
  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
      LIST_OF_EC2_AUTOSCALING=$($AWSCLI autoscaling describe-launch-configurations $PROFILE_OPT --region $regx --query LaunchConfigurations[*].LaunchConfigurationName --output text --max-items $MAXITEMS 2>&1 | grep -v None )
      if [[ $(echo "$LIST_OF_EC2_AUTOSCALING" | grep -E 'AccessDenied|UnauthorizedOperation|AuthorizationError') ]]; then
          textInfo "$regx: Access Denied trying to describe launch configurations" "$regx"
          continue
      fi
      if [[ $LIST_OF_EC2_AUTOSCALING ]];then
        for autoscaling_configuration in $LIST_OF_EC2_AUTOSCALING; do
          EC2_AUTOSCALING_USERDATA_FILE="$SECRETS_TEMP_FOLDER/extra775-$autoscaling_configuration-userData.decoded"
          EC2_AUTOSCALING_USERDATA=$($AWSCLI autoscaling describe-launch-configurations $PROFILE_OPT --launch-configuration-names $autoscaling_configuration --region $regx --query LaunchConfigurations[*].UserData --output text| grep -v ^None | decode_report > $EC2_AUTOSCALING_USERDATA_FILE)
          if [ -s $EC2_AUTOSCALING_USERDATA_FILE ];then
            FILE_FORMAT_ASCII=$(file -b $EC2_AUTOSCALING_USERDATA_FILE | grep ASCII)
            # This finds ftp or http URLs with credentials and common keywords
            # FINDINGS=$(egrep -i '[[:alpha:]]*://[[:alnum:]]*:[[:alnum:]]*@.*/|key|secret|token|pass' $EC2_AUTOSCALING_USERDATA_FILE |wc -l|tr -d '\ ')
            # New implementation using https://github.com/Yelp/detect-secrets
            if [[ $FILE_FORMAT_ASCII ]]; then
            FINDINGS=$(secretsDetector file $EC2_AUTOSCALING_USERDATA_FILE)
              if [[ $FINDINGS -eq 0 ]]; then
                textPass "$regx: No secrets found in $autoscaling_configuration" "$regx" "$autoscaling_configuration"
                # delete file if nothing interesting is there
                rm -f $EC2_AUTOSCALING_USERDATA_FILE
              else
                textFail "$regx: Potential secret found in $autoscaling_configuration" "$regx" "$autoscaling_configuration"
                # delete file to not leave trace, user must look at the autoscaling_configuration User Data
                rm -f $EC2_AUTOSCALING_USERDATA_FILE
              fi
            else
              mv $EC2_AUTOSCALING_USERDATA_FILE $EC2_AUTOSCALING_USERDATA_FILE.gz ; gunzip $EC2_AUTOSCALING_USERDATA_FILE.gz
              FINDINGS=$(secretsDetector file $EC2_AUTOSCALING_USERDATA_FILE)
              if [[ $FINDINGS -eq 0 ]]; then
                textPass "$regx: No secrets found in $autoscaling_configuration User Data" "$regx" "$autoscaling_configuration"
                rm -f $EC2_AUTOSCALING_USERDATA_FILE
              else
                textFail "$regx: Potential secret found in $autoscaling_configuration" "$regx" "$autoscaling_configuration"
              fi
            fi
          else 
            textPass "$regx: No secrets found in $autoscaling_configuration User Data or it is empty" "$regx" "$autoscaling_configuration"
          fi
        done
      else
        textInfo "$regx: No EC2 autoscaling_configurations found" "$regx"
      fi
    fi
  done
  rm -rf $SECRETS_TEMP_FOLDER
}
