Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 78 ยท Customizing and Automating Git

Signing, Credentials and Security

Sign commits and tags with GPG or SSH, understand credential helpers and SSH vs HTTPS, find and handle secrets in history, and protect branches. Runnable demos included.

Git was designed for trust inside a team, not for defending against attackers. By default anyone can write any name and email into a commit with one command, and a password pasted into a file stays in history forever. This lesson covers the practical security topics every Git user meets: proving who made a commit (signing), authenticating to remotes (credentials, SSH vs HTTPS), what happens when a secret is committed, and how to protect important branches.

The sandbox has GnuPG, so you can sign and verify commits for real. It has no network, no password manager and no working ssh-keygen, so SSH keys, credential helpers for real services and GitHub settings are shown as read-only commands and screens.

Anyone can claim to be anyone

The author line of a commit is just text. Nothing stops this:

CONSOLE
$ git -c user.name="Linus Torvalds" -c user.email="[email protected]" commit -m "Totally legit"

That commit now says it was written by someone else. On a hosting service the commit would show that person's name, but the platform did not verify anything: it matched the email string against accounts. Signing fixes this by attaching a cryptographic signature that only the holder of a private key can produce, and that anyone with the public key can verify.

Signing commits and tags with GPG

Git supports three signature formats: OpenPGP (GnuPG, the original), SSH keys, and X.509 certificates. With GPG you create a key pair, tell Git which key to use with user.signingkey, and add -S to git commit (or git tag -s). Git asks the gpg program to sign the commit object and stores the signature inside the commit in an extra header called gpgsig.

Bash Signing and verifying commits and tags with GPG

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The first command in the script generated a key; 1 means one secret key exists. %G? printed G (good signature) for the signed commit, with %GS giving the signer name, and N (no signature) for the commit made without -S. The signature sits in a gpgsig header (the grep -c count is 1), which is why you cannot add a signature later without changing the commit's hash. git verify-commit reported Good signature from "Ada <[email protected]>" [ultimate] for the signed one and exited with 1 for the unsigned one. git tag -s signed the tag, and git tag -v verified it. After commit.gpgsign true, plain git commit signs every commit, so the last one shows G without -S.

In your own repositories you would use your real key id: git config --global user.signingkey 3AA5C34371567BD2, and tell Git to ask for a passphrase through your agent. Create a key with gpg --full-generate-key, list it with gpg --list-secret-keys --keyid-format long, and export the public part with gpg --armor --export <id> to upload to GitHub or GitLab.

What a signature protects

A signature covers the whole commit object: tree, parents, author, committer, dates and message. Change one byte and the signature no longer matches. Because every commit contains its parents' hashes, that also vouches for the entire history below it.

Bash A forged commit fails verification

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The copy has exactly the same signature header, but its message differs. Git printed B, and GPG said BAD signature. This is what makes signed history tamper-evident.

Trust: a signature is only as good as your trust in the key

Good signature only says "this key made it". You still need to know the key belongs to the person. GPG calls that validity (ultimate here because we created the key ourselves). In teams the answer is usually the hosting service: after you upload your public key to your account, GitHub and GitLab show a Verified badge on commits whose signature matches a key registered to the committer's account. Locally, git log --show-signature prints the full check, and %G? letters tell you the result: G good, B bad, U good but of unknown validity, X expired signature, Y expired key, R revoked key, E cannot be checked (missing key), N none.

SSH signing (read-only)

Many people prefer to sign with the SSH key they already use for pushing (Git 2.34 and later). It needs no GnuPG. The sandbox cannot run ssh-keygen (it needs a user account entry that its temporary user does not have), so this part is a read-only recipe:

CONSOLE
$ ssh-keygen -t ed25519 -C "[email protected]"            # once, if you have no key yet
$ git config --global gpg.format ssh
$ git config --global user.signingkey ~/.ssh/id_ed25519.pub
$ git config --global commit.gpgsign true
$ git commit -m "Signed with my SSH key"

# to verify locally, list trusted keys in a file ("allowed signers"):
$ echo "[email protected] $(cat ~/.ssh/id_ed25519.pub)" >> ~/.config/git/allowed_signers
$ git config --global gpg.ssh.allowedSignersFile ~/.config/git/allowed_signers
$ git log --show-signature -1

Upload the same public key to GitHub as a signing key (Settings, SSH and GPG keys, "New SSH key", key type "Signing Key"); it is separate from the authentication key.

Signing proves authorship, not quality or safety. A signed commit can still contain a bug or malicious code. Teams combine signing with code review and branch protection (see the end of this lesson).

Authenticating to a remote

To push to a remote that is not yours, Git must prove who you are. There are two families.

