cyberark/secretless-broker

View on GitHub
bin/run_gosec

Summary

Maintainability
Test Coverage
#!/usr/bin/env bash

set -eo pipefail

# This script can run independently of secretless
# i.e. in any given local repository
#
# Performs a gosec scan with given parameters on 
# the entire local repository (in the case of main branch)
# or on just files modified, as detected in the git diff.
print_usage() {
    echo "Security Scanner"
    echo 
    echo "Description:"
    echo "Runs gosec on directories which git detects and marks in the diff."
    echo "If the branch is detected as 'main', it will scan all"
    echo "directories regardless of what has been modified locally."
    echo 
    echo "Format:"
    echo "security_scan [arguments]"
    echo 
    echo "Options:"
    echo "-h                        Show help"
    echo "-c                        Specify the minimum confidence gosec needs to report an issue."
    echo "-s                        Specify the minimum severity gosec needs to report an issue"
    echo "-b                        Specify the github branch to compare against main"
    echo "-e                        Directories to be excluded from the gosec scan"
    exit 0
}

# Default values for gosec
confidence='medium'
severity='high'
current_branch=''
excluded_directories=''

while getopts 'b:e:c:s:h' flag; do
  case "${flag}" in
    b) current_branch="${OPTARG}" ;;
    e) excluded_directories="${OPTARG}" ;;
    c) confidence="${OPTARG}" ;;
    s) severity="${OPTARG}" ;;
    h) print_usage ;;
    *) print_usage ;;
  esac
done

# If we are on main, scan the entire repository
modified_directories="./..."

# Get an array of directories containing modified files
if [[ ${current_branch} != 'main' ]]; then 
    echo 'Current branch is not main - running gosec on modified packages for this branch only'
    # Jenkins already fetches the main refs so only run locally
    if [[ ! -v BRANCH_NAME ]]; then
      git fetch origin main:refs/remotes/origin/main
    fi
    modified_directories=($(git diff origin/main...origin/"${current_branch}" --name-only | xargs -L1 sh -c '[ "$#" -gt 0 ] && dirname "$@"' - | uniq))
fi

# Remove output file just in case it exists
rm -f "gosec.output" 

set +e && set +o pipefail

# Run our scan, flagging only 'high' level issues with 'medium' or higher severity
"$(go env GOPATH)"/bin/gosec -fmt=junit-xml \
    -out=gosec.output \
    -severity="${severity}" \
    -confidence="${confidence}" \
    -exclude-dir="${excluded_directories}" \
    "${modified_directories[@]}"

# Display output of gosec
cat gosec.output