X509_Parser.cpp 136 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600
  1. /*
  2. * Copyright (C) 2011-2018 Intel Corporation. All rights reserved.
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions
  6. * are met:
  7. *
  8. * * Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. * * Redistributions in binary form must reproduce the above copyright
  11. * notice, this list of conditions and the following disclaimer in
  12. * the documentation and/or other materials provided with the
  13. * distribution.
  14. * * Neither the name of Intel Corporation nor the names of its
  15. * contributors may be used to endorse or promote products derived
  16. * from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. *
  30. */
  31. #include "X509Cert.h"
  32. #include <cstddef>
  33. #include <assert.h>
  34. #define X509_FOR_PSE_PR 1
  35. #ifdef X509_FOR_PSE_PR
  36. #include "pse_pr_support.h"
  37. // used to eliminate `unused variable' warning
  38. #define UNUSED(val) (void)(val)
  39. #endif
  40. #ifndef X509_FOR_PSE_PR
  41. #include "MeTypes.h"
  42. #include "SessMgrCommonDefs.h"
  43. #include "le2be_macros.h"
  44. #include "CryptoDefs.h"
  45. #include "romapi/romapi_rsa.h"
  46. #include "TimeSrv.h"
  47. #endif // #ifndef X509_FOR_PSE_PR
  48. #ifdef X509_FOR_PSE_PR
  49. STATUS CreateSha1Hash
  50. (
  51. /*in */ SessMgrDataBuffer *pSrcBuffer,
  52. /*out*/ SessMgrDataBuffer *pDigest
  53. )
  54. {
  55. PrepareHashSHA1 hash;
  56. hash.Update(pSrcBuffer->buffer, pSrcBuffer->length);
  57. if (!hash.Finalize((SHA1_HASH*)pDigest->buffer))
  58. return X509_GENERAL_ERROR;
  59. return STATUS_SUCCESS;
  60. };
  61. crypto_status_t EcDsa_VerifySignature
  62. (
  63. /*in */ const UINT8* pMsg,
  64. /*in */ uint32_t nMsg,
  65. /*in */ const EcDsaPubKey* pPublicKey,
  66. /*in */ const EcDsaSig* pSignature,
  67. /*out*/ bool* fValid
  68. )
  69. {
  70. crypto_status_t status = CRYPTO_STATUS_INTERNAL_ERROR;
  71. sgx_ecc_state_handle_t ecc_handle = NULL;
  72. *fValid = false;
  73. do
  74. {
  75. if (SGX_SUCCESS != sgx_ecc256_open_context(&ecc_handle)) break;
  76. uint8_t result;
  77. if ((SGX_SUCCESS == sgx_ecdsa_verify(pMsg, nMsg,
  78. (sgx_ec256_public_t *)pPublicKey,
  79. (sgx_ec256_signature_t *)pSignature,
  80. &result,
  81. ecc_handle)) && (result == SGX_EC_VALID ))
  82. *fValid = true;
  83. status = CRYPTO_STATUS_SUCCESS;
  84. } while (0);
  85. if (ecc_handle != NULL) sgx_ecc256_close_context(ecc_handle);
  86. return status;
  87. }
  88. #endif
  89. //*******************************************************************************************************************************************
  90. //*******************************************************************************************************************************************
  91. //*******************************************************************************************************************************************
  92. static STATUS VerifyBasicCertificateAttributes(const Uint8* certificateDerEncoded, const Uint8* workBuffer, const SessMgrCertificateFields* certificateFields,
  93. const ISSUER_INFO *IssuerInfo, CertificateType CertType, CertificateLevel CertLevel , BOOL UseFacsimileEpid);
  94. #ifndef X509_FOR_PSE_PR
  95. static STATUS VerifyOcspRevocationStatus(SessMgrCertificateFields* certificateFields,
  96. UINT8 NumberofSingleResponses, OCSP_CERT_STATUS_TABLE * OcspCertStatusTable, ISSUER_INFO *IssuerInfo);
  97. #endif
  98. static STATUS VerifySignature(const ISSUER_INFO *IssuerInfo, const SessMgrDataBuffer *MsgBuffer, const SessMgrDataBuffer *SignBuffer, BOOL UseFacsimileEpid);
  99. #ifndef X509_FOR_PSE_PR
  100. static void GetPublicKeyDataBuf(SessMgrDataBuffer *PubKeyBuffer, ISSUER_INFO *IssuerInfo);
  101. static STATUS VerifyOcspCachedResponseValidity(SessMgrOcspResponseFields *OcspResponseFields);
  102. static STATUS VerifyValidity(SessMgrDateTime notValidBeforeTime, SessMgrDateTime NotValidAfter);
  103. static STATUS ConvertTimeToNtp(SessMgrDateTime Time, NTP_TIMESTAMP *NtpTime);
  104. static STATUS StoreTrustedTime(SessMgrDateTime TrustedTime);
  105. #endif
  106. #ifndef X509_FOR_PSE_PR
  107. static STATUS VerifyOcspResponseAttributes(Uint8* OcspRespBuffer, SessMgrOcspResponseFields *ocspResponseFields, ISSUER_INFO* OcspCertRootPublicKey,
  108. SessMgrDataBuffer Nonce, OCSP_REQ_TYPE OcspReqType, BOOL UseFacsimileEpid);
  109. static BOOL VerifySha1Hash(SessMgrDataBuffer *HashData, UINT8 *Expectedhash, UINT32 ExpectedHashLength);
  110. #endif
  111. static STATUS sessMgrParseDerCert(IN X509_PROTOCOL* X509Protocol, IN Uint8* certificateDerEncoded,
  112. IN Uint8* pCertEnd, IN Uint8* workBuffer, IN UINT32 workBufferSize,
  113. OUT SessMgrCertificateFields* certificateFields, IN ISSUER_INFO *IssuerInfo,
  114. IN BOOL UseFacsimileEpid);
  115. #ifndef X509_FOR_PSE_PR
  116. static STATUS sessMgrParseOcspResponse(IN X509_PROTOCOL* X509Protocol, IN Uint8* OcspResponse,
  117. IN Uint8* OcspResponseEnd, IN Uint8* workBuffer, IN UINT32 workBufferSize,
  118. OUT SessMgrOcspResponseFields* OcspResponseFields);
  119. static STATUS ParseBoolean(UINT8 **ppCurrent, UINT8 *pEnd, BOOL* Value, BOOL optional);
  120. #endif
  121. static STATUS ParseInteger(UINT8 **ppCurrent, UINT8 *pEnd, SessMgrDataBuffer* DataBuf, BOOL isOptional, BOOL MustBePositive, UINT32 *PaddingLen);
  122. #ifndef X509_FOR_PSE_PR
  123. static STATUS ParseOcspExtensions(UINT8 **ppCurrent, UINT8 *pEnd, SessMgrOcspResponseFields* OcspResponseFields);
  124. static STATUS ParseCertExtensions(UINT8 **ppCurrent, UINT8 *pEnd, SessMgrCertificateFields* certificateFields);
  125. static STATUS ParseCertificatePolicy(UINT8 **ppCurrent, UINT8 *pEnd, SessMgrDataBuffer *CertificatePolicy);
  126. #endif
  127. static STATUS ParseSubjectPublicKeyInfo(UINT8 **ppCurrent, UINT8 *pEnd, UINT8 **pworkbuffer, SessMgrCertificateFields* certificateFields);
  128. static STATUS ParseRsaPublicKey(UINT8 **ppCurrent, UINT8 *pEnd, SessMgrRsaKey * RsaKey);
  129. static STATUS ParseEpidPublicKey(UINT8 **ppCurrent, UINT8 *pEnd, SessMgrEpidGroupPublicKey * EpidKey);
  130. static STATUS ParseEcdsaPublicKey(UINT8 **ppCurrent, UINT8 *pEnd, SessMgrEcdsaPublicKey * EcDsaKey, SessMgrEllipticCurveParameter params);
  131. static STATUS ParseOID(UINT8 **ppCurrent, UINT8 *pEnd, UINT32 *EnumVal, const UINT8 *OidList, UINT32 Max_Entries, UINT32 EntrySize );
  132. static STATUS ParseSignatureValue(UINT8 **ppCurrent, UINT8 *pEnd, UINT8 **pworkbuffer, UINT32 WorkBufferSize, SessMgrDataBuffer *SignatureValueBuf, UINT8 SignatureAlgoId);
  133. static STATUS ParseAlgoIdentifier(UINT8 **ppCurrent, UINT8 *pEnd, UINT32* algoId, AlgorithmTypes Type, SessMgrEllipticCurveParameter *params);
  134. static STATUS ParseAlgoParameters(UINT8 **ppCurrent, UINT8 *pEnd, UINT32* param);
  135. static STATUS ParseName(UINT8 **ppCurrent, UINT8 *pEnd, SessMgrX509Name* Name);
  136. static STATUS ParseTime(UINT8 **ppCurrent, UINT8 *pEnd, SessMgrDateTime* DateTime);
  137. static STATUS DecodeLength(UINT8* Buffer, UINT8* BufferEnd, UINT32* Length, UINT8* EncodingBytes);
  138. static void SwapEndian(UINT8* ptr, int length);
  139. static STATUS swapendian_memcpy(UINT8 *DestPtr, UINT32 DestLen, UINT8 *SrcPtr, UINT32 SrcLen);
  140. static STATUS ParseIdAndLength(UINT8 **ppCurrent, UINT8 *pEnd, UINT8 ExpectedId, UINT32* Length, UINT8* EncodingBytes, BOOL Optional);
  141. #ifndef X509_FOR_PSE_PR
  142. static int Pow(int num, int exp);
  143. #endif
  144. /* This list should always be synced up with the SessMgrAlgorithmOid enum */
  145. const UINT8 HardCodedSignatureAlgorithmOid[][9] =
  146. {
  147. {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x02},
  148. {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x03},
  149. {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x04},
  150. {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x05},
  151. {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x07},
  152. {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x08},
  153. {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x09},
  154. {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0a},
  155. {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0b},
  156. {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0c},
  157. {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0d},
  158. {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0e},
  159. {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x01},
  160. {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x02},
  161. };
  162. const UINT8 HardCodedPublicKeyAlgorithmOid[][10] =
  163. {
  164. {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01},
  165. {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01},
  166. {0x2A, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x09, 0x04, 0x01},
  167. {0x2A, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x09, 0x04, 0x02},
  168. {0x2A, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x09, 0x04, 0x03},
  169. };
  170. const UINT8 HashAlgorithmOid[][9] =
  171. {
  172. {0x2B, 0x0E, 0x03, 0x02, 0x1A},
  173. {0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01},
  174. };
  175. /* This list should always be synced up with the NameStruct enum */
  176. const UINT8 HardCodedNameOid[][10] =
  177. {
  178. {0x55, 0x04, 0x03},
  179. {0x55, 0x04, 0x0a},
  180. {0x55, 0x04, 0x06},
  181. {0x55, 0x04, 0x07},
  182. {0x55, 0x04, 0x08},
  183. {0x55, 0x04, 0x0b},
  184. {0x09, 0x92, 0x26, 0x89, 0x93, 0xF2, 0x2C, 0x64, 0x01, 0x01},
  185. };
  186. #ifndef X509_FOR_PSE_PR
  187. const UINT8 CertExtensionOid[][9] =
  188. {
  189. {0x55, 0x1d, 0x23},
  190. {0x55, 0x1d, 0x0E},
  191. {0x55, 0x1d, 0x0F},
  192. {0x55, 0x1d, 0x13},
  193. {0x55, 0x1d, 0x20},
  194. {0x55, 0x1d, 0x25},
  195. {0x2A, 0x86, 0x48, 0x86, 0xF8, 0x4D, 0x01, 0x09, 0x02},
  196. };
  197. const UINT8 OcspExtensionOid[][9] =
  198. {
  199. {0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x30, 0x01, 0x02}, // 1.3.6.1.5.5.7.48.1.2
  200. };
  201. #endif
  202. const UINT8 EllipticCurveOid[][8] =
  203. {
  204. {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07}
  205. };
  206. #ifndef X509_FOR_PSE_PR
  207. const UINT8 CertificatePolicyOid[][9] =
  208. {
  209. {0x2A, 0x86, 0x48, 0x86, 0xF8, 0x4d, 0x01, 0x09, 0x01}
  210. };
  211. const UINT8 CertificatePolicyQualifierIdOid[][8] =
  212. {
  213. {0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x02, 0x01}
  214. };
  215. const UINT8 OcspResponseTypeOid[][9] =
  216. {
  217. {0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x30, 0x01, 0x01}
  218. };
  219. const UINT8 ExtendedKeyUsageOcspSignOid[][8] =
  220. {
  221. 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x09
  222. };
  223. #endif
  224. #ifndef X509_FOR_PSE_PR
  225. /*
  226. ParseOcspResponseChain - Decodes a DER encoded X.509 OCSP response and makes a list of the serial numbers and hashes from the OCSP response.
  227. @param OcspRespBuffer - If not NULL, contains the OCSP response. OCSP response contains a list of certificates with their current status (good/revoked)
  228. @param OcspRespBufferLength - Total Length of the OCSP response
  229. @param OcspCertRootPublicKey - Public key used to sign the first certificate in the chain. This is the root of trust. If NULL, Intel public key is used.
  230. @param OcspCertStatusTable - Table containing interesting fields in the OCSP response which will be used to compare against the verifier certificate.
  231. @param NumberOfSingleResponses - Number of single responses that the OCSP response has returned to us.
  232. @param Nonce - Contains the Nonce that was sent. If nonce Exists, the OCSP response should have a nonce extension that contains the same values.
  233. @retval X509_STATUS_SUCCESS - The operation completed successfully.
  234. @retval STATUS_INVALID_VERSION
  235. @retval STATUS_UNSUPPORTED_ALGORITHM
  236. @retval STATUS_ENCODING_ERROR
  237. @retval STATUS_INVALID_ARGS
  238. @retval STATUS_UNSUPPORTED_CRITICAL_EXTENSION
  239. @retval STATUS_UNSUPPORTED_TYPE
  240. */
  241. STATUS ParseOcspResponseChain( UINT8* OcspRespBuffer,
  242. UINT32 OcspRespBufferLength,
  243. UINT8* workBuffer,
  244. UINT32 workBufferSize,
  245. ISSUER_INFO* OcspCertRootPublicKey,
  246. OCSP_CERT_STATUS_TABLE *OcspCertStatusTable,
  247. UINT8* NumberOfSingleResponses,
  248. SessMgrDataBuffer Nonce,
  249. OCSP_REQ_TYPE OcspReqType,
  250. BOOL UseFacsimileEpid)
  251. {
  252. STATUS Status;
  253. UINT32 Length = 0;
  254. UINT32 OcspResponseLength = 0;
  255. UINT8 TableIndex = 0;
  256. SessMgrOcspSingleResponse *SingleResponse;
  257. int i;
  258. SessMgrOcspResponseFields OcspResponseFields;
  259. UINT8 EncodingBytes; // number of bytes used for encoding into ASN DER format
  260. UINT8 *current_ptr = OcspRespBuffer;
  261. UINT8 *end_of_ocsp_response_chain = OcspRespBuffer + OcspRespBufferLength;
  262. // Workaround for Windows OCSP responder shortcoming. Loop through OCSP response
  263. // We will loop through each of the OCSP responses, verify the OCSP responder certificate and
  264. while(current_ptr < end_of_ocsp_response_chain){
  265. Status = DecodeLength(current_ptr + 1, end_of_ocsp_response_chain, &Length, &EncodingBytes);
  266. if(Status != X509_STATUS_SUCCESS){
  267. DBG_ASSERT(0);
  268. return X509_STATUS_ENCODING_ERROR;
  269. }
  270. OcspResponseLength = Length + EncodingBytes + 1;
  271. memset(workBuffer, 0, workBufferSize);
  272. memset(&OcspResponseFields, 0, sizeof(OcspResponseFields));
  273. Status = sessMgrParseOcspResponse( NULL, current_ptr, current_ptr + OcspResponseLength, workBuffer, workBufferSize, &OcspResponseFields);
  274. if(Status != X509_STATUS_SUCCESS){
  275. DBG_ASSERT(0);
  276. return X509_STATUS_ENCODING_ERROR;
  277. }
  278. Status = VerifyOcspResponseAttributes(NULL, &OcspResponseFields, NULL, Nonce, OcspReqType, UseFacsimileEpid);
  279. if(Status != X509_STATUS_SUCCESS){
  280. DBG_ASSERT(0);
  281. return X509_STATUS_OCSP_VERIFICATION_FAILED;
  282. }
  283. // copy the interesting data
  284. for(i=0;i<OcspResponseFields.numberOfSingleReponses;i++){
  285. SingleResponse = (SessMgrOcspSingleResponse *)(OcspResponseFields.allResponses) + i;
  286. Status = VerifyValidity(SingleResponse->thisUpdate, SingleResponse->nextUpdate);
  287. if(Status != X509_STATUS_SUCCESS){
  288. DBG_ASSERT(0);
  289. return X509_STATUS_OCSP_VERIFICATION_FAILED;
  290. }
  291. if(SingleResponse->ocspCertificateStatus == good){
  292. if(TableIndex == MAX_CERT_CHAIN_LENGTH){
  293. DBG_ASSERT(0);
  294. return X509_STATUS_OCSP_VERIFICATION_FAILED;
  295. }
  296. SESSMGR_MEMCPY_S(OcspCertStatusTable[TableIndex].serialNumber, sizeof(OcspCertStatusTable[TableIndex].serialNumber),
  297. SingleResponse->serialNumber.buffer, SingleResponse->serialNumber.length);
  298. DBG_ASSERT(SingleResponse->serialNumber.length <= 255);
  299. OcspCertStatusTable[TableIndex].SerialNumberSize = (UINT8)SingleResponse->serialNumber.length;
  300. SESSMGR_MEMCPY_S(OcspCertStatusTable[TableIndex].issuerKeyHash, sizeof(OcspCertStatusTable[TableIndex].issuerKeyHash),
  301. SingleResponse->issuerKeyHash.buffer, SingleResponse->issuerKeyHash.length);
  302. DBG_ASSERT(SingleResponse->issuerKeyHash.length <= 255);
  303. OcspCertStatusTable[TableIndex].issuerKeyHashSize = (UINT8)SingleResponse->issuerKeyHash.length;
  304. SESSMGR_MEMCPY_S(OcspCertStatusTable[TableIndex].issuerNameHash, sizeof(OcspCertStatusTable[TableIndex].issuerNameHash),
  305. SingleResponse->issuerNameHash.buffer, SingleResponse->issuerNameHash.length);
  306. DBG_ASSERT(SingleResponse->issuerNameHash.length <= 255);
  307. OcspCertStatusTable[TableIndex].issuerNameHashSize = (UINT8)SingleResponse->issuerNameHash.length;
  308. OcspCertStatusTable[TableIndex].HashAlgo = SingleResponse->issuerIdentifierHashType;
  309. TableIndex++;
  310. }
  311. }
  312. current_ptr += OcspResponseLength;
  313. }
  314. if (current_ptr != end_of_ocsp_response_chain){
  315. DBG_ASSERT(0);
  316. return X509_STATUS_INVALID_ARGS;
  317. }
  318. *NumberOfSingleResponses = TableIndex;
  319. return STATUS_SUCCESS;
  320. }
  321. #endif
  322. /*
  323. ParseCertificateChain - This function can
  324. - parse a certificate chain and return the CertificateFields of all the last certificate (usually the certificate of interest)
  325. - optionally take in root public key that was used to sign first certificate in the chain. If NULL, Intel public Key is used.
  326. - optionally take in ocspRespBuffer. If ocspRespBuffer is not NULL, this function will parse the ocsp response cert, make a list of
  327. certificates authenticated by OCSP responder, and use this list to verify if each certificate in the chain has been authenticated.
  328. - optionally takes in the root public key used to sign the first certifcate in the OCSP responders certificate.
  329. @param pCertChain - Pointer to the certificate chain. The first certificate in the chain is assumed to be Intel signed if root public key (arg 4) is NULL
  330. @param CertChainLength - Length of the certificate chain
  331. @param certificateFields - Data structure containing parsed output of the last certificate in the chain (usually the certificate of interest))
  332. @param RootPublicKey - Public key used to sign the first certificate in the chain. This is the root of trust. If NULL, Intel public key is used.
  333. @param NumberOfSingleResponses - Number of single responses that the OCSP response has returned to us.
  334. @param OcspCertStatusTable - Table containing interesting fields in the OCSP response which will be used to compare against the verifier certificate.
  335. @param VerifierCert - Contains pointer and length of the VerifierCertificate. If non NULL, the final certificate in the chain is populated with this Data.
  336. @param CertType - Indicates what type of certificate we are processing.Some checks are specific to certain types of certs.
  337. @retval X509_STATUS_SUCCESS - The operation completed successfully.
  338. */
  339. /* Input:
  340. pointer to buffer containing a chain of certificates
  341. Total Length
  342. Assumes the first certificate in the chain is signed by Intel
  343. */
  344. STATUS ParseCertificateChain(UINT8 *pCertChain,
  345. UINT32 CertChainLength,
  346. SessMgrCertificateFields *certificateFields,
  347. UINT8 *CertWorkBuffer,
  348. UINT32 CertWorkBufferLength,
  349. ISSUER_INFO *RootPublicKey,
  350. UINT8 NumberOfSingleResponses,
  351. OCSP_CERT_STATUS_TABLE *OcspCertStatusTable,
  352. CertificateType CertType,
  353. BOOL UseFacsimileEpid
  354. )
  355. {
  356. STATUS Status;
  357. UINT8 CertCount = 0;
  358. SessMgrEcdsaPublicKey ecdsa_pub_key;
  359. // This is the temp buffer used to store the issuer signing key to verify the next certificate in the chain.
  360. // This size of this buffer should be equal to the Max possible key size
  361. UINT8 TempSignKeyBuffer[200];
  362. SessMgrDataBuffer TempDataBuffer;
  363. UINT8 *pCert;
  364. UINT8 *pCertChainEnd;
  365. UINT32 CertLength = 0;
  366. UINT8 EncodingBytes; // number of bytes used for encoding into ASN DER format
  367. int MaxChainLengthAllowed = 0xFF; // This is to enforce the PathLen Basic Constraints.
  368. UINT8 HashOut[SHA1_HASH_LEN] = {0};
  369. UINT8 *KeyBufPtr;
  370. CertificateLevel CertLevel;
  371. ISSUER_INFO IssuerInfo;
  372. #ifdef X509_FOR_PSE_PR
  373. UNUSED(NumberOfSingleResponses);
  374. #endif
  375. if (pCertChain == NULL ||
  376. pCertChain + CertChainLength <= pCertChain ||
  377. CertWorkBuffer == NULL ||
  378. CertWorkBuffer + CertWorkBufferLength <= CertWorkBuffer)
  379. {
  380. return X509_STATUS_INVALID_ARGS;
  381. }
  382. memset(&IssuerInfo, 0 , sizeof(ISSUER_INFO));
  383. pCert = pCertChain;
  384. pCertChainEnd = pCertChain + CertChainLength;
  385. CertLevel = root;
  386. if(!RootPublicKey){
  387. // always use debug keys except for EPID group certs
  388. #ifdef X509_FOR_PSE_PR
  389. ecdsa_pub_key.px = SerializedPublicKey;
  390. ecdsa_pub_key.py = SerializedPublicKey + 32;
  391. #else
  392. if(gSessmgrCtx.FuseGidZero == FALSE){
  393. ecdsa_pub_key.px = INTEL_ECDSA_PUBKEY_PROD_BE;
  394. ecdsa_pub_key.py = INTEL_ECDSA_PUBKEY_PROD_BE + 32;
  395. }else{
  396. ecdsa_pub_key.px = INTEL_ECDSA_PUBKEY_DBG_BE;
  397. ecdsa_pub_key.py = INTEL_ECDSA_PUBKEY_DBG_BE + 32;
  398. }
  399. #endif
  400. ecdsa_pub_key.eccParameter = curvePrime256v1;
  401. IssuerInfo.buffer = (UINT8 *)&ecdsa_pub_key;
  402. IssuerInfo.length = sizeof(ecdsa_pub_key);
  403. IssuerInfo.AlgoType = X509_ecdsa_with_SHA256;
  404. }else{
  405. // Not allowing user to pass their own root key.
  406. DBG_ASSERT(0);
  407. return X509_STATUS_INVALID_ARGS;
  408. // memcpy(&IssuerInfo, RootPublicKey, sizeof(IssuerInfo));
  409. }
  410. // Set this up for the hash.
  411. IssuerInfo.EncodedPublicKeyHashBuffer.buffer = HashOut;
  412. IssuerInfo.EncodedPublicKeyHashBuffer.length = SHA1_HASH_LEN;
  413. // For root key, populate the ISSUER_INFO data structure. Refer to data strucutre definition for more details.
  414. // use the temp sign key buffer for this purpose.
  415. memset(TempSignKeyBuffer, 0 , sizeof(TempSignKeyBuffer));
  416. TempDataBuffer.buffer = TempSignKeyBuffer;
  417. KeyBufPtr = TempSignKeyBuffer;
  418. *KeyBufPtr = 0x04;
  419. KeyBufPtr++;
  420. SESSMGR_MEMCPY_S(KeyBufPtr, sizeof(TempSignKeyBuffer) - 1, ecdsa_pub_key.px, ECDSA_KEY_ELEMENT_SIZE);
  421. KeyBufPtr += ECDSA_KEY_ELEMENT_SIZE;
  422. SESSMGR_MEMCPY_S(KeyBufPtr, sizeof(TempSignKeyBuffer) - 1 - ECDSA_KEY_ELEMENT_SIZE, ecdsa_pub_key.py, ECDSA_KEY_ELEMENT_SIZE);
  423. TempDataBuffer.length = ECDSA_KEY_SIZE + 1; // +1 to reflect the addition of 0x04 in the beginning of the buffer.
  424. Status = CryptoCreateHash(CRYPTO_HASH_TYPE_SHA1,
  425. &TempDataBuffer,
  426. &IssuerInfo.EncodedPublicKeyHashBuffer,
  427. NULL,
  428. NULL,
  429. SINGLE_BLOCK);
  430. if(Status != STATUS_SUCCESS){
  431. DBG_ASSERT(0);
  432. return X509_STATUS_INTERNAL_ERROR;
  433. }
  434. while(pCert < pCertChainEnd)
  435. {
  436. /* certificate always starts with a sequence followed by length at offset 1. */
  437. CHECK_ID(*pCert, DER_ENCODING_SEQUENCE_ID);
  438. if ((pCert + 1) == pCertChainEnd) {
  439. break;
  440. }
  441. Status = DecodeLength(pCert + 1, pCertChainEnd, &CertLength, &EncodingBytes);
  442. if(Status != X509_STATUS_SUCCESS){
  443. DBG_ASSERT(0);
  444. return Status;
  445. }
  446. CertLength = CertLength + EncodingBytes + 1;
  447. if( (pCert + CertLength) >= pCertChainEnd){
  448. // if this is the last certificate in the chain, it is the leaf
  449. CertLevel = leaf;
  450. }
  451. // Check Basic Constraints Compliance
  452. if(MaxChainLengthAllowed <= 0 && CertLevel != leaf){
  453. // We have one more CA which is violating the basic constraints set by somebody. return error
  454. DBG_ASSERT(0);
  455. return X509_STATUS_BASIC_CONSTRAINTS_VIOLATION;
  456. }
  457. memset(certificateFields, 0, sizeof(SessMgrCertificateFields));
  458. memset(CertWorkBuffer, 0, CertWorkBufferLength);
  459. certificateFields->productType = invalidProductType;
  460. Status = sessMgrParseDerCert(NULL, pCert, pCert + CertLength, CertWorkBuffer, CertWorkBufferLength, certificateFields, &IssuerInfo, UseFacsimileEpid);
  461. if(Status != X509_STATUS_SUCCESS){
  462. DBG_ASSERT(0);
  463. return Status;
  464. }
  465. // First Certificate is always intel signed
  466. Status = VerifyBasicCertificateAttributes(pCert, CertWorkBuffer, certificateFields, &IssuerInfo, CertType, CertLevel, UseFacsimileEpid);
  467. if(Status != X509_STATUS_SUCCESS){
  468. DBG_ASSERT(0);
  469. return Status;
  470. }
  471. // Verifiation is required if OCSP table exists (even if empty), make sure the certificate has not been revoked
  472. if(OcspCertStatusTable){
  473. BOOL IntelSelfSignedRoot = false;
  474. #ifdef X509_FOR_PSE_PR
  475. if(CertLevel == root && memcmp(certificateFields->EncodedSubjectPublicKey.buffer+1, SerializedPublicKey, sizeof(SerializedPublicKey)) == 0)
  476. IntelSelfSignedRoot = true;
  477. #else
  478. if(CertLevel == root && memcmp(certificateFields->EncodedSubjectPublicKey.buffer+1, INTEL_ECDSA_PUBKEY_PROD_BE, sizeof(INTEL_ECDSA_PUBKEY_PROD_BE)) == 0)
  479. IntelSelfSignedRoot = true;
  480. else if(gSessmgrCtx.FuseGidZero && CertLevel == root && memcmp(certificateFields->EncodedSubjectPublicKey.buffer+1, INTEL_ECDSA_PUBKEY_DBG_BE, sizeof(INTEL_ECDSA_PUBKEY_DBG_BE)) == 0)
  481. IntelSelfSignedRoot = true;
  482. #endif
  483. // Skip revocation status check for Intel self-signed root certificate
  484. if(!IntelSelfSignedRoot) {
  485. #ifndef X509_FOR_PSE_PR
  486. Status = VerifyOcspRevocationStatus(certificateFields, NumberOfSingleResponses, OcspCertStatusTable, &IssuerInfo);
  487. if(Status != X509_STATUS_SUCCESS){
  488. DBG_ASSERT(0);
  489. return X509_STATUS_OCSP_FAILURE;
  490. }
  491. #endif
  492. }
  493. }
  494. // Certificate has been verified. Everything is good.
  495. // if this is not the leaf, store the public key and algorithm type to use in next certificate signature verification
  496. if(CertLevel != leaf){
  497. memset(TempSignKeyBuffer, 0, sizeof(TempSignKeyBuffer));
  498. SESSMGR_MEMCPY_S(TempSignKeyBuffer, sizeof(TempSignKeyBuffer), certificateFields->subjectPublicKey.buffer, certificateFields->subjectPublicKey.length);
  499. // Clear the issuer info structure.
  500. memset(&IssuerInfo, 0 , sizeof(ISSUER_INFO));
  501. // This key is the issuer key for the next certificate. Populate the IssuerInfo
  502. IssuerInfo.buffer = TempSignKeyBuffer;
  503. IssuerInfo.length = certificateFields->subjectPublicKey.length;
  504. IssuerInfo.AlgoType = certificateFields->algorithmIdentifierForSignature;
  505. // Set this up for the hash.
  506. IssuerInfo.EncodedPublicKeyHashBuffer.buffer = HashOut;
  507. IssuerInfo.EncodedPublicKeyHashBuffer.length = SHA1_HASH_LEN;
  508. Status = CryptoCreateHash(CRYPTO_HASH_TYPE_SHA1,
  509. &certificateFields->EncodedSubjectPublicKey,
  510. &IssuerInfo.EncodedPublicKeyHashBuffer,
  511. NULL,
  512. NULL,
  513. SINGLE_BLOCK);
  514. if(Status != STATUS_SUCCESS){
  515. DBG_ASSERT(0);
  516. return X509_STATUS_INTERNAL_ERROR;
  517. }
  518. // We might have zero or more intermediate certificates
  519. CertLevel = intermediate;
  520. // Record and Verify Basic Path Len Constraints. Refer to RFC for details on Basic constrains path len extensions.
  521. // If PathLen constraint set by this CA is more constrained than the one enforced by the previous CA, update MaxChainLength
  522. if(certificateFields->basicConstraint.isBasicConstraintPresent && certificateFields->basicConstraint.pathLenConstraint < (UINT32)MaxChainLengthAllowed)
  523. MaxChainLengthAllowed = certificateFields->basicConstraint.pathLenConstraint;
  524. else
  525. MaxChainLengthAllowed--;
  526. IssuerInfo.CommonNameBuf.buffer = (UINT8 *)certificateFields->subject.commonName;
  527. IssuerInfo.CommonNameBuf.length = certificateFields->subject.commonNameSize;
  528. IssuerInfo.productType = certificateFields->productType;
  529. }
  530. pCert += CertLength;
  531. CertCount++;
  532. }
  533. if (pCert != pCertChainEnd) {
  534. DBG_ASSERT(0);
  535. return X509_STATUS_INVALID_ARGS;
  536. }
  537. return X509_STATUS_SUCCESS;
  538. }
  539. #ifndef X509_FOR_PSE_PR
  540. /*
  541. This function compares the serial number of the certificate with the list of certificates that the OCSP responder sent us.
  542. If found, Make sure the status of the certificate is not revoked.
  543. */
  544. STATUS VerifyOcspRevocationStatus(SessMgrCertificateFields* certificateFields,
  545. UINT8 NumberofSingleResponses,
  546. OCSP_CERT_STATUS_TABLE* OcspCertStatusTable,
  547. ISSUER_INFO *IssuerInfo)
  548. {
  549. UINT32 i;
  550. STATUS Status;
  551. STATUS VerificationStatus = X509_STATUS_OCSP_VERIFICATION_FAILED;
  552. SessMgrDataBuffer HashBuf;
  553. SessMgrDataBuffer IssuerNameBuf;
  554. UINT8 HashOut[SHA1_HASH_LEN] = {0};
  555. HashBuf.buffer = HashOut;
  556. HashBuf.length = SHA1_HASH_LEN;
  557. IssuerNameBuf.buffer = (UINT8 *)certificateFields->issuer.DistinguishedName;
  558. IssuerNameBuf.length = certificateFields->issuer.DistinguishedNameSize;
  559. for (i=0;i<NumberofSingleResponses;i++){
  560. // Check serial number
  561. if(certificateFields->serialNumber.length != OcspCertStatusTable[i].SerialNumberSize ||
  562. memcmp(certificateFields->serialNumber.buffer, OcspCertStatusTable[i].serialNumber, OcspCertStatusTable[i].SerialNumberSize) != 0) {
  563. continue;
  564. }
  565. // Check hash key
  566. if(IssuerInfo->EncodedPublicKeyHashBuffer.length != OcspCertStatusTable[i].issuerKeyHashSize ||
  567. memcmp(IssuerInfo->EncodedPublicKeyHashBuffer.buffer, OcspCertStatusTable[i].issuerKeyHash, OcspCertStatusTable[i].issuerKeyHashSize) != 0){
  568. continue;
  569. }
  570. memset(HashBuf.buffer, 0, SHA1_HASH_LEN);
  571. Status = CryptoCreateHash(CRYPTO_HASH_TYPE_SHA1,
  572. &IssuerNameBuf,
  573. &HashBuf,
  574. NULL,
  575. NULL,
  576. SINGLE_BLOCK);
  577. if(Status != STATUS_SUCCESS){
  578. DBG_ASSERT(0);
  579. return X509_STATUS_INTERNAL_ERROR;
  580. }
  581. // Check issuer name
  582. if(SHA1_HASH_LEN != OcspCertStatusTable[i].issuerNameHashSize ||
  583. memcmp(HashBuf.buffer, OcspCertStatusTable[i].issuerNameHash, OcspCertStatusTable[i].issuerNameHashSize) != 0){
  584. continue;
  585. }
  586. // The certificate has been found in the OCSP response, break and return success
  587. VerificationStatus = X509_STATUS_SUCCESS;
  588. break;
  589. }
  590. DBG_ASSERT(VerificationStatus == X509_STATUS_SUCCESS);
  591. return VerificationStatus;
  592. }
  593. #endif
  594. #ifndef X509_FOR_PSE_PR
  595. /*
  596. This function will accept the algorithm and the keys as a void pointer and will verify the keys accordingly.
  597. */
  598. #define SESSMGR_RSA_WORK_BUFFER_SIZE (ROM_RSA_WIN_EXP_1_BUFFER_SIZE + 2*(RSA_KEY_SIZE_2048_BYTES))
  599. UINT8 RsaWorkBuffer[SESSMGR_RSA_WORK_BUFFER_SIZE];
  600. #endif // #ifndef X509_FOR_PSE_PR
  601. STATUS VerifySignature(const ISSUER_INFO *IssuerInfo, const SessMgrDataBuffer *MsgBuffer, const SessMgrDataBuffer *SignBuffer, BOOL UseFacsimileEpid)
  602. {
  603. #ifdef X509_FOR_PSE_PR
  604. BOOL VerifRes = FALSE;
  605. #else
  606. BOOL VerifRes = FALSE;
  607. SessMgrDataBuffer LocalSignBuffer;
  608. SessMgrDataBuffer LocalMsgBuffer;
  609. ROM_RSA_DATA_BUFFER workBuffer;
  610. ROM_RSA_VERIFY_PARAMS RsaVerifyParams;
  611. UINT8 RsaEBuffer[RSA_E_SIZE] = {0, 0 ,0 ,0};
  612. UINT8 RsaNBuffer[RSA_KEY_SIZE_2048_BYTES] = {0};
  613. #endif
  614. SessMgrEcdsaPublicKey *PublicKeyFromCert;
  615. PseEcdsaPublicKey EcdsaKey;
  616. G3Point* g3point;
  617. #ifndef X509_FOR_PSE_PR
  618. UINT32 hashSize = 0;
  619. BOOL IsSignatureValid = FALSE;
  620. SessMgrRsaKey *RsaKeyFromCert;
  621. #endif
  622. STATUS Status = X509_INVALID_SIGNATURE;
  623. #ifdef X509_FOR_PSE_PR
  624. UNUSED(UseFacsimileEpid);
  625. #endif
  626. do{
  627. switch(IssuerInfo->AlgoType){
  628. case X509_ecdsa_with_SHA1:
  629. Status = X509_STATUS_UNSUPPORTED_ALGORITHM;
  630. break;
  631. case X509_ecdsa_with_SHA256:
  632. PublicKeyFromCert = (SessMgrEcdsaPublicKey *)(IssuerInfo->buffer);
  633. SESSMGR_MEMCPY_S(EcdsaKey.px, sizeof(EcdsaKey.px), PublicKeyFromCert->px, 32);
  634. SESSMGR_MEMCPY_S(EcdsaKey.py, sizeof(EcdsaKey.py), PublicKeyFromCert->py, 32);
  635. // Allocate DWORD aligned local buffers for Signature and Msg.
  636. // Swap Key and signature Convert Intel signature of the parameters certificate prior verifying it
  637. g3point = reinterpret_cast<G3Point*>(EcdsaKey.px);
  638. SwapEndian_32B(g3point->x);
  639. SwapEndian_32B(g3point->y);
  640. SwapEndian_32B(reinterpret_cast<G3Point*>(SignBuffer->buffer)->x);
  641. SwapEndian_32B(reinterpret_cast<G3Point*>(SignBuffer->buffer)->y);
  642. #ifndef X509_FOR_PSE_PR
  643. void* pCtx = NULL;
  644. pCtx = UseFacsimileEpid ? gSessmgrCtx.KeysCtxFacsimile : gSessmgrCtx.KeysCtx;
  645. #endif
  646. Status = SafeIdSigmaEcDsaVerifyPriv( pCtx,
  647. MsgBuffer->buffer,
  648. MsgBuffer->length,
  649. (unsigned char *)&EcdsaKey,
  650. (unsigned char *)SignBuffer->buffer,
  651. CRYPTO_HASH_TYPE_SHA256,
  652. 0,
  653. 32,
  654. &VerifRes);
  655. if(Status != STATUS_SUCCESS){
  656. DBG_ASSERT(0);
  657. Status = SESSMGR_STATUS_INTERNAL_ERROR;
  658. break;
  659. }
  660. #ifndef X509_FOR_PSE_PR
  661. // Testing workaround: always allow production signed on SSKU part
  662. if(VerifRes == FALSE) {
  663. if(gSessmgrCtx.FuseGidZero)
  664. {
  665. Status = SafeIdSigmaEcDsaVerifyPriv(UseFacsimileEpid ? gSessmgrCtx.KeysCtxFacsimile : gSessmgrCtx.KeysCtx,
  666. MsgBuffer->buffer,
  667. MsgBuffer->length,
  668. INTEL_ECDSA_PUBKEY_PROD_LE,
  669. (unsigned char *)SignBuffer->buffer,
  670. CRYPTO_HASH_TYPE_SHA256,
  671. 0,
  672. 32,
  673. &VerifRes);
  674. DBG_ASSERT(Status == STATUS_SUCCESS);
  675. }
  676. if(VerifRes == FALSE) {
  677. DBG_ASSERT(0);
  678. return X509_INVALID_SIGNATURE;
  679. }
  680. }
  681. #else
  682. if(VerifRes == FALSE) {
  683. return X509_INVALID_SIGNATURE;
  684. }
  685. #endif
  686. // convert back
  687. g3point = reinterpret_cast<G3Point*>(EcdsaKey.px);
  688. SwapEndian_32B(g3point->x);
  689. SwapEndian_32B(g3point->y);
  690. SwapEndian_32B((reinterpret_cast<G3Point*>(SignBuffer->buffer))->x);
  691. SwapEndian_32B((reinterpret_cast<G3Point*>(SignBuffer->buffer))->y);
  692. break;
  693. case X509_sha1withRSAEncryption:
  694. case X509_sha256WithRSAEncryption:
  695. #ifdef X509_FOR_PSE_PR
  696. Status = X509_STATUS_UNSUPPORTED_ALGORITHM;
  697. #else
  698. RsaKeyFromCert = (SessMgrRsaKey *)(IssuerInfo->buffer);
  699. DBG_ASSERT(RsaKeyFromCert->n.length == RSA_KEY_SIZE_2048_BYTES);
  700. SESSMGR_MEMCPY_S(RsaEBuffer + sizeof(RsaEBuffer) - RsaKeyFromCert->e.length, RsaKeyFromCert->e.length, RsaKeyFromCert->e.buffer, RsaKeyFromCert->e.length);
  701. RsaKeyFromCert->e.buffer = RsaEBuffer;
  702. RsaKeyFromCert->e.length = RSA_E_SIZE;
  703. SESSMGR_MEMCPY_S(RsaNBuffer + RSA_KEY_SIZE_2048_BYTES - RsaKeyFromCert->n.length, RsaKeyFromCert->n.length, RsaKeyFromCert->n.buffer, RsaKeyFromCert->n.length);
  704. RsaKeyFromCert->n.buffer = RsaNBuffer;
  705. RsaKeyFromCert->n.length = RSA_KEY_SIZE_2048_BYTES;
  706. workBuffer.length = SESSMGR_RSA_WORK_BUFFER_SIZE;
  707. workBuffer.buffer = RsaWorkBuffer;
  708. SESSMGR_MEM_ALLOC_BUFFER(LocalSignBuffer.buffer, TRUSTED_MEM, sizeof(UINT32), SignBuffer->length, TX_WAIT_FOREVER);
  709. SESSMGR_MEM_ALLOC_BUFFER(LocalMsgBuffer.buffer, TRUSTED_MEM, sizeof(UINT32), MsgBuffer->length, TX_WAIT_FOREVER);
  710. SESSMGR_MEMCPY_S(LocalSignBuffer.buffer, SignBuffer->length, SignBuffer->buffer, SignBuffer->length);
  711. LocalSignBuffer.length = SignBuffer->length;
  712. SESSMGR_MEMCPY_S(LocalMsgBuffer.buffer, MsgBuffer->length, MsgBuffer->buffer, MsgBuffer->length);
  713. LocalMsgBuffer.length = MsgBuffer->length;
  714. // Swap the Key and signature buffers. These are local buffers so no swapping back is necessary.
  715. SwapEndian(RsaKeyFromCert->e.buffer, RsaKeyFromCert->e.length);
  716. SwapEndian(RsaKeyFromCert->n.buffer, RsaKeyFromCert->n.length);
  717. SwapEndian(LocalSignBuffer.buffer, LocalSignBuffer.length);
  718. RsaVerifyParams.pMsgBuffer = (ROM_RSA_DATA_BUFFER*)&LocalMsgBuffer;
  719. RsaVerifyParams.pSignatureBuffer = (ROM_RSA_DATA_BUFFER*)&LocalSignBuffer;
  720. RsaVerifyParams.pbIsValid = &IsSignatureValid;
  721. RsaVerifyParams.CallbackAbortNow = NULL;
  722. RsaVerifyParams.pWorkBuffer = &workBuffer;
  723. RsaVerifyParams.HashFunc = (X509_sha1withRSAEncryption == IssuerInfo->AlgoType ? ROM_RSA_SCHEME_HASH_SHA1 : ROM_RSA_SCHEME_HASH_SHA256);
  724. Status = CryptoRsaPkcsVerify((RSA_IPP_KEY*)RsaKeyFromCert,
  725. FALSE,
  726. (RSA_VERIFY_PARAMS*)&RsaVerifyParams);
  727. if(LocalSignBuffer.buffer){
  728. SESSMGR_MEM_FREE(LocalSignBuffer.buffer)
  729. LocalSignBuffer.length = 0;
  730. }
  731. if(LocalMsgBuffer.buffer){
  732. SESSMGR_MEM_FREE(LocalMsgBuffer.buffer)
  733. LocalMsgBuffer.length = 0;
  734. }
  735. if ((Status != STATUS_SUCCESS) || (IsSignatureValid != TRUE)){
  736. DBG_ASSERT(0);
  737. return X509_INVALID_SIGNATURE;
  738. }
  739. #endif // #ifdef X509_FOR_PSE_PR
  740. break;
  741. default:
  742. assert(0);
  743. }
  744. }while(0);
  745. return Status;
  746. }
  747. #define CRYPTO_SIZE_SHA256 32
  748. #ifndef X509_FOR_PSE_PR
  749. STATUS VerifyOcspResponseAttributes(Uint8* OcspRespBuffer, SessMgrOcspResponseFields *ocspResponseFields, ISSUER_INFO* OcspCertRootPublicKey,
  750. SessMgrDataBuffer Nonce, OCSP_REQ_TYPE OcspReqType, BOOL UseFacsimileEpid)
  751. {
  752. SessMgrCertificateFields certificateFields;
  753. STATUS Status;
  754. UINT32 workBufferSize = 1000;
  755. UINT8 *workBuffer = NULL;
  756. ISSUER_INFO IssuerInfo;
  757. SessMgrDataBuffer PubKeyHashBuf;
  758. UINT8 HashOut[SHA1_HASH_LEN] = {0};
  759. PubKeyHashBuf.buffer = HashOut;
  760. PubKeyHashBuf.length = SHA1_HASH_LEN;
  761. if(ocspResponseFields->ocspResponseStatus != successful){
  762. return X509_STATUS_OCSP_FAILURE;
  763. }
  764. // parse the ocsp certificate
  765. SESSMGR_MEM_ALLOC_BUFFER(workBuffer, MM_DATA_HEAP_SHARED_RW, sizeof(UINT32), workBufferSize, TX_WAIT_FOREVER);
  766. do {
  767. Status = ParseCertificateChain(ocspResponseFields->responderCertificate.buffer,
  768. ocspResponseFields->responderCertificate.length,
  769. &certificateFields,
  770. workBuffer,
  771. workBufferSize,
  772. NULL,
  773. 0,
  774. NULL,
  775. OcspResponderCertificate,
  776. UseFacsimileEpid);
  777. if(Status != X509_STATUS_SUCCESS){
  778. DBG_ASSERT(0);
  779. break;
  780. }
  781. // verify OCSP response signature.
  782. IssuerInfo.AlgoType = ocspResponseFields->algorithmIdentifierForSignature;
  783. IssuerInfo.buffer = certificateFields.subjectPublicKey.buffer;
  784. IssuerInfo.length = certificateFields.subjectPublicKey.length;
  785. Status = VerifySignature(&IssuerInfo, &ocspResponseFields->tbsResponseData, &ocspResponseFields->signature, UseFacsimileEpid);
  786. if(Status != X509_STATUS_SUCCESS){
  787. DBG_ASSERT(0);
  788. Status = X509_INVALID_SIGNATURE;
  789. break;
  790. }
  791. // Verify Nonce only on Signed FW.
  792. #ifndef _WIN32_DEVPLATFORM
  793. #ifndef X509_FOR_PSE_PR
  794. if(!(gManifestDataPtr->ManifestHeader.manifestFlags.r.debugManifest)){
  795. #endif
  796. // Verify Nonce only for Non-cached Response.
  797. if(OcspReqType == NON_CACHED){
  798. // Make sure we have a nonce in the OCSP response
  799. if(!ocspResponseFields->nonce.buffer || Nonce.length <= 0){
  800. DBG_ASSERT(0);
  801. Status = X509_STATUS_OCSP_FAILURE;
  802. break;
  803. }
  804. if( memcmp(ocspResponseFields->nonce.buffer, Nonce.buffer, Nonce.length) != 0 || (ocspResponseFields->nonce.length != Nonce.length) )
  805. {
  806. DBG_ASSERT(0);
  807. Status = X509_STATUS_OCSP_FAILURE;
  808. break;
  809. }
  810. }
  811. #ifndef X509_FOR_PSE_PR
  812. }
  813. #endif
  814. #endif
  815. // If ResponderId is a KeyHash, then verify its a Hash of the responders public key.
  816. if(ocspResponseFields->ocspResponderIdKeyHash.buffer){
  817. Status = CryptoCreateHash(CRYPTO_HASH_TYPE_SHA1,
  818. &certificateFields.EncodedSubjectPublicKey,
  819. &PubKeyHashBuf,
  820. NULL,
  821. NULL,
  822. SINGLE_BLOCK);
  823. if(Status != STATUS_SUCCESS){
  824. DBG_ASSERT(0);
  825. Status = X509_STATUS_INTERNAL_ERROR;
  826. break;
  827. }
  828. if(SHA1_HASH_LEN != ocspResponseFields->ocspResponderIdKeyHash.length ||
  829. memcmp(HashOut,ocspResponseFields->ocspResponderIdKeyHash.buffer, ocspResponseFields->ocspResponderIdKeyHash.length) != 0){
  830. DBG_ASSERT(0);
  831. Status = X509_STATUS_OCSP_FAILURE;
  832. break;
  833. }
  834. }else{
  835. // If there is no Hash, There has to be a name. In the name structure, Common Name has to exist.
  836. if(!ocspResponseFields->ocspResponderIdName.commonName){
  837. DBG_ASSERT(0);
  838. Status = X509_STATUS_OCSP_FAILURE;
  839. break;
  840. }
  841. // if Responder Id is a Name, make sure the value matches the value in the certificate.
  842. if(ocspResponseFields->ocspResponderIdName.commonNameSize != certificateFields.subject.commonNameSize ||
  843. memcmp(ocspResponseFields->ocspResponderIdName.commonName, certificateFields.subject.commonName, certificateFields.subject.commonNameSize) != 0){
  844. DBG_ASSERT(0);
  845. Status = X509_STATUS_OCSP_FAILURE;
  846. break;
  847. }
  848. }
  849. // We have verified the OCSP response. See if we have trusted time. Else provision it.
  850. if(OcspReqType == NON_CACHED){
  851. Status = StoreTrustedTime(ocspResponseFields->producedAt);
  852. if(Status == STATUS_SUCCESS)
  853. gSessmgrCtx.TrustedTimeProvisioned = TRUE;
  854. }
  855. // If we have cached response, Make sure produced at was not more than a day
  856. if(OcspReqType == CACHED){
  857. Status = VerifyOcspCachedResponseValidity(ocspResponseFields);
  858. if(Status != X509_STATUS_SUCCESS){
  859. DBG_ASSERT(0);
  860. Status = X509_STATUS_OCSP_FAILURE;
  861. break;
  862. }
  863. }
  864. #ifdef PRINT
  865. printf("\nOcsp response signature verified ");
  866. SetConsoleTextAttribute(hConsole, 2);
  867. printf("\n \n *************** VerifyOcspResponseAttributes complete ***************** \n \n");
  868. SetConsoleTextAttribute(hConsole, 8);
  869. #endif
  870. Status = X509_STATUS_SUCCESS;
  871. } while(0);
  872. SESSMGR_MEM_FREE(workBuffer);
  873. return Status;
  874. }
  875. #endif // #ifndef X509_FOR_PSE_PR
  876. STATUS VerifyBasicCertificateAttributes(const Uint8* certificateDerEncoded, const Uint8* workBuffer, const SessMgrCertificateFields* certificateFields,
  877. const ISSUER_INFO *IssuerInfo, const CertificateType CertType, CertificateLevel CertLevel, BOOL UseFacsimileEpid)
  878. {
  879. SessMgrEcdsaPublicKey *EcdsaKey;
  880. #ifdef X509_FOR_PSE_PR
  881. UNUSED(certificateDerEncoded);
  882. UNUSED(workBuffer);
  883. UNUSED(EcdsaKey);
  884. UNUSED(CertType);
  885. UNUSED(CertLevel);
  886. UNUSED(UseFacsimileEpid);
  887. #endif
  888. // Make sure the signature Algorithms for issuer is the same as the one used in the TbsCertificate
  889. if(certificateFields->TbsCertSignAlgoId != certificateFields->algorithmIdentifierForSignature){
  890. DBG_ASSERT(0);
  891. return X509_STATUS_ENCODING_ERROR;
  892. }
  893. #ifndef X509_FOR_PSE_PR //PSE Usage doesn't need to check Cert expiration
  894. STATUS Status = X509_GENERAL_ERROR;
  895. // Verify if the certificate time is valid. At this point we expect trusted time to be set.
  896. /* Chicken and Egg problem: we get trusted time from OCSP. How do we check validity of OCSP responder certificate?
  897. Solution : Intel signs the OCSP responder cert and EPID group certs. its valid for a really long time. So for these
  898. certs, dont check validity.*/
  899. if((CertType != EpidGroupCertificate) && (CertType != OcspResponderCertificate)){
  900. Status = VerifyValidity(certificateFields->notValidBeforeTime, certificateFields->notValidAfterTime);
  901. if(Status != X509_STATUS_SUCCESS){
  902. DBG_ASSERT(0);
  903. return X509_STATUS_EXPIRED_CERTIFICATE;
  904. }
  905. }
  906. Status = VerifySignature(IssuerInfo, &certificateFields->messageBuffer, &certificateFields->signatureBuffer, UseFacsimileEpid);
  907. if(Status != X509_STATUS_SUCCESS){
  908. DBG_ASSERT(0);
  909. return X509_INVALID_SIGNATURE;
  910. }
  911. #endif
  912. // Common name and OrgName should be present.
  913. if(!certificateFields->issuer.commonName || !certificateFields->subject.commonName || !certificateFields->subject.organization){
  914. DBG_ASSERT(0);
  915. return X509_STATUS_ENCODING_ERROR;
  916. }
  917. #if 0
  918. // The issuer of the root certificate has to be intel irrespective of the certificate type.
  919. if(CertLevel == root){
  920. if(certificateFields->issuer.commonNameSize != strlen("www.intel.com") ||
  921. memcmp(certificateFields->issuer.commonName, "www.intel.com", strlen("www.intel.com")) !=0){
  922. DBG_ASSERT(0);
  923. return X509_STATUS_ENCODING_ERROR;
  924. }
  925. }
  926. #endif
  927. // Make sure the subject of the prev certificate is the issuer of the current certificate
  928. if(IssuerInfo->CommonNameBuf.buffer && IssuerInfo->CommonNameBuf.length > 0){
  929. if(certificateFields->issuer.commonNameSize != IssuerInfo->CommonNameBuf.length ||
  930. memcmp(certificateFields->issuer.commonName, IssuerInfo->CommonNameBuf.buffer, IssuerInfo->CommonNameBuf.length) != 0){
  931. DBG_ASSERT(0);
  932. return X509_STATUS_ENCODING_ERROR;
  933. }
  934. }
  935. #ifndef X509_FOR_PSE_PR
  936. switch(CertType){
  937. case OcspResponderCertificate:
  938. if(certificateFields->keyUsage.value == 0){
  939. DBG_ASSERT(0);
  940. return X509_STATUS_ENCODING_ERROR;
  941. }
  942. // Make sure only the non-repudiation and digitalSignature are set.
  943. if(certificateFields->keyUsage.value != (X509_BIT0 | X509_BIT1)){
  944. DBG_ASSERT(0);
  945. return X509_STATUS_ENCODING_ERROR;
  946. }
  947. // ExtendedKeyUsage must be specified.
  948. if(certificateFields->ExtendedKeyUsage.value == 0){
  949. DBG_ASSERT(0);
  950. return X509_STATUS_ENCODING_ERROR;
  951. }
  952. // Basic constraints extension should be present.
  953. if(!certificateFields->basicConstraint.isBasicConstraintPresent){
  954. DBG_ASSERT(0);
  955. return X509_STATUS_ENCODING_ERROR;
  956. }
  957. // isCa should be deasserted. We will not delegate OCSP signing authority to anybody else.
  958. if(certificateFields->basicConstraint.isCa == DER_ENCODING_TRUE){
  959. DBG_ASSERT(0);
  960. return X509_STATUS_ENCODING_ERROR;
  961. }
  962. break;
  963. case VerifierCertificate:
  964. // Basic Constraint should be present.
  965. if(!certificateFields->basicConstraint.isBasicConstraintPresent){
  966. DBG_ASSERT(0);
  967. return X509_STATUS_ENCODING_ERROR;
  968. }
  969. // Make sure leaf certs dont have isCA set and intermediate Certs have isCa deasserted.
  970. if( (CertLevel == leaf && certificateFields->basicConstraint.isCa == DER_ENCODING_TRUE) ||
  971. (CertLevel != leaf && certificateFields->basicConstraint.isCa == DER_ENCODING_FALSE)){
  972. DBG_ASSERT(0);
  973. return X509_STATUS_ENCODING_ERROR;
  974. }
  975. if(certificateFields->algorithmIdentifierForSubjectPublicKey == X509_ecdsaPublicKey){
  976. // For ECDSA public key, we expect curvve to be prime256v1
  977. EcdsaKey = (SessMgrEcdsaPublicKey *)certificateFields->subjectPublicKey.buffer;
  978. if(EcdsaKey->eccParameter != curvePrime256v1){
  979. DBG_ASSERT(0);
  980. return X509_STATUS_ENCODING_ERROR;
  981. }
  982. }
  983. // For root and intermediate certificates, BIT5 (KeyCertSign) must be asserted
  984. if(CertLevel != leaf){
  985. if(certificateFields->keyUsage.value != X509_BIT5){
  986. DBG_ASSERT(0);
  987. return X509_STATUS_ENCODING_ERROR;
  988. }
  989. }else{
  990. if(certificateFields->keyUsage.value != (X509_BIT0 | X509_BIT1)){
  991. DBG_ASSERT(0);
  992. return X509_STATUS_ENCODING_ERROR;
  993. }
  994. }
  995. // Check for Subject Key Identifier. Per spec, all certificate except leaf should have this and should be equal to SHA1 of the public key.
  996. if(CertLevel != leaf){
  997. if(!certificateFields->SubjectKeyId.buffer || certificateFields->SubjectKeyId.length != SHA1_HASH_LEN ){
  998. DBG_ASSERT(0);
  999. return X509_STATUS_ENCODING_ERROR;
  1000. }
  1001. if(VerifySha1Hash(&certificateFields->EncodedSubjectPublicKey, certificateFields->SubjectKeyId.buffer , certificateFields->SubjectKeyId.length) == FALSE){
  1002. DBG_ASSERT(0);
  1003. return X509_STATUS_ENCODING_ERROR;
  1004. }
  1005. }
  1006. // Every verifier cert should have an authority key id
  1007. if(!certificateFields->AuthorityKeyId.buffer || (certificateFields->AuthorityKeyId.length != IssuerInfo->EncodedPublicKeyHashBuffer.length) ){
  1008. DBG_ASSERT(0);
  1009. return X509_STATUS_ENCODING_ERROR;
  1010. }
  1011. // Verify Authority Key Id. Spec says Authority Key ID of current cert should be equal to the SubjectKeyId of the upper cert. SubjectKeyId is nothing but the hash of the upper certs public key.
  1012. // we have that available in this function. So compare Authority Key with that.
  1013. if(certificateFields->AuthorityKeyId.length != IssuerInfo->EncodedPublicKeyHashBuffer.length ||
  1014. memcmp(certificateFields->AuthorityKeyId.buffer, IssuerInfo->EncodedPublicKeyHashBuffer.buffer, IssuerInfo->EncodedPublicKeyHashBuffer.length) != 0){
  1015. // if the first cert is signed by the prod Intel IVK & GID is 0, try again with hash of the prod Intel IVK
  1016. #ifndef X509_FOR_PSE_PR
  1017. if (gSessmgrCtx.FuseGidZero){
  1018. #endif
  1019. UINT8 TempSignKeyBuffer[ECDSA_KEY_SIZE + 1] = {0};
  1020. SessMgrDataBuffer TempDataBuffer = {sizeof(TempSignKeyBuffer), TempSignKeyBuffer};
  1021. TempSignKeyBuffer[0] = 0x04;
  1022. SESSMGR_MEMCPY_S(TempSignKeyBuffer + 1, ECDSA_KEY_SIZE, INTEL_ECDSA_PUBKEY_PROD_BE, sizeof(INTEL_ECDSA_PUBKEY_PROD_BE));
  1023. Status = CryptoCreateHash(CRYPTO_HASH_TYPE_SHA1,
  1024. &TempDataBuffer,
  1025. &IssuerInfo->EncodedPublicKeyHashBuffer,
  1026. NULL,
  1027. NULL,
  1028. SINGLE_BLOCK);
  1029. if (Status != STATUS_SUCCESS) {
  1030. DBG_ASSERT(0);
  1031. return X509_STATUS_INTERNAL_ERROR;
  1032. }
  1033. if (certificateFields->AuthorityKeyId.length != IssuerInfo->EncodedPublicKeyHashBuffer.length ||
  1034. memcmp(certificateFields->AuthorityKeyId.buffer, IssuerInfo->EncodedPublicKeyHashBuffer.buffer, IssuerInfo->EncodedPublicKeyHashBuffer.length) != 0){
  1035. DBG_ASSERT(0);
  1036. return X509_STATUS_ENCODING_ERROR;
  1037. }
  1038. #ifndef X509_FOR_PSE_PR
  1039. }
  1040. else{
  1041. DBG_ASSERT(0);
  1042. return X509_STATUS_ENCODING_ERROR;
  1043. }
  1044. #endif // #ifdef X509_FOR_PSE_PR
  1045. }
  1046. // Product type must be present
  1047. if(certificateFields->productType == invalidProductType || certificateFields->productType >= Max_ProductType){
  1048. DBG_ASSERT(0);
  1049. return X509_STATUS_ENCODING_ERROR;
  1050. }
  1051. // If issuer certificate product type exists, ensure it matches current cert
  1052. if ((IssuerInfo->productType != invalidProductType) && (IssuerInfo->productType != certificateFields->productType)) {
  1053. DBG_ASSERT(0);
  1054. return X509_STATUS_ENCODING_ERROR;
  1055. }
  1056. break;
  1057. }
  1058. #endif
  1059. #ifdef PRINT
  1060. SetConsoleTextAttribute(hConsole, 4);
  1061. printf("\n \n *************** VerifyBasicCertificateAttributes complete ***************** \n \n");
  1062. SetConsoleTextAttribute(hConsole, 8);
  1063. #endif
  1064. return X509_STATUS_SUCCESS;
  1065. }
  1066. #ifndef X509_FOR_PSE_PR
  1067. static BOOL VerifySha1Hash(SessMgrDataBuffer *HashData, UINT8 *Expectedhash, UINT32 ExpectedHashLength)
  1068. {
  1069. UINT8 HashOut[SHA1_HASH_LEN] = {0};
  1070. SessMgrDataBuffer HashBuf;
  1071. STATUS Status;
  1072. if(!HashData->buffer || HashData->length == 0)
  1073. return FALSE;
  1074. HashBuf.buffer = HashOut;
  1075. HashBuf.length = SHA1_HASH_LEN;
  1076. memset(HashBuf.buffer, 0 , HashBuf.length);
  1077. Status = CryptoCreateHash(CRYPTO_HASH_TYPE_SHA1,
  1078. HashData,
  1079. &HashBuf,
  1080. NULL,
  1081. NULL,
  1082. SINGLE_BLOCK);
  1083. if(Status != STATUS_SUCCESS){
  1084. DBG_ASSERT(0);
  1085. return FALSE;
  1086. }
  1087. if(HashBuf.length != ExpectedHashLength ||
  1088. memcmp(HashBuf.buffer, Expectedhash, ExpectedHashLength) != 0){
  1089. return FALSE;
  1090. }
  1091. return TRUE;
  1092. }
  1093. #endif
  1094. #ifndef X509_FOR_PSE_PR //NRG: not validating time in enclave
  1095. STATUS VerifyValidity(SessMgrDateTime notValidBeforeTime, SessMgrDateTime NotValidAfterTime)
  1096. {
  1097. STATUS Status;
  1098. NTP_TIMESTAMP CurrentTime, NotValidBefore, NotValidAfter;
  1099. // At this point, we expect trusted time to be provisioned. Else Error
  1100. if(!gSessmgrCtx.TrustedTimeProvisioned){
  1101. DBG_ASSERT(0);
  1102. return X509_STATUS_INTERNAL_ERROR;
  1103. }
  1104. Status = PrtcGetTime(&CurrentTime, gSessmgrCtx.TrustedTime.RtcOffset);
  1105. if(Status != STATUS_SUCCESS){
  1106. DBG_ASSERT(0);
  1107. return X509_STATUS_INTERNAL_ERROR;
  1108. }
  1109. // extract time from the certs and convert it into NTP. Get NotValidBefore and NotValidAfter.
  1110. // There is no day 0. We use that to find if the field has been populated. If not, ignore this check.
  1111. if(notValidBeforeTime.date.yearMonthDay.day != 0){
  1112. Status = ConvertTimeToNtp(notValidBeforeTime, &NotValidBefore);
  1113. if(Status != STATUS_SUCCESS){
  1114. DBG_ASSERT(0);
  1115. return X509_STATUS_INTERNAL_ERROR;
  1116. }
  1117. if( CurrentTime.Seconds < NotValidBefore.Seconds - 120){
  1118. DBG_ASSERT(0);
  1119. return X509_STATUS_EXPIRED_CERTIFICATE;
  1120. }
  1121. }
  1122. if(NotValidAfterTime.date.yearMonthDay.day != 0){
  1123. Status = ConvertTimeToNtp(NotValidAfterTime, &NotValidAfter);
  1124. if(Status != STATUS_SUCCESS){
  1125. DBG_ASSERT(0);
  1126. return X509_STATUS_INTERNAL_ERROR;
  1127. }
  1128. if(CurrentTime.Seconds > NotValidAfter.Seconds){
  1129. DBG_ASSERT(0);
  1130. return X509_STATUS_EXPIRED_CERTIFICATE;
  1131. }
  1132. }
  1133. return X509_STATUS_SUCCESS;
  1134. }
  1135. STATUS VerifyOcspCachedResponseValidity(SessMgrOcspResponseFields *OcspResponseFields)
  1136. {
  1137. STATUS Status;
  1138. NTP_TIMESTAMP CurrentTime = {0, 0};
  1139. NTP_TIMESTAMP ProducedAt = {0, 0};
  1140. // At this point, we expect trusted time to be provisioned. Else Error
  1141. if(!gSessmgrCtx.TrustedTimeProvisioned){
  1142. DBG_ASSERT(0);
  1143. return X509_STATUS_INTERNAL_ERROR;
  1144. }
  1145. Status = PrtcGetTime(&CurrentTime, gSessmgrCtx.TrustedTime.RtcOffset);
  1146. if(Status != STATUS_SUCCESS){
  1147. DBG_ASSERT(0);
  1148. return X509_STATUS_INTERNAL_ERROR;
  1149. }
  1150. // extract time from the certs and convert it into NTP. Get NotValidBefore and NotValidAfter
  1151. Status = ConvertTimeToNtp(OcspResponseFields->producedAt, &ProducedAt);
  1152. if(Status != STATUS_SUCCESS){
  1153. DBG_ASSERT(0);
  1154. return X509_STATUS_INTERNAL_ERROR;
  1155. }
  1156. #ifndef _WIN32_DEVPLATFORM // don't validate certificate time on DevPlatform
  1157. // assuming no rollover
  1158. if ((ProducedAt.Seconds > CurrentTime.Seconds) &&
  1159. ((ProducedAt.Seconds - CurrentTime.Seconds) > OCSP_DELAY_TOLERANCE_SECONDS )){
  1160. DBG_ASSERT(0);
  1161. return X509_STATUS_INTERNAL_ERROR;
  1162. }
  1163. if ((CurrentTime.Seconds > ProducedAt.Seconds) &&
  1164. ((CurrentTime.Seconds - ProducedAt.Seconds) > SECONDS_IN_DAY )){
  1165. DBG_ASSERT(0);
  1166. return X509_STATUS_EXPIRED_CERTIFICATE;
  1167. }
  1168. #endif // _WIN32_DEVPLATFORM
  1169. return X509_STATUS_SUCCESS;
  1170. }
  1171. #endif // #ifndef X509_FOR_PSE_PR
  1172. /*
  1173. This function will parse the certificate, will extract out interesting data (defined in the "Fields" structure) and return them to the caller.
  1174. */
  1175. static STATUS sessMgrParseDerCert
  1176. (
  1177. IN X509_PROTOCOL* X509Protocol,
  1178. IN Uint8* certificateDerEncoded,
  1179. IN Uint8* pCertEnd,
  1180. IN Uint8* workBuffer,
  1181. IN UINT32 workBufferSize,
  1182. OUT SessMgrCertificateFields* certificateFields,
  1183. IN ISSUER_INFO *IssuerInfo,
  1184. IN BOOL UseFacsimileEpid
  1185. )
  1186. {
  1187. UINT32 Status;
  1188. /* Refer to certificate structure for definition */
  1189. Uint8* workBufferStart = workBuffer;
  1190. UINT8* current_ptr = certificateDerEncoded;
  1191. UINT8* pTemp;
  1192. UINT32 length;
  1193. UINT32 i = 0;
  1194. SessMgrEllipticCurveParameter params = unknownParameter;
  1195. UINT8 EncodingBytes;
  1196. UINT32 padding;
  1197. #ifdef PRINT
  1198. printf("\n **************** Parsing a Certificate ******************** ");
  1199. for(i=0;i<certificateFields->serialNumber.length;i++)
  1200. printf("%hhx ",*(certificateFields->serialNumber.buffer + i));
  1201. #endif
  1202. #ifdef X509_FOR_PSE_PR
  1203. UNUSED(X509Protocol);
  1204. UNUSED(i);
  1205. #endif
  1206. do{
  1207. Status = ParseIdAndLength(&current_ptr, pCertEnd, DER_ENCODING_SEQUENCE_ID, &length, &EncodingBytes, FALSE);
  1208. if(Status != X509_STATUS_SUCCESS)
  1209. break;
  1210. certificateFields->messageBuffer.buffer = current_ptr;
  1211. /* Start of TBS Certificate : Starts with a sequence */
  1212. Status = ParseIdAndLength(&current_ptr, pCertEnd, DER_ENCODING_SEQUENCE_ID, &length, &EncodingBytes, FALSE);
  1213. if(Status != X509_STATUS_SUCCESS)
  1214. break;
  1215. // Total signed buffer length = certificate Length + Encoding Bytes ( +1 is for the Type identifier)
  1216. certificateFields->messageBuffer.length = length + EncodingBytes + 1;
  1217. /*** Early Signature Verification ****/
  1218. // Try to verify signature first. That way we resolve all corruption problems.
  1219. pTemp = certificateFields->messageBuffer.buffer + certificateFields->messageBuffer.length;
  1220. // Current pointer is at SignatureAlgorithm which is a algorithm identifier
  1221. Status = ParseAlgoIdentifier(&pTemp, pCertEnd, (UINT32*)&certificateFields->TbsCertSignAlgoId, signature_algo, &params);
  1222. if(Status != X509_STATUS_SUCCESS){
  1223. DBG_ASSERT(0);
  1224. break;
  1225. }
  1226. // Next field : SignatureValue
  1227. Status = ParseSignatureValue(&pTemp, pCertEnd, &workBuffer, workBufferSize - (int)(workBuffer-workBufferStart), &certificateFields->signatureBuffer, certificateFields->TbsCertSignAlgoId);
  1228. if(Status != X509_STATUS_SUCCESS){
  1229. DBG_ASSERT(0);
  1230. break;
  1231. }
  1232. Status = VerifySignature(IssuerInfo, &certificateFields->messageBuffer, &certificateFields->signatureBuffer, UseFacsimileEpid);
  1233. if(Status != X509_STATUS_SUCCESS){
  1234. DBG_ASSERT(0);
  1235. return X509_INVALID_SIGNATURE;
  1236. }
  1237. /**** End Early Signature Verification *****/
  1238. // Next Field : Version (Optional field with explicit tagging)
  1239. Status = ParseIdAndLength(&current_ptr, pCertEnd, EXPLICIT_TAG_0_ID_VALUE, &length, &EncodingBytes, TRUE);
  1240. if( (Status != X509_STATUS_SUCCESS) && Status != X509_STATUS_NOT_FOUND)
  1241. break;
  1242. if(Status != X509_STATUS_NOT_FOUND){
  1243. // We have a version number. Note: Not using ParseInteger function because certificateVersion is defined as a UINT32 and not a DataBuffer
  1244. Status = ParseIdAndLength(&current_ptr, pCertEnd, DER_ENCODING_INTEGER_ID, &length, &EncodingBytes, FALSE);
  1245. if(Status != X509_STATUS_SUCCESS || length > MAX_VERSION_LENGTH_SIZE_BYTES){
  1246. Status = X509_STATUS_ENCODING_ERROR;
  1247. break;
  1248. }
  1249. SESSMGR_MEMCPY_S((UINT8*)&certificateFields->certificateVersion + sizeof(UINT32) - length, length, current_ptr, length);
  1250. // The certificates are big endian.
  1251. SwapEndian((UINT8 *)&certificateFields->certificateVersion, sizeof(UINT32));
  1252. if(certificateFields->certificateVersion != v3){
  1253. Status = X509_STATUS_INVALID_VERSION;
  1254. break;
  1255. }
  1256. current_ptr+= length;
  1257. }else{
  1258. /* Default is v1 according to spec . But we dont support onyl v3. Return error. */
  1259. Status = X509_STATUS_INVALID_VERSION;
  1260. break;
  1261. }
  1262. // Next Field : Certificate Serial Number Format : Integer Identifier + Length + Value (Max 20 bytes)
  1263. Status = ParseInteger(&current_ptr, pCertEnd, &certificateFields->serialNumber, FALSE, TRUE, &padding);
  1264. if ((Status != X509_STATUS_SUCCESS) || (certificateFields->serialNumber.length + padding > MAX_HASH_LEN)) {
  1265. DBG_ASSERT(0);
  1266. Status = X509_STATUS_ENCODING_ERROR;
  1267. break;
  1268. }
  1269. #ifdef PRINT
  1270. printf("\n Serial Number ");
  1271. for(i=0;i<certificateFields->serialNumber.length;i++)
  1272. printf("%hhx ",*(certificateFields->serialNumber.buffer + i));
  1273. #endif
  1274. // Next Field : Algorithm Identifier (signature) The OID is expected to be one of the HardCodedSignatureAlgorithmOid array values.
  1275. Status = ParseAlgoIdentifier(&current_ptr, pCertEnd, (UINT32*)&certificateFields->algorithmIdentifierForSignature,signature_algo, &params);
  1276. if(Status != X509_STATUS_SUCCESS){
  1277. Status = X509_STATUS_ENCODING_ERROR;
  1278. break;
  1279. }
  1280. // Next Field : issuer
  1281. Status = ParseName(&current_ptr, pCertEnd, &certificateFields->issuer);
  1282. if(Status != X509_STATUS_SUCCESS){
  1283. DBG_ASSERT(0);
  1284. break;
  1285. }
  1286. // Next Field : Validity Format : sequence notBefore notAfter
  1287. Status = ParseIdAndLength(&current_ptr, pCertEnd, DER_ENCODING_SEQUENCE_ID, &length, &EncodingBytes, FALSE);
  1288. if(Status != X509_STATUS_SUCCESS)
  1289. break;
  1290. // Parse notBefore, notAfter, Subject, SubjectPublic key info
  1291. Status = ParseTime(&current_ptr, pCertEnd, &certificateFields->notValidBeforeTime);
  1292. if(Status != X509_STATUS_SUCCESS)
  1293. break;
  1294. Status = ParseTime(&current_ptr, pCertEnd, &certificateFields->notValidAfterTime);
  1295. if(Status != X509_STATUS_SUCCESS)
  1296. break;
  1297. Status = ParseName(&current_ptr, pCertEnd, &certificateFields->subject);
  1298. if(Status != X509_STATUS_SUCCESS)
  1299. break;
  1300. Status = ParseSubjectPublicKeyInfo(&current_ptr, pCertEnd, &workBuffer, certificateFields);
  1301. if(Status != X509_STATUS_SUCCESS)
  1302. break;
  1303. // Next Field: IssuerUniqueId [optional] Implicit TAG Number is 1 Type : UniqueIdentifier (BIT STRING)
  1304. Status = ParseIdAndLength(&current_ptr, pCertEnd, IMPLICIT_TAG_ID + TAG_NUMBER_ISSUER_UNIQUE_ID, &length, &EncodingBytes, TRUE);
  1305. if(Status != X509_STATUS_SUCCESS && Status != X509_STATUS_NOT_FOUND)
  1306. break;
  1307. if(Status != X509_STATUS_NOT_FOUND){
  1308. certificateFields->IssuerUniqueId.buffer = current_ptr;
  1309. certificateFields->IssuerUniqueId.length = length;
  1310. current_ptr += length;
  1311. }
  1312. // Next Field: SubjectUniqueId [optional] Implicit TAG Number is 2 Type : UniqueIdentifier (BIT STRING)
  1313. Status = ParseIdAndLength(&current_ptr, pCertEnd, IMPLICIT_TAG_ID + TAG_NUMBER_SUBJECT_UNIQUE_ID, &length, &EncodingBytes, TRUE);
  1314. if(Status != X509_STATUS_SUCCESS && Status != X509_STATUS_NOT_FOUND)
  1315. break;
  1316. if(Status != X509_STATUS_NOT_FOUND){
  1317. certificateFields->SubjectUniqueId.buffer = current_ptr;
  1318. certificateFields->SubjectUniqueId.length = length;
  1319. current_ptr += length;
  1320. }
  1321. // Next Field: Extensions [optional]
  1322. Status = ParseIdAndLength(&current_ptr, pCertEnd, EXPLICIT_TAG_ID + TAG_NUMBER_EXTENSIONS, &length, &EncodingBytes, TRUE);
  1323. if(Status != X509_STATUS_SUCCESS && Status != X509_STATUS_NOT_FOUND)
  1324. break;
  1325. if(Status != X509_STATUS_NOT_FOUND){
  1326. #ifndef X509_FOR_PSE_PR
  1327. Status = ParseCertExtensions(&current_ptr, current_ptr + length, certificateFields);
  1328. if(Status != X509_STATUS_SUCCESS){
  1329. DBG_ASSERT(0);
  1330. break;
  1331. }
  1332. #else
  1333. current_ptr += length;
  1334. #endif
  1335. }
  1336. /* End of TbsCErtificate */
  1337. // Current pointer is at SignatureAlgorithm which is a algorithm identifier
  1338. Status = ParseAlgoIdentifier(&current_ptr, pCertEnd, (UINT32*)&certificateFields->TbsCertSignAlgoId, signature_algo, &params);
  1339. if(Status != X509_STATUS_SUCCESS){
  1340. DBG_ASSERT(0);
  1341. break;
  1342. }
  1343. // Next field : SignatureValue
  1344. Status = ParseSignatureValue(&current_ptr, pCertEnd, &workBuffer, workBufferSize - (int)(workBuffer - workBufferStart), &certificateFields->signatureBuffer, certificateFields->algorithmIdentifierForSignature);
  1345. if(Status != X509_STATUS_SUCCESS){
  1346. DBG_ASSERT(0);
  1347. break;
  1348. }
  1349. }while(0);
  1350. DBG_ASSERT((int)(workBuffer - workBufferStart) < workBufferSize)
  1351. DBG_ASSERT(Status == X509_STATUS_SUCCESS);
  1352. if (current_ptr != pCertEnd) {
  1353. DBG_ASSERT(0);
  1354. return X509_STATUS_ENCODING_ERROR;
  1355. }
  1356. return Status;
  1357. }
  1358. #ifndef X509_FOR_PSE_PR
  1359. STATUS sessMgrParseOcspResponse
  1360. (
  1361. IN X509_PROTOCOL* X509Protocol,
  1362. IN Uint8* OcspResponse,
  1363. IN Uint8* OcspResponseEnd,
  1364. IN Uint8* workBuffer,
  1365. IN UINT32 workBufferSize,
  1366. OUT SessMgrOcspResponseFields* OcspResponseFields
  1367. )
  1368. {
  1369. STATUS Status;
  1370. Uint8* workBufferStart = workBuffer;
  1371. UINT8* current_ptr = OcspResponse;
  1372. UINT32 length;
  1373. UINT32 temp;
  1374. SessMgrOcspSingleResponse *SingleResponse;
  1375. UINT8 *end_of_single_responses;
  1376. SessMgrEllipticCurveParameter params;
  1377. UINT8 EncodingBytes;
  1378. UINT32 padding;
  1379. /* Ocsp response is a SEQ { responseStatus, response bytes }*/
  1380. do{
  1381. Status = ParseIdAndLength(&current_ptr, OcspResponseEnd, DER_ENCODING_SEQUENCE_ID, &length, &EncodingBytes, FALSE);
  1382. if(Status != X509_STATUS_SUCCESS)
  1383. break;
  1384. // Next Field: response status response status is a enumerated type
  1385. Status = ParseIdAndLength(&current_ptr, OcspResponseEnd, DER_ENCODING_ENUMERATED_ID, &length, &EncodingBytes, FALSE);
  1386. if(Status != X509_STATUS_SUCCESS || length != 1){
  1387. // Note: currently we support only 7 bits. So error out if length is more than 1 byte
  1388. Status = X509_STATUS_ENCODING_ERROR;
  1389. break;
  1390. }
  1391. OcspResponseFields->ocspResponseStatus = (ResponseStatus)*current_ptr;
  1392. current_ptr += length;
  1393. // Next Field: response bytes Reponsne Bytes is a SEQ { response type , response }. response bytes is optional
  1394. Status = ParseIdAndLength(&current_ptr, OcspResponseEnd, EXPLICIT_TAG_ID + TAG_NUMBER_RESPONSE_BYTES, &length, &EncodingBytes, TRUE);
  1395. if(Status != X509_STATUS_SUCCESS && Status != X509_STATUS_NOT_FOUND)
  1396. break;
  1397. if(Status == X509_STATUS_NOT_FOUND){
  1398. // No response bytes. Nothing more to parse.
  1399. Status = X509_STATUS_SUCCESS;
  1400. break;
  1401. }
  1402. /* WE HAVE A RESPONSE !!!! */
  1403. Status = ParseIdAndLength(&current_ptr, OcspResponseEnd, DER_ENCODING_SEQUENCE_ID, &length, &EncodingBytes, FALSE);
  1404. if(Status != X509_STATUS_SUCCESS)
  1405. break;
  1406. // Next Field: responseType Type : Object ID
  1407. Status = ParseOID(&current_ptr, OcspResponseEnd, &temp, &OcspResponseTypeOid[0][0],
  1408. sizeof(OcspResponseTypeOid)/sizeof(OcspResponseTypeOid[0]),
  1409. sizeof(OcspResponseTypeOid[0]));
  1410. if(Status != X509_STATUS_SUCCESS || temp != 0){
  1411. DBG_ASSERT(0);
  1412. Status = X509_STATUS_ENCODING_ERROR;
  1413. break;
  1414. }
  1415. // Next Field: response Type : OCTET STRING
  1416. Status = ParseIdAndLength(&current_ptr, OcspResponseEnd, DER_ENCODING_OCTET_STRING_ID, &length, &EncodingBytes, FALSE);
  1417. if(Status != X509_STATUS_SUCCESS)
  1418. break;
  1419. // The only response type we support is basicOcspResponse. BasicOcspResponse is SEQ {tbsResponseData, SignatureAlgo, Signature, Certs [optional] }
  1420. Status = ParseIdAndLength(&current_ptr, OcspResponseEnd, DER_ENCODING_SEQUENCE_ID, &length, &EncodingBytes, FALSE);
  1421. if(Status != X509_STATUS_SUCCESS)
  1422. break;
  1423. // Next Field : tbsResponseData Format : Seq { version [optional], ResponderId, ProducesdAt, responses, responseExtensions [optional]
  1424. OcspResponseFields->tbsResponseData.buffer = current_ptr;
  1425. Status = ParseIdAndLength(&current_ptr, OcspResponseEnd, DER_ENCODING_SEQUENCE_ID, &length, &EncodingBytes, FALSE);
  1426. if(Status != X509_STATUS_SUCCESS)
  1427. break;
  1428. OcspResponseFields->tbsResponseData.length = length + EncodingBytes + 1;
  1429. // We dont store the version anywhere. Just parse if present and move pointer to next type
  1430. Status = ParseIdAndLength(&current_ptr, OcspResponseEnd, EXPLICIT_TAG_ID + TAG_NUMBER_VERSION, &length, &EncodingBytes, TRUE);
  1431. if(Status != X509_STATUS_SUCCESS && Status != X509_STATUS_NOT_FOUND)
  1432. break;
  1433. if(Status != X509_STATUS_NOT_FOUND){
  1434. // we have version. Just parse over it
  1435. current_ptr += length;
  1436. }
  1437. // Next Field : ResponderId ResponderId can be a choice of either Name or KeyHash. We distinguish them using the tags
  1438. Status = ParseIdAndLength(&current_ptr, OcspResponseEnd, EXPLICIT_TAG_ID + TAG_NUMBER_RESPONDER_NAME, &length, &EncodingBytes, TRUE);
  1439. if(Status != X509_STATUS_SUCCESS && Status != X509_STATUS_NOT_FOUND)
  1440. break;
  1441. if(Status != X509_STATUS_NOT_FOUND){
  1442. Status = ParseName(&current_ptr, OcspResponseEnd, &OcspResponseFields->ocspResponderIdName);
  1443. if(Status != X509_STATUS_SUCCESS)
  1444. break;
  1445. }else{
  1446. Status = ParseIdAndLength(&current_ptr, OcspResponseEnd, EXPLICIT_TAG_ID + TAG_NUMBER_RESPONDER_KEYHASH, &length, &EncodingBytes, FALSE);
  1447. if(Status != X509_STATUS_SUCCESS){
  1448. /* We either need to have a Id or a Keyhash */
  1449. Status = X509_STATUS_ENCODING_ERROR;
  1450. break;
  1451. }
  1452. // KeyHash is a octet String
  1453. Status = ParseIdAndLength(&current_ptr, OcspResponseEnd, DER_ENCODING_OCTET_STRING_ID, &length, &EncodingBytes, FALSE);
  1454. if(Status != X509_STATUS_SUCCESS)
  1455. break;
  1456. OcspResponseFields->ocspResponderIdKeyHash.buffer = current_ptr;
  1457. OcspResponseFields->ocspResponderIdKeyHash.length = length;
  1458. current_ptr +=length;
  1459. }
  1460. /* Next Field : ProducedAt */
  1461. Status = ParseTime(&current_ptr, OcspResponseEnd, &OcspResponseFields->producedAt);
  1462. if(Status != X509_STATUS_SUCCESS)
  1463. break;
  1464. #ifdef TIME_PRINT
  1465. printf("\n Produced At ");
  1466. PrintValidity(&OcspResponseFields->producedAt);
  1467. #endif
  1468. // Next Field : response Format : responses is a SEQ { single Responses }
  1469. Status = ParseIdAndLength(&current_ptr, OcspResponseEnd, DER_ENCODING_SEQUENCE_ID, &length, &EncodingBytes, FALSE);
  1470. if(Status != X509_STATUS_SUCCESS)
  1471. break;
  1472. end_of_single_responses = current_ptr + length;
  1473. // Each single response is parsed and put into the SessMgrOcspSingleResponse structure. This structure is declared out of the work buffer
  1474. SingleResponse = (SessMgrOcspSingleResponse *)workBuffer;
  1475. OcspResponseFields->allResponses = (SessMgrOcspSingleResponse*) workBuffer;
  1476. OcspResponseFields->numberOfSingleReponses = 0;
  1477. while(current_ptr < end_of_single_responses){
  1478. // update workbuffer pointer for future use
  1479. workBuffer += sizeof(SessMgrOcspSingleResponse);
  1480. // Each single response is a SEQ { CertID, CertStatus, Thisupdate, nextUpdate [optional], SingleExtensions [optional] */
  1481. Status = ParseIdAndLength(&current_ptr, end_of_single_responses, DER_ENCODING_SEQUENCE_ID, &length, &EncodingBytes, FALSE);
  1482. if(Status != X509_STATUS_SUCCESS)
  1483. break;
  1484. // current pointer is over CertId CertId is a Seq {hash algorithm, issuername hash, issuerKeyHash, serialNumber}
  1485. Status = ParseIdAndLength(&current_ptr, end_of_single_responses, DER_ENCODING_SEQUENCE_ID, &length, &EncodingBytes, FALSE);
  1486. if(Status != X509_STATUS_SUCCESS)
  1487. break;
  1488. // current pointer over Hash algo Hash algorithm is a Algorithm identifier
  1489. Status = ParseAlgoIdentifier(&current_ptr, end_of_single_responses, (UINT32*)&SingleResponse->issuerIdentifierHashType,Hash_algo, &params);
  1490. if(Status != X509_STATUS_SUCCESS)
  1491. break;
  1492. // Next Field: IssueNameHash Type : octet string */
  1493. Status = ParseIdAndLength(&current_ptr, end_of_single_responses, DER_ENCODING_OCTET_STRING_ID, &length, &EncodingBytes, FALSE);
  1494. if(Status != X509_STATUS_SUCCESS)
  1495. break;
  1496. SingleResponse->issuerNameHash.buffer = current_ptr;
  1497. SingleResponse->issuerNameHash.length = length;
  1498. current_ptr+=length;
  1499. // Next Field: IssueKeyHash Type : octet string
  1500. Status = ParseIdAndLength(&current_ptr, end_of_single_responses, DER_ENCODING_OCTET_STRING_ID, &length, &EncodingBytes, FALSE);
  1501. if(Status != X509_STATUS_SUCCESS)
  1502. break;
  1503. SingleResponse->issuerKeyHash.buffer = current_ptr;
  1504. SingleResponse->issuerKeyHash.length = length;
  1505. current_ptr+=length;
  1506. // Next Field: SerialNumber Type : Integer */
  1507. Status = ParseInteger(&current_ptr, end_of_single_responses, &SingleResponse->serialNumber, FALSE, TRUE, &padding);
  1508. if(Status != X509_STATUS_SUCCESS || (SingleResponse->serialNumber.length + padding > MAX_HASH_LEN)){
  1509. DBG_ASSERT(0);
  1510. Status = X509_STATUS_ENCODING_ERROR;
  1511. break;
  1512. }
  1513. // Next field: CertStatus certStatus can be a choice of { good [type : NULL], revoked [type : revoked info], unknown [type : NULL]
  1514. switch(*current_ptr)
  1515. {
  1516. case IMPLICIT_TAG_ID + TAG_NUMBER_GOOD:
  1517. SingleResponse->ocspCertificateStatus = good;
  1518. current_ptr++;
  1519. /* NULL id is always followed by length 0x00 */
  1520. if(*current_ptr != 0)
  1521. {
  1522. DBG_ASSERT(0);
  1523. return X509_STATUS_ENCODING_ERROR;
  1524. }
  1525. current_ptr++;
  1526. break;
  1527. case IMPLICIT_TAG_ID + TAG_NUMBER_UNKNOWN:
  1528. SingleResponse->ocspCertificateStatus = unknown;
  1529. current_ptr++;
  1530. /* NULL id is always followed by length 0x00 */
  1531. if(*current_ptr != 0)
  1532. {
  1533. DBG_ASSERT(0);
  1534. return X509_STATUS_ENCODING_ERROR;
  1535. }
  1536. current_ptr++;
  1537. break;
  1538. case IMPLICIT_TAG_STRUCTURED_TYPE_ID + TAG_NUMBER_REVOKED:
  1539. SingleResponse->ocspCertificateStatus = revoked;
  1540. /* This will be followed by a revoked time and reason.
  1541. We parse but ignore those fields
  1542. */
  1543. current_ptr++;
  1544. /* Get length */
  1545. Status = DecodeLength(current_ptr, end_of_single_responses, &length, &EncodingBytes);
  1546. if(Status != X509_STATUS_SUCCESS)
  1547. break;
  1548. current_ptr += EncodingBytes;
  1549. /* Move current_ptr beyond the revoked data */
  1550. current_ptr +=length;
  1551. break;
  1552. default:
  1553. DBG_ASSERT(0);
  1554. return X509_STATUS_ENCODING_ERROR;
  1555. }
  1556. if(Status != X509_STATUS_SUCCESS)
  1557. break;
  1558. // Next Field : ThisUpdate type: GeneralizedTime
  1559. Status = ParseTime(&current_ptr, end_of_single_responses, &SingleResponse->thisUpdate);
  1560. if(Status != X509_STATUS_SUCCESS)
  1561. break;
  1562. /* Next Field : NextUpdate [optional] */
  1563. Status = ParseIdAndLength(&current_ptr, end_of_single_responses, EXPLICIT_TAG_ID + TAG_NUMBER_NEXT_UPDATE, &length, &EncodingBytes, TRUE);
  1564. if(Status != X509_STATUS_SUCCESS && Status != X509_STATUS_NOT_FOUND)
  1565. break;
  1566. if(Status != X509_STATUS_NOT_FOUND){
  1567. Status = ParseTime(&current_ptr, end_of_single_responses, &SingleResponse->nextUpdate);
  1568. if(Status != X509_STATUS_SUCCESS)
  1569. break;
  1570. }
  1571. /* INTERESTING CASE: Both singleExtensions and responseExtensions use the tag [1]. So at this point, there is no way of finding out if "A1" means Single or response Extentions.
  1572. We check the end of sequence pointer to resolve this.
  1573. */
  1574. if(current_ptr < end_of_single_responses){
  1575. // Next Field : Single Extensions [optional] we parse this but ignore the contents
  1576. Status = ParseIdAndLength(&current_ptr, end_of_single_responses, EXPLICIT_TAG_ID + TAG_NUMBER_SINGLE_EXTENSIONS, &length, &EncodingBytes, TRUE);
  1577. if(Status != X509_STATUS_SUCCESS && Status != X509_STATUS_NOT_FOUND)
  1578. break;
  1579. if(Status != X509_STATUS_NOT_FOUND){
  1580. /* Move pointer past the extensions */
  1581. current_ptr +=length;
  1582. }
  1583. }
  1584. SingleResponse = (SessMgrOcspSingleResponse *)((UINT8 *)SingleResponse + sizeof(SessMgrOcspSingleResponse));
  1585. OcspResponseFields->numberOfSingleReponses++;
  1586. Status = X509_STATUS_SUCCESS;
  1587. }
  1588. if(Status != X509_STATUS_SUCCESS){
  1589. DBG_ASSERT(0);
  1590. Status = X509_STATUS_ENCODING_ERROR;
  1591. break;
  1592. }
  1593. #ifdef PRINT
  1594. int i;
  1595. printf("\n Number of single responses %d", OcspResponseFields->numberOfSingleReponses);
  1596. for (i=0;i<OcspResponseFields->numberOfSingleReponses;i++){
  1597. printf("\n\n Response Number %d", i);
  1598. SingleResponse = (SessMgrOcspSingleResponse *)(OcspResponseFields->allResponses) + i;
  1599. printf("\n serial number ");
  1600. PrintDataBuffer(&SingleResponse->serialNumber);
  1601. #ifdef TIME_PRINT
  1602. printf("\n This Update ");
  1603. PrintValidity(&SingleResponse->thisUpdate);
  1604. #endif
  1605. }
  1606. #endif
  1607. // Next Field : Response Extensions [optional]
  1608. Status = ParseIdAndLength(&current_ptr, OcspResponseEnd, EXPLICIT_TAG_ID + TAG_NUMBER_RESPONSE_EXTENSIONS, &length, &EncodingBytes, TRUE);
  1609. if(Status != X509_STATUS_SUCCESS && Status != X509_STATUS_NOT_FOUND)
  1610. break;
  1611. if(Status != X509_STATUS_NOT_FOUND){
  1612. // Move pointer past the extensions
  1613. Status = ParseOcspExtensions(&current_ptr, current_ptr + length, OcspResponseFields);
  1614. if(Status != X509_STATUS_SUCCESS){
  1615. break;
  1616. }
  1617. }
  1618. // Next field : Signature Algorithm Id*/
  1619. Status = ParseAlgoIdentifier(&current_ptr, OcspResponseEnd, (UINT32 *)&OcspResponseFields->algorithmIdentifierForSignature ,signature_algo, &params);
  1620. if(Status != X509_STATUS_SUCCESS)
  1621. break;
  1622. Status = ParseSignatureValue(&current_ptr, OcspResponseEnd, &workBuffer, workBufferSize - (int)(workBuffer - workBufferStart), &OcspResponseFields->signature, OcspResponseFields->algorithmIdentifierForSignature);
  1623. if(Status != X509_STATUS_SUCCESS)
  1624. break;
  1625. // Next field : Certificate of the OCSP responder. This can be a chain */
  1626. // ??? why is this optional
  1627. Status = ParseIdAndLength(&current_ptr, OcspResponseEnd, EXPLICIT_TAG_ID + TAG_NUMBER_CERTS, &length, &EncodingBytes, TRUE);
  1628. if(Status != X509_STATUS_SUCCESS && Status != X509_STATUS_NOT_FOUND)
  1629. break;
  1630. if(Status != X509_STATUS_NOT_FOUND){
  1631. /* This is a sequence of certificates. */
  1632. Status = ParseIdAndLength(&current_ptr, OcspResponseEnd, DER_ENCODING_SEQUENCE_ID, &length, &EncodingBytes, FALSE);
  1633. if(Status != X509_STATUS_SUCCESS)
  1634. break;
  1635. OcspResponseFields->responderCertificate.buffer = current_ptr;
  1636. OcspResponseFields->responderCertificate.length = length;
  1637. current_ptr += length;
  1638. }
  1639. }while(0);
  1640. DBG_ASSERT(Status == X509_STATUS_SUCCESS);
  1641. if (current_ptr != OcspResponseEnd) {
  1642. DBG_ASSERT(0)
  1643. return X509_STATUS_ENCODING_ERROR;
  1644. }
  1645. return Status;
  1646. }
  1647. #endif
  1648. /* Common functions */
  1649. #ifndef X509_FOR_PSE_PR
  1650. static STATUS ParseBoolean(UINT8 **ppCurrent, UINT8 *pEnd, BOOL* Value, BOOL optional)
  1651. {
  1652. STATUS Status;
  1653. UINT8 *current_ptr = *ppCurrent;
  1654. UINT8 EncodingBytes;
  1655. UINT32 length;
  1656. Status = ParseIdAndLength(&current_ptr, pEnd, DER_ENCODING_BOOLEAN_ID, &length, &EncodingBytes, optional);
  1657. if(Status == X509_STATUS_NOT_FOUND && optional == TRUE)
  1658. return X509_STATUS_NOT_FOUND;
  1659. if(Status != X509_STATUS_SUCCESS || length != 1){
  1660. Status = X509_STATUS_ENCODING_ERROR;
  1661. return Status;
  1662. }
  1663. *Value = *current_ptr;
  1664. current_ptr++;
  1665. /* we expect Status to be 0xFF or 0x00 */
  1666. if( (*Value != DER_ENCODING_TRUE) && (*Value != DER_ENCODING_FALSE))
  1667. return X509_STATUS_ENCODING_ERROR;
  1668. *ppCurrent = current_ptr;
  1669. return X509_STATUS_SUCCESS;
  1670. }
  1671. #endif
  1672. /* ParseInteger will strip out the integer encoding part. If parsing is successful, ParseInteger
  1673. will update the current pointer and length
  1674. Returns X509_ENCODING_ERROR on failure
  1675. */
  1676. static STATUS ParseInteger(UINT8 **ppCurrent, UINT8 *pEnd, SessMgrDataBuffer* DataBuf, BOOL isOptional, BOOL MustBePositive, UINT32 *PaddingLen)
  1677. {
  1678. STATUS Status;
  1679. UINT8 *current_ptr = *ppCurrent;
  1680. UINT32 Integer_Length;
  1681. UINT8 EncodingBytes;
  1682. UINT32 PaddingCounter = 0;
  1683. Status = ParseIdAndLength(&current_ptr, pEnd, DER_ENCODING_INTEGER_ID, &Integer_Length, &EncodingBytes, isOptional);
  1684. if(isOptional == TRUE && Status == X509_STATUS_NOT_FOUND)
  1685. return X509_STATUS_NOT_FOUND;
  1686. if(Status != X509_STATUS_SUCCESS)
  1687. return X509_STATUS_ENCODING_ERROR;
  1688. // MSB must be zero for positive integer. Error if MSB is not zero and we expect positive
  1689. if(MustBePositive && (*current_ptr & 0x80))
  1690. return X509_STATUS_ENCODING_ERROR;
  1691. // Note : DER Integer Encoding adds 0x00 if MSB of the actual integer is one. Ignore the first byte if it is 0x00
  1692. if ((*current_ptr == 0) && (Integer_Length > 1)){
  1693. current_ptr++; // skip padding
  1694. Integer_Length--; // remove padding from length
  1695. PaddingCounter++;
  1696. }
  1697. DataBuf->buffer = current_ptr;
  1698. DataBuf->length = Integer_Length;
  1699. *ppCurrent = current_ptr + Integer_Length;
  1700. if (PaddingLen)
  1701. *PaddingLen = PaddingCounter;
  1702. return X509_STATUS_SUCCESS;
  1703. }
  1704. #ifndef X509_FOR_PSE_PR
  1705. STATUS ParseOcspExtensions(UINT8 **ppCurrent, UINT8 *pEnd, SessMgrOcspResponseFields* OcspResponseFields)
  1706. {
  1707. UINT8 *current_ptr = *ppCurrent;
  1708. UINT32 ExtensionType;
  1709. BOOL critical;
  1710. UINT32 length;
  1711. STATUS Status;
  1712. UINT8 EncodingBytes;
  1713. do{
  1714. // Extensions = SEQ { extension } Each extension is associated with a Object ID. We support the extensions listed in ExtensionOID array.
  1715. Status = ParseIdAndLength(&current_ptr, pEnd, DER_ENCODING_SEQUENCE_ID, &length, &EncodingBytes, FALSE);
  1716. if(Status != X509_STATUS_SUCCESS)
  1717. break;
  1718. while(current_ptr < pEnd){
  1719. // Each extension is a SEQ { extid (OID) , critical (BOOLEAN), extnValue (OCTET STRING) }
  1720. Status = ParseIdAndLength(&current_ptr, pEnd, DER_ENCODING_SEQUENCE_ID, &length, &EncodingBytes, FALSE);
  1721. if(Status != X509_STATUS_SUCCESS)
  1722. break;
  1723. /* Next Field : Extension OID */
  1724. Status = ParseOID(&current_ptr, pEnd, &ExtensionType, &OcspExtensionOid[0][0],
  1725. sizeof(OcspExtensionOid)/sizeof(OcspExtensionOid[0]),
  1726. sizeof(OcspExtensionOid[0]));
  1727. // Note : We might have unsupported extensions.
  1728. if(Status != X509_STATUS_SUCCESS && Status != X509_STATUS_UNKNOWN_OID){
  1729. DBG_ASSERT(0);
  1730. break;
  1731. }
  1732. // Next field is "Critical". This indicates whether it is mandatory for the parser to understand the extension. This is an optinal field. default is false
  1733. Status = ParseBoolean(&current_ptr, pEnd, &critical, TRUE);
  1734. if(Status != X509_STATUS_SUCCESS && Status != X509_STATUS_NOT_FOUND)
  1735. break;
  1736. if(Status == X509_STATUS_NOT_FOUND)
  1737. critical = DER_ENCODING_FALSE;
  1738. // Next Field: Extn Value This is a OCTET STRING
  1739. Status = ParseIdAndLength(&current_ptr, pEnd, DER_ENCODING_OCTET_STRING_ID, &length, &EncodingBytes, FALSE);
  1740. if(Status != X509_STATUS_SUCCESS)
  1741. break;
  1742. switch(ExtensionType)
  1743. {
  1744. case Nonce:
  1745. // Some OCSP responders have an additional encoding of OCTET string for the nonce.
  1746. // We know the Nonce is 32 bytes (Per Sigma Spec. If given length is more than that, then check if this extra encoding was included.
  1747. if(length > SIGMA_NONCE_LENGTH){
  1748. Status = ParseIdAndLength(&current_ptr, pEnd, DER_ENCODING_OCTET_STRING_ID, &length, &EncodingBytes, FALSE);
  1749. if(Status != X509_STATUS_SUCCESS)
  1750. break;
  1751. }
  1752. DBG_ASSERT(length == SIGMA_NONCE_LENGTH);
  1753. OcspResponseFields->nonce.buffer = current_ptr;
  1754. OcspResponseFields->nonce.length = length;
  1755. current_ptr+=length;
  1756. break;
  1757. default:
  1758. /* unsupported extension.
  1759. Check if it marked as critical. If so, return error else ignore this extension
  1760. */
  1761. if(critical == DER_ENCODING_TRUE){
  1762. DBG_ASSERT(0);
  1763. Status = X509_STATUS_UNSUPPORTED_CRITICAL_EXTENSION;
  1764. break;
  1765. }
  1766. else{
  1767. /* Extension is non-criticial. So it is ok if we dont support it .
  1768. Move current pointer to the next extension */
  1769. current_ptr += length;
  1770. continue;
  1771. }
  1772. } // switch
  1773. if(Status != X509_STATUS_SUCCESS){
  1774. DBG_ASSERT(0);
  1775. break;
  1776. }
  1777. Status = X509_STATUS_SUCCESS;
  1778. } // WHILE end of extensions
  1779. }while(0); // do_while
  1780. *ppCurrent = current_ptr;
  1781. return Status;
  1782. }
  1783. #endif
  1784. #ifndef X509_FOR_PSE_PR
  1785. STATUS ParseCertExtensions(UINT8 **ppCurrent, UINT8 *pEnd, SessMgrCertificateFields* certificateFields)
  1786. {
  1787. UINT8 *current_ptr = *ppCurrent;
  1788. UINT32 ExtensionType;
  1789. BOOL critical;
  1790. UINT32 length;
  1791. STATUS Status;
  1792. TAG_TYPE TagType;
  1793. UINT8 EncodingBytes;
  1794. UINT8 PaddedBits;
  1795. SessMgrDataBuffer DataBuf;
  1796. UINT32 ExtendedKeyUsageOcspType;
  1797. do{
  1798. // Extensions = SEQ { extension } Each extension is associated with a Object ID. We support the extensions listed in ExtensionOID array.
  1799. Status = ParseIdAndLength(&current_ptr, pEnd, DER_ENCODING_SEQUENCE_ID, &length, &EncodingBytes, FALSE);
  1800. if(Status != X509_STATUS_SUCCESS)
  1801. break;
  1802. while(current_ptr < pEnd){
  1803. // Each extension is a SEQ { extid (OID) , critical (BOOLEAN), extnValue (OCTET STRING) }
  1804. Status = ParseIdAndLength(&current_ptr, pEnd, DER_ENCODING_SEQUENCE_ID, &length, &EncodingBytes, FALSE);
  1805. if(Status != X509_STATUS_SUCCESS)
  1806. break;
  1807. /* Next Field : Extension OID */
  1808. Status = ParseOID(&current_ptr, pEnd, &ExtensionType, &CertExtensionOid[0][0],
  1809. sizeof(CertExtensionOid)/sizeof(CertExtensionOid[0]),
  1810. sizeof(CertExtensionOid[0]));
  1811. // Note : We might have unsupported extensions.
  1812. if(Status != X509_STATUS_SUCCESS && Status != X509_STATUS_UNKNOWN_OID){
  1813. DBG_ASSERT(0);
  1814. break;
  1815. }
  1816. // Next field is "Critical". This indicates whether it is mandatory for the parser to understand the extension. This is an optinal field. default is false
  1817. Status = ParseBoolean(&current_ptr, pEnd, &critical, TRUE);
  1818. if(Status != X509_STATUS_SUCCESS && Status != X509_STATUS_NOT_FOUND)
  1819. break;
  1820. if(Status == X509_STATUS_NOT_FOUND)
  1821. critical = DER_ENCODING_FALSE;
  1822. // Next Field: Extn Value This is a OCTET STRING
  1823. Status = ParseIdAndLength(&current_ptr, pEnd, DER_ENCODING_OCTET_STRING_ID, &length, &EncodingBytes, FALSE);
  1824. if(Status != X509_STATUS_SUCCESS)
  1825. break;
  1826. switch(ExtensionType)
  1827. {
  1828. case AuthorityKeyId:
  1829. /* Authority ID is a SEQ of {KeyIdentifier [optional TAG 0] , General Names [optional Tag 1], Certificate Serial number [optional Tag 2] */
  1830. /* Currently supported Intel and CA certs have general names and Certificate serial numbers as NULL */
  1831. Status = ParseIdAndLength(&current_ptr, pEnd, DER_ENCODING_SEQUENCE_ID, &length, &EncodingBytes, FALSE);
  1832. if(Status != X509_STATUS_SUCCESS)
  1833. break;
  1834. /* See if optional arguments are present */
  1835. // Note: InvalidTag means either the tag was not found (not an error if the field is optional) or the tag was not recognized.
  1836. FIND_TAG_TYPE(current_ptr, TAG_NUMBER_AUTHORITY_KEY_ID, TagType);
  1837. if(TagType != invalid_tag){
  1838. /* We have an implicit or explicit tag */
  1839. current_ptr++;
  1840. /* Get Length of sequence */
  1841. Status = DecodeLength(current_ptr, pEnd, &length, &EncodingBytes);
  1842. if(Status != X509_STATUS_SUCCESS)
  1843. break;
  1844. current_ptr += EncodingBytes;
  1845. if(TagType == explicit_tag){
  1846. Status = ParseIdAndLength(&current_ptr, pEnd, DER_ENCODING_OCTET_STRING_ID, &length, &EncodingBytes, FALSE);
  1847. if(Status != X509_STATUS_SUCCESS)
  1848. break;
  1849. }
  1850. /* Store the Authority Key ID into the data buffer */
  1851. certificateFields->AuthorityKeyId.buffer = current_ptr;
  1852. certificateFields->AuthorityKeyId.length = length;
  1853. current_ptr+=length;
  1854. }
  1855. FIND_TAG_TYPE(current_ptr, TAG_NUMBER_AUTHORITY_CERT_ISSUER_ID, TagType);
  1856. if(TagType != invalid_tag){
  1857. current_ptr++;
  1858. Status = DecodeLength(current_ptr, pEnd, &length, &EncodingBytes);
  1859. if(Status != X509_STATUS_SUCCESS)
  1860. break;
  1861. current_ptr += EncodingBytes;
  1862. if(TagType == explicit_tag){
  1863. /* Expecting a NULL. Encoding for NULL is 0x05 0x00 */
  1864. Status = ParseIdAndLength(&current_ptr, pEnd, DER_ENCODING_NULL_ID, &length, &EncodingBytes, FALSE);
  1865. if(Status != X509_STATUS_SUCCESS || length !=0)
  1866. break;
  1867. }
  1868. }
  1869. FIND_TAG_TYPE(current_ptr, TAG_NUMBER_AUTHORITY_CERT_SERIAL_NUMBER_ID, TagType);
  1870. if(TagType != invalid_tag){
  1871. current_ptr++;
  1872. Status = DecodeLength(current_ptr, pEnd, &length, &EncodingBytes);
  1873. if(Status != X509_STATUS_SUCCESS)
  1874. break;
  1875. current_ptr += EncodingBytes;
  1876. if(TagType == explicit_tag){
  1877. /* Expecting a NULL. Encoding for NULL is 0x05 0x00 */
  1878. Status = ParseIdAndLength(&current_ptr, pEnd, DER_ENCODING_NULL_ID, &length, &EncodingBytes, FALSE);
  1879. if(Status != X509_STATUS_SUCCESS || length !=0)
  1880. break;
  1881. }
  1882. }
  1883. break;
  1884. case SubjectKeyId:
  1885. // Next Field: Extn Value This is a OCTET STRING
  1886. Status = ParseIdAndLength(&current_ptr, pEnd, DER_ENCODING_OCTET_STRING_ID, &length, &EncodingBytes, FALSE);
  1887. if(Status != X509_STATUS_SUCCESS)
  1888. break;
  1889. /* Store the Subject Key ID into the data buffer */
  1890. certificateFields->SubjectKeyId.buffer = current_ptr;
  1891. certificateFields->SubjectKeyId.length = length;
  1892. current_ptr+=length;
  1893. break;
  1894. case KeyUsage:
  1895. /* KeyUsage is a bit string */
  1896. Status = ParseIdAndLength(&current_ptr, pEnd, DER_ENCODING_BIT_STRING_ID, &length, &EncodingBytes, FALSE);
  1897. if(Status != X509_STATUS_SUCCESS)
  1898. break;
  1899. /* KeyUsage is defined as a 16 bit value.So we expect the length to be 1 or 2. Add 1 to the check to account for the byte containing the number of bits paddd */
  1900. if(length != 2 && length != 3){
  1901. DBG_ASSERT(0);
  1902. Status = X509_STATUS_ENCODING_ERROR;
  1903. break;
  1904. }
  1905. /* current_ptr is pointing to the padded bits */
  1906. PaddedBits = *current_ptr;
  1907. current_ptr++;
  1908. /* decrementing length by one because length included the padded bits octet that we have already parsed*/
  1909. length--;
  1910. if(length == 2){
  1911. certificateFields->keyUsage.value = *current_ptr;
  1912. /* Shift by 8 */
  1913. certificateFields->keyUsage.value = certificateFields->keyUsage.value << 8;
  1914. current_ptr++;
  1915. }
  1916. certificateFields->keyUsage.value = *current_ptr;
  1917. current_ptr++;
  1918. break;
  1919. case ExtendedKeyUsage:
  1920. /* ExtendedKeyUsage is a sequence of KeyPurposeId's */
  1921. Status = ParseIdAndLength(&current_ptr, pEnd, DER_ENCODING_SEQUENCE_ID, &length, &EncodingBytes, FALSE);
  1922. if(Status != X509_STATUS_SUCCESS)
  1923. break;
  1924. // KeyPurposeId is a object identifier
  1925. Status = ParseOID(&current_ptr, pEnd, &ExtendedKeyUsageOcspType, &ExtendedKeyUsageOcspSignOid[0][0],
  1926. sizeof(ExtendedKeyUsageOcspSignOid)/sizeof(ExtendedKeyUsageOcspSignOid[0]),
  1927. sizeof(ExtendedKeyUsageOcspSignOid[0]));
  1928. if(Status != X509_STATUS_SUCCESS)
  1929. break;
  1930. /* we only support OcspSign in Extended key usage */
  1931. if(ExtendedKeyUsageOcspType != 0){
  1932. DBG_ASSERT(0);
  1933. Status = X509_STATUS_UNSUPPORTED_TYPE;
  1934. break;
  1935. }else{
  1936. certificateFields->ExtendedKeyUsage.usage.OCSPSign = 1;
  1937. }
  1938. break;
  1939. case BasicConstraint:
  1940. /* Basic constraint is a SEQ { BOOLEAN (default false) , Integer [optional] */
  1941. certificateFields->basicConstraint.isBasicConstraintPresent = TRUE;
  1942. Status = ParseIdAndLength(&current_ptr, pEnd, DER_ENCODING_SEQUENCE_ID, &length, &EncodingBytes, FALSE);
  1943. if(Status != X509_STATUS_SUCCESS)
  1944. break;
  1945. /* Next is a optional field for boolean */
  1946. Status = ParseBoolean(&current_ptr, pEnd, &certificateFields->basicConstraint.isCa, TRUE);
  1947. if(Status != X509_STATUS_SUCCESS && Status != X509_STATUS_NOT_FOUND)
  1948. break;
  1949. if(Status == X509_STATUS_NOT_FOUND)
  1950. certificateFields->basicConstraint.isCa = DER_ENCODING_FALSE;
  1951. // Next field is PathLenConstraint [Integer optional]
  1952. Status = ParseInteger(&current_ptr, pEnd, &DataBuf, TRUE, FALSE, NULL);
  1953. if(Status != X509_STATUS_SUCCESS && Status != X509_STATUS_NOT_FOUND )
  1954. break;
  1955. if(Status == X509_STATUS_NOT_FOUND)
  1956. certificateFields->basicConstraint.pathLenConstraint = 0xFF;
  1957. else{
  1958. Status = swapendian_memcpy((UINT8 *)&certificateFields->basicConstraint.pathLenConstraint,
  1959. sizeof(UINT32),
  1960. DataBuf.buffer, DataBuf.length);
  1961. if(Status != X509_STATUS_SUCCESS)
  1962. break;
  1963. }
  1964. Status = X509_STATUS_SUCCESS;
  1965. break;
  1966. case CertificatePolicy:
  1967. Status = ParseCertificatePolicy(&current_ptr, pEnd, &certificateFields->CertificatePolicy);
  1968. break;
  1969. case ProductType:
  1970. /* Product type is a enumerated type */
  1971. Status = ParseIdAndLength(&current_ptr, pEnd, DER_ENCODING_ENUMERATED_ID, &length, &EncodingBytes, FALSE);
  1972. if(Status != X509_STATUS_SUCCESS || length != 1)
  1973. {
  1974. Status = X509_STATUS_ENCODING_ERROR;
  1975. break;
  1976. }
  1977. certificateFields->productType = (SessMgrProductType)*current_ptr;
  1978. current_ptr++;
  1979. break;
  1980. default:
  1981. /* unsupported extension.
  1982. Check if it marked as critical. If so, return error else ignore this extension
  1983. */
  1984. if(critical == DER_ENCODING_TRUE){
  1985. DBG_ASSERT(0);
  1986. Status = X509_STATUS_UNSUPPORTED_CRITICAL_EXTENSION;
  1987. break;
  1988. }
  1989. else{
  1990. /* Extension is non-criticial. So it is ok if we dont support it .
  1991. Move current pointer to the next extension */
  1992. current_ptr += length;
  1993. continue;
  1994. }
  1995. } // switch
  1996. if(Status != X509_STATUS_SUCCESS){
  1997. DBG_ASSERT(0);
  1998. break;
  1999. }
  2000. Status = X509_STATUS_SUCCESS;
  2001. } // WHILE end of extensions
  2002. }while(0);
  2003. DBG_ASSERT(Status == X509_STATUS_SUCCESS);
  2004. *ppCurrent = current_ptr;
  2005. return Status;
  2006. }
  2007. /* Certificate Policy is a SEQ of Policy Information.
  2008. Policy information is Seq of {Policy Identifier, Policy Qualifier [optional] }
  2009. Policy Identifier is a Object ID
  2010. Policy Qualifier Info is Seq {PolicyqualifierId, qualifier }
  2011. PolicyqualifierId is a known Object id
  2012. Qualifier is a CHOICE{cPSuri, UserNotice}
  2013. we only support cpSuri which is a IA5string
  2014. */
  2015. static STATUS ParseCertificatePolicy(UINT8 **ppCurrent, UINT8 *pEnd, SessMgrDataBuffer *CertificatePolicy)
  2016. {
  2017. UINT8 *current_ptr = *ppCurrent;
  2018. UINT32 length;
  2019. UINT8* end_of_PolicyInformation = NULL;
  2020. UINT32 temp;
  2021. STATUS Status;
  2022. UINT8 EncodingBytes;
  2023. do{
  2024. /* Certificate Policy is a SEQ of Policy Information */
  2025. Status = ParseIdAndLength(&current_ptr, pEnd, DER_ENCODING_SEQUENCE_ID, &length, &EncodingBytes, FALSE);
  2026. if(Status != X509_STATUS_SUCCESS)
  2027. break;
  2028. end_of_PolicyInformation = current_ptr + length;
  2029. while(current_ptr < end_of_PolicyInformation){
  2030. /* Policy information is Seq of {Policy Identifier, Policy Qualifier [optional] */
  2031. Status = ParseIdAndLength(&current_ptr, end_of_PolicyInformation, DER_ENCODING_SEQUENCE_ID, &length, &EncodingBytes, FALSE);
  2032. if(Status != X509_STATUS_SUCCESS)
  2033. break;
  2034. // Policy Identifier is a Object ID
  2035. Status = ParseOID(&current_ptr, end_of_PolicyInformation, &temp, &CertificatePolicyOid[0][0],
  2036. sizeof(CertificatePolicyOid)/sizeof(CertificatePolicyOid[0]),
  2037. sizeof(CertificatePolicyOid[0]));
  2038. if(Status != X509_STATUS_SUCCESS)
  2039. break;
  2040. if(temp >= Max_Certificatepolicy){
  2041. /* this is a unsupported policy. Ignore */
  2042. current_ptr+= length;
  2043. continue;
  2044. }
  2045. /* We have a supported policy !!!! */
  2046. // Next Field: PolicyQualifiers PolicyQualifiers is a SEQ of Policy Qualifier Info. However, we only support one Policy Qualifier Info
  2047. Status = ParseIdAndLength(&current_ptr, end_of_PolicyInformation, DER_ENCODING_SEQUENCE_ID, &length, &EncodingBytes, FALSE);
  2048. if(Status != X509_STATUS_SUCCESS)
  2049. break;
  2050. Status = ParseIdAndLength(&current_ptr, end_of_PolicyInformation, DER_ENCODING_SEQUENCE_ID, &length, &EncodingBytes, FALSE);
  2051. if(Status != X509_STATUS_SUCCESS)
  2052. break;
  2053. Status = ParseOID(&current_ptr, end_of_PolicyInformation, &temp, &CertificatePolicyQualifierIdOid[0][0],
  2054. sizeof(CertificatePolicyQualifierIdOid)/sizeof(CertificatePolicyQualifierIdOid[0]),
  2055. sizeof(CertificatePolicyQualifierIdOid[0]));
  2056. if(Status != X509_STATUS_SUCCESS)
  2057. break;
  2058. if(temp >= Max_Certificatepolicy){
  2059. Status = X509_STATUS_ENCODING_ERROR;
  2060. break;
  2061. }
  2062. // we have a supported policy qualifier id. Qualifier can be a CHOICE{cPSuri, UserNotice}. Note : Parser only supports cPSuri
  2063. Status = ParseIdAndLength(&current_ptr, end_of_PolicyInformation, DER_ENCODING_IA5_STRING_ID, &length, &EncodingBytes, FALSE);
  2064. if(Status != X509_STATUS_SUCCESS)
  2065. break;
  2066. CertificatePolicy->buffer = current_ptr;
  2067. CertificatePolicy->length = length;
  2068. current_ptr +=length;
  2069. }
  2070. }while(0);
  2071. DBG_ASSERT(Status == X509_STATUS_SUCCESS);
  2072. *ppCurrent = current_ptr;
  2073. return Status;
  2074. }
  2075. #endif
  2076. static STATUS ParseSubjectPublicKeyInfo(UINT8 **ppCurrent, UINT8 *pEnd, UINT8 **pworkbuffer, SessMgrCertificateFields* certificateFields)
  2077. {
  2078. UINT8 *current_ptr = *ppCurrent;
  2079. UINT8 *workbuffer_ptr = *pworkbuffer;
  2080. UINT32 length;
  2081. SessMgrEllipticCurveParameter params = unknownParameter;
  2082. STATUS Status;
  2083. UINT8 EncodingBytes;
  2084. SessMgrDataBuffer* Key;
  2085. SessMgrPublicKeyAlgoType* KeyType;
  2086. /* Subject public key consist of a Algo Identifier and a BIT String containing the actual key */
  2087. Key = &certificateFields->subjectPublicKey;
  2088. KeyType = &certificateFields->algorithmIdentifierForSubjectPublicKey;
  2089. do{
  2090. Status = ParseIdAndLength(&current_ptr, pEnd, DER_ENCODING_SEQUENCE_ID, &length, &EncodingBytes, FALSE);
  2091. if(Status != X509_STATUS_SUCCESS)
  2092. break;
  2093. /* We first get the algo identifier */
  2094. Status = ParseAlgoIdentifier(&current_ptr, pEnd, (UINT32*)KeyType, PublicKey_algo, &params);
  2095. if(Status != X509_STATUS_SUCCESS)
  2096. break;
  2097. /* Next is the Subject Public Key. It is a BIT string. */
  2098. Status = ParseIdAndLength(&current_ptr, pEnd, DER_ENCODING_BIT_STRING_ID, &length, &EncodingBytes, FALSE);
  2099. if(Status != X509_STATUS_SUCCESS)
  2100. break;
  2101. /* current_ptr is over the number of padding bits for the BIT string . We expect this to always be zero since we are not dealing with bit level data */
  2102. if(*current_ptr != 0x00){
  2103. DBG_ASSERT(0);
  2104. return X509_STATUS_ENCODING_ERROR;
  2105. }
  2106. current_ptr++;
  2107. certificateFields->EncodedSubjectPublicKey.buffer = current_ptr;
  2108. certificateFields->EncodedSubjectPublicKey.length = length - 1;
  2109. switch(*KeyType)
  2110. {
  2111. case X509_ecdsaPublicKey:
  2112. // for ecdsa we know the length should be 66 bytes.
  2113. if(length != 66){
  2114. Status = X509_STATUS_ENCODING_ERROR;
  2115. break;
  2116. }
  2117. Key->buffer = workbuffer_ptr;
  2118. Key->length = sizeof(SessMgrEcdsaPublicKey);
  2119. workbuffer_ptr += sizeof(SessMgrEcdsaPublicKey);
  2120. Status = ParseEcdsaPublicKey(&current_ptr, pEnd, (SessMgrEcdsaPublicKey * )(Key->buffer), (SessMgrEllipticCurveParameter)params);
  2121. break;
  2122. case X509_intel_sigma_epidGroupPublicKey_epid11:
  2123. Key->buffer = workbuffer_ptr;
  2124. Key->length = sizeof(SessMgrEpidGroupPublicKey);
  2125. workbuffer_ptr += sizeof(SessMgrEpidGroupPublicKey);
  2126. Status = ParseEpidPublicKey(&current_ptr, pEnd, (SessMgrEpidGroupPublicKey * )(Key->buffer));
  2127. #ifdef PRINT
  2128. PrintEpidKey((void *)Key->buffer);
  2129. #endif
  2130. break;
  2131. case X509_rsaPublicKey:
  2132. Key->buffer = workbuffer_ptr;
  2133. Key->length = sizeof(SessMgrRsaKey);
  2134. workbuffer_ptr += sizeof(SessMgrRsaKey);
  2135. Status = ParseRsaPublicKey(&current_ptr, pEnd, (SessMgrRsaKey * )(Key->buffer));
  2136. break;
  2137. default:
  2138. DBG_ASSERT(0);
  2139. }
  2140. }while(0);
  2141. if(Status == X509_STATUS_SUCCESS){
  2142. *pworkbuffer = workbuffer_ptr;
  2143. *ppCurrent = current_ptr;
  2144. }
  2145. DBG_ASSERT(Status == X509_STATUS_SUCCESS);
  2146. return Status;
  2147. }
  2148. static STATUS ParseRsaPublicKey(UINT8 **ppCurrent, UINT8 *pEnd, SessMgrRsaKey * RsaKey)
  2149. {
  2150. UINT8 *current_ptr = *ppCurrent;
  2151. UINT32 length;
  2152. STATUS Status;
  2153. UINT8 EncodingBytes;
  2154. /* The data portion of the BIT string contains a sequence of Seq { n , e} where n and e are integers */
  2155. Status = ParseIdAndLength(&current_ptr, pEnd, DER_ENCODING_SEQUENCE_ID, &length, &EncodingBytes, FALSE);
  2156. if(Status != X509_STATUS_SUCCESS){
  2157. DBG_ASSERT(0);
  2158. return X509_STATUS_ENCODING_ERROR;
  2159. }
  2160. Status = ParseInteger(&current_ptr, pEnd, &RsaKey->n, FALSE, FALSE, NULL);
  2161. if(Status != X509_STATUS_SUCCESS)
  2162. return X509_STATUS_ENCODING_ERROR;
  2163. Status = ParseInteger(&current_ptr, pEnd, &RsaKey->e, FALSE, FALSE, NULL);
  2164. if(Status != X509_STATUS_SUCCESS)
  2165. return X509_STATUS_ENCODING_ERROR;
  2166. *ppCurrent = current_ptr;
  2167. return X509_STATUS_SUCCESS;
  2168. }
  2169. static STATUS ParseEpidPublicKey(UINT8 **ppCurrent, UINT8 *pEnd, SessMgrEpidGroupPublicKey * EpidKey)
  2170. {
  2171. UINT8 *current_ptr = *ppCurrent;
  2172. UINT32 length;
  2173. SessMgrDataBuffer DataBuf;
  2174. STATUS Status;
  2175. UINT8 EncodingBytes;
  2176. do{
  2177. /* We are expecting a sequence of {groupId [Integer], h1 [ECPoint], h2 [ECPoint], w [G2ECPoint] */
  2178. Status = ParseIdAndLength(&current_ptr, pEnd, DER_ENCODING_SEQUENCE_ID, &length, &EncodingBytes, FALSE);
  2179. if(Status != X509_STATUS_SUCCESS)
  2180. break;
  2181. /* Parse Integer */
  2182. Status = ParseInteger(&current_ptr, pEnd, &DataBuf, FALSE, FALSE, NULL);
  2183. if(Status != X509_STATUS_SUCCESS)
  2184. break;
  2185. Status = swapendian_memcpy((UINT8 *)&EpidKey->groupId, sizeof(UINT32), DataBuf.buffer, DataBuf.length);
  2186. if(Status != X509_STATUS_SUCCESS)
  2187. break;
  2188. // Next Field : h1 [octet string] This is a ECPoint which is a octet string
  2189. Status = ParseIdAndLength(&current_ptr, pEnd, DER_ENCODING_OCTET_STRING_ID, &length, &EncodingBytes, FALSE);
  2190. if(Status != X509_STATUS_SUCCESS)
  2191. break;
  2192. /* Make sure it has the first bype as 0x04 indicating key is uncompressed */
  2193. if(*current_ptr != 0x04){
  2194. Status = X509_STATUS_ENCODING_ERROR;
  2195. break;
  2196. }
  2197. current_ptr++;
  2198. EpidKey->h1x = current_ptr;
  2199. EpidKey->h1y = current_ptr + 32;
  2200. current_ptr += 64;
  2201. // Next Field : h2 [octet string] This is a ECPoint which is a octet string
  2202. Status = ParseIdAndLength(&current_ptr, pEnd, DER_ENCODING_OCTET_STRING_ID, &length, &EncodingBytes, FALSE);
  2203. if(Status != X509_STATUS_SUCCESS)
  2204. break;
  2205. /* Make sure it has the first bype as 0x04 indicating key is uncompressed */
  2206. if(*current_ptr != 0x04){
  2207. Status = X509_STATUS_ENCODING_ERROR;
  2208. break;
  2209. }
  2210. current_ptr++;
  2211. EpidKey->h2x = current_ptr;
  2212. EpidKey->h2y = current_ptr + 32;
  2213. current_ptr += 64;
  2214. // Next Field : w [octet string] This is a ECPoint which is a octet string
  2215. Status = ParseIdAndLength(&current_ptr, pEnd, DER_ENCODING_OCTET_STRING_ID, &length, &EncodingBytes, FALSE);
  2216. if(Status != X509_STATUS_SUCCESS)
  2217. break;
  2218. /* Make sure it has the first bype as 0x04 indicating key is uncompressed */
  2219. if(*current_ptr != 0x04){
  2220. Status = X509_STATUS_ENCODING_ERROR;
  2221. break;
  2222. }
  2223. current_ptr++;
  2224. EpidKey->wx0 = current_ptr;
  2225. EpidKey->wx1 = current_ptr + 32;
  2226. EpidKey->wx2 = current_ptr + 64;
  2227. EpidKey->wy0 = current_ptr + 96;
  2228. EpidKey->wy1 = current_ptr + 128;
  2229. EpidKey->wy2 = current_ptr + 160;
  2230. current_ptr += 192;
  2231. }while(0);
  2232. *ppCurrent = current_ptr;
  2233. return Status;
  2234. }
  2235. static STATUS ParseEcdsaPublicKey(UINT8 **ppCurrent, UINT8 *pEnd, SessMgrEcdsaPublicKey * EcDsaKey, SessMgrEllipticCurveParameter params)
  2236. {
  2237. UINT8 *current_ptr = *ppCurrent;
  2238. STATUS Status = X509_STATUS_SUCCESS;
  2239. #ifdef X509_FOR_PSE_PR
  2240. UNUSED(pEnd);
  2241. #endif
  2242. do{
  2243. /* Ecdsa Public Key is a Octet string. The SubjectPublicKey in the X509 definitiion is a bit string.
  2244. We use the following logic to convert the Octet String as a bit string as per the Verifier Cert Spec defined by Xiaoyu. */
  2245. /* First octet of bit string is 0x04 indicating key is uncompressed.
  2246. Note: The Key is in OCTET String form and we convert it to BIT STRING. Format : 0x04 | 64-bytes of keys */
  2247. if(*current_ptr != 0x04){
  2248. Status = X509_STATUS_ENCODING_ERROR;
  2249. break;
  2250. }
  2251. current_ptr++;
  2252. EcDsaKey->px = current_ptr;
  2253. EcDsaKey->py = current_ptr + ECDSA_KEY_ELEMENT_SIZE;
  2254. current_ptr += ECDSA_KEY_SIZE;
  2255. EcDsaKey->eccParameter = params;
  2256. }while(0);
  2257. DBG_ASSERT(Status == X509_STATUS_SUCCESS);
  2258. *ppCurrent = current_ptr;
  2259. return Status;
  2260. }
  2261. /* We will never send an OID to the caller. All the OID are matched to a corresponding enumerated type and sent to the caller. */
  2262. static STATUS ParseOID(UINT8 **ppCurrent, UINT8 *pEnd, UINT32 *EnumVal, const UINT8 *OidList, UINT32 Max_Entries, UINT32 EntrySize )
  2263. {
  2264. UINT8 *current_ptr = *ppCurrent;
  2265. UINT32 length;
  2266. UINT32 i;
  2267. STATUS Status;
  2268. UINT8 EncodingBytes;
  2269. do{
  2270. Status = ParseIdAndLength(&current_ptr, pEnd, DER_ENCODING_OBJECT_ID, &length, &EncodingBytes, FALSE);
  2271. if(Status != X509_STATUS_SUCCESS)
  2272. break;
  2273. /* We have a encoded list of hard coded OIDs that we support in an array. Just compare the OID with that array. */
  2274. for(i = 0;i< Max_Entries; i++)
  2275. {
  2276. if(memcmp(current_ptr, OidList, length) == 0){
  2277. /* We found a match. i is the algorithm number that the caller is looking for */
  2278. *EnumVal= i;
  2279. Status = X509_STATUS_SUCCESS;
  2280. break;
  2281. }
  2282. OidList+=EntrySize;
  2283. }
  2284. if(i >= Max_Entries) {
  2285. /* Never found a match */
  2286. *EnumVal= i;
  2287. Status = X509_STATUS_UNKNOWN_OID;
  2288. }
  2289. current_ptr += length;
  2290. }while(0);
  2291. DBG_ASSERT(Status == X509_STATUS_SUCCESS || Status == X509_STATUS_UNKNOWN_OID);
  2292. *ppCurrent = current_ptr;
  2293. return Status;
  2294. }
  2295. static STATUS ParseSignatureValue(UINT8 **ppCurrent, UINT8 *pEnd, UINT8 **pworkbuffer, UINT32 WorkBufferSize, SessMgrDataBuffer *SignatureValueBuf, UINT8 SignatureAlgoId)
  2296. {
  2297. UINT8 *current_ptr = *ppCurrent;
  2298. UINT32 length;
  2299. UINT8 *workbuffer_ptr;
  2300. STATUS Status;
  2301. SessMgrDataBuffer DataBuf;
  2302. UINT8 EncodingBytes;
  2303. #ifdef X509_FOR_PSE_PR
  2304. UNUSED(WorkBufferSize);
  2305. #endif
  2306. workbuffer_ptr = *pworkbuffer;
  2307. do{
  2308. /* SignatureValue is a BIT string. The content within the BIT string is based on the signature algorithm */
  2309. Status = ParseIdAndLength(&current_ptr, pEnd, DER_ENCODING_BIT_STRING_ID, &length, &EncodingBytes, FALSE);
  2310. if(Status != X509_STATUS_SUCCESS )
  2311. break;
  2312. /* Next Byte is the number of padded. Because this is a signature, we expect the resulting value to be a multiple of 8 bits meaning no padding will be necessery */
  2313. if(*current_ptr != 0){
  2314. Status = X509_STATUS_ENCODING_ERROR;
  2315. break;
  2316. }
  2317. //
  2318. // the inc below requires this (i'm choosing to care about **read** buffer overflows)
  2319. //
  2320. if ((current_ptr + 1) >= pEnd) {
  2321. Status = X509_STATUS_ENCODING_ERROR;
  2322. break;
  2323. }
  2324. /* increment current pointer. decrement length to reflect size of actual bit string excluding the padding data*/
  2325. current_ptr++;
  2326. length--;
  2327. /* Rest of the buffer is parsed based on the algo */
  2328. switch(SignatureAlgoId)
  2329. {
  2330. /* ECDSA based sign algorithm */
  2331. case X509_ecdsa_with_SHA1:
  2332. case X509_ecdsa_with_SHA256:
  2333. /* For ECDSA, Signature value is represented as a SEQ {r, s} where r and s are integers. We use the workbuffer to store this */
  2334. /* First memset the buffers where keys will be copied to */
  2335. memset(workbuffer_ptr, 0, ECDSA_SIGNATURE_SIZE);
  2336. Status = ParseIdAndLength(&current_ptr, pEnd, DER_ENCODING_SEQUENCE_ID, &length, &EncodingBytes, FALSE);
  2337. if(Status != X509_STATUS_SUCCESS)
  2338. break;
  2339. /* Parse R and S */
  2340. Status = ParseInteger(&current_ptr, pEnd, &DataBuf, FALSE, FALSE, NULL);
  2341. if(Status != X509_STATUS_SUCCESS || DataBuf.length > ECDSA_SIGNATURE_MAX_SIZE_R ){
  2342. Status = X509_STATUS_ENCODING_ERROR;
  2343. break;
  2344. }
  2345. SESSMGR_MEMCPY_S(workbuffer_ptr + (ECDSA_SIGNATURE_MAX_SIZE_R - DataBuf.length), WorkBufferSize - (workbuffer_ptr - *pworkbuffer), DataBuf.buffer, DataBuf.length);
  2346. workbuffer_ptr += ECDSA_SIGNATURE_MAX_SIZE_R;
  2347. Status = ParseInteger(&current_ptr, pEnd, &DataBuf, FALSE, FALSE, NULL);
  2348. if(Status != X509_STATUS_SUCCESS || DataBuf.length > ECDSA_SIGNATURE_MAX_SIZE_S){
  2349. Status = X509_STATUS_ENCODING_ERROR;
  2350. break;
  2351. }
  2352. SESSMGR_MEMCPY_S(workbuffer_ptr + (ECDSA_SIGNATURE_MAX_SIZE_S - DataBuf.length), WorkBufferSize - (workbuffer_ptr - *pworkbuffer), DataBuf.buffer, DataBuf.length);
  2353. workbuffer_ptr += ECDSA_SIGNATURE_MAX_SIZE_S;
  2354. break;
  2355. /* All the RSA algorithms */
  2356. case X509_sha1withRSAEncryption:
  2357. case X509_sha256WithRSAEncryption:
  2358. /* Assuming here that all RSA algorithms just have a bit string signaure */
  2359. if(length > RSA_SIGNATURE_SIZE){
  2360. Status = X509_STATUS_ENCODING_ERROR;
  2361. break;
  2362. }
  2363. memset(workbuffer_ptr, 0 , length);
  2364. SESSMGR_MEMCPY_S(workbuffer_ptr, WorkBufferSize - (workbuffer_ptr - *pworkbuffer), current_ptr, length);
  2365. workbuffer_ptr += length;
  2366. current_ptr +=length;
  2367. break;
  2368. default:
  2369. DBG_ASSERT(0);
  2370. Status = X509_STATUS_INVALID_ARGS;
  2371. }
  2372. }while(0);
  2373. if(Status == X509_STATUS_SUCCESS){
  2374. // Signature value has been parsed successfully. Store the offset in the workbuffer in the DataBuffer that will be passed back to the caller
  2375. SignatureValueBuf->buffer = *pworkbuffer;
  2376. // length is the amount of work buffer we have used up
  2377. SignatureValueBuf->length = static_cast<Uint32>(workbuffer_ptr - *pworkbuffer);
  2378. }else{
  2379. DBG_ASSERT(0);
  2380. }
  2381. *pworkbuffer = workbuffer_ptr;
  2382. *ppCurrent = current_ptr;
  2383. return Status;
  2384. }
  2385. static STATUS ParseAlgoIdentifier(UINT8 **ppCurrent, UINT8 *pEnd, UINT32* algoId, AlgorithmTypes Type, SessMgrEllipticCurveParameter *params)
  2386. {
  2387. /*****
  2388. Format : Sequence Id + length + Object Id + length + OID value + parameters (optional)
  2389. *****/
  2390. UINT8 *current_ptr = *ppCurrent;
  2391. UINT32 length;
  2392. UINT8 *end_of_sequence;
  2393. STATUS Status;
  2394. UINT8 EncodingBytes;
  2395. Status = ParseIdAndLength(&current_ptr, pEnd, DER_ENCODING_SEQUENCE_ID, &length, &EncodingBytes, FALSE);
  2396. if(Status != X509_STATUS_SUCCESS){
  2397. DBG_ASSERT(0);
  2398. return X509_STATUS_ENCODING_ERROR;
  2399. }
  2400. end_of_sequence = current_ptr + length;
  2401. switch(Type){
  2402. case signature_algo:
  2403. Status = ParseOID(&current_ptr, pEnd, algoId, &HardCodedSignatureAlgorithmOid[0][0],
  2404. static_cast<uint32_t>(sizeof(HardCodedSignatureAlgorithmOid)/sizeof(HardCodedSignatureAlgorithmOid[0])),
  2405. sizeof(HardCodedSignatureAlgorithmOid[0]));
  2406. break;
  2407. case PublicKey_algo:
  2408. Status = ParseOID(&current_ptr, pEnd, algoId, &HardCodedPublicKeyAlgorithmOid[0][0],
  2409. static_cast<uint32_t>(sizeof(HardCodedPublicKeyAlgorithmOid)/sizeof(HardCodedPublicKeyAlgorithmOid[0])),
  2410. sizeof(HardCodedPublicKeyAlgorithmOid[0]));
  2411. break;
  2412. case Hash_algo:
  2413. Status = ParseOID(&current_ptr, pEnd, algoId, &HashAlgorithmOid[0][0],
  2414. static_cast<uint32_t>(sizeof(HashAlgorithmOid)/sizeof(HashAlgorithmOid[0])),
  2415. sizeof(HashAlgorithmOid[0]));
  2416. break;
  2417. default:
  2418. DBG_ASSERT(0);
  2419. }
  2420. if(Status != X509_STATUS_SUCCESS){
  2421. DBG_ASSERT(0);
  2422. return X509_STATUS_ENCODING_ERROR;
  2423. }
  2424. if(current_ptr < end_of_sequence){
  2425. /* We have some parameters */
  2426. Status = ParseAlgoParameters(&current_ptr, end_of_sequence, (UINT32 *)params);
  2427. if(Status == X509_STATUS_UNSUPPORTED_PARAMETER){
  2428. // As per spec, we just move on.
  2429. current_ptr = end_of_sequence;
  2430. *params = unknownParameter;
  2431. Status = X509_STATUS_SUCCESS;
  2432. }
  2433. if(Status != X509_STATUS_SUCCESS)
  2434. Status = X509_STATUS_ENCODING_ERROR;
  2435. }else{
  2436. *params=unknownParameter;
  2437. }
  2438. *ppCurrent = current_ptr;
  2439. return Status;
  2440. }
  2441. static STATUS ParseAlgoParameters(UINT8 **ppCurrent, UINT8 *pEnd, UINT32* param)
  2442. {
  2443. UINT8 *current_ptr = *ppCurrent;
  2444. UINT32 length;
  2445. UINT32 i;
  2446. STATUS Status = X509_STATUS_SUCCESS;
  2447. UINT8 EncodingBytes;
  2448. if ((!param) || ((current_ptr + 1) >= pEnd))
  2449. {
  2450. DBG_ASSERT(0);
  2451. return X509_STATUS_INVALID_ARGS;
  2452. }
  2453. /* current_ptr is over the parameters. We currently support a NULL parameter or an object ID specifiying some algo specific data */
  2454. switch(*current_ptr)
  2455. {
  2456. case DER_ENCODING_NULL_ID:
  2457. current_ptr++;
  2458. /* NULL id is always followed by length 0x00 */
  2459. if(*current_ptr != 0)
  2460. {
  2461. DBG_ASSERT(0);
  2462. return X509_STATUS_ENCODING_ERROR;
  2463. }
  2464. current_ptr++;
  2465. *param = unknownParameter;
  2466. break;
  2467. case DER_ENCODING_OBJECT_ID:
  2468. current_ptr++;
  2469. /* Get Length of object identifier */
  2470. Status = DecodeLength(current_ptr, pEnd, &length, &EncodingBytes);
  2471. if(Status != X509_STATUS_SUCCESS)
  2472. break;
  2473. current_ptr += EncodingBytes;
  2474. /* This can describe the curve */
  2475. for(i = 0;i< MaxElipticCurveOidSupported; i++)
  2476. {
  2477. if(memcmp(current_ptr, EllipticCurveOid[i], length) == 0){
  2478. /* We found a match. "i+1" is the algorithm number that the caller is looking for */
  2479. *param = i;
  2480. break;
  2481. }
  2482. }
  2483. if(i >= MaxElipticCurveOidSupported) {
  2484. /* Never found a match */
  2485. DBG_ASSERT(0);
  2486. *param = unknownParameter;
  2487. Status = X509_STATUS_ENCODING_ERROR;
  2488. }
  2489. current_ptr+=length;
  2490. break;
  2491. default:
  2492. Status = X509_STATUS_UNSUPPORTED_PARAMETER;
  2493. break;
  2494. // unknown parameter. We ignore this.
  2495. }
  2496. *ppCurrent = current_ptr;
  2497. return Status;
  2498. }
  2499. static STATUS ParseName(UINT8 **ppCurrent, UINT8 *pEnd, SessMgrX509Name* Name)
  2500. {
  2501. UINT8* end_of_sequence = NULL;
  2502. UINT8 *current_ptr = *ppCurrent;
  2503. UINT32 length;
  2504. STATUS Status;
  2505. UINT8 EncodingBytes;
  2506. UINT32 NameType;
  2507. memset(Name, 0, sizeof(SessMgrX509Name));
  2508. do{
  2509. Name->DistinguishedName = (char *)current_ptr;
  2510. /* Format : Sequence [ Set [ Sequence [ OID Value] ] ] */
  2511. Status = ParseIdAndLength(&current_ptr, pEnd, DER_ENCODING_SEQUENCE_ID, &length, &EncodingBytes, FALSE);
  2512. if(Status != X509_STATUS_SUCCESS)
  2513. break;
  2514. Name->DistinguishedNameSize = length + EncodingBytes + 1;
  2515. end_of_sequence = current_ptr + length;
  2516. /* Because Set can have variable number of data underneath it, we need to cap it using the length of the sequence
  2517. We will use variable End_of_set and loop through until end is reached. */
  2518. while(current_ptr < end_of_sequence){
  2519. Status = ParseIdAndLength(&current_ptr, end_of_sequence, DER_ENCODING_SET_ID, &length, &EncodingBytes, FALSE);
  2520. if(Status != X509_STATUS_SUCCESS)
  2521. break;
  2522. Status = ParseIdAndLength(&current_ptr, end_of_sequence, DER_ENCODING_SEQUENCE_ID, &length, &EncodingBytes, FALSE);
  2523. if(Status != X509_STATUS_SUCCESS)
  2524. break;
  2525. /* Expected value : Attribute type (OID) and value (Can be anything) */
  2526. Status = ParseOID(&current_ptr, end_of_sequence, &NameType, &HardCodedNameOid[0][0],
  2527. static_cast<uint32_t>(sizeof(HardCodedNameOid)/sizeof(HardCodedNameOid[0])),
  2528. sizeof(HardCodedNameOid[0]));
  2529. // We might have some cases where we are getting an Unknown OID which we just ignore.
  2530. if(Status != X509_STATUS_SUCCESS && Status != X509_STATUS_UNKNOWN_OID){
  2531. DBG_ASSERT(0);
  2532. break;
  2533. }
  2534. /* Value can be any type. Mostly some form of ascii string */
  2535. Status = ParseIdAndLength(&current_ptr, end_of_sequence, DER_ENCODING_UTF8_ID, &length, &EncodingBytes, TRUE);
  2536. if(Status != X509_STATUS_SUCCESS && Status != X509_STATUS_NOT_FOUND)
  2537. break;
  2538. if(Status == X509_STATUS_NOT_FOUND){
  2539. // Has to be one of UTF8 or PRINTABLE_STRING or IA5
  2540. Status = ParseIdAndLength(&current_ptr, end_of_sequence, DER_ENCODING_PRINTABLE_STRING_ID, &length, &EncodingBytes, TRUE);
  2541. if(Status != X509_STATUS_SUCCESS && Status != X509_STATUS_NOT_FOUND)
  2542. break;
  2543. if(Status == X509_STATUS_NOT_FOUND){
  2544. Status = ParseIdAndLength(&current_ptr, end_of_sequence, DER_ENCODING_IA5_STRING_ID, &length, &EncodingBytes, FALSE);
  2545. if(Status != X509_STATUS_SUCCESS){
  2546. DBG_ASSERT(0);
  2547. break;
  2548. }
  2549. }
  2550. }
  2551. switch(NameType)
  2552. {
  2553. case commonName:
  2554. Name->commonName = (char *)current_ptr;
  2555. Name->commonNameSize = length;
  2556. break;
  2557. case organization:
  2558. Name->organization = (char *)current_ptr;
  2559. Name->organizationSize = length;
  2560. break;
  2561. case country:
  2562. Name->country = (char *)current_ptr;
  2563. Name->countrySize = length;
  2564. break;
  2565. case locality:
  2566. Name->locality = (char *)current_ptr;
  2567. Name->localitySize = length;
  2568. break;
  2569. case state:
  2570. Name->state = (char *)current_ptr;
  2571. Name->stateSize = length;
  2572. break;
  2573. case organizationUnit:
  2574. Name->organizationUnit = (char *)current_ptr;
  2575. Name->organizationUnitSize = length;
  2576. break;
  2577. case UserId:
  2578. Name->UserId = (char *)current_ptr;
  2579. Name->UserIdSize = length;
  2580. break;
  2581. default:
  2582. // Dont support this NameType. Just continue.
  2583. break;
  2584. }
  2585. current_ptr += length;
  2586. }
  2587. }while(0);
  2588. *ppCurrent = current_ptr;
  2589. return Status;
  2590. }
  2591. #define DecodeTime_FourBytes(current_ptr) ((1000*( (*current_ptr) - 0x30)) + \
  2592. (100*( *(current_ptr+1) - 0x30)) + \
  2593. (10*( *(current_ptr+2) - 0x30)) + \
  2594. (*(current_ptr + 3) - 0x30)) \
  2595. #define DecodeTime_TwoBytes(current_ptr) ((10*( (*current_ptr) - 0x30)) + \
  2596. (*(current_ptr + 1) - 0x30)) \
  2597. #if 0
  2598. UINT32 DecodeTime(UINT8 *current_ptr, UINT8 length)
  2599. {
  2600. UINT32 value = 0;
  2601. UINT32 digit;
  2602. int i;
  2603. for(i=0; i<length - 1;i++)
  2604. {
  2605. digit = *current_ptr - 0x30;
  2606. digit = digit * Pow(10, length - i - 1);
  2607. value += digit;
  2608. current_ptr++;
  2609. }
  2610. return value;
  2611. }
  2612. #endif
  2613. static STATUS ParseTime(UINT8 **ppCurrent, UINT8 *pEnd, SessMgrDateTime* DateTime)
  2614. {
  2615. /* Id : Either UTC Time or Generalized Time */
  2616. /*****
  2617. Supported UTC formats : YYMMDDhhmmZ
  2618. YYMMDDhhmm+hhmm
  2619. YYMMDDhhmm-hhmm
  2620. YYMMDDhhmmssZ
  2621. YYMMDDhhmmss+hhmm
  2622. YYMMDDhhmmss-hhmm
  2623. *****/
  2624. UINT8 *current_ptr = *ppCurrent;
  2625. UINT32 length;
  2626. BOOL isUTC;
  2627. STATUS Status;
  2628. UINT8 EncodingBytes;
  2629. UINT8 *date_start_ptr;
  2630. DateTime->date.data = 0;
  2631. DateTime->time.data = 0;
  2632. /* Check whether current_ptr is pointing to UTC time or Generalized time*/
  2633. if(*current_ptr == DER_ENCODING_UTC_TIME_ID){
  2634. /* Year format is YY */
  2635. isUTC = TRUE;
  2636. }
  2637. else if(*current_ptr == DER_ENCODING_GENERALIZED_TIME_ID){
  2638. /* Year format is YYYY */
  2639. isUTC = FALSE;
  2640. }else{
  2641. DBG_ASSERT(0);
  2642. return X509_STATUS_ENCODING_ERROR;
  2643. }
  2644. current_ptr++;
  2645. /* get Length of the time */
  2646. Status = DecodeLength(current_ptr, pEnd, &length, &EncodingBytes);
  2647. if(Status != X509_STATUS_SUCCESS){
  2648. DBG_ASSERT(0);
  2649. return X509_STATUS_ENCODING_ERROR;
  2650. }
  2651. current_ptr += EncodingBytes;
  2652. date_start_ptr = current_ptr;
  2653. /* Only difference between generalized and UTC is number of digits for the years.
  2654. UTC has 2 digits and Generalized has 4 digits */
  2655. if(!isUTC){
  2656. DateTime->date.yearMonthDay.year = static_cast<short unsigned int>(DecodeTime_FourBytes(current_ptr));
  2657. current_ptr += 4;
  2658. }else{
  2659. // per rfc3280, if XX >= 50 then 19XX, otherwise 20XX. However, here we always use 20XX.
  2660. DateTime->date.yearMonthDay.year = static_cast<short unsigned int>(DecodeTime_TwoBytes(current_ptr));
  2661. current_ptr += 2;
  2662. DateTime->date.yearMonthDay.year = static_cast<short unsigned int>(DateTime->date.yearMonthDay.year + 2000);
  2663. }
  2664. /* The next 8 bytes are common for both UTC and Generalized time */
  2665. DateTime->date.yearMonthDay.month = DecodeTime_TwoBytes(current_ptr) & 0xF;
  2666. current_ptr += 2;
  2667. DateTime->date.yearMonthDay.day = DecodeTime_TwoBytes(current_ptr) & 0x3F;
  2668. current_ptr += 2;
  2669. DateTime->time.hourMinuteSecond.hour = DecodeTime_TwoBytes(current_ptr) & 0x3F;
  2670. current_ptr += 2;
  2671. DateTime->time.hourMinuteSecond.minute = DecodeTime_TwoBytes(current_ptr) & 0x3F;
  2672. current_ptr += 2;
  2673. /* Next character can be a numeral(incase we have seconds), +, - or Z */
  2674. if(isdigit(*current_ptr)){
  2675. /* we have second. Get the next two bytes as seconds. */
  2676. DateTime->time.hourMinuteSecond.second = DecodeTime_TwoBytes(current_ptr) & 0x3F;
  2677. current_ptr += 2;
  2678. }
  2679. /* Next character has to be +, - or Z */
  2680. switch(*current_ptr)
  2681. {
  2682. case '-':
  2683. DateTime->time.hourMinuteSecond.timezone_is_neg = true;
  2684. /* fallthrough */
  2685. case '+':
  2686. current_ptr++;
  2687. DateTime->time.hourMinuteSecond.timezone_hour = DecodeTime_TwoBytes(current_ptr) & 0x3F;
  2688. current_ptr += 2;
  2689. DateTime->time.hourMinuteSecond.timezone_minute = DecodeTime_TwoBytes(current_ptr) & 0x3F;
  2690. current_ptr += 2;
  2691. break;
  2692. case 'Z':
  2693. /* End of time */
  2694. current_ptr++;
  2695. break;
  2696. default:
  2697. DBG_ASSERT(0);
  2698. return X509_STATUS_ENCODING_ERROR;
  2699. }
  2700. // ensure the length parsed is equal to the specified length
  2701. if ((current_ptr - date_start_ptr) != length)
  2702. {
  2703. DBG_ASSERT(0);
  2704. return X509_STATUS_ENCODING_ERROR;
  2705. }
  2706. // date sanity check
  2707. if (DateTime->date.yearMonthDay.year < 2000 || DateTime->date.yearMonthDay.year >= 2137 ||
  2708. DateTime->date.yearMonthDay.month < 1 || DateTime->date.yearMonthDay.month > 12 ||
  2709. DateTime->date.yearMonthDay.day < 1 || DateTime->date.yearMonthDay.day > 31 ||
  2710. DateTime->time.hourMinuteSecond.hour > 24 ||
  2711. DateTime->time.hourMinuteSecond.minute > 60 ||
  2712. DateTime->time.hourMinuteSecond.second > 60 ||
  2713. DateTime->time.hourMinuteSecond.timezone_hour > 24 ||
  2714. DateTime->time.hourMinuteSecond.timezone_minute > 60)
  2715. {
  2716. DBG_ASSERT(0);
  2717. return X509_STATUS_ENCODING_ERROR;
  2718. }
  2719. *ppCurrent = current_ptr;
  2720. return X509_STATUS_SUCCESS;
  2721. }
  2722. /**
  2723. \param[in] Buffer Buffer which is pointing to a length field in Asn DER encoded form
  2724. \param[out] Length Length of the Asn DER encoded type in bytes
  2725. \param[out] EncodingBytes Number of bytes used for the encoding of the length
  2726. \retval X509_STATUS_SUCCESS
  2727. \retval STATUS_INVALID_PARAMS THere was some error in parsing the ASN Der encoded buffer.
  2728. @brief Return length of the ASN DER encoded type
  2729. */
  2730. static STATUS DecodeLength(UINT8* Buffer, UINT8* BufferEnd, UINT32* Length, UINT8* EncodingBytes)
  2731. {
  2732. if(Buffer[0] < 0x81){
  2733. /* length is only one byte */
  2734. *Length = Buffer[0];
  2735. *EncodingBytes = 1;
  2736. } else if ((Buffer[0] == 0x81) && (&Buffer[1] < BufferEnd)) {
  2737. /* length is two bytes */
  2738. *Length = Buffer[1];
  2739. *EncodingBytes = 2;
  2740. } else if ((Buffer[0] == 0x82) && (&Buffer[2] < BufferEnd)) {
  2741. /* length is 3 bytes */
  2742. *Length = (Buffer[1] << 8) + Buffer[2];
  2743. *EncodingBytes = 3;
  2744. }else{
  2745. return X509_STATUS_ENCODING_ERROR;
  2746. }
  2747. //
  2748. // check for unsigned integer overflow
  2749. //
  2750. UINT32 tempLength = *EncodingBytes + *Length;
  2751. if (((size_t) Buffer + tempLength) >= tempLength) {
  2752. if ((Buffer + tempLength) > BufferEnd) {
  2753. return X509_STATUS_ENCODING_ERROR;
  2754. }
  2755. }
  2756. else {
  2757. return X509_STATUS_ENCODING_ERROR;
  2758. }
  2759. return X509_STATUS_SUCCESS;
  2760. }
  2761. static void SwapEndian(UINT8* ptr, int length)
  2762. {
  2763. UINT8 temp;
  2764. int i;
  2765. for(i=0;i<length/2;i++)
  2766. {
  2767. temp = *(ptr + i);
  2768. *(ptr + i) = *(ptr + length - i - 1);
  2769. *(ptr + length - i - 1) = temp;
  2770. }
  2771. }
  2772. #ifndef X509_FOR_PSE_PR
  2773. static int Pow(int num, int exp)
  2774. {
  2775. int i;
  2776. for(i=0;i<(exp -1);i++)
  2777. num *=num;
  2778. return num;
  2779. }
  2780. #endif
  2781. /*
  2782. This function is used to copy a variable length Big-Endian buffer to a little-endian static length buffer. the buffer is copied over and endianness changed.
  2783. Does not affect Source Buffer. Copies dest buffer uses some ptr arithmatic and converts endianness.
  2784. */
  2785. static STATUS swapendian_memcpy(UINT8 *DestPtr, UINT32 DestLen, UINT8 *SrcPtr, UINT32 SrcLen)
  2786. {
  2787. if( (!DestPtr) || (!SrcPtr) || (DestLen < SrcLen))
  2788. return STATUS_INVALID_PARAMS;
  2789. memset(DestPtr, 0, DestLen);
  2790. SESSMGR_MEMCPY_S(DestPtr + DestLen - SrcLen, DestLen, SrcPtr, SrcLen);
  2791. SwapEndian(DestPtr, DestLen);
  2792. return STATUS_SUCCESS;
  2793. }
  2794. /**
  2795. @brief ASN DER encoding follows the TLV format : Type Identifier || Length || Value
  2796. 1. This function will parse the Type ID and Length, validate it with Expected Id and some encoding rules.
  2797. 2. If no errors, function will move the current ptr to the value.
  2798. \param[in] pCurrentPtr This is a pointer to the current pointer. The function will move the current pointer after parsing the ID and length
  2799. \param[in] ExpectedId Expected Type identifier
  2800. \param[out] Length Length in Bytes of the "Value"
  2801. \param[out] EncodingBytes Number of Bytes used to encode the length field.
  2802. \param[in] Optional Is the ExpectedIdOptional
  2803. @retval X509_STATUS_SUCCESS ID and length were parsed and verified successfully.
  2804. @retval X509_STATUS_NOT_FOUND This value is only returned
  2805. @retval STATUS_ENCODING_ERROR Some error in the encoding of the certificate.
  2806. */
  2807. static STATUS ParseIdAndLength(UINT8 **ppCurrent, UINT8 *pEnd, UINT8 ExpectedId, UINT32* Length, UINT8* EncodingBytes, BOOL Optional)
  2808. {
  2809. UINT8* current_ptr = *ppCurrent;
  2810. STATUS Status;
  2811. if(*current_ptr != ExpectedId){
  2812. if(Optional)
  2813. return X509_STATUS_NOT_FOUND;
  2814. else{
  2815. DBG_ASSERT(0);
  2816. return X509_STATUS_ENCODING_ERROR;
  2817. }
  2818. }
  2819. current_ptr++;
  2820. if (current_ptr != pEnd) {
  2821. Status = DecodeLength(current_ptr, pEnd, Length, EncodingBytes);
  2822. if(Status != X509_STATUS_SUCCESS){
  2823. DBG_ASSERT(0);
  2824. return X509_STATUS_ENCODING_ERROR;
  2825. }
  2826. current_ptr += *EncodingBytes;
  2827. *ppCurrent = current_ptr;
  2828. return X509_STATUS_SUCCESS;
  2829. }
  2830. else {
  2831. return X509_STATUS_ENCODING_ERROR;
  2832. }
  2833. }
  2834. #ifndef X509_FOR_PSE_PR
  2835. /*
  2836. * This function expects the trusted time to be available from the OCSP parsing and stored in the SessMgrCtx.
  2837. * This call is protected by the Mutex we acquire when we get the ProcessS2GetS3 call.
  2838. */
  2839. STATUS StoreTrustedTime(SessMgrDateTime TrustedTime)
  2840. {
  2841. STATUS Status;
  2842. STORAGE_FILE_ATTRIB Blob;
  2843. STORAGE_OPERATION_FLAGS StorageFlags = {0};
  2844. NTP_TIMESTAMP NtpTime = {0,0};
  2845. Status = ConvertTimeToNtp(TrustedTime, &NtpTime );
  2846. if(Status != STATUS_SUCCESS){
  2847. DBG_ASSERT(0);
  2848. return Status;
  2849. }
  2850. // We have the time in NTP. Call PrtcSetTime. This will give us an offset which we can use to find out current time.
  2851. Status = PrtcSetTime(&NtpTime, &gSessmgrCtx.TrustedTime.RtcOffset);
  2852. if(Status != STATUS_SUCCESS){
  2853. DBG_ASSERT(0);
  2854. return Status;
  2855. }
  2856. gSessmgrCtx.TrustedTime.Seconds = NtpTime.Seconds;
  2857. // Store RTC offset in the Blob
  2858. SESSMGR_INIT_BLOB_ATTRIB(Blob);
  2859. Blob.Attributes.BlobType = AR_BLOB;
  2860. StorageFlags.Data = 0;
  2861. Status = gSessmgrCtx.StorageProtocol->Write(gSessmgrCtx.StorageProtocol,
  2862. SESS_MGR_TRUSTED_TIME_NVAR_NAME,
  2863. &Blob, &StorageFlags,
  2864. sizeof(gSessmgrCtx.TrustedTime),
  2865. &gSessmgrCtx.TrustedTime, 0);
  2866. if(Status != STATUS_SUCCESS){
  2867. DBG_ASSERT(0);
  2868. return Status;
  2869. }
  2870. return STATUS_SUCCESS;
  2871. }
  2872. STATUS ConvertTimeToNtp(SessMgrDateTime Time, NTP_TIMESTAMP *NtpTime)
  2873. {
  2874. STATUS Status;
  2875. RTC_TIME RtcTime;
  2876. TZ_DST TimeZoneAndDST;
  2877. memset(&RtcTime, 0, sizeof(RTC_TIME));
  2878. memset(NtpTime, 0, sizeof(NTP_TIMESTAMP));
  2879. if (Time.date.yearMonthDay.year < 2000 || Time.date.yearMonthDay.year >= 2137)
  2880. return STATUS_FAILURE;
  2881. RtcTime.Year = (UINT8)(Time.date.yearMonthDay.year - 2000);
  2882. RtcTime.Month = (UINT8)Time.date.yearMonthDay.month;
  2883. RtcTime.Day = (UINT8)Time.date.yearMonthDay.day;
  2884. RtcTime.Hour = (UINT8)Time.time.hourMinuteSecond.hour;
  2885. RtcTime.Min = (UINT8)Time.time.hourMinuteSecond.minute;
  2886. RtcTime.Sec = (UINT8)Time.time.hourMinuteSecond.second;
  2887. RtcTime.Status.DM = 1; // DM = 1 => Binary data representation.
  2888. RtcTime.Status.HOURFORM = 1; // HOURFORM = 1 => 24 hour
  2889. TimeZoneAndDST.DST = 0;
  2890. TimeZoneAndDST.HalfHourAdjust = Time.time.hourMinuteSecond.timezone_minute ? 1 : 0;
  2891. TimeZoneAndDST.RSVD = 0;
  2892. TimeZoneAndDST.TimeZone = (Time.time.hourMinuteSecond.timezone_is_neg ? TIME_ZONE_OFFSET_SIGN_MASK : 0) |
  2893. Time.time.hourMinuteSecond.timezone_hour;
  2894. Status = PrtcLocalToNtp(&RtcTime, TimeZoneAndDST, NtpTime);
  2895. if(Status != STATUS_SUCCESS){
  2896. DBG_ASSERT(0);
  2897. return Status;
  2898. }
  2899. // PrtcLocalToNtp has a starting offset of year 1900 and will overflow in year 2037
  2900. // Shift the offset to start at year 2000, so that we can operate in years 2000-2137
  2901. NtpTime->Seconds -= SECONDS_FROM_1900_TO_2000;
  2902. return STATUS_SUCCESS;
  2903. }
  2904. #endif // #ifndef X509_FOR_PSE_PR