summaryrefslogtreecommitdiffstats
path: root/bin/sudoers-add
blob: e359d46eb041f21b092df93693b9f2ecdfd4f758 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#!/usr/bin/env bash
# William Mantly <wmantly@gmail.com>
# MIT License
# https://github.com/wmantly/sudoers-add

NEWLINE=$'\n'
CONTENT=""
ME="$(basename "$(test -L "$0" && readlink "$0" || echo "$0")")"

if [ "$1" == "--help" ] || [ "$1" == "-h" ]; then
	echo "Usage: $ME [file_path] [sudoers-file-name]"
	echo "Usage: [content] | $ME sudoers-file-name"
	echo "This will take a sudoers config validate it and add it to /etc/sudoers.d/{sudoers-file-name}"
	echo "The config can come from a file, first usage example or piped in second example."

	exit 0
fi

if [ "$1" == "" ]; then
	(>&2 echo "This command take at lest one argument. See $ME --help")

	exit 1	
fi

if [ "$2" == "" ]; then
	FILE_NAME=$1
	shift
else
	FILE_NAME=$2
fi

if [[ $EUID -ne 0 ]]; then
	echo "This script must be run as root"

	exit 1
fi

while read -r line
do
	CONTENT+="${line}${NEWLINE}"
done < "${1:-/dev/stdin}"

if [ "$CONTENT" == "" ]; then
	(>&2 echo "No config content specified. See $ME --help")
	exit 1
fi

if [ "$FILE_NAME" == "" ]; then
	(>&2 echo "No sudoers file name specified. See $ME --help")
	exit 1
fi

# Verify that the resulting file name begins with /etc/sudoers.d
FILE_NAME="$(realpath "/etc/sudoers.d/$FILE_NAME")"
if [[ "$FILE_NAME" != "/etc/sudoers.d/"* ]] ; then
	echo -n "Invalid sudoers filename: Final sudoers file "
	echo "location ($FILE_NAME) does not begin with /etc/sudoers.d"
	exit 1
fi

# Make a temp file to hold the sudoers config
umask 077
TEMP_FILE=$(mktemp)
echo "$CONTENT" > "$TEMP_FILE"

# Make sure the content is valid
visudo_STDOUT=$(visudo -c -f "$TEMP_FILE" 2>&1)
visudo_code=$?
# The temp file is no longer needed
rm "$TEMP_FILE"

if [ $visudo_code -eq 0 ]; then
	echo "$CONTENT" > "$FILE_NAME"
	chmod 0440 "$FILE_NAME"
	echo "The sudoers file $FILE_NAME has been successfully created!"

	exit 0
else
	echo "Invalid sudoers config!"
	echo "$visudo_STDOUT"

	exit 1
fi