#!/bin/bash
# Version: 1.0

# Warning! Be sure to download latest version of this script from its primary source:
# https://access.redhat.com/security/vulnerabilities/3199382
# DO NOT blindly trust any internet sources and NEVER do `curl something | bash`!

# Checking against the list of vulnerable packages is necessary because of the way how features
# are back-ported to older versions of packages in various channels.


VULNERABLE_VERSIONS=(
    'dnsmasq-2.66-12.ael7b'
    'dnsmasq-2.66-13.ael7b_1'
    'dnsmasq-2.66-14.ael7b_1'
    'dnsmasq-2.39-2.el5'
    'dnsmasq-2.45-1.el5_2.1'
    'dnsmasq-2.45-1.1.el5_3'
    'dnsmasq-2.48-4.el6'
    'dnsmasq-2.48-5.el6'
    'dnsmasq-2.48-6.el6'
    'dnsmasq-2.48-13.el6'
    'dnsmasq-2.48-14.el6'
    'dnsmasq-2.48-16.el6_7'
    'dnsmasq-2.48-17.el6'
    'dnsmasq-2.66-10.el7'
    'dnsmasq-2.66-12.el7'
    'dnsmasq-2.66-13.el7_1'
    'dnsmasq-2.66-14.el7_1'
    'dnsmasq-2.66-14.el7_2.1'
    'dnsmasq-2.66-21.el7'
    'dnsmasq-2.76-2.el7'
)


basic_args() {
    # Parses basic commandline arguments and sets basic environment.
    #
    # Args:
    #     parameters - an array of commandline arguments
    #
    # Side effects:
    #     Exits if --help parameters is used
    #     Sets COLOR constants and debug variable

    local parameters=( "$@" )

    RED="\033[1;31m"
    YELLOW="\033[1;33m"
    GREEN="\033[1;32m"
    BOLD="\033[1m"
    RESET="\033[0m"
    for parameter in "${parameters[@]}"; do
        if [[ "$parameter" == "-h" || "$parameter" == "--help" ]]; then
            echo "Usage: $( basename "$0" ) [-n | --no-colors] [-d | --debug]"
            exit 1
        elif [[ "$parameter" == "-n" || "$parameter" == "--no-colors" ]]; then
            RED=""
            YELLOW=""
            GREEN=""
            BOLD=""
            RESET=""
        elif [[ "$parameter" == "-d" || "$parameter" == "--debug" ]]; then
            debug=true
        fi
    done
}


basic_reqs() {
    # Prints common disclaimer and checks basic requirements.
    #
    # Args:
    #     CVE - string printed in the disclaimer
    #
    # Side effects:
    #     Exits when 'rpm' command is not available

    local CVE="$1"

    # Disclaimer
    echo
    echo -e "${BOLD}This script is primarily designed to detect $CVE on supported"
    echo -e "Red Hat Enterprise Linux systems and kernel packages."
    echo -e "Result may be inaccurate for other RPM based systems.${RESET}"
    echo

    # RPM is required
    if ! command -v rpm &> /dev/null; then
        echo "'rpm' command is required, but not installed. Exiting."
        exit 1
    fi
}


check_supported_kernel() {
    # Checks if running kernel is supported.
    #
    # Args: 
    #     running_kernel - kernel string as returned by 'uname -r'
    #
    # Side effects:
    #     Exits when running kernel is obviously not supported
    
    local running_kernel="$1"

    # Check supported platform
    if [[ "$running_kernel" != *".el"[5-7]* ]]; then
        echo -e "${RED}This script is meant to be used only on Red Hat Enterprise"
        echo -e "Linux 5, 6 and 7.${RESET}"
        exit 1
    fi   
}


get_rhel() {
    # Gets RHEL number.
    # 
    # Args: 
    #     running_kernel - kernel string as returned by 'uname -r'
    #
    # Prints:
    #     RHEL number, e.g. '5', '6', or '7'
    
    local running_kernel="$1"
    
    local rhel=$( sed -r -n 's/^.*el([[:digit:]]).*$/\1/p' <<< "$running_kernel" )
    echo "$rhel"
}


check_package() {
    # Checks if installed package is in list of vulnerable packages.
    #
    # Args:
    #     installed_packages - installed packages string as returned by 'rpm -qa package'
    #                          (may be multiline)
    #     vulnerable_versions - an array of vulnerable versions
    #
    # Prints:
    #     First vulnerable package string as returned by 'rpm -qa package', or nothing

    local installed_packages=( $1 )  # Convert to array, use word splitting
    shift
    local vulnerable_versions=( "$@" )

    for tested_package in "${vulnerable_versions[@]}"; do
        for installed_package in "${installed_packages[@]}"; do
            installed_package_without_arch="${installed_package%.*}"
            if [[ "$installed_package_without_arch" == "$tested_package" ]]; then
                echo "$installed_package"
                return 0
            fi
        done
    done
}


get_installed_packages() {
    # Checks for installed packages of a 'package_name'. Compatible with RHEL5.
    #
    # Args:
    #     package_name - package name string
    #
    # Prints:
    #     Lines with N-V-R.A strings of all installed packages.

    local package_name="$1"

    rpm -qa --queryformat="%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n" "$package_name"
}


if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then

    basic_args "$@"
    basic_reqs "CVE-2017-14491"
    running_kernel=$( uname -r )
    check_supported_kernel "$running_kernel"

    rhel=$( get_rhel "$running_kernel" )
    if [[ "$rhel" == "5" ]]; then
        export PATH='/sbin':$PATH
    fi

    # dnsmasq version
    installed_packages=$( get_installed_packages "dnsmasq" )
    if [[ ! "$installed_packages" ]]; then
        echo -e "${GREEN}'dnsmasq' is not installed${RESET}."
        exit 0
    fi

    # Basic checks
    vulnerable_package=$( check_package "$installed_packages" "${VULNERABLE_VERSIONS[@]}" )



    # Debug prints
    if [[ "$debug" ]]; then
        echo "installed_packages = *$installed_packages*"
        echo "vulnerable_package = *$vulnerable_package*"
        echo "running_kernel = *$running_kernel*"
        echo "rhel = *$rhel*"
        echo
    fi

    # Results
    echo -e "Detected 'dnsmasq' packages are:${BOLD}"
    echo -e "$installed_packages${RESET}"

    if [[ "$vulnerable_package" ]]; then

        echo -e "${RED}This dnsmasq version is vulnerable.${RESET}"
        echo -e "Red Hat recommends that you update the dnsmasq package."
        echo -e "Follow https://access.redhat.com/security/vulnerabilities/3199382 for advice."
        exit 2

    else
        echo -e "${GREEN}This dnsmasq version is not vulnerable.${RESET}"
        exit 0
    fi
fi
