Search in sources :

Example 6 with InternalLogWriter

use of org.apache.geode.internal.logging.InternalLogWriter in project geode by apache.

the class ServerHandShakeProcessor method readGFEHandshake.

private static boolean readGFEHandshake(ServerConnection connection, Version clientVersion) {
    int handShakeTimeout = connection.getHandShakeTimeout();
    InternalLogWriter securityLogWriter = connection.getSecurityLogWriter();
    try {
        Socket socket = connection.getSocket();
        DistributedSystem system = connection.getDistributedSystem();
        // hitesh:it will set credentials and principals
        HandShake handshake = new HandShake(socket, handShakeTimeout, system, clientVersion, connection.getCommunicationMode());
        connection.setHandshake(handshake);
        ClientProxyMembershipID proxyId = handshake.getMembership();
        connection.setProxyId(proxyId);
        // Hitesh:for older version we should set this
        if (clientVersion.compareTo(Version.GFE_65) < 0 || connection.getCommunicationMode() == Acceptor.GATEWAY_TO_GATEWAY) {
            long uniqueId = setAuthAttributes(connection);
            // for older clients < 6.5
            connection.setUserAuthId(uniqueId);
        }
    } catch (SocketTimeoutException timeout) {
        logger.warn(LocalizedMessage.create(LocalizedStrings.ServerHandShakeProcessor_0_HANDSHAKE_REPLY_CODE_TIMEOUT_NOT_RECEIVED_WITH_IN_1_MS, new Object[] { connection.getName(), Integer.valueOf(handShakeTimeout) }));
        connection.stats.incFailedConnectionAttempts();
        connection.cleanup();
        return false;
    } catch (EOFException e) {
        // no need to warn client just gave up on this server before we could
        // handshake
        logger.info("{} {}", connection.getName(), e);
        connection.stats.incFailedConnectionAttempts();
        connection.cleanup();
        return false;
    } catch (SocketException e) {
        // no need to warn client just gave up on this
        // server before we could handshake
        logger.info("{} {}", connection.getName(), e);
        connection.stats.incFailedConnectionAttempts();
        connection.cleanup();
        return false;
    } catch (IOException e) {
        logger.warn(LocalizedMessage.create(LocalizedStrings.ServerHandShakeProcessor_0_RECEIVED_NO_HANDSHAKE_REPLY_CODE, connection.getName()), e);
        connection.stats.incFailedConnectionAttempts();
        connection.cleanup();
        return false;
    } catch (AuthenticationRequiredException noauth) {
        String exStr = noauth.getLocalizedMessage();
        if (noauth.getCause() != null) {
            exStr += " : " + noauth.getCause().getLocalizedMessage();
        }
        if (securityLogWriter.warningEnabled()) {
            securityLogWriter.warning(LocalizedStrings.ONE_ARG, connection.getName() + ": Security exception: " + exStr);
        }
        connection.stats.incFailedConnectionAttempts();
        connection.refuseHandshake(noauth.getMessage(), HandShake.REPLY_EXCEPTION_AUTHENTICATION_REQUIRED);
        connection.cleanup();
        return false;
    } catch (AuthenticationFailedException failed) {
        String exStr = failed.getLocalizedMessage();
        if (failed.getCause() != null) {
            exStr += " : " + failed.getCause().getLocalizedMessage();
        }
        if (securityLogWriter.warningEnabled()) {
            securityLogWriter.warning(LocalizedStrings.ONE_ARG, connection.getName() + ": Security exception: " + exStr);
        }
        connection.stats.incFailedConnectionAttempts();
        connection.refuseHandshake(failed.getMessage(), HandShake.REPLY_EXCEPTION_AUTHENTICATION_FAILED);
        connection.cleanup();
        return false;
    } catch (Exception ex) {
        logger.warn("{} {}", connection.getName(), ex.getLocalizedMessage());
        connection.stats.incFailedConnectionAttempts();
        connection.refuseHandshake(ex.getMessage(), REPLY_REFUSED);
        connection.cleanup();
        return false;
    }
    return true;
}
Also used : SocketException(java.net.SocketException) InternalLogWriter(org.apache.geode.internal.logging.InternalLogWriter) AuthenticationFailedException(org.apache.geode.security.AuthenticationFailedException) IOException(java.io.IOException) AuthenticationRequiredException(org.apache.geode.security.AuthenticationRequiredException) DistributedSystem(org.apache.geode.distributed.DistributedSystem) InternalDistributedSystem(org.apache.geode.distributed.internal.InternalDistributedSystem) VersionException(org.apache.geode.cache.VersionException) AuthenticationFailedException(org.apache.geode.security.AuthenticationFailedException) SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) EOFException(java.io.EOFException) IncompatibleVersionException(org.apache.geode.cache.IncompatibleVersionException) AuthenticationRequiredException(org.apache.geode.security.AuthenticationRequiredException) UnsupportedVersionException(org.apache.geode.cache.UnsupportedVersionException) SocketTimeoutException(java.net.SocketTimeoutException) EOFException(java.io.EOFException) Socket(java.net.Socket)

