#!/bin/bash
source /etc/profile.d/red[bB]order-manager.sh
##########  Variable Declarations - Start  ##########
#name of the current script
SCRIPT_NAME=configure-fsecure.sh
#version of the current script
SCRIPT_VERSION=1.3.2

LOGSTASH_ETCDIR_CONF=$LOGSTASH_PIPELINES_PATH/vault

#name of the service, in this case fsecure
SERVICE="fsecure"

RB_PATH=${RB_PATH:=""}
RB_EXTENSIONS_DIR="$RB_PATH/var/rb-extensions"

#name and location of fsecure logstash file
LOGSTASH_CONFFILE=$LOGSTASH_ETCDIR_CONF/41_fsecure.conf

MANUAL_CONFIG_INSTRUCTION="Manual instructions to configure fsecure is available at https://suport.redborder.com/docs/fsecure-server-logs#manual. Logstash troubleshooting instructions are available at https://support.redborder.com/docs/troubleshooting-logstash/"

INSTALLED_FILE=$EXTENSION_DIR/extension-installed.txt

##########  Variable Declarations - End  ##########


##########  FSecure Functions  - Start   ###########

#function to write the contents of  logstash config file

writeFileContents()
{
	echo "INFO" "INFO: Creating file $LOGSTASH_CONFFILE"
	sudo touch $LOGSTASH_CONFFILE
	sudo chmod o+w $LOGSTASH_CONFFILE

        if [ ! -f $DIMENSIONS_CONFFILE ]; then
          echo "cannot find the dimension file to setup the logstash pipeline. exiting..."
          exit 1
        fi

        # build the array of original dimensions
ORIG_DIM=$(
ruby - <<END
  require 'yaml'
  original_dimensions = []
  dimensions = {}
  dimensions = dimensions.merge(YAML.load_file("$DIMENSIONS_CONFFILE"))
  dimensions.each { | key, dimension | original_dimensions.push(dimension['original_dimension']) }
  puts original_dimensions.to_s
END
)

imfileStr='filter {
  if [message] =~ /PROXY-ERROR:/ {
    mutate {
      gsub => [
        "message", "#.*", ""
      ]
    }
    grok {
      patterns_dir => ["'$LOGSTASH_ETCDIR_CONF'/patterns/fsecure"]
      match => [
        "message","%{FSIGK_P1}",
        "message","%{FSIGK_UM}"
      ]      
    }
  }
}'

#change the file to variable from above and also take the directory of the fsecure log file.

sudo cat << EOIPFW > $LOGSTASH_CONFFILE
$imfileStr
EOIPFW

	restartLogstash
}

