Search in sources :

Example 11 with CJException

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());
}
Also used : ArrayList(java.util.ArrayList) AuthenticationLdapSaslClientPlugin(com.mysql.cj.protocol.a.authentication.AuthenticationLdapSaslClientPlugin) NativePacketPayload(com.mysql.cj.protocol.a.NativePacketPayload) CJException(com.mysql.cj.exceptions.CJException) Test(org.junit.jupiter.api.Test)

Example 12 with CJException

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());
}
Also used : ArrayList(java.util.ArrayList) AuthenticationLdapSaslClientPlugin(com.mysql.cj.protocol.a.authentication.AuthenticationLdapSaslClientPlugin) NativePacketPayload(com.mysql.cj.protocol.a.NativePacketPayload) CJException(com.mysql.cj.exceptions.CJException) Test(org.junit.jupiter.api.Test)

Example 13 with CJException

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());
        }
    }
}
Also used : Log(com.mysql.cj.log.Log) SQLException(java.sql.SQLException) ExceptionInterceptor(com.mysql.cj.exceptions.ExceptionInterceptor) Properties(java.util.Properties) CJException(com.mysql.cj.exceptions.CJException) CJCommunicationsException(com.mysql.cj.exceptions.CJCommunicationsException) OperationCancelledException(com.mysql.cj.exceptions.OperationCancelledException) ConnectionIsClosedException(com.mysql.cj.exceptions.ConnectionIsClosedException) SQLException(java.sql.SQLException) IOException(java.io.IOException) ExceptionInterceptorChain(com.mysql.cj.exceptions.ExceptionInterceptorChain) Map(java.util.Map) HashMap(java.util.HashMap) CJException(com.mysql.cj.exceptions.CJException)

Example 14 with CJException

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);
    }
}
Also used : NativePacketPayload(com.mysql.cj.protocol.a.NativePacketPayload) CJException(com.mysql.cj.exceptions.CJException)

Example 15 with CJException

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();
    }
}
Also used : WrongArgumentException(com.mysql.cj.exceptions.WrongArgumentException) Properties(java.util.Properties) SslMode(com.mysql.cj.conf.PropertyDefinitions.SslMode) CJException(com.mysql.cj.exceptions.CJException)

Aggregations

CJException (com.mysql.cj.exceptions.CJException)21 NativePacketPayload (com.mysql.cj.protocol.a.NativePacketPayload)9 ArrayList (java.util.ArrayList)6 AuthenticationLdapSaslClientPlugin (com.mysql.cj.protocol.a.authentication.AuthenticationLdapSaslClientPlugin)5 Test (org.junit.jupiter.api.Test)5 CJCommunicationsException (com.mysql.cj.exceptions.CJCommunicationsException)4 IOException (java.io.IOException)4 SQLException (java.sql.SQLException)4 UnableToConnectException (com.mysql.cj.exceptions.UnableToConnectException)3 WrongArgumentException (com.mysql.cj.exceptions.WrongArgumentException)3 ServerPreparedQuery (com.mysql.cj.ServerPreparedQuery)2 OperationCancelledException (com.mysql.cj.exceptions.OperationCancelledException)2 PasswordExpiredException (com.mysql.cj.exceptions.PasswordExpiredException)2 Resultset (com.mysql.cj.protocol.Resultset)2 LazyString (com.mysql.cj.util.LazyString)2 Properties (java.util.Properties)2 NativeSession (com.mysql.cj.NativeSession)1 PreparedQuery (com.mysql.cj.PreparedQuery)1 UsernameCallback (com.mysql.cj.callback.UsernameCallback)1 HostInfo (com.mysql.cj.conf.HostInfo)1