From d8d55918b26e529d6b8e073eef14ad5536a90b04 Mon Sep 17 00:00:00 2001 From: Ilya Maykov Date: Mon, 10 Apr 2023 17:43:57 -0700 Subject: [PATCH] [core] clang-format almost all first-party code Added a .clang-format file and auto-formatted almost all first-party code (all except `core/include/config.h` and the auto-generated file `core/src/checks/wycheproof/ecdsa_secp256k1_sha256_bitcoin_test.h`). --- core/.clang-format | 225 ++++++++++++++++++ core/external-crypto/.clang-format | 1 + core/include/aes_gcm_dev.h | 23 +- core/include/aes_gcm_ncipher.h | 20 +- core/include/checks.h | 2 +- core/include/config.h | 5 + core/include/hash.h | 14 +- core/include/init_wallet.h | 3 +- core/include/log.h | 66 ++--- core/include/memzero.h | 2 +- core/include/module_certificate.h | 2 +- core/include/print.h | 6 +- core/include/protection.h | 14 +- core/include/qrsignatures.h | 2 +- core/include/rpc.h | 8 +- core/include/script.h | 12 +- core/include/sign.h | 2 +- core/include/strlcpy.h | 40 ++-- core/include/transact.h | 3 +- core/proto/.clang-format | 1 + core/src/checks/bip32.c | 25 +- core/src/checks/check_sign_tx.c | 101 ++++---- core/src/checks/conv_checks.c | 33 +-- core/src/checks/misc_checks.c | 1 + core/src/checks/validate_fees.c | 33 ++- core/src/checks/verify_mix_entropy.c | 40 ++-- core/src/checks/verify_protect_pubkey.c | 3 +- .../ecdsa_secp256k1_sha256_bitcoin_test.h | 4 + core/src/checks/wycheproof_checks.c | 147 ++++++------ core/src/conv.c | 2 +- core/src/dev/additional_checks.c | 8 +- core/src/dev/aes_gcm.c | 94 ++++---- core/src/dev/execute_command_hooks.c | 2 +- core/src/dev/init.c | 4 +- core/src/dev/init_wallet.c | 11 +- core/src/dev/no_rollback.c | 5 +- core/src/dev/protection.c | 9 +- core/src/finalize_wallet.c | 26 +- core/src/fuzz.c | 6 +- core/src/hash.c | 22 +- core/src/init_wallet.c | 3 +- core/src/main.c | 13 +- core/src/memzero.c | 8 +- core/src/nanopb_stream.c | 18 +- core/src/ncipher/additional_checks.c | 44 ++-- core/src/ncipher/aes_gcm.c | 66 ++--- core/src/ncipher/execute_command_hooks.c | 28 +-- core/src/ncipher/init.c | 4 +- core/src/ncipher/init_wallet.c | 17 +- core/src/ncipher/module_certificate.c | 10 +- core/src/ncipher/no_rollback.c | 11 +- core/src/ncipher/protection.c | 1 - core/src/ncipher/transact.c | 2 +- core/src/print.c | 26 +- core/src/protect.c | 63 ++--- core/src/qrsignatures.c | 13 +- core/src/rpc.c | 64 ++--- core/src/script.c | 4 +- core/src/sign.c | 106 ++++----- core/trezor-crypto/.clang-format | 1 + utils/tests_wycheproof_generate.py | 5 +- 61 files changed, 881 insertions(+), 653 deletions(-) create mode 100644 core/.clang-format create mode 100644 core/external-crypto/.clang-format create mode 100644 core/proto/.clang-format create mode 100644 core/trezor-crypto/.clang-format diff --git a/core/.clang-format b/core/.clang-format new file mode 100644 index 00000000..cc8f85ea --- /dev/null +++ b/core/.clang-format @@ -0,0 +1,225 @@ +# see https://clang.llvm.org/docs/ClangFormatStyleOptions.html +--- +# BasedOnStyle: Mozilla + +Language: Cpp +AccessModifierOffset: -2 +AlignAfterOpenBracket: AlwaysBreak +AlignArrayOfStructures: None +AlignConsecutiveAssignments: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: true +AlignConsecutiveBitFields: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: false +AlignConsecutiveDeclarations: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: false +AlignConsecutiveMacros: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: false +AlignEscapedNewlines: Left +AlignOperands: Align +AlignTrailingComments: + Kind: Always + OverEmptyLines: 0 +AllowAllArgumentsOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: false +AllowShortBlocksOnASingleLine: Never +AllowShortCaseLabelsOnASingleLine: false +AllowShortEnumsOnASingleLine: true +AllowShortFunctionsOnASingleLine: Inline +AllowShortIfStatementsOnASingleLine: Never +AllowShortLambdasOnASingleLine: All +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: true +AlwaysBreakTemplateDeclarations: Yes +AttributeMacros: + - __capability +BinPackArguments: false +BinPackParameters: false +BitFieldColonSpacing: Both +BraceWrapping: + AfterCaseLabel: false + AfterClass: false + AfterControlStatement: Never + AfterEnum: false + AfterExternBlock: false + AfterFunction: false + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: false + SplitEmptyRecord: false + SplitEmptyNamespace: false +BreakAfterAttributes: Never +BreakAfterJavaFieldAnnotations: false +BreakArrays: false +BreakBeforeBinaryOperators: None +BreakBeforeConceptDeclarations: Always +BreakBeforeBraces: Custom +BreakBeforeInlineASMColon: OnlyMultiline +BreakBeforeTernaryOperators: true +BreakConstructorInitializers: AfterColon +BreakInheritanceList: AfterColon +BreakStringLiterals: true +ColumnLimit: 120 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: false +DerivePointerAlignment: false +DisableFormat: false +EmptyLineAfterAccessModifier: Never +EmptyLineBeforeAccessModifier: LogicalBlock +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IfMacros: + - KJ_IF_MAYBE +IncludeBlocks: Regroup +IncludeCategories: + - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 3 + SortPriority: 0 + CaseSensitive: false + - Regex: '.*' + Priority: 1 + SortPriority: 0 + CaseSensitive: false +IncludeIsMainRegex: '(Test)?$' +IncludeIsMainSourceRegex: '' +IndentAccessModifiers: false +IndentCaseBlocks: false +IndentCaseLabels: false +IndentExternBlock: AfterExternBlock +IndentGotoLabels: true +IndentPPDirectives: BeforeHash +IndentRequiresClause: true +IndentWidth: 2 +IndentWrappedFunctionNames: false +InsertBraces: true +InsertNewlineAtEOF: true +InsertTrailingCommas: None +IntegerLiteralSeparator: + Binary: 0 + BinaryMinDigits: 0 + Decimal: 0 + DecimalMinDigits: 0 + Hex: 0 + HexMinDigits: 0 +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: false +LambdaBodyIndentation: Signature +LineEnding: DeriveLF +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 2 +ObjCBreakBeforeNestedBlockParam: true +ObjCSpaceAfterProperty: true +ObjCSpaceBeforeProtocolList: false +PackConstructorInitializers: CurrentLine +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakOpenParenthesis: 0 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyIndentedWhitespace: 0 +PenaltyReturnTypeOnItsOwnLine: 200 +PointerAlignment: Left +PPIndentWidth: -1 +QualifierAlignment: Leave +ReferenceAlignment: Pointer +ReflowComments: true +RemoveBracesLLVM: false +RemoveSemicolon: true +RequiresClausePosition: OwnLine +RequiresExpressionIndentation: OuterScope +SeparateDefinitionBlocks: Always +ShortNamespaceLines: 1 +SortIncludes: CaseSensitive +SortJavaStaticImport: Before +SortUsingDeclarations: LexicographicNumeric +SpaceAfterCStyleCast: true +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: false +SpaceAroundPointerQualifiers: Default +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: Custom +SpaceBeforeParensOptions: + AfterControlStatements: true + AfterForeachMacros: true + AfterFunctionDefinitionName: false + AfterFunctionDeclarationName: false + AfterIfMacros: true + AfterOverloadedOperator: false + AfterRequiresInClause: false + AfterRequiresInExpression: false + BeforeNonEmptyParentheses: false +SpaceBeforeRangeBasedForLoopColon: true +SpaceBeforeSquareBrackets: false +SpaceInEmptyBlock: false +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: Never +SpacesInConditionalStatement: false +SpacesInContainerLiterals: false +SpacesInCStyleCastParentheses: false +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Latest +StatementAttributeLikeMacros: + - Q_EMIT +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TabWidth: 8 +UseTab: Never +WhitespaceSensitiveMacros: + - BOOST_PP_STRINGIZE + - CF_SWIFT_NAME + - NS_SWIFT_NAME + - PP_STRINGIZE + - STRINGIZE diff --git a/core/external-crypto/.clang-format b/core/external-crypto/.clang-format new file mode 100644 index 00000000..e3845288 --- /dev/null +++ b/core/external-crypto/.clang-format @@ -0,0 +1 @@ +DisableFormat: true diff --git a/core/include/aes_gcm_dev.h b/core/include/aes_gcm_dev.h index 71fff4b2..b3475107 100644 --- a/core/include/aes_gcm_dev.h +++ b/core/include/aes_gcm_dev.h @@ -19,17 +19,24 @@ // reserved for an invalid key object in the nCipher target. We would like to // simulate this behavior in the dev target, and therefore avoid value 0 for // M_KeyID enum below. -typedef enum {master_seed_encryption_key = 1, - pub_key_encryption_key = 2} M_KeyID; +typedef enum { master_seed_encryption_key = 1, pub_key_encryption_key = 2 } M_KeyID; // Key encryption key declaration, for AES-128-GCM // KEK[0], i.e., KEK[master_seed_encryption_key - 1], is master seed encryption key // KEK[1], i.e., KEK[pub_key_encryption_key], is public key encryption key extern uint8_t KEK[2][16]; -Result aes_gcm_encrypt(M_KeyID keyId, uint8_t *plaintext, size_t plaintext_len, - uint8_t *ciphertext, size_t ciphertext_len, - size_t *bytes_written); -Result aes_gcm_decrypt(M_KeyID keyId, const uint8_t *ciphertext, - size_t ciphertext_len, uint8_t *plaintext, - size_t plaintext_len, size_t *bytes_written); +Result aes_gcm_encrypt( + M_KeyID keyId, + uint8_t* plaintext, + size_t plaintext_len, + uint8_t* ciphertext, + size_t ciphertext_len, + size_t* bytes_written); +Result aes_gcm_decrypt( + M_KeyID keyId, + const uint8_t* ciphertext, + size_t ciphertext_len, + uint8_t* plaintext, + size_t plaintext_len, + size_t* bytes_written); diff --git a/core/include/aes_gcm_ncipher.h b/core/include/aes_gcm_ncipher.h index a05eb148..2e40d900 100644 --- a/core/include/aes_gcm_ncipher.h +++ b/core/include/aes_gcm_ncipher.h @@ -13,9 +13,17 @@ // aes_gcm_ncipher:$(echo -n "aes_gcm_ncipher" | sha256sum | cut -c1-16) #define MAGIC "aes_gcm_ncipher:ffb944993c73a1d3" -Result aes_gcm_encrypt(M_KeyID keyId, uint8_t *plaintext, size_t plaintext_len, - uint8_t *ciphertext, size_t ciphertext_len, - size_t *bytes_written); -Result aes_gcm_decrypt(M_KeyID keyId, const uint8_t *ciphertext, - size_t ciphertext_len, uint8_t *plaintext, - size_t plaintext_len, size_t *bytes_written); +Result aes_gcm_encrypt( + M_KeyID keyId, + uint8_t* plaintext, + size_t plaintext_len, + uint8_t* ciphertext, + size_t ciphertext_len, + size_t* bytes_written); +Result aes_gcm_decrypt( + M_KeyID keyId, + const uint8_t* ciphertext, + size_t ciphertext_len, + uint8_t* plaintext, + size_t plaintext_len, + size_t* bytes_written); diff --git a/core/include/checks.h b/core/include/checks.h index 0f54edeb..7cf5bca0 100644 --- a/core/include/checks.h +++ b/core/include/checks.h @@ -63,4 +63,4 @@ int verify_rpc_oversized_message_rejected(void); ERROR("got: %s", value); \ return -1; \ } \ - } while(0) + } while (0) diff --git a/core/include/config.h b/core/include/config.h index df952804..27953526 100644 --- a/core/include/config.h +++ b/core/include/config.h @@ -1,3 +1,6 @@ +// clang-format off +// (to avoid conflicting with production patch files) + #pragma once // maximum size for xpub. TODO: we can make this 112 bytes, based on: @@ -119,3 +122,5 @@ #define MASTER_SEED_SIZE 64 #define COMPRESSED_PUBKEY_SIZE 33 + +// clang-format on diff --git a/core/include/hash.h b/core/include/hash.h index dce634e3..b053394e 100644 --- a/core/include/hash.h +++ b/core/include/hash.h @@ -4,13 +4,13 @@ #include #include -void hash_uint8(Hasher *hasher, uint8_t value); -void hash_uint16(Hasher *hasher, uint16_t value); -void hash_uint32(Hasher *hasher, uint32_t value); -void hash_uint64(Hasher *hasher, uint64_t value); +void hash_uint8(Hasher* hasher, uint8_t value); +void hash_uint16(Hasher* hasher, uint16_t value); +void hash_uint32(Hasher* hasher, uint32_t value); +void hash_uint64(Hasher* hasher, uint64_t value); // hashes are serialized in "normal" order -void hash_bytes(Hasher *hasher, const uint8_t *data, size_t len); +void hash_bytes(Hasher* hasher, const uint8_t* data, size_t len); // addresses are serialized in reverse order -void hash_rev_bytes(Hasher *hasher, const uint8_t *data, size_t len); +void hash_rev_bytes(Hasher* hasher, const uint8_t* data, size_t len); // scripts are serialized with a length prefix -void hash_var_bytes(Hasher *hasher, const uint8_t *data, size_t len); +void hash_var_bytes(Hasher* hasher, const uint8_t* data, size_t len); diff --git a/core/include/init_wallet.h b/core/include/init_wallet.h index aca9bbe3..ef712a95 100644 --- a/core/include/init_wallet.h +++ b/core/include/init_wallet.h @@ -5,5 +5,4 @@ #include -Result mix_entropy(uint8_t wallet_entropy[static MASTER_SEED_SIZE], - const InternalCommandRequest* const in); +Result mix_entropy(uint8_t wallet_entropy[static MASTER_SEED_SIZE], const InternalCommandRequest* const in); diff --git a/core/include/log.h b/core/include/log.h index ef23a38e..70222c5e 100644 --- a/core/include/log.h +++ b/core/include/log.h @@ -23,46 +23,58 @@ #if ENABLE_DEBUG_LOGGING == 1 // Print DEBUG to stdout in cyan - #define DEBUG(...) \ - do { \ - printf("\033[0;36m"); \ - printf("[DEBUG] %s:%d ", __FILENAME__, __LINE__); \ - printf(__VA_ARGS__); \ - printf("\033[0m\n"); \ + #define DEBUG(...) \ + do { \ + printf("\033[0;36m"); \ + printf("[DEBUG] %s:%d ", __FILENAME__, __LINE__); \ + printf(__VA_ARGS__); \ + printf("\033[0m\n"); \ } while (0) - #define DEBUG_(...) \ - do { \ - printf("\033[0;36m"); \ - printf(__VA_ARGS__); \ - printf("\033[0m"); \ + #define DEBUG_(...) \ + do { \ + printf("\033[0;36m"); \ + printf(__VA_ARGS__); \ + printf("\033[0m"); \ } while (0) #else - #define DEBUG(...) do { snprintf(NULL, 0, __VA_ARGS__); } while(0) - #define DEBUG_(...) do { snprintf(NULL, 0, __VA_ARGS__); } while(0) + #define DEBUG(...) \ + do { \ + snprintf(NULL, 0, __VA_ARGS__); \ + } while (0) + #define DEBUG_(...) \ + do { \ + snprintf(NULL, 0, __VA_ARGS__); \ + } while (0) #endif #if ENABLE_INFO_AND_ERROR_LOGGING == 1 // Print INFO to stdout in green - #define INFO(...) \ - do { \ - printf("\033[0;32m"); \ - printf("[INFO] %s:%d ", __FILENAME__, __LINE__); \ - printf(__VA_ARGS__); \ - printf("\033[0m\n"); \ + #define INFO(...) \ + do { \ + printf("\033[0;32m"); \ + printf("[INFO] %s:%d ", __FILENAME__, __LINE__); \ + printf(__VA_ARGS__); \ + printf("\033[0m\n"); \ } while (0) // Print ERROR to stdout in red - #define ERROR(...) \ - do { \ - printf("\033[0;31m"); \ - printf("[ERROR] %s:%d ", __FILENAME__, __LINE__); \ - printf(__VA_ARGS__); \ - printf("\033[0m\n"); \ + #define ERROR(...) \ + do { \ + printf("\033[0;31m"); \ + printf("[ERROR] %s:%d ", __FILENAME__, __LINE__); \ + printf(__VA_ARGS__); \ + printf("\033[0m\n"); \ } while (0) #else - #define INFO(...) do { snprintf(NULL, 0, __VA_ARGS__); } while(0) - #define ERROR(...) do { snprintf(NULL, 0, __VA_ARGS__); } while(0) + #define INFO(...) \ + do { \ + snprintf(NULL, 0, __VA_ARGS__); \ + } while (0) + #define ERROR(...) \ + do { \ + snprintf(NULL, 0, __VA_ARGS__); \ + } while (0) #endif #undef ENABLE_DEBUG_LOGGING diff --git a/core/include/memzero.h b/core/include/memzero.h index 683be187..08a649b6 100644 --- a/core/include/memzero.h +++ b/core/include/memzero.h @@ -1,4 +1,4 @@ #pragma once #include -void memzero(void *s, size_t n); +void memzero(void* s, size_t n); diff --git a/core/include/module_certificate.h b/core/include/module_certificate.h index bc0286f7..ad787da9 100644 --- a/core/include/module_certificate.h +++ b/core/include/module_certificate.h @@ -6,4 +6,4 @@ #include Result module_certificate_init(M_CertificateList* cert_list, M_Certificate certs[static SEE_CERT_SIGNER_SIZE]); -void module_certificate_cleanup(M_CertificateList *cert_list); \ No newline at end of file +void module_certificate_cleanup(M_CertificateList* cert_list); diff --git a/core/include/print.h b/core/include/print.h index 6628f49a..f6b0a2e8 100644 --- a/core/include/print.h +++ b/core/include/print.h @@ -7,6 +7,6 @@ void print_uint8(uint8_t value); void print_uint16(uint16_t value); void print_uint32(uint32_t value); void print_uint64(uint64_t value); -void print_bytes(const uint8_t *buffer, size_t len); -void print_rev_bytes(const uint8_t *buffer, size_t len); -void print_var_bytes(const uint8_t *buffer, size_t len); +void print_bytes(const uint8_t* buffer, size_t len); +void print_rev_bytes(const uint8_t* buffer, size_t len); +void print_var_bytes(const uint8_t* buffer, size_t len); diff --git a/core/include/protection.h b/core/include/protection.h index 17e8d25b..37cc0dec 100644 --- a/core/include/protection.h +++ b/core/include/protection.h @@ -11,26 +11,24 @@ * * Always zeros xpub. */ -Result protect_pubkey(char xpub[static XPUB_SIZE], - EncryptedPubKey *encrypted_pub_key); +Result protect_pubkey(char xpub[static XPUB_SIZE], EncryptedPubKey* encrypted_pub_key); /** * Decrypt encrypted_pub_key with pubkey encryption key. */ -Result expose_pubkey(const EncryptedPubKey* const encrypted_pub_key, - char xpub[static XPUB_SIZE]); +Result expose_pubkey(const EncryptedPubKey* const encrypted_pub_key, char xpub[static XPUB_SIZE]); /** * Encrypt master_seed with master_seed_encryption_key. * * Zeros master_seed. */ -Result protect_wallet(uint8_t master_seed[static MASTER_SEED_SIZE], - EncryptedMasterSeed *encrypted_master_seed); +Result protect_wallet(uint8_t master_seed[static MASTER_SEED_SIZE], EncryptedMasterSeed* encrypted_master_seed); /** * Decrypt master_seed with master_seed_encryption_key. In dev, we XOR with a * magic byte. */ -Result expose_wallet(const EncryptedMasterSeed* const encrypted_master_seed, - uint8_t master_seed[static MASTER_SEED_SIZE]); +Result expose_wallet( + const EncryptedMasterSeed* const encrypted_master_seed, + uint8_t master_seed[static MASTER_SEED_SIZE]); diff --git a/core/include/qrsignatures.h b/core/include/qrsignatures.h index bab085a7..cd3d9f12 100644 --- a/core/include/qrsignatures.h +++ b/core/include/qrsignatures.h @@ -16,7 +16,7 @@ * - None of the pointers may be NULL. * - data_len must be > 0. * - signature_len must equal QRSIGNATURE_LEN. - * + * * @return true on successful signature verification and false otherwise. */ bool check_qrsignature( diff --git a/core/include/rpc.h b/core/include/rpc.h index 448dc358..fba8baff 100644 --- a/core/include/rpc.h +++ b/core/include/rpc.h @@ -3,15 +3,13 @@ #include "pb.h" #include "squareup/subzero/internal.pb.h" -void handle_incoming_message(pb_istream_t *input, pb_ostream_t *output); +void handle_incoming_message(pb_istream_t* input, pb_ostream_t* output); -Result handle_init_wallet( - const InternalCommandRequest* const in, - InternalCommandResponse_InitWalletResponse *out); +Result handle_init_wallet(const InternalCommandRequest* const in, InternalCommandResponse_InitWalletResponse* out); Result handle_finalize_wallet( const InternalCommandRequest_FinalizeWalletRequest* const in, - InternalCommandResponse_FinalizeWalletResponse *out); + InternalCommandResponse_FinalizeWalletResponse* out); Result pre_execute_command(const InternalCommandRequest* const in); void post_execute_command(void); diff --git a/core/include/script.h b/core/include/script.h index adbc9078..b30b3778 100644 --- a/core/include/script.h +++ b/core/include/script.h @@ -12,9 +12,11 @@ typedef struct _script_t { uint8_t data[SCRIPT_MAX_LEN]; } script_t; -#define SCRIPT_EMPTY \ - { \ - 0, { 0 } \ +#define SCRIPT_EMPTY \ + { \ + 0, { \ + 0 \ + } \ } /** Script opcodes */ @@ -162,5 +164,5 @@ enum opcodetype { OP_INVALIDOPCODE = 0xff, }; -Result script_push(script_t *script, enum opcodetype opcode); -Result script_push_data(script_t *script, const uint8_t *data, size_t len); +Result script_push(script_t* script, enum opcodetype opcode); +Result script_push_data(script_t* script, const uint8_t* data, size_t len); diff --git a/core/include/sign.h b/core/include/sign.h index 8434cf64..b3c06338 100644 --- a/core/include/sign.h +++ b/core/include/sign.h @@ -6,6 +6,6 @@ Result handle_sign_tx( const InternalCommandRequest_SignTxRequest* const request, - InternalCommandResponse_SignTxResponse *response); + InternalCommandResponse_SignTxResponse* response); bool validate_fees(const InternalCommandRequest_SignTxRequest* const request); diff --git a/core/include/strlcpy.h b/core/include/strlcpy.h index e3bc0262..5f2cb9d7 100644 --- a/core/include/strlcpy.h +++ b/core/include/strlcpy.h @@ -24,27 +24,27 @@ * chars will be copied. Always NUL terminates (unless dsize == 0). * Returns strlen(src); if retval >= dsize, truncation occurred. */ -static inline size_t -subzero_strlcpy(char *dst, const char *src, size_t dsize) -{ - const char *osrc = src; - size_t nleft = dsize; +static inline size_t subzero_strlcpy(char* dst, const char* src, size_t dsize) { + const char* osrc = src; + size_t nleft = dsize; - /* Copy as many bytes as will fit. */ - if (nleft != 0) { - while (--nleft != 0) { - if ((*dst++ = *src++) == '\0') - break; - } - } + /* Copy as many bytes as will fit. */ + if (nleft != 0) { + while (--nleft != 0) { + if ((*dst++ = *src++) == '\0') { + break; + } + } + } - /* Not enough room in dst, add NUL and traverse rest of src. */ - if (nleft == 0) { - if (dsize != 0) - *dst = '\0'; /* NUL-terminate dst */ - while (*src++) - ; - } + /* Not enough room in dst, add NUL and traverse rest of src. */ + if (nleft == 0) { + if (dsize != 0) { + *dst = '\0'; /* NUL-terminate dst */ + } + while (*src++) + ; + } - return(src - osrc - 1); /* count does not include NUL */ + return (src - osrc - 1); /* count does not include NUL */ } diff --git a/core/include/transact.h b/core/include/transact.h index 67e9673d..41b0b659 100644 --- a/core/include/transact.h +++ b/core/include/transact.h @@ -4,5 +4,4 @@ #include -Result transact(M_Command *command, M_Reply *reply); - +Result transact(M_Command* command, M_Reply* reply); diff --git a/core/proto/.clang-format b/core/proto/.clang-format new file mode 100644 index 00000000..e3845288 --- /dev/null +++ b/core/proto/.clang-format @@ -0,0 +1 @@ +DisableFormat: true diff --git a/core/src/checks/bip32.c b/core/src/checks/bip32.c index 01f50a65..08f47dc3 100644 --- a/core/src/checks/bip32.c +++ b/core/src/checks/bip32.c @@ -18,8 +18,9 @@ * TODO(alok): use "official" test vectors? */ int verify_bip32(void) { - const char *mnemonic = "license amount assist beach story farm duck among " - "door meat prepare path"; + const char* mnemonic = + "license amount assist beach story farm duck among " + "door meat prepare path"; if (!mnemonic_check(mnemonic)) { ERROR("mnemonic_check failed."); return -1; @@ -27,15 +28,17 @@ int verify_bip32(void) { // Derive and check seed uint8_t seed[SHA512_DIGEST_LENGTH]; - mnemonic_to_seed(mnemonic, /* passphrase */ "", seed, - /* progress_callback */ NULL); - uint8_t expected_seed[SHA512_DIGEST_LENGTH] = { - 0x16, 0x0a, 0x87, 0x8c, 0x27, 0xef, 0xfd, 0xb5, 0x6f, 0xff, 0xda, - 0x39, 0x11, 0xed, 0x1f, 0x2f, 0x04, 0x80, 0x44, 0x2b, 0xed, 0x6b, - 0xd1, 0x81, 0xb1, 0x23, 0xbe, 0xa7, 0x26, 0x80, 0x4e, 0x33, 0xac, - 0x38, 0x4b, 0xf2, 0x8a, 0xfc, 0x25, 0x83, 0xbf, 0x97, 0x2a, 0x1a, - 0x41, 0x9b, 0x6c, 0x89, 0x7f, 0xae, 0x6c, 0x8a, 0x48, 0x23, 0x76, - 0x27, 0xbe, 0x86, 0xa5, 0xaa, 0xde, 0x06, 0x70, 0xb3}; + mnemonic_to_seed( + mnemonic, + /* passphrase */ "", + seed, + /* progress_callback */ NULL); + uint8_t expected_seed[SHA512_DIGEST_LENGTH] = { 0x16, 0x0a, 0x87, 0x8c, 0x27, 0xef, 0xfd, 0xb5, 0x6f, 0xff, 0xda, + 0x39, 0x11, 0xed, 0x1f, 0x2f, 0x04, 0x80, 0x44, 0x2b, 0xed, 0x6b, + 0xd1, 0x81, 0xb1, 0x23, 0xbe, 0xa7, 0x26, 0x80, 0x4e, 0x33, 0xac, + 0x38, 0x4b, 0xf2, 0x8a, 0xfc, 0x25, 0x83, 0xbf, 0x97, 0x2a, 0x1a, + 0x41, 0x9b, 0x6c, 0x89, 0x7f, 0xae, 0x6c, 0x8a, 0x48, 0x23, 0x76, + 0x27, 0xbe, 0x86, 0xa5, 0xaa, 0xde, 0x06, 0x70, 0xb3 }; if (memcmp(seed, expected_seed, SHA512_DIGEST_LENGTH) != 0) { ERROR("seed != expected_seed"); return -1; diff --git a/core/src/checks/check_sign_tx.c b/core/src/checks/check_sign_tx.c index b466cb4e..299ebd0d 100644 --- a/core/src/checks/check_sign_tx.c +++ b/core/src/checks/check_sign_tx.c @@ -21,9 +21,8 @@ #include // Return a constructed request for test -static int construct_request(InternalCommandRequest_SignTxRequest *tx) { - - const char *mnemonic1 = +static int construct_request(InternalCommandRequest_SignTxRequest* tx) { + const char* mnemonic1 = "turn inch relief grit abuse machine riot proof they model way dad " "pelican oven gold spoil cave gloom dismiss dress leader scale isolate " "tribe"; @@ -33,8 +32,11 @@ static int construct_request(InternalCommandRequest_SignTxRequest *tx) { } uint8_t seed[MASTER_SEED_SIZE]; static_assert(MASTER_SEED_SIZE >= 64, "MASTER_SEED_SIZE too small"); - mnemonic_to_seed(mnemonic1, /* passphrase */ "", seed, - /* progress_callback */ NULL); + mnemonic_to_seed( + mnemonic1, + /* passphrase */ "", + seed, + /* progress_callback */ NULL); // "Encrypt" seed as if it had come from init_wallet Result r = protect_wallet(seed, &tx->encrypted_master_seed); @@ -43,7 +45,7 @@ static int construct_request(InternalCommandRequest_SignTxRequest *tx) { return -1; } - char wallets[MULTISIG_PARTS][XPUB_SIZE] = {TEST_WALLET_1, TEST_WALLET_2, TEST_WALLET_3, TEST_WALLET_4}; + char wallets[MULTISIG_PARTS][XPUB_SIZE] = { TEST_WALLET_1, TEST_WALLET_2, TEST_WALLET_3, TEST_WALLET_4 }; // Encrypt each pubkey as if it had come from finalize_wallet for (int i = 0; i < MULTISIG_PARTS; i++) { @@ -57,10 +59,9 @@ static int construct_request(InternalCommandRequest_SignTxRequest *tx) { // Create signature tx->inputs_count = 1; - pb_byte_t prev_hash[] = {0xd3, 0x73, 0x65, 0xc6, 0xa3, 0xc0, 0x89, 0x57, - 0x6b, 0x1e, 0xa1, 0xcb, 0x8b, 0xee, 0x2b, 0xaa, - 0x00, 0x5a, 0xfc, 0x96, 0xd2, 0x40, 0x80, 0x51, - 0x56, 0x35, 0xf8, 0x52, 0xc6, 0x80, 0xd1, 0x27}; + pb_byte_t prev_hash[] = { 0xd3, 0x73, 0x65, 0xc6, 0xa3, 0xc0, 0x89, 0x57, 0x6b, 0x1e, 0xa1, + 0xcb, 0x8b, 0xee, 0x2b, 0xaa, 0x00, 0x5a, 0xfc, 0x96, 0xd2, 0x40, + 0x80, 0x51, 0x56, 0x35, 0xf8, 0x52, 0xc6, 0x80, 0xd1, 0x27 }; memcpy(tx->inputs[0].prev_hash, prev_hash, sizeof(prev_hash)); tx->inputs[0].prev_index = 0; tx->inputs[0].has_amount = true; @@ -92,12 +93,10 @@ static int construct_request(InternalCommandRequest_SignTxRequest *tx) { * Self-check with a fixed transaction. */ int verify_sign_tx(void) { - InternalCommandRequest_SignTxRequest tx = - InternalCommandRequest_SignTxRequest_init_default; + InternalCommandRequest_SignTxRequest tx = InternalCommandRequest_SignTxRequest_init_default; construct_request(&tx); - InternalCommandResponse_SignTxResponse resp = - InternalCommandResponse_SignTxResponse_init_default; + InternalCommandResponse_SignTxResponse resp = InternalCommandResponse_SignTxResponse_init_default; INFO("checking sign_tx."); Result r = handle_sign_tx(&tx, &resp); if (r != Result_SUCCESS) { @@ -108,23 +107,20 @@ int verify_sign_tx(void) { uint8_t expected_der[] = EXPECTED_SIGNATURE; if (resp.signatures_count != tx.inputs_count) { - ERROR("Unexpected signatures_count: %d != %d", resp.signatures_count, - tx.inputs_count); + ERROR("Unexpected signatures_count: %d != %d", resp.signatures_count, tx.inputs_count); return -1; } if (resp.signatures[0].der.size != sizeof(expected_der)) { - ERROR("unexpected der_len: %d != %zu.", resp.signatures[0].der.size, - sizeof(expected_der)); + ERROR("unexpected der_len: %d != %zu.", resp.signatures[0].der.size, sizeof(expected_der)); return -1; } - if (memcmp(resp.signatures[0].der.bytes, expected_der, - resp.signatures[0].der.size) != 0) { + if (memcmp(resp.signatures[0].der.bytes, expected_der, resp.signatures[0].der.size) != 0) { ERROR("der mismatch."); print_bytes(expected_der, sizeof(expected_der)); print_bytes(resp.signatures[0].der.bytes, resp.signatures[0].der.size); return -1; } - + return 0; } @@ -134,57 +130,42 @@ int verify_sign_tx(void) { * It will just test our verify signature wrapper. */ -int verify_check_qrsignature_pub(void){ +int verify_check_qrsignature_pub(void) { INFO("Checking check_qrsignature_pub."); // Test ECDSA private key. - uint8_t private_key[32] = { - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 - }; + uint8_t private_key[32] = { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 }; // bytes to be signed. - uint8_t buf[8] = { - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 - }; - - uint8_t signature[QRSIGNATURE_LEN] = {0}; - - // echo "ef3fd8719c72b1410df9494c61bc99825b73a2236b54832d524dc9f8d261c3c04c7b5c0f1527a74e3432f319e576fba8ac402b378c47fed2760dfc933e382096" | xxd -r -p | xxd -i - uint8_t expected_signature[QRSIGNATURE_LEN] = { - 0xef, 0x3f, 0xd8, 0x71, 0x9c, 0x72, 0xb1, 0x41, 0x0d, 0xf9, 0x49, 0x4c, - 0x61, 0xbc, 0x99, 0x82, 0x5b, 0x73, 0xa2, 0x23, 0x6b, 0x54, 0x83, 0x2d, - 0x52, 0x4d, 0xc9, 0xf8, 0xd2, 0x61, 0xc3, 0xc0, 0x4c, 0x7b, 0x5c, 0x0f, - 0x15, 0x27, 0xa7, 0x4e, 0x34, 0x32, 0xf3, 0x19, 0xe5, 0x76, 0xfb, 0xa8, - 0xac, 0x40, 0x2b, 0x37, 0x8c, 0x47, 0xfe, 0xd2, 0x76, 0x0d, 0xfc, 0x93, - 0x3e, 0x38, 0x20, 0x96 - }; - - - if(0 != ecdsa_sign( - (const ecdsa_curve *)&nist256p1, - HASHER_SHA2, - private_key, - buf, - sizeof(buf), - signature, - NULL, - NULL - ) - ){ + uint8_t buf[8] = { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 }; + + uint8_t signature[QRSIGNATURE_LEN] = { 0 }; + + // echo + // "ef3fd8719c72b1410df9494c61bc99825b73a2236b54832d524dc9f8d261c3c04c7b5c0f1527a74e3432f319e576fba8ac402b378c47fed2760dfc933e382096" + // | xxd -r -p | xxd -i + uint8_t expected_signature[QRSIGNATURE_LEN] = { 0xef, 0x3f, 0xd8, 0x71, 0x9c, 0x72, 0xb1, 0x41, 0x0d, 0xf9, 0x49, + 0x4c, 0x61, 0xbc, 0x99, 0x82, 0x5b, 0x73, 0xa2, 0x23, 0x6b, 0x54, + 0x83, 0x2d, 0x52, 0x4d, 0xc9, 0xf8, 0xd2, 0x61, 0xc3, 0xc0, 0x4c, + 0x7b, 0x5c, 0x0f, 0x15, 0x27, 0xa7, 0x4e, 0x34, 0x32, 0xf3, 0x19, + 0xe5, 0x76, 0xfb, 0xa8, 0xac, 0x40, 0x2b, 0x37, 0x8c, 0x47, 0xfe, + 0xd2, 0x76, 0x0d, 0xfc, 0x93, 0x3e, 0x38, 0x20, 0x96 }; + + if (0 != + ecdsa_sign((const ecdsa_curve*) &nist256p1, HASHER_SHA2, private_key, buf, sizeof(buf), signature, NULL, NULL)) { ERROR("Could not sign during self check."); return 1; } DEBUG("Signature:"); print_bytes(signature, QRSIGNATURE_LEN); - if(memcmp(signature, expected_signature, sizeof(signature)) != 0){ + if (memcmp(signature, expected_signature, sizeof(signature)) != 0) { ERROR("Expected signature was not generated."); return 2; } - uint8_t pub[QRSIGNATURE_PUBKEY_LEN] = {0}; - ecdsa_get_public_key65((const ecdsa_curve *)&nist256p1, private_key, pub); + uint8_t pub[QRSIGNATURE_PUBKEY_LEN] = { 0 }; + ecdsa_get_public_key65((const ecdsa_curve*) &nist256p1, private_key, pub); // flip sig bits. signature[sizeof(signature) - 1] ^= 0xff; // This should return false. @@ -196,7 +177,7 @@ int verify_check_qrsignature_pub(void){ // flip data bits. buf[0] ^= 0xff; - //this should return false. + // this should return false. if (check_qrsignature_pub(buf, sizeof(buf), signature, sizeof(signature), pub, sizeof(pub))) { ERROR("Signature should not have verified with wrong data."); return 4; diff --git a/core/src/checks/conv_checks.c b/core/src/checks/conv_checks.c index 63af5751..af182e7e 100644 --- a/core/src/checks/conv_checks.c +++ b/core/src/checks/conv_checks.c @@ -9,11 +9,12 @@ int verify_conv_btc_to_satoshi(void) { uint64_t satoshi = conv_btc_to_satoshi(btc); uint64_t expected = 0; if (satoshi != expected) { - ERROR("%s: conv_btc_to_satoshi(%" PRIu32 ") returned %" PRIu64 " (expected: %" PRIu64 ")", - __func__, - btc, - satoshi, - expected); + ERROR( + "%s: conv_btc_to_satoshi(%" PRIu32 ") returned %" PRIu64 " (expected: %" PRIu64 ")", + __func__, + btc, + satoshi, + expected); return -1; } @@ -21,11 +22,12 @@ int verify_conv_btc_to_satoshi(void) { satoshi = conv_btc_to_satoshi(btc); expected = 100000000ull; if (satoshi != expected) { - ERROR("%s: conv_btc_to_satoshi(%" PRIu32 ") returned %" PRIu64 " (expected: %" PRIu64 ")", - __func__, - btc, - satoshi, - expected); + ERROR( + "%s: conv_btc_to_satoshi(%" PRIu32 ") returned %" PRIu64 " (expected: %" PRIu64 ")", + __func__, + btc, + satoshi, + expected); return -1; } @@ -33,11 +35,12 @@ int verify_conv_btc_to_satoshi(void) { satoshi = conv_btc_to_satoshi(btc); expected = 2100000000000000ull; if (satoshi != expected) { - ERROR("%s: conv_btc_to_satoshi(%" PRIu32 ") returned %" PRIu64 " (expected: %" PRIu64 ")", - __func__, - btc, - satoshi, - expected); + ERROR( + "%s: conv_btc_to_satoshi(%" PRIu32 ") returned %" PRIu64 " (expected: %" PRIu64 ")", + __func__, + btc, + satoshi, + expected); return -1; } diff --git a/core/src/checks/misc_checks.c b/core/src/checks/misc_checks.c index c6c89238..778971e0 100644 --- a/core/src/checks/misc_checks.c +++ b/core/src/checks/misc_checks.c @@ -10,6 +10,7 @@ int verify_byte_order(void) { uint8_t bytes[sizeof(uint32_t) / sizeof(uint8_t)]; uint32_t word; } u; + u.word = 1; const bool is_little_endian = (u.bytes[0] == (uint8_t) 1); #if BYTE_ORDER == LITTLE_ENDIAN diff --git a/core/src/checks/validate_fees.c b/core/src/checks/validate_fees.c index acd0a86c..8e7f541a 100644 --- a/core/src/checks/validate_fees.c +++ b/core/src/checks/validate_fees.c @@ -11,8 +11,7 @@ int verify_validate_fees(void) { // test case where the fee is within both limits (under 1BTC, under 10% of // total) - InternalCommandRequest_SignTxRequest tx1 = - InternalCommandRequest_SignTxRequest_init_default; + InternalCommandRequest_SignTxRequest tx1 = InternalCommandRequest_SignTxRequest_init_default; tx1.inputs_count = 1; tx1.inputs[0].has_amount = true; tx1.inputs[0].amount = 100000; @@ -27,8 +26,7 @@ int verify_validate_fees(void) { } // test case where fee is under 1BTC but over 10% - InternalCommandRequest_SignTxRequest tx2 = - InternalCommandRequest_SignTxRequest_init_default; + InternalCommandRequest_SignTxRequest tx2 = InternalCommandRequest_SignTxRequest_init_default; tx2.inputs_count = 1; tx2.inputs[0].has_amount = true; tx2.inputs[0].amount = 1000000; @@ -43,8 +41,7 @@ int verify_validate_fees(void) { } // test case where fee is over 1BTC but under 10% - InternalCommandRequest_SignTxRequest tx3 = - InternalCommandRequest_SignTxRequest_init_default; + InternalCommandRequest_SignTxRequest tx3 = InternalCommandRequest_SignTxRequest_init_default; tx3.inputs_count = 1; tx3.inputs[0].has_amount = true; tx3.inputs[0].amount = 2000000000; @@ -59,8 +56,7 @@ int verify_validate_fees(void) { } // test case where fee is over 1BTC and over 10% - InternalCommandRequest_SignTxRequest tx4 = - InternalCommandRequest_SignTxRequest_init_default; + InternalCommandRequest_SignTxRequest tx4 = InternalCommandRequest_SignTxRequest_init_default; tx4.inputs_count = 1; tx4.inputs[0].has_amount = true; tx4.inputs[0].amount = 10000000000L; @@ -71,8 +67,9 @@ int verify_validate_fees(void) { t = validate_fees(&tx4); if (t) { r = -1; - ERROR("verify_validate_fees: tx4 did not fail fee validation, but fee is " - "over limits."); + ERROR( + "verify_validate_fees: tx4 did not fail fee validation, but fee is " + "over limits."); } // test case where fee is over 1BTC and over 10% if you don't count the amount @@ -83,8 +80,7 @@ int verify_validate_fees(void) { // we miscalculated the fee % by including the amount going to the change // address as part of the total, it would be 9.29%, which would pass // validation - InternalCommandRequest_SignTxRequest tx5 = - InternalCommandRequest_SignTxRequest_init_default; + InternalCommandRequest_SignTxRequest tx5 = InternalCommandRequest_SignTxRequest_init_default; tx5.inputs_count = 1; tx5.inputs[0].has_amount = true; tx5.inputs[0].amount = 10000000000L; @@ -98,13 +94,13 @@ int verify_validate_fees(void) { t = validate_fees(&tx5); if (t) { r = -1; - ERROR("verify_validate_fees: tx5 did not fail fee validation, but fee is " - "over limits."); + ERROR( + "verify_validate_fees: tx5 did not fail fee validation, but fee is " + "over limits."); } // test case with negative fee - InternalCommandRequest_SignTxRequest tx6 = - InternalCommandRequest_SignTxRequest_init_default; + InternalCommandRequest_SignTxRequest tx6 = InternalCommandRequest_SignTxRequest_init_default; tx6.inputs_count = 1; tx6.inputs[0].has_amount = true; tx6.inputs[0].amount = 1000; @@ -119,8 +115,9 @@ int verify_validate_fees(void) { t = validate_fees(&tx6); if (t) { r = -1; - ERROR("verify_validate_fees: tx6 did not fail fee validation, but fee is " - "negative."); + ERROR( + "verify_validate_fees: tx6 did not fail fee validation, but fee is " + "negative."); } return r; diff --git a/core/src/checks/verify_mix_entropy.c b/core/src/checks/verify_mix_entropy.c index ccdec76a..722380a0 100644 --- a/core/src/checks/verify_mix_entropy.c +++ b/core/src/checks/verify_mix_entropy.c @@ -10,25 +10,19 @@ int verify_mix_entropy(void) { // create the first buffer with known bytes uint8_t buffer1[] = { - 0x75, 0x96, 0x8d, 0x5b, 0xc9, 0x4d, 0x5c, 0x9c, - 0xda, 0xe8, 0xdf, 0x35, 0xb7, 0x4d, 0x62, 0x28, - 0xd4, 0xbf, 0x5c, 0x2f, 0x4f, 0x89, 0x60, 0x54, - 0x0c, 0x4d, 0x26, 0x96, 0x7b, 0x60, 0x86, 0x4b, - 0x3f, 0x3e, 0xf1, 0x2f, 0x43, 0x5f, 0x04, 0xa4, - 0xf5, 0xc0, 0xb5, 0x17, 0xe0, 0x5b, 0xa1, 0xf9, - 0x29, 0x81, 0x33, 0xc0, 0x74, 0x12, 0x07, 0x72, - 0x5d, 0xdd, 0xba, 0xdf, 0x3c, 0xdc, 0x0c, 0xe9}; + 0x75, 0x96, 0x8d, 0x5b, 0xc9, 0x4d, 0x5c, 0x9c, 0xda, 0xe8, 0xdf, 0x35, 0xb7, 0x4d, 0x62, 0x28, + 0xd4, 0xbf, 0x5c, 0x2f, 0x4f, 0x89, 0x60, 0x54, 0x0c, 0x4d, 0x26, 0x96, 0x7b, 0x60, 0x86, 0x4b, + 0x3f, 0x3e, 0xf1, 0x2f, 0x43, 0x5f, 0x04, 0xa4, 0xf5, 0xc0, 0xb5, 0x17, 0xe0, 0x5b, 0xa1, 0xf9, + 0x29, 0x81, 0x33, 0xc0, 0x74, 0x12, 0x07, 0x72, 0x5d, 0xdd, 0xba, 0xdf, 0x3c, 0xdc, 0x0c, 0xe9 + }; // create second buffer uint8_t buffer2[] = { - 0xe4, 0x88, 0xa6, 0x4e, 0xd9, 0xca, 0x63, 0xcb, - 0x3f, 0xca, 0x7f, 0x00, 0xda, 0xf9, 0x6f, 0xab, - 0x18, 0x23, 0x54, 0x0b, 0x1d, 0x10, 0xfa, 0xff, - 0x57, 0xbe, 0x00, 0xcc, 0x83, 0xdf, 0x03, 0x66, - 0xc5, 0x5b, 0x82, 0xe8, 0x46, 0x6d, 0x7d, 0x31, - 0x7d, 0xdd, 0x92, 0xda, 0x75, 0x38, 0xea, 0x91, - 0x23, 0x75, 0xa0, 0xae, 0x5a, 0xfb, 0x8a, 0x2b, - 0x93, 0xa9, 0x3d, 0xd7, 0x4e, 0x40, 0x62, 0x62}; + 0xe4, 0x88, 0xa6, 0x4e, 0xd9, 0xca, 0x63, 0xcb, 0x3f, 0xca, 0x7f, 0x00, 0xda, 0xf9, 0x6f, 0xab, + 0x18, 0x23, 0x54, 0x0b, 0x1d, 0x10, 0xfa, 0xff, 0x57, 0xbe, 0x00, 0xcc, 0x83, 0xdf, 0x03, 0x66, + 0xc5, 0x5b, 0x82, 0xe8, 0x46, 0x6d, 0x7d, 0x31, 0x7d, 0xdd, 0x92, 0xda, 0x75, 0x38, 0xea, 0x91, + 0x23, 0x75, 0xa0, 0xae, 0x5a, 0xfb, 0x8a, 0x2b, 0x93, 0xa9, 0x3d, 0xd7, 0x4e, 0x40, 0x62, 0x62 + }; InternalCommandRequest in = InternalCommandRequest_init_default; in.which_command = InternalCommandRequest_InitWallet_tag; @@ -42,15 +36,11 @@ int verify_mix_entropy(void) { } // verify result - uint8_t buffer3[MASTER_SEED_SIZE] = { - 0x91, 0x1e, 0x2b, 0x15, 0x10, 0x87, 0x3f, 0x57, - 0xe5, 0x22, 0xa0, 0x35, 0x6d, 0xb4, 0x0d, 0x83, - 0xcc, 0x9c, 0x08, 0x24, 0x52, 0x99, 0x9a, 0xab, - 0x5b, 0xf3, 0x26, 0x5a, 0xf8, 0xbf, 0x85, 0x2d, - 0xfa, 0x65, 0x73, 0xc7, 0x05, 0x32, 0x79, 0x95, - 0x88, 0x1d, 0x27, 0xcd, 0x95, 0x63, 0x4b, 0x68, - 0x0a, 0xf4, 0x93, 0x6e, 0x2e, 0xe9, 0x8d, 0x59, - 0xce, 0x74, 0x87, 0x08, 0x72, 0x9c, 0x6e, 0x8b}; + uint8_t buffer3[MASTER_SEED_SIZE] = { 0x91, 0x1e, 0x2b, 0x15, 0x10, 0x87, 0x3f, 0x57, 0xe5, 0x22, 0xa0, 0x35, 0x6d, + 0xb4, 0x0d, 0x83, 0xcc, 0x9c, 0x08, 0x24, 0x52, 0x99, 0x9a, 0xab, 0x5b, 0xf3, + 0x26, 0x5a, 0xf8, 0xbf, 0x85, 0x2d, 0xfa, 0x65, 0x73, 0xc7, 0x05, 0x32, 0x79, + 0x95, 0x88, 0x1d, 0x27, 0xcd, 0x95, 0x63, 0x4b, 0x68, 0x0a, 0xf4, 0x93, 0x6e, + 0x2e, 0xe9, 0x8d, 0x59, 0xce, 0x74, 0x87, 0x08, 0x72, 0x9c, 0x6e, 0x8b }; if (memcmp(buffer1, buffer3, MASTER_SEED_SIZE) != 0) { ERROR("mix_entropy failed to return expected value"); diff --git a/core/src/checks/verify_protect_pubkey.c b/core/src/checks/verify_protect_pubkey.c index e936355a..573ff3ae 100644 --- a/core/src/checks/verify_protect_pubkey.c +++ b/core/src/checks/verify_protect_pubkey.c @@ -11,8 +11,7 @@ int verify_protect_pubkey(void) { EncryptedPubKey temp = EncryptedPubKey_init_default; - char buffer1[XPUB_SIZE] = - "xpub661MyMwAqRbcGw6rpZ6SYUfFk6Z5YX216YRXnhuB6UcdwuVe4XUKKiPg"; + char buffer1[XPUB_SIZE] = "xpub661MyMwAqRbcGw6rpZ6SYUfFk6Z5YX216YRXnhuB6UcdwuVe4XUKKiPg"; char buffer2[XPUB_SIZE]; subzero_strlcpy(buffer2, buffer1, sizeof(buffer2)); diff --git a/core/src/checks/wycheproof/ecdsa_secp256k1_sha256_bitcoin_test.h b/core/src/checks/wycheproof/ecdsa_secp256k1_sha256_bitcoin_test.h index 736737fd..4629bd36 100644 --- a/core/src/checks/wycheproof/ecdsa_secp256k1_sha256_bitcoin_test.h +++ b/core/src/checks/wycheproof/ecdsa_secp256k1_sha256_bitcoin_test.h @@ -1,3 +1,5 @@ +// clang-format off + /* Note: this file was autogenerated using tests_wycheproof_generate.py. Do not edit. */ #define SECP256K1_ECDSA_WYCHEPROOF_NUMBER_TESTVECTORS (463) @@ -1562,3 +1564,5 @@ static const wycheproof_ecdsa_testvector testvectors[SECP256K1_ECDSA_WYCHEPROOF_ {6370, 569, 7, 38778, 71, 1 }, }; + +// clang-format on diff --git a/core/src/checks/wycheproof_checks.c b/core/src/checks/wycheproof_checks.c index 8aa2d28f..4df6bc95 100644 --- a/core/src/checks/wycheproof_checks.c +++ b/core/src/checks/wycheproof_checks.c @@ -1,5 +1,5 @@ -#include "config.h" #include "checks.h" +#include "config.h" #include "ecdsa.h" #include "log.h" #include "memzero.h" @@ -8,14 +8,14 @@ #include // This function was copied from the trezor-firmware library, and was not included -// in the initial fork. +// in the initial fork. // https://github.com/trezor/trezor-firmware/blob/fee0d70211e89629e682f6cda95a83d17ea88825/crypto/ecdsa.c#L1206 // // ** NOTE **: ONLY USE THIS FUNCTION FOR TESTING. -// +// // Parse a DER-encoded signature. We don't check whether the encoded integers // satisfy DER requirements regarding leading zeros. -static int ecdsa_sig_from_der(const uint8_t *der, size_t der_len, uint8_t sig[64]) { +static int ecdsa_sig_from_der(const uint8_t* der, size_t der_len, uint8_t sig[64]) { memzero(sig, 64); // Check sequence header. @@ -64,77 +64,81 @@ static int ecdsa_sig_from_der(const uint8_t *der, size_t der_len, uint8_t sig[64 // Returns true if the test vector fails but we intentionally want to ignore. static bool should_ignore_failure(size_t vector_label) { - switch (vector_label) { - case 1: - // { - // "tcId": 1, - // "comment": "Signature malleability", - // "flags": ["SignatureMalleabilityBitcoin"], - // "msg": "313233343030", - // "sig": "3046022100813ef79ccefa9a56f7ba805f0e478584fe5f0dd5f567bc09b5123ccbc9832365022100900e75ad233fcc908509dbff5922647db37c21f4afd3203ae8dc4ae7794b0f87", - // "result": "invalid" - // } - - // The signature is using the high s-value instead of the low one from [bip 62](https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki) - // The [code in bitcoin](https://github.com/bitcoin/bitcoin/blob/v0.9.3/src/key.cpp#L202-L227) checks this. - // if (s > N/2) { s := N - s } - // The group order for secp256k1 is `N = FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141` - - // HalfN := 0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0 - // s := 0x900e75ad233fcc908509dbff5922647db37c21f4afd3203ae8dc4ae7794b0f87 - // s > HalfN -> true - - case 100: - // { - // "tcId": 100, - // "comment": "truncated r", - // "flags": ["ModifiedSignature"], - // "msg": "313233343030", - // "sig": "30440220813ef79ccefa9a56f7ba805f0e478584fe5f0dd5f567bc09b5123ccbc983236502206ff18a52dcc0336f7af62400a6dd9b810732baf1ff758000d6f613a556eb31ba", - // "result": "invalid" - // } - - // The DER encoding does not encode leading zeros that it should. Here the signature's r-value is encoded as just a 0x20-byte long bignum, - // but it should be 0x21-byte long integer with a leading 0x00. The parser is a bit too lenient. However, we are not using this DER parser - // for anything other than testing. - - case 388: - // { - // "tcId": 388, - // "comment": "edge case for signature malleability", - // "flags": ["ArithmeticError"], - // "msg": "313233343030", - // "sig": "304402207fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a002207fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a1", - // "result": "invalid" - // } - - // This is the same issue as vector 1 as this vector also uses the high s-value. - // r := 7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0 - // s := 7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a1 - // Note that r = HalfN from case 1 above - // s is larger than HalfN so this is similar to case 1 and s should be `N - s` instead - - return true; - - default: - return false; - } + switch (vector_label) { + case 1: + // { + // "tcId": 1, + // "comment": "Signature malleability", + // "flags": ["SignatureMalleabilityBitcoin"], + // "msg": "313233343030", + // "sig": + // "3046022100813ef79ccefa9a56f7ba805f0e478584fe5f0dd5f567bc09b5123ccbc9832365022100900e75ad233fcc908509dbff5922647db37c21f4afd3203ae8dc4ae7794b0f87", + // "result": "invalid" + // } + + // The signature is using the high s-value instead of the low one from [bip + // 62](https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki) The [code in + // bitcoin](https://github.com/bitcoin/bitcoin/blob/v0.9.3/src/key.cpp#L202-L227) checks this. if (s > N/2) { s := + // N - s } The group order for secp256k1 is `N = FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C + // D0364141` + + // HalfN := 0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0 + // s := 0x900e75ad233fcc908509dbff5922647db37c21f4afd3203ae8dc4ae7794b0f87 + // s > HalfN -> true + + case 100: + // { + // "tcId": 100, + // "comment": "truncated r", + // "flags": ["ModifiedSignature"], + // "msg": "313233343030", + // "sig": + // "30440220813ef79ccefa9a56f7ba805f0e478584fe5f0dd5f567bc09b5123ccbc983236502206ff18a52dcc0336f7af62400a6dd9b810732baf1ff758000d6f613a556eb31ba", + // "result": "invalid" + // } + + // The DER encoding does not encode leading zeros that it should. Here the signature's r-value is encoded as just a + // 0x20-byte long bignum, but it should be 0x21-byte long integer with a leading 0x00. The parser is a bit too + // lenient. However, we are not using this DER parser for anything other than testing. + + case 388: + // { + // "tcId": 388, + // "comment": "edge case for signature malleability", + // "flags": ["ArithmeticError"], + // "msg": "313233343030", + // "sig": + // "304402207fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a002207fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a1", + // "result": "invalid" + // } + + // This is the same issue as vector 1 as this vector also uses the high s-value. + // r := 7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0 + // s := 7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a1 + // Note that r = HalfN from case 1 above + // s is larger than HalfN so this is similar to case 1 and s should be `N - s` instead + + return true; + + default: + return false; + } } // runs tests against each wycheproof vector and reports any failures int verify_wycheproof(void) { - // inline the include to have the smallest scope possible for the variables defined in the include file. - #include "wycheproof/ecdsa_secp256k1_sha256_bitcoin_test.h" +// inline the include to have the smallest scope possible for the variables defined in the include file. +#include "wycheproof/ecdsa_secp256k1_sha256_bitcoin_test.h" int failures = 0; for (size_t t = 0; t < SECP256K1_ECDSA_WYCHEPROOF_NUMBER_TESTVECTORS; t++) { // The json test vectors are 1-indexed. const size_t vector_label = t + 1; - const uint8_t *msg = NULL; - const uint8_t *der_sig = NULL; - const uint8_t *pk = NULL; - const ecdsa_curve *curve = &secp256k1; - uint8_t sig[64] = {0}; + const uint8_t* msg = NULL; + const uint8_t* der_sig = NULL; + const uint8_t* pk = NULL; + const ecdsa_curve* curve = &secp256k1; + uint8_t sig[64] = { 0 }; curve_point pub; pk = &wycheproof_ecdsa_public_keys[testvectors[t].pk_offset]; @@ -148,7 +152,7 @@ int verify_wycheproof(void) { msg = &wycheproof_ecdsa_messages[testvectors[t].msg_offset]; der_sig = &wycheproof_ecdsa_signatures[testvectors[t].sig_offset]; - // returns non-zero if parsing fails, ignore the return value and continue with the verification, and + // returns non-zero if parsing fails, ignore the return value and continue with the verification, and // in an actual verification function, we would bail if we found a problem here. ecdsa_sig_from_der(der_sig, testvectors[t].sig_len, sig); @@ -164,10 +168,11 @@ int verify_wycheproof(void) { continue; } - ERROR("wycheproof test vector failed [vector:%zu][expected: %d][actual: %d]", - vector_label, - testvectors[t].expected_verify, - actual_verify); + ERROR( + "wycheproof test vector failed [vector:%zu][expected: %d][actual: %d]", + vector_label, + testvectors[t].expected_verify, + actual_verify); failures++; } diff --git a/core/src/conv.c b/core/src/conv.c index 021de96f..fccd1b85 100644 --- a/core/src/conv.c +++ b/core/src/conv.c @@ -1,5 +1,5 @@ #include "conv.h" uint64_t conv_btc_to_satoshi(uint32_t btc) { - return (uint64_t) btc * 100000000ull; + return (uint64_t) btc * 100000000ull; } diff --git a/core/src/dev/additional_checks.c b/core/src/dev/additional_checks.c index e7a36fcc..466b23d9 100644 --- a/core/src/dev/additional_checks.c +++ b/core/src/dev/additional_checks.c @@ -3,6 +3,10 @@ /** * Dev specific checks go here. */ -int pre_run_self_checks(void) { return 0; } +int pre_run_self_checks(void) { + return 0; +} -int post_run_self_checks(void) { return 0; } +int post_run_self_checks(void) { + return 0; +} diff --git a/core/src/dev/aes_gcm.c b/core/src/dev/aes_gcm.c index b0fb26ef..e843f979 100644 --- a/core/src/dev/aes_gcm.c +++ b/core/src/dev/aes_gcm.c @@ -27,10 +27,13 @@ uint8_t aes_gcm_buffer[1000]; * * All pointer arguments of the function must not be NULL. */ -Result aes_gcm_encrypt(M_KeyID keyId, uint8_t * plaintext, size_t plaintext_len, - uint8_t *ciphertext, size_t ciphertext_len, - size_t *bytes_written) -{ +Result aes_gcm_encrypt( + M_KeyID keyId, + uint8_t* plaintext, + size_t plaintext_len, + uint8_t* ciphertext, + size_t ciphertext_len, + size_t* bytes_written) { // NULL pointer checks. if (!plaintext) { ERROR("%s: plaintext must not be NULL", __func__); @@ -47,8 +50,8 @@ Result aes_gcm_encrypt(M_KeyID keyId, uint8_t * plaintext, size_t plaintext_len, return Result_UNKNOWN_INTERNAL_FAILURE; } - uint8_t iv[IV_SIZE_IN_BYTES] = {0}; - uint8_t tag[TAG_SIZE_IN_BYTES] = {0}; + uint8_t iv[IV_SIZE_IN_BYTES] = { 0 }; + uint8_t tag[TAG_SIZE_IN_BYTES] = { 0 }; // In theory, we don't need the following array to be static to zero // initialize it. We could have done "gcm_ctx ctx[1] = {0}" according to the // C standard. Unfortunately, a gcc version (4.8.5) that we would like to @@ -66,20 +69,19 @@ Result aes_gcm_encrypt(M_KeyID keyId, uint8_t * plaintext, size_t plaintext_len, size_t expected_ciphertext_len = plaintext_len + sizeof(iv) + sizeof(tag); if (ciphertext_len < expected_ciphertext_len) { - ERROR("aes_gcm_encrypt: ciphertext buffer too small."); - memzero(plaintext, plaintext_len); - return Result_AES_GCM_ENCRYPT_BUFFER_TOO_SMALL_FAILURE; + ERROR("aes_gcm_encrypt: ciphertext buffer too small."); + memzero(plaintext, plaintext_len); + return Result_AES_GCM_ENCRYPT_BUFFER_TOO_SMALL_FAILURE; } if (expected_ciphertext_len > sizeof(aes_gcm_buffer)) { - ERROR("aes_gcm_encrypt: plaintext too long."); - memzero(plaintext, plaintext_len); - return Result_AES_GCM_ENCRYPT_PLAINTEXT_TOO_LONG_FAILURE; + ERROR("aes_gcm_encrypt: plaintext too long."); + memzero(plaintext, plaintext_len); + return Result_AES_GCM_ENCRYPT_PLAINTEXT_TOO_LONG_FAILURE; } - if (RETURN_GOOD != gcm_init_and_key(KEK[keyId - 1], sizeof(KEK[keyId - 1]), ctx)) - { - ERROR("gcm_init_and_key failed"); - return Result_UNKNOWN_INTERNAL_FAILURE; + if (RETURN_GOOD != gcm_init_and_key(KEK[keyId - 1], sizeof(KEK[keyId - 1]), ctx)) { + ERROR("gcm_init_and_key failed"); + return Result_UNKNOWN_INTERNAL_FAILURE; } // Generate a random IV @@ -89,19 +91,22 @@ Result aes_gcm_encrypt(M_KeyID keyId, uint8_t * plaintext, size_t plaintext_len, memcpy(aes_gcm_buffer, plaintext, plaintext_len); memzero(plaintext, plaintext_len); - if (RETURN_GOOD != gcm_encrypt_message(iv, sizeof(iv), - NULL, 0, // empty header - aes_gcm_buffer, plaintext_len, - tag, sizeof(tag), - ctx)) - { + if (RETURN_GOOD != gcm_encrypt_message( + iv, + sizeof(iv), + NULL, + 0, // empty header + aes_gcm_buffer, + plaintext_len, + tag, + sizeof(tag), + ctx)) { ERROR("gcm_encrypt_message failed"); memzero(aes_gcm_buffer, sizeof(aes_gcm_buffer)); return Result_UNKNOWN_INTERNAL_FAILURE; } - if (RETURN_GOOD != gcm_end(ctx)) - { + if (RETURN_GOOD != gcm_end(ctx)) { ERROR("gcm_end failed"); memzero(aes_gcm_buffer, sizeof(aes_gcm_buffer)); return Result_UNKNOWN_INTERNAL_FAILURE; @@ -119,10 +124,13 @@ Result aes_gcm_encrypt(M_KeyID keyId, uint8_t * plaintext, size_t plaintext_len, /** * AES-GCM decryption. */ -Result aes_gcm_decrypt(M_KeyID keyId, const uint8_t *ciphertext, size_t ciphertext_len, - uint8_t *plaintext, size_t plaintext_len, - size_t *bytes_written) -{ +Result aes_gcm_decrypt( + M_KeyID keyId, + const uint8_t* ciphertext, + size_t ciphertext_len, + uint8_t* plaintext, + size_t plaintext_len, + size_t* bytes_written) { // NULL pointer checks. if (!plaintext) { ERROR("%s: plaintext must not be NULL", __func__); @@ -139,15 +147,14 @@ Result aes_gcm_decrypt(M_KeyID keyId, const uint8_t *ciphertext, size_t cipherte return Result_UNKNOWN_INTERNAL_FAILURE; } - uint8_t iv[IV_SIZE_IN_BYTES] = {0}; - uint8_t tag[TAG_SIZE_IN_BYTES] = {0}; + uint8_t iv[IV_SIZE_IN_BYTES] = { 0 }; + uint8_t tag[TAG_SIZE_IN_BYTES] = { 0 }; // Declare static to work around a bug in gcc 4.8.5 static gcm_ctx ctx[1]; memzero(plaintext, plaintext_len); - if (ciphertext_len < sizeof(iv) + sizeof(tag)) - { + if (ciphertext_len < sizeof(iv) + sizeof(tag)) { ERROR("%s: ciphertext buffer too small.", __func__); return Result_AES_GCM_DECRYPT_BUFFER_TOO_SMALL_FAILURE; } @@ -163,8 +170,7 @@ Result aes_gcm_decrypt(M_KeyID keyId, const uint8_t *ciphertext, size_t cipherte return Result_AES_GCM_DECRYPT_BUFFER_TOO_SMALL_FAILURE; } - if (RETURN_GOOD != gcm_init_and_key(KEK[keyId - 1], sizeof(KEK[keyId - 1]), ctx)) - { + if (RETURN_GOOD != gcm_init_and_key(KEK[keyId - 1], sizeof(KEK[keyId - 1]), ctx)) { ERROR("gcm_init_and_key failed"); return Result_UNKNOWN_INTERNAL_FAILURE; } @@ -174,12 +180,16 @@ Result aes_gcm_decrypt(M_KeyID keyId, const uint8_t *ciphertext, size_t cipherte memcpy(aes_gcm_buffer, ciphertext + sizeof(iv), expected_plaintext_len); memcpy(tag, ciphertext + sizeof(iv) + expected_plaintext_len, sizeof(tag)); - if (RETURN_GOOD != gcm_decrypt_message(iv, sizeof(iv), - NULL, 0, // empty header - aes_gcm_buffer, expected_plaintext_len, - tag, sizeof(tag), - ctx)) - { + if (RETURN_GOOD != gcm_decrypt_message( + iv, + sizeof(iv), + NULL, + 0, // empty header + aes_gcm_buffer, + expected_plaintext_len, + tag, + sizeof(tag), + ctx)) { #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION ERROR("gcm_decrypt_message failed"); memzero(aes_gcm_buffer, sizeof(aes_gcm_buffer)); @@ -204,8 +214,7 @@ Result aes_gcm_decrypt(M_KeyID keyId, const uint8_t *ciphertext, size_t cipherte #endif } - if (RETURN_GOOD != gcm_end(ctx)) - { + if (RETURN_GOOD != gcm_end(ctx)) { ERROR("gcm_end failed"); return Result_UNKNOWN_INTERNAL_FAILURE; } @@ -219,4 +228,3 @@ Result aes_gcm_decrypt(M_KeyID keyId, const uint8_t *ciphertext, size_t cipherte return Result_SUCCESS; } - diff --git a/core/src/dev/execute_command_hooks.c b/core/src/dev/execute_command_hooks.c index 79a27ad2..4faa4fef 100644 --- a/core/src/dev/execute_command_hooks.c +++ b/core/src/dev/execute_command_hooks.c @@ -2,7 +2,7 @@ #include "squareup/subzero/internal.pb.h" Result pre_execute_command(const InternalCommandRequest* const in) { - (void)in; + (void) in; return Result_SUCCESS; } diff --git a/core/src/dev/init.c b/core/src/dev/init.c index 4363a987..1c428bd1 100644 --- a/core/src/dev/init.c +++ b/core/src/dev/init.c @@ -3,6 +3,8 @@ /** * For now, we don't need any init() or cleanup(), so they are empty. */ -int init(void) { return 0; } +int init(void) { + return 0; +} void cleanup(void) {} diff --git a/core/src/dev/init_wallet.c b/core/src/dev/init_wallet.c index 715703a8..a283bff3 100644 --- a/core/src/dev/init_wallet.c +++ b/core/src/dev/init_wallet.c @@ -31,10 +31,8 @@ * - derive the pubkey * - encrypt the master_seed and pubkey */ -Result handle_init_wallet(const InternalCommandRequest* const in, - InternalCommandResponse_InitWalletResponse *out) { - - uint8_t entropy[MASTER_SEED_SIZE] = {0}; +Result handle_init_wallet(const InternalCommandRequest* const in, InternalCommandResponse_InitWalletResponse* out) { + uint8_t entropy[MASTER_SEED_SIZE] = { 0 }; random_buffer(entropy, sizeof(entropy)); Result r = mix_entropy(entropy, in); if (r != Result_SUCCESS) { @@ -44,7 +42,7 @@ Result handle_init_wallet(const InternalCommandRequest* const in, // Only use 32 bytes of entropy to derive mnemonic and print it to stdout for // debugging purpose. - const char *mnemonic = mnemonic_from_data(entropy, 32); + const char* mnemonic = mnemonic_from_data(entropy, 32); DEBUG("mnemonic: %s", mnemonic); uint8_t master_seed[MASTER_SEED_SIZE]; @@ -64,8 +62,7 @@ Result handle_init_wallet(const InternalCommandRequest* const in, hdnode_fill_public_key(&node); char pub_key[128]; - int ret = hdnode_serialize_public(&node, fingerprint, PUBKEY_PREFIX, - pub_key, sizeof(pub_key)); + int ret = hdnode_serialize_public(&node, fingerprint, PUBKEY_PREFIX, pub_key, sizeof(pub_key)); if (ret <= 0) { // TODO: create an error code for serialization failure? return Result_UNKNOWN_INTERNAL_FAILURE; diff --git a/core/src/dev/no_rollback.c b/core/src/dev/no_rollback.c index c13b4d71..14e9795a 100644 --- a/core/src/dev/no_rollback.c +++ b/core/src/dev/no_rollback.c @@ -10,7 +10,7 @@ Result no_rollback_read(const char* filename, char buf[static VERSION_SIZE]) { char tmp_file[100]; snprintf(tmp_file, sizeof(tmp_file), "/tmp/%s", filename); - FILE *f = fopen(tmp_file, "r"); + FILE* f = fopen(tmp_file, "r"); if (f == NULL) { // In dev, we magically create the file. It's one less thing to think about. no_rollback_write_version(filename, VERSION_MAGIC, VERSION); @@ -40,7 +40,7 @@ Result no_rollback_write(const char* filename, char buf[static VERSION_SIZE]) { char tmp_file[100]; snprintf(tmp_file, sizeof(tmp_file), "/tmp/%s", filename); - FILE *f = fopen(tmp_file, "w"); + FILE* f = fopen(tmp_file, "w"); if (f == NULL) { ERROR("no_rollback_write failed"); return Result_NO_ROLLBACK_FILE_NOT_FOUND; @@ -54,4 +54,3 @@ Result no_rollback_write(const char* filename, char buf[static VERSION_SIZE]) { return Result_SUCCESS; } - diff --git a/core/src/dev/protection.c b/core/src/dev/protection.c index 4a61e455..4fb3f93f 100644 --- a/core/src/dev/protection.c +++ b/core/src/dev/protection.c @@ -13,12 +13,9 @@ // Hardcoded master seed encryption key and public key encryption key // From test cases 1 and 3 in // https://csrc.nist.rip/groups/ST/toolkit/BCM/documents/proposedmodes/gcm/gcm-spec.pdf -uint8_t KEK[2][16] = -{ - {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - {0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c, - 0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08} +uint8_t KEK[2][16] = { + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, + { 0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c, 0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08 } }; // The following implementation is shared between dev and ncipher targets diff --git a/core/src/finalize_wallet.c b/core/src/finalize_wallet.c index 99fe9992..a4dab0d7 100644 --- a/core/src/finalize_wallet.c +++ b/core/src/finalize_wallet.c @@ -14,13 +14,11 @@ #include #include -Result -handle_finalize_wallet( +Result handle_finalize_wallet( const InternalCommandRequest_FinalizeWalletRequest* const in, - InternalCommandResponse_FinalizeWalletResponse *out) { + InternalCommandResponse_FinalizeWalletResponse* out) { if (in->encrypted_pub_keys_count != MULTISIG_PARTS) { - ERROR("expecting %d encrypted_pub_keys, received %d.", MULTISIG_PARTS, - in->encrypted_pub_keys_count); + ERROR("expecting %d encrypted_pub_keys, received %d.", MULTISIG_PARTS, in->encrypted_pub_keys_count); return Result_MISSING_ARGUMENTS; } @@ -76,8 +74,7 @@ handle_finalize_wallet( hdnode_fill_public_key(&node); char pub_key[XPUB_SIZE]; - int ret = hdnode_serialize_public(&node, fingerprint, PUBKEY_PREFIX, - pub_key, sizeof(pub_key)); + int ret = hdnode_serialize_public(&node, fingerprint, PUBKEY_PREFIX, pub_key, sizeof(pub_key)); if (ret <= 0) { ERROR("hdnode_serialize_public failed"); return Result_UNKNOWN_INTERNAL_FAILURE; @@ -92,14 +89,13 @@ handle_finalize_wallet( return Result_UNKNOWN_INTERNAL_FAILURE; } - static_assert(sizeof(out->pub_key.bytes) == XPUB_SIZE, - "misconfigured pub_key max size"); - if (subzero_strlcpy((char *)out->pub_key.bytes, pub_keys[i], - sizeof(out->pub_key.bytes)) >= sizeof(out->pub_key.bytes)) { - ERROR("pub_key %d is too long", i); - return Result_UNKNOWN_INTERNAL_FAILURE; - } - out->pub_key.size = (pb_size_t)strlen(pub_keys[i]); + static_assert(sizeof(out->pub_key.bytes) == XPUB_SIZE, "misconfigured pub_key max size"); + if (subzero_strlcpy((char*) out->pub_key.bytes, pub_keys[i], sizeof(out->pub_key.bytes)) >= + sizeof(out->pub_key.bytes)) { + ERROR("pub_key %d is too long", i); + return Result_UNKNOWN_INTERNAL_FAILURE; + } + out->pub_key.size = (pb_size_t) strlen(pub_keys[i]); // TODO: figure out pub_keys_hash story out->pub_keys_hash.bytes[0] = 0x99; diff --git a/core/src/fuzz.c b/core/src/fuzz.c index 07f8e78b..cfc56d8a 100644 --- a/core/src/fuzz.c +++ b/core/src/fuzz.c @@ -10,15 +10,15 @@ #include #include -extern int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size); +extern int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size); static uint8_t response_buf[4096] = { 0 }; -int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { +int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { pb_istream_t istream = pb_istream_from_buffer(data, size); pb_ostream_t ostream = pb_ostream_from_buffer(response_buf, sizeof(response_buf)); handle_incoming_message(&istream, &ostream); - return 0; // Values other than 0 and -1 are reserved for future use. + return 0; // Values other than 0 and -1 are reserved for future use. } diff --git a/core/src/hash.c b/core/src/hash.c index 573d6c1b..8c4462d9 100644 --- a/core/src/hash.c +++ b/core/src/hash.c @@ -3,40 +3,42 @@ #include "hasher.h" // hash_uint hashes in little-endian order (least-significant byte first) -static void hash_uint(Hasher *hasher, uint64_t value, uint8_t bytes) { +static void hash_uint(Hasher* hasher, uint64_t value, uint8_t bytes) { for (int i = 0; i < bytes; i++) { // Some extra (uint8_t) casts here so clang-tidy is happy - uint8_t byte = (uint8_t)(value & (uint8_t)0xFF); + uint8_t byte = (uint8_t) (value & (uint8_t) 0xFF); hasher_Update(hasher, &byte, 1); - value = value >> (uint8_t)8; + value = value >> (uint8_t) 8; } } -void hash_uint8(Hasher *hasher, uint8_t value) { hash_uint(hasher, value, 1); } +void hash_uint8(Hasher* hasher, uint8_t value) { + hash_uint(hasher, value, 1); +} -void hash_uint16(Hasher *hasher, uint16_t value) { +void hash_uint16(Hasher* hasher, uint16_t value) { hash_uint(hasher, value, 2); } -void hash_uint32(Hasher *hasher, uint32_t value) { +void hash_uint32(Hasher* hasher, uint32_t value) { hash_uint(hasher, value, 4); } -void hash_uint64(Hasher *hasher, uint64_t value) { +void hash_uint64(Hasher* hasher, uint64_t value) { hash_uint(hasher, value, 8); } -void hash_bytes(Hasher *hasher, const uint8_t *data, size_t len) { +void hash_bytes(Hasher* hasher, const uint8_t* data, size_t len) { hasher_Update(hasher, data, len); } -void hash_rev_bytes(Hasher *hasher, const uint8_t *data, size_t len) { +void hash_rev_bytes(Hasher* hasher, const uint8_t* data, size_t len) { for (size_t i = len; i-- > 0;) { hasher_Update(hasher, &data[i], 1); } } -void hash_var_bytes(Hasher *hasher, const uint8_t *data, size_t len) { +void hash_var_bytes(Hasher* hasher, const uint8_t* data, size_t len) { if (len <= 252) { hash_uint8(hasher, len); } else if (len <= 0xffff) { diff --git a/core/src/init_wallet.c b/core/src/init_wallet.c index 2b95229a..f8e5b49b 100644 --- a/core/src/init_wallet.c +++ b/core/src/init_wallet.c @@ -11,8 +11,7 @@ * We currently use XOR to mix the two buffers. * TODO(alok): replace with HMAC, which is slightly better. */ -Result mix_entropy(uint8_t master_seed[static MASTER_SEED_SIZE], - const InternalCommandRequest* const in) { +Result mix_entropy(uint8_t master_seed[static MASTER_SEED_SIZE], const InternalCommandRequest* const in) { if (in->command.InitWallet.random_bytes.size != MASTER_SEED_SIZE) { ERROR("unexpected random_bytes.size"); return Result_INCORRECT_RANDOM_BYTES_SIZE; diff --git a/core/src/main.c b/core/src/main.c index 8fae9af6..3cf1a187 100644 --- a/core/src/main.c +++ b/core/src/main.c @@ -21,7 +21,7 @@ #include #include -int main(int argc, char **argv) { +int main(int argc, char** argv) { int r; bool checks_only = false; bool listen_all_ip = false; @@ -33,12 +33,10 @@ int main(int argc, char **argv) { if (argc == 2) { if (strcmp(argv[1], "--checks-only") == 0) { checks_only = true; - } - else if (strcmp(argv[1], "--listen-all-ip") == 0) { + } else if (strcmp(argv[1], "--listen-all-ip") == 0) { listen_all_ip = true; INFO("server to listen on all interfaces"); - } - else { + } else { ERROR("the only valid argument is --checks-only or --listen-all-ip"); return -1; } @@ -81,8 +79,7 @@ int main(int argc, char **argv) { memzero(&serveraddr, sizeof(serveraddr)); serveraddr.sin_family = AF_INET; serveraddr.sin_port = htons(PORT); - serveraddr.sin_addr.s_addr = - listen_all_ip ? htonl(INADDR_ANY) : htonl(INADDR_LOOPBACK); + serveraddr.sin_addr.s_addr = listen_all_ip ? htonl(INADDR_ANY) : htonl(INADDR_LOOPBACK); int server; server = socket(AF_INET, SOCK_STREAM, 0); @@ -95,7 +92,7 @@ int main(int argc, char **argv) { int optval = 1; setsockopt(server, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); - if (bind(server, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) != 0) { + if (bind(server, (struct sockaddr*) &serveraddr, sizeof(serveraddr)) != 0) { ERROR("server socket binding failed."); cleanup(); return -1; diff --git a/core/src/memzero.c b/core/src/memzero.c index efc9b069..f49de553 100644 --- a/core/src/memzero.c +++ b/core/src/memzero.c @@ -10,12 +10,12 @@ * * Note: Trezor's crypto calls this function, so we can't change the name. */ -void memzero(void *s, size_t n) { - volatile uint8_t *ptr; +void memzero(void* s, size_t n) { + volatile uint8_t* ptr; - ptr = (uint8_t *)s; + ptr = (uint8_t*) s; - for (size_t i=0; i #include -static bool write_callback(pb_ostream_t *stream, const uint8_t *buf, - size_t count) { - int fd = (intptr_t)stream->state; - return send(fd, buf, count, 0) == (ssize_t)count; +static bool write_callback(pb_ostream_t* stream, const uint8_t* buf, size_t count) { + int fd = (intptr_t) stream->state; + return send(fd, buf, count, 0) == (ssize_t) count; } -static bool read_callback(pb_istream_t *stream, uint8_t *buf, size_t count) { - int fd = (intptr_t)stream->state; +static bool read_callback(pb_istream_t* stream, uint8_t* buf, size_t count) { + int fd = (intptr_t) stream->state; int result; result = recv(fd, buf, count, MSG_WAITALL); @@ -29,16 +28,15 @@ static bool read_callback(pb_istream_t *stream, uint8_t *buf, size_t count) { stream->bytes_left = 0; /* EOF */ } - return result == (int)count; + return result == (int) count; } pb_ostream_t pb_ostream_from_socket(int fd) { - pb_ostream_t stream = {&write_callback, (void *)(intptr_t)fd, SIZE_MAX, 0, - NULL}; + pb_ostream_t stream = { &write_callback, (void*) (intptr_t) fd, SIZE_MAX, 0, NULL }; return stream; } pb_istream_t pb_istream_from_socket(int fd) { - pb_istream_t stream = {&read_callback, (void *)(intptr_t)fd, SIZE_MAX, NULL}; + pb_istream_t stream = { &read_callback, (void*) (intptr_t) fd, SIZE_MAX, NULL }; return stream; } diff --git a/core/src/ncipher/additional_checks.c b/core/src/ncipher/additional_checks.c index c0b18eec..cd438276 100644 --- a/core/src/ncipher/additional_checks.c +++ b/core/src/ncipher/additional_checks.c @@ -11,8 +11,8 @@ extern M_KeyID master_seed_encryption_key; extern M_KeyID pub_key_encryption_key; -M_PermissionGroup check_aes_gcm_pg = {0}; -M_Action check_aes_gcm_act = {0}; +M_PermissionGroup check_aes_gcm_pg = { 0 }; +M_Action check_aes_gcm_act = { 0 }; static int check_aes_gcm(void); @@ -22,14 +22,13 @@ static int check_aes_gcm(void); int pre_run_self_checks(void) { // Create a temporary key, assign it to master_seed_encryption_key and // pub_key_encryption_key - M_Command command = {0}; - M_Reply reply = {0}; + M_Command command = { 0 }; + M_Reply reply = { 0 }; Result r; check_aes_gcm_act.type = Act_OpPermissions; check_aes_gcm_act.details.oppermissions.perms = - (Act_OpPermissions_Details_perms_Encrypt | - Act_OpPermissions_Details_perms_Decrypt); + (Act_OpPermissions_Details_perms_Encrypt | Act_OpPermissions_Details_perms_Decrypt); check_aes_gcm_pg.flags = 0; check_aes_gcm_pg.n_limits = 0; @@ -75,29 +74,26 @@ int post_run_self_checks(void) { */ static int check_aes_gcm(void) { // encrypt some bytes twice. - uint8_t plaintext[40] = {0x1a, 0x44, 0x2b, 0x56, 0x83, 0xa9, 0xa4, 0xd2, - 0x98, 0x1d, 0x2b, 0x29, 0x3a, 0x03, 0x93, 0xaa, - 0x0e, 0x78, 0xda, 0x47, 0x4e, 0x07, 0x36, 0x15, - 0xfc, 0x49, 0x97, 0xdd, 0x8f, 0x0f, 0x1b, 0xaa, - 0xd7, 0x63, 0x27, 0x72, 0x23, 0x0a, 0x49, 0x08}; - uint8_t plaintext2[40] = {0}; + uint8_t plaintext[40] = { 0x1a, 0x44, 0x2b, 0x56, 0x83, 0xa9, 0xa4, 0xd2, 0x98, 0x1d, 0x2b, 0x29, 0x3a, 0x03, + 0x93, 0xaa, 0x0e, 0x78, 0xda, 0x47, 0x4e, 0x07, 0x36, 0x15, 0xfc, 0x49, 0x97, 0xdd, + 0x8f, 0x0f, 0x1b, 0xaa, 0xd7, 0x63, 0x27, 0x72, 0x23, 0x0a, 0x49, 0x08 }; + uint8_t plaintext2[40] = { 0 }; memcpy(plaintext2, plaintext, sizeof(plaintext)); - uint8_t ciphertext1[100] = {0}; - uint8_t ciphertext2[100] = {0}; - uint8_t roundtrip[40] = {0}; + uint8_t ciphertext1[100] = { 0 }; + uint8_t ciphertext2[100] = { 0 }; + uint8_t roundtrip[40] = { 0 }; size_t ciphertext1_len, ciphertext2_len, roundtrip_len; - Result r = - aes_gcm_encrypt(master_seed_encryption_key, plaintext, sizeof(plaintext), - ciphertext1, sizeof(ciphertext1), &ciphertext1_len); + Result r = aes_gcm_encrypt( + master_seed_encryption_key, plaintext, sizeof(plaintext), ciphertext1, sizeof(ciphertext1), &ciphertext1_len); if (r != Result_SUCCESS) { ERROR("first encryption failed (%d).", r); return -1; } - r = aes_gcm_encrypt(master_seed_encryption_key, plaintext, sizeof(plaintext), - ciphertext2, sizeof(ciphertext2), &ciphertext2_len); + r = aes_gcm_encrypt( + master_seed_encryption_key, plaintext, sizeof(plaintext), ciphertext2, sizeof(ciphertext2), &ciphertext2_len); if (r != Result_SUCCESS) { ERROR("second encryption failed (%d).", r); return -1; @@ -115,8 +111,8 @@ static int check_aes_gcm(void) { } // check that we can decrypt back to the original string. - r = aes_gcm_decrypt(master_seed_encryption_key, ciphertext1, ciphertext1_len, - roundtrip, sizeof(roundtrip), &roundtrip_len); + r = aes_gcm_decrypt( + master_seed_encryption_key, ciphertext1, ciphertext1_len, roundtrip, sizeof(roundtrip), &roundtrip_len); if (r != Result_SUCCESS) { ERROR("first decryption failed (%d).", r); return -1; @@ -134,8 +130,8 @@ static int check_aes_gcm(void) { // check that modifying a byte causes decryption to fail. ciphertext2[10] = ciphertext2[10] ^ 0x22; ERROR("expecting aes_gcm_decrypt to fail."); - r = aes_gcm_decrypt(master_seed_encryption_key, ciphertext2, ciphertext2_len, - roundtrip, sizeof(roundtrip), &roundtrip_len); + r = aes_gcm_decrypt( + master_seed_encryption_key, ciphertext2, ciphertext2_len, roundtrip, sizeof(roundtrip), &roundtrip_len); if (r == Result_SUCCESS) { ERROR("decryption of corrupted bytes should not have worked."); return -1; diff --git a/core/src/ncipher/aes_gcm.c b/core/src/ncipher/aes_gcm.c index 086812bc..c6855cc6 100644 --- a/core/src/ncipher/aes_gcm.c +++ b/core/src/ncipher/aes_gcm.c @@ -28,10 +28,13 @@ uint8_t aes_gcm_buffer[1000]; * * All pointer arguments of the function must not be NULL. */ -Result aes_gcm_encrypt(M_KeyID keyId, uint8_t *plaintext, size_t plaintext_len, - uint8_t *ciphertext, size_t ciphertext_len, - size_t *bytes_written) { - +Result aes_gcm_encrypt( + M_KeyID keyId, + uint8_t* plaintext, + size_t plaintext_len, + uint8_t* ciphertext, + size_t ciphertext_len, + size_t* bytes_written) { // NULL pointer checks. if (!plaintext) { ERROR("%s: plaintext must not be NULL", __func__); @@ -57,8 +60,7 @@ Result aes_gcm_encrypt(M_KeyID keyId, uint8_t *plaintext, size_t plaintext_len, return Result_AES_GCM_ENCRYPT_PLAINTEXT_TOO_LONG_FAILURE; } - size_t expected_ciphertext_len = plaintext_len + IV_SIZE_IN_BYTES + - TAG_SIZE_IN_BYTES; + size_t expected_ciphertext_len = plaintext_len + IV_SIZE_IN_BYTES + TAG_SIZE_IN_BYTES; if (ciphertext_len < expected_ciphertext_len) { ERROR("aes_gcm_encrypt: ciphertext buffer too small."); memzero(plaintext, plaintext_len); @@ -71,8 +73,8 @@ Result aes_gcm_encrypt(M_KeyID keyId, uint8_t *plaintext, size_t plaintext_len, return Result_AES_GCM_ENCRYPT_PLAINTEXT_TOO_LONG_FAILURE; } - M_Command command = {0}; - M_Reply reply = {0}; + M_Command command = { 0 }; + M_Reply reply = { 0 }; command.cmd = Cmd_Encrypt; command.args.encrypt.key = keyId; @@ -96,8 +98,7 @@ Result aes_gcm_encrypt(M_KeyID keyId, uint8_t *plaintext, size_t plaintext_len, return r; } - if (reply.reply.encrypt.cipher.data.genericgcm128.cipher.len != - plaintext_len) { + if (reply.reply.encrypt.cipher.data.genericgcm128.cipher.len != plaintext_len) { ERROR("aes_gcm_encrypt: unexpected cipher len."); NFastApp_Free_Reply(app, NULL, NULL, &reply); return Result_AES_GCM_ENCRYPT_UNEXPECTED_CIPHERTEXT_LEN_FAILURE; @@ -110,11 +111,11 @@ Result aes_gcm_encrypt(M_KeyID keyId, uint8_t *plaintext, size_t plaintext_len, } memcpy(ciphertext, reply.reply.encrypt.cipher.iv.genericgcm128.iv.ptr, IV_SIZE_IN_BYTES); - memcpy(ciphertext + IV_SIZE_IN_BYTES, - reply.reply.encrypt.cipher.data.genericgcm128.cipher.ptr, - plaintext_len); - memcpy(ciphertext + plaintext_len + IV_SIZE_IN_BYTES, - reply.reply.encrypt.cipher.data.genericgcm128.tag.bytes, TAG_SIZE_IN_BYTES); + memcpy(ciphertext + IV_SIZE_IN_BYTES, reply.reply.encrypt.cipher.data.genericgcm128.cipher.ptr, plaintext_len); + memcpy( + ciphertext + plaintext_len + IV_SIZE_IN_BYTES, + reply.reply.encrypt.cipher.data.genericgcm128.tag.bytes, + TAG_SIZE_IN_BYTES); *bytes_written = expected_ciphertext_len; NFastApp_Free_Reply(app, NULL, NULL, &reply); @@ -124,9 +125,13 @@ Result aes_gcm_encrypt(M_KeyID keyId, uint8_t *plaintext, size_t plaintext_len, /** * AES-GCM decryption. */ -Result aes_gcm_decrypt(M_KeyID keyId, const uint8_t *ciphertext, - size_t ciphertext_len, uint8_t *plaintext, - size_t plaintext_len, size_t *bytes_written) { +Result aes_gcm_decrypt( + M_KeyID keyId, + const uint8_t* ciphertext, + size_t ciphertext_len, + uint8_t* plaintext, + size_t plaintext_len, + size_t* bytes_written) { // NULL pointer checks. if (!plaintext) { ERROR("%s: plaintext must not be NULL", __func__); @@ -145,8 +150,7 @@ Result aes_gcm_decrypt(M_KeyID keyId, const uint8_t *ciphertext, memzero(plaintext, plaintext_len); - if (ciphertext_len < IV_SIZE_IN_BYTES + TAG_SIZE_IN_BYTES) - { + if (ciphertext_len < IV_SIZE_IN_BYTES + TAG_SIZE_IN_BYTES) { ERROR("%s: ciphertext buffer too small.", __func__); return Result_AES_GCM_DECRYPT_BUFFER_TOO_SMALL_FAILURE; } @@ -156,8 +160,7 @@ Result aes_gcm_decrypt(M_KeyID keyId, const uint8_t *ciphertext, return Result_AES_GCM_DECRYPT_CIPHERTEXT_TOO_LONG_FAILURE; } - size_t expected_plaintext_len = ciphertext_len - IV_SIZE_IN_BYTES - - TAG_SIZE_IN_BYTES; + size_t expected_plaintext_len = ciphertext_len - IV_SIZE_IN_BYTES - TAG_SIZE_IN_BYTES; if (plaintext_len < expected_plaintext_len) { ERROR("aes_gcm_decrypt: plaintext buffer too small."); return Result_AES_GCM_DECRYPT_BUFFER_TOO_SMALL_FAILURE; @@ -167,8 +170,8 @@ Result aes_gcm_decrypt(M_KeyID keyId, const uint8_t *ciphertext, return Result_AES_GCM_DECRYPT_CIPHERTEXT_TOO_LONG_FAILURE; } - M_Command command = {0}; - M_Reply reply = {0}; + M_Command command = { 0 }; + M_Reply reply = { 0 }; Result r; command.cmd = Cmd_Decrypt; @@ -178,12 +181,12 @@ Result aes_gcm_decrypt(M_KeyID keyId, const uint8_t *ciphertext, memcpy(aes_gcm_buffer, ciphertext, ciphertext_len); command.args.decrypt.cipher.mech = Mech_RijndaelmGCM; - command.args.decrypt.cipher.data.genericgcm128.cipher.len = - expected_plaintext_len; - command.args.decrypt.cipher.data.genericgcm128.cipher.ptr = - aes_gcm_buffer + IV_SIZE_IN_BYTES; - memcpy(command.args.decrypt.cipher.data.genericgcm128.tag.bytes, - aes_gcm_buffer + ciphertext_len - TAG_SIZE_IN_BYTES, TAG_SIZE_IN_BYTES); + command.args.decrypt.cipher.data.genericgcm128.cipher.len = expected_plaintext_len; + command.args.decrypt.cipher.data.genericgcm128.cipher.ptr = aes_gcm_buffer + IV_SIZE_IN_BYTES; + memcpy( + command.args.decrypt.cipher.data.genericgcm128.tag.bytes, + aes_gcm_buffer + ciphertext_len - TAG_SIZE_IN_BYTES, + TAG_SIZE_IN_BYTES); command.args.decrypt.cipher.iv.genericgcm128.taglen = TAG_SIZE_IN_BYTES; command.args.decrypt.cipher.iv.genericgcm128.iv.len = IV_SIZE_IN_BYTES; command.args.decrypt.cipher.iv.genericgcm128.iv.ptr = aes_gcm_buffer; @@ -203,8 +206,7 @@ Result aes_gcm_decrypt(M_KeyID keyId, const uint8_t *ciphertext, } // success! - memcpy(plaintext, reply.reply.decrypt.plain.data.bytes.data.ptr, - expected_plaintext_len); + memcpy(plaintext, reply.reply.decrypt.plain.data.bytes.data.ptr, expected_plaintext_len); *bytes_written = expected_plaintext_len; diff --git a/core/src/ncipher/execute_command_hooks.c b/core/src/ncipher/execute_command_hooks.c index 67fb6dcb..f7959aa8 100644 --- a/core/src/ncipher/execute_command_hooks.c +++ b/core/src/ncipher/execute_command_hooks.c @@ -9,7 +9,7 @@ extern NFast_AppHandle app; -static Result ticket2keyId(const uint8_t *ticket_bytes, uint32_t ticket_len, M_KeyID *key_id); +static Result ticket2keyId(const uint8_t* ticket_bytes, uint32_t ticket_len, M_KeyID* key_id); extern M_KeyID master_seed_encryption_key; extern M_KeyID pub_key_encryption_key; @@ -30,16 +30,16 @@ Result pre_execute_command(const InternalCommandRequest* const in) { int i; // 1. Load the master_seed_encryption_key using the ticket - DEBUG("master_seed_encryption_key_ticket: %d", - in->master_seed_encryption_key_ticket.size); + DEBUG("master_seed_encryption_key_ticket: %d", in->master_seed_encryption_key_ticket.size); for (i = 0; i < in->master_seed_encryption_key_ticket.size; i++) { DEBUG_("%02x", in->master_seed_encryption_key_ticket.bytes[i]); } DEBUG_("\n"); - Result r = ticket2keyId(in->master_seed_encryption_key_ticket.bytes, - in->master_seed_encryption_key_ticket.size, - &master_seed_encryption_key); + Result r = ticket2keyId( + in->master_seed_encryption_key_ticket.bytes, + in->master_seed_encryption_key_ticket.size, + &master_seed_encryption_key); if (r != Result_SUCCESS) { ERROR("ticket2keyId failed (%d).", r); master_seed_encryption_key = 0; @@ -48,17 +48,15 @@ Result pre_execute_command(const InternalCommandRequest* const in) { INFO("master_seed_encryption_key loaded"); // 2. Load the pub_key_encryption_key using the ticket - DEBUG("pub_key_encryption_key_ticket: %d", - in->pub_key_encryption_key_ticket.size); + DEBUG("pub_key_encryption_key_ticket: %d", in->pub_key_encryption_key_ticket.size); for (i = 0; i < in->pub_key_encryption_key_ticket.size; i++) { DEBUG_("%02x", in->pub_key_encryption_key_ticket.bytes[i]); } DEBUG_("\n"); // Load the shared encryption key - r = ticket2keyId(in->pub_key_encryption_key_ticket.bytes, - in->pub_key_encryption_key_ticket.size, - &pub_key_encryption_key); + r = ticket2keyId( + in->pub_key_encryption_key_ticket.bytes, in->pub_key_encryption_key_ticket.size, &pub_key_encryption_key); if (r != Result_SUCCESS) { ERROR("ticket2keyId failed (%d).", r); master_seed_encryption_key = 0; @@ -76,14 +74,14 @@ void post_execute_command(void) { } uint8_t ticket_buffer[256]; -static Result ticket2keyId(const uint8_t *ticket_bytes, uint32_t ticket_len, - M_KeyID *key_id) { + +static Result ticket2keyId(const uint8_t* ticket_bytes, uint32_t ticket_len, M_KeyID* key_id) { if (ticket_len > sizeof(ticket_buffer)) { ERROR("ticket len too large"); return Result_TICKET_LEN_OVERFLOW_FAILURE; } - M_Command command = {0}; - M_Reply reply = {0}; + M_Command command = { 0 }; + M_Reply reply = { 0 }; M_ByteBlock ticket_block; Result r; diff --git a/core/src/ncipher/init.c b/core/src/ncipher/init.c index 18d91de2..617a1531 100644 --- a/core/src/ncipher/init.c +++ b/core/src/ncipher/init.c @@ -18,9 +18,9 @@ static int initialized = false; * returns -1 if nCipher init fails. * returns -2 if nCipher connect fails. */ - //TODO: convert to Result +// TODO: convert to Result int init(void) { - NFastAppInitArgs ia = {0}; + NFastAppInitArgs ia = { 0 }; M_Status rc; if ((rc = NFastApp_InitEx(&app, &ia, NULL))) { diff --git a/core/src/ncipher/init_wallet.c b/core/src/ncipher/init_wallet.c index 727d1c33..3dbcbe51 100644 --- a/core/src/ncipher/init_wallet.c +++ b/core/src/ncipher/init_wallet.c @@ -15,7 +15,7 @@ extern NFast_AppHandle app; -static Result gen_random(uint8_t *buffer, uint32_t buffer_len); +static Result gen_random(uint8_t* buffer, uint32_t buffer_len); /** * Initialize a wallet. @@ -34,12 +34,11 @@ static Result gen_random(uint8_t *buffer, uint32_t buffer_len); * - derive the pubkey * - encrypt the master_seed and pubkey */ -Result handle_init_wallet(const InternalCommandRequest* const in, - InternalCommandResponse_InitWalletResponse *out) { +Result handle_init_wallet(const InternalCommandRequest* const in, InternalCommandResponse_InitWalletResponse* out) { DEBUG("in handle_init_wallet"); // 1. Read random bytes from nCipher - uint8_t master_seed[MASTER_SEED_SIZE] = {0}; + uint8_t master_seed[MASTER_SEED_SIZE] = { 0 }; Result r = gen_random(master_seed, sizeof(master_seed)); if (r != Result_SUCCESS) { ERROR("generate_random_bytes failed (%d).", r); @@ -66,8 +65,7 @@ Result handle_init_wallet(const InternalCommandRequest* const in, hdnode_fill_public_key(&node); char pub_key[XPUB_SIZE]; - int ret = hdnode_serialize_public(&node, fingerprint, PUBKEY_PREFIX, - pub_key, sizeof(pub_key)); + int ret = hdnode_serialize_public(&node, fingerprint, PUBKEY_PREFIX, pub_key, sizeof(pub_key)); if (ret <= 0) { ERROR("hdnode_serialize_public failed"); return Result_UNKNOWN_INTERNAL_FAILURE; @@ -92,13 +90,14 @@ Result handle_init_wallet(const InternalCommandRequest* const in, } uint8_t gen_random_buffer[256]; -static Result gen_random(uint8_t *buffer, uint32_t buffer_len) { + +static Result gen_random(uint8_t* buffer, uint32_t buffer_len) { if (buffer_len > sizeof(gen_random_buffer)) { ERROR("buffer_len too large"); return Result_GEN_RANDOM_BUFFER_TOO_LARGE_FAILURE; } - M_Command command = {0}; - M_Reply reply = {0}; + M_Command command = { 0 }; + M_Reply reply = { 0 }; Result r; command.cmd = Cmd_GenerateRandom; diff --git a/core/src/ncipher/module_certificate.c b/core/src/ncipher/module_certificate.c index 5ae1681f..50e2406a 100644 --- a/core/src/ncipher/module_certificate.c +++ b/core/src/ncipher/module_certificate.c @@ -14,7 +14,7 @@ extern NFast_AppHandle app; * These are used to verify signatures on CodeSafe modules when they attempt to * access keys that are protected by a seeinteg key */ -Result module_certificate_init(M_CertificateList *cert_list, M_Certificate *certs) { +Result module_certificate_init(M_CertificateList* cert_list, M_Certificate* certs) { int signer_count = 0; M_Command command; M_Reply reply; @@ -53,20 +53,18 @@ Result module_certificate_init(M_CertificateList *cert_list, M_Certificate *cert int i; for (i = 0; i < signer_count; i++) { certs[i].type = CertType_SEECert; - memcpy(&certs[i].keyhash, - &(reply.reply.getworldsigners.sigs[i].hash), - sizeof(M_KeyHash)); + memcpy(&certs[i].keyhash, &(reply.reply.getworldsigners.sigs[i].hash), sizeof(M_KeyHash)); } NFastApp_Free_Reply(app, NULL, NULL, &reply); return Result_SUCCESS; } -void module_certificate_cleanup(M_CertificateList *cert_list) { +void module_certificate_cleanup(M_CertificateList* cert_list) { int i; for (i = 0; i < cert_list->n_certs; i++) { memzero(&cert_list->certs[i], sizeof(M_Certificate)); } memzero(cert_list, sizeof(M_CertificateList)); -} \ No newline at end of file +} diff --git a/core/src/ncipher/no_rollback.c b/core/src/ncipher/no_rollback.c index c1c3b761..07774242 100644 --- a/core/src/ncipher/no_rollback.c +++ b/core/src/ncipher/no_rollback.c @@ -29,8 +29,8 @@ extern NFast_AppHandle app; Result no_rollback_read(const char* filename, char buf[static VERSION_SIZE]) { Result r = Result_UNKNOWN_INTERNAL_FAILURE; - M_Command command = {0}; - M_Reply reply = {0}; + M_Command command = { 0 }; + M_Reply reply = { 0 }; command.cmd = Cmd_NVMemOp; command.args.nvmemop.module = 1; // we assume there's only HSM. @@ -45,8 +45,7 @@ Result no_rollback_read(const char* filename, char buf[static VERSION_SIZE]) { } // Validate magic string and return the version - DEBUG("no_rollback_read: nvram contents: (%d) ", - reply.reply.nvmemop.res.read.data.len); + DEBUG("no_rollback_read: nvram contents: (%d) ", reply.reply.nvmemop.res.read.data.len); for (unsigned int i = 0; i < reply.reply.nvmemop.res.read.data.len; i++) { DEBUG_("%02x", reply.reply.nvmemop.res.read.data.ptr[i]); } @@ -76,8 +75,8 @@ Result no_rollback_write(const char* filename, char buf[static VERSION_SIZE]) { Result r = Result_UNKNOWN_INTERNAL_FAILURE; - M_Command command = {0}; - M_Reply reply = {0}; + M_Command command = { 0 }; + M_Reply reply = { 0 }; command.cmd = Cmd_NVMemOp; command.args.nvmemop.module = 1; // we assume there's only one HSM. diff --git a/core/src/ncipher/protection.c b/core/src/ncipher/protection.c index 7de7fe66..8bfea6f9 100644 --- a/core/src/ncipher/protection.c +++ b/core/src/ncipher/protection.c @@ -15,4 +15,3 @@ M_KeyID pub_key_encryption_key = 0; // The following implementation is shared between dev and ncipher targets #include "../protect.c" - diff --git a/core/src/ncipher/transact.c b/core/src/ncipher/transact.c index 84abea48..9ba765e6 100644 --- a/core/src/ncipher/transact.c +++ b/core/src/ncipher/transact.c @@ -14,7 +14,7 @@ extern NFastApp_Connection conn; extern NFast_AppHandle app; extern M_CertificateList cert_list; -Result transact(M_Command *command, M_Reply *reply) { +Result transact(M_Command* command, M_Reply* reply) { if (command->cmd != Cmd_GetWorldSigners) { // Set certs_present, unless we are asking the HSM for the certs in the first place. command->certs = &cert_list; diff --git a/core/src/print.c b/core/src/print.c index e3d6605c..3da30150 100644 --- a/core/src/print.c +++ b/core/src/print.c @@ -11,21 +11,29 @@ static void print_uint(uint64_t value, uint8_t bytes) { for (int i = 0; i < bytes; i++) { // Some extra (uint8_t) casts here so clang-tidy is happy - uint8_t byte = (uint8_t)(value & (uint8_t)0xFF); + uint8_t byte = (uint8_t) (value & (uint8_t) 0xFF); DEBUG_("%02x", byte); - value = value >> (uint8_t)8; + value = value >> (uint8_t) 8; } } -void print_uint8(const uint8_t value) { print_uint(value, 1); } +void print_uint8(const uint8_t value) { + print_uint(value, 1); +} -void print_uint16(const uint16_t value) { print_uint(value, 2); } +void print_uint16(const uint16_t value) { + print_uint(value, 2); +} -void print_uint32(const uint32_t value) { print_uint(value, 4); } +void print_uint32(const uint32_t value) { + print_uint(value, 4); +} -void print_uint64(const uint64_t value) { print_uint(value, 8); } +void print_uint64(const uint64_t value) { + print_uint(value, 8); +} -void print_bytes(const uint8_t *buffer, size_t len) { +void print_bytes(const uint8_t* buffer, size_t len) { size_t i; for (i = 0; i < len; i++) { DEBUG_("%02x", buffer[i]); @@ -33,7 +41,7 @@ void print_bytes(const uint8_t *buffer, size_t len) { DEBUG_("\n"); } -void print_rev_bytes(const uint8_t *buffer, size_t len) { +void print_rev_bytes(const uint8_t* buffer, size_t len) { size_t i; for (i = len; i-- > 0;) { DEBUG_("%02x", buffer[i]); @@ -41,7 +49,7 @@ void print_rev_bytes(const uint8_t *buffer, size_t len) { DEBUG_("\n"); } -void print_var_bytes(const uint8_t *buffer, size_t len) { +void print_var_bytes(const uint8_t* buffer, size_t len) { if (len <= 252) { print_uint8(len); } else if (len <= 0xffff) { diff --git a/core/src/protect.c b/core/src/protect.c index 993d49df..73d6dacc 100644 --- a/core/src/protect.c +++ b/core/src/protect.c @@ -8,8 +8,7 @@ * * Zeros xpub. */ -Result protect_pubkey(char xpub[static XPUB_SIZE], - EncryptedPubKey *encrypted_pub_key) { +Result protect_pubkey(char xpub[static XPUB_SIZE], EncryptedPubKey* encrypted_pub_key) { // Insert magic string for binary static analysis. // This is extremely hacky, but works. ¯\_(ツ)_/¯ #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION @@ -21,8 +20,9 @@ Result protect_pubkey(char xpub[static XPUB_SIZE], return Result_UNKNOWN_INTERNAL_FAILURE; } - static_assert(sizeof(encrypted_pub_key->encrypted_pub_key.bytes) >= MAX_ENCRYPTED_PUBKEY_SIZE, - "misconfigured encrypted_pub_key max size"); + static_assert( + sizeof(encrypted_pub_key->encrypted_pub_key.bytes) >= MAX_ENCRYPTED_PUBKEY_SIZE, + "misconfigured encrypted_pub_key max size"); if (pub_key_encryption_key == 0) { ERROR("pub_key_encryption_key not initialized"); return Result_PROTECT_PUBKEY_NO_PUBKEY_ENCRYPTION_KEY_FAILURE; @@ -32,11 +32,13 @@ Result protect_pubkey(char xpub[static XPUB_SIZE], pb_size_t xpub_len = (pb_size_t) strlen(xpub); - Result r = aes_gcm_encrypt(pub_key_encryption_key, - (uint8_t *) xpub, xpub_len, - encrypted_pub_key->encrypted_pub_key.bytes, - sizeof(encrypted_pub_key->encrypted_pub_key.bytes), - &ciphertext_len); + Result r = aes_gcm_encrypt( + pub_key_encryption_key, + (uint8_t*) xpub, + xpub_len, + encrypted_pub_key->encrypted_pub_key.bytes, + sizeof(encrypted_pub_key->encrypted_pub_key.bytes), + &ciphertext_len); if (Result_SUCCESS != r) { ERROR("aes_gcm_encrypt failed (%d)", r); return r; @@ -58,8 +60,7 @@ Result protect_pubkey(char xpub[static XPUB_SIZE], /** * Decrypt encrypted_pub_key with pubkey encryption key. */ -Result expose_pubkey(const EncryptedPubKey* const encrypted_pub_key, - char xpub[static XPUB_SIZE]) { +Result expose_pubkey(const EncryptedPubKey* const encrypted_pub_key, char xpub[static XPUB_SIZE]) { if (pub_key_encryption_key == 0) { ERROR("pub_key_encryption_key not initialized"); return Result_EXPOSE_PUBKEY_NO_PUBKEY_ENCRYPTION_KEY_FAILURE; @@ -81,10 +82,13 @@ Result expose_pubkey(const EncryptedPubKey* const encrypted_pub_key, size_t xpub_len; - Result r = aes_gcm_decrypt(pub_key_encryption_key, - encrypted_pub_key->encrypted_pub_key.bytes, - encrypted_pub_key->encrypted_pub_key.size, - (uint8_t *)xpub, XPUB_SIZE - 1, &xpub_len); + Result r = aes_gcm_decrypt( + pub_key_encryption_key, + encrypted_pub_key->encrypted_pub_key.bytes, + encrypted_pub_key->encrypted_pub_key.size, + (uint8_t*) xpub, + XPUB_SIZE - 1, + &xpub_len); if (Result_SUCCESS != r) { ERROR("%s failed (%d)", __func__, r); return r; @@ -102,11 +106,10 @@ Result expose_pubkey(const EncryptedPubKey* const encrypted_pub_key, * * Zeros master_seed. */ -Result protect_wallet(uint8_t master_seed[static MASTER_SEED_SIZE], - EncryptedMasterSeed *encrypted_master_seed) { - static_assert(sizeof(encrypted_master_seed->encrypted_master_seed.bytes) >= - MASTER_SEED_SIZE, - "misconfigured encrypted_master_seed max size"); +Result protect_wallet(uint8_t master_seed[static MASTER_SEED_SIZE], EncryptedMasterSeed* encrypted_master_seed) { + static_assert( + sizeof(encrypted_master_seed->encrypted_master_seed.bytes) >= MASTER_SEED_SIZE, + "misconfigured encrypted_master_seed max size"); if (master_seed_encryption_key == 0) { ERROR("master_seed_encryption_key not initialized"); @@ -115,7 +118,9 @@ Result protect_wallet(uint8_t master_seed[static MASTER_SEED_SIZE], size_t ciphertext_len; Result r = aes_gcm_encrypt( - master_seed_encryption_key, master_seed, MASTER_SEED_SIZE, + master_seed_encryption_key, + master_seed, + MASTER_SEED_SIZE, encrypted_master_seed->encrypted_master_seed.bytes, sizeof(encrypted_master_seed->encrypted_master_seed.bytes), &ciphertext_len); @@ -138,8 +143,9 @@ Result protect_wallet(uint8_t master_seed[static MASTER_SEED_SIZE], /** * Decrypt master_seed with master_seed_encryption_key. */ -Result expose_wallet(const EncryptedMasterSeed* const encrypted_master_seed, - uint8_t master_seed[static MASTER_SEED_SIZE]) { +Result expose_wallet( + const EncryptedMasterSeed* const encrypted_master_seed, + uint8_t master_seed[static MASTER_SEED_SIZE]) { if (master_seed_encryption_key == 0) { ERROR("master_seed_encryption_key not initialized"); return Result_EXPOSE_WALLET_NO_MASTER_SEED_ENCRYPTION_KEY_FAILURE; @@ -151,10 +157,13 @@ Result expose_wallet(const EncryptedMasterSeed* const encrypted_master_seed, } size_t master_seed_len; - Result r = aes_gcm_decrypt(master_seed_encryption_key, - encrypted_master_seed->encrypted_master_seed.bytes, - encrypted_master_seed->encrypted_master_seed.size, - master_seed, MASTER_SEED_SIZE, &master_seed_len); + Result r = aes_gcm_decrypt( + master_seed_encryption_key, + encrypted_master_seed->encrypted_master_seed.bytes, + encrypted_master_seed->encrypted_master_seed.size, + master_seed, + MASTER_SEED_SIZE, + &master_seed_len); if (r != Result_SUCCESS) { ERROR("aes_gcm_decrypt failed (%d).", r); return r; diff --git a/core/src/qrsignatures.c b/core/src/qrsignatures.c index 6ec068fb..9aea625a 100644 --- a/core/src/qrsignatures.c +++ b/core/src/qrsignatures.c @@ -54,18 +54,13 @@ bool check_qrsignature_pub( } int result_verify = ecdsa_verify( - (const ecdsa_curve *)&nist256p1, - HASHER_SHA2, - (const uint8_t *) pubkey, - signature, - data, - (uint32_t)data_len); + (const ecdsa_curve*) &nist256p1, HASHER_SHA2, (const uint8_t*) pubkey, signature, data, (uint32_t) data_len); if (result_verify == 0) { - result = true; - DEBUG("QR signature verification successful."); + result = true; + DEBUG("QR signature verification successful."); } else { - DEBUG("QR signature verification failed."); + DEBUG("QR signature verification failed."); } out: diff --git a/core/src/rpc.c b/core/src/rpc.c index 970fd2a9..710789a3 100644 --- a/core/src/rpc.c +++ b/core/src/rpc.c @@ -14,8 +14,7 @@ #include #include -static void execute_command(const InternalCommandRequest* const cmd, - InternalCommandResponse *out); +static void execute_command(const InternalCommandRequest* const cmd, InternalCommandResponse* out); static int check_version(const InternalCommandRequest* const cmd) { if (VERSION != cmd->version) { @@ -24,14 +23,14 @@ static int check_version(const InternalCommandRequest* const cmd) { } return true; } + /** * Check signature on input bytes. * Deserialize them and then populate the internal command request's * redundant fields with the deserialized data. * @return Return an error if the signature check failed or decoding the bytes failed. */ -static Result populate_internal_command(InternalCommandRequest * to){ - +static Result populate_internal_command(InternalCommandRequest* to) { Result res = Result_SUCCESS; // The signature being checked here is on the serialized bytes generated by the coordinator service. // Those bytes are the serialization of CommandRequest structure. @@ -47,7 +46,8 @@ static Result populate_internal_command(InternalCommandRequest * to){ goto cleanup; } - pb_istream_t pb_command = pb_istream_from_buffer(to->serialized_command_request.bytes, to->serialized_command_request.size); + pb_istream_t pb_command = + pb_istream_from_buffer(to->serialized_command_request.bytes, to->serialized_command_request.size); CommandRequest from = CommandRequest_init_default; // Cannot use pb_decode_delimited as on the coordinator service the java code is generating bytes // without the delimited values. @@ -56,22 +56,21 @@ static Result populate_internal_command(InternalCommandRequest * to){ ERROR("Could not decode input bytes for command request."); goto cleanup; } - if(from.which_command != CommandRequest_SignTx_tag){ + if (from.which_command != CommandRequest_SignTx_tag) { res = Result_COMMAND_SHOULD_BE_SIGNTX; ERROR("Input command is not Sign Tx"); goto cleanup; - } + } to->command.SignTx.inputs_count = from.command.SignTx.inputs_count; to->command.SignTx.outputs_count = from.command.SignTx.outputs_count; - for(pb_size_t i = 0; i < from.command.SignTx.inputs_count ; i++){ - to->command.SignTx.inputs[i] = from.command.SignTx.inputs[i]; - + for (pb_size_t i = 0; i < from.command.SignTx.inputs_count; i++) { + to->command.SignTx.inputs[i] = from.command.SignTx.inputs[i]; } - for(pb_size_t i = 0; i < from.command.SignTx.outputs_count ; i++){ - to->command.SignTx.outputs[i] = from.command.SignTx.outputs[i]; + for (pb_size_t i = 0; i < from.command.SignTx.outputs_count; i++) { + to->command.SignTx.outputs[i] = from.command.SignTx.outputs[i]; } - - //lock time is used in internal hash calculation so it should be present. + + // lock time is used in internal hash calculation so it should be present. if (from.command.SignTx.has_lock_time) { to->command.SignTx.lock_time = from.command.SignTx.lock_time; } else { @@ -79,32 +78,33 @@ static Result populate_internal_command(InternalCommandRequest * to){ res = Result_REQUIRED_FIELDS_NOT_PRESENT; goto cleanup; } - //Wallet ID is optional and not really used in the code at the moment. + // Wallet ID is optional and not really used in the code at the moment. if (from.has_wallet_id) { to->wallet_id = from.wallet_id; } - cleanup: - +cleanup: + return res; } -static void handle_error(pb_istream_t * input, pb_ostream_t * output, Result error_code, const char * error_message){ + +static void handle_error(pb_istream_t* input, pb_ostream_t* output, Result error_code, const char* error_message) { InternalCommandResponse out = InternalCommandResponse_init_default; ERROR("%s: %s", error_message, PB_GET_ERROR(input)); out.which_response = InternalCommandResponse_Error_tag; out.response.Error.code = error_code; - snprintf(out.response.Error.message, sizeof(out.response.Error.message), - "%s: %s", error_message, PB_GET_ERROR(input)); + snprintf( + out.response.Error.message, sizeof(out.response.Error.message), "%s: %s", error_message, PB_GET_ERROR(input)); out.response.Error.has_message = true; if (!pb_encode_delimited(output, &InternalCommandResponse_msg, &out)) { - ERROR("Encoding error message about decoding failed: %s", - PB_GET_ERROR(output)); + ERROR("Encoding error message about decoding failed: %s", PB_GET_ERROR(output)); } - return; + return; } + // handle_incoming_message is the central RPC entry point that invokes the // requested command. -void handle_incoming_message(pb_istream_t *input, pb_ostream_t *output) { +void handle_incoming_message(pb_istream_t* input, pb_ostream_t* output) { InternalCommandRequest cmd = InternalCommandRequest_init_default; InternalCommandResponse out = InternalCommandResponse_init_default; @@ -114,7 +114,7 @@ void handle_incoming_message(pb_istream_t *input, pb_ostream_t *output) { } // For sign command QR code needs to be signed. if (cmd.which_command == InternalCommandRequest_SignTx_tag) { - if(!cmd.has_serialized_command_request){ + if (!cmd.has_serialized_command_request) { handle_error(input, output, Result_SERIALIZED_BYTES_SHOULD_BE_PRESENT, "Serialized QR code not present in input"); return; } @@ -134,8 +134,7 @@ void handle_incoming_message(pb_istream_t *input, pb_ostream_t *output) { } // execute command -static void execute_command(const InternalCommandRequest* const cmd, - InternalCommandResponse *out) { +static void execute_command(const InternalCommandRequest* const cmd, InternalCommandResponse* out) { if (!check_version(cmd)) { out->which_response = InternalCommandResponse_Error_tag; out->response.Error.code = Result_VERSION_MISMATCH; @@ -158,8 +157,7 @@ static void execute_command(const InternalCommandRequest* const cmd, break; case InternalCommandRequest_FinalizeWallet_tag: INFO("Command FinalizeWallet"); - r = handle_finalize_wallet(&cmd->command.FinalizeWallet, - &out->response.FinalizeWallet); + r = handle_finalize_wallet(&cmd->command.FinalizeWallet, &out->response.FinalizeWallet); out->which_response = InternalCommandResponse_FinalizeWallet_tag; break; case InternalCommandRequest_SignTx_tag: @@ -177,8 +175,12 @@ static void execute_command(const InternalCommandRequest* const cmd, if (r != Result_SUCCESS) { out->which_response = InternalCommandResponse_Error_tag; out->response.Error.code = r; - snprintf(out->response.Error.message, sizeof(out->response.Error.message), - "Error handling command tag %d; r = %d\n", cmd->which_command, r); + snprintf( + out->response.Error.message, + sizeof(out->response.Error.message), + "Error handling command tag %d; r = %d\n", + cmd->which_command, + r); ERROR("%s", out->response.Error.message); out->response.Error.has_message = true; } diff --git a/core/src/script.c b/core/src/script.c index c7f33c3a..86beb12e 100644 --- a/core/src/script.c +++ b/core/src/script.c @@ -4,7 +4,7 @@ #include -Result script_push(script_t *script, enum opcodetype opcode) { +Result script_push(script_t* script, enum opcodetype opcode) { if (script->len == SCRIPT_MAX_LEN) { return Result_SCRIPT_PUSH_OVERFLOW_FAILURE; } @@ -13,7 +13,7 @@ Result script_push(script_t *script, enum opcodetype opcode) { return Result_SUCCESS; } -Result script_push_data(script_t *script, const uint8_t *data, size_t len) { +Result script_push_data(script_t* script, const uint8_t* data, size_t len) { Result r; if (len < OP_PUSHDATA1) { r = script_push(script, len); diff --git a/core/src/sign.c b/core/src/sign.c index 940c4bc0..f4ff42c1 100644 --- a/core/src/sign.c +++ b/core/src/sign.c @@ -25,9 +25,8 @@ #include #include -static void compute_prevout_hash(const TxInput* const inputs, - pb_size_t inputs_count, - uint8_t hash[static HASHER_DIGEST_LENGTH]) { +static void +compute_prevout_hash(const TxInput* const inputs, pb_size_t inputs_count, uint8_t hash[static HASHER_DIGEST_LENGTH]) { Hasher hasher; hasher_Init(&hasher, HASHER_SHA2D); for (int i = 0; i < inputs_count; i++) { @@ -44,8 +43,8 @@ static void compute_prevout_hash(const TxInput* const inputs, } // This assumes all inputs have the same sequence value -static void compute_sequence_hash(uint32_t sequence, pb_size_t inputs_count, - uint8_t hash[static HASHER_DIGEST_LENGTH]) { +static void +compute_sequence_hash(uint32_t sequence, pb_size_t inputs_count, uint8_t hash[static HASHER_DIGEST_LENGTH]) { Hasher hasher; hasher_Init(&hasher, HASHER_SHA2D); for (int i = 0; i < inputs_count; i++) { @@ -58,9 +57,8 @@ static void compute_sequence_hash(uint32_t sequence, pb_size_t inputs_count, * Takes an (decrypted) extended public key and produces the public key derived * from the path specified. */ -static Result derive_public_key(const char *xpub, - const Path* const path, - uint8_t public_key[static COMPRESSED_PUBKEY_SIZE]) { +static Result +derive_public_key(const char* xpub, const Path* const path, uint8_t public_key[static COMPRESSED_PUBKEY_SIZE]) { HDNode node; int r = hdnode_deserialize(xpub, PUBKEY_PREFIX, 0, SECP256K1_NAME, &node, NULL); @@ -97,9 +95,7 @@ static Result derive_public_key(const char *xpub, * Takes the seed and a path. Returns HDNode suitable for signing transactions * at that path. */ -static Result derive_private_key(uint8_t seed[static SHA512_DIGEST_LENGTH], - const Path* const path, - HDNode *out) { +static Result derive_private_key(uint8_t seed[static SHA512_DIGEST_LENGTH], const Path* const path, HDNode* out) { if (hdnode_from_seed(seed, SHA512_DIGEST_LENGTH, SECP256K1_NAME, out) != 1) { ERROR("error: hdnode_from_seed failed."); return Result_DERIVE_PRIVATE_KEY_HDNODE_FROM_SEED_FAILURE; @@ -141,8 +137,7 @@ static void sort_public_keys( for (i = 0; i < MULTISIG_PARTS; i++) { int score = 0; for (j = 0; j < MULTISIG_PARTS; j++) { - if (strncmp((char *)unsorted_keys[i], (char *)unsorted_keys[j], - COMPRESSED_PUBKEY_SIZE) > 0) { + if (strncmp((char*) unsorted_keys[i], (char*) unsorted_keys[j], COMPRESSED_PUBKEY_SIZE) > 0) { score++; } } @@ -153,10 +148,7 @@ static void sort_public_keys( /** * Returns the script (i.e. 2 [addr1] [addr2] [addr3] [addr4] 4 checkmultisig). */ -static Result multisig_script( - script_t *script, - char xpub[static MULTISIG_PARTS][XPUB_SIZE], - const Path* const path) { +static Result multisig_script(script_t* script, char xpub[static MULTISIG_PARTS][XPUB_SIZE], const Path* const path) { // Derive addresses for this path uint8_t public_keys[MULTISIG_PARTS][COMPRESSED_PUBKEY_SIZE]; for (int i = 0; i < MULTISIG_PARTS; i++) { @@ -242,15 +234,15 @@ bool validate_fees(const InternalCommandRequest_SignTxRequest* const request) { return fee < conv_btc_to_satoshi(1) || fee * 10 < total; } -static Result hash_input(char xpub[static MULTISIG_PARTS][XPUB_SIZE], - const TxInput* const input, - uint32_t sequence, - uint32_t lock_time, - uint8_t prevoutsHash[static HASHER_DIGEST_LENGTH], - uint8_t seqHash[static HASHER_DIGEST_LENGTH], - uint8_t outputHash[static HASHER_DIGEST_LENGTH], - uint8_t hash[static HASHER_DIGEST_LENGTH]) { - +static Result hash_input( + char xpub[static MULTISIG_PARTS][XPUB_SIZE], + const TxInput* const input, + uint32_t sequence, + uint32_t lock_time, + uint8_t prevoutsHash[static HASHER_DIGEST_LENGTH], + uint8_t seqHash[static HASHER_DIGEST_LENGTH], + uint8_t outputHash[static HASHER_DIGEST_LENGTH], + uint8_t hash[static HASHER_DIGEST_LENGTH]) { Hasher hasher; DEBUG("hash_input"); @@ -313,10 +305,7 @@ static Result hash_input(char xpub[static MULTISIG_PARTS][XPUB_SIZE], } // hash_p2pkh_address derives a P2PKH address and hashes it into hasher -static Result hash_p2pkh_address( - Hasher *hasher, - const char *xpub, - const Path* const path) { +static Result hash_p2pkh_address(Hasher* hasher, const char* xpub, const Path* const path) { uint8_t public_key[COMPRESSED_PUBKEY_SIZE]; Result r = derive_public_key(xpub, path, public_key); if (r != Result_SUCCESS) { @@ -371,9 +360,7 @@ static Result hash_p2pkh_address( // hash_change_address computes a change address for Path and hashes it. // TODO: While this looks mostly right, it's untested. -static Result hash_change_address(Hasher *hasher, - char xpub[static MULTISIG_PARTS][XPUB_SIZE], - const Path* const path) { +static Result hash_change_address(Hasher* hasher, char xpub[static MULTISIG_PARTS][XPUB_SIZE], const Path* const path) { // Here we need to generate a P2SH-P2WSH change transaction back to the // cold wallet @@ -461,12 +448,11 @@ static Result hash_change_address(Hasher *hasher, } // compute_output_hash iterates over all -static Result -compute_output_hash(char xpub[static MULTISIG_PARTS][XPUB_SIZE], - const TxOutput* const outputs, - pb_size_t outputs_count, - uint8_t output_hash[static HASHER_DIGEST_LENGTH]) { - +static Result compute_output_hash( + char xpub[static MULTISIG_PARTS][XPUB_SIZE], + const TxOutput* const outputs, + pb_size_t outputs_count, + uint8_t output_hash[static HASHER_DIGEST_LENGTH]) { Hasher hasher; hasher_Init(&hasher, HASHER_SHA2D); for (int i = 0; i < outputs_count; i++) { @@ -503,15 +489,16 @@ compute_output_hash(char xpub[static MULTISIG_PARTS][XPUB_SIZE], * An effort has been made to zeroize them regardless of success or failure of this function. * */ -Result handle_sign_tx(const InternalCommandRequest_SignTxRequest* const request, - InternalCommandResponse_SignTxResponse *response) { +Result handle_sign_tx( + const InternalCommandRequest_SignTxRequest* const request, + InternalCommandResponse_SignTxResponse* response) { Result r = Result_SUCCESS; - uint8_t CONFIDENTIAL seed[SHA512_DIGEST_LENGTH] = {0}; + uint8_t CONFIDENTIAL seed[SHA512_DIGEST_LENGTH] = { 0 }; HDNode CONFIDENTIAL wallet; memzero(&wallet, sizeof(HDNode)); - char CONFIDENTIAL xpub[MULTISIG_PARTS][XPUB_SIZE] = {{0}}; - uint8_t CONFIDENTIAL public_key[33] = {0}; + char CONFIDENTIAL xpub[MULTISIG_PARTS][XPUB_SIZE] = { { 0 } }; + uint8_t CONFIDENTIAL public_key[33] = { 0 }; if (!validate_fees(request)) { ERROR("validate_fees failed"); @@ -564,12 +551,10 @@ Result handle_sign_tx(const InternalCommandRequest_SignTxRequest* const request, // Create a signature for each input. for (int i = 0; i < request->inputs_count; i++) { - // Compute hash to sign: BIP-0143 uint8_t hash[HASHER_DIGEST_LENGTH]; - r = hash_input(xpub, &request->inputs[i], sequence, request->lock_time, - prevoutsHash, seqHash, outputHash, hash); + r = hash_input(xpub, &request->inputs[i], sequence, request->lock_time, prevoutsHash, seqHash, outputHash, hash); if (r != Result_SUCCESS) { ERROR("hash_input failed: (%d).", r); goto cleanup; @@ -589,23 +574,23 @@ Result handle_sign_tx(const InternalCommandRequest_SignTxRequest* const request, ERROR("Failed deriving public key"); goto cleanup; } - static_assert(sizeof(public_key) == sizeof(wallet.public_key), - "Pubkey size mismatch"); + static_assert(sizeof(public_key) == sizeof(wallet.public_key), "Pubkey size mismatch"); if (memcmp(public_key, wallet.public_key, sizeof(public_key)) == 0) { DEBUG("Signing for pubkey %d", j); found = true; } } if (!found) { - ERROR("We're signing with a private key that doesn't match one of our " - "public keys"); + ERROR( + "We're signing with a private key that doesn't match one of our " + "public keys"); print_bytes(wallet.public_key, sizeof(wallet.public_key)); r = Result_UNKNOWN_INTERNAL_FAILURE; goto cleanup; } // sign the hash - uint8_t sig[64] = {0}; + uint8_t sig[64] = { 0 }; if (hdnode_sign_digest(&wallet, hash, sig, NULL, NULL) != 0) { ERROR("hdnode_sign_digest failed"); r = Result_UNKNOWN_INTERNAL_FAILURE; @@ -616,8 +601,7 @@ Result handle_sign_tx(const InternalCommandRequest_SignTxRequest* const request, // we are operating correctly, and can also potentially prevent some types // of glitch attacks. hdnode_fill_public_key(&wallet); - if (ecdsa_verify_digest(wallet.curve->params, wallet.public_key, sig, - hash) != 0) { + if (ecdsa_verify_digest(wallet.curve->params, wallet.public_key, sig, hash) != 0) { ERROR("Verifying signature we just created failed"); r = Result_UNKNOWN_INTERNAL_FAILURE; goto cleanup; @@ -628,7 +612,7 @@ Result handle_sign_tx(const InternalCommandRequest_SignTxRequest* const request, int der_len = ecdsa_sig_to_der(sig, response->signatures[i].der.bytes); response->signatures[i].has_der = true; - response->signatures[i].der.size = (pb_size_t)der_len; + response->signatures[i].der.size = (pb_size_t) der_len; DEBUG("Signature:"); for (int j = 0; j < der_len; j++) { DEBUG_("%02x", response->signatures[i].der.bytes[j]); @@ -636,21 +620,19 @@ Result handle_sign_tx(const InternalCommandRequest_SignTxRequest* const request, DEBUG_("\n"); response->signatures[i].has_hash = true; - static_assert(sizeof(hash) == sizeof(response->signatures[i].hash), - "Expect hash size to match proto size"); + static_assert(sizeof(hash) == sizeof(response->signatures[i].hash), "Expect hash size to match proto size"); memcpy(response->signatures[i].hash, hash, sizeof(hash)); } response->signatures_count = request->inputs_count; - - cleanup: + +cleanup: // cleanup the house be it error or success. memzero(seed, SHA512_DIGEST_LENGTH); memzero(&wallet, sizeof(HDNode)); - for (int i = 0 ; i < MULTISIG_PARTS ; i++) { - memzero(xpub[i], XPUB_SIZE); + for (int i = 0; i < MULTISIG_PARTS; i++) { + memzero(xpub[i], XPUB_SIZE); } memzero(public_key, 33); - return r; } diff --git a/core/trezor-crypto/.clang-format b/core/trezor-crypto/.clang-format new file mode 100644 index 00000000..e3845288 --- /dev/null +++ b/core/trezor-crypto/.clang-format @@ -0,0 +1 @@ +DisableFormat: true diff --git a/utils/tests_wycheproof_generate.py b/utils/tests_wycheproof_generate.py index b26dfa89..2abaee90 100644 --- a/utils/tests_wycheproof_generate.py +++ b/utils/tests_wycheproof_generate.py @@ -100,7 +100,8 @@ def to_c_array(x): } wycheproof_ecdsa_testvector; """ - +print("// clang-format off") +print("") print("/* Note: this file was autogenerated using tests_wycheproof_generate.py. Do not edit. */") print(f"#define SECP256K1_ECDSA_WYCHEPROOF_NUMBER_TESTVECTORS ({num_vectors})") @@ -113,3 +114,5 @@ def to_c_array(x): print("static const wycheproof_ecdsa_testvector testvectors[SECP256K1_ECDSA_WYCHEPROOF_NUMBER_TESTVECTORS] = {") print(out) print("};") +print("") +print("// clang-format on")