#function to write the contents of fsecure logstash config file
writeDimensionsFile()
{
	echo "INFO: Creating dimensions file $DIMENSIONS_CONFFILE"
	sudo touch $DIMENSIONS_CONFFILE
	sudo chmod o+w $DIMENSIONS_CONFFILE


imfileStr=$SERVICE'_connection_time:
  name: "FS - IGK - Connection Time"
  category: "fsecure"
  type: string
  original_dimension: "fsecure_connection_time"
'$SERVICE'_source_ip:
  name: "FS - IGK - Source Ip"
  category: "fsecure"
  type: string
  original_dimension: "fsecure_source_ip"
'$SERVICE'_protocol:
  name: "FS - IGK - Protocol"
  category: "fsecure"
  type: string
  original_dimension: "fsecure_protocol"
'$SERVICE'_http_code:
  name: "FS - IGK - HTTP Code"
  category: "fsecure"
  type: string
  original_dimension: "fsecure_http_code"
'$SERVICE'_file_size:
  name: "FS - IGK - File Size"
  category: "fsecure"
  type: string
  original_dimension: "fsecure_file_size"
'$SERVICE'_request_method:
  name: "FS - IGK - Request Method"
  category: "fsecure"
  type: string
  original_dimension: "fsecure_request_method"
'$SERVICE'_destiny_address:
  name: "FS - IGK - Destiny Address"
  category: "fsecure"
  type: string
  original_dimension: "fsecure_destiny_address"
'$SERVICE'_destiny_ip:
  name: "FS - IGK - Destiny IP"
  category: "fsecure"
  type: string
  original_dimension: "fsecure_destiny_ip"
'$SERVICE'_content_type:
  name: "FS - IGK - Content Type"
  category: "fsecure"
  type: string
  original_dimension: "fsecure_content_type"
'$SERVICE'_detection:
  name: "FS - IGK - Detection"
  category: "fsecure"
  type: string
  original_dimension: "fsecure_detection"
'$SERVICE'_virus_name:
  name: "FS - IGK - Virus Name"
  category: "fsecure"
  type: string
  original_dimension: "fsecure_virus_name"
'$SERVICE'_file_name:
  name: "FS - IGK - File Name"
  category: "fsecure"
  type: string
  original_dimension: "fsecure_file_name"
'$SERVICE'_quarantined_name:
  name: "FS - IGK - Quarantined Name"
  category: "fsecure"
  type: string
  original_dimension: "fsecure_quarantined_name"
'$SERVICE'_action:
  name: "FS - IGK - Action"
  category: "fsecure"
  type: string
  original_dimension: "fsecure_action"
'$SERVICE'_service_type:
  name: "FS - IGK - Service Type"
  category: "fsecure"
  type: string
  original_dimension: "fsecure_service_type"
'$SERVICE'_internal_process_id:
  name: "FS - IGK - Internal Process Id"
  category: "fsecure"
  type: string
  original_dimension: "fsecure_internal_process_id"
'$SERVICE'_process_id:
  name: "FS - IGK - Process Id"
  category: "fsecure"
  type: string
  original_dimension: "fsecure_process_id"
'$SERVICE'_host_ip:
  name: "FS - IGK - Host IP"
  category: "fsecure"
  type: string
  original_dimension: "fsecure_host_ip"
'$SERVICE'_processed_file:
  name: "FS - IGK - Processed File"
  category: "fsecure"
  type: string
  original_dimension: "fsecure_processed_file"
'$SERVICE'_checked_virus:
  name: "FS - IGK - Checked Virus"
  category: "fsecure"
  type: string
  original_dimension: "fsecure_checked_virus"
'$SERVICE'_detection_time:
  name: "FS - IGK - Detection Time"
  category: "fsecure"
  type: string
  original_dimension: "fsecure_detection_time"
'$SERVICE'_detection_info:
  name: "FS - IGK - Detection Info"
  category: "fsecure"
  type: string
  original_dimension: "fsecure_detection_info"
'$SERVICE'_protocol_sender:
  name: "FS - IGK - Protocol Sender"
  category: "fsecure"
  type: string
  original_dimension: "fsecure_protocol_sender"
'$SERVICE'_protocol_msg_id:
  name: "FS - IGK - Protocol Message Id"
  category: "fsecure"
  type: string
  original_dimension: "fsecure_protocol_msg_id"
'$SERVICE'_proxy_error:
  name: "FS - IGK - Proxy Error"
  category: "fsecure"
  type: string
  original_dimension: "fsecure_proxy_error"'

sudo cat << EOIPFW > $DIMENSIONS_CONFFILE
$imfileStr
EOIPFW
	
}

##########  FSecure Functions - End   ###########



##########  Start of the common part  ###########

