Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
0526128
refactor(crypto): extract keystore library from framework module
Apr 2, 2026
7f0c0ba
feat(plugins): add keystore new and import commands to Toolkit
Apr 2, 2026
2bced5f
feat(plugins): add keystore list and update commands, deprecate --key…
Apr 2, 2026
1a641b4
fix(plugins): handle duplicate-address keystores and add import warning
Apr 3, 2026
791d91f
fix(plugins): block duplicate import, improve error messages and secu…
Apr 5, 2026
3c0f8eb
style(plugins): use picocli output streams and address review findings
Apr 16, 2026
cf823df
fix(plugins): secure keystore file creation and improve robustness
Apr 16, 2026
ce482cb
test(plugins): improve keystore test coverage and assertions
Apr 16, 2026
115e226
fix(plugins): unify keystore validation and fix inconsistent error me…
Apr 16, 2026
b079839
test(plugins): improve coverage for keystore validation and edge cases
Apr 17, 2026
b083fc6
test(plugins): add direct unit tests for KeystoreCliUtils
Apr 17, 2026
241590c
test(framework): expand coverage for WalletFile POJO and KeystoreFactory
Apr 17, 2026
cdb038f
ci: re-trigger build after transient apt mirror failure
Apr 17, 2026
4e19b0b
ci: re-trigger after transient infrastructure failure
Apr 17, 2026
368d104
fix(crypto): enforce keystore address consistency in Wallet.decrypt
Apr 18, 2026
c383a83
fix(plugins): prevent address spoofing in keystore update command
Apr 18, 2026
5a76ed8
docs(plugins): document keystore list address trust model
Apr 18, 2026
070316c
refactor(crypto): centralize secure keystore file writing in WalletUtils
Apr 18, 2026
40ec5ce
fix(plugins): reject symlinked password/key files to prevent file dis…
Apr 18, 2026
e5bbc20
fix(crypto): preserve whitespace in non-TTY password input
Apr 21, 2026
4bcb850
feat(plugins): hint at legacy password-truncation on keystore update …
Apr 21, 2026
f681124
feat(framework): hint at legacy password-truncation on SR startup fai…
Apr 21, 2026
99159e2
test(crypto): move keystore tests to framework for jacoco coverage
Apr 22, 2026
340669c
fix(plugins): reject symlinks in keystore directory scans
Apr 22, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
import org.tron.common.crypto.SignUtils;
import org.tron.common.utils.ByteArray;
import org.tron.common.utils.StringUtil;
import org.tron.core.config.args.Args;
import org.tron.core.exception.CipherException;

/**
Expand Down Expand Up @@ -168,8 +167,8 @@ private static byte[] generateMac(byte[] derivedKey, byte[] cipherText) {
return Hash.sha3(result);
}

public static SignInterface decrypt(String password, WalletFile walletFile)
throws CipherException {
public static SignInterface decrypt(String password, WalletFile walletFile,
boolean ecKey) throws CipherException {

validate(walletFile);

Expand Down Expand Up @@ -205,14 +204,29 @@ public static SignInterface decrypt(String password, WalletFile walletFile)

byte[] derivedMac = generateMac(derivedKey, cipherText);

if (!Arrays.equals(derivedMac, mac)) {
if (!java.security.MessageDigest.isEqual(derivedMac, mac)) {
throw new CipherException("Invalid password provided");
}

byte[] encryptKey = Arrays.copyOfRange(derivedKey, 0, 16);
byte[] privateKey = performCipherOperation(Cipher.DECRYPT_MODE, iv, encryptKey, cipherText);

return SignUtils.fromPrivate(privateKey, Args.getInstance().isECKeyCryptoEngine());
SignInterface keyPair = SignUtils.fromPrivate(privateKey, ecKey);

// Enforce address consistency: if the keystore declares an address, it MUST match
// the address derived from the decrypted private key. Prevents address spoofing
// where a crafted keystore displays one address but encrypts a different key.
String declared = walletFile.getAddress();
if (declared != null && !declared.isEmpty()) {
String derived = StringUtil.encode58Check(keyPair.getAddress());
if (!declared.equals(derived)) {
throw new CipherException(
"Keystore address mismatch: file declares " + declared
+ " but private key derives " + derived);
}
}

return keyPair;
}

static void validate(WalletFile walletFile) throws CipherException {
Expand Down
294 changes: 294 additions & 0 deletions crypto/src/main/java/org/tron/keystore/WalletUtils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,294 @@
package org.tron.keystore;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.Console;
import java.io.File;
import java.io.IOException;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Scanner;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.tron.common.crypto.SignInterface;
import org.tron.common.crypto.SignUtils;
import org.tron.common.utils.Utils;
import org.tron.core.exception.CipherException;

/**
* Utility functions for working with Wallet files.
*/
public class WalletUtils {

private static final ObjectMapper objectMapper = new ObjectMapper();

private static final Set<PosixFilePermission> OWNER_ONLY =
Collections.unmodifiableSet(EnumSet.of(
PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE));

static {
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}

public static String generateFullNewWalletFile(String password, File destinationDirectory,
boolean ecKey)
throws NoSuchAlgorithmException, NoSuchProviderException,
InvalidAlgorithmParameterException, CipherException, IOException {

return generateNewWalletFile(password, destinationDirectory, true, ecKey);
}

public static String generateLightNewWalletFile(String password, File destinationDirectory,
boolean ecKey)
throws NoSuchAlgorithmException, NoSuchProviderException,
InvalidAlgorithmParameterException, CipherException, IOException {

return generateNewWalletFile(password, destinationDirectory, false, ecKey);
}

public static String generateNewWalletFile(
String password, File destinationDirectory, boolean useFullScrypt, boolean ecKey)
throws CipherException, IOException, InvalidAlgorithmParameterException,
NoSuchAlgorithmException, NoSuchProviderException {

SignInterface ecKeyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom(), ecKey);
return generateWalletFile(password, ecKeyPair, destinationDirectory, useFullScrypt);
}

