Search in sources :

Example 76 with HeapDataOutputStream

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

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

the class Message method serializeAndAddPartNoCopying.

private void serializeAndAddPartNoCopying(Object o) {
    Version v = this.version;
    if (this.version.equals(Version.CURRENT)) {
        v = null;
    }
    // Create the HDOS with a flag telling it that it can keep any byte[] or ByteBuffers/ByteSources
    // passed to it. Do NOT close the HeapDataOutputStream!
    HeapDataOutputStream hdos = new HeapDataOutputStream(this.chunkSize, v, true);
    try {
        BlobHelper.serializeTo(o, hdos);
    } catch (IOException ex) {
        throw new SerializationException("failed serializing object", ex);
    }
    this.messageModified = true;
    Part part = this.partsList[this.currentPart];
    part.setPartState(hdos, true);
    this.currentPart++;
}
Also used : SerializationException(org.apache.geode.SerializationException) Version(org.apache.geode.internal.Version) HeapDataOutputStream(org.apache.geode.internal.HeapDataOutputStream) IOException(java.io.IOException)

Example 78 with HeapDataOutputStream

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

the class Message method addStringPart.

public void addStringPart(String str, boolean enableCaching) {
    if (str == null) {
        addRawPart(null, false);
        return;
    }
    Part part = this.partsList[this.currentPart];
    if (enableCaching) {
        byte[] bytes = CACHED_STRINGS.get(str);
        if (bytes == null) {
            try (HeapDataOutputStream hdos = new HeapDataOutputStream(str)) {
                bytes = hdos.toByteArray();
                CACHED_STRINGS.put(str, bytes);
            }
        }
        part.setPartState(bytes, false);
    } else {
        // do NOT close the HeapDataOutputStream
        this.messageModified = true;
        part.setPartState(new HeapDataOutputStream(str), false);
    }
    this.currentPart++;
}
Also used : HeapDataOutputStream(org.apache.geode.internal.HeapDataOutputStream)

Example 79 with HeapDataOutputStream

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

the class OffHeapStoredObject method sendTo.

@Override
public void sendTo(DataOutput out) throws IOException {
    if (!this.isCompressed() && out instanceof HeapDataOutputStream) {
        ByteBuffer bb = createDirectByteBuffer();
        if (bb != null) {
            HeapDataOutputStream hdos = (HeapDataOutputStream) out;
            if (this.isSerialized()) {
                hdos.write(bb);
            } else {
                hdos.writeByte(DSCODE.BYTE_ARRAY);
                InternalDataSerializer.writeArrayLength(bb.remaining(), hdos);
                hdos.write(bb);
            }
            return;
        }
    }
    super.sendTo(out);
}
Also used : HeapDataOutputStream(org.apache.geode.internal.HeapDataOutputStream) ByteBuffer(java.nio.ByteBuffer)

Example 80 with HeapDataOutputStream

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

the class NWayMergeResults method toData.

// TODO : optimize for struct elements , by directly writing the fields
// instead
// of struct
@Override
public void toData(DataOutput out) throws IOException {
    boolean isStruct = this.collectionType.getElementType().isStructType();
    DataSerializer.writeObject(this.collectionType.getElementType(), out);
    DataSerializer.writePrimitiveBoolean(this.isDistinct, out);
    HeapDataOutputStream hdos = new HeapDataOutputStream(1024, null);
    LongUpdater lu = hdos.reserveLong();
    Iterator<E> iter = this.iterator();
    int numElements = 0;
    while (iter.hasNext()) {
        E data = iter.next();
        if (isStruct) {
            Object[] fields = ((Struct) data).getFieldValues();
            DataSerializer.writeObjectArray(fields, out);
        } else {
            DataSerializer.writeObject(data, hdos);
        }
        ++numElements;
    }
    lu.update(numElements);
    hdos.sendTo(out);
}
Also used : LongUpdater(org.apache.geode.internal.HeapDataOutputStream.LongUpdater) HeapDataOutputStream(org.apache.geode.internal.HeapDataOutputStream) Struct(org.apache.geode.cache.query.Struct)

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