Search in sources :

Example 11 with GemFireSecurityException

use of org.apache.geode.security.GemFireSecurityException in project geode by apache.

the class SecurityService method getObjectOfTypeFromFactoryMethod.

/**
   * this method would never return null, it either throws an exception or returns an object
   */
public static <T> T getObjectOfTypeFromFactoryMethod(String factoryMethodName, Class<T> expectedClazz) {
    T actualObject = null;
    try {
        Method factoryMethod = ClassLoadUtil.methodFromName(factoryMethodName);
        actualObject = (T) factoryMethod.invoke(null, (Object[]) null);
    } catch (Exception e) {
        throw new GemFireSecurityException("Instance could not be obtained from " + factoryMethodName, e);
    }
    if (actualObject == null) {
        throw new GemFireSecurityException("Instance could not be obtained from " + factoryMethodName);
    }
    return actualObject;
}
Also used : GemFireSecurityException(org.apache.geode.security.GemFireSecurityException) Method(java.lang.reflect.Method) GemFireSecurityException(org.apache.geode.security.GemFireSecurityException)

Example 12 with GemFireSecurityException

use of org.apache.geode.security.GemFireSecurityException in project geode by apache.

the class HandShake method readCredentials.

// This assumes that authentication is the last piece of info in handshake
public static Properties readCredentials(DataInputStream dis, DataOutputStream dos, DistributedSystem system) throws GemFireSecurityException, IOException {
    boolean requireAuthentication = securityService.isClientSecurityRequired();
    Properties credentials = null;
    try {
        byte secureMode = dis.readByte();
        throwIfMissingRequiredCredentials(requireAuthentication, secureMode != CREDENTIALS_NONE);
        if (secureMode == CREDENTIALS_NORMAL) {
            if (requireAuthentication) {
                credentials = DataSerializer.readProperties(dis);
            } else {
                // ignore the credentials
                DataSerializer.readProperties(dis);
            }
        } else if (secureMode == CREDENTIALS_DHENCRYPT) {
            boolean sendAuthentication = dis.readBoolean();
            InternalLogWriter securityLogWriter = (InternalLogWriter) system.getSecurityLogWriter();
            // Get the symmetric encryption algorithm to be used
            String skAlgo = DataSerializer.readString(dis);
            // Get the public key of the other side
            byte[] keyBytes = DataSerializer.readByteArray(dis);
            byte[] challenge = null;
            PublicKey pubKey = null;
            if (requireAuthentication) {
                // Generate PublicKey from encoded form
                X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
                KeyFactory keyFact = KeyFactory.getInstance("DH");
                pubKey = keyFact.generatePublic(x509KeySpec);
                // Send the public key to other side
                keyBytes = dhPublicKey.getEncoded();
                challenge = new byte[64];
                random.nextBytes(challenge);
                // sign the challenge from client.
                if (sendAuthentication) {
                    // Get the challenge string from client
                    byte[] clientChallenge = DataSerializer.readByteArray(dis);
                    if (privateKeyEncrypt == null) {
                        throw new AuthenticationFailedException(LocalizedStrings.HandShake_SERVER_PRIVATE_KEY_NOT_AVAILABLE_FOR_CREATING_SIGNATURE.toLocalizedString());
                    }
                    // Sign the challenge from client and send it to the client
                    Signature sig = Signature.getInstance(privateKeySignAlgo);
                    sig.initSign(privateKeyEncrypt);
                    sig.update(clientChallenge);
                    byte[] signedBytes = sig.sign();
                    dos.writeByte(REPLY_OK);
                    DataSerializer.writeByteArray(keyBytes, dos);
                    // DataSerializer.writeString(privateKeyAlias, dos);
                    DataSerializer.writeString(privateKeySubject, dos);
                    DataSerializer.writeByteArray(signedBytes, dos);
                    securityLogWriter.fine("HandShake: sent the signed client challenge");
                } else {
                    // These two lines should not be moved before the if{} statement in
                    // a common block for both if...then...else parts. This is to handle
                    // the case when an AuthenticationFailedException is thrown by the
                    // if...then part when sending the signature.
                    dos.writeByte(REPLY_OK);
                    DataSerializer.writeByteArray(keyBytes, dos);
                }
                // Now send the server challenge
                DataSerializer.writeByteArray(challenge, dos);
                securityLogWriter.fine("HandShake: sent the public key and challenge");
                dos.flush();
                // Read and decrypt the credentials
                byte[] encBytes = DataSerializer.readByteArray(dis);
                KeyAgreement ka = KeyAgreement.getInstance("DH");
                ka.init(dhPrivateKey);
                ka.doPhase(pubKey, true);
                Cipher decrypt;
                int keysize = getKeySize(skAlgo);
                int blocksize = getBlockSize(skAlgo);
                if (keysize == -1 || blocksize == -1) {
                    SecretKey sKey = ka.generateSecret(skAlgo);
                    decrypt = Cipher.getInstance(skAlgo);
                    decrypt.init(Cipher.DECRYPT_MODE, sKey);
                } else {
                    String algoStr = getDhAlgoStr(skAlgo);
                    byte[] sKeyBytes = ka.generateSecret();
                    SecretKeySpec sks = new SecretKeySpec(sKeyBytes, 0, keysize, algoStr);
                    IvParameterSpec ivps = new IvParameterSpec(sKeyBytes, keysize, blocksize);
                    decrypt = Cipher.getInstance(algoStr + "/CBC/PKCS5Padding");
                    decrypt.init(Cipher.DECRYPT_MODE, sks, ivps);
                }
                byte[] credentialBytes = decrypt.doFinal(encBytes);
                ByteArrayInputStream bis = new ByteArrayInputStream(credentialBytes);
                DataInputStream dinp = new DataInputStream(bis);
                credentials = DataSerializer.readProperties(dinp);
                byte[] challengeRes = DataSerializer.readByteArray(dinp);
                // Check the challenge string
                if (!Arrays.equals(challenge, challengeRes)) {
                    throw new AuthenticationFailedException(LocalizedStrings.HandShake_MISMATCH_IN_CHALLENGE_BYTES_MALICIOUS_CLIENT.toLocalizedString());
                }
                dinp.close();
            } else {
                if (sendAuthentication) {
                    // Read and ignore the client challenge
                    DataSerializer.readByteArray(dis);
                }
                dos.writeByte(REPLY_AUTH_NOT_REQUIRED);
                dos.flush();
            }
        } else if (secureMode == SECURITY_MULTIUSER_NOTIFICATIONCHANNEL) {
            // hitesh there will be no credential CCP will get credential(Principal) using
            // ServerConnection..
            logger.debug("readCredential where multiuser mode creating callback connection");
        }
    } catch (IOException ex) {
        throw ex;
    } catch (GemFireSecurityException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new AuthenticationFailedException(LocalizedStrings.HandShake_FAILURE_IN_READING_CREDENTIALS.toLocalizedString(), ex);
    }
    return credentials;
}
Also used : InternalLogWriter(org.apache.geode.internal.logging.InternalLogWriter) AuthenticationFailedException(org.apache.geode.security.AuthenticationFailedException) PublicKey(java.security.PublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) IOException(java.io.IOException) Properties(java.util.Properties) VersionedDataInputStream(org.apache.geode.internal.VersionedDataInputStream) DataInputStream(java.io.DataInputStream) 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) SecretKey(javax.crypto.SecretKey) GemFireSecurityException(org.apache.geode.security.GemFireSecurityException) ByteArrayInputStream(java.io.ByteArrayInputStream) SecretKeySpec(javax.crypto.spec.SecretKeySpec) Signature(java.security.Signature) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) KeyAgreement(javax.crypto.KeyAgreement) KeyFactory(java.security.KeyFactory)

