Penetration Test Report (NCCGroup): NCC Group O1LabsOperatingCo Report 2022 02 21 v1.0

Mina Client SDK, Signature Library and Base
Components – Cryptography and
Implementation Review
O(1) Labs Operating Co.
February 21, 2022 – Version 1.0
Preparedfor
EmreTekisalp
IzaakMeckler
AneeshaRaines
BijanShahrokhi
Preparedby
EricSchorn
AvaHowell
©2022–NCCGroup
PreparedbyNCCGroupSecurityServices,Inc. forO(1)LabsOperatingCo.. Portionsofthisdocument
andthetemplatesusedinitsproductionarethepropertyofNCCGroupandcannotbecopied(infullor
inpart)withoutNCCGroup’spermission.
Whileprecautionshavebeentakeninthepreparationofthisdocument,NCCGroupthepublisher,and
theauthor(s)assumenoresponsibilityforerrors,omissions,orfordamagesresultingfromtheuseof
the information contained herein. Use of NCC Group’s services does not guarantee the security of a
system,orthatcomputerintrusionswillnotoccur.
Executive Summary
Synopsis
DuringOctober2021, O(1)LabsengagedNCCGroup’sCryptographyServicesteamtoconductacryptographyand
implementation review of selected components within the main source code repository for the Mina project. Mina
implementsacryptocurrencywithalightweightandconstant-sizedblockchain,wherethecodeisprimarilywrittenin
OCaml. TheselectedcomponentsinvolvedtheclientSDK,private/publickeyfunctionality,Schnorrsignaturelogicand
severalotherrelatedfunctions.FullaccesstosourcecodewasprovidedwithsupportoverDiscord,andtwoconsultants
deliveredtheengagementwitheightperson-daysofeffort.
Scope
TheprojectscopecenteredaroundthemainMinarepositorycommita1d868fandincludedthreecentralelements
andsupportingdocumentation:
• client_sdk • signature_lib
– src/app/client_sdk/* – src/nonconsensus/signature_lib/private_key.ml
• mina_base – src/nonconsensus/signature_lib/schnorr.ml
– src/lib/mina_base/signed_command_payload.ml – src/nonconsensus/signature_lib/public_key.ml
– src/lib/mina_base/signed_command.ml – src/nonconsensus/rosetta_coding/coding.ml
• Documentationfromwithintherepositoryandalsoat: – src/nonconsensus/snark_params/snark_params_n
– https://docs.minaprotocol.com/en onconsensus.ml
– https://eprint.iacr.org/2020/352
Thesourcecodefilesareconsideredthe‘entrypoints’andexecutionflowwastracedthroughouttherepository.
Limitations
Whilethein-scopefunctionalitylieswithinamuchlargersystemcontext,goodcoveragewasachievedoverallin-scope
material. Executionflowwastracedthroughtheclient_sdkJavaScriptcode,butnoothernon-OCamlpaths(e.g. Rust,
GoorC).
KeyFindings
The in-scope code was carefully architected, conservatively implemented, and generally exhibited a high degree of
quality. However,thereviewdiduncoverasetofcommonapplicationflawsinvolving:
• Incomplete Bounds Checking on Random Private Key: The code may not detect randomness sourced from a
broken, intermittently failing or low-entropy random generator, and cannot generate a very small proportion of
legalprivatekeyvalues.
• MissingPrivateKeyValidation:Thecodemayallowmultiplebase58checkencodedprivatekeystomaptothesame
decodedvaluewhichrisksconfusion,downstreammalleabilityand/orinteroperabilityissues.
• MissingBoundsValidationofSignatureValues: Thecodemayallowmultiplesignaturestobesuccessfullyverified
againstthesamemessage,andthusleadtomalleabilityconcerns.
• OutdatedDependenciesandBuildWarnings: Thecodemayallowanattackertoidentifyandutilizevulnerabilities
inoutdateddependenciestoexploittheapplication.
Ascanbeseenabove, themajorityofidentifiedissuesinvolvedinputvalidation. Notethatthedocumentation(and
testing)didnotprominentlyspecifydetailedencodingformatsorconstraints.
StrategicRecommendations
NCC Group recommends addressing the findings from this engagement and prioritizing several aspects of future
developmentasfollows:
• Preciselydefineandprominentlydocumentexactencodingformatsandconstraints.
• Reviewopportunitiesforinputvalidationandimplementaggressiverejectpolicies.
• Developadditionaltestcasestoincludenegativecodepaths,particularlyaroundinputvalidation.
Anongoingprogramofincremental-testingofincremental-implementationwillsupportarobustcodebase.
2 | MinaClientSDK,SignatureLibraryandBaseComponents NCCGroup
Dashboard
TargetMetadata EngagementData
Name MinaRepository Type CodeReview
Type Selectedcomponentsin/aroundclient Method Manualsourcecodeanalysis
SDK
Platforms OcamlwithC/Rustbindings Dates 2021-10-11to2021-10-15
Environment Testing Consultants 2
LevelofEffort 8person-days
Targets
Commita1d868fofhttps://github.com/MinaProtocol/mina
FindingBreakdown
Criticalissues 0
Highissues 0
Mediumissues 2
Lowissues 3
Informationalissues 1
Totalissues 6
CategoryBreakdown
Cryptography 4
DataValidation 1
Patching 1
Key
Critical High Medium Low Informational
3 | MinaClientSDK,SignatureLibraryandBaseComponents NCCGroup
Table of Findings
Foreachfinding,NCCGroupusesacompositeriskscorethattakesintoaccounttheseverityoftherisk,application’s
exposureanduserpopulation,technicaldifficultyofexploitation,andotherfactors. ForanexplanationofNCCGroup’s
riskratingandfindingcategorization,seeAppendixAonpage14.
Title ID Risk
MissingPrivateKeyValidation 002 Medium
MissingBoundsValidationofSignatureValues 004 Medium
IncompleteBoundsCheckingonRandomPrivateKey 001 Low
OutdatedDependenciesandBuildWarnings 003 Low
IssuesInvolvingUnicode,UTF-8/16,ASCII,JavaScript,andOcaml 005 Low
LackofDomainSeparationTagsinRandomOracles 006 Informational
4 | MinaClientSDK,SignatureLibraryandBaseComponents NCCGroup
Finding Details
Finding MissingPrivateKeyValidation
Risk Medium Impact: Medium,Exploitability: Medium
Identifier NCC-E002674-002
Category Cryptography
Location • ThepublicKeyOfPrivateKeymethodonlines22-29ofsrc/app/client_sdk/client_sdk.ml
– Withinsimilarfunctionsthatconsumeabase58checkencodedprivatekeysuchasrawP
ublicKeyOfPrivateKey,validKeypair,signString,signPayment,signStakeDeleg
ationandsignRosettaTransaction
• Theof_base58_check_exnfunctiononlines131-133ofsrc/lib/signature_lib/private_key.ml
• Thedecode_exnfunctiononlines58-81ofsrc/lib/base58_check/base58_check.ml
Impact Without checking a required base58check encoded string length or constraining the han-
dlingleadingzerovalues,multipleencodedprivatekeyswillmaptothesamevalue. Thisis
exacerbatedbyamissingrangecheckonthedecodedvalue. Thismayresultinconfusion,
downstreammalleabilityand/orinteroperabilityissues.
Description Inthecontextofellipticcurves,privatekeysaretypicallyanon-zeroscalarmodulothecurve
order.1 Aninjectivestring:keyencodingisdesiredandthecorrectrangemustbevalidatedto
satisfydownstreamassumptions.
Theminasourcefileclient_sdk.mlprovidesthemethodpublicKeyOfPrivateKeyimple-
mentedonlines22-29whichcalculatesthepublickeythatcorrespondstoasuppliedprivate
key. Earlyintheprocess(line25),thecodeutilizesthePrivate_key.of_base58_check_exn
function. Thisfunctionisimplementedinprivate_key.mlandinturnutilizesBase58_che
ck.decode_exntoperformthecheckeddecodingofabase58string. Thislatterfunctionis
excerptedbelow.
let decode_exn s =
58
let bytes = Bytes.of_string s in
59
let decoded =
60
try B58.decode mina_alphabet bytes |> Bytes.to_string
61
with B58.Invalid_base58_character ->
62
raise (Invalid_base58_character M.description)
63
in
64
let len = String.length decoded in
65
(* input must be at least as long as the version byte and checksum *)
66
if len < version_len + checksum_len then
67
raise (Invalid_base58_check_length M.description) ;
68
let checksum =
69
String.sub decoded
70
~pos:(String.length decoded - checksum_len)
71
~len:checksum_len
72
in
73
let payload =
74
String.sub decoded ~pos:1 ~len:(len - version_len - checksum_len)
75
in
76
if not (String.equal checksum (compute_checksum payload)) then
77
raise (Invalid_base58_checksum M.description) ;
78
if not (Char.equal decoded.[0] version_byte) then
79
raise (Invalid_base58_version_byte (decoded.[0], M.description)) ;
80
payload
81
1https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-bls-signature-04#section-2.3
5 | MinaClientSDK,SignatureLibraryandBaseComponents NCCGroup
Ascanbeseenabove,thecodecorrectlythrowsexceptionsforinvalidcharactersonline63,
astringshorterthan(effectively)5online68,abadchecksumonline78,andabadversion
byteonline80.
However,theexpectedst