public static String generateWalletFile(
String password, SignInterface ecKeyPair, File destinationDirectory, boolean useFullScrypt)
throws CipherException, IOException {

WalletFile walletFile;
if (useFullScrypt) {
walletFile = Wallet.createStandard(password, ecKeyPair);
} else {
walletFile = Wallet.createLight(password, ecKeyPair);
}

String fileName = getWalletFileName(walletFile);
File destination = new File(destinationDirectory, fileName);
writeWalletFile(walletFile, destination);

return fileName;
}

/**
* Write a WalletFile to the given destination path with owner-only (0600)
* permissions, using a temp file + atomic rename.
*
* <p>On POSIX filesystems, the temp file is created atomically with 0600
* permissions via {@link Files#createTempFile(Path, String, String,
* java.nio.file.attribute.FileAttribute[])}, avoiding any window where the
* file is world-readable.
*
* <p>On non-POSIX filesystems (e.g. Windows) the fallback uses
* {@link File#setReadable(boolean, boolean)} /
* {@link File#setWritable(boolean, boolean)} which is best-effort — these
* methods manipulate only DOS-style attributes on Windows and may not update
* file ACLs. The sensitive keystore JSON is written only after the narrowing
* calls, so no confidential data is exposed during the window, but callers
* on Windows should not infer strict owner-only ACL enforcement from this.
*
* @param walletFile the keystore to serialize
* @param destination the final target file (existing file will be replaced)
*/
public static void writeWalletFile(WalletFile walletFile, File destination)
throws IOException {
Path dir = destination.getAbsoluteFile().getParentFile().toPath();
Files.createDirectories(dir);

Path tmp;
try {
tmp = Files.createTempFile(dir, "keystore-", ".tmp",
PosixFilePermissions.asFileAttribute(OWNER_ONLY));
} catch (UnsupportedOperationException e) {
// Windows / non-POSIX fallback — best-effort narrowing only (see JavaDoc)
tmp = Files.createTempFile(dir, "keystore-", ".tmp");
File tf = tmp.toFile();
tf.setReadable(false, false);
tf.setReadable(true, true);
tf.setWritable(false, false);
tf.setWritable(true, true);
}

try {
objectMapper.writeValue(tmp.toFile(), walletFile);
try {
Files.move(tmp, destination.toPath(),
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.ATOMIC_MOVE);
} catch (AtomicMoveNotSupportedException e) {
Files.move(tmp, destination.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
} catch (Exception e) {
try {
Files.deleteIfExists(tmp);
} catch (IOException suppress) {
e.addSuppressed(suppress);
}
throw e;
}
}

public static Credentials loadCredentials(String password, File source, boolean ecKey)
throws IOException, CipherException {
WalletFile walletFile = objectMapper.readValue(source, WalletFile.class);
return Credentials.create(Wallet.decrypt(password, walletFile, ecKey));
}

public static String getWalletFileName(WalletFile walletFile) {
DateTimeFormatter format = DateTimeFormatter.ofPattern(
"'UTC--'yyyy-MM-dd'T'HH-mm-ss.nVV'--'");
ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);

return now.format(format) + walletFile.getAddress() + ".json";
}

public static String getDefaultKeyDirectory() {
return getDefaultKeyDirectory(System.getProperty("os.name"));
}

static String getDefaultKeyDirectory(String osName1) {
String osName = osName1.toLowerCase();

if (osName.startsWith("mac")) {
return String.format(
"%s%sLibrary%sEthereum", System.getProperty("user.home"), File.separator,
File.separator);
} else if (osName.startsWith("win")) {
return String.format("%s%sEthereum", System.getenv("APPDATA"), File.separator);
} else {
return String.format("%s%s.ethereum", System.getProperty("user.home"), File.separator);
}
}

public static String getTestnetKeyDirectory() {
return String.format(
"%s%stestnet%skeystore", getDefaultKeyDirectory(), File.separator, File.separator);
}

public static String getMainnetKeyDirectory() {
return String.format("%s%skeystore", getDefaultKeyDirectory(), File.separator);
}

/**
* Strip trailing line terminators ({@code \n}/{@code \r}) and a leading
* UTF-8 BOM ({@code \uFEFF}) from a line of input. Unlike
* {@link String#trim()} this preserves internal whitespace, so passwords
* containing spaces (e.g. passphrases) survive intact.
*
* <p>Intended as the canonical helper for normalizing raw user-provided
* password/line input across both CLI console and file-driven paths.
* Returns {@code null} if the input is {@code null}.
*/
public static String stripPasswordLine(String s) {
if (s == null) {
return null;
}
if (s.length() > 0 && s.charAt(0) == '\uFEFF') {
s = s.substring(1);
}
int end = s.length();
while (end > 0) {
char c = s.charAt(end - 1);
if (c == '\n' || c == '\r') {
end--;
} else {
break;
}
}
return s.substring(0, end);
}

public static boolean passwordValid(String password) {
if (StringUtils.isEmpty(password)) {
return false;
}
if (password.length() < 6) {
return false;
}
//Other rule;
return true;
}

/**
* Lazily-initialized Scanner shared across successive
* {@link #inputPassword()} calls on the non-TTY path so that
* {@link #inputPassword2Twice()} can read two lines in sequence
* without losing data. Each call to {@code new Scanner(System.in)}
* internally buffers bytes from the underlying {@link BufferedReader};
* constructing a second Scanner after the first has been discarded
* drops any buffered bytes the first pulled from stdin, causing
* {@code NoSuchElementException}.
*/
private static Scanner sharedStdinScanner;

/**
* Visible for testing: reset the cached Scanner so subsequent calls
* see a freshly rebound {@link System#in}.
*/
static synchronized void resetSharedStdinScanner() {
sharedStdinScanner = null;
}

private static synchronized Scanner getSharedStdinScanner() {
if (sharedStdinScanner == null) {
sharedStdinScanner = new Scanner(System.in);
}
return sharedStdinScanner;
}

public static String inputPassword() {
String password;
Console cons = System.console();
Scanner in = cons == null ? getSharedStdinScanner() : null;
while (true) {
if (cons != null) {
char[] pwd = cons.readPassword("password: ");
password = String.valueOf(pwd);
} else {
// Preserve the full password including embedded whitespace.
// The previous implementation applied trim() + split("\\s+")[0]
// which silently truncated passwords like "correct horse battery
// staple" to "correct" when piped via stdin (e.g. echo ... | java).
// stripPasswordLine only removes the UTF-8 BOM and trailing line
// terminators — internal whitespace is part of the password.
password = stripPasswordLine(in.nextLine());
}
if (passwordValid(password)) {
return password;
}
System.out.println("Invalid password, please input again.");
}
}

public static String inputPassword2Twice() {
String password0;
while (true) {
System.out.println("Please input password.");
password0 = inputPassword();
System.out.println("Please input password again.");
String password1 = inputPassword();
if (password0.equals(password1)) {
break;
}
System.out.println("Two passwords do not match, please input again.");
}
return password0;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,27 @@ public static LocalWitnesses initFromKeystore(

List<String> privateKeys = new ArrayList<>();
try {
Credentials credentials = WalletUtils.loadCredentials(pwd, new File(fileName));
Credentials credentials = WalletUtils.loadCredentials(pwd, new File(fileName),
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#6588 has already decided to remove the unused SM2 algorithm and related configuration. Why is this PR still adding compatibility for it (e.g., the boolean ecKey parameter and --sm2 option)?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@halibobo1205 It has currently been decided to retain SM2. See: #6627 (comment)

Args.getInstance().isECKeyCryptoEngine());
SignInterface sign = credentials.getSignInterface();
String prikey = ByteArray.toHexString(sign.getPrivateKey());
privateKeys.add(prikey);
} catch (IOException | CipherException e) {
logger.error("Witness node start failed!");
// Legacy-truncation hint: if this keystore was created with
// `FullNode.jar --keystore-factory` in non-TTY mode (e.g.
// `echo PASS | java ...`), the legacy code encrypted with only
// the first whitespace-separated word of the password. Emit the
// tip only when the entered password has internal whitespace —
// otherwise truncation cannot be the cause.
if (e instanceof CipherException && pwd != null && pwd.matches(".*\\s.*")) {
logger.error(
"Tip: keystores created via `FullNode.jar --keystore-factory` in "
+ "non-TTY mode were encrypted with only the first "
+ "whitespace-separated word of the password. Try restarting "
+ "with only that first word as `-p`, then reset the password "
+ "via `java -jar Toolkit.jar keystore update`.");
}
throw new TronError(e, TronError.ErrCode.WITNESS_KEYSTORE_LOAD);
}

Expand Down
Loading
Loading