#downloads configure-extensions.sh
setupDependencies() {
  ERROR="true"
  # Check if there is internet or/and can access to the web of the script
  response=$(curl --write-out %{http_code} --silent --output /dev/null https://repo.redborder.com/install/common/configure-extensions.sh)
  if [[ $response -eq 200 ]]; then
    echo "INFO: Downloading dependencies.."
    curl -s -o configure-extensions.sh https://repo.redborder.com/install/common/configure-extensions.sh
  else
    echo "configure-extensions script could not be retrieved, local copy is needed"
  fi
  
  if [ -f configure-extensions.sh ]; then
    if [ `head -1 configure-extensions.sh | grep bash | wc -l` -gt 0 ]; then
      source configure-extensions.sh "being-invoked"

      #definitions of variables relying on the configure-extensions-script
      EXTENSION_DIR=$RB_EXTENSIONS_DIR/$SERVICE
      DIMENSIONS_CONFFILE=$EXTENSION_DIR/dimensions.yml

      ERROR="false"
    else
      echo "local configure-extensions script is not valid, we need to exit"  
    fi
  fi
  
  if [ "$ERROR" != "false" ]; then
    echo "ERROR: Missing dependencies!"
    exit 1
  fi
}

#Setup Fsecure Patterns
setupPatterns(){
	echo "INFO: Creating Fsecure Patterns"
	sudo touch $RB_PATH/share/logstash-rules/fsecure

imfileStr='# Start/Stop

### Pattern 1:ACCESS file(GET short, POST, CONNECT short, HEAD, GET Keep Alive, HEAD, PASS_USER_AGENT)

FSIGK_P1	^%{SPACE}%{DATA:fsecure_connection_time} %{IPV4:fsecure_source_ip} %{DATA:fsecure_protocol}/%{DATA:fsecure_http_code} %{WORD:fsecure_file_size} %{WORD:fsecure_request_method} %{DATA:fsecure_destiny_address} - DIRECT/%{DATA:fsecure_destiny_ip} %{DATA:fsecure_content_type} DETECT-STAT:%{DATA:fsecure_detection}:%{DATA:fsecure_virus_name}:%{DATA:fsecure_file_name}:%{DATA:fsecure_quarantined_name}:: ACTION:%{DATA:fsecure_action}: PROXY-STAT:%{DATA:fsecure_service_type}:%{DATA:fsecure_internal_process_id}:%{DATA:fsecure_process_id}:%{DATA:fsecure_host_ip}:%{DATA:fsecure_processed_file}:%{DATA:fsecure_checked_virus}:%{DATA:fsecure_detection_time}:%{DATA:fsecure_detection_info}: PROTOCOL-STAT:%{DATA:fsecure_protocol_sender}:%{DATA:fsecure_protocol_msg_id}: PROXY-ERROR:%{GREEDYDATA:fsecure_proxy_error}:$
FSIGK_UM %{GREEDYDATA:fsecure_unmatched_messages}'

sudo cat << EOIPFW > $RB_PATH/share/logstash-rules/fsecure
$imfileStr
EOIPFW

sudo ln -snf $RB_PATH/share/logstash-rules/fsecure $LOGSTASH_ETCDIR_CONF/patterns/fsecure
}

#RemovePatterns
removePatterns(){
	sudo rm -r $LOGSTASH_ETCDIR_CONF/patterns/fsecure
	sudo rm -r $RB_PATH/share/logstash-rules/fsecure
}

#display usage syntax
usage()
{
cat << EOF
usage: configure-$SERVICE [-i to install]
usage: configure-$SERVICE [-r to rollback]
usage: configure-$SERVICE [-v for version]
usage: configure-$SERVICE [-u to update]
usage: configure-$SERVICE [-h for help]
EOF
}

##########  Get Inputs from User - Start  ##########

if [ $# -eq 0 ]; then
    usage
  exit
else
while [ "$1" != "" ]; do
    case $1 in
      -r | --rollback )
          REDBORDER_ROLLBACK="true"
          ;;
      -i | --install )
          INSTALL="true"
          ;;    
      -v | --version )
          echo "The version of $SERVICE is $SCRIPT_VERSION, to check for any update use ./configure-$SERVICE-$SCRIPT_VERSION -u"
          exit
          ;;
      -u | --update )
          echo "Checking for updates..."
          UPDATING="true"
          ;;
      -h | --help )
          usage
          exit
          ;;

    esac
    shift
done
fi

startCheck(){
    setupDependencies
    checkIfUserHasRootPrivileges
    SVERSION=`cat $LOGSTASH_CONFFILE | head -1 | awk '{print $2}'`
}

if [ "$REDBORDER_ROLLBACK" != "" ]; then
    startCheck
    removeRedborderConf
    removePatterns

elif [ "$INSTALL" == "true" ]; then
    startCheck
    if [ "$SVERSION" == "$SCRIPT_VERSION" ]; then
      echo "Already up to date"
    else
      installRedborderConf
      setupPatterns
    fi

elif [ "$UPDATING" == "true" ]; then
    startCheck
    checkForUpdate

else
    usage
fi

##########  Get Inputs from User - End  ##########
