Search code examples
bashsecuritysshredhatopenssh

SSHD Config checking in bash script


I'm currently making a simple security audit script, which will print OK/Error for every mismatch in configuration. Scenario is next - for example, for SSHD_Config I've put next if case:

if [ "`grep -E ^Protocol /etc/ssh/sshd_config`" == "Protocol 1" ]; then
  echo "Protocol should be set to 2";
fi

The problem is - what if there is more than one space between some variable and its value? (Protocol 2 or PermitRootLogin No for ex.); /*s , /s and similar tricks didn't help.

Does anybody have a sample for checking SSHD Config in a bash script to post cases here? Thanks in advance !


Solution

  • The -E option of grep puts it in extended regular expressions mode. So, you can use extended regular expressions (^Protocol +1 means a line starting with Protocol, followed by 1 or more spaces, and then character 1):

    if grep -Eq '^Protocol +1' /etc/ssh/sshd_config; then
      echo "Protocol should be set to 2";
    fi
    

    [yY] means character y or Y:

    if grep -Eq '^PermitEmptyPasswords +[yY][eE][sS]' /etc/ssh/sshd_config; then
      echo "PermitEmptyPasswords should be set to no";
    elif grep -Eq '^PermitEmptyPasswords +[nN][oO]' /etc/ssh/sshd_config; then
      echo "PermitEmptyPasswords meets requirements";
    fi
    

    And many other interesting features. Notes:

    • You should probably consider cases where you have more than one matching line in the sshd_config file.
    • The -q grep option suppresses the printing of matching lines. grep just exits with status 0 if a matching line has been found, else with status 1 (not found) or 2 (error).
    • The if statement can be directly followed by a list of commands to execute. If the exit status of the list is 0, the then branch is taken. In our case the list is just the grep.