assets: fix unchecked fmemopen result
What changed, and why it matters
This commit fixes a bug where a memory-backed file handle could fail to open, but the code immediately tried to use and close it anyway. If opening failed, the program could crash or behave unpredictably when handling asset contract data on a Blockstream Jade hardware wallet. The fix checks whether the file handle was created successfully before using it.
Treat as a low-to-moderate reliability/defensive fix. Review whether other fmemopen() or fopen() calls in the codebase are similarly unchecked. No immediate incident response required unless paired with a reproducible crash or exploit.
Security signals we found
Unchecked fmemopen() return value (CWE-690 / CWE-476)
Potential NULL pointer dereference in asset contract parsing
Resource cleanup conditional on successful allocation
Evidence from the diff
In main/assets.c, get_asset_contract_hash() calls fmemopen() to create a FILE* stream backed by a stack buffer. Previously, the code did not check if fmemopen returned NULL before passing fstr to cbor_value_to_json() and then fclose(). On memory pressure or other failure, this would cause a NULL pointer dereference/use and a double-cleanup risk. The patch adds a NULL check and only closes the stream if it was actually opened.
Changed components
main/assets.cget_asset_contract_hash()Liquid asset contract CBOR-to-JSON conversionInspect captured patch +4 / −2
diff --git a/main/assets.c b/main/assets.c
index e91d151..53a87da 100644
--- a/main/assets.c
+++ b/main/assets.c
@@ -47,9 +47,11 @@ static bool get_asset_contract_hash(const CborValue* contract, uint8_t* contract
char contract_json[ASSET_CONTRACT_BUFFER_LEN];
FILE* const fstr = fmemopen((uint8_t*)contract_json, sizeof(contract_json), "w");
- if (cbor_value_to_json(fstr, contract, CborConvertDefaultFlags) != CborNoError) {
+ if (!fstr || cbor_value_to_json(fstr, contract, CborConvertDefaultFlags) != CborNoError) {
JADE_LOGE("Failed to convert asset contract data to json");
- fclose(fstr);
+ if (fstr) {
+ fclose(fstr);
+ }
return false;
}
fclose(fstr);
Why this scored 37/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.