Example 13 with GemFireSecurityException

use of org.apache.geode.security.GemFireSecurityException in project geode by apache.

the class HandShake method getCredentials.

public static Properties getCredentials(String authInitMethod, Properties securityProperties, DistributedMember server, boolean isPeer, InternalLogWriter logWriter, InternalLogWriter securityLogWriter) throws AuthenticationRequiredException {
    Properties credentials = null;
    // if no authInit, Try to extract the credentials directly from securityProps
    if (StringUtils.isBlank(authInitMethod)) {
        return SecurityService.getCredentials(securityProperties);
    }
    // if authInit exists
    try {
        AuthInitialize auth = SecurityService.getObjectOfType(authInitMethod, AuthInitialize.class);
        auth.init(logWriter, securityLogWriter);
        try {
            credentials = auth.getCredentials(securityProperties, server, isPeer);
        } finally {
            auth.close();
        }
    } catch (GemFireSecurityException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new AuthenticationRequiredException(LocalizedStrings.HandShake_FAILED_TO_ACQUIRE_AUTHINITIALIZE_METHOD_0.toLocalizedString(authInitMethod), ex);
    }
    return credentials;
}
Also used : GemFireSecurityException(org.apache.geode.security.GemFireSecurityException) AuthenticationRequiredException(org.apache.geode.security.AuthenticationRequiredException) Properties(java.util.Properties) 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) AuthInitialize(org.apache.geode.security.AuthInitialize)

Example 14 with GemFireSecurityException

