### Install Shellharden with Cargo Source: https://github.com/anordal/shellharden/blob/master/README.md Install the shellharden tool using the cargo package manager. Ensure you have Rust and Cargo installed. ```bash cargo install shellharden ``` -------------------------------- ### Install Built Shellharden Binary Source: https://github.com/anordal/shellharden/blob/master/README.md After building, move the compiled shellharden executable to a directory in your system's PATH for easy access. ```bash mv target/release/shellharden ~/.local/bin/ ``` -------------------------------- ### Using Arrays for File Lists in Bash Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Demonstrates the correct way to handle lists of items, especially filenames, using Bash arrays to avoid issues with whitespace. The 'good' example uses arrays, while the 'bad' example shows a problematic approach with whitespace-delimited strings. ```bash files=( a b ) duplicates=() for f in "${files[@]}"; do if cmp -- "$f" other/"$f"; then duplicates+=("$f") fi done if [ "${#duplicates[@]}" -gt 0 ]; then rm -- "${duplicates[@]}" fi ``` ```bash files=" \ a \ b \ " duplicates= for f in $files; do if cmp -- "$f" other/"$f"; then duplicates+=" $f" fi done if ! [ "$duplicates" = '' ]; then rm -- $duplicates fi ``` -------------------------------- ### Run Shellharden Tests Source: https://github.com/anordal/shellharden/blob/master/README.md Execute the test suite for shellharden to ensure its components are functioning correctly. This requires bash to be installed. ```bash cargo test ``` -------------------------------- ### Splitting a String into an Array with a Custom Separator in Bash Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Shows how to safely split a string into an array using a custom separator. The 'good' example uses a while loop with read, while the 'bad' example demonstrates an unsafe method relying on IFS. ```bash IFS="$sep" array=($string) ``` ```bash array=() while read -rd "$sep" i; do array+=("$i") done < <(printf '%s%s' "$string" "$sep") ``` -------------------------------- ### Passing Arguments Safely in Bash Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Compares different methods of passing arguments to commands, highlighting the importance of quoting variables to prevent word splitting and globbing. The good example uses individual quotes for each argument. ```bash some_command $arg1 $arg2 $arg3 ``` ```bash some_command ${arg1} ${arg2} ${arg3} ``` ```bash some_command "${arg1}" "${arg2}" "${arg3}" ``` ```bash some_command "$arg1" "$arg2" "$arg3" ``` -------------------------------- ### String Interpolation with Variables in Bash Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Shows examples of string interpolation where a variable is embedded within a string literal, using curly braces to clearly define the variable's boundaries. Shellharden allows braces in these contexts. ```bash "${var} " ``` ```bash " ${var}" ``` ```bash "${var}${var}" ``` -------------------------------- ### Implement `--version` option Source: https://github.com/anordal/shellharden/blob/master/CHANGELOG.md Adds a `--version` option to display the current version of the tool. ```shell # Implement the --version option. ``` -------------------------------- ### Build Shellharden from Source Source: https://github.com/anordal/shellharden/blob/master/README.md Build the shellharden tool in release mode from its source code. This command compiles the project for optimal performance. ```bash cargo build --release ``` -------------------------------- ### Avoid Shell for Simple Commands (C/POSIX) Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md For C/POSIX environments, use `posix_spawnp` with an argument array to safely execute commands without involving the shell. Ensure the argument list is NULL-terminated. ```c char* const args[] = {"rm", "-rf", path, NULL}; pid_t child; posix_spawnp(&child, args[0], NULL, NULL, args, NULL); int status; waitpid(child, &status, 0); ``` -------------------------------- ### Fish Shell Compatibility Check (Bash) Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Demonstrates how to check for Fish shell compatibility by testing specific syntax. This is useful when inter-operating with shells that have different parsing rules. ```bash test '\\' ``` ```bash echo "This is POSIX!" ``` ```bash test ' ``` ```bash echo "This is fish!" ``` ```bash test \' ``` -------------------------------- ### Enable Test Coverage Instrumentation Source: https://github.com/anordal/shellharden/blob/master/README.md Compile shellharden with coverage instrumentation enabled using RUSTFLAGS and set LLVM_PROFILE_FILE for raw profile data generation. ```bash env RUSTFLAGS="-C instrument-coverage" LLVM_PROFILE_FILE='run-%m.profraw' cargo test ``` -------------------------------- ### Standard Bash script hashbang Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Use '#!/usr/bin/env bash' for portability. Avoid placing script-altering options like '-euo pipefail' in the hashbang as they can be overridden. ```bash #!/usr/bin/env bash ``` -------------------------------- ### POSIX Default Value Expansion Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Shows how to provide default values for variables that might be unset or empty, using POSIX-compliant syntax. ```bash "${var-val}" # default value if unset ``` ```bash "${var:-val}" # default value if unset or empty ``` -------------------------------- ### Enable nullglob and globstar for safer globbing Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Set 'nullglob' to make globs expand to nothing if no files match, and 'globstar' to enable recursive globbing. This simplifies handling of file patterns. ```bash shopt -s nullglob globstar ``` -------------------------------- ### Safe String Comparisons in Bash Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Demonstrates POSIX-compliant and readable ways to compare strings against empty values. Avoids `-n` and `-z` flags for clarity and to prevent issues with unset variables. ```bash test "$s" != "" ``` ```bash test "$s" = "" ``` ```bash [ "$s" != "" ] ``` ```bash [ "$s" = "" ] ``` -------------------------------- ### Normalize `test` command for xyes comparison Source: https://github.com/anordal/shellharden/blob/master/CHANGELOG.md Simplifies `test x"$s" = xyes` to `test "$s" = yes` by removing the unnecessary 'x' prefix. ```shell test x"$s" = xyes → test "$s" = yes ``` -------------------------------- ### Custom `echo` Replacement Function Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Define a custom function like `println` using `printf` to provide a safe and predictable alternative to the problematic `echo` command. ```bash println() { printf '%s\n' "$*" } ``` -------------------------------- ### Handling Command Failure with Output in Bash Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Use `command || echo Command returned $?` to execute a command and print its exit status only if it fails. This is a concise way to report errors. ```bash command || echo Command returned $? ``` -------------------------------- ### Replacing `echo` with `printf` for Safety Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Avoid `echo` due to its unpredictable option parsing. Use `printf` for reliable output formatting, especially when dealing with variables or special characters. ```bash printf '%s\n' "$var" ``` ```bash printf '%s' "$var" ``` ```bash printf '%s\r' "$var" ``` ```bash printf '%s %s\n' "$a" "$b" ``` ```bash printf '%s\n' "${array[*]}" ``` -------------------------------- ### Rewrite `test` command for empty string checks Source: https://github.com/anordal/shellharden/blob/master/CHANGELOG.md Replaces `test -n "$s"` with `test "$s" != ""` and `test -z "$s"` with `test "$s" = ""` for more explicit empty string comparisons. ```shell test -n "$s" → test "$s" != "" ``` ```shell test -z "$s" → test "$s" = "" ``` -------------------------------- ### Fuzz Test Shellharden Source: https://github.com/anordal/shellharden/blob/master/README.md Set up and run fuzz tests for shellharden using cargo-afl. This helps discover bugs by feeding unexpected inputs to the program. ```bash cargo install cargo-afl ``` ```bash cargo afl build --release ``` ```bash cargo afl fuzz -i moduletests/original -o /tmp/fuzz-shellharden target/release/shellharden '' ``` -------------------------------- ### Using Local with Command Substitution Safely in Bash Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md To use `local` with command substitution while `set -e` is active, declare the variable first, then assign the substituted command's output to it. ```bash set -e # Fail if nproc is not installed local jobs jobs=$(nproc) make -j"$jobs" ``` -------------------------------- ### Correct Command Substitution with Backticks in Bash Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Illustrates the correct, though less preferred, usage of backticks for command substitution, emphasizing the need for careful escaping. Dollar-parentheses are generally safer and easier to manage. ```bash > x=`echo "This is a doublequote: \""`; echo "$x" This is a doublequote: " ``` ```bash > x="`echo "This is a doublequote: \""`"; echo "$x" bash: command substitution: line 1: unexpected EOF while looking for matching `"' ``` -------------------------------- ### Iterate over command output using a while loop and process substitution Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Avoid subshells when iterating over command output by using a while loop with process substitution (<(...)). This allows the loop to modify variables outside its scope. ```bash while read -r i; do printf '%s\n' "$i" done < <(seq 1 10) ``` -------------------------------- ### Assert Command Dependencies in Bash Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Defines a `require` function to check if specified commands are available in the system's PATH. If a command is not found, the script exits with status 127. This prevents failures due to missing external dependencies. ```bash require(){ hash "$@" || exit 127; } require … require … require … ``` -------------------------------- ### Avoid Shell for Simple Commands (Python) Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md When a command does not require shell features like piping or redirection, use an array representation for safer execution. This prevents unexpected shell interpretation of arguments. ```python subprocess.check_call(['rm', '-rf', path]) ``` -------------------------------- ### Generate HTML Test Coverage Report Source: https://github.com/anordal/shellharden/blob/master/README.md Use grcov to process the raw profile data generated during instrumented tests and create an HTML report for visualizing test coverage. ```bash grcov . --binary-path ./target/debug/ -s . -t html -o ./coverage/ ``` -------------------------------- ### Safe Echoing of Potentially Malicious Strings in Bash Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Demonstrates how to safely echo a string that might contain shell metacharacters. Always quote variable expansions to prevent unintended command execution. ```bash input=\"; rm -rf /\" echo "$input" ``` -------------------------------- ### Split string to array using IFS and read Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Use IFS with the read -a command to split a string into an array. The -r option prevents backslash interpretation, and -d '' reads until the end of the string. Guard with '|| true' if errexit is enabled. ```bash IFS="$sep" read -rd '' -a array < <(printf '%s%s' "$string" "$sep") || true ``` -------------------------------- ### Splitting a String into an Array with readarray (Bash 4+) Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md An alternative method for splitting a string into an array using the `readarray` command, available in Bash version 4 and later. This method is efficient for custom separators. ```bash readarray -td "$sep" array < <(printf '%s%s' "$string" "$sep") ``` -------------------------------- ### Safe SSH Command Execution (Python) Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md For commands executed over SSH, construct a single string with properly quoted and escaped arguments. This 'often correct' method assumes a POSIX-compatible remote shell. ```python subprocess.check_call(['ssh', 'user@host', "sha1sum '{}'".format(path.replace("'", "'\\''"))]) ``` -------------------------------- ### Safe Condition Combination in Bash Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Use `&&` and `||` with command grouping `{}` for unambiguous condition logic, avoiding the pitfalls of `test` or `[` operators like `-a` and `-o`. ```bash ! test -e "$f" && { test "$s" = yes || test "$s" = y; } ``` ```bash ! [ -e "$f" ] && { [ "$s" = yes ] || [ "$s" = y ]; } ``` -------------------------------- ### Variable Expansion with Delimiting Braces in Bash Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Shows how curly braces are used to delimit variable names, especially when the variable is immediately followed by characters that could be part of a variable name. This is often necessary for correct string interpolation. ```bash "${image%.png}.jpg" ``` ```bash "${var}string literal" ``` -------------------------------- ### Bash Strict Mode with Feature Check Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Implements Bash's unofficial strict mode, conditionally enabling `nounset` based on shell compatibility to avoid issues with empty arrays in older Bash versions. This ensures a safer subset of strict mode is used. ```bash if test "$BASH" = "" || "$BASH" -uc "a=();true \"\\\${a[@]}\"" 2>/dev/null; then # Bash 4.4, Zsh set -euo pipefail else # Bash 4.3 and older chokes on empty arrays with set -u. set -eo pipefail fi ``` -------------------------------- ### Correct Command Substitution with Errexit in Bash Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md When using `set -e` and command substitution, ensure the substitution is part of an assignment or a direct command argument, not within special builtins like `local`. ```bash set -e # Fail if nproc is not installed jobs=$(nproc) make -j"$jobs" ``` -------------------------------- ### Handling NUL-Separated Data with readarray in Bash Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Demonstrates how to use `readarray` with a NUL separator, which is useful for processing data like the output of `find -print0`. This ensures correct handling of filenames containing special characters. ```bash readarray -td $' ' array < <(find -print0) ``` -------------------------------- ### Idiomatic If-Statement in Bash Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md The standard `if command; then ... fi` structure is the most robust way to handle conditional execution in Bash. ```bash if command; then … fi ``` -------------------------------- ### Bash Conditional Command Types Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Identifies the nature of `test`, `[`, and `[[ ]]` within the shell environment. `test` and `[` are commands, while `[[ ]]` is a shell keyword with extended syntax. ```bash type test test is a shell builtin ``` ```bash type [ [ is a shell builtin ``` ```bash type [[ [[ is a shell keyword ``` -------------------------------- ### Embed Static Shellscripts Safely (Python) Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md If shell features are necessary, embed static shellscripts and pass arguments to them. This approach treats the shellscript as a single unit, with arguments passed explicitly. ```python subprocess.check_call(['docker', 'exec', instance, 'bash', '-ec', 'printf %s "$0" > "$1"', content, path]) ``` -------------------------------- ### Split string to variables using IFS and read Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Use IFS with the read command to split a string into separate variables. The -r option prevents backslash interpretation, and -d '' reads until the end of the string. Guard with '|| true' if errexit is enabled. ```bash IFS="$sep" read -rd '' a b rest < <(printf '%s%s' "$string" "$sep") || true ``` -------------------------------- ### Clean Up Raw Profile Data Source: https://github.com/anordal/shellharden/blob/master/README.md Remove the raw profile data files generated during the test coverage instrumentation process. ```bash rm run-*.profraw ``` -------------------------------- ### Rewrite associative array expansion Source: https://github.com/anordal/shellharden/blob/master/CHANGELOG.md Transforms `${a[*]}` to `"${a[@]}"` for named arrays, analogous to the `$*` to `"$@"` transformation. ```shell ${a[*]} → "${a[@]}" ``` -------------------------------- ### Concatenating Variables and String Literals in Bash Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Demonstrates an alternative to string interpolation using braces, by concatenating a quoted variable expansion with a separate string literal. This method avoids potential issues with brace usage. ```bash "$var"'string literal' ``` -------------------------------- ### Safe String Comparison in Bash Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md The `test x"$s" = xyes` idiom is generally unnecessary for safety in modern Bash, as quoting and argument precedence handle most ambiguities. ```bash test x"$s" = xyes ``` -------------------------------- ### Deferred Cleanup with Trap in Bash Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Use `trap cleanup EXIT` to ensure cleanup functions are executed when the script exits, even if it terminates due to an error (errexit). ```bash tmpfile=$(mktemp -t myprogram-XXXXXX) cleanup() { rm -f "$tmpfile" } trap cleanup EXIT ``` -------------------------------- ### Checking Variable Existence in Bash (Bash 4.2+) Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Uses the `[[ -v varname ]]` construct to reliably check if a variable is set. Includes a feature check for compatibility with older Bash versions. ```bash # Feature check to fail early on Mac OS with Bash 3.9: [[ -v PWD ]] ``` ```bash [[ -v var ]] ``` -------------------------------- ### Capturing Command Output in Bash If-Statement Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Use an assignment within the `if` condition to capture a command's output while also checking its success. Avoid using `local` directly in this context. ```bash if output=$(command); then … fi ``` -------------------------------- ### Rewrite backticks to `$PWD` Source: https://github.com/anordal/shellharden/blob/master/CHANGELOG.md Replaces `` `pwd` `` with `$PWD` directly, even when quoting is not strictly required, for consistency. ```shell `pwd` → $PWD ``` -------------------------------- ### Explicitly Exit Bash Script with Success Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Ensures a Bash script terminates with an exit status of 0, indicating successful execution. This is the recommended way to end a script when the last command's status might not accurately reflect overall success. ```bash exit 0 ``` -------------------------------- ### Negated Command as If-Statement in Bash Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Use `! command || …` as a safe shorthand for an if-statement. This pattern correctly handles the exit status of the command. ```bash ! command || … ``` -------------------------------- ### Shellharden Rewriting Braces and Quotes in Bash Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Illustrates how Shellharden automatically adjusts braces and quotes for safety and consistency. It adds necessary quotes and can remove redundant braces around individually quoted variables. ```bash " ${arg} $arg"ument" " → ""$arg" "${arg}ument"" ``` ```bash " "${arg}"" → ""$arg"" ``` -------------------------------- ### Suppressing Command Failure in Bash Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Use `|| true` to prevent a script from exiting when a command fails. This is a common way to ignore errors for specific commands. ```bash command || true ``` -------------------------------- ### Rewrite array expansion for quoted variables Source: https://github.com/anordal/shellharden/blob/master/CHANGELOG.md Changes `for i in $a` to `for i in "${a[@]}"` when variable `a` must necessarily be an array to be quoted correctly. ```shell for i in $a → for i in "${a[@]}" ``` -------------------------------- ### Checking Exit Status Safely in Bash Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Avoid checking `$?` directly after a command if errexit is enabled, as the script may have already exited. The `if command; then ... else ... fi` structure is preferred. ```bash if command; then true else echo Command returned $? fi ``` -------------------------------- ### Avoid Unquoted Variables in Bash Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Unquoted variables can lead to unexpected behavior due to word splitting and wildcard expansion. Avoid this practice. ```bash $my_var ``` ```bash $(cmd) ``` -------------------------------- ### Safe Filename Quoting (Bash) Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md When dealing with filenames that contain special characters, use single quotes with proper escaping for the single quote itself (`'\''`) to ensure correct interpretation. ```bash echo 'Don'\''t stop (12" dub mix).mp3' ``` -------------------------------- ### Errexit Behavior in Group Commands in Bash Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Shows that `set -e` is ignored in group commands (`{ ... }`) when their success is checked by the caller. The script continues execution. ```bash { set -e false echo Unreachable } && echo Great success ``` -------------------------------- ### Safe Shorthand If-Statements in Bash Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md When using `&&` for conditional execution, always pair it with `|| true` to act as an else-branch. This prevents script termination if the condition is false. ```bash command && … || true ``` -------------------------------- ### Errexit Behavior in Functions in Bash Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Illustrates that `set -e` within a function is ignored if the function's success is checked by the caller. The script executes past the failing command. ```bash f() { set -e false echo Unreachable } f && echo Great success ``` -------------------------------- ### Quote Variables in Bash Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Always quote variable expansions to prevent word splitting and pathname expansion. This is a fundamental rule for safe Bash scripting. ```bash "$my_var" ``` ```bash " $(cmd)" ``` -------------------------------- ### Errexit Behavior in Subshells in Bash Source: https://github.com/anordal/shellharden/blob/master/how_to_do_things_safely_in_bash.md Demonstrates that `set -e` is ignored within subshells if the subshell's exit status is checked by the caller. The script proceeds past `false`. ```bash ( set -e false echo Unreachable ) && echo Great success ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.