Debian 11服务器安全配置:保护你的MySQL和Ollama大模型服务

云信安装大师
90
AI 质量分
11 5 月, 2025
4 分钟阅读
0 阅读

Debian 11服务器安全配置:保护你的MySQL和Ollama大模型服务

引言

在当今数据驱动的时代,服务器安全配置至关重要。特别是当你同时运行MySQL数据库和Ollama大模型服务时,确保系统安全就更加重要。本文将指导你完成Debian 11服务器的基础安全配置,重点保护MySQL数据库和Ollama大模型服务。

准备工作

在开始之前,请确保:
– 已安装干净的Debian 11系统
– 拥有root或sudo权限
– 基本的Linux命令行知识

1. 系统基础安全配置

1.1 更新系统和软件包

代码片段
# 更新软件包列表
sudo apt update

# 升级所有已安装的软件包
sudo apt upgrade -y

# 自动移除不再需要的依赖
sudo apt autoremove -y

原理说明:保持系统最新可以修补已知的安全漏洞。

1.2 创建专用用户(避免使用root)

代码片段
# 创建新用户(例如:secureadmin)
sudo adduser secureadmin

# 授予sudo权限
sudo usermod -aG sudo secureadmin

注意事项:创建强密码并妥善保管。

1.3 SSH安全加固

编辑SSH配置文件:

代码片段
sudo nano /etc/ssh/sshd_config

修改以下参数:

代码片段
Port 2222                   # 更改默认SSH端口
PermitRootLogin no          # 禁止root直接登录
PasswordAuthentication no   # 禁用密码认证(仅密钥)
MaxAuthTries 3              # 限制尝试次数

重启SSH服务:

代码片段
sudo systemctl restart sshd

实践经验:修改端口后,确保防火墙允许新端口通过。

2. MySQL安全配置

2.1 MySQL安装与基础配置

安装MySQL服务器:

代码片段
sudo apt install mysql-server -y

运行安全安装脚本:

代码片段
sudo mysql_secure_installation

按照提示完成以下设置:
– 设置root密码(如果尚未设置)
– 移除匿名用户
– 禁止远程root登录
– 移除测试数据库
– 重新加载权限表

2.2 MySQL高级安全配置

编辑MySQL配置文件:

代码片段
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

添加/修改以下内容:

代码片段
[mysqld]
bind-address = 127.0.0.1    # MySQL仅监听本地连接(如果不需要远程访问)
skip-name-resolve           # DNS反向解析可能带来安全隐患和性能问题

# SSL/TLS设置(如果启用)
ssl-ca=/etc/mysql/ca.pem    # CA证书路径示例,需替换为实际路径
ssl-cert=/etc/mysql/server-cert.pem 
ssl-key=/etc/mysql/server-key.pem 
require_secure_transport=ON # (可选)强制SSL连接

# Logging for security auditing(可选)
log_error = /var/log/mysql/mysql-error.log 
slow_query_log = ON 
slow_query_log_file = /var/log/mysql/mysql-slow.log 
long_query_time = -1        # Log all queries for security auditing (optional)
log_queries_not_using_indexes = ON 

重启MySQL服务:

代码片段
sudo systemctl restart mysql.service 

实践建议

  • 定期备份数据库:使用 mysqldump或专业工具进行定期备份。
  • 最小权限原则:为每个应用创建专用数据库用户并仅授予必要权限。
  • 监控日志文件:定期检查 /var/log/mysql/error.log中的异常活动。

3. Ollama大模型服务安全

3.1 Ollama安装

按照官方指南安装Ollama:

代码片段
curl https://ollama.ai/install.sh | sh 

3.2 Ollama基础安全

  • 使用专用用户运行Ollama
代码片段
sudo useradd -r -s /bin/false ollamauser 
sudo chown -R ollamauser:ollamauser /usr/share/ollama/ 
  • 限制网络访问

编辑systemd服务文件:

代码片段
sudo nano /etc/systemd/system/ollama.service.d/override.conf  

添加:

代码片段
[Service]  
User=ollamauser  
Group=ollamauser  
PrivateTmp=true  
ProtectSystem=full  
NoNewPrivileges=true  
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6  
RestrictNamespaces=true  
CapabilityBoundingSet=CAP_NET_BIND_SERVICE CAP_SETUID CAP_SETGID  
DevicePolicy=closed  
ProtectKernelTunables=true  
ProtectKernelModules=true  
ProtectControlGroups=true  

Environment="OLLAMA_HOST=127.0.0.1:11434"   # Only listen locally by default   
Environment="OLLAMA_ORIGINS=https://yourdomain.com"   # Restrict CORS if needed   

重载并重启:

代码片段
sudo systemctl daemon-reload && sudo systemctl restart ollama.service   

3.3 Ollama与Nginx反向代理(可选)

如果需要外部访问,建议通过Nginx反向代理并添加HTTPS:

