#!/bin/sh
#
# Set Output Colors
RED=`tput setaf 1`
GRB=`tput setaf 2; tput bold`
YLW=`tput setaf 3`
BLB=`tput setaf 4; tput bold`
BLD=`tput bold`
RST=`tput sgr0`
#
#
#
#read -p "${BLB}Enter A Description For Your New ESA Rule: ${RST}" ESA_RULE_DESCRIPTION
#read -p "Enter The \"Alert On\" Meta Key From Your App Rule : " APP_RULE_META_KEY
#read -p "${BLB}Enter your ESA Rule Severity ${YLW}(MEDIUM, HIGH, or CRITICAL): ${RST}" ESA_RULE_SEVERITY
#read -p "${BLB}Choose the Appropriate Checksum Meta Key for your Rule ${YLW}(checksum_src, checksum_dst, checksum): ${RST}" RISK_RULE_FILE_META
#read -p "${BLB}Choose the Appropriate Filename Meta Key for your Rule ${YLW}(filename_src, filename_dst, filename): ${RST}" RISK_RULE_FILE_NAME
#read -p "${BLB}Enable Risk Scoring? ${YLW}true or ${YLW}false: ${RST}" RISK_SCORING

# Prompt user for input for all the required fields for custom ESA and Risk Scoring Rules
# Applying some error checking and input validation to try and eliminate errors in formatting
while true; do
	read -p "${BLB}Enter A Name For Your New ESA Rule: ${RST}" ESA_RULE_NAME
	if [ -z "$ESA_RULE_NAME" ]; then
		echo "${RED}${BLD}   Your ESA Rule Name Cannot Be Blank. Please try again.${RST}"
	elif [ -n "$ESA_RULE_NAME" ]; then
		echo "${YLW}   ESA Rule Name Set: ${GRB}${BLD}"$ESA_RULE_NAME${RST}
		break
	else
		:
	fi
done

while true; do
	read -p "${BLB}Enter A Description For Your New ESA Rule: ${RST}" ESA_RULE_DESCRIPTION
	if [ -z "$ESA_RULE_DESCRIPTION" ]; then
		echo "${RED}${BLD}   Your ESA Rule Description Cannot Be Blank. Please try again.${RST}"
	elif [ -n "$ESA_RULE_NAME" ]; then
		echo "${YLW}   ESA Rule Description Set: ${GRB}${BLD}"$ESA_RULE_DESCRIPTION${RST}
		break
	else
		:
	fi
done

while true; do
	read -p "${BLB}Enter The Name From Your Log Decoder App Rule ${YLW}(case sensitive... must match EXACTLY): ${RST}" APP_RULE_META_VALUE
	echo "${YLW}   Checking for a valid Log Decoder App Rule. This may take a few seconds...${RST}"
	appRuleCheck=$(salt "*" cmd.run 'cat /etc/netwitness/ng/NwLogdecoder.cfg' 2>&1 | grep -o "$APP_RULE_META_VALUE" | sed "1q;d")
	#echo $appRuleCheck
	if [ -z "$appRuleCheck" ]; then
		echo "${RED}${BLD}   That does not appear to match an existing Log Decoder App Rule Name. Please try again.${RST}"
	elif [[ $appRuleCheck == $APP_RULE_META_VALUE ]]; then
		echo "${YLW}   Found Log Decoder App Rule: ${GRB}${BLD}"$APP_RULE_META_VALUE${RST}
		echo "${YLW}   Identifying Meta Key from ${GRB}${BLD}"$APP_RULE_META_VALUE"${RST}${YLW}, this may take another few seconds...${RST}"
		APP_RULE_META_KEY=$(salt "*" cmd.run 'cat /etc/netwitness/ng/NwLogdecoder.cfg' 2>&1 | grep "$APP_RULE_META_VALUE" | sed "1q;d" | grep -Po "alert=.+?\s" | sed -e "s/alert=//" | tr -d " ")
		echo "${YLW}   Found Meta Key: ${GRB}${BLD}"$APP_RULE_META_KEY${RST}
		break
	else
		:
	fi
