#!/bin/bash -p
# see: https://developer.apple.com/library/archive/documentation/OpenSource/Conceptual/ShellScripting/ShellScriptSecurity/ShellScriptSecurity.html#//apple_ref/doc/uid/TP40004268-CH8-SW29

# EMBA - EMBEDDED LINUX ANALYZER
#
# Copyright 2020-2024 Siemens Energy AG
#
# EMBA comes with ABSOLUTELY NO WARRANTY. This is free software, and you are
# welcome to redistribute it under the terms of the GNU General Public License.
# See LICENSE file for usage of this software.
#
# EMBA is licensed under GPLv3
# SPDX-License-Identifier: GPL-3.0-only
#
# Author(s): Michael Messner

# Description:  Update script for collection of known exploited vulnerabilities

EMBA_CONFIG_PATH="./config"

## Color definition
GREEN="\033[0;32m"
ORANGE="\033[0;33m"
NC="\033[0m"  # no color

if ! [[ -d "${EMBA_CONFIG_PATH}" ]]; then
  echo "[-] No EMBA config directory found! Please start this crawler from the EMBA directory"
  exit 1
fi

if [[ -f "${EMBA_CONFIG_PATH}"/known_exploited_vulnerabilities.csv ]]; then
  echo -e "${GREEN}[+] Known exploit database has ${ORANGE}$(wc -l "${EMBA_CONFIG_PATH}"/known_exploited_vulnerabilities.csv | awk '{print $1}')${GREEN} exploit entries (before update).${NC}"
fi

echo "[*] Update the known_exploited_vulnerabilities database"
wget https://www.cisa.gov/sites/default/files/csv/known_exploited_vulnerabilities.csv -O "${EMBA_CONFIG_PATH}"/known_exploited_vulnerabilities_new.csv || (echo "[-] Update of known exploited vulnerabilities failed" && exit 1)

if [[ $(wc -l "${EMBA_CONFIG_PATH}"/known_exploited_vulnerabilities_new.csv | awk '{print $1}') -ge $(wc -l "${EMBA_CONFIG_PATH}"/known_exploited_vulnerabilities.csv | awk '{print $1}') ]]; then
  # copy it only if the updated file is bigger then the installed one
  mv "${EMBA_CONFIG_PATH}"/known_exploited_vulnerabilities_new.csv "${EMBA_CONFIG_PATH}"/known_exploited_vulnerabilities.csv || (echo "[-] Update of known exploited vulnerabilities failed" && exit 1)
fi

if [[ -f "${EMBA_CONFIG_PATH}"/known_exploited_vulnerabilities_new.csv ]]; then
  rm "${EMBA_CONFIG_PATH}"/known_exploited_vulnerabilities_new.csv
fi

if [[ -f "${EMBA_CONFIG_PATH}"/known_exploited_vulnerabilities.csv ]]; then
  echo -e "${GREEN}[+] Known exploit database now has ${ORANGE}$(wc -l "${EMBA_CONFIG_PATH}"/known_exploited_vulnerabilities.csv | awk '{print $1}')${GREEN} exploit entries (after update).${NC}"
fi
