Skip to content

Commit ea3ffb4

Browse files
authored
fix(jsonrpc): harden RPC/HTTP parameter validation (#6828)
1 parent 1691fdd commit ea3ffb4

12 files changed

Lines changed: 528 additions & 62 deletions

File tree

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

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ public class Commons {
2121

2222
public static final int ASSET_ISSUE_COUNT_LIMIT_MAX = 1000;
2323

24+
public static final int BASE58_ADDRESS_LENGTH = 34;
25+
2426
public static byte[] decode58Check(String input) {
2527
byte[] decodeCheck = Base58.decode(input);
2628
if (decodeCheck.length <= 4) {
@@ -41,9 +43,16 @@ public static byte[] decode58Check(String input) {
4143
return null;
4244
}
4345

46+
/**
47+
* Decode a Base58Check address string to its 21-byte form.
48+
*/
4449
public static byte[] decodeFromBase58Check(String addressBase58) {
4550
if (StringUtils.isEmpty(addressBase58)) {
46-
logger.warn("Warning: Address is empty !!");
51+
logger.debug("address is empty !!");
52+
return null;
53+
}
54+
if (addressBase58.length() != BASE58_ADDRESS_LENGTH) {
55+
logger.debug("invalid Base58 address length");
4756
return null;
4857
}
4958
byte[] address = decode58Check(addressBase58);

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

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1313,7 +1313,18 @@ static ByteString unescapeBytesSelfType(String input, final String fliedName)
13131313
throws InvalidEscapeSequence {
13141314
//Address base58 -> ByteString
13151315
if (HttpSelfFormatFieldName.isAddressFormat(fliedName)) {
1316-
return ByteString.copyFrom(Commons.decodeFromBase58Check(input));
1316+
byte[] addressBytes = null;
1317+
try {
1318+
addressBytes = Commons.decodeFromBase58Check(input);
1319+
} catch (IllegalArgumentException e) {
1320+
// Base58.decode throws on illegal chars -> leave addressBytes null (treated as invalid)
1321+
}
1322+
if (addressBytes == null) {
1323+
// empty / wrong-length / bad-checksum / illegal chars -> all invalid addresses; throw a
1324+
// clear error instead of letting ByteString.copyFrom(null) throw a bare NPE.
1325+
throw new InvalidEscapeSequence("invalid address for field: " + fliedName);
1326+
}
1327+
return ByteString.copyFrom(addressBytes);
13171328
}
13181329

13191330
//Normal String -> ByteString

‎framework/src/main/java/org/tron/core/services/jsonrpc/JsonRpcApiUtil.java‎

Lines changed: 105 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,13 @@
88
import java.security.SecureRandom;
99
import java.util.ArrayList;
1010
import java.util.List;
11+
import java.util.regex.Pattern;
1112
import lombok.extern.slf4j.Slf4j;
1213
import org.apache.commons.lang3.StringUtils;
1314
import org.bouncycastle.util.encoders.Hex;
1415
import org.tron.api.GrpcAPI.AssetIssueList;
1516
import org.tron.common.crypto.Hash;
17+
import org.tron.common.math.StrictMathWrapper;
1618
import org.tron.common.parameter.CommonParameter;
1719
import org.tron.common.runtime.vm.DataWord;
1820
import org.tron.common.utils.ByteArray;
@@ -60,6 +62,7 @@ public class JsonRpcApiUtil {
6062
public static final String TAG_PENDING_SUPPORT_ERROR = "TAG pending not supported";
6163
public static final String TAG_SAFE_SUPPORT_ERROR = "TAG safe not supported";
6264
public static final String BLOCK_NUM_ERROR = "invalid block number";
65+
public static final String TX_INDEX_ERROR = "invalid index value";
6366

6467
private static final SecureRandom random = new SecureRandom();
6568

@@ -395,46 +398,90 @@ public static long getUnfreezeAssetAmount(byte[] addressBytes, Wallet wallet) {
395398
*/
396399
public static byte[] addressCompatibleToByteArray(String hexAddress)
397400
throws JsonRpcInvalidParamsException {
401+
// ADDRESS_SIZE (42) is the hex length of a 21-byte address; +2 leaves room for the optional
402+
// "0x" prefix, so a 0x-prefixed 21-byte address (0x41..., 44 chars) is still accepted.
403+
if (hexAddress == null || hexAddress.length() > DecodeUtil.ADDRESS_SIZE + 2) {
404+
throw new JsonRpcInvalidParamsException("invalid address");
405+
}
398406
byte[] addressByte;
399407
try {
400408
addressByte = ByteArray.fromHexString(hexAddress);
401409
if (addressByte.length != DecodeUtil.ADDRESS_SIZE / 2
402410
&& addressByte.length != DecodeUtil.ADDRESS_SIZE / 2 - 1) {
403-
throw new JsonRpcInvalidParamsException("invalid address hash value");
411+
throw new JsonRpcInvalidParamsException("invalid address");
404412
}
405413

406414
if (addressByte.length == DecodeUtil.ADDRESS_SIZE / 2 - 1) {
407415
addressByte = ByteUtil.merge(new byte[] {DecodeUtil.addressPreFixByte}, addressByte);
408416
} else if (addressByte[0] != ByteArray.fromHexString(DecodeUtil.addressPreFixString)[0]) {
409417
// addressByte.length == DecodeUtil.ADDRESS_SIZE / 2
410-
throw new JsonRpcInvalidParamsException("invalid address hash value");
418+
throw new JsonRpcInvalidParamsException("invalid address");
411419
}
412420
} catch (Exception e) {
413421
throw new JsonRpcInvalidParamsException(e.getMessage());
414422
}
415423
return addressByte;
416424
}
417425

426+
/** Matches a 32-byte hash hex string: optional 0x prefix + 64 hex chars (also caps length). */
427+
public static final String HASH_REGEX = "^(0x)?[0-9a-fA-F]{64}$";
428+
418429
/**
419-
* convert 40 hex string of address to byte array, padding 0 ahead if length is odd.
430+
* Convert a hash hex string (optional 0x prefix) to a byte array, validating
431+
* format and length via {@link #HASH_REGEX} first.
420432
*/
421-
public static byte[] addressToByteArray(String hexAddress) throws JsonRpcInvalidParamsException {
422-
byte[] addressByte = ByteArray.fromHexString(hexAddress);
423-
if (addressByte.length != DecodeUtil.ADDRESS_SIZE / 2 - 1) {
424-
throw new JsonRpcInvalidParamsException("invalid address: " + hexAddress);
433+
public static byte[] hashToByteArray(String hash) throws JsonRpcInvalidParamsException {
434+
if (hash == null || !Pattern.matches(HASH_REGEX, hash)) {
435+
throw new JsonRpcInvalidParamsException("invalid hash value");
425436
}
426-
return new DataWord(addressByte).getLast20Bytes();
437+
byte[] bHash;
438+
try {
439+
bHash = ByteArray.fromHexString(hash);
440+
} catch (Exception e) {
441+
throw new JsonRpcInvalidParamsException(e.getMessage());
442+
}
443+
return bHash;
427444
}
428445

429446
/**
430-
* check if topic is hex string of size 64, padding 0 ahead if length is odd.
447+
* Matches a 32-byte topic hex string: optional 0x prefix + 63 or 64 hex chars.
448+
*/
449+
public static final String TOPIC_REGEX = "^(0x)?[0-9a-fA-F]{63,64}$";
450+
451+
/**
452+
* Convert a topic hex string (optional 0x prefix, leading zero may be omitted) to a 32-byte
453+
* array, validating format and length via {@link #TOPIC_REGEX} first.
431454
*/
432455
public static byte[] topicToByteArray(String hexTopic) throws JsonRpcInvalidParamsException {
433-
byte[] topicByte = ByteArray.fromHexString(hexTopic);
434-
if (topicByte.length != 32) {
456+
if (hexTopic == null || !Pattern.matches(TOPIC_REGEX, hexTopic)) {
457+
throw new JsonRpcInvalidParamsException("invalid topic: " + hexTopic);
458+
}
459+
try {
460+
return ByteArray.fromHexString(hexTopic);
461+
} catch (Exception e) {
435462
throw new JsonRpcInvalidParamsException("invalid topic: " + hexTopic);
436463
}
437-
return topicByte;
464+
}
465+
466+
/**
467+
* convert 40 hex string of address to byte array, padding 0 ahead if length is odd.
468+
*/
469+
public static byte[] addressToByteArray(String hexAddress) throws JsonRpcInvalidParamsException {
470+
if (hexAddress == null) {
471+
throw new JsonRpcInvalidParamsException("address is null");
472+
} else if (hexAddress.length() > DecodeUtil.ADDRESS_SIZE) {
473+
throw new JsonRpcInvalidParamsException("invalid address: " + hexAddress);
474+
}
475+
byte[] addressByte;
476+
try {
477+
addressByte = ByteArray.fromHexString(hexAddress);
478+
} catch (Exception e) {
479+
throw new JsonRpcInvalidParamsException("invalid address: " + hexAddress);
480+
}
481+
if (addressByte.length != DecodeUtil.ADDRESS_SIZE / 2 - 1) {
482+
throw new JsonRpcInvalidParamsException("invalid address: " + hexAddress);
483+
}
484+
return new DataWord(addressByte).getLast20Bytes();
438485
}
439486

440487
public static boolean paramStringIsNull(String string) {
@@ -499,7 +546,10 @@ public static long parseQuantityValue(String value) throws JsonRpcInvalidParamsE
499546
throw new JsonRpcInvalidParamsException("invalid param value: invalid hex number");
500547
}
501548
}
502-
549+
// QUANTITY is unsigned; reject a signed ("0x-..") value instead of returning a negative.
550+
if (callValue < 0) {
551+
throw new JsonRpcInvalidParamsException("invalid param value: negative");
552+
}
503553
return callValue;
504554
}
505555

@@ -603,10 +653,11 @@ public static long parseBlockTag(String tag, Wallet wallet)
603653
/**
604654
* Max allowed length for a JSON-RPC block number hex/decimal input.
605655
* API-level DoS guard: rejects pathological inputs before BigInteger parsing,
606-
* whose cost grows quadratically with length. Covers hex (0x + 64 chars for
607-
* uint256) and decimal (78 chars for uint256) representations with headroom.
656+
* whose cost grows quadratically with length. A block number fits a signed long,
657+
* so the longest valid input is 19 chars (decimal Long.MAX_VALUE) or 18 (0x + 16
658+
* hex); 20 leaves a small margin.
608659
*/
609-
private static final int MAX_BLOCK_NUM_HEX_LEN = 100;
660+
private static final int MAX_BLOCK_NUM_HEX_LEN = 20;
610661

611662
/**
612663
* Parse a JSON-RPC block number (hex "0x..." or decimal) into a long,
@@ -636,16 +687,50 @@ public static long parseBlockNumber(String blockNum)
636687
}
637688

638689
/**
639-
* Parse a block tag or hex number. Uses strict jsonHexToLong (requires 0x prefix) for hex.
640-
* Callers needing flexible hex parsing (0x -> hex, bare number -> decimal) should use
641-
* isBlockTag/parseBlockTag and handle hex separately with hexToBigInteger.
690+
* Parse a block tag, or a 0x-prefixed hex block number.
642691
*/
643692
public static long parseBlockNumber(String blockNumOrTag, Wallet wallet)
644693
throws JsonRpcInvalidParamsException {
645694
if (isBlockTag(blockNumOrTag)) {
646695
return parseBlockTag(blockNumOrTag, wallet);
647696
}
648-
return ByteArray.jsonHexToLong(blockNumOrTag);
697+
if (blockNumOrTag == null || !blockNumOrTag.startsWith("0x")) {
698+
throw new JsonRpcInvalidParamsException("Incorrect hex syntax");
699+
}
700+
return parseBlockNumber(blockNumOrTag);
701+
}
702+
703+
/**
704+
* Max hex digits of a 32-bit int (0x7FFFFFFF). A transaction index fits a signed int, so the
705+
* longest valid input is "0x" + 8 hex digits; the +2 in the guard covers the prefix.
706+
*/
707+
private static final int MAX_TX_INDEX_HEX_LEN = 8;
708+
709+
/**
710+
* Parse a 0x-prefixed hex transaction index at the JSON-RPC boundary.
711+
*/
712+
public static int parseTxIndex(String index) throws JsonRpcInvalidParamsException {
713+
if (index == null || index.length() > MAX_TX_INDEX_HEX_LEN + 2) {
714+
throw new JsonRpcInvalidParamsException(TX_INDEX_ERROR);
715+
}
716+
try {
717+
return ByteArray.jsonHexToInt(index);
718+
} catch (Exception e) {
719+
throw new JsonRpcInvalidParamsException(TX_INDEX_ERROR);
720+
}
721+
}
722+
723+
/**
724+
* Compute feeLimit = gas * energyFee with overflow protection. A gas value large enough to
725+
* overflow a signed 64-bit feeLimit is rejected as invalid-params instead of silently wrapping
726+
* to a bogus (possibly negative) value.
727+
*/
728+
public static long calcFeeLimit(long gas, long energyFee) throws JsonRpcInvalidParamsException {
729+
try {
730+
return StrictMathWrapper.multiplyExact(gas, energyFee);
731+
} catch (ArithmeticException e) {
732+
throw new JsonRpcInvalidParamsException("invalid gas: fee limit overflow");
733+
}
649734
}
650735

651736
public static String generateFilterId() {

‎framework/src/main/java/org/tron/core/services/jsonrpc/TronJsonRpcImpl.java‎

Lines changed: 32 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,18 @@
33
import static org.tron.core.Wallet.CONTRACT_VALIDATE_ERROR;
44
import static org.tron.core.services.http.Util.setTransactionExtraData;
55
import static org.tron.core.services.http.Util.setTransactionPermissionId;
6-
import static org.tron.core.services.jsonrpc.JsonRpcApiUtil.BLOCK_NUM_ERROR;
76
import static org.tron.core.services.jsonrpc.JsonRpcApiUtil.FINALIZED_STR;
7+
import static org.tron.core.services.jsonrpc.JsonRpcApiUtil.HASH_REGEX;
88
import static org.tron.core.services.jsonrpc.JsonRpcApiUtil.LATEST_STR;
99
import static org.tron.core.services.jsonrpc.JsonRpcApiUtil.addressCompatibleToByteArray;
10+
import static org.tron.core.services.jsonrpc.JsonRpcApiUtil.calcFeeLimit;
1011
import static org.tron.core.services.jsonrpc.JsonRpcApiUtil.generateFilterId;
1112
import static org.tron.core.services.jsonrpc.JsonRpcApiUtil.getEnergyUsageTotal;
1213
import static org.tron.core.services.jsonrpc.JsonRpcApiUtil.getTransactionIndex;
1314
import static org.tron.core.services.jsonrpc.JsonRpcApiUtil.getTxID;
15+
import static org.tron.core.services.jsonrpc.JsonRpcApiUtil.hashToByteArray;
1416
import static org.tron.core.services.jsonrpc.JsonRpcApiUtil.parseBlockNumber;
17+
import static org.tron.core.services.jsonrpc.JsonRpcApiUtil.parseTxIndex;
1518
import static org.tron.core.services.jsonrpc.JsonRpcApiUtil.triggerCallContract;
1619

1720
import com.google.common.annotations.VisibleForTesting;
@@ -157,7 +160,11 @@ public enum RequestSource {
157160
private final Map<String, BlockFilterAndResult> blockFilter2ResultSolidity =
158161
new ConcurrentHashMap<>();
159162

160-
public static final String HASH_REGEX = "(0x)?[a-zA-Z0-9]{64}$";
163+
// Storage key is a 32-byte word: 64 hex chars + optional "0x" prefix = 66 max.
164+
// Reject oversized input before fromHexString / new DataWord, which would otherwise
165+
// throw a RuntimeException whose message embeds the whole hex (amplifying log output)
166+
// and surface as a -32603 Internal error instead of -32602 invalid params.
167+
public static final int MAX_STORAGE_KEY_HEX_LEN = 66;
161168

162169
public static final String INVALID_BLOCK_RANGE = "invalid block range params";
163170

@@ -366,20 +373,6 @@ public BlockResult ethGetBlockByNumber(String blockNumOrTag, Boolean fullTransac
366373
return (b == null ? null : getBlockResult(b, fullTransactionObjects));
367374
}
368375

369-
private byte[] hashToByteArray(String hash) throws JsonRpcInvalidParamsException {
370-
if (!Pattern.matches(HASH_REGEX, hash)) {
371-
throw new JsonRpcInvalidParamsException("invalid hash value");
372-
}
373-
374-
byte[] bHash;
375-
try {
376-
bHash = ByteArray.fromHexString(hash);
377-
} catch (Exception e) {
378-
throw new JsonRpcInvalidParamsException(e.getMessage());
379-
}
380-
return bHash;
381-
}
382-
383376
/**
384377
* Reject any block selector that is not "latest".
385378
* Accepts "latest" silently; throws for other tags, numeric blocks, or invalid input.
@@ -612,8 +605,19 @@ public String getStorageAt(String address, String storageIdx, String blockNumOrT
612605
throws JsonRpcInvalidParamsException {
613606
requireLatestBlockTag(blockNumOrTag);
614607

608+
if (storageIdx == null || storageIdx.length() > MAX_STORAGE_KEY_HEX_LEN) {
609+
throw new JsonRpcInvalidParamsException("invalid storage key value");
610+
}
611+
615612
byte[] addressByte = addressCompatibleToByteArray(address);
616613

614+
DataWord index;
615+
try {
616+
index = new DataWord(ByteArray.fromHexString(storageIdx));
617+
} catch (Exception e) {
618+
throw new JsonRpcInvalidParamsException("invalid storage key value");
619+
}
620+
617621
// get contract from contractStore
618622
BytesMessage.Builder build = BytesMessage.newBuilder();
619623
BytesMessage bytesMessage = build.setValue(ByteString.copyFrom(addressByte)).build();
@@ -627,7 +631,7 @@ public String getStorageAt(String address, String storageIdx, String blockNumOrT
627631
storage.setContractVersion(smartContract.getVersion());
628632
storage.generateAddrHash(smartContract.getTrxHash().toByteArray());
629633

630-
DataWord value = storage.getValue(new DataWord(ByteArray.fromHexString(storageIdx)));
634+
DataWord value = storage.getValue(index);
631635
return ByteArray.toJsonHex(value == null ? new byte[32] : value.getData());
632636
}
633637

@@ -812,14 +816,9 @@ private TransactionResult formatTransactionResult(TransactionInfo transactioninf
812816

813817
private TransactionResult getTransactionByBlockAndIndex(Block block, String index)
814818
throws JsonRpcInvalidParamsException {
815-
int txIndex;
816-
try {
817-
txIndex = ByteArray.jsonHexToInt(index);
818-
} catch (Exception e) {
819-
throw new JsonRpcInvalidParamsException("invalid index value");
820-
}
819+
int txIndex = parseTxIndex(index);
821820

822-
if (txIndex >= block.getTransactionsCount()) {
821+
if (txIndex < 0 || txIndex >= block.getTransactionsCount()) {
823822
return null;
824823
}
825824

@@ -934,9 +933,10 @@ public List<TransactionReceipt> getBlockReceipts(String blockNumOrHashOrTag)
934933

935934
Block block = null;
936935

937-
if (Pattern.matches(HASH_REGEX, blockNumOrHashOrTag)) {
936+
if (blockNumOrHashOrTag != null && Pattern.matches(HASH_REGEX, blockNumOrHashOrTag)) {
938937
block = getBlockByJsonHash(blockNumOrHashOrTag);
939938
} else {
939+
// null falls through to getBlockByNumOrTag -> parseBlockNumber -> -32602 (not an NPE)
940940
block = getBlockByNumOrTag(blockNumOrHashOrTag);
941941
}
942942

@@ -1141,7 +1141,11 @@ private TransactionJson buildCreateSmartContractTransaction(byte[] ownerAddress,
11411141
ABI.Builder abiBuilder = ABI.newBuilder();
11421142
if (StringUtils.isNotEmpty(args.getAbi())) {
11431143
String abiStr = "{" + "\"entrys\":" + args.getAbi() + "}";
1144-
JsonFormat.merge(abiStr, abiBuilder, args.isVisible());
1144+
try {
1145+
JsonFormat.merge(abiStr, abiBuilder, args.isVisible());
1146+
} catch (StackOverflowError e) {
1147+
throw new JsonRpcInvalidParamsException("invalid abi");
1148+
}
11451149
}
11461150

11471151
SmartContract.Builder smartBuilder = SmartContract.newBuilder();
@@ -1167,7 +1171,7 @@ private TransactionJson buildCreateSmartContractTransaction(byte[] ownerAddress,
11671171
.createTransactionCapsule(build.build(), ContractType.CreateSmartContract).getInstance();
11681172
Transaction.Builder txBuilder = tx.toBuilder();
11691173
Transaction.raw.Builder rawBuilder = tx.getRawData().toBuilder();
1170-
rawBuilder.setFeeLimit(args.parseGas() * wallet.getEnergyFee());
1174+
rawBuilder.setFeeLimit(calcFeeLimit(args.parseGas(), wallet.getEnergyFee()));
11711175

11721176
txBuilder.setRawData(rawBuilder);
11731177
tx = setTransactionPermissionId(args.getPermissionId(), txBuilder.build());
@@ -1216,7 +1220,7 @@ private TransactionJson buildTriggerSmartContractTransaction(byte[] ownerAddress
12161220

12171221
Transaction.Builder txBuilder = tx.toBuilder();
12181222
Transaction.raw.Builder rawBuilder = tx.getRawData().toBuilder();
1219-
rawBuilder.setFeeLimit(args.parseGas() * wallet.getEnergyFee());
1223+
rawBuilder.setFeeLimit(calcFeeLimit(args.parseGas(), wallet.getEnergyFee()));
12201224
txBuilder.setRawData(rawBuilder);
12211225

12221226
Transaction trx = wallet

0 commit comments

Comments
 (0)