MariaDB需以专用低权限用户(通常为mysql)运行,避免越权访问系统资源。通过以下命令验证运行用户:
ps -ef | egrep "^mysql.*$"
正常输出应显示进程所有者为mysql。
/var/lib/mysql):存储数据库文件,需归属mysql:mysql,权限设为750(所有者可读写执行,组可读执行,其他用户无权限):sudo chown -R mysql:mysql /var/lib/mysql
sudo chmod 750 /var/lib/mysql
/etc/mysql/my.cnf或/etc/my.cnf):仅root可写,其他用户可读:sudo chown root:root /etc/mysql/my.cnf
sudo chmod 644 /etc/mysql/my.cnf
/var/log/mysql/mysql.log):归属mysql:mysql,权限640:sudo chown mysql:mysql /var/log/mysql/mysql.log
sudo chmod 640 /var/log/mysql/mysql.log
DELETE FROM mysql.user WHERE User='';
FLUSH PRIVILEGES;
ALTER USER 'root'@'%' DISABLE;
DROP DATABASE IF EXISTS test;
若系统启用SELinux,需调整策略允许MariaDB正常运行:
# 允许MariaDB访问网络端口(默认3306)
sudo setsebool -P mysql_connect_any 1
# 设置数据目录的安全上下文
sudo chcon -Rv --type=mariadb_db_t /var/lib/mysql
开放MariaDB默认端口(3306),仅允许可信IP访问:
sudo firewall-cmd --add-port=3306/tcp --permanent
sudo firewall-cmd --reload
使用root用户登录,输入密码:
mysql -u root -p
localhost表示本地连接,%表示任意主机):CREATE USER 'username'@'localhost' IDENTIFIED BY 'StrongPassword123!';
ALTER USER 'username'@'localhost' IDENTIFIED BY 'NewStrongPassword456!';
DROP USER 'username'@'localhost';
GRANT ALL PRIVILEGES ON database_name.* TO 'username'@'localhost';
GRANT SELECT, INSERT, UPDATE ON database_name.table_name TO 'username'@'localhost';
192.168.1.100):GRANT ALL PRIVILEGES ON database_name.* TO 'username'@'192.168.1.100';
执行权限变更后,需刷新使设置立即生效:
FLUSH PRIVILEGES;
移除用户的特定权限或全部权限:
REVOKE INSERT, UPDATE ON database_name.table_name FROM 'username'@'localhost';
REVOKE ALL PRIVILEGES ON database_name.* FROM 'username'@'localhost';
FLUSH PRIVILEGES;
SHOW GRANTS FOR 'username'@'localhost';
SELECT User, Host FROM mysql.user;
SET GLOBAL require_secure_transport = ON;