use of org.apache.geode.security.GemFireSecurityException in project geode by apache.

the class HandShake method readCredential.

// This assumes that authentication is the last piece of info in handshake
public Properties readCredential(DataInputStream dis, DataOutputStream dos, DistributedSystem system) throws GemFireSecurityException, IOException {
    Properties credentials = null;
    boolean requireAuthentication = securityService.isClientSecurityRequired();
    try {
        byte secureMode = dis.readByte();
        throwIfMissingRequiredCredentials(requireAuthentication, secureMode != CREDENTIALS_NONE);
        if (secureMode == CREDENTIALS_NORMAL) {
            this.appSecureMode = CREDENTIALS_NORMAL;
        /*
         * if (requireAuthentication) { credentials = DataSerializer.readProperties(dis); } else {
         * DataSerializer.readProperties(dis); // ignore the credentials }
         */
        } else if (secureMode == CREDENTIALS_DHENCRYPT) {
            this.appSecureMode = CREDENTIALS_DHENCRYPT;
            boolean sendAuthentication = dis.readBoolean();
            InternalLogWriter securityLogWriter = (InternalLogWriter) system.getSecurityLogWriter();
            // Get the symmetric encryption algorithm to be used
            // String skAlgo = DataSerializer.readString(dis);
            this.clientSKAlgo = DataSerializer.readString(dis);
            // Get the public key of the other side
            byte[] keyBytes = DataSerializer.readByteArray(dis);
            byte[] challenge = null;
            // PublicKey pubKey = null;
            if (requireAuthentication) {
                // Generate PublicKey from encoded form
                X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
                KeyFactory keyFact = KeyFactory.getInstance("DH");
                this.clientPublicKey = keyFact.generatePublic(x509KeySpec);
                // Send the public key to other side
                keyBytes = dhPublicKey.getEncoded();
                challenge = new byte[64];
                random.nextBytes(challenge);
                // sign the challenge from client.
                if (sendAuthentication) {
                    // Get the challenge string from client
                    byte[] clientChallenge = DataSerializer.readByteArray(dis);
                    if (privateKeyEncrypt == null) {
                        throw new AuthenticationFailedException(LocalizedStrings.HandShake_SERVER_PRIVATE_KEY_NOT_AVAILABLE_FOR_CREATING_SIGNATURE.toLocalizedString());
                    }
                    // Sign the challenge from client and send it to the client
                    Signature sig = Signature.getInstance(privateKeySignAlgo);
                    sig.initSign(privateKeyEncrypt);
                    sig.update(clientChallenge);
                    byte[] signedBytes = sig.sign();
                    dos.writeByte(REPLY_OK);
                    DataSerializer.writeByteArray(keyBytes, dos);
                    // DataSerializer.writeString(privateKeyAlias, dos);
                    DataSerializer.writeString(privateKeySubject, dos);
                    DataSerializer.writeByteArray(signedBytes, dos);
                    securityLogWriter.fine("HandShake: sent the signed client challenge");
                } else {
                    // These two lines should not be moved before the if{} statement in
                    // a common block for both if...then...else parts. This is to handle
                    // the case when an AuthenticationFailedException is thrown by the
                    // if...then part when sending the signature.
                    dos.writeByte(REPLY_OK);
                    DataSerializer.writeByteArray(keyBytes, dos);
                }
                // Now send the server challenge
                DataSerializer.writeByteArray(challenge, dos);
                securityLogWriter.fine("HandShake: sent the public key and challenge");
                dos.flush();
                // Read and decrypt the credentials
                byte[] encBytes = DataSerializer.readByteArray(dis);
                Cipher c = getDecryptCipher(this.clientSKAlgo, this.clientPublicKey);
                byte[] credentialBytes = decryptBytes(encBytes, c);
                ByteArrayInputStream bis = new ByteArrayInputStream(credentialBytes);
                DataInputStream dinp = new DataInputStream(bis);
                // credentials = DataSerializer.readProperties(dinp);//Hitesh: we don't send in handshake
                // now
                byte[] challengeRes = DataSerializer.readByteArray(dinp);
                // Check the challenge string
                if (!Arrays.equals(challenge, challengeRes)) {
                    throw new AuthenticationFailedException(LocalizedStrings.HandShake_MISMATCH_IN_CHALLENGE_BYTES_MALICIOUS_CLIENT.toLocalizedString());
                }
                dinp.close();
            } else {
                if (sendAuthentication) {
                    // Read and ignore the client challenge
                    DataSerializer.readByteArray(dis);
                }
                dos.writeByte(REPLY_AUTH_NOT_REQUIRED);
                dos.flush();
            }
        }
    } catch (IOException ex) {
        throw ex;
    } catch (GemFireSecurityException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new AuthenticationFailedException(LocalizedStrings.HandShake_FAILURE_IN_READING_CREDENTIALS.toLocalizedString(), ex);
    }
    return credentials;
}
Also used : InternalLogWriter(org.apache.geode.internal.logging.InternalLogWriter) AuthenticationFailedException(org.apache.geode.security.AuthenticationFailedException) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) IOException(java.io.IOException) Properties(java.util.Properties) VersionedDataInputStream(org.apache.geode.internal.VersionedDataInputStream) DataInputStream(java.io.DataInputStream) 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) ByteArrayInputStream(java.io.ByteArrayInputStream) Signature(java.security.Signature) Cipher(javax.crypto.Cipher) KeyFactory(java.security.KeyFactory)

