-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.sh
540 lines (463 loc) · 19 KB
/
main.sh
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
#!/bin/bash
#######
# Name: Linux Security Script for Debian and Redhat distributions
# Goal: Secure both Ubuntu and Redhat low-hanging fruit
# By: Tristan Stapert (aka tbird)
# Credits: @sour and others for good inspiration
#######
#######
# Goals and outcome (always growing. Initial ideas)
#
# Set closer hosted repositories if possible
# Permission management
# - Fix file permissions
# - /etc/shadow
# - /etc/gshadow
# - /etc/passwd
# - /etc/group
# - /etc/sudoers
# - lockdown SSH keys?
# - remove bad SUID bins?
# User audits
# - Verify good users
# - Remove bad admins
# - Check sudoers
# - Check groups
# Firewalls (using iptables primarily, maybe ufw)
# - Evaluate open ports
# - Configure initial rule list
# - Manual verification and edit
# - continue to next phase
# Some common configuration file hardening
# Other subject to time allowance
# - Harden SSH?
# - Harden FTP?
# Updates and Upgrades!
# - Last segment of code will do this due to time requirement
#######
#######
# Colors for clear output
#######
blue='\e[1m'
red='\033[1;31m'
yellow='\033[1;33m'
green='\033[1;32m'
nocolor='\e[m'
good="${green}[+] ${nocolor}"
prompt="${yellow}[?] ${nocolor}"
warn="${yellow}[!] ${nocolor}"
error="${red}[#] ${nocolor}"
########
# Common Variables
########
# SET THIS WITH THE NEW BATCH PASSWORD!
password_change="Password1!"
########
# Reminder Flags
# If failure, turn on for end reminder
########
#TODO Add more reminder flags for an closing reminder...
repo_changed=0
repo_update=0
user_audit=0
admin_audit=0
sudoers_audit=0
firewalls_deployed=0
########
# Common Functions
########
# credits @sour, thanks for a succinct confirmation prompt
confirm() {
while true; do
echo -en "\t$1 (y/n): "
read
case $REPLY in
[yY]) return 0;;
*) return 1;;
esac
done
}
#########
# INIT
#########
clear
echo -e "\tWelcome to the quick linux security script of Tbird. Hopefully this does something good!"
echo -e "\tThis does require an operator! please stand by and follow prompted tasks."
#* Verify root privileges
if [[ $EUID -ne 0 ]]; then
echo -e "${error} MUST BE RUN AS ROOT!"
exit 1
fi
# DEBUG
echo -e "${good} Welcome, root!"
#########
# Point Repositories at repo.ialab.dsu.edu for faster installations.
# Then run a quick update so that later package installs go fast
#########
if confirm "${prompt} Change repositories to DSU hosted collection?"; then
#* Notify user that repositories are being dynamically adjusted
echo -e "${good}Correcting repositories based on system active system information."
os_id=$(cat /etc/os-release | awk -F= '/^ID=/{print $2}');
#TODO Verify that all ubuntu test versions work with the repository change over!
# ialab currently supports back to 14.04...
#* Ubuntu related repository format
if [[ "$os_id" == "ubuntu" ]]; then
echo -e "${good}This is believed to be ${green}UBUNTU${nocolor}. We are configuring the sources.list and moving source.list.d"
os_version=$(cat /etc/os-release | awk -F= '/VERSION_CODENAME=/{print $2}');
# make backups
repos="/etc/apt/sources.list"
cp "$repos" "$repos.bak"
mv "$repos.d" "$repos.d.bak"
echo "deb http://repo.ialab.dsu.edu/ubuntu/ $os_version main restricted universe multiverse" > $repos
echo "deb http://repo.ialab.dsu.edu/ubuntu/ $os_version-updates main restricted universe multiverse" >> $repos
echo "deb http://repo.ialab.dsu.edu/ubuntu/ $os_version-backports main restricted universe multiverse" >> $repos
echo "deb http://repo.ialab.dsu.edu/ubuntu/ $os_version-security main restricted universe multiverse" >> $repos
#TODO Test that Debian format is working... should be...
#* Debian Format
elif [[ "$os_id" == "debian" ]]; then
echo -e "${good}This is believed to be ${green}DEBIAN${nocolor}. Now configuring sources.list and backing up old .list and .list.d"
os_version=$(cat /etc/os-release | awk -F= '/VERSION_CODENAME=/{print $2}');
# make backups
repos="/etc/apt/sources.list"
cp "$repos" "$repos.bak"
mv "$repos.d" "$repos.d.bak"
if [[ "$os_version" == "bookworm" || "$os_version" == "bullseye" || "$os_version" == "buster" ]]; then
echo "deb http://repo.ialab.dsu.edu/debian/ $os_version main contrib non-free" > $repos
echo "deb http://repo.ialab.dsu.edu/debian/ $os_version-updates main contrib non-free" >> $repos
echo "deb http://repo.ialab.dsu.edu/debian/ $os_version-security main contrib non-free" >> $repos
else
echo -e "${warn}This release is older than the 'oldoldstable' release. Defaulting to archive repositories"
echo "deb http://archive.debian.org/debian/ $os_version main contrib non-free" > $repos
echo "deb http://archive.debian.org/debian/ $os_version-updates main contrib non-free" >> $repos
echo "deb http://archive.debian.org/debian/ $os_version-security main contrib non-free" >> $repos
fi
#* Fedora/RHEL format
elif [[ "$os_id" == "fedora" ]]; then
# Initialize variables
os_version=$(cat /etc/os-release | awk -F= '/VERSION_ID=/{print $2}');
repos="/etc/yum.repos.d"
dnfconf="/etc/dnf/dnf.conf"
fedora="/etc/yum.repos.d/fedora.repo"
updates="/etc/yum.repos.d/fedora-updates.repo"
# Make backups. Moving repos directory to wipe potential bad
mv "$repos" "$repos.bak"
mkdir "$repos"
cp "$dnfconf" "$dnfconf.bak"
# fix dnf conf (easier)
echo "[main]" > "$dnfconf"
echo "gpgcheck=1" >> "$dnfconf"
echo "installonly_limit=3" >> "$dnfconf"
echo "clean_requirements_on_remove=true" >> "$dnfconf"
echo -e "${warn}IAlab does not currently have repositories for fedora distributions older than 36. This will set to regular mirrors!"
if [ "$os_version" -gt 35 ]; then
echo -e "${good}This is believed to be ${green}FEDORA ${os_version}${nocolor}. We are configuring the /etc/dnf/dnf.conf /etc/yum.repos.d/ and backing up old for restore point."
# now attempt to return to standard repositories!""
# fedora.repo file
echo "[fedora]" > "$fedora"
echo 'name=Fedora $releasever - $basearch' >> "$fedora"
echo 'baseurl=http://repo.ialab.dsu.edu/fedora/linux/releases/$releasever/Everything/$basearch/os/' >> "$fedora"
echo 'enabled=1' >> "$fedora"
# fedora-updates.repo file
echo "[updates]" > "$updates"
echo 'name=Fedora $releasever - $basearch - Updates' >> "$updates"
echo 'baseurl=http://repo.ialab.dsu.edu/fedora/linux/updates/$releasever/Everything/$basearch/' >> "$updates"
echo 'enabled=1' >> "$updates"
else
echo -e "${warn}This is believed to be ${green}FEDORA ${yellow}${os_version}${nocolor}. Setting up archive repositories."
# now attempt to return to standard repositories!""
# fedora.repo file
echo "[fedora]" > "$fedora"
echo 'name=Fedora $releasever - $basearch' >> "$fedora"
echo 'baseurl=https://archives.fedoraproject.org/pub/archive/fedora/linux/releases/$releasever/Everything/$basearch/os/' >> "$fedora"
echo 'enabled=1' >> "$fedora"
# fedora-updates.repo file
echo "[updates]" > "$updates"
echo 'name=Fedora $releasever - $basearch - Updates' >> "$updates"
echo 'baseurl=https://archives.fedoraproject.org/pub/archive/fedora/linux/releases/$releasever/Everything/$basearch/os/' >> "$updates"
echo 'enabled=1' >> "$updates"
fi
#TODO Write one for CentOS. Probably similar situation to Fedora
# Account for problematic distribution. Set error flag.
else
echo -e "${error}Unexpected distribution. Script mishandle. UPDATE MANUALLY!"
repo_changed=1
fi
# Attempt to refresh repository information
if which apt > /dev/null; then
echo -e "${good}Using 'apt' to update repositories...."
apt-get update
echo -e "${good}DONE!"
elif which dnf > /dev/null; then
echo -e "${good}Using 'dnf' to update repositories...."
dnf check-update
echo -e "${good}DONE!"
else
echo -e "${error}Unable to identify package manager. UPDATE MANUALLY!"
repo_update=1
fi
fi
#########
# Verify good file permissions
#########
echo -e "${good}Next: Verify common configuration file permissions."
echo -e "${good}Backing up passwd, group, shadow, gshadow, sudoers"
cp "/etc/passwd" "/etc/passwd-"
cp "/etc/group" "/etc/group-"
cp "/etc/shadow" "/etc/shadow-"
cp "/etc/gshadow" "/etc/gshadow-"
cp "/etc/sudoers" "/etc/sudoers-"
echo -e "${good}Correcting root ownership and access permissions"
#* passwd file
chown root:root "/etc/passwd"
chmod 644 "/etc/passwd"
chown root:root "/etc/passwd-"
chmod 644 "/etc/passwd-"
#* group file
chown root:root "/etc/group"
chmod 644 "/etc/group"
chown root:root "/etc/group-"
chmod 644 "/etc/group-"
#* (g)shadow files. Try root:shadow. Fallback root:root
if grep -E "^shadow" "/etc/group" > /dev/null; then
chown root:shadow "/etc/shadow"
chown root:shadow "/etc/shadow-"
chown root:shadow "/etc/gshadow"
chown root:shadow "/etc/gshadow-"
else
echo -e "${warn}No shadow group. defaulting to root:root ownership."
chown root:root "/etc/shadow"
chown root:root "/etc/shadow-"
chown root:root "/etc/gshadow"
chown root:root "/etc/gshadow-"
fi
chmod 640 "/etc/shadow"
chmod 640 "/etc/shadow-"
chmod 640 "/etc/gshadow"
chmod 640 "/etc/gshadow-"
#* sudoers file and directory
chown root:root "/etc/sudoers"
chmod 440 "/etc/sudoers"
chown root:root "/etc/sudoers-"
chmod 440 "/etc/sudoers-"
chown -R root:root "/etc/sudoers.d/"
chmod -R 440 "/etc/sudoers.d/"
cp -r "/etc/sudoers.d/" "/etc/sudoers.d-/"
if grep -E "^.includedir" "/etc/sudoers" 2>/dev/null; then
echo -e "${warn}Located an included sudoers directory."
if confirm "${prompt}Remove includedir statement from sudoers?"; then
sed -i '/includedir/d' /etc/sudoers
echo -e "${warn}Removed includedir statements from active sudoers file"
fi
fi
echo -e "${good}Finished with common account configuration files"
#########
# Fix Users
#########
#########
# Concept: Verify good users are in current.
# Remaining good users will be added
# Remaining current users will be removed.
#########
echo -e "${good}Moving onto User Auditing"
#* Collect roster of current existing shell users
if confirm "${prompt}Perform user audit?";then
if ! confirm "${prompt}Have you provided a user list already?"; then
if confirm "Enter users in file one username per line. Avoid additional spaces and new lines. \n\tWhen ready: send y and enter"; then
vi userlist.txt
fi
fi
echo -e "${good}Correcting users based on user list"
good_users=($(sort -u userlist.txt))
current_users=($(cat /etc/passwd | grep -v root | grep -E "/bin/.*sh" | cut -d: -f1 | sort -u))
#DEBUG
echo -e "${warn}Starting loop"
for g in "${!good_users[@]}"; do
for c in "${!current_users[@]}"; do
#DEBUG
echo -e "${warn}Checking user from good with current list"
if [[ "${good_users[g]}" == "${current_users[c]}" ]]; then
echo -e "${good}User ${good_users[g]} found!"
unset "good_users[g]"
unset "current_users[c]"
break
fi
done
done
echo -e "${good}Users have been compared. Current statistics below v"
if [ ${#good_users[@]} -gt 0 ];then
echo -e "${warn}Missing ${green}good${nocolor} users:" "${good_users[@]}"
echo -e "${good}Adding missing users from userlist!"
for u in "${good_users[@]}"; do
useradd -m "$u"
[ $? == 0 ] && echo -e "${good}User $u added!" || echo -e "${error}User $u failed to add!"
done
else
echo -e "${good}No missing users"
fi
if [ ${#current_users[@]} -gt 0 ];then
echo -e "${warn}${red}Unauthorized${nocolor} shell users:" "${current_users[@]}"
if confirm "${prompt}Remove the unauthorized shell users on the system?"; then
for u in "${current_users[@]}"; do
# remove user and pip errors to /dev/null (mostly mail errors)
userdel -r "$u" 2>/dev/null
[ $? == 0 ] && echo -e "${warn}User $u removed!" || echo -e "${error}User $u failed to remove!"
done
fi
else
echo -e "${good}No unauthorized users identified!"
fi
if confirm "${prompt}Change all shell user passwords?"; then
echo -e "${warn}Changing all shell passwords to: $password_change"
for u in $(cat /etc/passwd | grep -E "/bin/.*sh" | cut -d: -f1); do
echo "$u:$password_change" | chpasswd;
done
echo -e "${warn}Changing root passwd. Prepare for prompt!"
passwd root
fi
echo -e "${good}User audit complete."
else
echo -e "${warn}User audit skipped. Do this by hand later."
user_audit=1
fi
echo -e "${good}Moving on to admin audit!"
#* Collect roster of current existing admin users
if confirm "${prompt}Perform admin audit?";then
if ! confirm "${prompt}Have you provided a admin list already?"; then
if confirm "Enter admins in file one username per line. Avoid additional spaces and new lines. \n\tWhen ready: send y and enter"; then
vi adminlist.txt
fi
fi
echo -e "${good}Correcting admins based on user list"
good_admins=($(cat adminlist.txt))
my_admins=$(printf "%s," "${good_admins[@]}")
#DEBUG
echo -e "${warn}Current my_admins var: ${my_admins}"
# Correct the entry for sudo or wheel in group and gshadow for provided admin list
if grep "sudo" /etc/group > /dev/null; then
# Regex is looking for "sudo:x:#:[anything else for all the names]"
# Capturing the statement prior to names in order to replace with exact number
sed -i "s/\(sudo:x:[[:digit:]]*:\).*/\1${my_admins}/" /etc/group
sed -i "s/\(sudo:.*::\).*/\1${my_admins}/" /etc/gshadow
elif grep "wheel" /etc/group > /dev/null; then
sed -i "s/\(wheel:x:[[:digit:]]*:\).*/\1${my_admins}/" /etc/group
sed -i "s/\(wheel:.*::\).*/\1${my_admins}/" /etc/gshadow
else
echo -e "${error}Did not find 'sudo' or 'wheel' group. Check admins by hand."
admin_audit=1
fi
echo -e "${good}Admin audit complete."
else
echo -e "${warn}Admin audit skipped. Do this by hand later."
admin_audit=1
fi
#########
# Fix Sudoers
#########
echo -e "${good}Moving to Sudoers file check."
if confirm "${prompt}Audit sudoers file?"; then
echo -e "${good}Looking for NOPASSWD statements..."
if grep -i nopasswd /etc/sudoers; then
echo -e "${warn}Found ${red}NOPASSWD${nocolor}!"
if confirm "${prompt}Remove NOPASSWD from line?";then
visudo
else
echo -e "${error}NOPASSWD FOUND IN SUDOERS. CHECK BY HAND!"
sudoers_audit=1
fi
else
echo -e "${good}No NOPASSWD directives found!"
fi
echo -e "${good}Sudoers audit complete!"
else
echo -e "${warn}Sudoers audit skipped. Do by hand later!"
sudoers_audit=1
fi
#########
# Stand up Firewalls
#########
echo -e "${good}Moving on to Firewalls"
if confirm "${prompt}Run automated firewall?";then
echo -e "${warn}Clearing existing rules..."
iptables -F
iptables -X
# Configure inbound firewall states
# Allow loopback
echo -e "${good}Allowing all to ${blue}LOOPBACK${nocolor}"
iptables -A INPUT -i lo -j ACCEPT
# Allow ping
echo -e "${good}Allowing ${blue}PING (ICMP)${nocolor}"
iptables -A INPUT -p icmp -j ACCEPT
# Dynamically build input roster based on listening ports. (Currently not looking for malicious listeners)
# regex to match capture TCP or UDP, then a port number. Builds
OLDIFS=$IFS
IFS=$'\n'
echo -e "${good}Adding rules for existing listening sockets"
for r in $(ss -pluntH | sed -r 's/(\S+).+:(\S+) .*:\*.*"(.+)".*/iptables -A INPUT -p \1 --dport \2\t -j ACCEPT -m comment --comment "\3"/g'); do
# DEBUG
echo -e "${warn}$r"
bash -c "$r"
done
IFS=$OLDIFS
# Allow currently established session traffic inbound and related new sessions.
echo -e "${good}Allowing in any related or established sessions"
iptables -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
# Default policy DROP
echo -e "${warn}Setting inbound policy to ${yellow}DROP${nocolor}"
iptables -P INPUT DROP
echo -e "${good}Saving rules to '/root/iptables_rules.txt'. You can edit and apply changes with 'iptables-restore < iptables_rules.txt'"
iptables-save > /root/iptables_rules.txt
#TODO make while loop?
if confirm "${prompt}See current iptables configuration?"; then
iptables-save
if confirm "${prompt}Make changes to configuration?"; then
vi /root/iptables_rules.txt
iptables-restore < /root/iptables_rules.txt
fi
fi
if [ ! -f "/etc/systemd/system/iptables-persistent.service" ]; then
if confirm "${prompt}Make iptables persistent?"; then
echo -e "${good}Making systemd service file"
echo -e "[Unit]
Description=Restore iptables on reboot
After=network.target
[Service]
Type=oneshot
ExecStart=/sbin/iptables-restore < /root/iptables_rules.txt
WorkingDirectory=/root
[Install]
WantedBy=multi-user.target" > /etc/systemd/system/iptables-persistent.service
echo -e "${good}Reloading daemons"
systemctl daemon-reload
echo -e "${good}Enabling service on reboot"
systemctl enable iptables-persistent
echo -e "${good}DONE!"
fi
fi
echo -e "${good}Generic inbound firewall established!"
else
echo -e "${warn}Skipping firewall deployment. Recommend activating firewalls."
firewalls_deployed=1
fi
######
# REMINDERS: anything that flipped a flag for further investigation
######
echo -e "${good}Script complete..."
echo -e "${warn}Recommend reviewing any content that appears below v"
if [ $repo_changed == 1 ]; then
echo -e "${prompt}Failed to change repository information. Verify integrity of repository information before updating!"
fi
if [ $repo_update == 1 ]; then
echo -e "${prompt}Failed to pull updated repository information. Check that repositories are pointing to correct resources!"
fi
if [ $user_audit == 1 ]; then
echo -e "${prompt}Skipped user audit. MAKE SURE YOUR USERS ARE GOOD!"
fi
if [ $admin_audit == 1 ]; then
echo -e "${prompt}Skipped admin audit. VERIFY YOUR ADMINISTRATORS!"
fi
if [ $sudoers_audit == 1 ]; then
echo -e "${prompt}Skipped sudoers audit. VERIFY SUDOER CONFIGURATION!"
fi
if [ $firewalls_deployed == 1 ]; then
echo -e "${prompt}Firewalls were not deployed. Deploy manually."
fi