Example 7 with InternalLogWriter

use of org.apache.geode.internal.logging.InternalLogWriter in project geode by apache.

the class HandShake method writeCredential.

/**
   * This method writes what readCredential() method expects to read. (Note the use of singular
   * credential). It is similar to writeCredentials(), except that it doesn't write
   * credential-properties.
   */
public byte writeCredential(DataOutputStream dos, DataInputStream dis, String authInit, boolean isNotification, DistributedMember member, HeapDataOutputStream heapdos) throws IOException, GemFireSecurityException {
    if (!this.multiuserSecureMode && (authInit == null || authInit.length() == 0)) {
        // No credentials indicator
        heapdos.writeByte(CREDENTIALS_NONE);
        heapdos.flush();
        dos.write(heapdos.toByteArray());
        dos.flush();
        return -1;
    }
    if (dhSKAlgo == null || dhSKAlgo.length() == 0) {
        // Normal credentials without encryption indicator
        heapdos.writeByte(CREDENTIALS_NORMAL);
        this.appSecureMode = CREDENTIALS_NORMAL;
        // DataSerializer.writeProperties(p_credentials, heapdos);
        heapdos.flush();
        dos.write(heapdos.toByteArray());
        dos.flush();
        return -1;
    }
    byte acceptanceCode = -1;
    try {
        InternalLogWriter securityLogWriter = (InternalLogWriter) this.system.getSecurityLogWriter();
        securityLogWriter.fine("HandShake: using Diffie-Hellman key exchange with algo " + dhSKAlgo);
        boolean requireAuthentication = (certificateFilePath != null && certificateFilePath.length() > 0);
        if (requireAuthentication) {
            securityLogWriter.fine("HandShake: server authentication using digital " + "signature required");
        }
        // Credentials with encryption indicator
        heapdos.writeByte(CREDENTIALS_DHENCRYPT);
        this.appSecureMode = CREDENTIALS_DHENCRYPT;
        heapdos.writeBoolean(requireAuthentication);
        // Send the symmetric encryption algorithm name
        DataSerializer.writeString(dhSKAlgo, heapdos);
        // Send the DH public key
        byte[] keyBytes = dhPublicKey.getEncoded();
        DataSerializer.writeByteArray(keyBytes, heapdos);
        byte[] clientChallenge = null;
        if (requireAuthentication) {
            // Authentication of server should be with the client supplied
            // challenge
            clientChallenge = new byte[64];
            random.nextBytes(clientChallenge);
            DataSerializer.writeByteArray(clientChallenge, heapdos);
        }
        heapdos.flush();
        dos.write(heapdos.toByteArray());
        dos.flush();
        // Expect the alias and signature in the reply
        acceptanceCode = dis.readByte();
        if (acceptanceCode != REPLY_OK && acceptanceCode != REPLY_AUTH_NOT_REQUIRED) {
            // Ignore the useless data
            dis.readByte();
            dis.readInt();
            if (!isNotification) {
                DataSerializer.readByteArray(dis);
            }
            readMessage(dis, dos, acceptanceCode, member);
        } else if (acceptanceCode == REPLY_OK) {
            // Get the public key of the other side
            keyBytes = DataSerializer.readByteArray(dis);
            if (requireAuthentication) {
                String subject = DataSerializer.readString(dis);
                byte[] signatureBytes = DataSerializer.readByteArray(dis);
                if (!certificateMap.containsKey(subject)) {
                    throw new AuthenticationFailedException(LocalizedStrings.HandShake_HANDSHAKE_FAILED_TO_FIND_PUBLIC_KEY_FOR_SERVER_WITH_SUBJECT_0.toLocalizedString(subject));
                }
                // Check the signature with the public key
                X509Certificate cert = (X509Certificate) certificateMap.get(subject);
                Signature sig = Signature.getInstance(cert.getSigAlgName());
                sig.initVerify(cert);
                sig.update(clientChallenge);
                // Check the challenge string
                if (!sig.verify(signatureBytes)) {
                    throw new AuthenticationFailedException("Mismatch in client " + "challenge bytes. Malicious server?");
                }
                securityLogWriter.fine("HandShake: Successfully verified the " + "digital signature from server");
            }
            // Read server challenge bytes
            byte[] serverChallenge = DataSerializer.readByteArray(dis);
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFact = KeyFactory.getInstance("DH");
            // PublicKey pubKey = keyFact.generatePublic(x509KeySpec);
            this.clientPublicKey = keyFact.generatePublic(x509KeySpec);
            HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT);
            try {
                // Add the challenge string
                DataSerializer.writeByteArray(serverChallenge, hdos);
                // byte[] encBytes = encrypt.doFinal(hdos.toByteArray());
                byte[] encBytes = encryptBytes(hdos.toByteArray(), getEncryptCipher(dhSKAlgo, this.clientPublicKey));
                DataSerializer.writeByteArray(encBytes, dos);
            } finally {
                hdos.close();
            }
        }
    } catch (IOException ex) {
        throw ex;
    } catch (GemFireSecurityException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new AuthenticationFailedException("HandShake failed in Diffie-Hellman key exchange", ex);
    }
    dos.flush();
    return acceptanceCode;
}
Also used : InternalLogWriter(org.apache.geode.internal.logging.InternalLogWriter) AuthenticationFailedException(org.apache.geode.security.AuthenticationFailedException) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) ServerRefusedConnectionException(org.apache.geode.cache.client.ServerRefusedConnectionException) GemFireSecurityException(org.apache.geode.security.GemFireSecurityException) InternalGemFireException(org.apache.geode.InternalGemFireException) GatewayConfigurationException(org.apache.geode.cache.GatewayConfigurationException) EOFException(java.io.EOFException) AuthenticationFailedException(org.apache.geode.security.AuthenticationFailedException) GemFireConfigException(org.apache.geode.GemFireConfigException) IOException(java.io.IOException) AuthenticationRequiredException(org.apache.geode.security.AuthenticationRequiredException) GemFireSecurityException(org.apache.geode.security.GemFireSecurityException) HeapDataOutputStream(org.apache.geode.internal.HeapDataOutputStream) Signature(java.security.Signature) KeyFactory(java.security.KeyFactory)

