use of com.mysql.cj.exceptions.CJException in project aws-mysql-jdbc by awslabs.
the class AuthenticationTest method authLdapSaslCliPluginChallengeBadIterations.
/**
* Test wrong 'server-first-message' due to insufficient iterations.
* Data based on test vector from <a href="https://tools.ietf.org/html/rfc5802#section-5">RFC 5802, Section 5</a>.
*
* @throws Exception
*/
@Test
public void authLdapSaslCliPluginChallengeBadIterations() throws Exception {
AuthenticationPlugin<NativePacketPayload> authPlugin = new AuthenticationLdapSaslClientPlugin();
// Initialize plugin with some protocol (none is needed).
authPlugin.init(null);
// Set authentication parameters.
authPlugin.setAuthenticationParameters("user", "pencil");
// Initial server packet: Protocol::AuthSwitchRequest
// [authentication_ldap_sasl_client.SCRAM-SHA-1]
// ;; "." --> 0 byte.
// ;; first part of the packet is already processed.
NativePacketPayload challenge = new NativePacketPayload("SCRAM-SHA-1".getBytes("ASCII"));
// Expected 'client-first-message':
// [n,,n=user,r=<CNONCE>]
// ;; <CNONCE> is generated internally and needs to be replaced by the expected value from the test vector in order to continue the test.
List<NativePacketPayload> response = new ArrayList<>();
authPlugin.nextAuthenticationStep(challenge, response);
assertEquals(1, response.size());
String data = response.get(0).readString(StringSelfDataType.STRING_EOF, "UTF-8");
assertTrue(data.startsWith("n,,n=user,r="));
assertEquals("n,,n=user,r=".length() + 32, data.length());
// Replace the internal plugin data in order to match the expected 'client-first-message':
// [n,,n=user,r=fyko+d2lbbFgONRv9qkxdawL]
overrideSaslClientData(authPlugin, "fyko+d2lbbFgONRv9qkxdawL");
// Server's 'server-first-message':
// [r=fyko+d2lbbFgONRv9qkxdawL3rfcNHYJY1ZVvWVs7j,s=QSXCR+Q6sek8bf92,i=1024]
// ;; Bad 'i' attribute.
NativePacketPayload badChallenge = new NativePacketPayload("r=fyko+d2lbbFgONRv9qkxdawL3rfcNHYJY1ZVvWVs7j,s=QSXCR+Q6sek8bf92,i=1024".getBytes("UTF-8"));
// Expect Exception.
CJException ex = assertThrows(CJException.class, "Error while processing an authentication iteration for the authentication mechanism 'SCRAM-SHA-1'\\.", () -> authPlugin.nextAuthenticationStep(badChallenge, response));
assertEquals(SaslException.class, ex.getCause().getClass());
assertEquals("Announced SCRAM-SHA-1 iteration count is too low.", ex.getCause().getMessage());
}
use of com.mysql.cj.exceptions.CJException in project aws-mysql-jdbc by awslabs.
the class AuthenticationTest method authLdapSaslCliPluginChallengeBadNonce.
/**
* Test wrong 'server-first-message' due to bad server nonce.
* Data based on test vector from <a href="https://tools.ietf.org/html/rfc5802#section-5">RFC 5802, Section 5</a>.
*
* @throws Exception
*/
@Test
public void authLdapSaslCliPluginChallengeBadNonce() throws Exception {
AuthenticationPlugin<NativePacketPayload> authPlugin = new AuthenticationLdapSaslClientPlugin();
// Initialize plugin with some protocol (none is needed).
authPlugin.init(null);
// Set authentication parameters.
authPlugin.setAuthenticationParameters("user", "pencil");
// Initial server packet: Protocol::AuthSwitchRequest
// [authentication_ldap_sasl_client.SCRAM-SHA-1]
// ;; "." --> 0 byte.
// ;; first part of the packet is already processed.
NativePacketPayload challenge = new NativePacketPayload("SCRAM-SHA-1".getBytes("ASCII"));
// Expected 'client-first-message':
// [n,,n=user,r=<CNONCE>]
// ;; <CNONCE> is generated internally and needs to be replaced by the expected value from the test vector in order to continue the test.
List<NativePacketPayload> response = new ArrayList<>();
authPlugin.nextAuthenticationStep(challenge, response);
assertEquals(1, response.size());
String data = response.get(0).readString(StringSelfDataType.STRING_EOF, "UTF-8");
assertTrue(data.startsWith("n,,n=user,r="));
assertEquals("n,,n=user,r=".length() + 32, data.length());
// Replace the internal plugin data in order to match the expected 'client-first-message':
// [n,,n=user,r=fyko+d2lbbFgONRv9qkxdawL]
overrideSaslClientData(authPlugin, "fyko+d2lbbFgONRv9qkxdawL");
// Server's 'server-first-message':
// [r=XXXXXXXXXXXXXXXXXXXXXXXX3rfcNHYJY1ZVvWVs7j,s=QSXCR+Q6sek8bf92,i=4096]
// ;; Bad 'r' attribute.
NativePacketPayload badChallenge = new NativePacketPayload("r=XXXXXXXXXXXXXXXXXXXXXXXX3rfcNHYJY1ZVvWVs7j,s=QSXCR+Q6sek8bf92,i=4096".getBytes("UTF-8"));
// Expect Exception.
CJException ex = assertThrows(CJException.class, "Error while processing an authentication iteration for the authentication mechanism 'SCRAM-SHA-1'\\.", () -> authPlugin.nextAuthenticationStep(badChallenge, response));
assertEquals(SaslException.class, ex.getCause().getClass());
assertEquals("Invalid server nonce for SCRAM-SHA-1 authentication.", ex.getCause().getMessage());
}
use of com.mysql.cj.exceptions.CJException in project aws-mysql-jdbc by awslabs.
the class NativeSession method createConfigCacheIfNeeded.
private void createConfigCacheIfNeeded(Object syncMutex) {
synchronized (syncMutex) {
if (this.serverConfigCache != null) {
return;
}
try {
Class<?> factoryClass = Class.forName(getPropertySet().getStringProperty(PropertyKey.serverConfigCacheFactory).getStringValue());
@SuppressWarnings("unchecked") CacheAdapterFactory<String, Map<String, String>> cacheFactory = ((CacheAdapterFactory<String, Map<String, String>>) factoryClass.newInstance());
this.serverConfigCache = cacheFactory.getInstance(syncMutex, this.hostInfo.getDatabaseUrl(), Integer.MAX_VALUE, Integer.MAX_VALUE);
ExceptionInterceptor evictOnCommsError = new ExceptionInterceptor() {
public ExceptionInterceptor init(Properties config, Log log1) {
return this;
}
public void destroy() {
}
@SuppressWarnings("synthetic-access")
public Exception interceptException(Exception sqlEx) {
if (sqlEx instanceof SQLException && ConnectionUtils.isNetworkException((SQLException) sqlEx)) {
NativeSession.this.serverConfigCache.invalidate(NativeSession.this.hostInfo.getDatabaseUrl());
}
return null;
}
};
if (this.exceptionInterceptor == null) {
this.exceptionInterceptor = evictOnCommsError;
} else {
((ExceptionInterceptorChain) this.exceptionInterceptor).addRingZero(evictOnCommsError);
}
} catch (ClassNotFoundException e) {
throw ExceptionFactory.createException(Messages.getString("Connection.CantFindCacheFactory", new Object[] { getPropertySet().getStringProperty(PropertyKey.parseInfoCacheFactory).getValue(), PropertyKey.parseInfoCacheFactory }), e, getExceptionInterceptor());
} catch (InstantiationException | IllegalAccessException | CJException e) {
throw ExceptionFactory.createException(Messages.getString("Connection.CantLoadCacheFactory", new Object[] { getPropertySet().getStringProperty(PropertyKey.parseInfoCacheFactory).getValue(), PropertyKey.parseInfoCacheFactory }), e, getExceptionInterceptor());
}
}
}
use of com.mysql.cj.exceptions.CJException in project aws-mysql-jdbc by awslabs.
the class ServerPreparedQuery method sendExecutePacket.
public NativePacketPayload sendExecutePacket(NativePacketPayload packet, String queryAsString) {
// TODO queryAsString should be shared instead of passed
final long begin = this.session.getCurrentTimeNanosOrMillis();
resetCancelledState();
CancelQueryTask timeoutTask = null;
try {
// Get this before executing to avoid a shared packet pollution in the case some other query is issued internally, such as when using I_S.
timeoutTask = startQueryTimer(this, this.timeoutInMillis);
statementBegins();
NativePacketPayload resultPacket = this.session.sendCommand(packet, false, 0);
final long queryEndTime = this.session.getCurrentTimeNanosOrMillis();
if (timeoutTask != null) {
stopQueryTimer(timeoutTask, true, true);
timeoutTask = null;
}
final long executeTime = queryEndTime - begin;
setExecuteTime(executeTime);
if (this.logSlowQueries) {
this.queryWasSlow = //
this.useAutoSlowLog ? this.session.getProtocol().getMetricsHolder().checkAbonormallyLongQuery(executeTime) : executeTime > this.slowQueryThresholdMillis.getValue();
if (this.queryWasSlow) {
this.session.getProfilerEventHandler().processEvent(ProfilerEvent.TYPE_SLOW_QUERY, this.session, this, null, executeTime, new Throwable(), Messages.getString("ServerPreparedStatement.15", new String[] { String.valueOf(this.session.getSlowQueryThreshold()), String.valueOf(executeTime), this.originalSql, queryAsString }));
}
}
if (this.gatherPerfMetrics) {
this.session.getProtocol().getMetricsHolder().registerQueryExecutionTime(executeTime);
this.session.getProtocol().getMetricsHolder().incrementNumberOfPreparedExecutes();
}
if (this.profileSQL) {
this.session.getProfilerEventHandler().processEvent(ProfilerEvent.TYPE_EXECUTE, this.session, this, null, executeTime, new Throwable(), truncateQueryToLog(queryAsString));
}
return resultPacket;
} catch (CJException sqlEx) {
if (this.session.shouldIntercept()) {
this.session.invokeQueryInterceptorsPost(() -> {
return getOriginalSql();
}, this, null, true);
}
throw sqlEx;
} finally {
this.statementExecuting.set(false);
stopQueryTimer(timeoutTask, false, false);
}
}
use of com.mysql.cj.exceptions.CJException in project aws-mysql-jdbc by awslabs.
the class DefaultPropertySet method initializeProperties.
public void initializeProperties(Properties props) {
if (props != null) {
Properties infoCopy = (Properties) props.clone();
// TODO do we need to remove next properties (as it was before)?
infoCopy.remove(PropertyKey.HOST.getKeyName());
infoCopy.remove(PropertyKey.PORT.getKeyName());
infoCopy.remove(PropertyKey.USER.getKeyName());
infoCopy.remove(PropertyKey.PASSWORD.getKeyName());
infoCopy.remove(PropertyKey.DBNAME.getKeyName());
for (PropertyKey propKey : PropertyDefinitions.PROPERTY_KEY_TO_PROPERTY_DEFINITION.keySet()) {
try {
RuntimeProperty<?> propToSet = getProperty(propKey);
propToSet.initializeFrom(infoCopy, null);
} catch (CJException e) {
throw ExceptionFactory.createException(WrongArgumentException.class, e.getMessage(), e);
}
}
// Translate legacy SSL properties if sslMode isn't explicitly set. Default sslMode is PREFERRED.
RuntimeProperty<SslMode> sslMode = this.<SslMode>getEnumProperty(PropertyKey.sslMode);
if (!sslMode.isExplicitlySet()) {
RuntimeProperty<Boolean> useSSL = this.getBooleanProperty(PropertyKey.useSSL);
RuntimeProperty<Boolean> verifyServerCertificate = this.getBooleanProperty(PropertyKey.verifyServerCertificate);
RuntimeProperty<Boolean> requireSSL = this.getBooleanProperty(PropertyKey.requireSSL);
if (useSSL.isExplicitlySet() || verifyServerCertificate.isExplicitlySet() || requireSSL.isExplicitlySet()) {
if (!useSSL.getValue()) {
sslMode.setValue(SslMode.DISABLED);
} else if (verifyServerCertificate.getValue()) {
sslMode.setValue(SslMode.VERIFY_CA);
} else if (requireSSL.getValue()) {
sslMode.setValue(SslMode.REQUIRED);
}
}
}
// add user-defined properties
for (Object key : infoCopy.keySet()) {
String val = infoCopy.getProperty((String) key);
PropertyDefinition<String> def = new StringPropertyDefinition((String) key, null, val, PropertyDefinitions.RUNTIME_MODIFIABLE, Messages.getString("ConnectionProperties.unknown"), "8.0.10", PropertyDefinitions.CATEGORY_USER_DEFINED, Integer.MIN_VALUE);
RuntimeProperty<String> p = new StringProperty(def);
addProperty(p);
}
postInitialization();
}
}
Aggregations