done

while true; do
	read -p "${BLB}Enter your ESA Rule Severity ${YLW}(MEDIUM  HIGH  CRITICAL): ${RST}" ESA_RULE_SEVERITY
	case $ESA_RULE_SEVERITY in
		MEDIUM ) echo "${YLW}   ESA Rule Severity Set: ${GRB}${BLD}"$ESA_RULE_SEVERITY${RST}; break;;

		HIGH ) echo "${YLW}   ESA Rule Severity Set: ${GRB}${BLD}"$ESA_RULE_SEVERITY${RST}; break;;

		CRITICAL ) echo "${YLW}   ESA Rule Severity Set: ${GRB}${BLD}"$ESA_RULE_SEVERITY${RST}; break;;

		* )	echo "${RED}${BLD}   You Must Choose One of: MEDIUM  HIGH  CRITICAL${RST}"
			echo "${RED}${BLD}   **These Options Are Case Sensitive**${RST}";;
	esac
done

while true; do
	echo "${BLB}Choose the Appropriate Checksum Meta Key for your Risk Scoring Rule${RST}"
	echo "${YLW}   **NOTE: You May Choose To SKIP The Checksum Meta Key...**${RST}"
	echo "${YLW}   **...Which Will Also Automatically SKIP The Filename Meta Key**${RST}"
	read -p "${YLW}${BLD}   checksum_src  checksum_dst  checksum  SKIP: ${RST}" RISK_RULE_FILE_META
	case $RISK_RULE_FILE_META in
		checksum_src ) echo "${YLW}   Checksum Meta Key Set: ${GRB}${BLD}"$RISK_RULE_FILE_META${RST}; break;;

		checksum_dst ) echo "${YLW}   Checksum Meta Key Set: ${GRB}${BLD}"$RISK_RULE_FILE_META${RST}; break;;

		checksum ) echo "${YLW}   Checksum Meta Key Set: ${GRB}${BLD}"$RISK_RULE_FILE_META${RST}; break;;

		SKIP ) echo "${RED}   You Have Chosen To ${BLD}SKIP${RST}${RED} This${RST}"; break;;

		* )	echo "${RED}${BLD}   You Must Choose One of: checksum_src  checksum_dst  checksum  SKIP${RST}"
			echo "${RED}${BLD}   **These Options Are Case Sensitive**${RST}";;
	esac
done

while true; do
	echo "${BLB}Choose the Appropriate Filename Meta Key for your Risk Scoring Rule${RST}"
	#echo "${YLW}   **NOTE: If You Previously Chose to SKIP The Checksum Meta Key, The Filename Meta Key Will Also Skip**${RST}"
	if [[ $RISK_RULE_FILE_META == "SKIP" ]]; then
		echo "${RED}   You Previously Chose to ${BLD}SKIP${RST}${RED} The Checksum Meta Key...${RST}"
		echo "${RED}   ....Skipping The Filename Meta Key Also${RST}"
		RISK_RULE_FILE_NAME="SKIP"
		break
	else
		read -p "${YLW}${BLD}   filename_src  filename_dst  filename: ${RST}" RISK_RULE_FILE_NAME
		case $RISK_RULE_FILE_NAME in
			filename_src ) echo "${YLW}   Checksum Meta Key Set: ${GRB}${BLD}"$RISK_RULE_FILE_NAME${RST}; break;;

			filename_dst ) echo "${YLW}   Checksum Meta Key Set: ${GRB}${BLD}"$RISK_RULE_FILE_NAME${RST}; break;;

			filename ) echo "${YLW}   Checksum Meta Key Set: ${GRB}${BLD}"$RISK_RULE_FILE_NAME${RST}; break;;

			* )	echo "${RED}${BLD}   You Must Choose One of: filename_src  filename_dst  filename${RST}"
				echo "${RED}${BLD}   **These Options Are Case Sensitive**${RST}";;
		esac
	fi
