bash

Bash Scripting Tips

I went looking around for bash scripting tips, especially secure coding of bash. Can't find much information, so decided to consolidate whatever I found here. Smiling

  • Salt string comparisons of variables to increase security

    if [[ "a$?" == "a4" ]]; then
    

  • Use the full paths to any binaries, either by hardcoding them into the script or use variable substitution. This prevents the script from executing incorrect/rogue binaries in the path.

    /bin/grep "hardcoding the full path" *
    
    echo=/bin/echo
    ${echo} "From bash manpage under EXPANSION:
    The order of expansions is: brace expansion, tilde expansion,  parameter,
    variable  and  arithmetic  expansion  and command substitution (done in a
    left-to-right fashion), word splitting, and pathname expansion."
    

  • Change the environment path at the start of the script to ensure no rouge directories are in the PATH

    #!/bin/bash
    # comments
    PATH=/bin:/usr/bin
    

  • Write a function to explain the usage of the script

    function print_usage () {
        ${echo} "
    $0
    Usage: $0 [-a opts] [arguments]
     or    $0 -h
    Description: Something fishy
    Options:
      -a opts    (Optional) Options
      -h         (Optional) Help
      arguments  Smelly smelly fish
    "
    }
    

  • Here's a sample code snippet to process script options

    if [ $# -lt 2 ]; then
        print_usage
        exit 1
    else
        while getopts ha:b: options; do
            case "${options}" in
                h)  print_usage
                    exit 1
                    ;;
                a)  flag=${options}
                    ;;
                b)  flag=${options}
                    ;;
                *)  echo "default case, everything else fits here"
                    ;;
            esac
        done
        shift $((${OPTIND} - 1))
    

  • Variables should be enclosed in parenthesis when used, to indicate exactly which variable you are using. Of course, this can prevent an exploit involving longer variable names.

    a=erie
    ab=were
    if [[ "${a}b" == "erieb" ]]; then
    

Syndicate content