Skip to content

Commit bdb9018

Browse files
authored
fix(api): harden external input validation (#7023)
1 parent 3b35e94 commit bdb9018

29 files changed

Lines changed: 1695 additions & 243 deletions

‎chainbase/src/main/java/org/tron/common/utils/WalletUtil.java‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@
88
import java.util.List;
99
import java.util.stream.Collectors;
1010
import org.tron.common.crypto.Hash;
11+
import org.tron.common.math.StrictMathWrapper;
1112
import org.tron.common.parameter.CommonParameter;
13+
import org.tron.core.Constant;
1214
import org.tron.core.capsule.ContractCapsule;
1315
import org.tron.core.capsule.TransactionCapsule;
1416
import org.tron.core.exception.ContractValidateException;
@@ -24,6 +26,8 @@
2426

2527
public class WalletUtil {
2628

29+
private static final String INVALID_ADDRESS = "invalid-address";
30+
2731
public static boolean checkPermissionOperations(Permission permission, Contract contract)
2832
throws PermissionException {
2933
ByteString operations = permission.getOperations();
@@ -115,9 +119,22 @@ public static boolean isConstant(SmartContract.ABI abi, byte[] selector) {
115119
return false;
116120
}
117121

122+
public static String getAddressString(byte[] address) {
123+
if (address == null) {
124+
return INVALID_ADDRESS + "(null)";
125+
}
126+
if (address.length == Constant.STANDARD_ADDRESS_SIZE
127+
|| address.length == Constant.TRON_ADDRESS_SIZE) {
128+
return encode58Check(address);
129+
}
130+
int shown = StrictMathWrapper.min(address.length, Constant.TRON_ADDRESS_SIZE);
131+
return INVALID_ADDRESS + "(" + ByteArray.toHexString(Arrays.copyOf(address, shown))
132+
+ (shown < address.length ? "..." : "") + ",len=" + address.length + ")";
133+
}
134+
118135
public static List<String> getAddressStringList(Collection<ByteString> collection) {
119136
return collection.stream()
120-
.map(bytes -> encode58Check(bytes.toByteArray()))
137+
.map(address -> getAddressString(address.toByteArray()))
121138
.collect(Collectors.toList());
122139
}
123140

‎chainbase/src/main/java/org/tron/core/db/TransactionTrace.java‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818
import org.tron.common.utils.DecodeUtil;
1919
import org.tron.common.utils.ForkController;
2020
import org.tron.common.utils.Sha256Hash;
21-
import org.tron.common.utils.StringUtil;
2221
import org.tron.common.utils.WalletUtil;
2322
import org.tron.core.Constant;
2423
import org.tron.core.capsule.AccountCapsule;
@@ -141,7 +140,7 @@ public void checkIsConstant() throws ContractValidateException, VMIllegalExcepti
141140
.get(triggerContractFromTransaction.getContractAddress().toByteArray());
142141
if (contract == null) {
143142
throw new ContractValidateException(String.format("contract: %s is not in contract store",
144-
StringUtil.encode58Check(triggerContractFromTransaction
143+
WalletUtil.getAddressString(triggerContractFromTransaction
145144
.getContractAddress().toByteArray())));
146145

147146
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package org.tron.core.exception;
2+
3+
import java.security.InvalidParameterException;
4+
5+
public class InvalidHttpParameterException extends InvalidParameterException {
6+
7+
public InvalidHttpParameterException(String message) {
8+
super(message);
9+
}
10+
11+
public InvalidHttpParameterException(String message, Throwable cause) {
12+
super(message);
13+
initCause(cause);
14+
}
15+
}

‎consensus/src/main/java/org/tron/consensus/pbft/message/PbftBaseMessage.java‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,12 @@
33
import com.google.protobuf.InvalidProtocolBufferException;
44
import java.io.IOException;
55
import java.security.SignatureException;
6-
import java.util.stream.Collectors;
76
import org.bouncycastle.util.encoders.Hex;
87
import org.tron.common.crypto.ECKey;
98
import org.tron.common.overlay.message.Message;
109
import org.tron.common.utils.ByteUtil;
1110
import org.tron.common.utils.Sha256Hash;
12-
import org.tron.common.utils.StringUtil;
11+
import org.tron.common.utils.WalletUtil;
1312
import org.tron.core.capsule.TransactionCapsule;
1413
import org.tron.core.exception.P2pException;
1514
import org.tron.protos.Protocol.PBFTMessage;
@@ -119,8 +118,7 @@ public String getDataString() {
119118
private String decode() {
120119
try {
121120
SRL srList = SRL.parseFrom(pbftMessage.getRawData().getData().toByteArray());
122-
return "sr list = " + srList.getSrAddressList().stream().map(
123-
bytes -> StringUtil.encode58Check(bytes.toByteArray())).collect(Collectors.toList());
121+
return "sr list = " + WalletUtil.getAddressStringList(srList.getSrAddressList());
124122
} catch (InvalidProtocolBufferException e) {
125123
}
126124
return "decode error";

‎framework/src/main/java/org/tron/core/Wallet.java‎

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,6 @@
118118
import org.tron.common.utils.ByteUtil;
119119
import org.tron.common.utils.DecodeUtil;
120120
import org.tron.common.utils.Sha256Hash;
121-
import org.tron.common.utils.StringUtil;
122121
import org.tron.common.utils.Utils;
123122
import org.tron.common.utils.WalletUtil;
124123
import org.tron.common.zksnark.IncrementalMerkleTreeContainer;
@@ -262,6 +261,9 @@ public class Wallet {
262261
"Shielded transaction API is disabled; "
263262
+ "set node.allowShieldedTransactionApi=true to enable.";
264263
private static final String PAYMENT_ADDRESS_FORMAT_WRONG = "paymentAddress format is wrong";
264+
// the authoritative bound is checkBigIntegerRange: uint256 max is 78 decimal digits,
265+
// this only keeps the string short enough to convert cheaply
266+
private static final int MAX_SHIELDED_AMOUNT_LENGTH = 80;
265267
private static final String SHIELDED_TRANSACTION_SCAN_RANGE =
266268
"request requires start_block_index >= 0 && end_block_index > "
267269
+ "start_block_index && end_block_index - start_block_index <= 1000";
@@ -3235,7 +3237,7 @@ public SmartContract getContract(GrpcAPI.BytesMessage bytesMessage) {
32353237
if (accountCapsule == null) {
32363238
logger.warn(
32373239
"Get contract failed, the account {} does not exist or the account "
3238-
+ "does not have a code hash!", StringUtil.encode58Check(address));
3240+
+ "does not have a code hash!", WalletUtil.getAddressString(address));
32393241
return null;
32403242
}
32413243

@@ -3264,7 +3266,7 @@ public SmartContractDataWrapper getContractInfo(GrpcAPI.BytesMessage bytesMessag
32643266
if (accountCapsule == null) {
32653267
logger.warn(
32663268
"Get contract failed, the account {} does not exist or the account does not have a code "
3267-
+ "hash!", StringUtil.encode58Check(address));
3269+
+ "hash!", WalletUtil.getAddressString(address));
32683270
return null;
32693271
}
32703272

@@ -4240,6 +4242,9 @@ private BigInteger getBigIntegerFromString(String in) {
42404242
if (trimmedIn.length() == 0) {
42414243
return BigInteger.ZERO;
42424244
}
4245+
if (trimmedIn.length() > MAX_SHIELDED_AMOUNT_LENGTH) {
4246+
throw new IllegalArgumentException("invalid shielded amount");
4247+
}
42434248
return new BigInteger(trimmedIn, 10);
42444249
}
42454250

@@ -4351,7 +4356,12 @@ public BytesMessage getTriggerInputForShieldedTRC20Contract(
43514356

43524357
ShieldedTRC20Parameters shieldedTRC20Parameters = request.getShieldedTRC20Parameters();
43534358
List<BytesMessage> spendAuthoritySignature = request.getSpendAuthoritySignatureList();
4354-
BigInteger value = getBigIntegerFromString(request.getAmount());
4359+
BigInteger value;
4360+
try {
4361+
value = getBigIntegerFromString(request.getAmount());
4362+
} catch (IllegalArgumentException e) {
4363+
throw new ContractValidateException("invalid amount", e);
4364+
}
43554365
checkBigIntegerRange(value);
43564366
byte[] transparentToAddress = request.getTransparentToAddress().toByteArray();
43574367
byte[] transparentToAddressTvm = new byte[20];
@@ -4416,9 +4426,16 @@ public BytesMessage getTriggerInputForShieldedTRC20Contract(
44164426
}
44174427
parametersBuilder.setBurnCiphertext(burnCiper);
44184428
}
4419-
String input = parametersBuilder
4420-
.getTriggerContractInput(shieldedTRC20Parameters, spendAuthoritySignature, value, false,
4421-
transparentToAddressTvm);
4429+
String input;
4430+
try {
4431+
input = parametersBuilder
4432+
.getTriggerContractInput(shieldedTRC20Parameters, spendAuthoritySignature, value, false,
4433+
transparentToAddressTvm);
4434+
} catch (IllegalArgumentException e) {
4435+
// the builder names the offending argument in fixed strings; none of them echoes an input
4436+
throw new ContractValidateException(
4437+
"invalid shielded TRC-20 trigger input: " + e.getMessage(), e);
4438+
}
44224439
if (Objects.isNull(input)) {
44234440
throw new ZksnarkException("generate the trigger contract parameters error");
44244441
}

‎framework/src/main/java/org/tron/core/net/message/handshake/HelloMessage.java‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import org.apache.commons.lang3.StringUtils;
66
import org.tron.common.utils.ByteArray;
77
import org.tron.common.utils.Sha256Hash;
8-
import org.tron.common.utils.StringUtil;
8+
import org.tron.common.utils.WalletUtil;
99
import org.tron.core.ChainBaseManager;
1010
import org.tron.core.capsule.BlockCapsule;
1111
import org.tron.core.config.args.Args;
@@ -132,7 +132,7 @@ public String toString() {
132132
ByteString address = helloMessage.getAddress();
133133
if (!address.isEmpty()) {
134134
builder.append("address:")
135-
.append(StringUtil.encode58Check(address.toByteArray())).append("\n");
135+
.append(WalletUtil.getAddressString(address.toByteArray())).append("\n");
136136
}
137137

138138
ByteString signature = helloMessage.getSignature();

‎framework/src/main/java/org/tron/core/services/http/servlets/GetBrokerageServlet.java‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
import javax.servlet.http.HttpServletRequest;
44
import javax.servlet.http.HttpServletResponse;
55
import lombok.extern.slf4j.Slf4j;
6-
import org.bouncycastle.util.encoders.DecoderException;
76
import org.springframework.beans.factory.annotation.Autowired;
87
import org.springframework.stereotype.Component;
98
import org.tron.core.db.Manager;
@@ -21,18 +20,19 @@ public class GetBrokerageServlet extends RateLimiterServlet {
2120
private Manager manager;
2221

2322
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
23+
byte[] address;
24+
try {
25+
address = Util.getAddress(request);
26+
} catch (Exception e) {
27+
Util.processError(e, response);
28+
return;
29+
}
2430
try {
25-
int value = 0;
26-
byte[] address = Util.getAddress(request);
2731
long cycle = manager.getDynamicPropertiesStore().getCurrentCycleNumber();
28-
if (address != null) {
29-
value = manager.getDelegationStore().getBrokerage(cycle, address);
30-
}
32+
int value = manager.getDelegationStore().getBrokerage(cycle, address);
3133
response.getWriter().println("{\"brokerage\": " + value + "}");
32-
} catch (DecoderException | IllegalArgumentException e) {
33-
Util.writeAuditedError(Util.INVALID_ADDRESS_MSG, response);
3434
} catch (Exception e) {
35-
Util.processError(e, response);
35+
Util.processServerError(e, response);
3636
}
3737
}
3838

‎framework/src/main/java/org/tron/core/services/http/servlets/GetRewardServlet.java‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
import javax.servlet.http.HttpServletRequest;
44
import javax.servlet.http.HttpServletResponse;
55
import lombok.extern.slf4j.Slf4j;
6-
import org.bouncycastle.util.encoders.DecoderException;
76
import org.springframework.beans.factory.annotation.Autowired;
87
import org.springframework.stereotype.Component;
98
import org.tron.core.db.Manager;
@@ -21,18 +20,19 @@ public class GetRewardServlet extends RateLimiterServlet {
2120
private Manager manager;
2221

2322
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
23+
byte[] address;
2424
try {
25-
long value = 0;
26-
byte[] address = Util.getAddress(request);
27-
if (address != null) {
28-
value = manager.getMortgageService().queryReward(address);
29-
}
25+
address = Util.getAddress(request);
26+
} catch (Exception e) {
27+
Util.processError(e, response);
28+
return;
29+
}
30+
try {
31+
long value = manager.getMortgageService().queryReward(address);
3032
String out = JsonFormat.isInt64AsString()
3133
? "{\"reward\": \"" + value + "\"}"
3234
: "{\"reward\": " + value + "}";
3335
response.getWriter().println(out);
34-
} catch (DecoderException | IllegalArgumentException e) {
35-
Util.writeAuditedError(Util.INVALID_ADDRESS_MSG, response);
3636
} catch (Exception e) {
3737
Util.processServerError(e, response);
3838
}

‎framework/src/main/java/org/tron/core/services/http/servlets/JsonFormat.java‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,8 @@ public class JsonFormat {
8484
= "Writing to a StringBuilder threw an IOException (should never happen).";
8585
private static final String EXPECTED_STRING = "Expected string.";
8686
private static final String MISSING_END_QUOTE = "String missing ending quote.";
87+
// Keeps the genesis block addresses compatible with their Base58Check rendering.
88+
private static final int MAX_BASE58_ADDRESS_SIZE = 128;
8789

8890
// Bounds all work and error messages performed by parseInteger after tokenization.
8991
static final int MAX_INTEGER_TOKEN_LENGTH = 256;
@@ -889,6 +891,9 @@ static String escapeBytes(ByteString input, final String fieldName, boolean self
889891
static String escapeBytesSelfType(ByteString input, final String fieldName) {
890892
//Address
891893
if (HttpSelfFormatFieldName.isAddressFormat(fieldName)) {
894+
if (input.size() > MAX_BASE58_ADDRESS_SIZE) {
895+
return ByteArray.toHexString(input.toByteArray());
896+
}
892897
return StringUtil.encode58Check(input.toByteArray());
893898
}
894899
//Normal String

0 commit comments

Comments
 (0)