Nếu bạn là một người thường xuyên phải deploy các sản phẩm test, hẳn sẽ không ít lần bạn phải loay hoay chạy đi chạy lại đống script cấu hình server mỗi khi khởi tạo một VPS mới.
Script tự động cấu hình VPS mới thì mình thấy cũng nhiều bài đăng rồi, tuy nhiên những script đó chưa đáp ứng được nhu cầu của mình về thiết lập sẵn các cơ chế bảo vệ an toàn cho server.
Với kinh nghiệm không dưới 100 lần cài mới VPS, mình đã viết lại thành bộ script tự động, giúp các bạn giảm tối đa thời gian thiết lập ban đầu cho VPS. Nếu không tính thời gian chờ đợi do cập nhật OS, thì các bạn sẽ chỉ mất 1 tích tắc để cài đặt xong cấu hình chung cho 1 VPS.
Tại sao cần script tự động?
Tới đây chắc có nhiều bạn thắc mắc, tại sao không restore từ file image của VPS cũ. Lý do là bởi server của mình được xử lý bảo vệ bởi 3 lớp: Public Key (tạo ngẫu nhiên theo từng client), Password của account SSH, và Passcode của Google Authenticator (cái này thay đổi theo từng account, từng VPS).
Vì vậy, các công việc mình làm khi khởi tạo 1 VPS mới như sau:
- Restore image với bản update OS mới nhất để giảm thời gian chờ đợi cập nhật khi chạy script.
- Chạy script tự động thiết lập cấu hình ban đầu cho VPS.
Script tự động thiết lập những gì?
Dưới đây là những thiết lập mà One-Press VPS Starter hỗ trợ:
- Khởi tạo account có quyền quản trị thay cho account root.
- Không cho phép truy cập root bằng kết nối từ xa.
- Đổi port SSH mặc định.
- Thiết lập cấu hình firewall với chính sách bảo mật cần thiết, đáng tin cậy.
- Xác thực 3 lớp, sử dụng Public Key, mật khẩu và Google Authenticator. Đây là thiết lập cũng khá quan trọng, vì thông thường mình thấy các bạn hay chỉ sử dụng Public Key thay cho mật khẩu, tiềm ẩn khá nhiều rủi ro khi Private Key của các bạn bị sao chép, server không có các lớp bảo vệ khác, rất dễ bị tấn công, rủi ro nhất đối với server launching product go live.
One-Press VPS Starter
Không dông dài nữa, sau đây là nội dung bộ One-Press VPS Starter script mình đúc kết lại.
[alert type=”info” title=”Tham khảo”] Source code được lưu trữ trên GitHub tại repository: https://github.com/travistran1989/one-press-vps-starter [/alert]
travis_vps_starter.sh
Đây là file thực thi chính, gọi tới các file thực thi con. Khi không cần thực hiện thiết lập nào chỉ cần comment lại là OK.
#!/bin/bash # # @author: Travis Tran # @website: https://travistran.me # @notice: run as root # Read arguments while getopts ":u:k:p:" opt; do case $opt in u) ADMIN_USER="$OPTARG" ;; k) PUB_KEY="$OPTARG" ;; p) SSH_PORT="$OPTARG" ;; ?) echo "Invalid option -$OPTARG" >&2 exit 1 ;; esac done echo 'Starting set up VPS...' [ -z "$SSH_PORT" ] && SSH_PORT=1989 [ -z "$ADMIN_USER" ] && ADMIN_USER=adminUser # Update OS chmod +x update_os.sh ./update_os.sh # Install some useful packages chmod +x useful_packages.sh ./useful_packages.sh # Automatically update clock chmod +x update_clock.sh ./update_clock.sh # Setup iptables chmod +x setup_iptables.sh ./setup_iptables.sh # Setup SSH configuration chmod +x setup_sshd.sh ./setup_sshd.sh $SSH_PORT # Create user with administrator rights chmod +x create_user.sh ./create_user.sh $ADMIN_USER $PUB_KEY echo 'Setting up VPS all DONE.'
update_os.sh
Cập nhật hệ điều hành.
#!/bin/bash # # @author: Travis Tran # @website: https://travistran.me # @notice: run as root echo 'Updating OS...' sudo yum update -y echo 'Updating OS... DONE'
useful_packages.sh
Cài đặt một số gói cần thiết.
#!/bin/bash # # @author: Travis Tran # @website: https://travistran.me # @notice: run as root echo 'Installing useful packages...' sudo yum -y install nc telnet traceroute gcc make pcre pcre-devel openssl libcurl libcurl-devel rpm nano tar zip unzip echo 'Installing useful packages... DONE'
update_clock.sh
Thiết lập giờ hệ thống, tự động đồng bộ giờ quốc tế.
#!/bin/bash # # @author: Travis Tran # @website: https://travistran.me # @notice: run as root echo 'Setting auto-update time...' sudo rm -rf /etc/localtime # Change to your locale as needed sudo ln -s /usr/share/zoneinfo/Asia/Ho_Chi_Minh /etc/localtime cat <<EOT >> /etc/sysconfig/clock ZONE="Asia/Ho_Chi_Minh" UTC=false ARC=false EOT sudo hwclock --systohc --localtime sudo hwclock # Synchronize local time with global time from internet sudo yum -y install ntp sudo systemctl enable ntpd sudo ntpdate -b -u time.nist.gov sudo systemctl start ntpd echo 'Setting auto-update time... DONE'
setup_iptables.sh
Thiết lập iptables và các chính sách cần thiết. Mình đã có bài viết tổng hợp các câu lệnh thường dùng với iptables. Xem tại: https://travistran.me/su-dung-iptables-tren-centos-1357/
#!/bin/bash # # @author: Travis Tran # @website: https://travistran.me # @notice: run as root echo 'Setting up iptables...' # Disable firewalld on CentOS 7 sudo systemctl stop firewalld sudo systemctl disable firewalld # Install iptables sudo yum install -y iptables-services sudo systemctl start iptables sudo systemctl status iptables sudo systemctl enable iptables echo 'Setting up basic policies...' # Basic rules sudo iptables -F sudo iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP sudo iptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP sudo iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP sudo iptables -A INPUT -i lo -j ACCEPT sudo iptables -A INPUT -p tcp -m multiport --dport 80,443 -j ACCEPT sudo iptables -I INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT sudo iptables -P OUTPUT ACCEPT sudo iptables -P INPUT DROP # Save configuration sudo iptables-save | sudo tee /etc/sysconfig/iptables # Apply changes sudo systemctl restart iptables echo 'Setting up iptables... DONE'
setup_sshd.sh
Thiết lập cấu hình SSH.
#!/bin/bash # # @author: Travis Tran # @website: https://travistran.me # @notice: run as root SSH_PORT=$1 [ -z "$SSH_PORT" ] && SSH_PORT=22 echo 'Setting up SSH service...' if [ "$SSH_PORT" != "22" ]; then echo 'Changing SSH port...' # If SSH port difference than 22, configure new SSH port # Here you need to change "#Port 22" for fit with your current SSH configuration sudo sed -i -e 's/'"#Port 22"'/'"Port $SSH_PORT"'/g' /etc/ssh/sshd_config sudo yum install -y policycoreutils-python sudo semanage port -a -t ssh_port_t -p tcp $SSH_PORT sudo systemctl restart sshd fi echo 'Adding SSH port to iptables...' # Add SSH port to firewall sudo iptables -I INPUT -p tcp -m tcp --dport $SSH_PORT -j ACCEPT sudo iptables -I INPUT -p tcp --dport $SSH_PORT -m state --state NEW -m recent --set --name ssh --rsource sudo iptables -I INPUT -p tcp --dport $SSH_PORT -m state --state NEW -m recent ! --rcheck --seconds 60 --hitcount 4 --name ssh --rsource -j ACCEPT sudo iptables-save | sudo tee /etc/sysconfig/iptables sudo service iptables restart echo 'Setting up SSH service... DONE'
create_user.sh
Khởi tạo user và thiết lập các chính
#!/bin/bash # # @author: Travis Tran # @website: https://travistran.me # @notice: run as root ADMIN_USER=$1 PUB_KEY=$2 # Validate arguments [ -z "$ADMIN_USER" ] && echo "ADMIN_USER is empty. Exiting..." && exit 1 [ -z "$PUB_KEY" ] && echo "PUB_KEY is empty. Exiting..." && exit 1 echo 'Creating admin user $ADMIN_USER...' # Create user adduser $ADMIN_USER # Add user to group wheel gpasswd -a $ADMIN_USER wheel # Set password for user. Here I set password same as user. echo -e "$ADMIN_USERn$ADMIN_USER" | passwd $ADMIN_USER # Create .ssh directory for public key authentication runuser -l $ADMIN_USER -c 'mkdir -p ~/.ssh' runuser -l $ADMIN_USER -c 'chmod 700 ~/.ssh' runuser -l $ADMIN_USER -c 'touch ~/.ssh/authorized_keys' runuser -l $ADMIN_USER -c 'chmod 600 ~/.ssh/authorized_keys' # Copy public key to .ssh folder cp $PUB_KEY '/home/'"$ADMIN_USER"'/.ssh/' # Change owner to new user chown "$ADMIN_USER"'.' '/home/'"$ADMIN_USER"'/.ssh/'"$PUB_KEY" # Append key file to store. Here you could delete key file after appending. runuser -l $ADMIN_USER -c 'cat ~/.ssh/'"$PUB_KEY"' >> ~/.ssh/authorized_keys' # Create Google Authenticator and write output to file. After setup completed, you could nano the output file for details. sudo yum -y install google-authenticator runuser -l $ADMIN_USER -c 'cd ~' runuser -l $ADMIN_USER -c 'google-authenticator -t -d -f -r 3 -R 30 -W >> .google-authenticator.out' cat <<EOT >> /etc/pam.d/sshd # Google Authenticator auth required pam_google_authenticator.so EOT # Change SSH configuration for 3 layers security: public key, password and Google Authenticator sudo sed -i -e 's/'"#PermitRootLogin no"'/'"PermitRootLogin no"'/g' /etc/ssh/sshd_config sudo sed -i -e 's/'"PermitRootLogin yes"'/'"PermitRootLogin no"'/g' /etc/ssh/sshd_config sudo sed -i -e 's/'"#StrictModes yes"'/'"StrictModes yes"'/g' /etc/ssh/sshd_config sudo sed -i -e 's/'"StrictModes no"'/'"StrictModes yes"'/g' /etc/ssh/sshd_config sudo sed -i -e 's/'"#PubkeyAuthentication yes"'/'"PubkeyAuthentication yes"'/g' /etc/ssh/sshd_config sudo sed -i -e 's/'"PubkeyAuthentication no"'/'"PubkeyAuthentication yes"'/g' /etc/ssh/sshd_config sudo sed -i -e 's/'"#PasswordAuthentication no"'/'"PasswordAuthentication no"'/g' /etc/ssh/sshd_config sudo sed -i -e 's/'"PasswordAuthentication yes"'/'"PasswordAuthentication no"'/g' /etc/ssh/sshd_config sudo sed -i -e 's/'"#PermitEmptyPasswords no"'/'"PermitEmptyPasswords no"'/g' /etc/ssh/sshd_config sudo sed -i -e 's/'"PermitEmptyPasswords yes"'/'"PermitEmptyPasswords no"'/g' /etc/ssh/sshd_config sudo sed -i -e 's/'"#ChallengeResponseAuthentication yes"'/'"ChallengeResponseAuthentication yes"'/g' /etc/ssh/sshd_config sudo sed -i -e 's/'"ChallengeResponseAuthentication no"'/'"ChallengeResponseAuthentication yes"'/g' /etc/ssh/sshd_config cat <<EOT >> /etc/ssh/sshd_config AuthenticationMethods publickey,keyboard-interactive publickey,password EOT # Restart SSH service to apply changes. sudo systemctl restart sshd echo 'Creating admin user $ADMIN_USER... DONE'
Tôi sẽ sử dụng nó thế nào?
Chuẩn bị
- Copy thư mục
travis_vps_starter
lên server. - Tạo một cặp khóa key-pair có sử dụng mật khẩu (passphrase) ở máy khách như desktop, laptop, … (google cách tạo nha), sau đó copy public key lên thư mục
travis_vps_starter
trên server. Ví dụ, trên Mac OS, bạn có thể tạo cặp key-pair bằng câu lệnh sau:ssh-keygen -t rsa -C "[email protected]"
.
Thực thi
- Gán quyền thực thi cho script bằng lệnh:
chmod +x travis_vps_starter.sh
- Thực thi file chạy:
./travis_vps_starter.sh -u "admin" -k "id_rsa.pub" -p 1989
. Trong đó:-u
: tài khoản có quyền quản trị.-k
: tên file public key đã tải lên, nằm trong cùng thư mục với file thực thi.-p
: port SSH.
Kiểm tra
Mình đính kèm file log khi thực thi mẫu trên một VPS cài đặt CentOS 7 mới. Các bạn có thể tham khảo tại đường link: https://github.com/travistran1989/one-press-vps-starter/blob/master/travis_vps_starter/test.log
Chúc các bạn thành công.
Một vài hình ảnh sau khi tậu thành chánh quả.
[su_carousel source=”media: 1393,1396,1395,1394″ link=”lightbox”]