-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathssh-setup-and-config.sh
More file actions
executable file
·594 lines (389 loc) · 16.5 KB
/
Copy pathssh-setup-and-config.sh
File metadata and controls
executable file
·594 lines (389 loc) · 16.5 KB
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
#!/bin/bash
# Usage function.
usage() {
echo ""
echo "Usage: $0 [OPTIONS]"
echo ""
echo "Options:"
echo " -c, --config FILE Use configuration file to provide input variables."
echo " -d, --debug Enable debug output messages for detailed logging."
echo " -v, --verbose Show standard output from commands (suppress by default)."
echo " -h, --help Show this help message and exit."
echo ""
echo "This script automates the setup and configuration of an SSH server with key-based authentication."
echo "It installs OpenSSH, starts the SSH service, configures firewall rules, and secures the SSH server by"
echo "disabling root login and password authentication. Additionally, it guides the user to add client keys."
echo ""
echo "Configuration file format:"
echo " The configuration file is a bash script that will be sourced."
echo " Use standard bash variable assignment syntax: variable=\"value\""
echo " Lines starting with # are treated as comments and ignored."
echo ""
}
# Parsed from command line arguments.
while [[ $# -gt 0 ]]; do
case "$1" in
-c|--config)
configFile="$2"
shift 2
;;
-d|--debug)
debug=true
shift
;;
-v|--verbose)
verbose=true
shift
;;
-h|--help)
usage
exit 0
;;
*)
echo "Invalid option: $1" >&2
usage
exit 1
;;
esac
done
# ===================================
# === PREPARE ENVIRONMENT ===========
# ===================================
# region
# INFRASTRUCTURE SETUP
# Set external logger- and error handling script paths
externalLogger=$(dirname "${BASH_SOURCE[0]}")"/utils/logging-and-output-function.sh"
externalErrorHandler=$(dirname "${BASH_SOURCE[0]}")"/utils/error-handling-function.sh"
# Source external logger and error handler (but allow execution without them)
source "${externalErrorHandler}" "Failed to set up SSH" || true
source "${externalLogger}" || true
# Redirect output functions if not debug enabled
run() {
if [[ "${verbose}" == "true" ]]; then
"$@"
else
"$@" > /dev/null
fi
}
# Verify if logger function exists or sett fallback
if [[ $(type -t logMessage) != function ]]; then
# Fallback minimalistic logger function
logMessage() {
local level="${2:-INFO}"
echo "[${level}] $1"
}
fi
# CONFIG FILE SOURCING
# Set default config file if none specified
: "${configFile:=$(dirname "${BASH_SOURCE[0]}")/setup.conf}"
# Source configuration file if it exists and is readable
if [[ -r "$configFile" ]]; then
logMessage "Sourcing configuration from '$configFile'..." "INFO"
# Source the configuration file
if source "$configFile"; then
logMessage "Configuration file loaded successfully." "DEBUG"
else
logMessage "Failed to source configuration file. Continuing with interactive prompts..." "WARNING"
fi
else
logMessage "No readable configuration file found. Continuing with interactive prompts..." "INFO"
fi
# BUSINESS LOGIC SETUP
# Get the username from environment variable
username="${USER}"
# Get the IP address of the machine
address=$(hostname -I | awk '{print $1}')
logMessage "Identified user '${username}' @ host '$(hostname)'" "DEBUG"
# If the username is "root", ask for confirmation before continuing
if [ "${username}" == "root" ]; then
# Prompt user for confirmation to continue
read -p "You are logged in as root. Are you sure you want to continue? (y/n): " confirmation
# If not "Yes" the abort script
if [[ ! "${confirmation}" =~ ^[Yy]$ ]]; then
logMessage "Aborted by user. Exiting setup..." "INFO"
exit 0
fi
fi
#endregion
logMessage "Starting SSH setup and config..." "INFO"
# ===================================
# === INSTALL & START SSH ===========
# ===================================
# region
# Check if OpenSSH server is installed
if dpkg -l | grep -q openssh-server; then
logMessage "OpenSSH server is already installed." "DEBUG"
else
logMessage "Installing OpenSSH server..." "INFO"
# Update and install OpenSSH server
run sudo apt-get update && run sudo apt-get install -y openssh-server
fi
# Check if SSH service is already running
if ! systemctl is-active --quiet ssh; then
logMessage "Starting and enabling SSH service..." "INFO"
# Start and enable the SSH service
sudo systemctl start ssh
sudo systemctl enable ssh
else
logMessage "SSH service is already running." "DEBUG"
fi
# endregion
# ===================================
# === CONFIGURE FIREWALL ============
# ===================================
# region
# Check if UFW is installed and SSH rule exists
if command -v ufw >/dev/null; then
logMessage "Checking firewall rules..." "DEBUG"
# Check if SSH firewall rule is already configured
if sudo ufw show added | grep -q ' 22/tcp'; then
logMessage "Firewall rule for SSH already exists." "DEBUG"
else
logMessage "Configuring firewall to allow SSH..." "INFO"
# Set allow rule for SSH on port 22 and reload UFW
run sudo ufw allow 22/tcp comment 'SSH'
run sudo ufw reload
fi
else
echo "UFW is not installed. Skipping firewall configuration." "WARNING"
fi
# endregion
# ===================================
# === INSTALL KEYCHAIN & PASS =======
# ===================================
# region
# Check if Keychain is installed
if command -v keychain &> /dev/null; then
logMessage "Keychain is already installed." "DEBUG"
else
logMessage "Installing Keychain Key Manager..." "INFO"
# Install Keychain Key Manager
run sudo apt-get update
run sudo apt-get install -y keychain
fi
# Check if pass is installed
if command -v pass &> /dev/null; then
logMessage "Pass is already installed." "DEBUG"
else
logMessage "Installing Pass Password Manager..." "INFO"
# Install Pass - The Standard Unix Password Manager
run sudo apt-get update
run sudo apt-get install -y pass
fi
# endregion
# ===================================
# === CREATE KEY & INITIALIZE PASS ==
# ===================================
# region
logMessage "Initializing 'Pass' Password Manager..." "INFO"
# Check if Pass is already initialized
if [[ -f "${HOME}/.password-store/.gpg-id" ]]; then
logMessage "Pass is already initialized." "DEBUG"
else
logMessage "Checking for existing GPG keys..." "INFO"
# Check for existing GPG keys
existingGpgKeys=$(gpg --list-secret-keys --keyid-format LONG)
# Check if any existing GPG keys were found
if [[ -n "${existingGpgKeys}" ]]; then
logMessage "Existing GPG keys found." "DEBUG"
echo "You already have one or more GPG keys:"
# List existing GPG keys
gpg --list-secret-keys --keyid-format LONG
fi
# Prompt the user: Enter to continue (default), Y to add a new entry
read -p "Press 'Enter' to add a new GPG key, or type 'N/n' to continue without adding: " 2>&1 confirm
# If user hits Enter, set confirm to "y"
if [[ -z "$confirm" ]]; then
confirm="y"
fi
# If user confirmed, generate a new GPG key
if [[ "${confirm}" =~ ^[Yy]$ ]]; then
logMessage "Generating a new GPG key..." "INFO"
# Prompt for GPG details if not provided in config
[[ -n "$gpgNameReal" ]] || read -p "Enter your real name for the GPG key: " 2>&1 gpgNameReal
[[ -n "$gpgNameEmail" ]] || read -p "Enter your email address for the GPG key: " 2>&1 gpgNameEmail
# Set default GPG configuration values if not provided
[[ -n "$gpgKeyType" ]] || gpgKeyType="RSA"
[[ -n "$gpgKeyLength" ]] || gpgKeyLength="4096"
[[ -n "$gpgExpireDate" ]] || gpgExpireDate="0"
# Create temporary GPG batch file
tempBatchFile=$(mktemp)
cat > "$tempBatchFile" <<EOF
Key-Type: ${gpgKeyType}
Key-Length: ${gpgKeyLength}
Name-Real: ${gpgNameReal}
Name-Email: ${gpgNameEmail}
Expire-Date: ${gpgExpireDate}
%commit
EOF
# Generate GPG key using temporary batch file
if gpg --batch --pinentry-mode=ask --generate-key "$tempBatchFile"; then
logMessage "GPG key generated successfully." "DEBUG"
else
logMessage "Failed to generate GPG key." "ERROR"
fi
# Clean up temporary file
rm -f "$tempBatchFile"
fi
logMessage "Fetching the last generated GPG key..." "INFO"
# Get the last generated key’s fingerprint
keyId=$(gpg --list-secret-keys --keyid-format LONG | grep 'sec' | tail -n1 | awk '{print $2}' | cut -d'/' -f2)
# Check if the key ID is empty
if [[ -z "${keyId}" ]]; then
logMessage "No GPG key found. Cannot initialize password manager." "ERROR"
else
logMessage "Found GPG Key ID: ${keyId}" "DEBUG"
logMessage "Initializing Password Manager with GPG key..." "INFO"
# Initialize pass with this key
pass init "${keyId}"
fi
fi
# endregion
# ===================================
# === CLIENT SSH AUTHENTICATION =====
# ===================================
# region
logMessage "Setting up SSH key-based authentication for '${username}'..." "INFO"
# Create SSH directory if it doesn't exist and set correct permissions
if [ ! -d "/home/${username}/.ssh" ]; then
# Create directory and set correct permissions
sudo mkdir -p /home/"${username}"/.ssh
sudo chmod 700 /home/"${username}"/.ssh
fi
# Create authorized_keys file if it doesn't exist
if [ ! -f /home/"${username}"/.ssh/authorized_keys ]; then
echo "Creating the authorized keys file..." "INFO"
# Create file and set correct permissions
sudo touch /home/"${username}"/.ssh/authorized_keys
sudo chmod 600 /home/"${username}"/.ssh/authorized_keys
fi
# Track the initial line count of the authorized_keys file
initialKeyCount=$(wc -l < /home/"${username}"/.ssh/authorized_keys 2>/dev/null || echo 0)
# Check if key file contains any pre-existing client entries
if [ $initialKeyCount -gt 0 ]; then
# Prompt user to add new key or continue
echo "The 'Authorized Keys' file already contains one or more entries. Do you want to add a new key entry?"
echo -e "\e[33mWARNING: Continuing the script will disable SSH password login, ensure the existing client public key is correct."
read -p "Press 'Enter' to continue or 'Y/y' to add a new client key: " 2>&1 reply
# If "N" or "n", set flag to add new client key
if [[ "${reply}" =~ ^[Yy]$ ]]; then
copyKey=true
else
logMessage "Continuing with existing client entries." "DEBUG"
fi
else
# Set flag
copyKey=true
fi
# Loop to check and prompt for the public key until it is found in the authorized_keys file
while [[ "$copyKey" == true ]]; do
logMessage "Waiting for new client public key..." "INFO"
# Prompt user to copy the public key from the client computer
echo "Please use the 'ssh-copy-id' command on your client machine to copy client public key to this server."
echo "Example: 'ssh-copy-id ${username}@${address}' or 'ssh-copy-id ${username}@$(hostname)'."
read -p "Press 'Enter' after copying the public key to continue..." 2>&1
# Get the current line count
currentKeyCount=$(wc -l < /home/"${username}"/.ssh/authorized_keys 2>/dev/null || echo 0)
# Check for new line and validate new key
if [ "${currentKeyCount}" -gt "${initialKeyCount}" ] && tail -n 1 /home/"${username}"/.ssh/authorized_keys | grep -q "^ssh-"; then
logMessage "Client public key successfully added." "INFO"
break
else
logMessage "Public key not found in the authorized keys file." "WARNING"
fi
done
# endregion
# ===================================
# === DISABLE MOTD MESSAGES =========
# ===================================
# region
logMessage "Disabling SSH welcome messages..." "INFO"
# Backup PAM SSH configuration
pamSshdFile="/etc/pam.d/sshd"
pamSshdBackup="${pamSshdFile}.bak.${timestamp}"
if [ -f "${pamSshdFile}" ]; then
sudo cp "${pamSshdFile}" "${pamSshdBackup}"
# Comment out MOTD lines if they exist and are not already commented
if sudo grep -q "^[[:space:]]*session[[:space:]]*optional[[:space:]]*pam_motd\.so.*motd=/run/motd\.dynamic" "${pamSshdFile}"; then
sudo sed -i '/^[[:space:]]*session[[:space:]]*optional[[:space:]]*pam_motd\.so.*motd=\/run\/motd\.dynamic/s/^/# /' "${pamSshdFile}"
logMessage "Commented out dynamic MOTD line in ${pamSshdFile}" "DEBUG"
fi
if sudo grep -q "^[[:space:]]*session[[:space:]]*optional[[:space:]]*pam_motd\.so.*noupdate" "${pamSshdFile}"; then
sudo sed -i '/^[[:space:]]*session[[:space:]]*optional[[:space:]]*pam_motd\.so.*noupdate/s/^/# /' "${pamSshdFile}"
logMessage "Commented out noupdate MOTD line in ${pamSshdFile}" "DEBUG"
fi
logMessage "MOTD messages disabled." "INFO"
else
logMessage "PAM SSH configuration file not found. Skipping MOTD disable." "WARNING"
fi
# endregion
logMessage "SSH enabled and key-based authentication configured for user '${username}'." "INFO"
# ===================================
# === SSH CONFIGURATION =============
# ===================================
# region
logMessage "Backing up existing SSH config and disabling root login and password authentication..."
# Backup existing SSH configuration
timestamp=$(date +"%Y-%m-%d_%H-%M-%S")
sshConfigFile="/etc/ssh/sshd_config"
sshConfigBackup="${sshConfigFile}.bak.${timestamp}"
sudo cp "${sshConfigFile}" "${sshConfigBackup}"
# Check and update SSH configuration values only if necessary
sshConfigUpdate() {
local setting="$1"
local value="$2"
# Check if a non-commented line for the setting already exists (excluding lines starting with "# ")
if sudo grep -E "^[[:space:]]*${setting}\b" "${sshConfigFile}" > /dev/null; then
# Update existing setting line
sudo sed -i -E "/^# /! s|^[[:space:]]*${setting}\b.*|${setting} ${value}|" "${sshConfigFile}"
# If only a commented line exists
elif sudo grep -E "^[[:space:]]*#?[[:space:]]*${setting}\b" "${sshConfigFile}" > /dev/null; then
# Replace commented line (but not "# " style comments)
sudo sed -i -E "/^# /! s|^[[:space:]]*#?[[:space:]]*${setting}\b.*|${setting} ${value}|" "${sshConfigFile}"
else
# Append if setting does not exist at all
echo "${setting} ${value}" | sudo tee -a "${sshConfigFile}" > /dev/null
fi
configUpdated=true
}
# Modify config to disable root login and password authentication
sshConfigUpdate "PermitRootLogin" "no"
sshConfigUpdate "PasswordAuthentication" "no"
sshConfigUpdate "ChallengeResponseAuthentication" "no"
sshConfigUpdate "UsePAM" "yes"
sshConfigUpdate "PrintMotd" "no"
sshConfigUpdate "PrintLastLog" "yes"
logMessage "Disabling SSH welcome messages..." "INFO"
# Backup PAM SSH configuration
sshPamFile="/etc/pam.d/sshd"
sshPamBackup="${sshPamFile}.bak.${timestamp}"
if [ -f "${sshPamFile}" ]; then
sudo cp "${sshPamFile}" "${sshPamBackup}"
# Comment out MOTD lines if they exist and are not already commented
if sudo grep -q "^[[:space:]]*session[[:space:]]*optional[[:space:]]*pam_motd\.so.*motd=/run/motd\.dynamic" "${sshPamFile}"; then
sudo sed -i '/^[[:space:]]*session[[:space:]]*optional[[:space:]]*pam_motd\.so.*motd=\/run\/motd\.dynamic/s/^/# /' "${sshPamFile}"
logMessage "Commented out dynamic MOTD line in ${sshPamFile}" "DEBUG"
fi
if sudo grep -q "^[[:space:]]*session[[:space:]]*optional[[:space:]]*pam_motd\.so.*noupdate" "${sshPamFile}"; then
sudo sed -i '/^[[:space:]]*session[[:space:]]*optional[[:space:]]*pam_motd\.so.*noupdate/s/^/# /' "${sshPamFile}"
logMessage "Commented out no-update MOTD line in ${sshPamFile}" "DEBUG"
fi
logMessage "MOTD messages disabled." "DEBUG"
else
logMessage "PAM SSH configuration file not found. Skipping MOTD disable." "WARNING"
fi
# If config was updated, restart SSH and keep the backup
if [ "${configUpdated}" = true ]; then
logMessage "SSH configuration updated. Restarting SSH service..." "INFO"
# Restart SSH service to apply changes
sudo systemctl restart ssh
else
logMessage "No changes made to the SSH configuration. Removing configuration backup..." "INFO"
# Remove the backup file if no changes were made
sudo rm "${sshConfigBackup}"
fi
# endregion
logMessage "SSH enabled and key-based authentication configured for user '${username}'." "INFO"
# Inform user about login
echo "You can now log in using the private key corresponding to the provided- or existing public key."
exit 0