- Docs Home
- About TiDB
- Quick Start
- Develop
- Overview
- Quick Start
- Build a TiDB Cluster in TiDB Cloud (Developer Tier)
- CRUD SQL in TiDB
- Build a Simple CRUD App with TiDB
- Example Applications
- Connect to TiDB
- Design Database Schema
- Write Data
- Read Data
- Transaction
- Optimize
- Troubleshoot
- Reference
- Cloud Native Development Environment
- Third-party Support
- Deploy
- Software and Hardware Requirements
- Environment Configuration Checklist
- Plan Cluster Topology
- Install and Start
- Verify Cluster Status
- Test Cluster Performance
- Migrate
- Overview
- Migration Tools
- Migration Scenarios
- Migrate from Aurora
- Migrate MySQL of Small Datasets
- Migrate MySQL of Large Datasets
- Migrate and Merge MySQL Shards of Small Datasets
- Migrate and Merge MySQL Shards of Large Datasets
- Migrate from CSV Files
- Migrate from SQL Files
- Migrate from One TiDB Cluster to Another TiDB Cluster
- Migrate from TiDB to MySQL-compatible Databases
- Advanced Migration
- Integrate
- Overview
- Integration Scenarios
- Maintain
- Monitor and Alert
- Troubleshoot
- TiDB Troubleshooting Map
- Identify Slow Queries
- Analyze Slow Queries
- SQL Diagnostics
- Identify Expensive Queries Using Top SQL
- Identify Expensive Queries Using Logs
- Statement Summary Tables
- Troubleshoot Hotspot Issues
- Troubleshoot Increased Read and Write Latency
- Save and Restore the On-Site Information of a Cluster
- Troubleshoot Cluster Setup
- Troubleshoot High Disk I/O Usage
- Troubleshoot Lock Conflicts
- Troubleshoot TiFlash
- Troubleshoot Write Conflicts in Optimistic Transactions
- Troubleshoot Inconsistency Between Data and Indexes
- Performance Tuning
- Tuning Guide
- Configuration Tuning
- System Tuning
- Software Tuning
- SQL Tuning
- Overview
- Understanding the Query Execution Plan
- SQL Optimization Process
- Overview
- Logic Optimization
- Physical Optimization
- Prepare Execution Plan Cache
- Control Execution Plans
- Tutorials
- TiDB Tools
- Overview
- Use Cases
- Download
- TiUP
- Documentation Map
- Overview
- Terminology and Concepts
- Manage TiUP Components
- FAQ
- Troubleshooting Guide
- Command Reference
- Overview
- TiUP Commands
- TiUP Cluster Commands
- Overview
- tiup cluster audit
- tiup cluster check
- tiup cluster clean
- tiup cluster deploy
- tiup cluster destroy
- tiup cluster disable
- tiup cluster display
- tiup cluster edit-config
- tiup cluster enable
- tiup cluster help
- tiup cluster import
- tiup cluster list
- tiup cluster patch
- tiup cluster prune
- tiup cluster reload
- tiup cluster rename
- tiup cluster replay
- tiup cluster restart
- tiup cluster scale-in
- tiup cluster scale-out
- tiup cluster start
- tiup cluster stop
- tiup cluster template
- tiup cluster upgrade
- TiUP DM Commands
- Overview
- tiup dm audit
- tiup dm deploy
- tiup dm destroy
- tiup dm disable
- tiup dm display
- tiup dm edit-config
- tiup dm enable
- tiup dm help
- tiup dm import
- tiup dm list
- tiup dm patch
- tiup dm prune
- tiup dm reload
- tiup dm replay
- tiup dm restart
- tiup dm scale-in
- tiup dm scale-out
- tiup dm start
- tiup dm stop
- tiup dm template
- tiup dm upgrade
- TiDB Cluster Topology Reference
- DM Cluster Topology Reference
- Mirror Reference Guide
- TiUP Components
- PingCAP Clinic Diagnostic Service
- TiDB Operator
- Dumpling
- TiDB Lightning
- TiDB Data Migration
- About TiDB Data Migration
- Architecture
- Quick Start
- Deploy a DM cluster
- Tutorials
- Advanced Tutorials
- Maintain
- Cluster Upgrade
- Tools
- Performance Tuning
- Manage Data Sources
- Manage Tasks
- Export and Import Data Sources and Task Configurations of Clusters
- Handle Alerts
- Daily Check
- Reference
- Architecture
- Command Line
- Configuration Files
- OpenAPI
- Compatibility Catalog
- Secure
- Monitoring and Alerts
- Error Codes
- Glossary
- Example
- Troubleshoot
- Release Notes
- Backup & Restore (BR)
- Point-in-Time Recovery
- TiDB Binlog
- TiCDC
- Dumpling
- sync-diff-inspector
- TiSpark
- Reference
- Cluster Architecture
- Key Monitoring Metrics
- Secure
- Privileges
- SQL
- SQL Language Structure and Syntax
- SQL Statements
ADD COLUMNADD INDEXADMINADMIN CANCEL DDLADMIN CHECKSUM TABLEADMIN CHECK [TABLE|INDEX]ADMIN SHOW DDL [JOBS|QUERIES]ADMIN SHOW TELEMETRYALTER DATABASEALTER INDEXALTER INSTANCEALTER PLACEMENT POLICYALTER TABLEALTER TABLE COMPACTALTER TABLE SET TIFLASH MODEALTER USERANALYZE TABLEBACKUPBATCHBEGINCHANGE COLUMNCOMMITCHANGE DRAINERCHANGE PUMPCREATE [GLOBAL|SESSION] BINDINGCREATE DATABASECREATE INDEXCREATE PLACEMENT POLICYCREATE ROLECREATE SEQUENCECREATE TABLE LIKECREATE TABLECREATE USERCREATE VIEWDEALLOCATEDELETEDESCDESCRIBEDODROP [GLOBAL|SESSION] BINDINGDROP COLUMNDROP DATABASEDROP INDEXDROP PLACEMENT POLICYDROP ROLEDROP SEQUENCEDROP STATSDROP TABLEDROP USERDROP VIEWEXECUTEEXPLAIN ANALYZEEXPLAINFLASHBACK TABLEFLUSH PRIVILEGESFLUSH STATUSFLUSH TABLESGRANT <privileges>GRANT <role>INSERTKILL [TIDB]LOAD DATALOAD STATSMODIFY COLUMNPREPARERECOVER TABLERENAME INDEXRENAME TABLEREPLACERESTOREREVOKE <privileges>REVOKE <role>ROLLBACKSAVEPOINTSELECTSET DEFAULT ROLESET [NAMES|CHARACTER SET]SET PASSWORDSET ROLESET TRANSACTIONSET [GLOBAL|SESSION] <variable>SHOW ANALYZE STATUSSHOW [BACKUPS|RESTORES]SHOW [GLOBAL|SESSION] BINDINGSSHOW BUILTINSSHOW CHARACTER SETSHOW COLLATIONSHOW [FULL] COLUMNS FROMSHOW CONFIGSHOW CREATE PLACEMENT POLICYSHOW CREATE SEQUENCESHOW CREATE TABLESHOW CREATE USERSHOW DATABASESSHOW DRAINER STATUSSHOW ENGINESSHOW ERRORSSHOW [FULL] FIELDS FROMSHOW GRANTSSHOW INDEX [FROM|IN]SHOW INDEXES [FROM|IN]SHOW KEYS [FROM|IN]SHOW MASTER STATUSSHOW PLACEMENTSHOW PLACEMENT FORSHOW PLACEMENT LABELSSHOW PLUGINSSHOW PRIVILEGESSHOW [FULL] PROCESSSLISTSHOW PROFILESSHOW PUMP STATUSSHOW SCHEMASSHOW STATS_HEALTHYSHOW STATS_HISTOGRAMSSHOW STATS_METASHOW STATUSSHOW TABLE NEXT_ROW_IDSHOW TABLE REGIONSSHOW TABLE STATUSSHOW [FULL] TABLESSHOW [GLOBAL|SESSION] VARIABLESSHOW WARNINGSSHUTDOWNSPLIT REGIONSTART TRANSACTIONTABLETRACETRUNCATEUPDATEUSEWITH
- Data Types
- Functions and Operators
- Overview
- Type Conversion in Expression Evaluation
- Operators
- Control Flow Functions
- String Functions
- Numeric Functions and Operators
- Date and Time Functions
- Bit Functions and Operators
- Cast Functions and Operators
- Encryption and Compression Functions
- Locking Functions
- Information Functions
- JSON Functions
- Aggregate (GROUP BY) Functions
- Window Functions
- Miscellaneous Functions
- Precision Math
- Set Operations
- List of Expressions for Pushdown
- TiDB Specific Functions
- Clustered Indexes
- Constraints
- Generated Columns
- SQL Mode
- Table Attributes
- Transactions
- Garbage Collection (GC)
- Views
- Partitioning
- Temporary Tables
- Cached Tables
- Character Set and Collation
- Placement Rules in SQL
- System Tables
mysql- INFORMATION_SCHEMA
- Overview
ANALYZE_STATUSCLIENT_ERRORS_SUMMARY_BY_HOSTCLIENT_ERRORS_SUMMARY_BY_USERCLIENT_ERRORS_SUMMARY_GLOBALCHARACTER_SETSCLUSTER_CONFIGCLUSTER_HARDWARECLUSTER_INFOCLUSTER_LOADCLUSTER_LOGCLUSTER_SYSTEMINFOCOLLATIONSCOLLATION_CHARACTER_SET_APPLICABILITYCOLUMNSDATA_LOCK_WAITSDDL_JOBSDEADLOCKSENGINESINSPECTION_RESULTINSPECTION_RULESINSPECTION_SUMMARYKEY_COLUMN_USAGEMETRICS_SUMMARYMETRICS_TABLESPARTITIONSPLACEMENT_POLICIESPROCESSLISTREFERENTIAL_CONSTRAINTSSCHEMATASEQUENCESSESSION_VARIABLESSLOW_QUERYSTATISTICSTABLESTABLE_CONSTRAINTSTABLE_STORAGE_STATSTIDB_HOT_REGIONSTIDB_HOT_REGIONS_HISTORYTIDB_INDEXESTIDB_SERVERS_INFOTIDB_TRXTIFLASH_REPLICATIKV_REGION_PEERSTIKV_REGION_STATUSTIKV_STORE_STATUSUSER_PRIVILEGESVARIABLES_INFOVIEWS
METRICS_SCHEMA
- UI
- TiDB Dashboard
- Overview
- Maintain
- Access
- Overview Page
- Cluster Info Page
- Top SQL Page
- Key Visualizer Page
- Metrics Relation Graph
- SQL Statements Analysis
- Slow Queries Page
- Cluster Diagnostics
- Monitoring Page
- Search Logs Page
- Instance Profiling
- Session Management and Configuration
- FAQ
- CLI
- Command Line Flags
- Configuration File Parameters
- System Variables
- Storage Engines
- Telemetry
- Errors Codes
- Table Filter
- Schedule Replicas by Topology Labels
- FAQs
- Release Notes
- All Releases
- Release Timeline
- TiDB Versioning
- TiDB Installation Packages
- v6.2
- v6.1
- v6.0
- v5.4
- v5.3
- v5.2
- v5.1
- v5.0
- v4.0
- v3.1
- v3.0
- v2.1
- v2.0
- v1.0
- Glossary
Certificate-Based Authentication for Login
TiDB supports a certificate-based authentication method for users to log into TiDB. With this method, TiDB issues certificates to different users, uses encrypted connections to transfer data, and verifies certificates when users log in. This approach is more secure than the traditional password-based authentication method commonly used by MySQL users and is thus adopted by an increasing number of users.
To use certificate-based authentication, you might need to perform the following operations:
- Create security keys and certificates
- Configure certificates for TiDB and the client
- Configure the user certificate information to be verified when the user logs in
- Update and replace certificates
The rest of the document introduces in detail how to perform these operations.
Create security keys and certificates
It is recommended that you use OpenSSL to create keys and certificates. The certificate generation process is similar to the process described in Enable TLS Between TiDB Clients and Servers. The following paragraphs demonstrate how to configure more attribute fields that need to be verified in the certificate.
It is recommended that you use OpenSSL to create keys and certificates. The certificate generation process is similar to the process described in Enable TLS Between TiDB Clients and Servers. The following paragraphs demonstrate how to configure more attribute fields that need to be verified in the certificate.
Generate CA key and certificate
Execute the following command to generate the CA key:
sudo openssl genrsa 2048 > ca-key.pemThe output of the above command:
Generating RSA private key, 2048 bit long modulus (2 primes) ....................+++++ ...............................................+++++ e is 65537 (0x010001)Execute the following command to generate the certificate corresponding to the CA key:
sudo openssl req -new -x509 -nodes -days 365000 -key ca-key.pem -out ca-cert.pemEnter detailed certificate information. For example:
Country Name (2 letter code) [AU]:US State or Province Name (full name) [Some-State]:California Locality Name (e.g. city) []:San Francisco Organization Name (e.g. company) [Internet Widgits Pty Ltd]:PingCAP Inc. Organizational Unit Name (e.g. section) []:TiDB Common Name (e.g. server FQDN or YOUR name) []:TiDB admin Email Address []:s@pingcap.comNoteIn the above certificate details, texts after
:are the entered information.
Generate server key and certificate
Execute the following command to generate the server key:
sudo openssl req -newkey rsa:2048 -days 365000 -nodes -keyout server-key.pem -out server-req.pemEnter detailed certificate information. For example:
Country Name (2 letter code) [AU]:US State or Province Name (full name) [Some-State]:California Locality Name (e.g. city) []:San Francisco Organization Name (e.g. company) [Internet Widgits Pty Ltd]:PingCAP Inc. Organizational Unit Name (e.g. section) []:TiKV Common Name (e.g. server FQDN or YOUR name) []:TiKV Test Server Email Address []:k@pingcap.com Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []: An optional company name []:Execute the following command to generate the RSA key of the server:
sudo openssl rsa -in server-key.pem -out server-key.pemThe output of the above command:
writing RSA keyUse the CA certificate signature to generate the signed server certificate:
sudo openssl x509 -req -in server-req.pem -days 365000 -CA ca-cert.pem -CAkey ca-key.pem -set_serial 01 -out server-cert.pemThe output of the above command (for example):
Signature ok subject=C = US, ST = California, L = San Francisco, O = PingCAP Inc., OU = TiKV, CN = TiKV Test Server, emailAddress = k@pingcap.com Getting CA Private KeyNoteWhen you log in, TiDB checks whether the information in the
subjectsection of the above output is consistent or not.
Generate client key and certificate
After generating the server key and certificate, you need to generate the key and certificate for the client. It is often necessary to generate different keys and certificates for different users.
Execute the following command to generate the client key:
sudo openssl req -newkey rsa:2048 -days 365000 -nodes -keyout client-key.pem -out client-req.pemEnter detailed certificate information. For example:
Country Name (2 letter code) [AU]:US State or Province Name (full name) [Some-State]:California Locality Name (e.g. city) []:San Francisco Organization Name (e.g. company) [Internet Widgits Pty Ltd]:PingCAP Inc. Organizational Unit Name (e.g. section) []:TiDB Common Name (e.g. server FQDN or YOUR name) []:tpch-user1 Email Address []:zz@pingcap.com Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []: An optional company name []:Execute the following command to generate the RSA key of the client:
sudo openssl rsa -in client-key.pem -out client-key.pemThe output of the above command:
writing RSA keyUse the CA certificate signature to generate the client certificate:
sudo openssl x509 -req -in client-req.pem -days 365000 -CA ca-cert.pem -CAkey ca-key.pem -set_serial 01 -out client-cert.pemThe output of the above command (for example):
Signature ok subject=C = US, ST = California, L = San Francisco, O = PingCAP Inc., OU = TiDB, CN = tpch-user1, emailAddress = zz@pingcap.com Getting CA Private KeyNoteThe information of the
subjectsection in the above output is used for certificate configuration for login verification in therequiresection.
Verify certificate
Execute the following command to verify certificate:
openssl verify -CAfile ca-cert.pem server-cert.pem client-cert.pem
If the certificate is verified, you will see the following result:
server-cert.pem: OK
client-cert.pem: OK
Configure TiDB and the client to use certificates
After generating the certificates, you need to configure the TiDB server and the client to use the corresponding server certificate or client certificate.
Configure TiDB to use server certificate
Modify the [security] section in the TiDB configuration file. This step specifies the directory in which the CA certificate, the server key, and the server certificate are stored. You can replace path/to/server-cert.pem, path/to/server-key.pem, path/to/ca-cert.pem with your own directory.
[security]
ssl-cert ="path/to/server-cert.pem"
ssl-key ="path/to/server-key.pem"
ssl-ca="path/to/ca-cert.pem"
Start TiDB and check logs. If the following information is displayed in the log, the configuration is successful:
[INFO] [server.go:264] ["secure connection is enabled"] ["client verification enabled"=true]
Configure the client to use client certificate
Configure the client so that the client uses the client key and certificate for login.
Taking the MySQL client as an example, you can use the newly created client certificate, client key and CA by specifying ssl-cert, ssl-key, and ssl-ca:
mysql -utest -h0.0.0.0 -P4000 --ssl-cert /path/to/client-cert.new.pem --ssl-key /path/to/client-key.new.pem --ssl-ca /path/to/ca-cert.pem
/path/to/client-cert.new.pem, /path/to/client-key.new.pem, and /path/to/ca-cert.pem are the directory of the CA certificate, client key, and client certificate. You can replace them with your own directory.
Configure the user certificate information for login verification
First, connect TiDB using the client to configure the login verification. Then, you can get and configure the user certificate information to be verified.
Get user certificate information
The user certificate information can be specified by require subject, require issuer, require san, and require cipher, which are used to check the X509 certificate attributes.
require subject: Specifies thesubjectinformation of the client certificate when you log in. With this option specified, you do not need to configurerequire sslor x509. The information to be specified is consistent with the enteredsubjectinformation in Generate client keys and certificates.To get this option, execute the following command:
openssl x509 -noout -subject -in client-cert.pem | sed 's/.\{8\}//' | sed 's/, /\//g' | sed 's/ = /=/g' | sed 's/^/\//'require issuer: Specifies thesubjectinformation of the CA certificate that issues the user certificate. The information to be specified is consistent with the enteredsubjectinformation in Generate CA key and certificate.To get this option, execute the following command:
openssl x509 -noout -subject -in ca-cert.pem | sed 's/.\{8\}//' | sed 's/, /\//g' | sed 's/ = /=/g' | sed 's/^/\//'require san: Specifies theSubject Alternative Nameinformation of the CA certificate that issues the user certificate. The information to be specified is consistent with thealt_namesof theopenssl.cnfconfiguration file used to generate the client certificate.Execute the following command to get the information of the
require sanitem in the generated certificate:openssl x509 -noout -extensions subjectAltName -in client.crtrequire sancurrently supports the followingSubject Alternative Namecheck items:- URI
- IP
- DNS
Multiple check items can be configured after they are connected by commas. For example, configure
require sanas follows for theu1user:create user 'u1'@'%' require san 'DNS:d1,URI:spiffe://example.org/myservice1,URI:spiffe://example.org/myservice2'The above configuration only allows the
u1user to log in to TiDB using the certificate with the URI itemspiffe://example.org/myservice1orspiffe://example.org/myservice2and the DNS itemd1.
require cipher: Checks the cipher method supported by the client. Use the following statement to check the list of supported cipher methods:SHOW SESSION STATUS LIKE 'Ssl_cipher_list';
Configure user certificate information
After getting the user certificate information (require subject, require issuer, require san, require cipher), configure these information to be verified when creating a user, granting privileges, or altering a user. Replace <replaceable> with the corresponding information in the following statements.
You can configure one option or multiple options using the space or and as the separator.
Configure user certificate when creating a user (
create user):create user 'u1'@'%' require issuer '<replaceable>' subject '<replaceable>' san '<replaceable>' cipher '<replaceable>';Configure user certificate when granting privileges:
grant all on *.* to 'u1'@'%' require issuer '<replaceable>' subject '<replaceable>' san '<replaceable>' cipher '<replaceable>';Configure user certificate when altering a user:
alter user 'u1'@'%' require issuer '<replaceable>' subject '<replaceable>' san '<replaceable>' cipher '<replaceable>';
After the above configuration, the following items will be verified when you log in:
- SSL is used; the CA that issues the client certificate is consistent with the CA configured in the server.
- The
issuerinformation of the client certificate matches the information specified inrequire issuer. - The
subjectinformation of the client certificate matches the information specified inrequire cipher. - The
Subject Alternative Nameinformation of the client certificate matches the information specified inrequire san.
You can log into TiDB only after all the above items are verified. Otherwise, the ERROR 1045 (28000): Access denied error is returned. You can use the following command to check the TLS version, the cipher algorithm and whether the current connection uses the certificate for the login.
Connect the MySQL client and execute the following statement:
\s
The output:
--------------
mysql Ver 15.1 Distrib 10.4.10-MariaDB, for Linux (x86_64) using readline 5.1
Connection id: 1
Current database: test
Current user: root@127.0.0.1
SSL: Cipher in use is TLS_AES_256_GCM_SHA384
Then execute the following statement:
show variables like '%ssl%';
The output:
+---------------+----------------------------------+
| Variable_name | Value |
+---------------+----------------------------------+
| ssl_cert | /path/to/server-cert.pem |
| ssl_ca | /path/to/ca-cert.pem |
| have_ssl | YES |
| have_openssl | YES |
| ssl_key | /path/to/server-key.pem |
+---------------+----------------------------------+
6 rows in set (0.067 sec)
Update and replace certificate
The key and certificate are updated regularly. The following sections introduce how to update the key and certificate.
The CA certificate is the basis for mutual verification between the client and server. To replace the CA certificate, generate a combined certificate that supports the authentication for both old and new certificates. On the client and server, first replace the CA certificate, then replace the client/server key and certificate.
Update CA key and certificate
Back up the old CA key and certificate (suppose that
ca-key.pemis stolen):mv ca-key.pem ca-key.old.pem && \ mv ca-cert.pem ca-cert.old.pemGenerate the new CA key:
sudo openssl genrsa 2048 > ca-key.pemGenerate the new CA certificate using the newly generated CA key:
sudo openssl req -new -x509 -nodes -days 365000 -key ca-key.pem -out ca-cert.new.pemNoteGenerating the new CA certificate is to replace the keys and certificates on the client and server, and to ensure that online users are not affected. Therefore, the appended information in the above command must be consistent with the
require issuerinformation.Generate the combined CA certificate:
cat ca-cert.new.pem ca-cert.old.pem > ca-cert.pem
After the above operations, restart the TiDB server with the newly created combined CA certificate. Then the server accepts both the new and old CA certificates.
Also replace the old CA certificate with the combined certificate so that the client accepts both the old and new CA certificates.
Update client key and certificate
Perform the following steps only after you have replaced the old CA certificate on the client and server with the combined CA certificate.
Generate the new RSA key of the client:
sudo openssl req -newkey rsa:2048 -days 365000 -nodes -keyout client-key.new.pem -out client-req.new.pem && \ sudo openssl rsa -in client-key.new.pem -out client-key.new.pemNoteThe above command is to replace the client key and certificate, and to ensure that the online users are not affected. Therefore, the appended information in the above command must be consistent with the
require subjectinformation.Use the combined certificate and the new CA key to generate the new client certificate:
sudo openssl x509 -req -in client-req.new.pem -days 365000 -CA ca-cert.pem -CAkey ca-key.pem -set_serial 01 -out client-cert.new.pemMake the client (for example, MySQL) connect TiDB with the new client key and certificate:
mysql -utest -h0.0.0.0 -P4000 --ssl-cert /path/to/client-cert.new.pem --ssl-key /path/to/client-key.new.pem --ssl-ca /path/to/ca-cert.pemNote/path/to/client-cert.new.pem,/path/to/client-key.new.pem, and/path/to/ca-cert.pemspecify the directory of the CA certificate, client key, and client certificate. You can replace them with your own directory.
Update the server key and certificate
Generate the new RSA key of the server:
sudo openssl req -newkey rsa:2048 -days 365000 -nodes -keyout server-key.new.pem -out server-req.new.pem && \ sudo openssl rsa -in server-key.new.pem -out server-key.new.pemUse the combined CA certificate and the new CA key to generate the new server certificate:
sudo openssl x509 -req -in server-req.new.pem -days 365000 -CA ca-cert.pem -CAkey ca-key.pem -set_serial 01 -out server-cert.new.pemConfigure the TiDB server to use the new server key and certificate. See Configure TiDB server for details.