X509_Parser.cpp 137 KB

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