• Skip to main content

PineWise

CI/CD and DevOps Consultants in Israel • Pinewise

  • The DevOps Blueprint
  • Kubernetes Operators
  • Blog
  • Media and Interviews
  • Contact
Never Commit Secrets to Git  with Pre-Commit Hooks

Never Commit Secrets to Git with Pre-Commit Hooks

posted on September 8, 2022

Moving on with our “Quick Wins / You’re Overthinking It” series, I wanted to share a very simple security practice you can implement in just a few minutes.

In my previous post about security scanning, we used Trivy to scan our git repo and container images. One of those scans would alert you if anyone committed secrets to git.

And by secrets, I mean things like API keys, credentials, private keys, etc.

The problem is that by the time you scan it on GitHub, it’s too late. The secret is already on git, and now you have to:

  1. Work to remove the secret from history.
  2. Revoke and replace the secret, which could be a hassle.

The solution for this is very simple – Add a pre-commit hook.

Git hooks allow you to run scripts at different points in the git lifecycle.
Pre-Commit hooks scripts run before code is committed, exactly where we want to run our scanner.

In this example, I’m going to use the Trivy scanner, but there are other tools out there that will do the same job.

Adding the pre-commit script

Git Hooks can be found in the .git/hooks folder. If you look at the contents of this folder, you will find sample scripts for each hook.

We are interested in the pre-commit hook, so we’ll create the file:

touch .git/hooks/pre-commit

Then edit the file and add our script:

#!/bin/sh

trivy --quiet fs --exit-code 1 --security-checks secret .

Then we will need to make it executable:

chmod +x .git/hooks/pre-commit

That’s it.

To test it, I added AWS credentials to one of my files, and here is the result:

Pre-Commit Hook runs Trivy and catches a secret.

You can find a list of built-in rules here:
https://github.com/aquasecurity/fanal/blob/main/secret/builtin-rules.go


Filed Under: Quick Wins, Uncategorized Tagged With: quick win, secrets, security, security scanner, Trivy

Copyright © 2023 PineWise Ltd. · Contact · Blog · Illustrations by Freepik Storyset