HTTPS URLs (https://github.com/ada/shop.git) authenticate with a username and a token or password. Hosting services no longer accept account passwords for Git operations; you use a personal access token (PAT, ideally fine-grained and limited to one repository and an expiry date) or an OAuth flow started by a credential helper.

SSH URLs ([email protected]:ada/shop.git) authenticate with a key pair: you upload the public key to your account and keep the private key on your machine, protected by a passphrase and an agent (ssh-agent). Nothing secret travels over the network, and nothing has to expire every 90 days. On the other hand, SSH ports are sometimes blocked on company networks.

HTTPS SSH
Secret token (can leak, has an expiry) private key (never leaves your machine)
Works through strict firewalls usually sometimes blocked
Setup credential helper + token generate key, upload public key
Switch a repository git remote set-url origin <url> git remote set-url origin <url>

Credential helpers

Typing a token on every push would be unbearable, so Git delegates to a credential helper, a small program that stores and returns secrets. Which one you use depends on the operating system:

INI
# ~/.gitconfig (read-only: these helpers talk to your OS)
[credential]
    helper = manager          # Windows and Git Credential Manager (also macOS/Linux)
    # helper = osxkeychain    # macOS keychain
    # helper = libsecret      # Linux desktop keyring
    # helper = cache --timeout=3600   # keep in memory for an hour (Linux/macOS)

The built-in store helper writes plain text to a file, which is convenient and dangerous. The following demo uses it only to show the protocol Git speaks with every helper: approve saves a credential, fill asks for one, reject deletes it. The key=value format is the same for Git Credential Manager and the others.

Bash The credential helper protocol with the store helper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The file holds a single URL, https://ada:[email protected]. fill printed the four fields back, the last two coming from the helper, and after reject the file was empty (0 bytes). When a push fails with 401, Git calls reject, which is why a wrong token does not stay cached.

Never put a token in a remote URL (https://ada:[email protected]/...). It is saved in plain text in .git/config, appears in git remote -v, and may end up in shell history and logs. Use a credential helper or SSH instead.

Secrets in history

The most common Git security incident is a password, API key or token committed by accident. The tempting fix is to delete it in the next commit. That hides it from the current files but does not remove it from history, and anyone who cloned or fetched already has it.

Bash A deleted secret is still in the history

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

git grep found nothing in HEAD, but git log -S (the pickaxe from blame, grep and Searching History) lists the two commits that added and removed the string, and the loop over git rev-list --all found it in Add config. (AKIAIOSFODNN7EXAMPLE is the dummy key that AWS uses in its own documentation.)

What to do when a secret has been committed, in this order:

  1. Revoke or rotate the secret first. Assume it is compromised the moment it is pushed. This is the only step that really fixes the problem.
  2. Remove it from history if you must (to avoid scanners flagging the repository, or because the secret is personal data): use git filter-repo or BFG, then force-push and ask every collaborator to re-clone (Amending, Splitting and Rewriting Commits). Also contact the hosting service: forks, pull request refs and caches can keep the old objects reachable.
  3. Prevent a repeat: keep secrets in environment variables or a secrets manager, list local config files in .gitignore (.gitignore and Untracked Files), commit an .env.example without real values, and scan before commits leave your machine.

You can scan at commit time with a hook (Git Hooks). This tiny version only looks at lines being added:

Bash A pre-commit hook that blocks key-like strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Real projects use dedicated scanners (gitleaks, trufflehog, detect-secrets) with hundreds of patterns and entropy checks; GitHub offers secret scanning with push protection, which rejects pushes containing known token formats on the server, where --no-verify cannot bypass it.

Protecting branches and the supply chain

Everything above is advice for individuals. Teams enforce rules on the server (see Git Hooks for the plain-Git version). On GitHub these are branch protection rules or rulesets, on GitLab protected branches. The usual set for main:

  • require a pull request with at least one approval (Pull Requests and Code Review);
  • require status checks (CI) to pass before merging;
  • block force pushes and deletion of the branch;
  • require signed commits or a linear history if your policy needs it;
  • restrict who can push, and use CODEOWNERS for sensitive paths.

Further good habits, all read-only here because they live on the hosting service or your OS:

  • Turn on two-factor authentication for your account and prefer SSH keys with passphrases or hardware keys (FIDO2, ed25519-sk).
  • Use fine-grained tokens with the minimum scopes and an expiry date; never share one token between tools.
  • Enable dependency alerts (Dependabot), secret scanning and code scanning.
  • Treat cloned repositories as untrusted: do not run their hooks or build scripts blindly. Git itself helps: core.hooksPath is read from config, and hooks in .git/hooks are not cloned, so a clone never brings executable hooks with it.
  • Know safe.directory. If a repository is owned by another user, Git refuses to work in it with fatal: detected dubious ownership in repository, to stop a malicious .git/config in a shared folder from running commands as you. Only add a directory with git config --global --add safe.directory <path> if you trust it.
  • Consider git config --global transfer.fsckObjects true to have Git check objects for corruption and malformed data when fetching and receiving.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a good GPG or SSH signature on a commit prove?

    A signature binds the exact commit contents to a key. It says nothing about quality or safety; you still need review and CI.
  2. 2. You committed an API token and pushed it. What is the first thing to do?

    Anyone who fetched the commit has the token, and deleting it in a later commit does not remove it from history. Rotate it first, then clean history if needed.
  3. 3. Which command prints the signature status letter (G, B, N...) next to each commit?

    The format placeholder %G? shows the validity of the signature: G good, B bad, N none, and so on.
  4. 4. Why is putting a token inside a remote URL a bad idea?

    Use a credential helper or SSH keys, so secrets are kept in an OS keystore or in an agent, not in a readable config file.
  5. 5. A teammate pushes with git push --no-verify. Which control still stops a push that contains a known token format?

    --no-verify skips client-side hooks only. Checks that run on the server cannot be skipped by the pusher.

Summary

  • Author and committer names in a commit are unverified text. Signing (git commit -S, git tag -s, commit.gpgsign true) adds a verifiable signature in the gpgsig header; git verify-commit, git tag -v and git log --format=%G? check it. Any change to a signed commit breaks the signature.
  • Git supports OpenPGP, SSH (Git 2.34 and later, gpg.format ssh) and X.509 signatures. Hosting services show a Verified badge when the key is registered to the account.
  • Authenticate with SSH keys or HTTPS tokens, and keep secrets in a credential helper (manager, osxkeychain, libsecret), never in the remote URL. store saves plain text.
  • A secret removed in a later commit is still in history. Rotate it first, rewrite history only if needed, and prevent repeats with .gitignore, secret scanners and hooks.
  • Enforce rules on the server: branch protection or rulesets, required reviews and checks, no force pushes, push protection for secrets.
  • Be careful with untrusted repositories and safe.directory.

Next: Large Repositories: Shallow, Partial and Sparse