done

while true; do
	read -p "${BLB}Enable Risk Scoring? ${YLW}true or ${YLW}false: ${RST}" RISK_SCORING
	case $RISK_SCORING in
		true ) echo "${YLW}Checksum Meta Key Set: ${GRB}${BLD}"$RISK_SCORING${RST}; break;;

		false ) echo "${YLW}Checksum Meta Key Set: ${GRB}${BLD}"$RISK_SCORING${RST}; break;;

		* )	echo "${RED}${BLD}   You Must Choose One of: true  false${RST}"
			echo "${RED}${BLD}   **These Options Are Case Sensitive**${RST}";;
	esac
done

# Gather all the input into the correct fields and format in preparation
# for adding the custom rules to the system
esaRulePretty="{ \"id\": \"${GRB}$ESA_RULE_NAME${RST}\", \"key\": \"${GRB}$APP_RULE_META_KEY${RST}\", \"value\": \"${GRB}$APP_RULE_META_VALUE${RST}\", \"title\": \"${GRB}$ESA_RULE_NAME${RST}\", \"type\": \"ENDPOINT\", \"enabled\": true, \"description\": \"${GRB}$ESA_RULE_DESCRIPTION${RST}\", \"severity\": \"${GRB}$ESA_RULE_SEVERITY${RST}\" }"
esaRule="{ \"id\": \"$ESA_RULE_NAME\", \"key\": \"$APP_RULE_META_KEY\", \"value\": \"$APP_RULE_META_VALUE\", \"title\": \"$ESA_RULE_NAME\", \"type\": \"ENDPOINT\", \"enabled\": true, \"description\": \"$ESA_RULE_DESCRIPTION\", \"severity\": \"$ESA_RULE_SEVERITY\" }"

if [[ $RISK_RULE_FILE_META == "SKIP" ]] && [[ $RISK_RULE_FILE_NAME == "SKIP" ]]; then
	riskRulePretty="[ { \"name\" : \"${GRB}$ESA_RULE_NAME${RST}\", \"enabled\" : ${GRB}$RISK_SCORING${RST}, \"handler\" : \"Default\", \"entities\" : { }, \"metas\" : { \"Host\" : [ { \"meta\" : \"agent_id\", \"name\" : \"alias_host\", \"weight\" : NumberInt(100) } ] }, \"_class\" : \"com.rsa.asoc.respond.pipeline.risk.rules.AlertScoringRule\" } ]"
	echo -e "db.risk_rule.insert( [ { \"name\" : \"$ESA_RULE_NAME\", \"enabled\" : $RISK_SCORING, \"handler\" : \"Default\", \"entities\" : { }, \"metas\" : { \"Host\" : [ { \"meta\" : \"agent_id\", \"name\" : \"alias_host\", \"weight\" : NumberInt(100) } ] }, \"_class\" : \"com.rsa.asoc.respond.pipeline.risk.rules.AlertScoringRule\" } ] )" > /tmp/mongoRiskRuleCustom.js
else
	riskRulePretty="[ { \"name\" : \"${GRB}$ESA_RULE_NAME${RST}\", \"enabled\" : ${GRB}$RISK_SCORING${RST}, \"handler\" : \"Default\", \"entities\" : { }, \"metas\" : { \"File\" : [ { \"meta\" : \"${GRB}$RISK_RULE_FILE_META${RST}\", \"name\" : \"${GRB}$RISK_RULE_FILE_NAME${RST}\", \"weight\" : NumberInt(100) } ], \"Host\" : [ { \"meta\" : \"agent_id\", \"name\" : \"alias_host\", \"weight\" : NumberInt(100) } ] }, \"_class\" : \"com.rsa.asoc.respond.pipeline.risk.rules.AlertScoringRule\" } ]"
	echo -e "db.risk_rule.insert( [ { \"name\" : \"$ESA_RULE_NAME\", \"enabled\" : $RISK_SCORING, \"handler\" : \"Default\", \"entities\" : { }, \"metas\" : { \"File\" : [ { \"meta\" : \"$RISK_RULE_FILE_META\", \"name\" : \"$RISK_RULE_FILE_NAME\", \"weight\" : NumberInt(100) } ], \"Host\" : [ { \"meta\" : \"agent_id\", \"name\" : \"alias_host\", \"weight\" : NumberInt(100) } ] }, \"_class\" : \"com.rsa.asoc.respond.pipeline.risk.rules.AlertScoringRule\" } ] )" > /tmp/mongoRiskRuleCustom.js
