Securing Database Connections and Following Least-Privilege Principles in MySQL
Course: MySQL Training
Topic: Securing Database Connections and Following Least-Privilege Principles
Course Link: MySQL Training Course – JustAcademy
Demo Link: Register for a Course Demo
1. Introduction to Database Connection Security
Database connection security is the process of protecting communication between database clients, applications, administrators, and the MySQL server. A database connection allows an application or user to authenticate, submit SQL statements, and retrieve or modify information.
If connections are not configured securely, attackers may intercept network traffic, exploit weak authentication, connect from unauthorized hosts, or gain access through accounts with excessive permissions. These risks become particularly important when a MySQL server stores confidential information such as customer records, employee details, financial transactions, and application data.
MySQL provides several mechanisms to protect database connections, including TLS encryption, certificate verification, account-level connection requirements, host restrictions, authentication controls, and privilege management.
In addition to securing connections, administrators should follow the principle of least privilege. This principle means that every user or application receives only the permissions required to perform its assigned tasks.
Example Scenario
Suppose an e-commerce application connects to a MySQL database containing customer details and orders. The application needs to read products, create orders, and update order statuses. It does not need permission to drop databases, create administrative accounts, or access unrelated employee records.
A secure configuration should encrypt remote connections, restrict which hosts can connect, use a dedicated application account, and grant only the required database privileges.
2. Learning Objectives
After completing these notes, you will be able to:
- Understand database connection security in MySQL.
- Explain the purpose of TLS-encrypted connections.
- Configure MySQL to require secure transport.
- Understand client-side SSL modes and certificate verification.
- Restrict accounts to specific hosts and encrypted connections.
- Understand the principle of least privilege.
- Create users with limited database permissions.
- Use
GRANT, REVOKE, and SHOW GRANTS for access control.
- Use roles to manage permissions efficiently.
- Identify excessive privileges and common security mistakes.
- Apply connection-security and access-control best practices.
- Build and test a secure MySQL application-access configuration.
3. What Is Database Connection Security?
Database connection security protects the communication channel and the process through which a client connects to MySQL. It covers the connection's confidentiality, integrity, authentication, and authorization.
Major Components
| Component |
Description |
Security Purpose |
| Authentication |
Verifies the identity of a user or application. |
Prevents unauthorized account access. |
| Encryption |
Protects network traffic using TLS. |
Reduces the risk of intercepted information being read. |
| Certificate verification |
Checks the server's certificate and, when configured, its hostname. |
Helps prevent impersonation and man-in-the-middle attacks. |
| Host restrictions |
Limits where an account can connect from. |
Reduces unnecessary remote access. |
| Authorization |
Controls the SQL operations an authenticated account can perform. |
Prevents unauthorized database operations. |
| Network filtering |
Uses firewalls and network rules to limit connectivity. |
Reduces exposure to untrusted networks. |
| Monitoring |
Records or reviews authentication and access activity. |
Helps identify suspicious activity. |
4. Understanding the MySQL Connection Process
When a client connects to MySQL, the server verifies the connection and authenticates the account. After authentication, MySQL checks the account's privileges when the client requests database operations.
Connection Security Workflow
- Client initiates a connection: An application, command-line client, or administration tool contacts the MySQL server.
- Transport is established: The client and server use a supported transport, such as TCP/IP or a local socket.
- Encryption is negotiated: If TLS is used, the client and server establish an encrypted connection.
- Server identity is verified: When certificate verification is enabled, the client checks the certificate and potentially the server hostname.
- User authentication occurs: MySQL verifies the supplied account credentials using the configured authentication method.
- Connection requirements are checked: MySQL enforces relevant account and server requirements.
- SQL statements are authorized: MySQL checks whether the account has permission to perform requested operations.
- Results are returned: Authorized operations execute, and results are sent over the connection.
Encryption and authentication serve different purposes. Encryption protects communication, while authentication verifies identity. Authorization determines what the authenticated account is permitted to do.
5. Understanding TLS Encryption in MySQL
TLS stands for Transport Layer Security. It protects data transmitted between a MySQL client and server by encrypting network communication and helping ensure that transmitted information has not been altered unnoticed.
Without encryption, network traffic may be exposed to interception in an insecure environment. Although MySQL's authentication protocol does not simply send the account password as cleartext, other transmitted information can still be sensitive. TLS helps protect the complete communication channel.
Benefits of TLS
- Protects SQL statements and returned data during network transmission.
- Reduces the risk of network eavesdropping.
- Helps protect sensitive information transmitted between applications and databases.
- Supports server identity verification through certificate validation.
- Helps meet organizational and regulatory security requirements.
Example of an Encrypted Connection
A reporting application connects to a remote MySQL server over TCP/IP using TLS. When properly configured, the SQL statements and results are encrypted while traveling across the network.
Important: TLS does not automatically protect data stored on disk, prevent SQL injection, or stop an authorized account from misusing its privileges. Those risks require additional controls.
6. Checking MySQL SSL and TLS Configuration
Administrators should inspect the server's encryption configuration before requiring encrypted connections.
Check Whether Secure Transport Is Required
SHOW VARIABLES LIKE 'require_secure_transport';
If the value is ON, MySQL requires supported secure transport for connections. If it is OFF, the server does not enforce that global requirement.
Inspect TLS-Related Server Variables
SHOW VARIABLES LIKE 'ssl%';
SHOW VARIABLES LIKE 'tls_version';
These commands help inspect SSL/TLS configuration, including certificate paths, keys, and supported protocol versions, depending on the MySQL release and configuration.
Check the Current Session's Encryption Status
SHOW SESSION STATUS LIKE 'Ssl_cipher';
SHOW SESSION STATUS LIKE 'Ssl_version';
A non-empty cipher value generally indicates that the current session is using an encrypted connection. Check the session associated with the connection being tested, because a different administrative session may have different connection properties.
7. Requiring Secure Transport on the MySQL Server
MySQL provides the require_secure_transport system variable to require clients to use supported secure transport methods. This is useful when an organization wants to prevent insecure remote TCP/IP connections.
Enable Secure Transport for the Running Server and Persist the Setting
SET PERSIST require_secure_transport = ON;
This command changes the global setting and persists it for subsequent server restarts, provided the MySQL version supports the variable and the executing account has the required privileges.
Configure It in the MySQL Configuration File
[mysqld]
require_secure_transport=ON
The configuration file is commonly named my.cnf on Unix-like systems or my.ini on Windows, although the exact location depends on the installation.
Important Considerations
- Verify that TLS certificates and keys are configured correctly before enforcing secure transport.
- Test application clients to confirm that they can connect securely.
- Plan for legacy clients that do not support the required TLS configuration.
- Remember that local Unix socket and Windows shared-memory connections can qualify as secure transports under MySQL's rules without using network TLS.
- Review operational requirements before applying the setting to a production server.
8. Understanding MySQL Client SSL Modes
MySQL client programs provide the --ssl-mode option to control encrypted connection behavior. Selecting the appropriate mode helps ensure that applications do not silently fall back to an insecure connection.
| SSL Mode |
Behavior |
Typical Use |
DISABLED |
Uses an unencrypted connection. |
Generally avoid for remote connections carrying sensitive data. |
PREFERRED |
Attempts encryption but may fall back to an unencrypted connection. |
Compatibility scenarios where fallback is accepted. |
REQUIRED |
Requires encryption but does not by itself verify the server certificate's identity. |
Ensuring that the connection is encrypted. |
VERIFY_CA |
Requires encryption and validates the server certificate against a trusted CA. |
Connections requiring certificate verification. |
VERIFY_IDENTITY |
Requires encryption, validates the certificate chain, and verifies the server hostname against the certificate identity. |
Strong protection against server impersonation when correctly configured. |
Example: Require Encryption
mysql --host=db.example.com \
--user=app_user \
--ssl-mode=REQUIRED
Example: Verify the Certificate and Server Identity
mysql --host=db.example.com \
--user=app_user \
--ssl-mode=VERIFY_IDENTITY \
--ssl-ca=/path/to/ca.pem
Use the actual database hostname and trusted CA certificate path for your environment. The hostname must match the identity in the server certificate for VERIFY_IDENTITY to succeed.
Recommended approach: For remote connections in security-sensitive environments, use VERIFY_IDENTITY when the certificate infrastructure and client support it. Do not assume that REQUIRED verifies the server's identity.
9. Requiring Encrypted Connections for Individual Accounts
In addition to server-wide secure transport settings, MySQL can enforce encryption requirements for specific accounts. This is useful when particular users must always connect over an encrypted channel.
Create an Account That Requires SSL
CREATE USER 'secure_app'@'192.168.1.25'
IDENTIFIED BY 'Replace-With-A-Strong-Unique-Password'
REQUIRE SSL;
This creates an account that requires an SSL/TLS-encrypted connection. Replace the placeholder password securely and use the actual permitted client host.
Apply an SSL Requirement to an Existing Account
ALTER USER 'secure_app'@'192.168.1.25'
REQUIRE SSL;
Require a Valid Client Certificate
ALTER USER 'secure_app'@'192.168.1.25'
REQUIRE X509;
The REQUIRE X509 clause requires the client to present a valid certificate according to MySQL's certificate requirements. More specific requirements can be configured using supported options such as ISSUER and SUBJECT.
Certificate requirements must be configured carefully. Client certificates, trusted certificate authorities, server settings, and application client options must all be compatible.
10. Restricting Database Connections by Host
MySQL identifies accounts using a username and host combination. Restricting the host component helps limit where an account can connect from.
Account Format
'username'@'host'
Example: Local-Only Account
CREATE USER 'local_app'@'localhost'
IDENTIFIED BY 'Replace-With-A-Strong-Unique-Password';
This account is intended for connections matching the localhost host entry.
Example: Restrict an Account to a Specific Client Host
CREATE USER 'remote_app'@'192.168.1.25'
IDENTIFIED BY 'Replace-With-A-Strong-Unique-Password'
REQUIRE SSL;
This configuration restricts the account to the specified host entry and requires an encrypted connection.
Avoid Unnecessarily Broad Host Patterns
-- Avoid using a broad host pattern unless it is justified.
CREATE USER 'app_user'@'%'
IDENTIFIED BY 'Replace-With-A-Strong-Unique-Password';
The percent sign can match connections from many hosts, subject to MySQL's account-matching rules. Use the narrowest practical host restriction, and reinforce it with firewall rules, network segmentation, and secure authentication.
11. What Is the Principle of Least Privilege?
The principle of least privilege is a security practice in which each user, application, service, or administrator receives only the permissions necessary to perform its assigned responsibilities.
For example, a reporting user may need to read tables but should not automatically be allowed to insert records, change table structures, create users, or drop databases.
Key Principles
- Grant only required privileges.
- Use separate accounts for separate responsibilities.
- Avoid unnecessary global privileges.
- Restrict access to specific databases and tables.
- Review permissions regularly.
- Revoke privileges when they are no longer needed.
- Use dedicated service accounts for applications.
- Keep administrative accounts separate from routine application accounts.
Benefits of Least Privilege
| Benefit |
Explanation |
| Reduced attack impact |
A compromised account has fewer permissions available to misuse. |
| Improved data protection |
Users cannot access unrelated data when permissions are properly restricted. |
| Reduced accidental damage |
Users are less likely to delete or modify information outside their responsibilities. |
| Better accountability |
Separate accounts make it easier to associate actions with specific services or users. |
| Simpler audits |
Permissions can be reviewed against each account's intended purpose. |
12. Understanding MySQL Privilege Levels
MySQL supports privileges at different levels. Choosing the narrowest appropriate level is an important part of least-privilege design.
| Privilege Level |
Example |
Scope |
| Global |
*.* |
Server-wide privileges across applicable databases and objects. |
| Database |
company_db.* |
Applicable objects within one database. |
| Table |
company_db.orders |
A specific table. |
| Column |
company_db.employees (department) |
A specific column for supported column-level privileges. |
| Routine |
PROCEDURE company_db.create_order |
Privileges associated with a specific stored procedure. |
Why Global Privileges Need Special Care
Global privileges apply broadly and may provide access to many databases. Granting a global privilege to a routine application account can create unnecessary risk.
-- Broad access: avoid unless explicitly required.
GRANT ALL PRIVILEGES ON *.*
TO 'app_user'@'localhost';
Instead, grant the specific privileges required at the appropriate database or table level.
13. Creating a Least-Privilege MySQL User
Creating a dedicated account for each application or responsibility helps separate access rights and improves accountability.
Step 1: Create a Dedicated User
CREATE USER 'report_user'@'localhost'
IDENTIFIED BY 'Replace-With-A-Strong-Unique-Password';
Step 2: Grant Read-Only Access
GRANT SELECT ON company_db.*
TO 'report_user'@'localhost';
The account can read applicable objects in the company_db database but does not receive database-level write privileges from this grant.
Step 3: Inspect the Assigned Permissions
SHOW GRANTS FOR 'report_user'@'localhost';
Step 4: Test the Account
Connect using the reporting account in a controlled environment. Verify that permitted read queries succeed and that insert, update, and delete operations are denied unless another grant or active role provides those privileges.
Important: The effective permissions of an account can come from multiple grants and active roles. Always inspect the complete access configuration before concluding that a user is read-only.
14. Granting Only Required Table Permissions
Some applications need access to only a few tables rather than every table in a database. Table-level privileges allow administrators to enforce more precise access restrictions.
Example: Orders Application
CREATE USER 'orders_app'@'localhost'
IDENTIFIED BY 'Replace-With-A-Strong-Unique-Password';
GRANT SELECT, INSERT, UPDATE
ON company_db.orders
TO 'orders_app'@'localhost';
This grant allows the account to read, insert, and update records in the specified table. It does not grant the account DELETE permission on that table through this statement.
Example: Read-Only Product Catalogue
CREATE USER 'catalog_reader'@'localhost'
IDENTIFIED BY 'Replace-With-A-Strong-Unique-Password';
GRANT SELECT
ON company_db.products
TO 'catalog_reader'@'localhost';
This account receives read access to the specified products table through the grant shown.
Benefits of Table-Level Access
- Limits access to relevant business data.
- Reduces the chance of accidental changes to unrelated tables.
- Supports separation of responsibilities between application components.
- Makes access reviews more precise.
15. Revoking Unnecessary Privileges
Least privilege is not a one-time configuration. Permissions should be reviewed and reduced when users change roles, applications are retired, or security requirements change.
MySQL provides the REVOKE statement to remove specified privileges.
Example: Remove Write Access
REVOKE INSERT, UPDATE, DELETE
ON company_db.orders
FROM 'orders_app'@'localhost';
This removes the specified table-level privileges from the account. If the user receives the same privileges through another grant or role, access may remain available.
Example: Verify Remaining Grants
SHOW GRANTS FOR 'orders_app'@'localhost';
Recommended Access Review
- Identify the account's purpose and owner.
- Inspect its current grants and assigned roles.
- Compare permissions with the account's actual responsibilities.
- Revoke unnecessary privileges.
- Inspect the resulting grants again.
- Test expected permitted and denied operations.
- Record the change and approval according to organizational procedures.
16. Using MySQL Roles for Permission Management
A role is a named collection of privileges that can be granted to users or other roles. Roles help administrators manage permissions consistently across users with similar responsibilities.
Create a Read-Only Role
CREATE ROLE 'reporting_role';
GRANT SELECT ON company_db.*
TO 'reporting_role';
Assign the Role to a User
GRANT 'reporting_role'
TO 'report_user'@'localhost';
Set a Default Role
SET DEFAULT ROLE 'reporting_role'
TO 'report_user'@'localhost';
Setting a default role causes the specified role to be activated by default when the account connects, subject to MySQL's role behavior and configuration.
Inspect Role Assignments
SHOW GRANTS FOR 'report_user'@'localhost';
Revoke a Role
REVOKE 'reporting_role'
FROM 'report_user'@'localhost';
Roles simplify access administration, but they must be reviewed carefully. A user may have multiple roles, and removing one role does not necessarily remove equivalent permissions supplied by another role or direct grants.
17. Separating Administrative and Application Accounts
Administrative accounts can perform sensitive operations such as creating users, changing server configuration, managing privileges, and modifying database structures. Application accounts generally need a much smaller set of permissions.
Recommended Account Separation
| Account Type |
Typical Responsibilities |
Access Strategy |
| Database administrator |
Manage server settings, users, backups, and database maintenance. |
Use carefully controlled administrative privileges. |
| Application account |
Read and modify data required by an application. |
Grant only necessary table or database privileges. |
| Reporting account |
Run queries and generate reports. |
Prefer read-only access to required data. |
| Migration account |
Perform approved schema changes during deployments. |
Grant schema-changing privileges only when required and remove them afterward if appropriate. |
| Backup account |
Perform approved backup operations. |
Grant the specific privileges needed by the backup mechanism. |
Do not configure an application to use a highly privileged administrative account simply because it is convenient. A compromised application could expose every privilege assigned to that account.
18. Protecting Against SQL Injection
SQL injection occurs when untrusted input is incorporated into SQL statements in a way that changes the intended query structure. Attackers may use this weakness to read, modify, or delete data using the application's database connection.
Prepared statements and parameterized queries are primary defenses against SQL injection. Least-privilege permissions provide an additional layer of protection by limiting what a compromised query or application account can do.
Unsafe Conceptual Example
-- Unsafe pattern: concatenating untrusted input
-- into an SQL statement can permit SQL injection.
Safer PHP Example Using PDO
<?php
$pdo = new PDO(
'mysql:host=db.example.com;dbname=company_db;charset=utf8mb4',
$dbUser,
$dbPassword,
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false
]
);
$stmt = $pdo->prepare(
'SELECT order_id, status
FROM orders
WHERE customer_id = :customer_id'
);
$stmt->execute([
'customer_id' => $customerId
]);
$orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
This example uses a prepared statement to separate query structure from input values. The variables $dbUser, $dbPassword, and $customerId must be supplied securely by the application. Parameterized queries do not replace authorization checks, secure connection configuration, or least-privilege database permissions.
19. Network Security and Firewall Restrictions
A secure MySQL account is only one part of database protection. Network controls should limit which systems can reach the MySQL service.
Recommended Network Controls
- Allow connections only from trusted application servers and administration hosts.
- Restrict access to the MySQL port using firewall rules.
- Avoid exposing the database directly to the public internet unless there is a justified and carefully secured architecture.
- Use private networks or approved secure connectivity for application-to-database traffic.
- Restrict remote administrative access to authorized locations.
- Review network rules after deployments and infrastructure changes.
- Monitor connection attempts and investigate unexpected sources.
Important Principle
Firewall restrictions and MySQL host restrictions complement one another. A firewall limits network reachability, while MySQL account definitions determine which accounts can authenticate from matching hosts.
20. Verifying Encrypted Connections from the Client
Administrators should confirm that clients actually establish encrypted connections rather than assuming encryption is active because the server supports TLS.
Using the MySQL Client
mysql --host=db.example.com \
--user=report_user \
--ssl-mode=VERIFY_IDENTITY \
--ssl-ca=/path/to/ca.pem
After connecting, run:
SHOW SESSION STATUS LIKE 'Ssl_cipher';
SHOW SESSION STATUS LIKE 'Ssl_version';
Check that the cipher value is non-empty and that the session uses an expected TLS version. Certificate verification also depends on the client's SSL mode and the trustworthiness of the certificate configuration.
What Should Be Verified?
- The client connects to the expected server hostname.
- The connection uses the required TLS mode.
- The certificate is trusted and valid.
- The server identity matches the certificate when identity verification is required.
- The account's privileges match its intended purpose.
- The application handles connection failures securely without silently switching to an insecure configuration.
21. Common Security Mistakes
| Mistake |
Risk |
Recommended Improvement |
| Using an administrative account in an application |
A compromised application may gain excessive database control. |
Create a dedicated application account with limited permissions. |
Granting privileges on *.* unnecessarily |
Access may extend to many databases and objects. |
Grant only the required privileges at the narrowest suitable level. |
| Allowing every host to connect |
Increases the number of possible connection sources. |
Use specific host restrictions and firewall rules. |
| Accepting unencrypted remote connections |
Network traffic may be exposed. |
Require secure transport and configure client TLS correctly. |
| Using encryption without server identity verification |
A client may be vulnerable to connecting to an impersonated server. |
Use certificate verification, preferably hostname verification where appropriate. |
| Sharing one database account among many applications |
Makes accountability and permission separation difficult. |
Use separate accounts for distinct applications and services. |
| Leaving old accounts active |
Unused accounts may become unauthorized access paths. |
Review, lock, or remove accounts according to policy. |
| Ignoring assigned roles |
Users may retain permissions through other roles. |
Inspect direct grants, role assignments, and active roles. |
| Building SQL queries through string concatenation |
May introduce SQL injection vulnerabilities. |
Use prepared statements and validate application inputs. |
| Storing credentials in source code |
Secrets may leak through repositories or deployment artifacts. |
Use an approved secret-management solution. |
22. Practical Example: Secure an Application Database Account
Scenario: An online ordering application needs to read and update order records in the company_db database. The company wants to restrict connection access, require encryption, and apply least privilege.
Step 1: Create a Restricted Account
CREATE USER 'orders_app'@'192.168.1.25'
IDENTIFIED BY 'Replace-With-A-Strong-Unique-Password'
REQUIRE SSL;
This account is restricted to the specified host entry and requires an encrypted connection. Use the actual application server address and a securely managed unique password.
Step 2: Grant Only the Required Permissions
GRANT SELECT, INSERT, UPDATE
ON company_db.orders
TO 'orders_app'@'192.168.1.25';
The application receives read, insert, and update privileges on the specified table through this grant. It does not receive the DELETE privilege through this statement.
Step 3: Require Secure Transport Server-Wide Where Appropriate
SET PERSIST require_secure_transport = ON;
Apply this setting only after verifying that all required clients support secure connections and that the server's TLS configuration is correct. It affects connections beyond the example application account.
Step 4: Inspect the Account Definition and Grants
SHOW CREATE USER 'orders_app'@'192.168.1.25';
SHOW GRANTS FOR 'orders_app'@'192.168.1.25';
Step 5: Connect Using Certificate Verification
mysql --host=db.example.com \
--user=orders_app \
--ssl-mode=VERIFY_IDENTITY \
--ssl-ca=/path/to/ca.pem
The hostname, CA certificate, client network location, and account configuration must match the real environment.
Step 6: Test Expected Operations
- Confirm that the application can read the required order records.
- Confirm that it can insert orders when required.
- Confirm that it can update permitted order records.
- Confirm that unauthorized operations are denied unless another grant or role provides access.
- Confirm that a connection without the required encryption is rejected.
- Verify that the TLS certificate and server identity are checked by the client.
Expected outcome: The account is restricted by host, requires encrypted transport, and has only the specified table privileges from the grant shown. Its effective permissions must still be reviewed for any additional grants or roles.
23. Hands-On Exercises
- Create a test MySQL account that can connect from a specific host.
- Create a read-only account with
SELECT permission on a test database.
- Use
SHOW GRANTS to inspect the account's permissions.
- Grant
SELECT, INSERT, and UPDATE on one table to an application account.
- Verify that the account cannot perform operations for which it has no effective privilege.
- Configure an account to require SSL and test the connection with a compatible client.
- Inspect the server's
require_secure_transport setting.
- Connect using
--ssl-mode=VERIFY_IDENTITY with a valid trusted CA certificate.
- Create a role for reporting users and assign it to a test account.
- Revoke a privilege or role and verify the resulting permissions.
- Review an example application query and replace unsafe string concatenation with a prepared statement.
- Prepare a security checklist covering network access, TLS, authentication, privileges, and account ownership.
24. Mini Project: MySQL Connection and Access Security Audit
Project objective: Configure and audit a MySQL database environment so that application connections are protected and users have only the access required for their responsibilities.
Project Requirements
- Create a sample database named
company_db.
- Create separate accounts for reporting and application access.
- Restrict account host patterns wherever practical.
- Configure TLS and verify client connection behavior.
- Require secure transport where appropriate for the environment.
- Grant only the necessary database or table privileges.
- Use roles where they simplify consistent permission management.
- Review privileges with
SHOW GRANTS.
- Test authorized and unauthorized SQL operations.
- Document connection settings, certificate requirements, account owners, and recovery procedures.
Sample SQL Workflow
CREATE DATABASE IF NOT EXISTS company_db;
CREATE USER IF NOT EXISTS 'report_user'@'localhost'
IDENTIFIED BY 'Replace-With-A-Strong-Unique-Password';
GRANT SELECT ON company_db.*
TO 'report_user'@'localhost';
CREATE USER IF NOT EXISTS 'orders_app'@'192.168.1.25'
IDENTIFIED BY 'Replace-With-A-Strong-Unique-Password'
REQUIRE SSL;
GRANT SELECT, INSERT, UPDATE
ON company_db.orders
TO 'orders_app'@'192.168.1.25';
SHOW CREATE USER 'report_user'@'localhost';
SHOW GRANTS FOR 'report_user'@'localhost';
SHOW CREATE USER 'orders_app'@'192.168.1.25';
SHOW GRANTS FOR 'orders_app'@'192.168.1.25';
Run this workflow in a test environment with an authorized administrative account. The example assumes that the orders table exists before its privileges are granted. Replace all placeholder credentials and host values with appropriate values for the test environment. Do not execute production-wide configuration changes without reviewing their effects on existing applications.
25. Interview Questions and Answers
Q1. What is database connection security?
Answer: It protects the communication channel and access process between MySQL clients and the server through encryption, authentication, host restrictions, and other controls.
Q2. What is TLS in MySQL?
Answer: TLS encrypts network communication between compatible MySQL clients and servers and supports certificate-based identity verification.
Q3. What does require_secure_transport do?
Answer: It requires supported secure transport for MySQL connections when enabled.
Q4. What is the difference between REQUIRED and VERIFY_IDENTITY?
Answer: Both require encryption. VERIFY_IDENTITY also verifies the server certificate and checks the hostname against the certificate identity.
Q5. What does REQUIRE SSL do in a MySQL account definition?
Answer: It requires that the account connect using an SSL/TLS-encrypted connection.
Q6. What is the principle of least privilege?
Answer: It means assigning each account only the privileges needed for its intended responsibilities.
Q7. What is the difference between authentication and authorization?
Answer: Authentication verifies identity, while authorization determines which operations that identity may perform.
Q8. Why should applications not use an administrative account?
Answer: If the application is compromised, excessive administrative permissions could allow an attacker to make broad changes or access unrelated data.
Q9. How do you inspect a MySQL account's privileges?
SHOW GRANTS FOR 'username'@'host';
Q10. What is the purpose of MySQL roles?
Answer: Roles group privileges under a named identity so that permissions can be assigned and managed consistently.
Q11. Why are host restrictions important?
Answer: They limit which hosts can use a particular account and reduce unnecessary remote access.
Q12. How does TLS differ from least privilege?
Answer: TLS protects communication in transit, while least privilege limits what an authenticated account can do inside the database.
Q13. How can SQL injection be reduced?
Answer: Use prepared statements and parameterized queries, validate application inputs, and restrict the database account's permissions.
Q14. Does encryption alone make a database secure?
Answer: No. Secure databases also need appropriate authentication, least-privilege access, network controls, monitoring, and safe application code.
Q15. Why should permissions be reviewed regularly?
Answer: Users and applications change over time. Regular reviews help remove obsolete access and reduce excessive privileges.
26. Quick Revision Checklist
- Use TLS to protect sensitive network communication.
- Use certificate and hostname verification when appropriate.
- Configure
require_secure_transport only after validating server and client compatibility.
- Use account-level
REQUIRE SSL or certificate requirements when needed.
- Restrict accounts to appropriate host patterns.
- Avoid broad access from every host unless there is a justified design.
- Follow the principle of least privilege.
- Prefer table-level or database-level privileges over unnecessary global privileges.
- Separate administrative, reporting, and application accounts.
- Use
GRANT to assign only necessary permissions.
- Use
REVOKE to remove unnecessary permissions.
- Use roles for consistent permission management.
- Verify effective access using
SHOW GRANTS and role inspection.
- Use prepared statements to reduce SQL injection risk.
- Store credentials securely and never hard-code production passwords.
- Review accounts, connection settings, and permissions regularly.
27. Conclusion
Securing database connections and following least-privilege principles are essential for maintaining a safe MySQL environment. TLS helps protect communication between clients and servers, while certificate verification helps clients confirm the server's identity. Host restrictions, authentication controls, and network filtering reduce unnecessary access to the database.
Least privilege complements these controls by ensuring that each user and application receives only the permissions required for its tasks. By using dedicated accounts, narrowly scoped grants, roles, regular permission reviews, and prepared statements, organizations can reduce the potential impact of compromised credentials and application vulnerabilities.
Effective database security requires multiple layers working together. Encryption, authentication, authorization, secure application code, monitoring, and careful account management should be reviewed as part of an ongoing security process.
28. Official Documentation and Course Resources