Search in sources :

Example 1 with SslMode

use of com.mysql.cj.conf.PropertyDefinitions.SslMode in project ABC by RuiPinto96274.

the class NativeAuthenticationProvider method connect.

/**
 * Initialize communications with the MySQL server. Handles logging on, and
 * handling initial connection errors.
 *
 * @param user
 *            user name
 * @param pass
 *            password
 * @param db
 *            database name
 */
@Override
public void connect(String user, String pass, String db) {
    ServerSession sessState = this.protocol.getServerSession();
    this.username = user;
    this.password = pass;
    this.database = db;
    NativeCapabilities capabilities = (NativeCapabilities) sessState.getCapabilities();
    NativePacketPayload buf = capabilities.getInitialHandshakePacket();
    SslMode sslMode = this.propertySet.<SslMode>getEnumProperty(PropertyKey.sslMode).getValue();
    int capabilityFlags = capabilities.getCapabilityFlags();
    if (((capabilityFlags & NativeServerSession.CLIENT_SSL) == 0) && sslMode != SslMode.DISABLED && sslMode != SslMode.PREFERRED) {
        // check SSL availability
        throw ExceptionFactory.createException(UnableToConnectException.class, Messages.getString("MysqlIO.15"), getExceptionInterceptor());
    } else if ((capabilityFlags & NativeServerSession.CLIENT_SECURE_CONNECTION) == 0) {
        // TODO: better messaging
        throw ExceptionFactory.createException(UnableToConnectException.class, "CLIENT_SECURE_CONNECTION is required", getExceptionInterceptor());
    } else if ((capabilityFlags & NativeServerSession.CLIENT_PLUGIN_AUTH) == 0) {
        // TODO: better messaging
        throw ExceptionFactory.createException(UnableToConnectException.class, "CLIENT_PLUGIN_AUTH is required", getExceptionInterceptor());
    }
    // read status flags (2 bytes)
    sessState.setStatusFlags(capabilities.getStatusFlags());
    int authPluginDataLength = capabilities.getAuthPluginDataLength();
    StringBuilder fullSeed = new StringBuilder(authPluginDataLength > 0 ? authPluginDataLength : NativeConstants.SEED_LENGTH);
    // read auth-plugin-data-part-1 (string[8])
    fullSeed.append(capabilities.getSeed());
    fullSeed.append(// read string[$len] auth-plugin-data-part-2 ($len=MAX(13, length of auth-plugin-data - 8))
    authPluginDataLength > 0 ? buf.readString(StringLengthDataType.STRING_FIXED, "ASCII", authPluginDataLength - 8) : buf.readString(StringSelfDataType.STRING_TERM, "ASCII"));
    this.seed = fullSeed.toString();
    this.useConnectWithDb = (this.database != null) && (this.database.length() > 0) && !this.propertySet.getBooleanProperty(PropertyKey.createDatabaseIfNotExist).getValue();
    long clientParam = NativeServerSession.CLIENT_SECURE_CONNECTION | NativeServerSession.CLIENT_PLUGIN_AUTH | // 
    (capabilityFlags & NativeServerSession.CLIENT_LONG_PASSWORD) | // 
    (capabilityFlags & NativeServerSession.CLIENT_PROTOCOL_41) | // Need this to get server status values
    (capabilityFlags & NativeServerSession.CLIENT_TRANSACTIONS) | // We always allow multiple result sets
    (capabilityFlags & NativeServerSession.CLIENT_MULTI_RESULTS) | // We always allow multiple result sets for SSPS
    (capabilityFlags & NativeServerSession.CLIENT_PS_MULTI_RESULTS) | // 
    (capabilityFlags & NativeServerSession.CLIENT_LONG_FLAG) | // 
    (capabilityFlags & NativeServerSession.CLIENT_DEPRECATE_EOF) | (capabilityFlags & NativeServerSession.CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA) | (capabilityFlags & NativeServerSession.CLIENT_QUERY_ATTRIBUTES) | (this.propertySet.getBooleanProperty(PropertyKey.useCompression).getValue() ? (capabilityFlags & NativeServerSession.CLIENT_COMPRESS) : 0) | (this.useConnectWithDb ? (capabilityFlags & NativeServerSession.CLIENT_CONNECT_WITH_DB) : 0) | (this.propertySet.getBooleanProperty(PropertyKey.useAffectedRows).getValue() ? 0 : (capabilityFlags & NativeServerSession.CLIENT_FOUND_ROWS)) | (this.propertySet.getBooleanProperty(PropertyKey.allowLoadLocalInfile).getValue() || this.propertySet.getStringProperty(PropertyKey.allowLoadLocalInfileInPath).isExplicitlySet() ? (capabilityFlags & NativeServerSession.CLIENT_LOCAL_FILES) : 0) | (this.propertySet.getBooleanProperty(PropertyKey.interactiveClient).getValue() ? (capabilityFlags & NativeServerSession.CLIENT_INTERACTIVE) : 0) | (this.propertySet.getBooleanProperty(PropertyKey.allowMultiQueries).getValue() ? (capabilityFlags & NativeServerSession.CLIENT_MULTI_STATEMENTS) : 0) | (this.propertySet.getBooleanProperty(PropertyKey.disconnectOnExpiredPasswords).getValue() ? 0 : (capabilityFlags & NativeServerSession.CLIENT_CAN_HANDLE_EXPIRED_PASSWORD)) | (NONE.equals(this.propertySet.getStringProperty(PropertyKey.connectionAttributes).getValue()) ? 0 : (capabilityFlags & NativeServerSession.CLIENT_CONNECT_ATTRS)) | (this.propertySet.<SslMode>getEnumProperty(PropertyKey.sslMode).getValue() != SslMode.DISABLED ? (capabilityFlags & NativeServerSession.CLIENT_SSL) : 0) | (this.propertySet.getBooleanProperty(PropertyKey.trackSessionState).getValue() ? (capabilityFlags & NativeServerSession.CLIENT_SESSION_TRACK) : 0);
    sessState.setClientParam(clientParam);
    /* First, negotiate SSL connection */
    if ((clientParam & NativeServerSession.CLIENT_SSL) != 0) {
        this.protocol.negotiateSSLConnection();
    }
    if (buf.isOKPacket()) {
        throw ExceptionFactory.createException(Messages.getString("AuthenticationProvider.UnexpectedAuthenticationApproval"), getExceptionInterceptor());
    }
    proceedHandshakeWithPluggableAuthentication(buf);
    this.password = null;
}
Also used : ServerSession(com.mysql.cj.protocol.ServerSession) SslMode(com.mysql.cj.conf.PropertyDefinitions.SslMode) UnableToConnectException(com.mysql.cj.exceptions.UnableToConnectException)