fi

echo -e 'connect --service correlation-server\ncd correlation/keyvalue/settings/set\ninvoke --file /tmp/esaCustom.json' > /tmp/nwShellEsaCustom.script
echo "$esaRule" > /tmp/esaCustom.json

# Display the formatted custom rules for user review and validation
sleep 2
echo ""
echo "${YLW}   Review your ESA Rule For Accuracy${RST}"
echo "${YLW}   Your Choices Are ${GRB}Highlighted${RST}"
echo "${YLW}   Everything Else Is Hardcoded And Should Not Be Changed${RST}"
echo ""
echo "$esaRulePretty"
echo ""
sleep 2
echo "${YLW}   Review your Risk Scoring Rule For Accuracy${RST}"
echo "${YLW}   Your Choices Are ${GRB}Highlighted${RST}"
echo "${YLW}   Everything Else Is Hardcoded And Should Not Be Changed${RST}"
echo ""
echo "$riskRulePretty"
echo ""
sleep 2

# Prompt for user input to confirm whether to add the custom rules
while true; do
	read -p "${BLB}Continue And Add Custom Rules? ${YLW}${BLD}(y/N) ${RST}" continue
	case $continue in
		[yY]* )	echo -e "\n${YLW}Adding Your ESA Rule To The Correlation Server. This will take a few seconds...${RST}";
				nw-shell @/tmp/nwShellEsaCustom.script;
				echo -e "\n${YLW}Adding Your Risk Scoring Rule To The Respond Server. This will also take a few seconds...${RST}";
				# Get "deploy_admin" password
				DEPLOY_PW=$(security-cli-client --get-config-prop --prop-hierarchy nw.security-client --prop-name platform.deployment.password --quiet)
				mongo respond-server --authenticationDatabase admin -u deploy_admin -p $DEPLOY_PW /tmp/mongoRiskRuleCustom.js --quiet;
				echo -e "\n${YLW}Done.${RST}";
				echo -e "\n${YLW}Confirming Presence Of Both Rules In the Database...${RST}";
				newEsaRule=$(mongo correlation-server --authenticationDatabase admin -u deploy_admin -p $DEPLOY_PW --eval "db.keyValueRuleSettingsEntity.find({title:\"$ESA_RULE_NAME\"})" --quiet);
				riskScoringRule=$(mongo respond-server --authenticationDatabase admin -u deploy_admin -p $DEPLOY_PW --eval "db.risk_rule.find({name:\"$ESA_RULE_NAME\"})" --quiet)
				if [ -z "$newEsaRule" ] || [ -z "$riskScoringRule" ]; then
					echo "${RED}${BLD}   Something Went Wrong, Please Try Again. Exiting...${RST}"
					exit
				else
					echo ""
					echo "${YLW}Your ESA Rule In the Correlation Server...${RST}"
					echo ""
					echo "$newEsaRule"
					echo ""
					echo "${YLW}Your Risk Scoring Rule In the Respond Server...${RST}"
					echo ""
					echo "$riskScoringRule"
					echo ""
					echo "${GRB}Confirmed Both Rules Added Successfully. Restarting Respond Server...${RST}"
					systemctl restart rsa-nw-respond-server
				fi
				break;;

		[nN]* ) echo "${RED}${BLD}   Exiting...${RST}";	exit;;

		* ) echo "${YLW}   Y or N, please${RST}";;
	esac
done
