Basic Database Security in MySQL 🔒🔐

Basic Database Security in MySQL 🔒🔐
Database security is crucial for protecting sensitive data from unauthorized access, data breaches, and cyber threats.
1️⃣ Why is Database Security Important? 🤔
Prevents unauthorized access to confidential information.
Protects against SQL injection attacks and hacking attempts.
Ensures data integrity by preventing accidental or malicious modifications.
Maintains system performance by avoiding data leaks or corruption.
2️⃣ User Authentication & Access Control 👤🔐
Properly managing users and their privileges ensures only authorized users access critical data.
✅ Create a Secure User
CREATE USER 'secure_user'@'localhost' IDENTIFIED BY 'StrongP@ssword!';
GRANT SELECT, INSERT, UPDATE ON my_database.* TO 'secure_user'@'localhost';
Avoid using GRANT ALL PRIVILEGES unless necessary.
✅ Revoke Unnecessary Privileges
REVOKE DELETE ON my_database.* FROM 'secure_user'@'localhost';
✅ Check User Privileges
SHOW GRANTS FOR 'secure_user'@'localhost';
3️⃣ Protecting Against SQL Injection Attacks 🚨
SQL injection is a common hacking method where attackers insert malicious SQL code.
❌ Bad Practice (Vulnerable to SQL Injection)
$query = "SELECT * FROM users WHERE username = '$user' AND password = '$pass'";
✅ Safe Practice: Use Prepared Statements
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->execute([$user, $pass]);
🔹 Why? This prevents attackers from injecting malicious SQL commands.
4️⃣ Secure Database Configuration ⚙️
✅ Disable Remote Root Access (For Security)
Edit MySQL configuration file (my.cnf or my.ini) and set:
bind-address = 127.0.0.1
This prevents external unauthorized access.
✅ Change the Default Root Password
ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewS3cur3P@ss!';
✅ Remove Anonymous Users
DELETE FROM mysql.user WHERE User='';
FLUSH PRIVILEGES;
Prevents unauthorized access by anonymous users.
5️⃣ Backup & Recovery 💾
Regular backups protect against data loss due to hacking, system failure, or accidental deletion.
✅ Create a Backup
mysqldump -u root -p my_database > backup.sql
✅ Restore a Backup
mysql -u root -p my_database < backup.sql
🎯 Summary: Best Security Practices
Security Measure Command/Action
Use Strong Passwords CREATE USER 'user'@'localhost' IDENTIFIED BY 'StrongP@ssword!';
Limit User Privileges GRANT SELECT, INSERT ON db.* TO 'user'@'localhost';
Prevent SQL Injection Use prepared statements instead of direct SQL queries.
Disable Remote Root Login Set bind-address = 127.0.0.1 in MySQL config.
Remove Anonymous Users DELETE FROM mysql.user WHERE User='';
Regular Backups mysqldump -u root -p my_database > backup.sqlDate: 2025-03-29 00:00:00.000000