Example 15 with GemFireSecurityException

use of org.apache.geode.security.GemFireSecurityException in project geode by apache.

the class GMSJoinLeave method attemptToJoin.

/**
   * send a join request and wait for a reply. Process the reply. This may throw a
   * SystemConnectException or an AuthenticationFailedException
   *
   * @return true if the attempt succeeded, false if it timed out
   */
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "WA_NOT_IN_LOOP")
boolean attemptToJoin() {
    SearchState state = searchState;
    // send a join request to the coordinator and wait for a response
    InternalDistributedMember coord = state.possibleCoordinator;
    if (state.alreadyTried.contains(coord)) {
        logger.info("Probable coordinator is still {} - waiting for a join-response", coord);
    } else {
        logger.info("Attempting to join the distributed system through coordinator " + coord + " using address " + this.localAddress);
        int port = services.getHealthMonitor().getFailureDetectionPort();
        JoinRequestMessage req = new JoinRequestMessage(coord, this.localAddress, services.getAuthenticator().getCredentials(coord), port, services.getMessenger().getRequestId());
        // services.getMessenger().send(req, state.view);
        services.getMessenger().send(req);
    }
    JoinResponseMessage response;
    try {
        response = waitForJoinResponse();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        return false;
    }
    if (response == null) {
        if (!isJoined) {
            logger.debug("received no join response");
        }
        return isJoined;
    }
    logger.debug("received join response {}", response);
    joinResponse[0] = null;
    String failReason = response.getRejectionMessage();
    if (failReason != null) {
        if (failReason.contains("Rejecting the attempt of a member using an older version") || failReason.contains("15806")) {
            throw new SystemConnectException(failReason);
        } else if (failReason.contains("Failed to find credentials")) {
            throw new AuthenticationRequiredException(failReason);
        }
        throw new GemFireSecurityException(failReason);
    }
    // there is no way we can rech here right now
    throw new RuntimeException("Join Request Failed with response " + joinResponse[0]);
}
Also used : GemFireSecurityException(org.apache.geode.security.GemFireSecurityException) InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) JoinResponseMessage(org.apache.geode.distributed.internal.membership.gms.messages.JoinResponseMessage) AuthenticationRequiredException(org.apache.geode.security.AuthenticationRequiredException) JoinRequestMessage(org.apache.geode.distributed.internal.membership.gms.messages.JoinRequestMessage) SystemConnectException(org.apache.geode.SystemConnectException)

Aggregations

GemFireSecurityException (org.apache.geode.security.GemFireSecurityException)39 IOException (java.io.IOException)18 GemFireConfigException (org.apache.geode.GemFireConfigException)13 CancelException (org.apache.geode.CancelException)9 LocalRegion (org.apache.geode.internal.cache.LocalRegion)8 Part (org.apache.geode.internal.cache.tier.sockets.Part)8 AuthenticationRequiredException (org.apache.geode.security.AuthenticationRequiredException)8 GatewayConfigurationException (org.apache.geode.cache.GatewayConfigurationException)7 RegionDestroyedException (org.apache.geode.cache.RegionDestroyedException)7 ServerRefusedConnectionException (org.apache.geode.cache.client.ServerRefusedConnectionException)7 ServerLocation (org.apache.geode.distributed.internal.ServerLocation)7 CacheServerStats (org.apache.geode.internal.cache.tier.sockets.CacheServerStats)7 AuthenticationFailedException (org.apache.geode.security.AuthenticationFailedException)7 EOFException (java.io.EOFException)6 ByteBuffer (java.nio.ByteBuffer)6 Properties (java.util.Properties)6 InternalGemFireException (org.apache.geode.InternalGemFireException)5 EventID (org.apache.geode.internal.cache.EventID)5 EventIDHolder (org.apache.geode.internal.cache.EventIDHolder)5 CachedRegionHelper (org.apache.geode.internal.cache.tier.CachedRegionHelper)5