Search in sources :

Example 71 with BufferUnderflowException

use of java.nio.BufferUnderflowException in project android_frameworks_base by DirtyUnicorns.

the class ApkSignatureSchemeV2Verifier method verify.

/**
     * Verifies the contents of the provided APK file against the provided APK Signature Scheme v2
     * Block.
     *
     * @param signatureInfo APK Signature Scheme v2 Block and information relevant for verifying it
     *        against the APK file.
     */
private static X509Certificate[][] verify(FileDescriptor apkFileDescriptor, SignatureInfo signatureInfo) throws SecurityException {
    int signerCount = 0;
    Map<Integer, byte[]> contentDigests = new ArrayMap<>();
    List<X509Certificate[]> signerCerts = new ArrayList<>();
    CertificateFactory certFactory;
    try {
        certFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new RuntimeException("Failed to obtain X.509 CertificateFactory", e);
    }
    ByteBuffer signers;
    try {
        signers = getLengthPrefixedSlice(signatureInfo.signatureBlock);
    } catch (IOException e) {
        throw new SecurityException("Failed to read list of signers", e);
    }
    while (signers.hasRemaining()) {
        signerCount++;
        try {
            ByteBuffer signer = getLengthPrefixedSlice(signers);
            X509Certificate[] certs = verifySigner(signer, contentDigests, certFactory);
            signerCerts.add(certs);
        } catch (IOException | BufferUnderflowException | SecurityException e) {
            throw new SecurityException("Failed to parse/verify signer #" + signerCount + " block", e);
        }
    }
    if (signerCount < 1) {
        throw new SecurityException("No signers found");
    }
    if (contentDigests.isEmpty()) {
        throw new SecurityException("No content digests found");
    }
    verifyIntegrity(contentDigests, apkFileDescriptor, signatureInfo.apkSigningBlockOffset, signatureInfo.centralDirOffset, signatureInfo.eocdOffset, signatureInfo.eocd);
    return signerCerts.toArray(new X509Certificate[signerCerts.size()][]);
}
Also used : ArrayList(java.util.ArrayList) ArrayMap(android.util.ArrayMap) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) CertificateFactory(java.security.cert.CertificateFactory) DirectByteBuffer(java.nio.DirectByteBuffer) ByteBuffer(java.nio.ByteBuffer) X509Certificate(java.security.cert.X509Certificate) BigInteger(java.math.BigInteger) BufferUnderflowException(java.nio.BufferUnderflowException)

Example 72 with BufferUnderflowException

use of java.nio.BufferUnderflowException in project opennms by OpenNMS.

the class TrivialTimeMonitor method pollTimeUdp.

/**
 * <p>pollTimeUdp</p>
 *
 * @param svc a {@link org.opennms.netmgt.poller.MonitoredService} object.
 * @param parameters a {@link java.util.Map} object.
 * @param serviceStatus a {@link org.opennms.netmgt.poller.PollStatus} object.
 * @param tracker a {@link org.opennms.core.utils.TimeoutTracker} object.
 * @param ipv4Addr a {@link java.net.InetAddress} object.
 * @param port a int.
 * @param allowedSkew a int.
 * @param persistSkew a boolean.
 * @return a {@link org.opennms.netmgt.poller.PollStatus} object.
 */
public PollStatus pollTimeUdp(MonitoredService svc, Map<String, Object> parameters, PollStatus serviceStatus, TimeoutTracker tracker, InetAddress ipv4Addr, int port, int allowedSkew, boolean persistSkew) {
    int localTime = 0;
    int remoteTime = 0;
    boolean gotTime = false;
    for (tracker.reset(); tracker.shouldRetry() && !gotTime; tracker.nextAttempt()) {
        DatagramSocket socket = null;
        final String hostAddress = InetAddressUtils.str(ipv4Addr);
        try {
            tracker.startAttempt();
            socket = new DatagramSocket();
            socket.setSoTimeout(tracker.getSoTimeout());
            LOG.debug("Requesting time from host: {} on UDP port: {}", ipv4Addr, port);
            // 
            // Send an empty datagram per RFC868
            // 
            socket.send(new DatagramPacket(new byte[] {}, 0, ipv4Addr, port));
            // 
            // Try to receive a response from the remote socket
            // 
            byte[] timeBytes = new byte[4];
            ByteBuffer timeByteBuffer = ByteBuffer.wrap(timeBytes);
            DatagramPacket timePacket = new DatagramPacket(timeBytes, timeBytes.length, ipv4Addr, port);
            socket.receive(timePacket);
            int bytesRead = timePacket.getLength();
            if (bytesRead != 4)
                continue;
            LOG.debug("pollTimeUdp: bytes read = {}", bytesRead);
            try {
                remoteTime = timeByteBuffer.getInt();
            } catch (BufferUnderflowException bue) {
                LOG.error("Encountered buffer underflow while reading time from remote socket.");
                remoteTime = 0;
                serviceStatus = PollStatus.unavailable("Failed to read a valid time from remote host.");
                // to next iteration of for() loop
                continue;
            }
            localTime = (int) (System.currentTimeMillis() / 1000) - EPOCH_ADJ_FACTOR;
            gotTime = true;
            serviceStatus = qualifyTime(remoteTime, localTime, allowedSkew, serviceStatus, tracker.elapsedTimeInMillis(), persistSkew);
        } catch (PortUnreachableException e) {
            String reason = "Port unreachable exception for address " + hostAddress;
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } catch (NoRouteToHostException e) {
            String reason = "No route to host exception for address " + hostAddress;
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } catch (InterruptedIOException e) {
            String reason = "did not connect to host with " + tracker;
            LOG.debug(reason);
            serviceStatus = PollStatus.unavailable(reason);
        } catch (IOException e) {
            String reason = "IOException while polling address: " + ipv4Addr;
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } finally {
            if (socket != null)
                socket.close();
        }
    }
    return serviceStatus;
}
Also used : InterruptedIOException(java.io.InterruptedIOException) PortUnreachableException(java.net.PortUnreachableException) DatagramSocket(java.net.DatagramSocket) DatagramPacket(java.net.DatagramPacket) IOException(java.io.IOException) InterruptedIOException(java.io.InterruptedIOException) ByteBuffer(java.nio.ByteBuffer) NoRouteToHostException(java.net.NoRouteToHostException) BufferUnderflowException(java.nio.BufferUnderflowException)