Example 2 with SslMode

use of com.mysql.cj.conf.PropertyDefinitions.SslMode in project ABC by RuiPinto96274.

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)

Example 3 with SslMode

use of com.mysql.cj.conf.PropertyDefinitions.SslMode in project JavaSegundasQuintas by ecteruel.

the class ExportControlled method performTlsHandshake.

/**
 * Converts the socket being used in the given SocketConnection to an SSLSocket by performing the SSL/TLS handshake.
 *
 * @param rawSocket
 *            original non-SSL socket
 * @param socketConnection
 *            the Protocol instance containing the socket to convert to an SSLSocket.
 * @param serverVersion
 *            ServerVersion object
 * @param log
 *            Logger
 * @return SSL socket
 * @throws IOException
 *             if i/o exception occurs
 * @throws SSLParamsException
 *             if the handshake fails, or if this distribution of Connector/J doesn't contain the SSL crypto hooks needed to perform the handshake.
 * @throws FeatureNotAvailableException
 *             if TLS is not supported
 */
public static Socket performTlsHandshake(Socket rawSocket, SocketConnection socketConnection, ServerVersion serverVersion, Log log) throws IOException, SSLParamsException, FeatureNotAvailableException {
    PropertySet pset = socketConnection.getPropertySet();
    SslMode sslMode = pset.<SslMode>getEnumProperty(PropertyKey.sslMode).getValue();
    boolean verifyServerCert = sslMode == SslMode.VERIFY_CA || sslMode == SslMode.VERIFY_IDENTITY;
    boolean fallbackToSystemTrustStore = pset.getBooleanProperty(PropertyKey.fallbackToSystemTrustStore).getValue();
    // (serverVersion == null) means that it was called from the X DevAPI.
    KeyStoreConf trustStore = !verifyServerCert ? new KeyStoreConf() : getTrustStoreConf(pset, serverVersion == null && verifyServerCert && !fallbackToSystemTrustStore);
    KeyStoreConf keyStore = getKeyStoreConf(pset);
    SSLSocketFactory socketFactory = getSSLContext(keyStore, trustStore, fallbackToSystemTrustStore, verifyServerCert, sslMode == PropertyDefinitions.SslMode.VERIFY_IDENTITY ? socketConnection.getHost() : null, socketConnection.getExceptionInterceptor()).getSocketFactory();
    SSLSocket sslSocket = (SSLSocket) socketFactory.createSocket(rawSocket, socketConnection.getHost(), socketConnection.getPort(), true);
    String[] allowedProtocols = getAllowedProtocols(pset, serverVersion, sslSocket.getSupportedProtocols());
    sslSocket.setEnabledProtocols(allowedProtocols);
    String[] allowedCiphers = getAllowedCiphers(pset, Arrays.asList(sslSocket.getEnabledCipherSuites()));
    if (allowedCiphers != null) {
        sslSocket.setEnabledCipherSuites(allowedCiphers);
    }
    sslSocket.startHandshake();
    if (log != null) {
        String tlsVersion = sslSocket.getSession().getProtocol();
        if (TLSv1.equalsIgnoreCase(tlsVersion) || TLSv1_1.equalsIgnoreCase(tlsVersion)) {
            log.logWarn("This connection is using " + tlsVersion + " which is now deprecated and will be removed in a future release of Connector/J.");
        }
    }
    return sslSocket;
}
Also used : SslMode(com.mysql.cj.conf.PropertyDefinitions.SslMode) SSLSocket(javax.net.ssl.SSLSocket) PropertySet(com.mysql.cj.conf.PropertySet) SSLSocketFactory(javax.net.ssl.SSLSocketFactory)

