Search in sources :

Example 71 with HeapDataOutputStream

use of org.apache.geode.internal.HeapDataOutputStream in project geode by apache.

the class FilterPreAuthorization method authorizeOperation.

public boolean authorizeOperation(String regionName, OperationContext context) {
    assert !context.isPostOperation();
    OperationCode opCode = context.getOperationCode();
    if (opCode.isPut()) {
        PutOperationContext createContext = (PutOperationContext) context;
        // byte[] serializedValue = createContext.getSerializedValue();
        byte[] serializedValue = null;
        Object value = createContext.getValue();
        int valLength;
        byte lastByte;
        if (value == null) {
            // This means serializedValue too is null.
            valLength = 0;
            lastByte = 0;
        } else {
            if (value instanceof byte[]) {
                serializedValue = (byte[]) value;
                valLength = serializedValue.length;
                lastByte = serializedValue[valLength - 1];
            } else {
                ObjectWithAuthz authzObj = new ObjectWithAuthz(value, Integer.valueOf(value.hashCode()));
                createContext.setValue(authzObj, true);
                return true;
            }
        }
        HeapDataOutputStream hos = new HeapDataOutputStream(valLength + 32, Version.CURRENT);
        try {
            InternalDataSerializer.writeUserDataSerializableHeader(ObjectWithAuthz.CLASSID, hos);
            if (serializedValue != null) {
                hos.write(serializedValue);
            }
            // Some value that determines the Principals that can get this object.
            Integer allowedIndex = Integer.valueOf(lastByte);
            DataSerializer.writeObject(allowedIndex, hos);
        } catch (Exception ex) {
            return false;
        }
        createContext.setSerializedValue(hos.toByteArray(), true);
        if (this.logger.fineEnabled())
            this.logger.fine("FilterPreAuthorization: added authorization " + "info for key: " + createContext.getKey());
    } else if (opCode.isPutAll()) {
        PutAllOperationContext createContext = (PutAllOperationContext) context;
        Map map = createContext.getMap();
        Collection entries = map.entrySet();
        Iterator iterator = entries.iterator();
        Map.Entry mapEntry = null;
        while (iterator.hasNext()) {
            mapEntry = (Map.Entry) iterator.next();
            String currkey = (String) mapEntry.getKey();
            Object value = mapEntry.getValue();
            Integer authCode;
            if (value != null) {
                String valStr = value.toString();
                authCode = (int) valStr.charAt(valStr.length() - 1);
            } else {
                authCode = 0;
            }
            ObjectWithAuthz authzObj = new ObjectWithAuthz(value, authCode);
            mapEntry.setValue(authzObj);
            if (this.logger.fineEnabled())
                this.logger.fine("FilterPreAuthorization: putAll: added authorization " + "info for key: " + currkey);
        }
    // Now each of the map's values have become ObjectWithAuthz
    }
    return true;
}
Also used : OperationCode(org.apache.geode.cache.operations.OperationContext.OperationCode) NotAuthorizedException(org.apache.geode.security.NotAuthorizedException) PutAllOperationContext(org.apache.geode.cache.operations.PutAllOperationContext) HeapDataOutputStream(org.apache.geode.internal.HeapDataOutputStream) Iterator(java.util.Iterator) Collection(java.util.Collection) PutOperationContext(org.apache.geode.cache.operations.PutOperationContext) HashMap(java.util.HashMap) Map(java.util.Map)

Example 72 with HeapDataOutputStream

use of org.apache.geode.internal.HeapDataOutputStream in project geode by apache.

the class GMSMemberJUnitTest method testGMSMemberBackwardCompatibility.

/**
   * <p>
   * GEODE-2875 - adds vmKind to on-wire form of GMSMember.writeEssentialData
   * </p>
   * <p>
   * This must be backward-compatible with Geode 1.0 (Version.GFE_90)
   * </p>
   * 
   * @throws Exception
   */