Example 73 with BufferUnderflowException

use of java.nio.BufferUnderflowException in project jvm-tools by aragozin.

the class PagedVirtualMemory method readBytes.

public void readBytes(long position, byte[] chars) {
    try {
        ByteBuffer buf = ensureBuffer(position);
        buf.position((int) (position & pageMask));
        buf.get(chars);
        buf.position(0);
    } catch (IndexOutOfBoundsException e) {
        readSafe(position, chars, chars.length);
    } catch (BufferUnderflowException e) {
        readSafe(position, chars, chars.length);
    }
}
Also used : ByteBuffer(java.nio.ByteBuffer) BufferUnderflowException(java.nio.BufferUnderflowException)

Example 74 with BufferUnderflowException

use of java.nio.BufferUnderflowException in project jetty.project by eclipse.

the class BadDualDecoder method decode.

@Override
public Fruit decode(ByteBuffer bytes) throws DecodeException {
    try {
        int id = bytes.get(bytes.position());
        if (id != FruitBinaryEncoder.FRUIT_ID_BYTE) {
            // not a binary fruit object
            throw new DecodeException(bytes, "Not an encoded Binary Fruit object");
        }
        Fruit fruit = new Fruit();
        fruit.name = getUTF8String(bytes);
        fruit.color = getUTF8String(bytes);
        return fruit;
    } catch (BufferUnderflowException e) {
        throw new DecodeException(bytes, "Unable to read Fruit from binary message", e);
    }
}
Also used : Fruit(org.eclipse.jetty.websocket.jsr356.samples.Fruit) DecodeException(javax.websocket.DecodeException) BufferUnderflowException(java.nio.BufferUnderflowException)

Example 75 with BufferUnderflowException

use of java.nio.BufferUnderflowException in project jvm-serializers by eishay.

the class MediaContent method unmarshal.

/**
	 * Deserializes the object.
	 * @param buf the data source.
	 * @param offset the initial index for {@code buf}, inclusive.
	 * @return the final index for {@code buf}, exclusive.
	 * @throws BufferUnderflowException when {@code buf} is incomplete. (EOF)
	 * @throws SecurityException on an upper limit breach defined by either {@link #colferSizeMax} or {@link #colferListMax}.
	 * @throws InputMismatchException when the data does not match this object's schema.
	 */
public int unmarshal(byte[] buf, int offset) {
    int i = offset;
    try {
        byte header = buf[i++];
        if (header == (byte) 0) {
            int length = 0;
            for (int shift = 0; true; shift += 7) {
                byte b = buf[i++];
                length |= (b & 0x7f) << shift;
                if (shift == 28 || b >= 0)
                    break;
            }
            if (length > colferListMax)
                throw new SecurityException(format("colfer: field serializers/colfer/media.mediaContent.images length %d exceeds %d elements", length, colferListMax));
            Image[] a = new Image[length];
            for (int ai = 0; ai < length; ai++) {
                Image o = new Image();
                i = o.unmarshal(buf, i);
                a[ai] = o;
            }
            this.images = a;
            header = buf[i++];
        }
        if (header == (byte) 1) {
            this.media = new Media();
            i = this.media.unmarshal(buf, i);
            header = buf[i++];
        }
        if (header != (byte) 0x7f)
            throw new InputMismatchException(format("colfer: unknown header at byte %d", i - 1));
    } catch (IndexOutOfBoundsException e) {
        if (i - offset > colferSizeMax)
            throw new SecurityException(format("colfer: serial exceeds %d bytes", colferSizeMax));
        if (i >= buf.length)
            throw new BufferUnderflowException();
        throw new RuntimeException("colfer: bug", e);
    }
    if (i - offset > colferSizeMax)
        throw new SecurityException(format("colfer: serial exceeds %d bytes", colferSizeMax));
    return i;
}
Also used : InputMismatchException(java.util.InputMismatchException) BufferUnderflowException(java.nio.BufferUnderflowException)

Aggregations

BufferUnderflowException (java.nio.BufferUnderflowException)123 ByteBuffer (java.nio.ByteBuffer)70 IOException (java.io.IOException)25 ArrayList (java.util.ArrayList)22 DirectByteBuffer (java.nio.DirectByteBuffer)15 Test (org.junit.Test)14 CertificateException (java.security.cert.CertificateException)12 X509Certificate (java.security.cert.X509Certificate)11 BigInteger (java.math.BigInteger)10 ByteSource (org.apache.geode.internal.tcp.ByteBufferInputStream.ByteSource)9 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)9 SerializationTest (org.apache.geode.test.junit.categories.SerializationTest)9 UnitTest (org.apache.geode.test.junit.categories.UnitTest)9 CharBuffer (java.nio.CharBuffer)7 ByteArrayInputStream (java.io.ByteArrayInputStream)6 FloatBuffer (java.nio.FloatBuffer)6 CertificateFactory (java.security.cert.CertificateFactory)6 HashMap (java.util.HashMap)6 ArrayMap (android.util.ArrayMap)5 HSIconFileElement (com.android.anqp.HSIconFileElement)5