代码片段
server {     
    listen       443 ssl;     
    server_name yourdomain.com;      

    ssl_certificate     /path/to/cert.pem;      
    ssl_certificate_key /path/to/key.pem;      

    location / {         
        proxy_pass http://127.0.0.1:11434;         
        proxy_set_header Host $host;         
        proxy_set_header X-Real-IP $remote_addr;         
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;         
        proxy_set_header X-Forwarded-Proto $scheme;      

        auth_basic "Restricted Access";   # Optional basic auth        
        auth_basic_user_file /etc/nginx/.htpasswd;     
    }     
}   

4. 防火墙与入侵检测

4. 1 UFW防火墙设置

启用并配置UFW防火墙:

代码片段
sudo ufw enable    
sudo ufw default deny incoming    
sudo ufw default allow outgoing    

# Allow SSH (on custom port)    
sudo ufw allow from your_ip to any port your_ssh_port    

# Allow HTTP/HTTPS if needed    
sudo ufw allow http    
sudo ufw allow https    

# Optionally allow specific IPs to access Ollama port    
# sudo ufw allow from trusted_ip to any port ollama_port proto tcp    

验证规则:

代码片段
sudo ufw status numbered    

4. 2 Fail2Ban安装配置

安装Fail2Ban防止暴力破解:

代码片段
sudo apt install fail2ban -y    
cp /etc/fail2ban/jail.{conf,local}    
nano /etc/fail2ban/jail.local    

添加针对SSH和自定义端口的保护:

代码片段
[sshd]    
enabled = true    
port = your_custom_ssh_port    
filter = sshd    
logpath = %(sshd_log)s    
maxretry =3    

[nginx-botsearch]   # If using Nginx     
enabled =true     
port=http,https     
filter=nginx-botsearch     
logpath=/var/log/nginx/*error.log     
maxretry=5     
bantime=3600     
findtime=3600     

[mysql-auth]       # Protect MySQL if exposed     
enabled=true     
port=3306     
filter=mysql-auth     
logpath=/var/log/mysql/*error.log     
maxretry=3     
bantime=86400     

[ollama-auth]      # Custom jail for Ollama if exposed      
enabled=true      
port=11434      
filter=ollama-auth      
logpath=/var/log/ollama.log      
maxretry=5      
bantime=86400      
findtime=3600       

重启Fail2Ban:

代码片段
systemctl restart fail2ban.service   
systemctl enable fail2ban.service   
fail2ban-client status   # Check active jails   

5. 定期维护与监控

  • ### 5. 1自动化更新
    设置无人值守更新:
代码片段
apt install unattended-upgrades apt-listchanges -y   
dpkg-reconfigure --priority-low unattended-upgrades   
nano /etc/apt/apt.conf.d/50unattended-upgrades   

// Ensure these lines are present and uncommented:   
"origin=Dabian,codename=${distro_codename},label=Dabian-Security";   
"origin=Dabian,codename=${distro_codename}-security,label=Dabian-Security";   

// Also consider adding:   
Unattended-Upgrade::Remove-Unused-Dependencies "true";   
Unattended-Upgrade::Automatic-Reboot "true";   
Unattended-Upgrade::Automatic-Reboot-Time "02:00";   

systemctl enable unattended-upgrades && systemctl start unattended-upgrades   

// Verify with:   
tail -f /var/log/unattended-upgrades/unattended-upgrades.log   

// Check configuration with:   
unattended-upgrades --dry-run --debug   
  • ### * 5. * * * * 日志轮转与监控

确保日志不会无限增长:

代码片段
// Install logrotate if not present:  

apt install logrotate - y  

// Example config for MySQL logs in `/ etc/logrotate.d/mysql-server`:  

/ var/log/mysql/* log {  

daily  

rotate7  

missingok  

create640 mysql adm  

compress  

delaycompress  

notifempty  

sharedscripts  

postrotate  

test-x / usr/bin/mysqladmin || exit0    

// If mysqld is running, send flush-logs command    

MYADMIN="/ usr/bin/mysqladmin --defaults-file=/ etc/mysql/debian.cnf"    

if [ -z "$($MYADMIN ping2 > & amp;/dev/null)" ]; then    

$MYADMIN flush-logs    

fi    

endscript <br>
 

考虑使用监控工具如Prometheus+Grafana或Netdata进行实时监控。

## 6. 总结回顾**

通过以上步骤,我们完成了Debian11服务器的基本加固,特别关注了MySQL和Ollama服务的安全。关键点包括:

  • 系统层面 :最小特权原则、及时更新、防火墙配置、入侵防护(Fail2Ban)

  • MySQL :本地绑定、SSL加密、审计日志、专用账户

  • Ollama :专用用户运行、网络隔离、反向代理保护

  • 运维最佳实践 :自动化更新、日志管理、持续监控

记住,安全性是一个持续的过程而非一次性任务。建议定期审计服务器状态并关注相关CVE公告。对于生产环境,还应考虑实施更严格的SELinux策略、网络隔离和备份方案。

原创 高质量