- Posted on
- • Artificial Intelligence
Artificial Intelligence Bash Security Checks
- Author
-
-
- User
- linuxbash
- Posts by this author
- Posts by this author
-
Artificial Intelligence Bash Security Checks: Catch Vulnerabilities Before They Catch You
If your infrastructure lives on Bash, your uptime and reputation do too. A single unquoted variable, an unsafe eval, or a sloppy path can become a production outage or a foothold for attackers. The good news: you can combine classic static analysis with AI-assisted reviews to spot risky patterns early—before they make it to prod.
This post shows you how to set up “AI Bash Security Checks” on any Linux box using simple, scriptable tools. You’ll get baseline static checks, an optional AI reviewer, Git pre-commit integration, and hardened Bash patterns you can reuse today.
Why this matters
Bash powers deploys, cron jobs, CI glue, and admin tasks—exactly the places attackers love.
Common foot-guns like unquoted variables, word splitting, globbing, unsafe PATHs, and eval are easy to miss in code review.
Static analysis catches many issues; AI can find higher-level risks such as command injection flows, secret leakage, or logic that breaks under input edge cases.
What are “AI Bash Security Checks”?
A layered approach:
Use ShellCheck for fast, deterministic static analysis.
Add an AI reviewer (local script + API) to reason about intent, input flows, and privilege boundaries.
Wire both into Git pre-commit so problems are blocked before they merge.
Harden your scripts with safe defaults.
1) Install prerequisites
We’ll use ShellCheck, curl, and jq.
- Debian/Ubuntu (apt):
sudo apt update
sudo apt install -y shellcheck curl jq
- Fedora/RHEL/CentOS (dnf):
# On RHEL/CentOS, you may need EPEL first:
# sudo dnf install -y epel-release
sudo dnf install -y ShellCheck curl jq
- openSUSE (zypper):
sudo zypper refresh
sudo zypper install -y ShellCheck curl jq
Verify:
shellcheck --version
curl --version
jq --version
2) Baseline static analysis with ShellCheck
ShellCheck flags quoting mistakes, undefined variables, bad globbing, and more.
- Scan a single script:
shellcheck -x ./script.sh
- Scan all staged shell files:
git diff --cached --name-only --diff-filter=ACM \
| grep -E '\.sh$|/bash(rc|_profile)$' \
| xargs -r shellcheck -x
Tip: Fix high-severity issues first (unquoted variables, undefined vars, command substitutions). ShellCheck’s SC codes are Googleable and point straight to practices that reduce attack surface.
3) Add an AI reviewer (script + API)
Use an OpenAI-compatible API to get a reasoned security review. This script sends your Bash file and asks for a JSON list of issues and fixes.
Important:
Redact secrets before sending code to third-party services.
For internal or sensitive scripts, point the script at a self-hosted or private-compatible endpoint.
Create ai_bash_review.sh:
#!/usr/bin/env bash
set -euo pipefail
: "${OPENAI_API_KEY:?Set OPENAI_API_KEY}"
MODEL="${MODEL:-gpt-4o-mini}" # Or any OpenAI-compatible chat model
FILE="${1:?Usage: $0 path/to/script.sh}"
PROMPT=$(cat <<'EOF'
You are a security auditor for Bash. Analyze the script and return concise JSON with:
- issues: array of {severity: "low|medium|high|critical", code: "AI-XXX|SC-XXX|CWE-XXX", description, line, snippet, fix}
- risk_score: integer 0-100
- summary: short text
Focus on quoting, word splitting, globbing, unsafe eval, command injection, PATH safety, set -euo pipefail, traps, IFS, and privilege use.
Only output valid JSON.
EOF
)
CONTENT=$(sed 's/[[:cntrl:]]//g' "$FILE")
payload=$(jq -n --arg model "$MODEL" --arg prompt "$PROMPT" --arg code "$CONTENT" '{
model: $model,
messages: [
{role: "system", content: $prompt},
{role: "user", content: ("Here is the Bash script:\n\n```bash\n" + $code + "\n```")}
],
temperature: 0.2
}')
resp=$(curl -sS https://api.openai.com/v1/chat/completions \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d "$payload")
echo "$resp" | jq -r '.choices[0].message.content' | jq .
Make it executable:
chmod +x ./ai_bash_review.sh
Use it:
OPENAI_API_KEY=... ./ai_bash_review.sh ./script.sh
Notes:
You can set MODEL to another OpenAI-compatible model.
For private/self-hosted endpoints, replace the URL and headers to match your provider.
4) Gate code with a Git pre-commit hook
Automatically run ShellCheck and (optionally) the AI review when you commit.
Create .git/hooks/pre-commit:
#!/usr/bin/env bash
set -euo pipefail
fail=0
if ! command -v shellcheck >/dev/null; then
echo "ShellCheck not found. Install it first." >&2
exit 1
fi
files=$(git diff --cached --name-only --diff-filter=ACM \
| grep -E '\.sh$|/bash(rc|_profile)$' || true)
[ -z "$files" ] && exit 0
echo "[pre-commit] ShellCheck..."
if ! shellcheck -x $files; then
fail=1
fi
# AI check is optional: set OPENAI_API_KEY to enable, or export AI_CHECK=0 to skip
if [ "${AI_CHECK:-1}" = "1" ] && [ -n "${OPENAI_API_KEY:-}" ]; then
if [ ! -x ./ai_bash_review.sh ]; then
echo "[pre-commit] ai_bash_review.sh not found or not executable; skipping AI check."
else
echo "[pre-commit] AI review..."
for f in $files; do
echo " -> $f"
if ! ./ai_bash_review.sh "$f" >/dev/null; then
echo "AI review reported issues in $f"
fail=1
fi
done
fi
else
echo "[pre-commit] AI check skipped (set OPENAI_API_KEY or export AI_CHECK=0)"
fi
exit $fail
Make it executable:
chmod +x .git/hooks/pre-commit
Now risky code won’t slip through unnoticed.
5) Harden your Bash scripts with safe defaults
Drop-in patterns that cut entire classes of bugs.
- Safe shell options, PATH, IFS, and umask:
#!/usr/bin/env bash
set -Eeuo pipefail
IFS=$'\n\t'
umask 027
# Minimal, explicit PATH
readonly SAFE_PATH="/usr/sbin:/usr/bin:/sbin:/bin"
export PATH="$SAFE_PATH"
trap 'code=$?; echo "Error on line $LINENO"; exit $code' ERR
- Validate inputs and avoid eval:
usage() { echo "Usage: $0 --env dev|stage|prod --dir /safe/path" >&2; exit 2; }
ENV=""; DIR=""
while [[ $# -gt 0 ]]; do
case "$1" in
--env) ENV="${2:-}"; shift 2;;
--dir) DIR="${2:-}"; shift 2;;
*) usage;;
esac
done
[[ "$ENV" =~ ^(dev|stage|prod)$ ]] || usage
[[ -d "$DIR" ]] || { echo "Directory not found: $DIR" >&2; exit 1; }
# No eval; use arrays for args
cmd=(rsync -a --delete "./build/" "$DIR/")
"${cmd[@]}"
- Quote everything and check dependencies:
command -v rsync >/dev/null || { echo "rsync missing"; exit 1; }
: "${REQUIRED_VAR:?REQUIRED_VAR must be set}"
Real-world mini example
A flawed deploy script:
#!/usr/bin/env bash
TARGET_DIR=$1
BRANCH=$2
rm -rf $TARGET_DIR/*
cd $TARGET_DIR
git pull origin $BRANCH
cp -r $3 $TARGET_DIR
eval $EXTRA_CMD
What can go wrong:
Unquoted vars => word splitting, globbing, accidental deletes (rm -rf).
No checks for directory existence.
eval permits arbitrary code execution.
Missing set -euo pipefail => silent failures.
A safer rewrite:
#!/usr/bin/env bash
set -Eeuo pipefail
IFS=$'\n\t'
TARGET_DIR="${1:?Usage: $0 /path/to/dir branch srcdir}"
BRANCH="${2:?branch required}"
SRC="${3:?source dir required}"
[[ -d "$TARGET_DIR" ]] || { echo "No such dir: $TARGET_DIR" >&2; exit 1; }
[[ -d "$SRC" ]] || { echo "No such dir: $SRC" >&2; exit 1; }
readonly SAFE_PATH="/usr/sbin:/usr/bin:/sbin:/bin"
export PATH="$SAFE_PATH"
umask 027
trap 'code=$?; echo "Failed on line $LINENO"; exit $code' ERR
cd "$TARGET_DIR"
git fetch --all --prune
git checkout --force --quiet "$BRANCH"
git pull --ff-only origin "$BRANCH"
# Safer cleanup using rsync --delete or find with explicit path
rsync -a --delete "$SRC"/ "$TARGET_DIR"/
Run ShellCheck to catch mistakes, then run the AI reviewer to get a prioritised list of improvements.
Optional: Summarize logs with AI when something looks off
When a job fails, you can have AI quickly summarize suspicious lines.
Example for a systemd unit:
#!/usr/bin/env bash
set -euo pipefail
: "${OPENAI_API_KEY:?Set OPENAI_API_KEY}"
UNIT="${1:?Usage: $0 UNIT}"
MODEL="${MODEL:-gpt-4o-mini}"
logs=$(journalctl -u "$UNIT" -n 500 --no-pager --output=short-iso 2>/dev/null | tail -n +1)
payload=$(jq -n --arg model "$MODEL" --arg txt "$logs" '{
model: $model,
messages: [
{role: "system", content: "Summarize security-relevant anomalies, suspicious commands, and likely root causes in these logs. Be concise with bullet points."},
{role: "user", content: $txt}
],
temperature: 0.2
}')
curl -sS https://api.openai.com/v1/chat/completions \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d "$payload" \
| jq -r '.choices[0].message.content'
Dependencies (already covered above):
apt:
sudo apt install -y curl jqdnf:
sudo dnf install -y curl jqzypper:
sudo zypper install -y curl jq
Conclusion and next steps
Security isn’t a one-time scan; it’s a workflow. Set a solid baseline with ShellCheck, add an AI reviewer for deeper reasoning, wire both into Git pre-commit, and harden your scripts with safe defaults. This layered approach catches both the obvious and the subtle.
Your next steps:
Install ShellCheck, curl, and jq using your package manager.
Drop ai_bash_review.sh and the pre-commit hook into your repo.
Refactor one critical script with the hardening template.
Iterate: make “no unquoted vars, no eval” a team norm.
Have a Bash security pattern you love or an AI prompt that works wonders? Share it with the community and help raise the bar for everyone.