Menu
blog.headdesk.me
blog.headdesk.me

Prevent private key from being committed to git

Posted on 2025/04/222025/09/12

Here is how you can block commits using git pre-commit hook.

In your git repo, go to .git/hooks and create a pre-commit script. It looks for a certain pattern in your files. In this example, my script will examine newly staged files, and grep the file content for PEM boundary. If found, the commit will be blocked with an error.

#!/usr/bin/env bash

# Check files to be committed, reject if the file contains what appears to be private key
for f in $(git diff --name-only --cached | grep .key$); do
        if grep -qE '\-+BEGIN.*KEY\-+' $f ; then
                echo "HOOK: Key $f is not encrypted. To unstage, run git restore --staged $f"
                exit 1
        fi
done

Remember to run chmod 755 pre-commit and make it executable. Otherwise the hook will be ignored.

This script will only block PEM-encoded keys. Other formats are not supported at the moment. This script will also block encrypted PEM keys.

Git hooks work on the client side. If you want to distribute the hooks to all team members, store your hooks in the git repo – say .githooks and commit it to your repo. Each client still need to run the following once to tell git where to look for hooks:

git config core.hooksPath .githooks

I wish client setting can be git-cloned.

Loading

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Full text search

Recent Posts

  • Generate secure password
  • AWS Compute Savings Plans
  • AWS Zonal Shift
  • Coffee break…
  • Prevent private key from being committed to git
  • aws (14)
  • coffee (2)
  • headfi (1)
  • linux (9)
  • others (61)
  • security (2)
  • tech (41)
  • terraform (3)
  • wordpress (2)

Loading

apache aws awscli azure backup boot cloud coffee docker ec2 EL8 ElasticBeanstalk espresso featured git kernel lelit linux lvm meltdown MFA nat gateway php power proliant python rdp Redhat RHEL rpm Ryzen scp security smartarray smart switch snapshot spectre tech terraform ubuntu ubuntu upgrade vpn windows wordpress workspace

©2026 blog.headdesk.me | Powered by SuperbThemes