ubuntu服务器初始化安全设置

初始化 ubuntu 20.04 的安全设置 shell 脚本。同时添加 clodflare ip 段到特定端口白名单。

初始化脚本

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
#!/bin/bash

# Untuntu 20.04 LTS x64 Server Setup Script

# Variables
new_ssh_port=1000 # Replace with your desired SSH port
new_user="xxx" # Replace with your desired username
public_key="xxxxx" # Replace with your public SSH key

# Ensure the script is run as root
if [ "$(id -u)" != "0" ]; then
echo "This script must be run as root" 1>&2
exit 1
fi

# Check if openssh-server is installed
if ! dpkg -l | grep -q openssh-server; then
echo "Installing OpenSSH Server..."
apt-get update
apt-get install -y openssh-server
fi

# Enable SSH service
systemctl enable ssh.service

# Start SSH service
systemctl start ssh.service

# Verify service status
if systemctl is-active --quiet ssh.service; then
echo "SSH service is running"
else
echo "SSH service failed to start"
systemctl status ssh.service
exit 1
fi

# 1. Configure SSH
echo "Configuring SSH..."

# Remove cloud init
rm /etc/ssh/sshd_config.d/*

# Replace Port configuration - matches both commented and uncommented
sed -i -E 's/^#?Port[[:space:]]+[0-9]+/Port '"$new_ssh_port"'/' /etc/ssh/sshd_config

# Replace PasswordAuthentication - matches both commented and uncommented, any value
sed -i -E 's/^#?PasswordAuthentication[[:space:]]+(yes|no)/PasswordAuthentication no/' /etc/ssh/sshd_config

# Replace PermitRootLogin - matches any existing value
sed -i -E 's/^#?PermitRootLogin[[:space:]]+(yes|no|prohibit-password|without-password)/PermitRootLogin no/' /etc/ssh/sshd_config

# Additional SSH security configurations
sed -i -E '
s/^#?Protocol.*/Protocol 2/;
s/^#?MaxAuthTries.*/MaxAuthTries 3/;
s/^#?LoginGraceTime.*/LoginGraceTime 60/;
s/^#?StrictModes.*/StrictModes yes/;
s/^#?X11Forwarding.*/X11Forwarding no/;
s/^#?PermitEmptyPasswords.*/PermitEmptyPasswords no/;
s/^#?ClientAliveInterval.*/ClientAliveInterval 300/;
s/^#?ClientAliveCountMax.*/ClientAliveCountMax 2/;
s/^#?AllowUsers.*/AllowUsers '"$new_user"'/;
s/^#?UsePrivilegeSeparation.*/UsePrivilegeSeparation yes/;
s/^#?TCPKeepAlive.*/TCPKeepAlive no/
' /etc/ssh/sshd_config

# 2. Create new user with sudo privileges
echo "Creating new user '$new_user' with sudo privileges..."
adduser --gecos "" "$new_user"
echo "$new_user ALL=(ALL) ALL" >> /etc/sudoers

# Add public key for new user
echo "Adding public key for new user..."
mkdir -p /home/$new_user/.ssh
echo $public_key > /home/$new_user/.ssh/authorized_keys
chown -R $new_user:$new_user /home/$new_user/.ssh
chmod 700 /home/$new_user/.ssh
chmod 600 /home/$new_user/.ssh/authorized_keys

systemctl restart sshd

# 3. Configure UFW Firewall
echo "Configuring UFW Firewall..."
ufw default deny incoming
ufw default allow outgoing
ufw allow $new_ssh_port/tcp
ufw enable
ufw reload
ufw status

# 4. Install Fail2Ban and configure
echo "Installing Fail2Ban..."
apt-get install -y fail2ban
cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
sed -i "s/bantime = 10m/bantime = 1h/" /etc/fail2ban/jail.local
sed -i "s/findtime = 10m/findtime = 10m/" /etc/fail2ban/jail.local
sed -i "s/maxretry = 5/maxretry = 3/" /etc/fail2ban/jail.local
systemctl restart fail2ban

# 5. Install nginx
echo "Installing nginx..."
apt-get install -y nginx

echo "Configuration complete. Please remember to test SSH login before closing your current session."

添加cf白名单

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
#!/bin/bash

# Check if jq is installed
if ! command -v jq &> /dev/null
then
echo "jq could not be found, attempting to install..."
sudo apt-get update -y
sudo apt-get install -y jq
else
echo "jq is already installed"
fi

# List all UFW rules with numbers and filter by port 8443
rules=$(ufw status numbered | grep '8443' | awk -F '[][]' '{ print $2 }')

# Check if any rules were found
if [ -z "$rules" ]; then
echo "No UFW rules found for port 8443."
else
# Reverse the rules order to avoid disrupting the numbering
for rule in $(echo "$rules" | tac); do
echo "Deleting rule $rule for port 8443..."
yes | ufw delete $rule
done

echo "UFW rules deletion complete."
# Show current status
ufw status verbose

echo "\n\n----------- update to new ip ranges ---------\n\n"
fi

# Fetch JSON data using curl
json_data=$(curl --request GET \
--url https://api.cloudflare.com/client/v4/ips \
--header 'Authorization: Bearer YOUR_BEARER_TOKEN' \
--header 'Content-Type: application/json')

# Check if curl command was successful
if [ $? -ne 0 ]; then
echo "Failed to fetch data from API."
exit 1
fi

# Extract ipv4_cidrs using jq and convert it into a Bash array
readarray -t ip_ranges < <(echo "$json_data" | jq -r '.result.ipv4_cidrs[]')

# Add UFW rules for each IP range
for ip in "${ip_ranges[@]}"; do
echo "Allowing IP range $ip on port 8443"
ufw allow from $ip to any port 8443
done

ufw status verbose
ufw reload

echo "UFW rules added successfully."