Example 8 with InternalLogWriter

use of org.apache.geode.internal.logging.InternalLogWriter in project geode by apache.

the class HandShake method writeCredentials.

/**
   * This assumes that authentication is the last piece of info in handshake
   */
public void writeCredentials(DataOutputStream dos, DataInputStream dis, Properties p_credentials, boolean isNotification, DistributedMember member, HeapDataOutputStream heapdos) throws IOException, GemFireSecurityException {
    if (p_credentials == null) {
        // No credentials indicator
        heapdos.writeByte(CREDENTIALS_NONE);
        heapdos.flush();
        dos.write(heapdos.toByteArray());
        dos.flush();
        return;
    }
    if (dhSKAlgo == null || dhSKAlgo.length() == 0) {
        // Normal credentials without encryption indicator
        heapdos.writeByte(CREDENTIALS_NORMAL);
        DataSerializer.writeProperties(p_credentials, heapdos);
        heapdos.flush();
        dos.write(heapdos.toByteArray());
        dos.flush();
        return;
    }
    try {
        InternalLogWriter securityLogWriter = (InternalLogWriter) this.system.getSecurityLogWriter();
        securityLogWriter.fine("HandShake: using Diffie-Hellman key exchange with algo " + dhSKAlgo);
        boolean requireAuthentication = (certificateFilePath != null && certificateFilePath.length() > 0);
        if (requireAuthentication) {
            securityLogWriter.fine("HandShake: server authentication using digital " + "signature required");
        }
        // Credentials with encryption indicator
        heapdos.writeByte(CREDENTIALS_DHENCRYPT);
        heapdos.writeBoolean(requireAuthentication);
        // Send the symmetric encryption algorithm name
        DataSerializer.writeString(dhSKAlgo, heapdos);
        // Send the DH public key
        byte[] keyBytes = dhPublicKey.getEncoded();
        DataSerializer.writeByteArray(keyBytes, heapdos);
        byte[] clientChallenge = null;
        if (requireAuthentication) {
            // Authentication of server should be with the client supplied
            // challenge
            clientChallenge = new byte[64];
            random.nextBytes(clientChallenge);
            DataSerializer.writeByteArray(clientChallenge, heapdos);
        }
        heapdos.flush();
        dos.write(heapdos.toByteArray());
        dos.flush();
        // Expect the alias and signature in the reply
        byte acceptanceCode = dis.readByte();
        if (acceptanceCode != REPLY_OK && acceptanceCode != REPLY_AUTH_NOT_REQUIRED) {
            // Ignore the useless data
            dis.readByte();
            dis.readInt();
            if (!isNotification) {
                DataSerializer.readByteArray(dis);
            }
            readMessage(dis, dos, acceptanceCode, member);
        } else if (acceptanceCode == REPLY_OK) {
            // Get the public key of the other side
            keyBytes = DataSerializer.readByteArray(dis);
            if (requireAuthentication) {
                String subject = DataSerializer.readString(dis);
                byte[] signatureBytes = DataSerializer.readByteArray(dis);
                if (!certificateMap.containsKey(subject)) {
                    throw new AuthenticationFailedException(LocalizedStrings.HandShake_HANDSHAKE_FAILED_TO_FIND_PUBLIC_KEY_FOR_SERVER_WITH_SUBJECT_0.toLocalizedString(subject));
                }
                // Check the signature with the public key
                X509Certificate cert = (X509Certificate) certificateMap.get(subject);
                Signature sig = Signature.getInstance(cert.getSigAlgName());
                sig.initVerify(cert);
                sig.update(clientChallenge);
                // Check the challenge string
                if (!sig.verify(signatureBytes)) {
                    throw new AuthenticationFailedException("Mismatch in client " + "challenge bytes. Malicious server?");
                }
                securityLogWriter.fine("HandShake: Successfully verified the " + "digital signature from server");
            }
            byte[] challenge = DataSerializer.readByteArray(dis);
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFact = KeyFactory.getInstance("DH");
            // PublicKey pubKey = keyFact.generatePublic(x509KeySpec);
            this.clientPublicKey = keyFact.generatePublic(x509KeySpec);
            HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT);
            try {
                DataSerializer.writeProperties(p_credentials, hdos);
                // Also add the challenge string
                DataSerializer.writeByteArray(challenge, hdos);
                // byte[] encBytes = encrypt.doFinal(hdos.toByteArray());
                byte[] encBytes = encryptBytes(hdos.toByteArray(), getEncryptCipher(dhSKAlgo, this.clientPublicKey));
                DataSerializer.writeByteArray(encBytes, dos);
            } finally {
                hdos.close();
            }
        }
    } catch (IOException ex) {
        throw ex;
    } catch (GemFireSecurityException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new AuthenticationFailedException("HandShake failed in Diffie-Hellman key exchange", ex);
    }
    dos.flush();
}
Also used : InternalLogWriter(org.apache.geode.internal.logging.InternalLogWriter) AuthenticationFailedException(org.apache.geode.security.AuthenticationFailedException) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) ServerRefusedConnectionException(org.apache.geode.cache.client.ServerRefusedConnectionException) GemFireSecurityException(org.apache.geode.security.GemFireSecurityException) InternalGemFireException(org.apache.geode.InternalGemFireException) GatewayConfigurationException(org.apache.geode.cache.GatewayConfigurationException) EOFException(java.io.EOFException) AuthenticationFailedException(org.apache.geode.security.AuthenticationFailedException) GemFireConfigException(org.apache.geode.GemFireConfigException) IOException(java.io.IOException) AuthenticationRequiredException(org.apache.geode.security.AuthenticationRequiredException) GemFireSecurityException(org.apache.geode.security.GemFireSecurityException) HeapDataOutputStream(org.apache.geode.internal.HeapDataOutputStream) Signature(java.security.Signature) KeyFactory(java.security.KeyFactory)

