-
Notifications
You must be signed in to change notification settings - Fork 19
/
init-linux-harden.sh
1351 lines (1111 loc) · 42.9 KB
/
init-linux-harden.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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
SCRIPT_NAME=linux_init_harden
SCRIPT_VERSION=1.0
LOGFILE=/tmp/"$SCRIPT_NAME"_v"$SCRIPT_VERSION".log
# Reset previous log file
TS=$(date '+%d_%m_%Y-%H_%M_%S')
echo "Starting $0 - $TS" > "$LOGFILE"
BACKUP_EXTENSION='.'$TS"_bak"
# Colors
CSI='\033['
CEND="${CSI}0m"
CRED="${CSI}1;31m"
CGREEN="${CSI}1;32m"
##############################################################
# Usage
##############################################################
# Script takes arguments as follows
# linux_init_harden -username pratik --resetrootpwd
# linux_init_harden -u pratik --resetrootpwd
# linux_init_harden -username pratik --resetrootpwd -q -hide
function usage() {
if [ -n "$1" ]; then
echo ""
echo -e "${CRED}$1${CEND}\n"
fi
echo "Usage: sudo bash $0 [-u|--username username] [-r|--resetrootpwd] [--defaultsourcelist]"
echo " -u, --username Username for your server (If omitted script will choose an username for you)"
echo " -r, --resetrootpwd Reset current root password"
echo " -hide, --hide-credentials Credentials will hidden from screen and can ONLY be found in the logfile"
echo " eg: tail -n 20 logfile"
echo " -d, --defaultsourcelist Updates /etc/apt/sources.list to download software from debian.org"
echo " -ou, --only-user Only creates the user and its SSH authorizations"
echo " NOTE: -r, -d would be ignored"
echo ""
echo "Example: bash ./$SCRIPT_NAME.sh --username myuseraccount --resetrootpwd"
printf "\\nBelow restrictions apply to usernames - \\n"
printf "%2s - [a-zA-Z0-9] [-] [_] are allowed\\n%2s - NO special characters.\\n%2s - NO spaces.\\n" " " " " " "
}
##############################################################
# Basic checks before starting
##############################################################
# No root - no good
[ "$(id -u)" != "0" ] && {
usage "ERROR: You must be root to run this script.\\nPlease login as root and execute the script again."
exit 1
}
function os_not_supported() {
printf "This script only supports: \\n\\tDebian 9, 10, and 11\\n"
printf "\\tUbuntu 16.04, 18.04, 18.10, 20.04, and 21.04\\n"
printf "Your OS is NOT supported.\\n"
}
function new_os_version_warning(){
echo "${1} version ${2} is not tested. Continuing is NOT RECOMMENDED."
read -p "Continue (NOT RECOMMENDED)? (Y/N): " confirm && [[ $confirm == [yY] || $confirm == [yY][eE][sS] ]] || exit 1
}
# Fail-fast: No apt - no good
if ! command -v apt-get >/dev/null; then
os_not_supported
exit 1
fi
# Check supported OSes
if [ -f /etc/os-release ]; then
. /etc/os-release
OS=$ID
VER=$VERSION_ID
CODE_NAME=$VERSION_CODENAME
else
os_not_supported
exit 1
fi
case "$OS" in
debian)
# If the versions are not 9, 10, 11
# warn user and ask them to proceed with caution
DEB_VER_STR=$CODE_NAME
if ((VER >= 9 && VER <= 11)); then
new_os_version_warning
fi
;;
ubuntu)
# If the versions are not 16.04, 18.04, 18.10, 20.04. 21.04
# warn user and ask them to proceed with caution
UBT_VER_STR=$CODE_NAME
if [[ "$VER" != "16.04" ]] && [[ "$VER" != "18.04" ]] && [[ "$VER" != "18.10" ]] && [[ "$VER" != "20.04" ]] && [[ "$VER" != "21.04" ]]; then
new_os_version_warning "${OS}" "${VER}"
fi
;;
*)
os_not_supported
exit 1
;;
esac
##################################
# Parse script arguments
##################################
# defaults
AUTO_GEN_USERNAME="y"
RESET_ROOT_PWD="n"
DEFAULT_SOURCE_LIST="n"
QUIET="n"
HIDE_CREDENTIALS="n"
USER_CREATION_ALONE="n"
while [[ "$#" -gt 0 ]]; do
case $1 in
-u|--username)
# validate username
if [[ $(echo "$2" | grep -Pnc '^[a-zA-Z0-9_-]+$') -eq 0 ]]; then
usage "Invalid characters in the user name."
exit 1
elif [[ $(getent passwd "$2" | wc -l) -gt 0 ]]; then
echo
echo -e "${CRED}User name ($2) already exists.${CEND}\n"
exit 1
else
AUTO_GEN_USERNAME="n"
NORM_USER_NAME="$2"
fi
shift
shift
;;
-ou|--only-user)
USER_CREATION_ALONE="y"
shift
;;
-r|--resetrootpwd)
RESET_ROOT_PWD="y"
shift
;;
-d|--defaultsourcelist)
DEFAULT_SOURCE_LIST="y"
shift
;;
-q|--quiet|--nowait|--noprompt)
QUIET="y"
shift
;;
-hide|--hide-credentials)
HIDE_CREDENTIALS="y"
shift
;;
-h|--help)
echo
usage
echo
exit 0
shift
;;
*)
usage "Unknown parameter passed: $1" "h"
exit 1
shift
shift
;;
esac
done
##############################################################
# Display what the script does
##############################################################
clear
cat <<INFORM | more
!!! READ BELOW & PRESS ENTER/RETURN TO CONTINUE !!!
##################################################################
- Before editing any file, script creates a back up of that file in
the same directory. If script detects any error, then it restores the
original files.
- If any operation which involves credentials generation, succeeds -
then those credentials will be displayed at the end of all operations.
- If script reports any error or something does not work as expected,
please take a look at the log file at (${LOGFILE}).
- Operations are NOT idempotent
All backup files have extension (${BACKUP_EXTENSION})
Script logs all operation into (${LOGFILE}) file.
##################################################################
INFORM
echo "Installation options selected - " | tee -a "$LOGFILE"
if [[ "$AUTO_GEN_USERNAME" == "y" ]]; then
printf "%3s Username will be auto generated by script\\n" " -" | tee -a "$LOGFILE"
else
printf "%3s Username you opted = %s\\n" " -" "$NORM_USER_NAME" | tee -a "$LOGFILE"
fi
if [[ "$DEFAULT_SOURCE_LIST" == "y" && "$USER_CREATION_ALONE" == "n" ]]; then
printf "%3s Reset the url for apt repo from VPS provided CDN to OS provided ones\\n" " -" | tee -a "$LOGFILE"
fi
if [[ "$RESET_ROOT_PWD" == "y" && "$USER_CREATION_ALONE" == "n" ]]; then
printf "%3s Reset root password\\n" " -" | tee -a "$LOGFILE"
fi
if [[ $HIDE_CREDENTIALS == "y" ]]; then
printf "%3s Credentials WILL NOT be displayed on screen\\n" " -" | tee -a "$LOGFILE"
printf "%3s Credentials can be found in the logfile ${LOGFILE}\\n" " -" | tee -a "$LOGFILE"
fi
if [[ "$QUIET" == "y" ]]; then
printf "%3s No prompt installation selected\\n\\n" " -" | tee -a "$LOGFILE"
fi
echo
echo "TO CONTINUE (press enter/return)..."
echo "TO EXIT (ctrl + c)..."
echo
if [[ $QUIET == "n" ]]; then
read -r
clear
fi
# Start recording execution time from now on
SECONDS=0
##############################################################
# Log - Cosmetics
##############################################################
CVERTICAL="|"
CHORIZONTAL="_"
CLINESIZE=72
function center_text(){
textsize=${#1}
width=$2
span=$((($width + $textsize) / 2))
printf "%${span}s" "$1"
}
function center_err_text(){
printf "${CRED}"
center_text "$1" "$CLINESIZE"
printf "${CEND}\\n"
}
function center_reg_text(){
center_text "$1" $CLINESIZE
printf "\\n"
}
function horizontal_fill() {
local char=$1
declare -i rep=$2
for ((x = 0; x < "$rep"; x++)); do
printf %s "$char"
done
}
function line_fill() {
horizontal_fill "$1" "$2"
printf "\\n"
}
##############################################################
# Op Logs
##############################################################
function file_log(){
printf "%s - %s\\n" "$(date '+%d-%b-%Y %H:%M:%S')" "$1" >> "$LOGFILE"
}
function log_step_status() {
local EVENT=$1
local RESULT=$2
if [[ "$RESULT" = "SUCCESSFUL" ]]; then
printf "\r%33s %7s [${CGREEN}${RESULT}${CEND}]\\n" "$EVENT" " "
file_log "${EVENT} - ${RESULT}"
elif [[ "$RESULT" = "FAILED" ]]; then
printf "\r%33s %7s [${CRED}${RESULT}${CEND}]\\n" "$EVENT" " "
file_log "${EVENT} - ${RESULT}"
elif [[ "$RESULT" = "NO-OP" ]]; then
printf "\r%33s %7s [${RESULT}]\\n" "$EVENT" " "
file_log "${EVENT} - No operation done. Check above for details..."
else
printf "%33s %7s [${CRED}..${CEND}]" "$EVENT" " "
file_log "${EVENT} - begin..."
fi
}
function log_op_rev_status(){
printf "${CRED}"
log_step_status "$1" "$2"
printf "${CEND}"
}
function log_ops_finish (){
local purpose=$1
local status=$2
local value=$3
if [[ $status -eq 0 ]]; then
echo "${purpose}: Did not start this operation. See log above." 2>> ${LOGFILE} >&2
value="[${CGREEN}--NO_OP--${CEND}]"
elif [[ $status -eq 2 ]]; then
echo "${purpose}: ${value}" 2>> ${LOGFILE} >&2
value="[${CGREEN}${value}${CEND}]"
elif [[ $status -eq 1 ]] || [[ $status -eq 3 ]]; then
echo "${purpose}: ERROR. See log above." 2>> ${LOGFILE} >&2
value="${CRED}--ERROR--${CEND}"
fi
if [[ $HIDE_CREDENTIALS == "n" ]]; then
horizontal_fill "$CVERTICAL" 1
printf "%23s:%3s%-54s" "$purpose" " " "$(echo -e "$value")"
line_fill "$CVERTICAL" 1
fi
}
function log_ops_finish_file_contents() {
local file_type=$1
local file_location=$2
file_log "$file_type"
cat "$file_location" 2>> "$LOGFILE" >&2
if [[ $HIDE_CREDENTIALS == "n" ]]; then
echo
center_reg_text "$file_type"
echo
printf "${CGREEN}"
cat "$file_location"
printf "${CEND}"
fi
}
function log_revert_error(){
log_step_status "$1" "FAILED"
echo
center_err_text "!!! Error restoring changes !!!"
center_err_text "!!! You may have to manually fix this !!!"
center_err_text "!!! Check the log file for details !!!"
echo
}
##############################################################
# Op Error Handling
##############################################################
# Remember to reset exit_code at end of EACH revert fn
function revert_create_user(){
file_log "Reverting New User Creation..."
# Remove user and its home directory only if user was created
if [[ $(getent passwd "$NORM_USER_NAME" | wc -l) -gt 0 ]]; then
{
file_log "Deleting user ${NORM_USER_NAME} ..."
deluser "$NORM_USER_NAME"
file_log "Deleting user ${NORM_USER_NAME} home directory and all its content ..."
rm -rf /home/"${NORM_USER_NAME:?}"
set_exit_code $?
} 2>> "$LOGFILE" >&2
set_exit_code $?
fi
if [[ $exit_code -eq 0 ]]; then
log_op_rev_status "Reverting - New User Creation" "SUCCESSFUL"
else
file_log "Error Code - ${exit_code}"
log_revert_error "Reverting - New User Creation"
fi
}
function revert_create_ssh_key(){
file_log "Reverting SSH Key Generation..."
revert_create_user
set_exit_code $?
# Since all SSH files are created inside the user's home directory
# There is nothing to revert if username is deleted
if [[ $exit_code -eq 0 ]]; then
log_op_rev_status "Reverting - SSH Key Generation" "SUCCESSFUL"
else
file_log "Error Code - ${exit_code}"
log_revert_error "Reverting - SSH Key Generation"
fi
}
function revert_secure_authorized_key(){
file_log "Reverting SSH Key Authorizations..."
if [[ -f "$SSH_DIR"/authorized_keys ]]; then
{
file_log "Removing the immutable flag from every file in /home/${NORM_USER_NAME}/.ssh/ directory ..."
chattr -i "$SSH_DIR"/*
set_exit_code $?
# Nothing else to restore since we are going to delete the user & its directories anyways
# All the files created/changed by the script are inside /home/[username]/.ssh directory only
} 2>> "$LOGFILE" >&2
fi
# Can remove the user only AFTER immutable attributes on authorized_keys is removed
revert_create_ssh_key
if [[ $exit_code -eq 0 ]]; then
log_op_rev_status "Reverting - SSH Key Authorization" "SUCCESSFUL"
else
file_log "Error Code - ${exit_code}"
log_revert_error "Reverting - SSH Key Authorization"
fi
}
function revert_source_list_changes(){
reset_exit_code
file_log "Reverting Source_list Changes..."
unalias cp &>/dev/null
if [[ -f /etc/apt/sources.list"${BACKUP_EXTENSION}" ]]; then
file_log "Restoring /etc/apt/sources.list${BACKUP_EXTENSION} into /etc/apt/sources.list ..."
cp -rf /etc/apt/sources.list"${BACKUP_EXTENSION}" /etc/apt/sources.list 2>> "$LOGFILE" >&2
set_exit_code $?
fi
SOURCE_FILES_BKP=(/etc/apt/source*/*.list"$BACKUP_EXTENSION")
if [[ ${#SOURCE_FILES_BKP[@]} -gt 0 ]]; then
for file in "${SOURCE_FILES_BKP[@]}";
do
file_log "Restoring ${file} into ${file//$BACKUP_EXTENSION/} ..."
cp -rf "$file" "${file//$BACKUP_EXTENSION/}" 2>> "$LOGFILE" >&2
set_exit_code $?
done
fi
if [[ $exit_code -eq 0 ]]; then
log_op_rev_status "Reverting - Source_list Changes" "SUCCESSFUL"
else
file_log "Error Code - ${exit_code}"
log_revert_error "Reverting - Source_list Changes"
fi
reset_exit_code
}
function revert_root_pass_change(){
reset_exit_code
echo
center_err_text "Changing root password failed..."
center_err_text "Your earlier root password remains VALID"
center_err_text "Script will continue to next step"
}
function revert_config_UFW(){
reset_exit_code
file_log "Reverting UFW Configuration..."
ufw disable 2>> "$LOGFILE" >&2
set_exit_code $?
if [[ $exit_code -eq 0 ]]; then
log_op_rev_status "Reverting - UFW Configuration" "SUCCESSFUL"
else
file_log "Error Code - ${exit_code}"
log_revert_error "Reverting - UFW Configuration"
fi
reset_exit_code
}
function revert_config_fail2ban(){
reset_exit_code
file_log "Reverting Fail2ban Config..."
unalias cp &>/dev/null
if [[ -f /etc/fail2ban/jail.local"$BACKUP_EXTENSION" ]]; then
# If /etc/fail2ban/jail.local/_bkp exists then this is NOT the 1st time script is run
# So, you would probaly want to get the last existing jail.local file back
file_log "Restoring /etc/fail2ban/jail.local${BACKUP_EXTENSION} into /etc/fail2ban/jail.local"
cp -rf /etc/fail2ban/jail.local"$BACKUP_EXTENSION" /etc/fail2ban/jail.local 2>> "$LOGFILE" >&2
set_exit_code $?
else
# If /etc/fail2ban/jail.local/_bkp does NOT exists then this IS the 1st time script is run
# You probably do NOT want the jail.local > which might be corrupted > which is why you are here
file_log "Removing /etc/fail2ban/jail.local"
rm /etc/fail2ban/jail.local 2>> "$LOGFILE" >&2
set_exit_code $?
fi
if [[ -f /etc/fail2ban/jail.d/defaults-debian.conf"$BACKUP_EXTENSION" ]]; then
file_log "Restoring /etc/fail2ban/jail.d/defaults-debian.conf${BACKUP_EXTENSION} into /etc/fail2ban/jail.d/defaults-debian.conf"
cp -rf /etc/fail2ban/jail.d/defaults-debian.conf"$BACKUP_EXTENSION" /etc/fail2ban/jail.d/defaults-debian.conf 2>> "$LOGFILE" >&2
set_exit_code $?
fi
file_log "Stopping fail2ban service ..."
{
set_exit_code $(service_action_and_chk_error "fail2ban" "stop")
} 2>> "$LOGFILE" >&2
if [[ $exit_code -eq 0 ]]; then
log_op_rev_status "Reverting - Fail2ban Config" "SUCCESSFUL"
else
file_log "Error Code - ${exit_code}"
log_revert_error "Reverting - Fail2ban Config"
fi
reset_exit_code
}
function revert_software_installs(){
reset_exit_code
echo
center_err_text "Error while installing softwares"
center_err_text "This may be a false-alarm"
center_err_text "Script will continue to next step"
file_log "Installing software failed..."
file_log "This is NOT a catastrophic error"
}
function revert_schedule_updates() {
reset_exit_code
file_log "Reverting Daily Update Download..."
rm "$dailycron_filename"
set_exit_code $?
if [[ $exit_code -eq 0 ]]; then
log_op_rev_status "Reverting - Daily Update Download" "SUCCESSFUL"
else
file_log "Error Code - ${exit_code}"
log_revert_error "Reverting - Daily Update Download"
fi
reset_exit_code
}
function revert_ssh_only_login(){
revert_secure_authorized_key
if [[ $DEFAULT_SOURCE_LIST = "y" ]]; then
revert_source_list_changes
fi
revert_config_UFW
revert_config_fail2ban
revert_schedule_updates
file_log "Reverting SSH-only Login..."
if [[ -f /etc/ssh/sshd_config"$BACKUP_EXTENSION" ]]; then
unalias cp &>/dev/null
file_log "Restoring /etc/ssh/sshd_config${BACKUP_EXTENSION} into /etc/ssh/sshd_config ..."
cp -rf /etc/ssh/sshd_config"$BACKUP_EXTENSION" /etc/ssh/sshd_config 2>> "$LOGFILE" >&2
set_exit_code $?
fi
file_log "Restarting ssh service ..."
{
set_exit_code $(service_action_and_chk_error "sshd" "restart")
if [[ $exit_code -eq 0 ]]; then
false
fi
} || {
# Because Ubuntu 14.04 does not have sshd
set_exit_code $(service_action_and_chk_error "ssh" "restart")
} 2>> "$LOGFILE" >&2
if [[ $exit_code -eq 0 ]]; then
log_op_rev_status "Reverting - SSH-only Login" "SUCCESSFUL"
else
file_log "Error Code - ${exit_code}"
log_revert_error "Reverting - SSH-only Login"
fi
reset_exit_code
}
function revert_everything_and_exit() {
echo
center_err_text "!!! ERROR OCCURED DURING OPERATION !!!"
center_err_text "!!! Reverting changes !!!"
center_err_text "Please look at $LOGFILE for details"
echo
file_log "Starting revert operation..."
reset_exit_code
if [[ $1 = "${STEP_TEXT[0]}" ]]; then
revert_create_user
elif [[ $1 = "${STEP_TEXT[1]}" ]]; then
revert_create_ssh_key
elif [[ $1 = "${STEP_TEXT[2]}" ]]; then
revert_secure_authorized_key
elif [[ $1 = "${STEP_TEXT[3]}" ]]; then
revert_ssh_only_login
fi
center_reg_text "Total execution time - ${SECONDS}s"
exit 1;
}
##############################################################
# Op-setup & Utility Functions
##############################################################
exit_code=0
# Step Status
# Each step has 1 of possible 3 states
# 0 - NO-OP - not executed
# 1 - STARTED - Started
# 2 - SUCCESSFUL - Successfully Completed
# 3 - FAILED - Completed with Error
CreateNonRootUser=0
CreateSSHKey=0
SecureAuthkeysfile=0
ChangeSourceList=0
InstallReqSoftwares=0
ConfigureUFW=0
ConfigureFail2Ban=0
ChangeRootPwd=0
ScheduleUpdate=0
EnableSSHOnly=0
STEP_TEXT=(
"Creating new user" #0
"Creating SSH Key for new user" #1
"Securing 'authorized_keys' file" #2
"Enabling SSH-only login" #3
"Reset sources.list to defaults" #4
"Installing required softwares" #5
"Configure UFW" #6
"Configure Fail2Ban" #7
"Changing root password" #8
"Scheduling daily update download" #9
)
function set_exit_code() {
if [[ $OP_CODE -eq 0 ]] && [[ $1 -gt 0 ]]; then
exit_code=$1
fi
}
function reset_exit_code() {
exit_code=0
}
function update_step_status() {
local event
event=$(get_step_var_from_stepname "$1")
eval "$event"="$2"
}
function get_step_status() {
step_variable_name=$(get_step_var_from_stepname "$1")
echo "${!step_variable_name}"
}
function get_step_var_from_stepname() {
case $1 in
"${STEP_TEXT[0]}")
echo "CreateNonRootUser"
;;
"${STEP_TEXT[1]}")
echo "CreateSSHKey"
;;
"${STEP_TEXT[2]}")
echo "SecureAuthkeysfile"
;;
"${STEP_TEXT[3]}")
echo "EnableSSHOnly"
;;
"${STEP_TEXT[4]}")
echo "ChangeSourceList"
;;
"${STEP_TEXT[5]}")
echo "InstallReqSoftwares"
;;
"${STEP_TEXT[6]}")
echo "ConfigureUFW"
;;
"${STEP_TEXT[7]}")
echo "ConfigureFail2Ban"
;;
"${STEP_TEXT[8]}")
echo "ChangeRootPwd"
;;
"${STEP_TEXT[9]}")
echo "ScheduleUpdate"
;;
*)
false
;;
esac
}
function service_action_and_chk_error() {
local servicename=$1
local serviceaction=$2
local servicemsg
servicemsg=$(service "$servicename" "$serviceaction" 2>&1)
file_log "$servicemsg"
return $(echo "$servicemsg" | grep -c 'ERROR')
}
function recap() {
if [[ $CreateNonRootUser -eq 2 ]] &&
[[ $CreateSSHKey -eq 2 ]] &&
[[ $SecureAuthkeysfile -eq 2 ]] &&
[[ $InstallReqSoftwares -eq 2 ]] &&
[[ $ChangeSourceList -le 2 ]] && # Since 0 (NO-OP) is still success
[[ $ConfigureUFW -le 2 ]] && # Since 0 (NO-OP) is still success
[[ $ConfigureFail2Ban -le 2 ]] && # Since 0 (NO-OP) is still success
[[ $ScheduleUpdate -le 2 ]] && # Since 0 (NO-OP) is still success
[[ $ChangeRootPwd -le 2 ]] && # Since 0 (NO-OP) is still success
[[ $EnableSSHOnly -eq 2 ]]; then
echo
line_fill "$CHORIZONTAL" "$CLINESIZE"
center_reg_text "ALL OPERATIONS COMPLETED SUCCESSFULLY"
fi
if [[ $ChangeSourceList -eq 3 ]] ||
[[ $InstallReqSoftwares -eq 3 ]] ||
[[ $ConfigureUFW -eq 3 ]] ||
[[ $ConfigureFail2Ban -eq 3 ]]
[[ $ScheduleUpdate -eq 3 ]] &&
[[ $ChangeRootPwd -eq 3 ]]; then
center_err_text "Some operations failed..."
center_err_text "System would function with reduced security"
center_err_text "Please check $LOGFILE file for details"
echo
fi
#Recap
file_log ""
file_log ""
file_log ""
file_log ""
if [[ $HIDE_CREDENTIALS == "n" ]]; then
line_fill "$CHORIZONTAL" "$CLINESIZE"
fi
log_ops_finish "User Name" "$CreateNonRootUser" "$NORM_USER_NAME"
log_ops_finish "User's Password" "$CreateNonRootUser" "$USER_PASS"
log_ops_finish "SSH Private Key File" "$CreateSSHKey" "$SSH_DIR"/"$NORM_USER_NAME".pem
log_ops_finish "SSH Public Key File" "$CreateSSHKey" "$SSH_DIR"/"$NORM_USER_NAME".pem.pub
log_ops_finish "SSH Key Passphrase" "$CreateSSHKey" "$KEY_PASS"
if [[ "$RESET_ROOT_PWD" == "y" && "$USER_CREATION_ALONE" == "n" ]]; then
log_ops_finish "New root Password" "$ChangeRootPwd" "$PASS_ROOT"
fi
if [[ $HIDE_CREDENTIALS == "n" ]]; then
line_fill "$CHORIZONTAL" "$CLINESIZE"
fi
log_ops_finish_file_contents "SSH Private Key" "$SSH_DIR"/"$NORM_USER_NAME".pem
log_ops_finish_file_contents "SSH Public Key" "$SSH_DIR"/"$NORM_USER_NAME".pem.pub
line_fill "$CHORIZONTAL" "$CLINESIZE"
center_reg_text "!!! DO NOT LOG OUT JUST YET !!!"
center_reg_text "Use another window to test out the above credentials"
center_reg_text "If you face issue logging in, check the log file to see what went wrong"
center_reg_text "Log file at ${LOGFILE}"
line_fill "$CHORIZONTAL" "$CLINESIZE"
echo
if [[ $HIDE_CREDENTIALS == "y" ]]; then
center_reg_text "Use the following command to see all credentials"
center_reg_text "tail -n 20 ${LOGFILE}"
fi
file_log "Total execution time in seconds - ${SECONDS}"
center_reg_text "Total execution time - ${SECONDS}s"
exit
}
function setup_step_start() {
reset_exit_code
update_step_status "$1" 1
log_step_status "$1"
}
function setup_step_end() {
# If it was a no op - Log and return
# Since we set step status to be 1 in setup_step_start(),
# it can become 0 only if we explicitly do the following INSIDE the step
# update_step_status "$1" 0
if [[ $(get_step_status "$1") -eq 0 ]]; then
log_step_status "$1" "NO-OP"
return
fi
if [[ $exit_code -eq 0 ]]; then
update_step_status "$1" 2
log_step_status "$1" "SUCCESSFUL"
else
file_log "Error code - ${exit_code}"
update_step_status "$1" 3
log_step_status "$1" "FAILED"
fi
}
##############################################################
# Step 1 - Create non-root user
##############################################################
setup_step_start "${STEP_TEXT[0]}"
{
if [[ $AUTO_GEN_USERNAME == 'y' ]]; then
NORM_USER_NAME="$(< /dev/urandom tr -cd 'a-z' | head -c 6)""$(< /dev/urandom tr -cd '0-9' | head -c 2)" || exit 1
file_log "Generated user name ${NORM_USER_NAME}"
fi
# Generate a 15 character random password
USER_PASS="$(< /dev/urandom tr -cd "[:alnum:]" | head -c 15)" || exit 1
file_log "Generated user password - ${USER_PASS}"
# Create the user and assign the above password
file_log "Creating user"
echo -e "${USER_PASS}\\n${USER_PASS}" | adduser "$NORM_USER_NAME" -q --gecos "First Last,RoomNumber,WorkPhone,HomePhone"
set_exit_code $?
# Give root privilages to the above user
file_log "Assigning user sudo privileges"
usermod -aG sudo "$NORM_USER_NAME"
set_exit_code $?
} 2>> "$LOGFILE" >&2
setup_step_end "${STEP_TEXT[0]}"
if [[ $exit_code -gt 0 ]]; then
revert_everything_and_exit "${STEP_TEXT[0]}"
fi
##############################################################
# Step 2 - Create SSH Key for the above new user
##############################################################
setup_step_start "${STEP_TEXT[1]}"
{
SSH_DIR=/home/"$NORM_USER_NAME"/.ssh
file_log "Creating SSH directory - $SSH_DIR"
mkdir "$SSH_DIR"
set_exit_code $?
# Generate a 15 character random password for key
KEY_PASS="$(< /dev/urandom tr -cd "[:alnum:]" | head -c 15)"
file_log "Generated SSH Key Passphrase - ${KEY_PASS}"
set_exit_code $?
# Create a OpenSSH-compliant ed25519-type key
file_log "Generating SSH Key File - $SSH_DIR/$NORM_USER_NAME.pem"
ssh-keygen -a 1000 -o -t ed25519 -N "$KEY_PASS" -C "$NORM_USER_NAME" -f "$SSH_DIR"/"$NORM_USER_NAME".pem -q
set_exit_code $?
# Copy the generated public file to authorized_keys
cat "$SSH_DIR"/"$NORM_USER_NAME".pem.pub >> "$SSH_DIR"/authorized_keys
set_exit_code $?
} 2>> "$LOGFILE" >&2
setup_step_end "${STEP_TEXT[1]}"
if [[ $exit_code -gt 0 ]]; then
file_log "Creating SSH Key for new user failed."
revert_everything_and_exit "${STEP_TEXT[1]}"
fi
##############################################################
# Step 3 - Secure authorized_keys file
##############################################################
setup_step_start "${STEP_TEXT[2]}"
{
# Set appropriate permissions for ".ssh" dir and "authorized_key" file
file_log "Setting appropriate permissions for $SSH_DIR dir and $SSH_DIR/authorized_keys file"
chown -R "$NORM_USER_NAME" "$SSH_DIR" && \
chgrp -R "$NORM_USER_NAME" "$SSH_DIR" && \
chmod 700 "$SSH_DIR" && \
chmod 400 "$SSH_DIR"/authorized_keys && \
chattr +i "$SSH_DIR"/authorized_keys
set_exit_code $?
# Restrict access to the generated SSH Key files as well
shopt -s nullglob
KEY_FILES=("$SSH_DIR"/"$NORM_USER_NAME".pem*)
for key in "${KEY_FILES[@]}"; do
file_log "Restricting access (chmod 400 and chattr +i) to ${key} file"
chmod 400 "$key" && \
chattr +i "$key"
set_exit_code $?
done
} 2>> "$LOGFILE" >&2
setup_step_end "${STEP_TEXT[2]}"
if [[ $exit_code -gt 0 ]]; then
file_log "Setting restrictive permissions for '~/.ssh/' directory failed"
file_log "Please do 'ls -lAh ~/.ssh/' and check manually to see what went wrong."
revert_everything_and_exit "${STEP_TEXT[2]}"
fi
if [[ "$USER_CREATION_ALONE" == "y" ]]; then
recap
fi
##############################################################
# Step 4 - Change default source-list
##############################################################
if [[ $DEFAULT_SOURCE_LIST = "y" ]]; then
# Low priority - But what to do if it fails???
setup_step_start "${STEP_TEXT[4]}"
{
file_log "Backing up /etc/apt/sources.list file to /etc/apt/sources.list${BACKUP_EXTENSION}"
cp /etc/apt/sources.list /etc/apt/sources.list"${BACKUP_EXTENSION}"
set_exit_code $?
file_log "Commenting out everthing in /etc/apt/sources.list"
sed -i "1,$(wc -l < /etc/apt/sources.list) s/^/#/" /etc/apt/sources.list
set_exit_code $?
if [[ $OS = "debian" ]]; then
file_log "Adding default CDN sources to /etc/apt/sources.list"
# Default sources list for debian
cat <<DEBIAN >> /etc/apt/sources.list
deb http://deb.debian.org/debian ${DEB_VER_STR} main contrib non-free
deb-src http://deb.debian.org/debian ${DEB_VER_STR} main contrib non-free
## Major bug fix updates produced after the final release of the
## distribution.
deb http://security.debian.org ${DEB_VER_STR}/updates main contrib non-free
deb-src http://security.debian.org ${DEB_VER_STR}/updates main contrib non-free
deb http://deb.debian.org/debian ${DEB_VER_STR}-updates main contrib non-free
deb-src http://deb.debian.org/debian ${DEB_VER_STR}-updates main contrib non-free
deb http://deb.debian.org/debian ${DEB_VER_STR}-backports main contrib non-free
deb-src http://deb.debian.org/debian ${DEB_VER_STR}-backports main contrib non-free
DEBIAN
set_exit_code $?
elif [[ $OS = "ubuntu" ]]; then
cat <<UBUNTU >> /etc/apt/sources.list
deb http://archive.ubuntu.com/ubuntu/ ${UBT_VER_STR} main restricted
deb-src http://archive.ubuntu.com/ubuntu/ ${UBT_VER_STR} main restricted
deb http://archive.ubuntu.com/ubuntu/ ${UBT_VER_STR}-updates main restricted
deb-src http://archive.ubuntu.com/ubuntu/ ${UBT_VER_STR}-updates main restricted
deb http://archive.ubuntu.com/ubuntu/ ${UBT_VER_STR} universe multiverse
deb-src http://archive.ubuntu.com/ubuntu/ ${UBT_VER_STR} universe multiverse
deb http://archive.ubuntu.com/ubuntu/ ${UBT_VER_STR}-updates universe multiverse
deb-src http://archive.ubuntu.com/ubuntu/ ${UBT_VER_STR}-updates universe multiverse
deb http://archive.ubuntu.com/ubuntu/ ${UBT_VER_STR}-backports main restricted universe multiverse
deb-src http://archive.ubuntu.com/ubuntu/ ${UBT_VER_STR}-backports main restricted universe multiverse
deb http://security.ubuntu.com/ubuntu ${UBT_VER_STR}-security main restricted
deb-src http://security.ubuntu.com/ubuntu ${UBT_VER_STR}-security main restricted
deb http://security.ubuntu.com/ubuntu ${UBT_VER_STR}-security universe
deb-src http://security.ubuntu.com/ubuntu ${UBT_VER_STR}-security universe
deb http://security.ubuntu.com/ubuntu ${UBT_VER_STR}-security multiverse
deb-src http://security.ubuntu.com/ubuntu ${UBT_VER_STR}-security multiverse
UBUNTU