Example 4 with SslMode

use of com.mysql.cj.conf.PropertyDefinitions.SslMode in project JavaSegundasQuintas by ecteruel.

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)

Example 5 with SslMode

use of com.mysql.cj.conf.PropertyDefinitions.SslMode in project aws-mysql-jdbc by awslabs.

the class NativeAuthenticationProvider method connect.

/**
 * Initialize communications with the MySQL server. Handles logging on, and
 * handling initial connection errors.
 *
 * @param user
 *            user name
 * @param pass
 *            password
 * @param db
 *            database name
 */
@Override
public void connect(String user, String pass, String db) {
    ServerSession sessState = this.protocol.getServerSession();
    this.username = user;
    this.password = pass;
    this.database = db;
    NativeCapabilities capabilities = (NativeCapabilities) sessState.getCapabilities();
    NativePacketPayload buf = capabilities.getInitialHandshakePacket();
    SslMode sslMode = this.propertySet.<SslMode>getEnumProperty(PropertyKey.sslMode).getValue();
    int capabilityFlags = capabilities.getCapabilityFlags();
    if (((capabilityFlags & NativeServerSession.CLIENT_SSL) == 0) && sslMode != SslMode.DISABLED && sslMode != SslMode.PREFERRED) {
        // check SSL availability
        throw ExceptionFactory.createException(UnableToConnectException.class, Messages.getString("MysqlIO.15"), getExceptionInterceptor());
    } else if ((capabilityFlags & NativeServerSession.CLIENT_SECURE_CONNECTION) == 0) {
        // TODO: better messaging
        throw ExceptionFactory.createException(UnableToConnectException.class, "CLIENT_SECURE_CONNECTION is required", getExceptionInterceptor());
    } else if ((capabilityFlags & NativeServerSession.CLIENT_PLUGIN_AUTH) == 0) {
        // TODO: better messaging
        throw ExceptionFactory.createException(UnableToConnectException.class, "CLIENT_PLUGIN_AUTH is required", getExceptionInterceptor());
    }
    // read status flags (2 bytes)
    sessState.setStatusFlags(capabilities.getStatusFlags());
    int authPluginDataLength = capabilities.getAuthPluginDataLength();
    StringBuilder fullSeed = new StringBuilder(authPluginDataLength > 0 ? authPluginDataLength : NativeConstants.SEED_LENGTH);
    // read auth-plugin-data-part-1 (string[8])
    fullSeed.append(capabilities.getSeed());
    fullSeed.append(// read string[$len] auth-plugin-data-part-2 ($len=MAX(13, length of auth-plugin-data - 8))
    authPluginDataLength > 0 ? buf.readString(StringLengthDataType.STRING_FIXED, "ASCII", authPluginDataLength - 8) : buf.readString(StringSelfDataType.STRING_TERM, "ASCII"));
    this.seed = fullSeed.toString();
    this.useConnectWithDb = (this.database != null) && (this.database.length() > 0) && !this.propertySet.getBooleanProperty(PropertyKey.createDatabaseIfNotExist).getValue();
    long clientParam = // 
    capabilityFlags & NativeServerSession.CLIENT_LONG_PASSWORD | (// 
    this.propertySet.getBooleanProperty(PropertyKey.useAffectedRows).getValue() ? 0 : // 
    capabilityFlags & NativeServerSession.CLIENT_FOUND_ROWS) | // 
    capabilityFlags & NativeServerSession.CLIENT_LONG_FLAG | // 
    (this.useConnectWithDb ? capabilityFlags & NativeServerSession.CLIENT_CONNECT_WITH_DB : 0) | (// 
    this.propertySet.getBooleanProperty(PropertyKey.useCompression).getValue() ? capabilityFlags & NativeServerSession.CLIENT_COMPRESS : // 
    0) | (this.propertySet.getBooleanProperty(PropertyKey.allowLoadLocalInfile).getValue() || // 
    this.propertySet.getStringProperty(PropertyKey.allowLoadLocalInfileInPath).isExplicitlySet() ? capabilityFlags & NativeServerSession.CLIENT_LOCAL_FILES : // 
    0) | // 
    capabilityFlags & NativeServerSession.CLIENT_PROTOCOL_41 | (// 
    this.propertySet.getBooleanProperty(PropertyKey.interactiveClient).getValue() ? capabilityFlags & NativeServerSession.CLIENT_INTERACTIVE : // 
    0) | (// 
    this.propertySet.<SslMode>getEnumProperty(PropertyKey.sslMode).getValue() != SslMode.DISABLED ? capabilityFlags & NativeServerSession.CLIENT_SSL : // 
    0) | // Required to get server status values.
    capabilityFlags & NativeServerSession.CLIENT_TRANSACTIONS | // 
    NativeServerSession.CLIENT_SECURE_CONNECTION | (// 
    this.propertySet.getBooleanProperty(PropertyKey.allowMultiQueries).getValue() ? capabilityFlags & NativeServerSession.CLIENT_MULTI_STATEMENTS : // 
    0) | // Always allow multiple result sets.
    capabilityFlags & NativeServerSession.CLIENT_MULTI_RESULTS | // Always allow multiple result sets for SSPS.
    capabilityFlags & NativeServerSession.CLIENT_PS_MULTI_RESULTS | // 
    NativeServerSession.CLIENT_PLUGIN_AUTH | (// 
    NONE.equals(this.propertySet.getStringProperty(PropertyKey.connectionAttributes).getValue()) ? 0 : // 
    capabilityFlags & NativeServerSession.CLIENT_CONNECT_ATTRS) | // 
    capabilityFlags & NativeServerSession.CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA | (// 
    this.propertySet.getBooleanProperty(PropertyKey.disconnectOnExpiredPasswords).getValue() ? 0 : // 
    capabilityFlags & NativeServerSession.CLIENT_CAN_HANDLE_EXPIRED_PASSWORD) | (// 
    this.propertySet.getBooleanProperty(PropertyKey.trackSessionState).getValue() ? capabilityFlags & NativeServerSession.CLIENT_SESSION_TRACK : // 
    0) | // 
    capabilityFlags & NativeServerSession.CLIENT_DEPRECATE_EOF | // 
    capabilityFlags & NativeServerSession.CLIENT_QUERY_ATTRIBUTES | capabilityFlags & NativeServerSession.CLIENT_MULTI_FACTOR_AUTHENTICATION;
    sessState.setClientParam(clientParam);
    /* First, negotiate SSL connection */
    if ((clientParam & NativeServerSession.CLIENT_SSL) != 0) {
        this.protocol.negotiateSSLConnection();
    }
    if (buf.isOKPacket()) {
        throw ExceptionFactory.createException(Messages.getString("AuthenticationProvider.UnexpectedAuthenticationApproval"), getExceptionInterceptor());
    }
    proceedHandshakeWithPluggableAuthentication(buf);
    this.password = null;
}
Also used : ServerSession(com.mysql.cj.protocol.ServerSession) SslMode(com.mysql.cj.conf.PropertyDefinitions.SslMode) UnableToConnectException(com.mysql.cj.exceptions.UnableToConnectException)

Aggregations

SslMode (com.mysql.cj.conf.PropertyDefinitions.SslMode)9 PropertySet (com.mysql.cj.conf.PropertySet)3 CJException (com.mysql.cj.exceptions.CJException)3 UnableToConnectException (com.mysql.cj.exceptions.UnableToConnectException)3 WrongArgumentException (com.mysql.cj.exceptions.WrongArgumentException)3 ServerSession (com.mysql.cj.protocol.ServerSession)3 Properties (java.util.Properties)3 SSLSocket (javax.net.ssl.SSLSocket)3 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)3