@Test
public void testGMSMemberBackwardCompatibility() throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    MemberAttributes attributes = new MemberAttributes(10, 20, 1, 2, "member", null, null);
    GMSMember member = new GMSMember();
    member.setAttributes(attributes);
    DataOutput dataOutput = new DataOutputStream(baos);
    member.writeEssentialData(dataOutput);
    // vmKind should be transmitted to a member with the current version
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    DataInput dataInput = new DataInputStream(bais);
    GMSMember newMember = new GMSMember();
    newMember.readEssentialData(dataInput);
    assertEquals(1, newMember.getVmKind());
    // vmKind should not be transmitted to a member with version GFE_90 or earlier
    dataOutput = new HeapDataOutputStream(Version.GFE_90);
    member.writeEssentialData(dataOutput);
    bais = new ByteArrayInputStream(baos.toByteArray());
    dataInput = new VersionedDataInputStream(new DataInputStream(bais), Version.GFE_90);
    newMember = new GMSMember();
    newMember.readEssentialData(dataInput);
    assertEquals(0, newMember.getVmKind());
}
Also used : DataInput(java.io.DataInput) DataOutput(java.io.DataOutput) MemberAttributes(org.apache.geode.distributed.internal.membership.MemberAttributes) ByteArrayInputStream(java.io.ByteArrayInputStream) DataOutputStream(java.io.DataOutputStream) HeapDataOutputStream(org.apache.geode.internal.HeapDataOutputStream) HeapDataOutputStream(org.apache.geode.internal.HeapDataOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DataInputStream(java.io.DataInputStream) VersionedDataInputStream(org.apache.geode.internal.VersionedDataInputStream) VersionedDataInputStream(org.apache.geode.internal.VersionedDataInputStream) SecurityTest(org.apache.geode.test.junit.categories.SecurityTest) Test(org.junit.Test) UnitTest(org.apache.geode.test.junit.categories.UnitTest)

Example 73 with HeapDataOutputStream

use of org.apache.geode.internal.HeapDataOutputStream in project geode by apache.

the class ServerHandShakeProcessor method writeServerMember.

// Keep the writeServerMember/readServerMember compatible with C++ native
// client
protected static void writeServerMember(DistributedMember member, DataOutputStream dos) throws IOException {
    Version v = Version.CURRENT;
    if (dos instanceof VersionedDataStream) {
        v = ((VersionedDataStream) dos).getVersion();
    }
    HeapDataOutputStream hdos = new HeapDataOutputStream(v);
    DataSerializer.writeObject(member, hdos);
    DataSerializer.writeByteArray(hdos.toByteArray(), dos);
    hdos.close();
}
Also used : Version(org.apache.geode.internal.Version) VersionedDataStream(org.apache.geode.internal.VersionedDataStream) HeapDataOutputStream(org.apache.geode.internal.HeapDataOutputStream)

Example 74 with HeapDataOutputStream

use of org.apache.geode.internal.HeapDataOutputStream 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 75 with HeapDataOutputStream

use of org.apache.geode.internal.HeapDataOutputStream in project geode by apache.

the class ServerHandShakeProcessor method refuse.

/**
   * Refuse a received handshake.
   * 
   * @param out the Stream to the waiting greeter.
   * @param message providing details about the refusal reception, mainly for client logging.
   * @param exception providing details about exception occurred.
   * @throws IOException
   */
public static void refuse(OutputStream out, String message, byte exception) throws IOException {
    HeapDataOutputStream hdos = new HeapDataOutputStream(32, Version.CURRENT);
    DataOutputStream dos = new DataOutputStream(hdos);
    // Write refused reply
    dos.writeByte(exception);
    // write dummy epType
    dos.writeByte(0);
    // write dummy qSize
    dos.writeInt(0);
    // Write the server's member
    DistributedMember member = InternalDistributedSystem.getAnyInstance().getDistributedMember();
    writeServerMember(member, dos);
    // Write the refusal message
    if (message == null) {
        message = "";
    }
    dos.writeUTF(message);
    // Write dummy delta-propagation property value. This will never be read at
    // receiver because the exception byte above will cause the receiver code
    // throw an exception before the below byte could be read.
    dos.writeBoolean(Boolean.TRUE);
    out.write(hdos.toByteArray());
    out.flush();
}
Also used : HeapDataOutputStream(org.apache.geode.internal.HeapDataOutputStream) DataOutputStream(java.io.DataOutputStream) HeapDataOutputStream(org.apache.geode.internal.HeapDataOutputStream) DistributedMember(org.apache.geode.distributed.DistributedMember)

Aggregations

HeapDataOutputStream (org.apache.geode.internal.HeapDataOutputStream)134 Test (org.junit.Test)55 IOException (java.io.IOException)40 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)36 SerializationTest (org.apache.geode.test.junit.categories.SerializationTest)33 DataInputStream (java.io.DataInputStream)29 ByteArrayInputStream (java.io.ByteArrayInputStream)23 UnitTest (org.apache.geode.test.junit.categories.UnitTest)15 DiskAccessException (org.apache.geode.cache.DiskAccessException)12 InternalDistributedMember (org.apache.geode.distributed.internal.membership.InternalDistributedMember)11 PdxSerializerObject (org.apache.geode.internal.PdxSerializerObject)10 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)8 Version (org.apache.geode.internal.Version)8 DataInput (java.io.DataInput)7 SerializableCallable (org.apache.geode.test.dunit.SerializableCallable)7 OutputStream (java.io.OutputStream)6 Properties (java.util.Properties)6 ByteBuffer (java.nio.ByteBuffer)5 HashMap (java.util.HashMap)5 InternalGemFireException (org.apache.geode.InternalGemFireException)5