#!/usr/bin/env bash

# Prowler - the handy cloud security tool (copyright 2018) 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_extra7172="7.172"
CHECK_TITLE_extra7172="[extra7172] Check if S3 buckets have ACLs enabled"
CHECK_SCORED_extra7172="NOT_SCORED"
CHECK_CIS_LEVEL_extra7172="EXTRA"
CHECK_SEVERITY_extra7172="Medium"
CHECK_ASFF_RESOURCE_TYPE_extra7172="AwsS3Bucket"
CHECK_ALTERNATE_check7172="extra7172"
CHECK_SERVICENAME_extra7172="s3"
CHECK_RISK_extra7172='S3 ACLs are a legacy access control mechanism that predates IAM. IAM and bucket policies are currently the preferred methods.'
CHECK_REMEDIATION_extra7172='Ensure that S3 ACLs are disabled (BucketOwnerEnforced). Use IAM policies and bucket policies to manage access.'
CHECK_DOC_extra7172='https://docs.aws.amazon.com/AmazonS3/latest/userguide/about-object-ownership.html'
CHECK_CAF_EPIC_extra7172='Logging and Monitoring'

extra7172(){
  # "Check if S3 buckets have server access logging enabled "
  LIST_OF_BUCKETS=$($AWSCLI s3api list-buckets $PROFILE_OPT --query Buckets[*].Name --output text 2>&1)
  if [[ $(echo "$LIST_OF_BUCKETS" | grep -E 'AccessDenied|UnauthorizedOperation|AuthorizationError') ]]; then
    textInfo "$REGION: Access Denied Trying to list buckets" "$REGION"
    exit
  fi
  if [[ $LIST_OF_BUCKETS ]]; then
    for bucket in $LIST_OF_BUCKETS;do
      BUCKET_ACLS_DISABLED=$($AWSCLI s3api get-bucket-ownership-controls --bucket $bucket $PROFILE_OPT --output text 2>&1)
      if [[ $(echo "$BUCKET_ACLS_DISABLED" | grep -E 'AccessDenied|UnauthorizedOperation|AuthorizationError') ]]; then
        textInfo "$REGION: Access Denied Trying to Get Bucket Ownership Controls for $bucket" "$REGION" "$bucket"
        continue
      fi
      if [[ $(echo "$BUCKET_ACLS_DISABLED" | grep "BucketOwnerEnforced") ]]; then
        textPass "$REGION: Bucket $bucket has bucket ACLs disabled!" "$REGION" "$bucket"
      elif [[ $(echo "$BUCKET_ACLS_DISABLED" | grep "BucketOwnerPreferred") ]]; then
        textFail "$REGION: Bucket $bucket has bucket ACLs enabled!" "$REGION" "$bucket"
      elif [[ $(echo "$BUCKET_ACLS_DISABLED" | grep "OwnershipControlsNotFoundError") ]]; then
        textFail "$REGION: Bucket $bucket has bucket ACLs enabled!" "$REGION" "$bucket"
      else
        textFail "$REGION: Bucket $bucket returned an unknown error" $BUCKET_ACLS_DISABLED
      fi
    done
  else
    textInfo "$REGION: No S3 Buckets found" "$REGION"
  fi
}
