0
# Authentication and Security
1
2
Pluggable authentication system supporting multiple authentication methods, credential providers, and SSL/TLS security configurations.
3
4
## Capabilities
5
6
### SSL/TLS Configuration
7
8
Comprehensive SSL/TLS security modes for encrypted connections.
9
10
```java { .api }
11
/**
12
* SSL connection modes
13
*/
14
public enum SslMode {
15
/** No SSL encryption */
16
DISABLE,
17
18
/** SSL encryption without certificate validation */
19
TRUST,
20
21
/** Validate certificate authority only */
22
VERIFY_CA,
23
24
/** Full certificate and hostname validation */
25
VERIFY_FULL;
26
}
27
```
28
29
**Usage Examples:**
30
31
```java
32
// Disable SSL (not recommended for production)
33
String disableUrl = "jdbc:mariadb://localhost:3306/mydb?sslMode=DISABLE";
34
35
// Enable SSL with trust mode (encryption only, no validation)
36
String trustUrl = "jdbc:mariadb://localhost:3306/mydb?sslMode=TRUST";
37
38
// Verify certificate authority
39
String verifyCaUrl = "jdbc:mariadb://localhost:3306/mydb?" +
40
"sslMode=VERIFY_CA&" +
41
"serverSslCert=/path/to/ca-cert.pem";
42
43
// Full certificate and hostname verification (recommended)
44
String verifyFullUrl = "jdbc:mariadb://localhost:3306/mydb?" +
45
"sslMode=VERIFY_FULL&" +
46
"trustStore=/path/to/truststore.jks&" +
47
"trustStorePassword=secret&" +
48
"trustStoreType=JKS";
49
50
// Client certificate authentication
51
String clientCertUrl = "jdbc:mariadb://localhost:3306/mydb?" +
52
"sslMode=VERIFY_FULL&" +
53
"keyStore=/path/to/client-keystore.jks&" +
54
"keyStorePassword=clientsecret&" +
55
"trustStore=/path/to/truststore.jks&" +
56
"trustStorePassword=secret";
57
58
// PEM format certificates
59
String pemUrl = "jdbc:mariadb://localhost:3306/mydb?" +
60
"sslMode=VERIFY_FULL&" +
61
"serverSslCert=/path/to/ca-cert.pem&" +
62
"clientSslCert=/path/to/client-cert.pem&" +
63
"clientSslKey=/path/to/client-key.pem";
64
65
// Custom cipher suites and protocols
66
String customSslUrl = "jdbc:mariadb://localhost:3306/mydb?" +
67
"sslMode=VERIFY_FULL&" +
68
"enabledSslCipherSuites=TLS_RSA_WITH_AES_256_CBC_SHA256,TLS_DHE_RSA_WITH_AES_256_CBC_SHA256&" +
69
"enabledSslProtocolSuites=TLSv1.2,TLSv1.3";
70
```
71
72
### Authentication Plugins
73
74
Pluggable authentication system supporting various authentication methods.
75
76
```java { .api }
77
/**
78
* Base authentication plugin interface
79
*/
80
public interface AuthenticationPlugin {
81
/**
82
* Get authentication type name
83
* @return Authentication type identifier
84
*/
85
String type();
86
87
/**
88
* Whether this plugin requires SSL connection
89
* @return true if SSL is mandatory
90
*/
91
boolean mustUseSsl();
92
93
/**
94
* Process authentication packet
95
* @param out Output stream to server
96
* @param in Input stream from server
97
* @param context Authentication context
98
* @return Authentication result
99
* @throws SQLException if authentication fails
100
*/
101
ReadAuthPacket authenticate(
102
Writer out,
103
Reader in,
104
Context context
105
) throws SQLException;
106
}
107
108
/**
109
* Authentication plugin factory interface
110
*/
111
public interface AuthenticationPluginFactory {
112
/**
113
* Get plugin type name
114
* @return Plugin type identifier
115
*/
116
String type();
117
118
/**
119
* Create authentication plugin instance
120
* @return New plugin instance
121
*/
122
AuthenticationPlugin create();
123
}
124
```
125
126
**Built-in Authentication Plugins:**
127
128
```java
129
// MySQL native password authentication
130
public class NativePasswordPlugin implements AuthenticationPlugin {
131
public String type() { return "mysql_native_password"; }
132
public boolean mustUseSsl() { return false; }
133
// Implementation for MySQL native password hashing
134
}
135
136
// Caching SHA2 password authentication
137
public class CachingSha2PasswordPlugin implements AuthenticationPlugin {
138
public String type() { return "caching_sha2_password"; }
139
public boolean mustUseSsl() { return true; }
140
// Implementation for MySQL 8.0+ caching SHA2 authentication
141
}
142
143
// Ed25519 password authentication (MariaDB-specific)
144
public class Ed25519PasswordPlugin implements AuthenticationPlugin {
145
public String type() { return "client_ed25519"; }
146
public boolean mustUseSsl() { return false; }
147
// Implementation for Ed25519 cryptographic authentication
148
}
149
150
// Clear text password authentication
151
public class ClearPasswordPlugin implements AuthenticationPlugin {
152
public String type() { return "mysql_clear_password"; }
153
public boolean mustUseSsl() { return true; }
154
// Implementation for clear text password (requires SSL)
155
}
156
157
// PAM authentication
158
public class SendPamAuthPacket implements AuthenticationPlugin {
159
public String type() { return "dialog"; }
160
public boolean mustUseSsl() { return false; }
161
// Implementation for PAM authentication dialog
162
}
163
164
// GSSAPI/Kerberos authentication
165
public class SendGssApiAuthPacket implements AuthenticationPlugin {
166
public String type() { return "auth_gssapi_client"; }
167
public boolean mustUseSsl() { return false; }
168
// Implementation for GSSAPI/Kerberos authentication
169
}
170
```
171
172
**Usage Examples:**
173
174
```java
175
// Restrict to specific authentication methods
176
String restrictedUrl = "jdbc:mariadb://localhost:3306/mydb?" +
177
"restrictedAuth=mysql_native_password,caching_sha2_password";
178
179
// Force specific authentication plugin
180
String ed25519Url = "jdbc:mariadb://localhost:3306/mydb?" +
181
"restrictedAuth=client_ed25519";
182
183
// GSSAPI/Kerberos authentication
184
String kerbUrl = "jdbc:mariadb://kerberos-enabled-server:3306/mydb?" +
185
"restrictedAuth=auth_gssapi_client&" +
186
"servicePrincipalName=mariadb/server.domain.com@REALM.COM";
187
188
// PAM authentication
189
String pamUrl = "jdbc:mariadb://pam-server:3306/mydb?" +
190
"restrictedAuth=dialog";
191
```
192
193
### Credential Providers
194
195
Pluggable credential management system for secure credential storage and retrieval.
196
197
```java { .api }
198
/**
199
* Credential provider plugin interface
200
* Extends Supplier<Credential> to support functional interface pattern
201
*/
202
public interface CredentialPlugin extends Supplier<Credential> {
203
/**
204
* Get credential plugin type
205
* @return Plugin type identifier
206
*/
207
String type();
208
209
/**
210
* Indicates if SSL is required for this credential plugin
211
* @return true if SSL must be enabled
212
*/
213
default boolean mustUseSsl();
214
215
/**
216
* Default authentication plugin type to use
217
* @return Plugin type, or null for default
218
*/
219
default String defaultAuthenticationPluginType();
220
221
/**
222
* Initialize plugin with connection parameters
223
* @param conf Connection configuration
224
* @param userName Requested username
225
* @param hostAddress Target host information
226
* @return Initialized plugin instance
227
* @throws SQLException if initialization fails
228
*/
229
default CredentialPlugin initialize(Configuration conf, String userName, HostAddress hostAddress) throws SQLException;
230
}
231
232
/**
233
* Basic credential holder
234
*/
235
public class Credential {
236
/**
237
* Create credential with username and password
238
* @param user Username
239
* @param password Password (may be null)
240
*/
241
public Credential(String user, String password);
242
243
public String getUser();
244
public String getPassword();
245
}
246
```
247
248
**Built-in Credential Providers:**
249
250
```java
251
// Environment variable credentials
252
public class EnvCredentialPlugin implements CredentialPlugin {
253
public String type() { return "ENV"; }
254
255
public Credential get(Configuration conf, String userName) throws SQLException {
256
// Reads credentials from environment variables:
257
// MARIADB_USER or DB_USER
258
// MARIADB_PASSWORD or DB_PASSWORD
259
String user = System.getenv("MARIADB_USER");
260
if (user == null) user = System.getenv("DB_USER");
261
262
String password = System.getenv("MARIADB_PASSWORD");
263
if (password == null) password = System.getenv("DB_PASSWORD");
264
265
return new Credential(user, password);
266
}
267
}
268
269
// AWS IAM credentials
270
public class AwsIamCredentialPlugin implements CredentialPlugin {
271
public String type() { return "AWS_IAM"; }
272
273
public Credential get(Configuration conf, String userName) throws SQLException {
274
// Uses AWS SDK to generate IAM authentication token
275
// Requires AWS credentials configured (IAM role, ~/.aws/credentials, etc.)
276
// Returns temporary token as password
277
}
278
}
279
280
// Properties file credentials
281
public class PropertiesCredentialPlugin implements CredentialPlugin {
282
public String type() { return "PROPERTY"; }
283
284
public Credential get(Configuration conf, String userName) throws SQLException {
285
// Reads credentials from properties file
286
// File path specified by 'propertiesFile' connection property
287
Properties props = new Properties();
288
props.load(new FileInputStream(conf.propertiesFile()));
289
return new Credential(
290
props.getProperty("user"),
291
props.getProperty("password")
292
);
293
}
294
}
295
```
296
297
**Usage Examples:**
298
299
```java
300
// Environment variable credentials
301
String envUrl = "jdbc:mariadb://localhost:3306/mydb?credentialType=ENV";
302
// Reads MARIADB_USER and MARIADB_PASSWORD environment variables
303
304
// AWS IAM authentication for RDS
305
String awsUrl = "jdbc:mariadb://mydb.cluster-xxx.us-east-1.rds.amazonaws.com:3306/mydb?" +
306
"credentialType=AWS_IAM&" +
307
"sslMode=VERIFY_FULL";
308
// Uses AWS credentials to generate authentication token
309
310
// Properties file credentials
311
String propUrl = "jdbc:mariadb://localhost:3306/mydb?" +
312
"credentialType=PROPERTY&" +
313
"propertiesFile=/etc/myapp/db.properties";
314
315
// Example properties file (/etc/myapp/db.properties):
316
// user=dbuser
317
// password=dbpass
318
319
// Set environment variables programmatically (for testing)
320
System.setProperty("MARIADB_USER", "testuser");
321
System.setProperty("MARIADB_PASSWORD", "testpass");
322
Connection envConn = DriverManager.getConnection(envUrl);
323
```
324
325
### TLS Socket Plugins
326
327
Customizable TLS socket implementation for advanced SSL/TLS configurations.
328
329
```java { .api }
330
/**
331
* TLS socket plugin interface
332
*/
333
public interface TlsSocketPlugin {
334
/**
335
* Get plugin name
336
* @return Plugin identifier
337
*/
338
String name();
339
340
/**
341
* Create TLS socket
342
* @param conf Connection configuration
343
* @param socket Underlying socket
344
* @return Configured SSLSocket
345
* @throws SQLException if TLS setup fails
346
*/
347
SSLSocket createSocket(Configuration conf, Socket socket) throws SQLException;
348
}
349
350
/**
351
* Default TLS socket implementation
352
*/
353
public class DefaultTlsSocketPlugin implements TlsSocketPlugin {
354
public String name() { return "DEFAULT"; }
355
356
public SSLSocket createSocket(Configuration conf, Socket socket) throws SQLException {
357
// Default SSL socket creation using standard Java SSL libraries
358
// Configures trust stores, key stores, cipher suites, etc.
359
}
360
}
361
```
362
363
**Usage Examples:**
364
365
```java
366
// Custom TLS configuration is typically handled automatically
367
// The driver uses DefaultTlsSocketPlugin by default
368
369
// Advanced SSL configuration through connection parameters
370
String advancedSslUrl = "jdbc:mariadb://localhost:3306/mydb?" +
371
"sslMode=VERIFY_FULL&" +
372
373
// Trust store configuration
374
"trustStore=/path/to/truststore.jks&" +
375
"trustStorePassword=trustsecret&" +
376
"trustStoreType=JKS&" +
377
378
// Key store configuration (for client certificates)
379
"keyStore=/path/to/keystore.jks&" +
380
"keyStorePassword=keystoresecret&" +
381
"keyStoreType=JKS&" +
382
383
// Cipher suite restrictions
384
"enabledSslCipherSuites=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256&" +
385
386
// Protocol restrictions
387
"enabledSslProtocolSuites=TLSv1.2,TLSv1.3";
388
```
389
390
## Security Best Practices
391
392
### Production SSL Configuration
393
394
```java
395
// Recommended production SSL configuration
396
String productionSslUrl = "jdbc:mariadb://db.company.com:3306/production?" +
397
// Require full certificate validation
398
"sslMode=VERIFY_FULL&" +
399
400
// Trust store with CA certificates
401
"trustStore=/etc/ssl/certs/mysql-ca-bundle.jks&" +
402
"trustStorePassword=secure_password&" +
403
"trustStoreType=JKS&" +
404
405
// Client certificate for mutual authentication
406
"keyStore=/etc/ssl/private/client-cert.jks&" +
407
"keyStorePassword=client_password&" +
408
"keyStoreType=JKS&" +
409
410
// Restrict to strong cipher suites
411
"enabledSslCipherSuites=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256&" +
412
413
// Require TLS 1.2 or higher
414
"enabledSslProtocolSuites=TLSv1.2,TLSv1.3&" +
415
416
// Credential management
417
"credentialType=ENV"; // Use environment variables
418
```
419
420
### AWS RDS SSL Configuration
421
422
```java
423
// AWS RDS with SSL and IAM authentication
424
String rdsUrl = "jdbc:mariadb://mydb.cluster-xxx.us-east-1.rds.amazonaws.com:3306/mydb?" +
425
// SSL configuration for RDS
426
"sslMode=VERIFY_FULL&" +
427
"serverSslCert=rds-ca-2019-root.pem&" + // Download from AWS
428
429
// IAM database authentication
430
"credentialType=AWS_IAM&" +
431
432
// Connection optimization for RDS
433
"connectTimeout=5000&" +
434
"socketTimeout=30000";
435
436
// Example IAM policy for database access:
437
// {
438
// "Version": "2012-10-17",
439
// "Statement": [
440
// {
441
// "Effect": "Allow",
442
// "Action": "rds-db:connect",
443
// "Resource": "arn:aws:rds-db:us-east-1:account-id:dbuser:mydb/iam-user"
444
// }
445
// ]
446
// }
447
```
448
449
### Certificate Management
450
451
```java
452
// Using Java KeyStore for certificates
453
// Create trust store with CA certificate
454
// keytool -import -alias mysql-ca -file ca-cert.pem -keystore truststore.jks -storepass secret
455
456
// Create client keystore with certificate and private key
457
// openssl pkcs12 -export -in client-cert.pem -inkey client-key.pem -out client.p12
458
// keytool -importkeystore -srckeystore client.p12 -srcstoretype PKCS12 -destkeystore keystore.jks
459
460
// Connection with KeyStore
461
String keystoreUrl = "jdbc:mariadb://secure-db:3306/mydb?" +
462
"sslMode=VERIFY_FULL&" +
463
"trustStore=/path/to/truststore.jks&" +
464
"trustStorePassword=truststorepass&" +
465
"keyStore=/path/to/keystore.jks&" +
466
"keyStorePassword=keystorepass";
467
468
// Alternative: Using PEM files directly
469
String pemUrl = "jdbc:mariadb://secure-db:3306/mydb?" +
470
"sslMode=VERIFY_FULL&" +
471
"serverSslCert=/path/to/ca-cert.pem&" +
472
"clientSslCert=/path/to/client-cert.pem&" +
473
"clientSslKey=/path/to/client-key.pem";
474
```
475
476
### Connection Security Hardening
477
478
```java
479
// Security-hardened connection configuration
480
String hardenedUrl = "jdbc:mariadb://db.company.com:3306/mydb?" +
481
// SSL/TLS security
482
"sslMode=VERIFY_FULL&" +
483
"trustStore=/etc/ssl/certs/ca-bundle.jks&" +
484
"enabledSslProtocolSuites=TLSv1.3&" + // Only TLS 1.3
485
486
// Authentication security
487
"restrictedAuth=caching_sha2_password&" + // Secure auth only
488
"credentialType=ENV&" + // Environment variables
489
490
// Connection security
491
"connectTimeout=5000&" + // Quick timeout to prevent hanging
492
"socketTimeout=30000&" + // Reasonable socket timeout
493
494
// Disable potentially insecure features
495
"allowMultiQueries=false&" + // Prevent SQL injection via multi-queries
496
"allowLocalInfile=false&" + // Prevent local file access
497
498
// Session security
499
"sessionVariables=sql_mode='STRICT_TRANS_TABLES,NO_ZERO_DATE,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO'";
500
```
501
502
### Credential Rotation
503
504
```java
505
// Environment-based credential rotation
506
public class CredentialRotationExample {
507
private static final long ROTATION_INTERVAL = 3600000; // 1 hour
508
private long lastRotation = 0;
509
private DataSource dataSource;
510
511
public Connection getConnection() throws SQLException {
512
// Check if credentials need rotation
513
if (System.currentTimeMillis() - lastRotation > ROTATION_INTERVAL) {
514
rotateCredentials();
515
}
516
517
return dataSource.getConnection();
518
}
519
520
private void rotateCredentials() {
521
// Update environment variables or credential source
522
// Create new DataSource with updated credentials
523
MariaDbDataSource newDataSource = new MariaDbDataSource();
524
newDataSource.setUrl("jdbc:mariadb://db:3306/mydb?credentialType=ENV&sslMode=VERIFY_FULL");
525
526
// Atomic replacement
527
DataSource oldDataSource = this.dataSource;
528
this.dataSource = newDataSource;
529
this.lastRotation = System.currentTimeMillis();
530
531
// Clean up old data source if it was pooled
532
if (oldDataSource instanceof Closeable) {
533
try {
534
((Closeable) oldDataSource).close();
535
} catch (Exception e) {
536
// Log error but don't fail rotation
537
}
538
}
539
}
540
}
541
```
542
543
## Monitoring and Auditing
544
545
### Connection Security Monitoring
546
547
```java
548
// Enable security-related logging and monitoring
549
String monitoredUrl = "jdbc:mariadb://db:3306/mydb?" +
550
"sslMode=VERIFY_FULL&" +
551
552
// Connection attributes for auditing
553
"connectionAttributes=" +
554
"program_name:MySecureApp," +
555
"version:1.0," +
556
"environment:production&" +
557
558
// Enable query logging (be careful in production)
559
"dumpQueriesOnException=true&" +
560
561
// Pool monitoring for connection tracking
562
"pool=true&" +
563
"registerJmxPool=true&" +
564
"poolName=SecurePool";
565
566
// JMX monitoring can track:
567
// - Connection counts by user
568
// - Failed authentication attempts
569
// - SSL handshake failures
570
// - Connection source IPs (if logged by database)
571
```