#!/bin/bash

##
# Astra PDAC Helper
#
# An assistant script for PDAC in cases where the necessary
# operation cannot be performed directly in the rule file for
# one reason or another, such commands are redirected here via
# the udev token RUN.
##

case "${1}" in
	# define and assign access rights for the device file
	"assign")
		if [[ (-z "${1}") || (-z "${2}") || (-z "${3}") || (-z "${4}") ]] ; then
			exit 1
		fi
		kernel="${2}"
		fstype="${3}"
		aml="${4}"
		case "$fstype" in
			"ntfs"|"iso9660")
				if [ ! -e /dev/$kernel\_pdac ]; then
					chown root:$aml /dev/$kernel
				else
					pdac_user=$(grep '^user=' /dev/$kernel\_pdac | cut -d'=' -f2)
					pdac_group=$(grep '^group=' /dev/$kernel\_pdac | cut -d'=' -f2)
					chown $pdac_user:$pdac_group /dev/$kernel
				fi
			;;
		esac
	;;
	# logging of part of PDAC security events by sending astraevents-compatible data to syslog
	"log")
		case "${2}" in
			"device-connect-status-changed")
				if ! [[ (-z "${11}") || (-z "${12}") ]] ; then
					let "fssize = ${11} * ${12}"
				else
					fssize="unknown"
				fi
				
				case "${14}" in
					"add")    action="подключение"
							  type="new-device-connect"
					;;
					"remove") action="отключение"
							  type="new-device-disconnect"
					;;
				esac
additional_params="fs_label=\"${8}\" \
dev_type=\"${9}\" \
dev_subsystem=\"${10}\" \
fs_size=\"$fssize\" \
fs_type=\"${13}\" \
action=\"$action\" \
dev_path=\"${15}\" \
dev_bus=\"${16}\""
			;;
			"usb-storage-connected")
				let "fssize = ${11} * ${12}"
				type="usb-storage-connected"
additional_params="fs_label=\"${8}\" \
dev_type=\"${9}\" \
dev_subsystem=\"${10}\" \
fs_size=\"$fssize\" \
fs_type=\"${13}\" \
action=\"${14}\" \
dev_path=\"${15}\" \
dev_bus=\"${16}\""
			;;
			"pdac-connect")
				case "${8}" in
					"allow") action="разрешение"
							 type="pdac-connect-allow"
					;;
					"block") action="блокировка"
							 type="pdac-connect-block"
					;;
					"by_rule") action="разрешение с назначением"
						       type="pdac-connect-by-rule"
					;;
				esac
				case "${10}" in
					"device") target="устройство"
					;;
					"type") target="тип устройства"
					;;
					"bus") target="шина подключения"
					;;
				esac
additional_params="action=\"$action\" \
pdac_type=\"${9}\" \
pdac_target=\"$target\" \
pdac_bus=\"${11}\" \
dev_path=\"${12}\""
			;;
		esac

logger="/usr/bin/logger -e -t pdachelper -p local4.info -- "

base_params="unixtime=\"$(date +%s)\" \
time=\"$(date +'%Y-%m-%dT%H:%M:%S%:z')\" \
pid=\"${3}\" \
vid=\"${4}\" \
exe=\"/usr/sbin/astra-pdac-helper\" \
success=\"1\" \
serial_number=\"${5}\" \
dev_name=\"$(echo -e "${6} (${7})")\" \
user=\"$(id -nu $UID)\" \
uid=\"$UID\" \
type=\"$type\""

$logger $base_params $additional_params
;;

esac