Example 9 with InternalLogWriter

use of org.apache.geode.internal.logging.InternalLogWriter in project geode by apache.

the class GMSAuthenticator method authenticate.

/**
   * Method is package protected to be used in testing.
   */
String authenticate(DistributedMember member, Properties credentials, Properties secProps) throws AuthenticationFailedException {
    // For older systems, locator might be started without cache, so secureService may not be
    // initialized here. We need to check
    // if the passed in secProps has peer authenticator or not
    String authMethod = secProps.getProperty(SECURITY_PEER_AUTHENTICATOR);
    // at this point,
    if (!securityService.isPeerSecurityRequired() && StringUtils.isBlank(authMethod)) {
        return null;
    }
    InternalLogWriter securityLogWriter = this.services.getSecurityLogWriter();
    if (credentials == null) {
        securityLogWriter.warning(AUTH_PEER_AUTHENTICATION_MISSING_CREDENTIALS, member);
        return AUTH_PEER_AUTHENTICATION_MISSING_CREDENTIALS.toLocalizedString(member);
    }
    String failMsg = null;
    try {
        if (this.securityService.isIntegratedSecurity()) {
            this.securityService.login(credentials);
            this.securityService.authorizeClusterManage();
        } else {
            invokeAuthenticator(secProps, member, credentials);
        }
    } catch (Exception ex) {
        securityLogWriter.warning(AUTH_PEER_AUTHENTICATION_FAILED_WITH_EXCEPTION, new Object[] { member, ex.getLocalizedMessage() }, ex);
        failMsg = AUTH_PEER_AUTHENTICATION_FAILED.toLocalizedString(ex.getLocalizedMessage());
    }
    return failMsg;
}
Also used : InternalLogWriter(org.apache.geode.internal.logging.InternalLogWriter) AuthenticationFailedException(org.apache.geode.security.AuthenticationFailedException) GemFireSecurityException(org.apache.geode.security.GemFireSecurityException)

