Last active
May 27, 2025 16:38
-
-
Save hungdh9x/41a3657374e9ffb6699017635af054a1 to your computer and use it in GitHub Desktop.
VPS setup
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# VPS Security Hardening Script for Ubuntu/Debian | |
# Author: Security Engineer | |
# Description: Automated security setup for new VPS on Vultr | |
set -euo pipefail | |
# Colors for output | |
RED='\033[0;31m' | |
GREEN='\033[0;32m' | |
YELLOW='\033[1;33m' | |
BLUE='\033[0;34m' | |
NC='\033[0m' # No Color | |
# Logging function | |
log() { | |
echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')] $1${NC}" | |
} | |
warn() { | |
echo -e "${YELLOW}[WARNING] $1${NC}" | |
} | |
error() { | |
echo -e "${RED}[ERROR] $1${NC}" | |
exit 1 | |
} | |
# Check if running as root | |
check_root() { | |
if [[ $EUID -ne 0 ]]; then | |
error "This script must be run as root" | |
fi | |
} | |
# Update system | |
update_system() { | |
log "Updating system packages..." | |
apt update && apt upgrade -y | |
apt install -y curl wget unzip software-properties-common apt-transport-https ca-certificates gnupg lsb-release | |
} | |
# Create non-root user | |
create_user() { | |
read -p "Enter username for new user: " USERNAME | |
read -s -p "Enter password for $USERNAME: " PASSWORD | |
echo | |
if id "$USERNAME" &>/dev/null; then | |
warn "User $USERNAME already exists" | |
else | |
log "Creating user: $USERNAME" | |
useradd -m -s /bin/bash "$USERNAME" | |
echo "$USERNAME:$PASSWORD" | chpasswd | |
usermod -aG sudo "$USERNAME" | |
# Setup SSH directory | |
mkdir -p /home/$USERNAME/.ssh | |
chmod 700 /home/$USERNAME/.ssh | |
chown $USERNAME:$USERNAME /home/$USERNAME/.ssh | |
fi | |
} | |
# Configure SSH security | |
configure_ssh() { | |
log "Configuring SSH security..." | |
# Backup original config | |
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup | |
# SSH security configurations | |
cat > /etc/ssh/sshd_config << 'EOF' | |
# SSH Security Configuration | |
Port 2222 | |
Protocol 2 | |
HostKey /etc/ssh/ssh_host_rsa_key | |
HostKey /etc/ssh/ssh_host_ecdsa_key | |
HostKey /etc/ssh/ssh_host_ed25519_key | |
# Authentication | |
LoginGraceTime 60 | |
PermitRootLogin no | |
StrictModes yes | |
MaxAuthTries 3 | |
MaxSessions 2 | |
PubkeyAuthentication yes | |
AuthorizedKeysFile .ssh/authorized_keys | |
PasswordAuthentication no | |
PermitEmptyPasswords no | |
ChallengeResponseAuthentication no | |
UsePAM yes | |
# Security options | |
X11Forwarding no | |
PrintMotd no | |
PrintLastLog yes | |
TCPKeepAlive yes | |
Compression delayed | |
ClientAliveInterval 300 | |
ClientAliveCountMax 2 | |
AllowTcpForwarding no | |
AllowStreamLocalForwarding no | |
GatewayPorts no | |
PermitTunnel no | |
# Restrict users | |
AllowUsers $USERNAME | |
DenyUsers root | |
# Logging | |
SyslogFacility AUTHPRIV | |
LogLevel INFO | |
# Subsystems | |
Subsystem sftp /usr/lib/openssh/sftp-server -f AUTHPRIV -l INFO | |
EOF | |
# Generate SSH key for user | |
if [[ ! -f /home/$USERNAME/.ssh/id_rsa ]]; then | |
log "Generating SSH key for $USERNAME..." | |
sudo -u $USERNAME ssh-keygen -t rsa -b 4096 -f /home/$USERNAME/.ssh/id_rsa -N "" | |
sudo -u $USERNAME cp /home/$USERNAME/.ssh/id_rsa.pub /home/$USERNAME/.ssh/authorized_keys | |
chmod 600 /home/$USERNAME/.ssh/authorized_keys | |
chown $USERNAME:$USERNAME /home/$USERNAME/.ssh/authorized_keys | |
fi | |
# Restart SSH service | |
systemctl restart sshd | |
systemctl enable sshd | |
} | |
# Configure firewall (UFW) | |
configure_firewall() { | |
log "Configuring UFW firewall..." | |
# Install and setup UFW | |
apt install -y ufw | |
# Default policies | |
ufw --force reset | |
ufw default deny incoming | |
ufw default allow outgoing | |
# Allow SSH on custom port | |
ufw allow 2222/tcp comment 'SSH' | |
# Allow common services (uncomment as needed) | |
# ufw allow 80/tcp comment 'HTTP' | |
# ufw allow 443/tcp comment 'HTTPS' | |
# ufw allow 53 comment 'DNS' | |
# Enable firewall | |
ufw --force enable | |
# Show status | |
ufw status numbered | |
} | |
# Install and configure Fail2Ban | |
configure_fail2ban() { | |
log "Installing and configuring Fail2Ban..." | |
apt install -y fail2ban | |
# Create custom jail configuration | |
cat > /etc/fail2ban/jail.local << 'EOF' | |
[DEFAULT] | |
# Ban time (seconds) | |
bantime = 3600 | |
findtime = 600 | |
maxretry = 3 | |
backend = systemd | |
# Email notifications (configure as needed) | |
# destemail = [email protected] | |
# sender = [email protected] | |
# action = %(action_mwl)s | |
[sshd] | |
enabled = true | |
port = 2222 | |
filter = sshd | |
logpath = /var/log/auth.log | |
maxretry = 3 | |
bantime = 3600 | |
[nginx-http-auth] | |
enabled = false | |
filter = nginx-http-auth | |
port = http,https | |
logpath = /var/log/nginx/error.log | |
[nginx-limit-req] | |
enabled = false | |
filter = nginx-limit-req | |
port = http,https | |
logpath = /var/log/nginx/error.log | |
EOF | |
# Start and enable Fail2Ban | |
systemctl start fail2ban | |
systemctl enable fail2ban | |
} | |
# System hardening | |
system_hardening() { | |
log "Applying system hardening..." | |
# Disable unused network protocols | |
cat >> /etc/modprobe.d/blacklist-rare-network.conf << 'EOF' | |
# Disable rare network protocols | |
install dccp /bin/true | |
install sctp /bin/true | |
install rds /bin/true | |
install tipc /bin/true | |
EOF | |
# Kernel security parameters | |
cat > /etc/sysctl.d/99-security.conf << 'EOF' | |
# IP Spoofing protection | |
net.ipv4.conf.default.rp_filter = 1 | |
net.ipv4.conf.all.rp_filter = 1 | |
# Ignore ICMP redirects | |
net.ipv4.conf.all.accept_redirects = 0 | |
net.ipv6.conf.all.accept_redirects = 0 | |
net.ipv4.conf.default.accept_redirects = 0 | |
net.ipv6.conf.default.accept_redirects = 0 | |
# Ignore send redirects | |
net.ipv4.conf.all.send_redirects = 0 | |
net.ipv4.conf.default.send_redirects = 0 | |
# Disable source packet routing | |
net.ipv4.conf.all.accept_source_route = 0 | |
net.ipv6.conf.all.accept_source_route = 0 | |
net.ipv4.conf.default.accept_source_route = 0 | |
net.ipv6.conf.default.accept_source_route = 0 | |
# Log Martians | |
net.ipv4.conf.all.log_martians = 1 | |
net.ipv4.conf.default.log_martians = 1 | |
# Ignore ICMP ping requests | |
net.ipv4.icmp_echo_ignore_all = 1 | |
# Ignore Directed pings | |
net.ipv4.icmp_echo_ignore_broadcasts = 1 | |
# Disable IPv6 if not needed | |
net.ipv6.conf.all.disable_ipv6 = 1 | |
net.ipv6.conf.default.disable_ipv6 = 1 | |
# TCP SYN flood protection | |
net.ipv4.tcp_syncookies = 1 | |
net.ipv4.tcp_max_syn_backlog = 2048 | |
net.ipv4.tcp_synack_retries = 2 | |
net.ipv4.tcp_syn_retries = 5 | |
# Control buffer overflow attacks | |
net.core.rmem_default = 262144 | |
net.core.rmem_max = 16777216 | |
net.core.wmem_default = 262144 | |
net.core.wmem_max = 16777216 | |
# Hide kernel pointers | |
kernel.kptr_restrict = 2 | |
# Restrict dmesg | |
kernel.dmesg_restrict = 1 | |
# Restrict ptrace | |
kernel.yama.ptrace_scope = 1 | |
EOF | |
# Apply sysctl settings | |
sysctl -p /etc/sysctl.d/99-security.conf | |
} | |
# Install security tools | |
install_security_tools() { | |
log "Installing security monitoring tools..." | |
# Install essential security tools | |
apt install -y \ | |
rkhunter \ | |
chkrootkit \ | |
lynis \ | |
aide \ | |
logwatch \ | |
psmisc \ | |
lsof \ | |
netstat-nat \ | |
tcpdump \ | |
nmap \ | |
htop \ | |
iftop \ | |
iotop \ | |
unattended-upgrades | |
# Configure automatic security updates | |
echo 'Unattended-Upgrade::Automatic-Reboot "false";' >> /etc/apt/apt.conf.d/50unattended-upgrades | |
echo 'Unattended-Upgrade::Automatic-Reboot-Time "02:00";' >> /etc/apt/apt.conf.d/50unattended-upgrades | |
# Enable automatic updates | |
systemctl enable unattended-upgrades | |
# Initialize AIDE database | |
log "Initializing AIDE database (this may take a while)..." | |
aideinit | |
mv /var/lib/aide/aide.db.new /var/lib/aide/aide.db | |
} | |
# Setup log monitoring | |
setup_log_monitoring() { | |
log "Setting up log monitoring..." | |
# Configure logrotate for security logs | |
cat > /etc/logrotate.d/security-logs << 'EOF' | |
/var/log/auth.log /var/log/syslog /var/log/messages { | |
daily | |
missingok | |
rotate 52 | |
compress | |
delaycompress | |
notifempty | |
sharedscripts | |
postrotate | |
systemctl reload rsyslog > /dev/null 2>&1 || true | |
endscript | |
} | |
EOF | |
# Setup basic log monitoring script | |
cat > /usr/local/bin/security-check.sh << 'EOF' | |
#!/bin/bash | |
# Basic security monitoring script | |
LOG_FILE="/var/log/security-check.log" | |
DATE=$(date '+%Y-%m-%d %H:%M:%S') | |
echo "[$DATE] Running security checks..." >> $LOG_FILE | |
# Check for failed login attempts | |
FAILED_LOGINS=$(grep "authentication failure" /var/log/auth.log | wc -l) | |
if [ $FAILED_LOGINS -gt 10 ]; then | |
echo "[$DATE] WARNING: $FAILED_LOGINS failed login attempts detected" >> $LOG_FILE | |
fi | |
# Check for new users | |
NEW_USERS=$(grep "new user" /var/log/auth.log | tail -n 5) | |
if [ ! -z "$NEW_USERS" ]; then | |
echo "[$DATE] INFO: New user accounts detected:" >> $LOG_FILE | |
echo "$NEW_USERS" >> $LOG_FILE | |
fi | |
# Check system load | |
LOAD=$(uptime | awk '{print $10}' | sed 's/,//') | |
if (( $(echo "$LOAD > 2.0" | bc -l) )); then | |
echo "[$DATE] WARNING: High system load: $LOAD" >> $LOG_FILE | |
fi | |
# Check disk usage | |
DISK_USAGE=$(df / | tail -1 | awk '{print $5}' | sed 's/%//') | |
if [ $DISK_USAGE -gt 80 ]; then | |
echo "[$DATE] WARNING: Disk usage is $DISK_USAGE%" >> $LOG_FILE | |
fi | |
echo "[$DATE] Security check completed" >> $LOG_FILE | |
EOF | |
chmod +x /usr/local/bin/security-check.sh | |
# Add to crontab for hourly execution | |
(crontab -l 2>/dev/null; echo "0 * * * * /usr/local/bin/security-check.sh") | crontab - | |
} | |
# Setup Docker security (optional) | |
setup_docker_security() { | |
read -p "Do you want to install and secure Docker? (y/n): " -n 1 -r | |
echo | |
if [[ $REPLY =~ ^[Yy]$ ]]; then | |
log "Installing Docker with security configurations..." | |
# Install Docker | |
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg | |
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null | |
apt update | |
apt install -y docker-ce docker-ce-cli containerd.io | |
# Add user to docker group | |
usermod -aG docker $USERNAME | |
# Docker security daemon configuration | |
mkdir -p /etc/docker | |
cat > /etc/docker/daemon.json << 'EOF' | |
{ | |
"icc": false, | |
"userland-proxy": false, | |
"no-new-privileges": true, | |
"log-driver": "json-file", | |
"log-opts": { | |
"max-size": "10m", | |
"max-file": "3" | |
}, | |
"live-restore": true | |
} | |
EOF | |
systemctl restart docker | |
systemctl enable docker | |
fi | |
} | |
# Final security recommendations | |
final_recommendations() { | |
log "Security hardening completed! Please note the following:" | |
echo | |
echo -e "${BLUE}=== IMPORTANT SECURITY INFORMATION ===${NC}" | |
echo -e "${YELLOW}1. SSH Configuration:${NC}" | |
echo " - SSH port changed to: 2222" | |
echo " - Root login disabled" | |
echo " - Password authentication disabled" | |
echo " - SSH key location: /home/$USERNAME/.ssh/id_rsa" | |
echo | |
echo -e "${YELLOW}2. Connection Command:${NC}" | |
echo " ssh -p 2222 -i /home/$USERNAME/.ssh/id_rsa $USERNAME@YOUR_SERVER_IP" | |
echo | |
echo -e "${YELLOW}3. Firewall Status:${NC}" | |
ufw status | |
echo | |
echo -e "${YELLOW}4. Security Tools Installed:${NC}" | |
echo " - Fail2Ban (intrusion prevention)" | |
echo " - RKHunter (rootkit detection)" | |
echo " - AIDE (file integrity monitoring)" | |
echo " - Lynis (security audit tool)" | |
echo " - Unattended-upgrades (automatic security updates)" | |
echo | |
echo -e "${YELLOW}5. Regular Security Tasks:${NC}" | |
echo " - Run: rkhunter --check" | |
echo " - Run: lynis audit system" | |
echo " - Run: aide --check" | |
echo " - Check: /var/log/security-check.log" | |
echo | |
echo -e "${RED}6. BACKUP YOUR SSH PRIVATE KEY!${NC}" | |
echo " Download and securely store: /home/$USERNAME/.ssh/id_rsa" | |
echo | |
echo -e "${GREEN}7. Next Steps:${NC}" | |
echo " - Logout and test SSH connection with new settings" | |
echo " - Configure additional services as needed" | |
echo " - Set up monitoring and alerting" | |
echo " - Regular security audits" | |
echo | |
warn "REBOOT REQUIRED for all changes to take effect!" | |
} | |
# Main execution | |
main() { | |
log "Starting VPS Security Hardening Script..." | |
check_root | |
update_system | |
create_user | |
configure_ssh | |
configure_firewall | |
configure_fail2ban | |
system_hardening | |
install_security_tools | |
setup_log_monitoring | |
setup_docker_security | |
final_recommendations | |
log "Security hardening script completed successfully!" | |
read -p "Do you want to reboot now? (y/n): " -n 1 -r | |
echo | |
if [[ $REPLY =~ ^[Yy]$ ]]; then | |
log "Rebooting system..." | |
reboot | |
fi | |
} | |
# Run main function | |
main "$@" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# MTProxy Auto Deploy Script for Ubuntu 20.04 LTS | |
# Author: Security Engineer | |
# Description: Automated deployment of MTProxy for Telegram | |
set -e | |
# Colors for output | |
RED='\033[0;31m' | |
GREEN='\033[0;32m' | |
YELLOW='\033[1;33m' | |
BLUE='\033[0;34m' | |
NC='\033[0m' # No Color | |
# Configuration | |
MTPROXY_USER="mtproxy" | |
MTPROXY_DIR="/opt/mtproxy" | |
SERVICE_NAME="mtproxy" | |
PORT="8443" | |
MGMT_PORT="8888" | |
SSH_PORT="2222" | |
FAKE_TLS_DOMAIN="google.com" | |
# Logging function | |
log() { | |
echo -e "${GREEN}[INFO]${NC} $1" | |
} | |
warn() { | |
echo -e "${YELLOW}[WARN]${NC} $1" | |
} | |
error() { | |
echo -e "${RED}[ERROR]${NC} $1" | |
} | |
# Check if running as root | |
check_root() { | |
if [[ $EUID -ne 0 ]]; then | |
error "This script must be run as root" | |
exit 1 | |
fi | |
} | |
# Update system | |
update_system() { | |
log "Updating system packages..." | |
apt update && apt upgrade -y | |
apt install -y curl wget git build-essential libssl-dev zlib1g-dev | |
} | |
# Install dependencies | |
install_dependencies() { | |
log "Installing dependencies..." | |
apt install -y git curl build-essential libssl-dev zlib1g-dev libcurl4-openssl-dev | |
} | |
# Create user for MTProxy | |
create_user() { | |
log "Creating user for MTProxy..." | |
if ! id "$MTPROXY_USER" &>/dev/null; then | |
useradd -r -s /bin/false -d "$MTPROXY_DIR" "$MTPROXY_USER" | |
fi | |
} | |
# Download and compile MTProxy | |
install_mtproxy() { | |
log "Downloading and compiling MTProxy..." | |
# Create directory | |
mkdir -p "$MTPROXY_DIR" | |
cd "$MTPROXY_DIR" | |
# Clone repository | |
if [ ! -d "MTProxy" ]; then | |
git clone https://github.com/TelegramMessenger/MTProxy.git | |
fi | |
cd MTProxy | |
# Compile | |
make && cd objs/bin | |
# Copy binary to main directory | |
cp mtproto-proxy "$MTPROXY_DIR/" | |
# Set permissions | |
chown -R "$MTPROXY_USER:$MTPROXY_USER" "$MTPROXY_DIR" | |
chmod +x "$MTPROXY_DIR/mtproto-proxy" | |
} | |
# Generate secret with fake TLS | |
generate_secret() { | |
log "Generating secret with fake TLS for $FAKE_TLS_DOMAIN..." | |
# Generate base secret (16 bytes) | |
BASE_SECRET=$(head -c 16 /dev/urandom | xxd -ps) | |
# Create fake TLS secret (dd prefix + domain + base secret) | |
# dd prefix indicates fake TLS | |
DOMAIN_HEX=$(echo -n "$FAKE_TLS_DOMAIN" | xxd -ps) | |
SECRET="dd${DOMAIN_HEX}${BASE_SECRET}" | |
echo "$SECRET" > "$MTPROXY_DIR/secret.txt" | |
echo "$BASE_SECRET" > "$MTPROXY_DIR/base_secret.txt" | |
log "Fake TLS secret generated for domain: $FAKE_TLS_DOMAIN" | |
log "Secret: $SECRET" | |
} | |
# Download proxy secret from Telegram | |
download_proxy_secret() { | |
log "Downloading proxy secret from Telegram..." | |
curl -s https://core.telegram.org/getProxySecret -o "$MTPROXY_DIR/proxy-secret" | |
if [ ! -s "$MTPROXY_DIR/proxy-secret" ]; then | |
error "Failed to download proxy secret" | |
exit 1 | |
fi | |
} | |
# Download proxy config | |
download_proxy_config() { | |
log "Downloading proxy config from Telegram..." | |
curl -s https://core.telegram.org/getProxyConfig -o "$MTPROXY_DIR/proxy-multi.conf" | |
if [ ! -s "$MTPROXY_DIR/proxy-multi.conf" ]; then | |
error "Failed to download proxy config" | |
exit 1 | |
fi | |
} | |
# Create systemd service | |
create_service() { | |
log "Creating systemd service..." | |
cat > "/etc/systemd/system/${SERVICE_NAME}.service" << EOF | |
[Unit] | |
Description=MTProxy Telegram Proxy Server | |
After=network.target | |
[Service] | |
Type=simple | |
User=$MTPROXY_USER | |
Group=$MTPROXY_USER | |
WorkingDirectory=$MTPROXY_DIR | |
ExecStart=$MTPROXY_DIR/mtproto-proxy -u $MTPROXY_USER -p $MGMT_PORT -H $PORT -S $(cat $MTPROXY_DIR/secret.txt) --aes-pwd $MTPROXY_DIR/proxy-secret $MTPROXY_DIR/proxy-multi.conf -M 1 | |
Restart=on-failure | |
RestartSec=5 | |
StandardOutput=journal | |
StandardError=journal | |
# Security settings | |
NoNewPrivileges=true | |
ProtectSystem=strict | |
ProtectHome=true | |
ReadWritePaths=$MTPROXY_DIR | |
PrivateTmp=true | |
ProtectKernelTunables=true | |
ProtectKernelModules=true | |
ProtectControlGroups=true | |
[Install] | |
WantedBy=multi-user.target | |
EOF | |
# Reload systemd and enable service | |
systemctl daemon-reload | |
log "Service name $SERVICE_NAME" | |
# systemctl enable "$SERVICE_NAME" | |
} | |
configure_firewall() { | |
log "Configuring firewall..." | |
# Install ufw if not present | |
if ! command -v ufw &> /dev/null; then | |
apt install -y ufw | |
fi | |
# Configure UFW | |
# ufw --force reset | |
ufw default deny incoming | |
ufw default allow outgoing | |
# Allow SSH on custom port 2222 | |
ufw allow "$SSH_PORT"/tcp comment 'SSH' | |
# Allow MTProxy port | |
ufw allow "$PORT"/tcp comment 'MTProxy' | |
# Allow management port (restrict to local only for security) | |
# ufw allow from 127.0.0.1 to any port $MGMT_PORT | |
# Enable firewall | |
ufw --force enable | |
log "Firewall configured. Allowed ports: SSH ($SSH_PORT), MTProxy ($PORT)" | |
warn "Make sure SSH is configured to use port $SSH_PORT before disconnecting!" | |
} | |
# Create monitoring script | |
create_monitoring() { | |
log "Creating monitoring script..." | |
cat > "$MTPROXY_DIR/monitor.sh" << 'EOF' | |
#!/bin/bash | |
SERVICE_NAME="mtproxy" | |
LOG_FILE="/var/log/mtproxy-monitor.log" | |
check_service() { | |
if systemctl is-active --quiet $SERVICE_NAME; then | |
echo "$(date): MTProxy is running" >> $LOG_FILE | |
return 0 | |
else | |
echo "$(date): MTProxy is not running, attempting to restart..." >> $LOG_FILE | |
systemctl restart $SERVICE_NAME | |
sleep 5 | |
if systemctl is-active --quiet $SERVICE_NAME; then | |
echo "$(date): MTProxy restarted successfully" >> $LOG_FILE | |
else | |
echo "$(date): Failed to restart MTProxy" >> $LOG_FILE | |
fi | |
return 1 | |
fi | |
} | |
check_service | |
EOF | |
chmod +x "$MTPROXY_DIR/monitor.sh" | |
# Add to crontab for monitoring every 5 minutes | |
(crontab -l 2>/dev/null; echo "*/5 * * * * $MTPROXY_DIR/monitor.sh") | crontab - | |
} | |
# Create management script | |
create_management_script() { | |
log "Creating management script..." | |
cat > "$MTPROXY_DIR/manage.sh" << EOF | |
#!/bin/bash | |
SERVICE_NAME="$SERVICE_NAME" | |
MTPROXY_DIR="$MTPROXY_DIR" | |
case \$1 in | |
start) | |
systemctl start \$SERVICE_NAME | |
echo "MTProxy started" | |
;; | |
stop) | |
systemctl stop \$SERVICE_NAME | |
echo "MTProxy stopped" | |
;; | |
restart) | |
systemctl restart \$SERVICE_NAME | |
echo "MTProxy restarted" | |
;; | |
status) | |
systemctl status \$SERVICE_NAME | |
;; | |
logs) | |
journalctl -u \$SERVICE_NAME -f | |
;; | |
stats) | |
curl -s http://localhost:$MGMT_PORT/stats || echo "Stats not available" | |
;; | |
regenerate-secret) | |
systemctl stop \$SERVICE_NAME | |
# Generate new fake TLS secret | |
BASE_SECRET=\$(head -c 16 /dev/urandom | xxd -ps) | |
DOMAIN_HEX=\$(echo -n "$FAKE_TLS_DOMAIN" | xxd -ps) | |
NEW_SECRET="dd\${DOMAIN_HEX}\${BASE_SECRET}" | |
echo "\$NEW_SECRET" > \$MTPROXY_DIR/secret.txt | |
echo "\$BASE_SECRET" > \$MTPROXY_DIR/base_secret.txt | |
echo "New secret: \$NEW_SECRET" | |
systemctl start \$SERVICE_NAME | |
echo "Secret regenerated and service restarted" | |
;; | |
update-config) | |
curl -s https://core.telegram.org/getProxySecret -o \$MTPROXY_DIR/proxy-secret | |
curl -s https://core.telegram.org/getProxyConfig -o \$MTPROXY_DIR/proxy-multi.conf | |
systemctl restart \$SERVICE_NAME | |
echo "Configuration updated and service restarted" | |
;; | |
*) | |
echo "Usage: \$0 {start|stop|restart|status|logs|stats|regenerate-secret|update-config}" | |
exit 1 | |
;; | |
esac | |
EOF | |
chmod +x "$MTPROXY_DIR/manage.sh" | |
# Create symbolic link in /usr/local/bin for easy access | |
ln -sf "$MTPROXY_DIR/manage.sh" /usr/local/bin/mtproxy | |
} | |
# Create log rotation | |
setup_log_rotation() { | |
log "Setting up log rotation..." | |
cat > "/etc/logrotate.d/mtproxy" << EOF | |
/var/log/mtproxy-monitor.log { | |
daily | |
missingok | |
rotate 7 | |
compress | |
delaycompress | |
notifempty | |
copytruncate | |
} | |
EOF | |
} | |
# Display connection information | |
show_connection_info() { | |
SERVER_IP=$(curl -s ifconfig.me) | |
SECRET=$(cat "$MTPROXY_DIR/secret.txt") | |
echo "" | |
echo "==================================" | |
echo -e "${GREEN}MTProxy Installation Complete!${NC}" | |
echo "==================================" | |
echo "" | |
echo -e "${BLUE}Server IP:${NC} $SERVER_IP" | |
echo -e "${BLUE}Port:${NC} $PORT" | |
echo -e "${BLUE}Secret:${NC} $SECRET" | |
echo -e "${BLUE}Fake TLS Domain:${NC} $FAKE_TLS_DOMAIN" | |
echo -e "${BLUE}SSH Port:${NC} $SSH_PORT" | |
echo "" | |
echo -e "${YELLOW}Telegram Proxy Link (Fake TLS):${NC}" | |
echo "https://t.me/proxy?server=$SERVER_IP&port=$PORT&secret=$SECRET" | |
echo "" | |
echo -e "${YELLOW}Alternative tg:// Link:${NC}" | |
echo "tg://proxy?server=$SERVER_IP&port=$PORT&secret=$SECRET" | |
echo "" | |
echo -e "${YELLOW}Management Commands:${NC}" | |
echo " mtproxy start - Start service" | |
echo " mtproxy stop - Stop service" | |
echo " mtproxy restart - Restart service" | |
echo " mtproxy status - Check status" | |
echo " mtproxy logs - View logs" | |
echo " mtproxy stats - View statistics" | |
echo "" | |
echo -e "${RED}Important Security Notes:${NC}" | |
echo "- SSH has been configured to use port $SSH_PORT" | |
echo "- Root login and password authentication are disabled" | |
echo "- Make sure you can connect via SSH key before closing this session!" | |
echo "- Save the proxy link above!" | |
echo "" | |
} | |
# Main installation function | |
main() { | |
log "Starting MTProxy installation..." | |
check_root | |
update_system | |
install_dependencies | |
create_user | |
install_mtproxy | |
generate_secret | |
download_proxy_secret | |
download_proxy_config | |
create_service | |
configure_firewall | |
create_monitoring | |
create_management_script | |
setup_log_rotation | |
# Set proper ownership | |
chown -R "$MTPROXY_USER:$MTPROXY_USER" "$MTPROXY_DIR" | |
# Start service | |
systemctl start "$SERVICE_NAME" | |
# Wait a moment for service to start | |
sleep 3 | |
# Check if service is running | |
if systemctl is-active --quiet "$SERVICE_NAME"; then | |
show_connection_info | |
else | |
error "Service failed to start. Check logs with: journalctl -u $SERVICE_NAME" | |
exit 1 | |
fi | |
} | |
# Run main function | |
main "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
2. Các tính năng bảo mật được tự động cấu hình:
SSH Security:
Thay đổi port SSH từ 22 → 2222
Vô hiệu hóa đăng nhập root
Chỉ cho phép đăng nhập bằng SSH key
Giới hạn số lần thử đăng nhập
Tạo user mới với quyền sudo
Firewall (UFW):
Chặn tất cả kết nối đến (trừ SSH)
Cho phép tất cả kết nối đi
Cấu hình rules cơ bản
Fail2Ban:
Tự động ban IP có hành vi đáng ngờ
Giám sát SSH, HTTP/HTTPS
Cấu hình thời gian ban và retry
System Hardening:
Vô hiệu hóa các protocol mạng không cần thiết
Tối ưu kernel parameters
Bảo vệ chống IP spoofing, DDOS
Ẩn thông tin hệ thống nhạy cảm
3. Công cụ giám sát được cài đặt:
RKHunter: Phát hiện rootkit
AIDE: Giám sát tính toàn vẹn file
Lynis: Audit bảo mật tổng thể
Logwatch: Giám sát log
Unattended-upgrades: Cập nhật bảo mật tự động
Kiểm tra định kỳ: