#!/bin/bash
# #################################################################################
# Exceed TurboX Connection Node
# © Rocket Software, Inc. or its affiliates. All Rights Reserved.
# ROCKET SOFTWARE, INC. CONFIDENTIAL
# #################################################################################
# Helper to let ETX work with SELinux
# #################################################################################

set -e

policy=etxproxy
install=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
workdir=$install/bin/sys/generated_selinux

if [[ $(getenforce 2>/dev/null) != "Enforcing" && $(getenforce) != "Permissive" ]]; then
	echo "SELinux is not enabled. Nothing to do."
	exit 0
fi

if [ "$1" = "allow" ]; then
	[ -d "$workdir" ] || mkdir "$workdir"
	pushd "$workdir"
	cat > "$policy.te" << _EOF_SELINUX_POLICY_
module $policy 1.0;

require {
        type default_t;
        type user_tmp_t;
        type unconfined_t;
        type unconfined_service_t;
        class dir { getattr read search write };
        class process { signal transition };
        class file entrypoint;
}

#============= unconfined_service_t ==============
allow unconfined_service_t unconfined_t:process transition;

#============= unconfined_t ==============
allow unconfined_t default_t:file entrypoint;
allow unconfined_t user_tmp_t:file entrypoint;
_EOF_SELINUX_POLICY_

	echo "Generating SELinux policy $workdir/$policy.te..."
	checkmodule -M -m -o "$policy.mod" "$policy.te"
	semodule_package -o "$policy.pp" -m "$policy.mod"
	echo "Installing SELinux policy $policy. This may take a few moments..."
	semodule --install "$policy.pp"

elif [ "$1" = "disallow" ]; then
	echo "Removing SELinux policy $policy. This may take a few moments..."
	# We don't use enable/disable because they seem to take just as long as install/remove
	# and they add complication when running allow again.
	semodule --remove "$policy"

else
	echo "Usage: $0 <allow|disallow>"
	echo ""
	echo " allow     Enables policy allowing etxproxy to launch subprocesses"
	echo " disallow  Disables policy, etxproxy subprocesses will fail"
fi