Example 10 with InternalLogWriter

use of org.apache.geode.internal.logging.InternalLogWriter in project geode by apache.

the class ConnectionNotificationFilterImpl method initLogWriter.

/**
   * Creates a LogWriterI18n for this Agent to use in logging.
   */
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "RV_RETURN_VALUE_IGNORED_BAD_PRACTICE", justification = "Return value for file delete is not important here.")
private void initLogWriter() throws org.apache.geode.admin.AdminException {
    final LogConfig logConfig = this.agentConfig.createLogConfig();
    // LOG: create logWriterAppender here
    this.logWriterAppender = LogWriterAppenders.getOrCreateAppender(LogWriterAppenders.Identifier.MAIN, false, logConfig, false);
    // LOG: look in AgentConfigImpl for existing LogWriter to use
    InternalLogWriter existingLogWriter = this.agentConfig.getInternalLogWriter();
    if (existingLogWriter != null) {
        this.logWriter = existingLogWriter;
    } else {
        // LOG: create LogWriterLogger
        this.logWriter = LogWriterFactory.createLogWriterLogger(false, false, logConfig, false);
        // LOG: changed statement from config to info
        this.logWriter.info(Banner.getString(null));
        // Set this log writer in AgentConfigImpl
        this.agentConfig.setInternalLogWriter(this.logWriter);
    }
    // LOG: create logWriter here
    this.logWriter = LogWriterFactory.createLogWriterLogger(false, false, logConfig, false);
    // Set this log writer in AgentConfig
    this.agentConfig.setInternalLogWriter(this.logWriter);
    // Print Banner information
    logger.info(Banner.getString(this.agentConfig.getOriginalArgs()));
    // LOG:CONFIG: changed next three statements from config to info
    logger.info(LogMarker.CONFIG, LocalizedStrings.AgentImpl_AGENT_CONFIG_PROPERTY_FILE_NAME_0.toLocalizedString(AgentConfigImpl.retrievePropertyFile()));
    logger.info(LogMarker.CONFIG, this.agentConfig.getPropertyFileDescription());
    logger.info(LogMarker.CONFIG, this.agentConfig.toPropertiesAsString());
}
Also used : InternalLogWriter(org.apache.geode.internal.logging.InternalLogWriter) LogConfig(org.apache.geode.internal.logging.LogConfig)

Aggregations

InternalLogWriter (org.apache.geode.internal.logging.InternalLogWriter)10 AuthenticationFailedException (org.apache.geode.security.AuthenticationFailedException)7 EOFException (java.io.EOFException)6 IOException (java.io.IOException)6 AuthenticationRequiredException (org.apache.geode.security.AuthenticationRequiredException)6 GemFireSecurityException (org.apache.geode.security.GemFireSecurityException)5 KeyFactory (java.security.KeyFactory)4 Signature (java.security.Signature)4 X509EncodedKeySpec (java.security.spec.X509EncodedKeySpec)4 GemFireConfigException (org.apache.geode.GemFireConfigException)4 InternalGemFireException (org.apache.geode.InternalGemFireException)4 GatewayConfigurationException (org.apache.geode.cache.GatewayConfigurationException)4 ServerRefusedConnectionException (org.apache.geode.cache.client.ServerRefusedConnectionException)4 Properties (java.util.Properties)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 DataInputStream (java.io.DataInputStream)2 SocketException (java.net.SocketException)2 SocketTimeoutException (java.net.SocketTimeoutException)2 X509Certificate (java.security.cert.X509Certificate)2 Cipher (javax.crypto.Cipher)2