Security Auditing
grep is a foundational tool for DevSecOps. It allows security engineers to scan codebases and server filesystems for leaked secrets, misconfigurations, and vulnerable code patterns.
1. Hunting for Leaked Secrets
Developers sometimes accidentally commit API keys, AWS credentials, or passwords into configuration files or source code.
We can use grep with Extended Regular Expressions (-E) to hunt for these patterns recursively (-r) across a project.
Finding AWS Access Keys
AWS Access Key IDs typically start with AKIA followed by 16 alphanumeric characters.
# Scan the /var/www directory for AWS Keys
grep -r -E "AKIA[0-9A-Z]{16}" /var/www/
Finding Private SSH/RSA Keys
Private keys have a very distinct header. We can search for this header across the entire filesystem to ensure no private keys are sitting in public directories.
# We use -l to just print the filename, as we don't want the key printed to our screen
grep -r -l "-----BEGIN RSA PRIVATE KEY-----" /home/
Finding Generic Passwords
We can construct an OR query to look for common variable names associated with secrets. We use -i for case insensitivity (matching password, PASSWORD, PassWord).
grep -r -i -E "password|passwd|api_key|secret_key|token" /etc/
2. Auditing Configuration Files
Security benchmarks (like CIS) require ensuring specific settings are enforced in configuration files.
Checking SSH Configurations
Ensure that Root Login is disabled in the SSH daemon config.
# 1. Use -v to strip comments (^#) and empty lines (^$)
# 2. Use a second grep to look for the PermitRootLogin directive
grep -E -v "^#|^$" /etc/ssh/sshd_config | grep "PermitRootLogin"
(If the output is PermitRootLogin yes, the system fails the audit).
Checking for World-Writable Permissions in Code
While find checks filesystem metadata, grep can check code. If a script executes chmod 777, it is a massive security risk.
# Look for any invocation of chmod that grants global write access
grep -r -E "chmod.*777" /projects/scripts/
3. Pre-Commit Hooks (Preventative Security)
You can build a simple Git pre-commit hook using grep to prevent developers from committing files that contain the word "TODO" or "FIXME".
#!/bin/bash
# .git/hooks/pre-commit
# If grep finds a match, it returns 0.
# We use -q to silence the output.
if git diff --cached | grep -q -E "TODO|FIXME"; then
echo "Commit rejected: Remove TODOs before committing."
exit 1
fi