From f1ede7921130c48d79ec4071ff70575b2552979f Mon Sep 17 00:00:00 2001 From: Roger Meier Date: Tue, 9 Oct 2012 18:42:16 +0000 Subject: [PATCH] THRIFT-1643 Denial of Service attack in TBinaryProtocol.readString Patch: Niraj Tolia Fix: add TCompactProtocol maxNetworkBytes git-svn-id: https://svn.apache.org/repos/asf/thrift/trunk@1396186 13f79535-47bb-0310-9956-ffa450edef68 --- .../thrift/protocol/TCompactProtocol.java | 41 +++++++++++++++++-- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/lib/java/src/org/apache/thrift/protocol/TCompactProtocol.java b/lib/java/src/org/apache/thrift/protocol/TCompactProtocol.java index 3b1d8869..3db256de 100644 --- a/lib/java/src/org/apache/thrift/protocol/TCompactProtocol.java +++ b/lib/java/src/org/apache/thrift/protocol/TCompactProtocol.java @@ -62,10 +62,18 @@ public class TCompactProtocol extends TProtocol { * TProtocolFactory that produces TCompactProtocols. */ public static class Factory implements TProtocolFactory { - public Factory() {} + private final long maxNetworkBytes_; + + public Factory() { + maxNetworkBytes_ = -1; + } + + public Factory(int maxNetworkBytes) { + maxNetworkBytes_ = maxNetworkBytes; + } public TProtocol getProtocol(TTransport trans) { - return new TCompactProtocol(trans); + return new TCompactProtocol(trans, maxNetworkBytes_); } } @@ -113,13 +121,32 @@ public class TCompactProtocol extends TProtocol { */ private Boolean boolValue_ = null; + /** + * The maximum number of bytes to read from the network for + * variable-length fields (such as strings or binary) or -1 for + * unlimited. + */ + private final long maxNetworkBytes_; + /** * Create a TCompactProtocol. * * @param transport the TTransport object to read from or write to. + * @param maxNetworkBytes the maximum number of bytes to read for + * variable-length fields. */ - public TCompactProtocol(TTransport transport) { + public TCompactProtocol(TTransport transport, long maxNetworkBytes) { super(transport); + maxNetworkBytes_ = maxNetworkBytes; + } + + /** + * Create a TCompactProtocol. + * + * @param transport the TTransport object to read from or write to. + */ + public TCompactProtocol(TTransport transport) { + this(transport, -1); } @Override @@ -617,6 +644,10 @@ public class TCompactProtocol extends TProtocol { return ""; } + if (maxNetworkBytes_ != -1 && length > maxNetworkBytes_) { + throw new TException("Read size greater than max allowed."); + } + try { if (trans_.getBytesRemainingInBuffer() >= length) { String str = new String(trans_.getBuffer(), trans_.getBufferPosition(), length, "UTF-8"); @@ -637,6 +668,10 @@ public class TCompactProtocol extends TProtocol { int length = readVarint32(); if (length == 0) return ByteBuffer.wrap(new byte[0]); + if (maxNetworkBytes_ != -1 && length > maxNetworkBytes_) { + throw new TException("Read size greater than max allowed."); + } + byte[] buf = new byte[length]; trans_.readAll(buf, 0, length); return ByteBuffer.wrap(buf); -- 2.17.1