android_keymaster_test.cpp 195 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484
  1. /*
  2. * Copyright (C) 2014 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <fstream>
  17. #include <memory>
  18. #include <string>
  19. #include <vector>
  20. #include <openssl/evp.h>
  21. #include <openssl/x509.h>
  22. #include <hardware/keymaster0.h>
  23. #include <keymaster/android_keymaster.h>
  24. #include <keymaster/attestation_record.h>
  25. #include <keymaster/contexts/pure_soft_keymaster_context.h>
  26. #include <keymaster/contexts/soft_keymaster_context.h>
  27. #include <keymaster/key_factory.h>
  28. #include <keymaster/km_openssl/hmac_key.h>
  29. #include <keymaster/km_openssl/openssl_utils.h>
  30. #include <keymaster/km_openssl/soft_keymaster_enforcement.h>
  31. #include <keymaster/legacy_support/keymaster0_engine.h>
  32. #include <keymaster/soft_keymaster_device.h>
  33. #include "android_keymaster_test_utils.h"
  34. using std::ifstream;
  35. using std::istreambuf_iterator;
  36. using std::ofstream;
  37. using std::string;
  38. using std::unique_ptr;
  39. using std::vector;
  40. extern "C" {
  41. int __android_log_print(int prio, const char* tag, const char* fmt);
  42. int __android_log_print(int prio, const char* tag, const char* fmt) {
  43. (void)prio, (void)tag, (void)fmt;
  44. return 0;
  45. }
  46. } // extern "C"
  47. namespace {
  48. // For some reason std::make_unique isn't available. Define make_unique.
  49. template <typename T, typename... Args> std::unique_ptr<T> make_unique(Args&&... args) {
  50. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  51. }
  52. } // namespace
  53. namespace keymaster {
  54. namespace test {
  55. const uint32_t kOsVersion = 060000;
  56. const uint32_t kOsPatchLevel = 201603;
  57. StdoutLogger logger;
  58. template <typename T> vector<T> make_vector(const T* array, size_t len) {
  59. return vector<T>(array, array + len);
  60. }
  61. /**
  62. * KeymasterEnforcement class for use in testing. It's permissive in the sense that it doesn't
  63. * check cryptoperiods, but restrictive in the sense that the clock never advances (so rate-limited
  64. * keys will only work once).
  65. */
  66. class TestKeymasterEnforcement : public SoftKeymasterEnforcement {
  67. public:
  68. TestKeymasterEnforcement() : SoftKeymasterEnforcement(3, 3) {}
  69. virtual bool activation_date_valid(uint64_t /* activation_date */) const { return true; }
  70. virtual bool expiration_date_passed(uint64_t /* expiration_date */) const { return false; }
  71. virtual bool auth_token_timed_out(const hw_auth_token_t& /* token */,
  72. uint32_t /* timeout */) const {
  73. return false;
  74. }
  75. virtual uint32_t get_current_time() const { return 0; }
  76. virtual bool ValidateTokenSignature(const hw_auth_token_t& /* token */) const { return true; }
  77. };
  78. /**
  79. * Variant of SoftKeymasterContext that provides a TestKeymasterEnforcement.
  80. */
  81. class TestKeymasterContext : public SoftKeymasterContext {
  82. public:
  83. TestKeymasterContext() {}
  84. explicit TestKeymasterContext(const string& root_of_trust)
  85. : SoftKeymasterContext(root_of_trust) {}
  86. KeymasterEnforcement* enforcement_policy() override { return &test_policy_; }
  87. private:
  88. TestKeymasterEnforcement test_policy_;
  89. };
  90. /**
  91. * Test instance creator that builds a pure software keymaster2 implementation.
  92. */
  93. class SoftKeymasterTestInstanceCreator : public Keymaster2TestInstanceCreator {
  94. public:
  95. keymaster2_device_t* CreateDevice() const override {
  96. std::cerr << "Creating software-only device" << std::endl;
  97. context_ = new TestKeymasterContext;
  98. SoftKeymasterDevice* device = new SoftKeymasterDevice(context_);
  99. AuthorizationSet version_info(AuthorizationSetBuilder()
  100. .Authorization(TAG_OS_VERSION, kOsVersion)
  101. .Authorization(TAG_OS_PATCHLEVEL, kOsPatchLevel));
  102. device->keymaster2_device()->configure(device->keymaster2_device(), &version_info);
  103. return device->keymaster2_device();
  104. }
  105. bool algorithm_in_km0_hardware(keymaster_algorithm_t) const override { return false; }
  106. int keymaster0_calls() const override { return 0; }
  107. bool is_keymaster1_hw() const override { return false; }
  108. KeymasterContext* keymaster_context() const override { return context_; }
  109. string name() const override { return "Soft Keymaster2"; }
  110. private:
  111. mutable TestKeymasterContext* context_;
  112. };
  113. /**
  114. * Test instance creator that builds a SoftKeymasterDevice which wraps a fake hardware keymaster1
  115. * instance, with minimal digest support.
  116. */
  117. class Sha256OnlyKeymaster1TestInstanceCreator : public Keymaster2TestInstanceCreator {
  118. keymaster2_device_t* CreateDevice() const override {
  119. std::cerr << "Creating keymaster1-backed device that supports only SHA256";
  120. // fake_device doesn't leak because device (below) takes ownership of it.
  121. keymaster1_device_t* fake_device = make_device_sha256_only(
  122. (new SoftKeymasterDevice(new TestKeymasterContext("PseudoHW")))->keymaster_device());
  123. // device doesn't leak; it's cleaned up by device->keymaster_device()->common.close().
  124. context_ = new TestKeymasterContext;
  125. SoftKeymasterDevice* device = new SoftKeymasterDevice(context_);
  126. device->SetHardwareDevice(fake_device);
  127. AuthorizationSet version_info(AuthorizationSetBuilder()
  128. .Authorization(TAG_OS_VERSION, kOsVersion)
  129. .Authorization(TAG_OS_PATCHLEVEL, kOsPatchLevel));
  130. device->keymaster2_device()->configure(device->keymaster2_device(), &version_info);
  131. return device->keymaster2_device();
  132. }
  133. bool algorithm_in_km0_hardware(keymaster_algorithm_t) const override { return false; }
  134. int keymaster0_calls() const override { return 0; }
  135. int minimal_digest_set() const override { return true; }
  136. bool is_keymaster1_hw() const override { return true; }
  137. KeymasterContext* keymaster_context() const override { return context_; }
  138. string name() const override { return "Wrapped fake keymaster1 w/minimal digests"; }
  139. private:
  140. mutable TestKeymasterContext* context_;
  141. };
  142. /**
  143. * Test instance creator that builds a SoftKeymasterDevice which wraps a fake hardware keymaster1
  144. * instance, with full digest support
  145. */
  146. class Keymaster1TestInstanceCreator : public Keymaster2TestInstanceCreator {
  147. keymaster2_device_t* CreateDevice() const override {
  148. std::cerr << "Creating keymaster1-backed device";
  149. // fake_device doesn't leak because device (below) takes ownership of it.
  150. keymaster1_device_t* fake_device =
  151. (new SoftKeymasterDevice(new TestKeymasterContext("PseudoHW")))->keymaster_device();
  152. // device doesn't leak; it's cleaned up by device->keymaster_device()->common.close().
  153. context_ = new TestKeymasterContext;
  154. SoftKeymasterDevice* device = new SoftKeymasterDevice(context_);
  155. device->SetHardwareDevice(fake_device);
  156. AuthorizationSet version_info(AuthorizationSetBuilder()
  157. .Authorization(TAG_OS_VERSION, kOsVersion)
  158. .Authorization(TAG_OS_PATCHLEVEL, kOsPatchLevel));
  159. device->keymaster2_device()->configure(device->keymaster2_device(), &version_info);
  160. return device->keymaster2_device();
  161. }
  162. bool algorithm_in_km0_hardware(keymaster_algorithm_t) const override { return false; }
  163. int keymaster0_calls() const override { return 0; }
  164. int minimal_digest_set() const override { return false; }
  165. bool is_keymaster1_hw() const override { return true; }
  166. KeymasterContext* keymaster_context() const override { return context_; }
  167. string name() const override { return "Wrapped fake keymaster1 w/full digests"; }
  168. private:
  169. mutable TestKeymasterContext* context_;
  170. };
  171. static auto test_params = testing::Values(
  172. InstanceCreatorPtr(new SoftKeymasterTestInstanceCreator),
  173. InstanceCreatorPtr(new Keymaster1TestInstanceCreator),
  174. InstanceCreatorPtr(new Sha256OnlyKeymaster1TestInstanceCreator));
  175. class NewKeyGeneration : public Keymaster2Test {
  176. protected:
  177. void CheckBaseParams() {
  178. AuthorizationSet auths = sw_enforced();
  179. EXPECT_GT(auths.SerializedSize(), 12U);
  180. EXPECT_TRUE(contains(auths, TAG_PURPOSE, KM_PURPOSE_SIGN));
  181. EXPECT_TRUE(contains(auths, TAG_PURPOSE, KM_PURPOSE_VERIFY));
  182. EXPECT_TRUE(contains(auths, TAG_USER_ID, 7));
  183. EXPECT_TRUE(contains(auths, TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD));
  184. EXPECT_TRUE(contains(auths, TAG_AUTH_TIMEOUT, 300));
  185. // Verify that App ID, App data and ROT are NOT included.
  186. EXPECT_FALSE(contains(auths, TAG_ROOT_OF_TRUST));
  187. EXPECT_FALSE(contains(auths, TAG_APPLICATION_ID));
  188. EXPECT_FALSE(contains(auths, TAG_APPLICATION_DATA));
  189. // Just for giggles, check that some unexpected tags/values are NOT present.
  190. EXPECT_FALSE(contains(auths, TAG_PURPOSE, KM_PURPOSE_ENCRYPT));
  191. EXPECT_FALSE(contains(auths, TAG_PURPOSE, KM_PURPOSE_DECRYPT));
  192. EXPECT_FALSE(contains(auths, TAG_AUTH_TIMEOUT, 301));
  193. // Now check that unspecified, defaulted tags are correct.
  194. EXPECT_TRUE(contains(auths, KM_TAG_CREATION_DATETIME));
  195. if (GetParam()->is_keymaster1_hw()) {
  196. // If the underlying (faked) HW is KM1, it will not have version info.
  197. EXPECT_FALSE(auths.Contains(TAG_OS_VERSION));
  198. EXPECT_FALSE(auths.Contains(TAG_OS_PATCHLEVEL));
  199. } else {
  200. // In all othe cases; SoftKeymasterDevice keys, or keymaster0 keys wrapped by
  201. // SoftKeymasterDevice, version information will be present and up to date.
  202. EXPECT_TRUE(contains(auths, TAG_OS_VERSION, kOsVersion));
  203. EXPECT_TRUE(contains(auths, TAG_OS_PATCHLEVEL, kOsPatchLevel));
  204. }
  205. }
  206. };
  207. INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, NewKeyGeneration, test_params);
  208. TEST_P(NewKeyGeneration, Rsa) {
  209. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  210. .RsaSigningKey(256, 3)
  211. .Digest(KM_DIGEST_NONE)
  212. .Padding(KM_PAD_NONE)));
  213. CheckBaseParams();
  214. // Check specified tags are all present, and in the right set.
  215. AuthorizationSet crypto_params;
  216. AuthorizationSet non_crypto_params;
  217. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA)) {
  218. EXPECT_NE(0U, hw_enforced().size());
  219. EXPECT_NE(0U, sw_enforced().size());
  220. crypto_params.push_back(hw_enforced());
  221. non_crypto_params.push_back(sw_enforced());
  222. } else {
  223. EXPECT_EQ(0U, hw_enforced().size());
  224. EXPECT_NE(0U, sw_enforced().size());
  225. crypto_params.push_back(sw_enforced());
  226. }
  227. EXPECT_TRUE(contains(crypto_params, TAG_ALGORITHM, KM_ALGORITHM_RSA));
  228. EXPECT_FALSE(contains(non_crypto_params, TAG_ALGORITHM, KM_ALGORITHM_RSA));
  229. EXPECT_TRUE(contains(crypto_params, TAG_KEY_SIZE, 256));
  230. EXPECT_FALSE(contains(non_crypto_params, TAG_KEY_SIZE, 256));
  231. EXPECT_TRUE(contains(crypto_params, TAG_RSA_PUBLIC_EXPONENT, 3));
  232. EXPECT_FALSE(contains(non_crypto_params, TAG_RSA_PUBLIC_EXPONENT, 3));
  233. EXPECT_EQ(KM_ERROR_OK, DeleteKey());
  234. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  235. EXPECT_EQ(2, GetParam()->keymaster0_calls());
  236. }
  237. TEST_P(NewKeyGeneration, RsaDefaultSize) {
  238. ASSERT_EQ(KM_ERROR_UNSUPPORTED_KEY_SIZE,
  239. GenerateKey(AuthorizationSetBuilder()
  240. .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA)
  241. .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3)
  242. .SigningKey()));
  243. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  244. }
  245. TEST_P(NewKeyGeneration, Ecdsa) {
  246. ASSERT_EQ(KM_ERROR_OK,
  247. GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(KM_DIGEST_NONE)));
  248. CheckBaseParams();
  249. // Check specified tags are all present, and in the right set.
  250. AuthorizationSet crypto_params;
  251. AuthorizationSet non_crypto_params;
  252. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC)) {
  253. EXPECT_NE(0U, hw_enforced().size());
  254. EXPECT_NE(0U, sw_enforced().size());
  255. crypto_params.push_back(hw_enforced());
  256. non_crypto_params.push_back(sw_enforced());
  257. } else {
  258. EXPECT_EQ(0U, hw_enforced().size());
  259. EXPECT_NE(0U, sw_enforced().size());
  260. crypto_params.push_back(sw_enforced());
  261. }
  262. EXPECT_TRUE(contains(crypto_params, TAG_ALGORITHM, KM_ALGORITHM_EC));
  263. EXPECT_FALSE(contains(non_crypto_params, TAG_ALGORITHM, KM_ALGORITHM_EC));
  264. EXPECT_TRUE(contains(crypto_params, TAG_KEY_SIZE, 224));
  265. EXPECT_FALSE(contains(non_crypto_params, TAG_KEY_SIZE, 224));
  266. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
  267. EXPECT_EQ(1, GetParam()->keymaster0_calls());
  268. }
  269. TEST_P(NewKeyGeneration, EcdsaDefaultSize) {
  270. ASSERT_EQ(KM_ERROR_UNSUPPORTED_KEY_SIZE,
  271. GenerateKey(AuthorizationSetBuilder()
  272. .Authorization(TAG_ALGORITHM, KM_ALGORITHM_EC)
  273. .SigningKey()
  274. .Digest(KM_DIGEST_NONE)));
  275. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  276. }
  277. TEST_P(NewKeyGeneration, EcdsaInvalidSize) {
  278. ASSERT_EQ(KM_ERROR_UNSUPPORTED_KEY_SIZE,
  279. GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(190).Digest(KM_DIGEST_NONE)));
  280. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  281. }
  282. TEST_P(NewKeyGeneration, EcdsaMismatchKeySize) {
  283. ASSERT_EQ(KM_ERROR_INVALID_ARGUMENT,
  284. GenerateKey(AuthorizationSetBuilder()
  285. .EcdsaSigningKey(224)
  286. .Authorization(TAG_EC_CURVE, KM_EC_CURVE_P_256)
  287. .Digest(KM_DIGEST_NONE)));
  288. }
  289. TEST_P(NewKeyGeneration, EcdsaAllValidSizes) {
  290. size_t valid_sizes[] = {224, 256, 384, 521};
  291. for (size_t size : valid_sizes) {
  292. EXPECT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(size).Digest(
  293. KM_DIGEST_NONE)))
  294. << "Failed to generate size: " << size;
  295. }
  296. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
  297. EXPECT_EQ(4, GetParam()->keymaster0_calls());
  298. }
  299. TEST_P(NewKeyGeneration, HmacSha256) {
  300. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  301. .HmacKey(128)
  302. .Digest(KM_DIGEST_SHA_2_256)
  303. .Authorization(TAG_MIN_MAC_LENGTH, 256)));
  304. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  305. }
  306. TEST_P(NewKeyGeneration, CheckKeySizes) {
  307. for (size_t key_size = 0; key_size <= kMaxHmacKeyLengthBits + 10; ++key_size) {
  308. if (key_size < kMinHmacKeyLengthBits || key_size > kMaxHmacKeyLengthBits ||
  309. key_size % 8 != 0) {
  310. EXPECT_EQ(KM_ERROR_UNSUPPORTED_KEY_SIZE,
  311. GenerateKey(AuthorizationSetBuilder()
  312. .HmacKey(key_size)
  313. .Digest(KM_DIGEST_SHA_2_256)
  314. .Authorization(TAG_MIN_MAC_LENGTH, 256)))
  315. << "HMAC key size " << key_size << " invalid.";
  316. } else {
  317. EXPECT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  318. .HmacKey(key_size)
  319. .Digest(KM_DIGEST_SHA_2_256)
  320. .Authorization(TAG_MIN_MAC_LENGTH, 256)));
  321. }
  322. }
  323. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  324. }
  325. TEST_P(NewKeyGeneration, HmacMultipleDigests) {
  326. ASSERT_EQ(KM_ERROR_UNSUPPORTED_DIGEST,
  327. GenerateKey(AuthorizationSetBuilder()
  328. .HmacKey(128)
  329. .Digest(KM_DIGEST_SHA1)
  330. .Digest(KM_DIGEST_SHA_2_256)
  331. .Authorization(TAG_MIN_MAC_LENGTH, 128)));
  332. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  333. }
  334. TEST_P(NewKeyGeneration, HmacDigestNone) {
  335. ASSERT_EQ(KM_ERROR_UNSUPPORTED_DIGEST,
  336. GenerateKey(AuthorizationSetBuilder()
  337. .HmacKey(128)
  338. .Digest(KM_DIGEST_NONE)
  339. .Authorization(TAG_MIN_MAC_LENGTH, 128)));
  340. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  341. }
  342. TEST_P(NewKeyGeneration, HmacSha256TooShortMacLength) {
  343. ASSERT_EQ(KM_ERROR_UNSUPPORTED_MIN_MAC_LENGTH,
  344. GenerateKey(AuthorizationSetBuilder()
  345. .HmacKey(128)
  346. .Digest(KM_DIGEST_SHA_2_256)
  347. .Authorization(TAG_MIN_MAC_LENGTH, 48)));
  348. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  349. }
  350. TEST_P(NewKeyGeneration, HmacSha256NonIntegralOctetMacLength) {
  351. ASSERT_EQ(KM_ERROR_UNSUPPORTED_MIN_MAC_LENGTH,
  352. GenerateKey(AuthorizationSetBuilder()
  353. .HmacKey(128)
  354. .Digest(KM_DIGEST_SHA_2_256)
  355. .Authorization(TAG_MIN_MAC_LENGTH, 130)));
  356. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  357. }
  358. TEST_P(NewKeyGeneration, HmacSha256TooLongMacLength) {
  359. ASSERT_EQ(KM_ERROR_UNSUPPORTED_MIN_MAC_LENGTH,
  360. GenerateKey(AuthorizationSetBuilder()
  361. .HmacKey(128)
  362. .Digest(KM_DIGEST_SHA_2_256)
  363. .Authorization(TAG_MIN_MAC_LENGTH, 384)));
  364. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  365. }
  366. typedef Keymaster2Test GetKeyCharacteristics;
  367. INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, GetKeyCharacteristics, test_params);
  368. TEST_P(GetKeyCharacteristics, SimpleRsa) {
  369. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  370. .RsaSigningKey(256, 3)
  371. .Digest(KM_DIGEST_NONE)
  372. .Padding(KM_PAD_NONE)));
  373. AuthorizationSet original(sw_enforced());
  374. ASSERT_EQ(KM_ERROR_OK, GetCharacteristics());
  375. EXPECT_EQ(original, sw_enforced());
  376. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  377. EXPECT_EQ(1, GetParam()->keymaster0_calls());
  378. }
  379. typedef Keymaster2Test SigningOperationsTest;
  380. INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, SigningOperationsTest, test_params);
  381. TEST_P(SigningOperationsTest, RsaSuccess) {
  382. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  383. .RsaSigningKey(256, 3)
  384. .Digest(KM_DIGEST_NONE)
  385. .Padding(KM_PAD_NONE)));
  386. string message = "12345678901234567890123456789012";
  387. string signature;
  388. SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
  389. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  390. EXPECT_EQ(3, GetParam()->keymaster0_calls());
  391. }
  392. TEST_P(SigningOperationsTest, RsaPssSha256Success) {
  393. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  394. .RsaSigningKey(768, 3)
  395. .Digest(KM_DIGEST_SHA_2_256)
  396. .Padding(KM_PAD_RSA_PSS)));
  397. // Use large message, which won't work without digesting.
  398. string message(1024, 'a');
  399. string signature;
  400. SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PSS);
  401. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  402. EXPECT_EQ(3, GetParam()->keymaster0_calls());
  403. }
  404. TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
  405. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  406. .RsaSigningKey(512, 3)
  407. .Digest(KM_DIGEST_NONE)
  408. .Padding(KM_PAD_NONE)));
  409. string message = "12345678901234567890123456789012";
  410. string signature;
  411. AuthorizationSet begin_params(client_params());
  412. begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
  413. begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
  414. EXPECT_EQ(KM_ERROR_INCOMPATIBLE_PADDING_MODE, BeginOperation(KM_PURPOSE_SIGN, begin_params));
  415. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  416. EXPECT_EQ(2, GetParam()->keymaster0_calls());
  417. }
  418. TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
  419. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  420. .RsaSigningKey(512, 3)
  421. .Digest(KM_DIGEST_SHA_2_256)
  422. .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
  423. string message(1024, 'a');
  424. string signature;
  425. SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PKCS1_1_5_SIGN);
  426. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  427. EXPECT_EQ(3, GetParam()->keymaster0_calls());
  428. }
  429. TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
  430. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  431. .RsaSigningKey(512, 3)
  432. .Digest(KM_DIGEST_NONE)
  433. .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
  434. string message(53, 'a');
  435. string signature;
  436. SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_RSA_PKCS1_1_5_SIGN);
  437. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  438. EXPECT_EQ(3, GetParam()->keymaster0_calls());
  439. }
  440. TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLarge) {
  441. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  442. .RsaSigningKey(512, 3)
  443. .Digest(KM_DIGEST_NONE)
  444. .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
  445. string message(54, 'a');
  446. AuthorizationSet begin_params(client_params());
  447. begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
  448. begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
  449. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
  450. string result;
  451. string signature;
  452. EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, FinishOperation(message, "", &signature));
  453. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  454. EXPECT_EQ(2, GetParam()->keymaster0_calls());
  455. }
  456. TEST_P(SigningOperationsTest, RsaPssSha256TooSmallKey) {
  457. // Key must be at least 10 bytes larger than hash, to provide eight bytes of random salt, so
  458. // verify that nine bytes larger than hash won't work.
  459. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  460. .RsaSigningKey(256 + 9 * 8, 3)
  461. .Digest(KM_DIGEST_SHA_2_256)
  462. .Padding(KM_PAD_RSA_PSS)));
  463. string message(1024, 'a');
  464. string signature;
  465. AuthorizationSet begin_params(client_params());
  466. begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
  467. begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PSS);
  468. EXPECT_EQ(KM_ERROR_INCOMPATIBLE_DIGEST, BeginOperation(KM_PURPOSE_SIGN, begin_params));
  469. }
  470. TEST_P(SigningOperationsTest, RsaNoPaddingHugeData) {
  471. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  472. .RsaSigningKey(256, 3)
  473. .Digest(KM_DIGEST_NONE)
  474. .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
  475. string message(64 * 1024, 'a');
  476. string signature;
  477. AuthorizationSet begin_params(client_params());
  478. begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
  479. begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
  480. ASSERT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
  481. string result;
  482. size_t input_consumed;
  483. EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, UpdateOperation(message, &result, &input_consumed));
  484. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  485. EXPECT_EQ(2, GetParam()->keymaster0_calls());
  486. }
  487. TEST_P(SigningOperationsTest, RsaAbort) {
  488. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  489. .RsaSigningKey(256, 3)
  490. .Digest(KM_DIGEST_NONE)
  491. .Padding(KM_PAD_NONE)));
  492. AuthorizationSet begin_params(client_params());
  493. begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
  494. begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
  495. ASSERT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
  496. EXPECT_EQ(KM_ERROR_OK, AbortOperation());
  497. // Another abort should fail
  498. EXPECT_EQ(KM_ERROR_INVALID_OPERATION_HANDLE, AbortOperation());
  499. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  500. EXPECT_EQ(2, GetParam()->keymaster0_calls());
  501. }
  502. TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
  503. GenerateKey(AuthorizationSetBuilder()
  504. .RsaSigningKey(256, 3)
  505. .Digest(KM_DIGEST_SHA_2_256 /* supported digest */)
  506. .Padding(KM_PAD_PKCS7));
  507. AuthorizationSet begin_params(client_params());
  508. begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
  509. ASSERT_EQ(KM_ERROR_UNSUPPORTED_PADDING_MODE, BeginOperation(KM_PURPOSE_SIGN, begin_params));
  510. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  511. EXPECT_EQ(2, GetParam()->keymaster0_calls());
  512. }
  513. TEST_P(SigningOperationsTest, RsaNoDigest) {
  514. // PSS requires a digest.
  515. GenerateKey(AuthorizationSetBuilder()
  516. .RsaSigningKey(256, 3)
  517. .Digest(KM_DIGEST_NONE)
  518. .Padding(KM_PAD_RSA_PSS));
  519. AuthorizationSet begin_params(client_params());
  520. begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
  521. begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PSS);
  522. ASSERT_EQ(KM_ERROR_INCOMPATIBLE_DIGEST, BeginOperation(KM_PURPOSE_SIGN, begin_params));
  523. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  524. EXPECT_EQ(2, GetParam()->keymaster0_calls());
  525. }
  526. TEST_P(SigningOperationsTest, RsaNoPadding) {
  527. // Padding must be specified
  528. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().RsaKey(256, 3).SigningKey().Digest(
  529. KM_DIGEST_NONE)));
  530. AuthorizationSet begin_params(client_params());
  531. begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
  532. ASSERT_EQ(KM_ERROR_UNSUPPORTED_PADDING_MODE, BeginOperation(KM_PURPOSE_SIGN, begin_params));
  533. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  534. EXPECT_EQ(2, GetParam()->keymaster0_calls());
  535. }
  536. TEST_P(SigningOperationsTest, RsaTooShortMessage) {
  537. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  538. .RsaSigningKey(256, 3)
  539. .Digest(KM_DIGEST_NONE)
  540. .Padding(KM_PAD_NONE)));
  541. string message = "1234567890123456789012345678901";
  542. string signature;
  543. SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
  544. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  545. EXPECT_EQ(3, GetParam()->keymaster0_calls());
  546. }
  547. TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
  548. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  549. .RsaEncryptionKey(256, 3)
  550. .Digest(KM_DIGEST_NONE)
  551. .Padding(KM_PAD_NONE)));
  552. AuthorizationSet begin_params(client_params());
  553. begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
  554. begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
  555. ASSERT_EQ(KM_ERROR_INCOMPATIBLE_PURPOSE, BeginOperation(KM_PURPOSE_SIGN, begin_params));
  556. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  557. EXPECT_EQ(2, GetParam()->keymaster0_calls());
  558. }
  559. TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
  560. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  561. .RsaSigningKey(256, 3)
  562. .Digest(KM_DIGEST_NONE)
  563. .Padding(KM_PAD_NONE)));
  564. string message(256 / 8, static_cast<char>(0xff));
  565. string signature;
  566. AuthorizationSet begin_params(client_params());
  567. begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
  568. begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
  569. ASSERT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
  570. string result;
  571. size_t input_consumed;
  572. ASSERT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
  573. ASSERT_EQ(message.size(), input_consumed);
  574. string output;
  575. ASSERT_EQ(KM_ERROR_INVALID_ARGUMENT, FinishOperation(&output));
  576. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  577. EXPECT_EQ(3, GetParam()->keymaster0_calls());
  578. }
  579. TEST_P(SigningOperationsTest, EcdsaSuccess) {
  580. ASSERT_EQ(KM_ERROR_OK,
  581. GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(KM_DIGEST_NONE)));
  582. string message(224 / 8, 'a');
  583. string signature;
  584. SignMessage(message, &signature, KM_DIGEST_NONE);
  585. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
  586. EXPECT_EQ(3, GetParam()->keymaster0_calls());
  587. }
  588. TEST_P(SigningOperationsTest, EcdsaSha256Success) {
  589. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(
  590. KM_DIGEST_SHA_2_256)));
  591. string message(1024, 'a');
  592. string signature;
  593. SignMessage(message, &signature, KM_DIGEST_SHA_2_256);
  594. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
  595. EXPECT_EQ(3, GetParam()->keymaster0_calls());
  596. }
  597. TEST_P(SigningOperationsTest, EcdsaSha384Success) {
  598. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(
  599. KM_DIGEST_SHA_2_384)));
  600. string message(1024, 'a');
  601. string signature;
  602. SignMessage(message, &signature, KM_DIGEST_SHA_2_384);
  603. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
  604. EXPECT_EQ(3, GetParam()->keymaster0_calls());
  605. }
  606. TEST_P(SigningOperationsTest, EcdsaNoPaddingHugeData) {
  607. ASSERT_EQ(KM_ERROR_OK,
  608. GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(KM_DIGEST_NONE)));
  609. string message(64 * 1024, 'a');
  610. string signature;
  611. AuthorizationSet begin_params(client_params());
  612. begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
  613. ASSERT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
  614. string result;
  615. size_t input_consumed;
  616. EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
  617. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
  618. EXPECT_EQ(2, GetParam()->keymaster0_calls());
  619. }
  620. TEST_P(SigningOperationsTest, EcdsaAllSizesAndHashes) {
  621. vector<int> key_sizes = {224, 256, 384, 521};
  622. vector<keymaster_digest_t> digests = {
  623. KM_DIGEST_SHA1, KM_DIGEST_SHA_2_224, KM_DIGEST_SHA_2_256,
  624. KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512,
  625. };
  626. for (int key_size : key_sizes) {
  627. for (keymaster_digest_t digest : digests) {
  628. ASSERT_EQ(
  629. KM_ERROR_OK,
  630. GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(key_size).Digest(digest)));
  631. string message(1024, 'a');
  632. string signature;
  633. if (digest == KM_DIGEST_NONE)
  634. message.resize(key_size / 8);
  635. SignMessage(message, &signature, digest);
  636. }
  637. }
  638. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
  639. EXPECT_EQ(digests.size() * key_sizes.size() * 3,
  640. static_cast<size_t>(GetParam()->keymaster0_calls()));
  641. }
  642. TEST_P(SigningOperationsTest, AesEcbSign) {
  643. ASSERT_EQ(KM_ERROR_OK,
  644. GenerateKey(AuthorizationSetBuilder().AesEncryptionKey(128).Authorization(
  645. TAG_BLOCK_MODE, KM_MODE_ECB)));
  646. ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_SIGN));
  647. ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_VERIFY));
  648. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  649. }
  650. TEST_P(SigningOperationsTest, HmacSha1Success) {
  651. GenerateKey(AuthorizationSetBuilder()
  652. .HmacKey(128)
  653. .Digest(KM_DIGEST_SHA1)
  654. .Authorization(TAG_MIN_MAC_LENGTH, 160));
  655. string message = "12345678901234567890123456789012";
  656. string signature;
  657. MacMessage(message, &signature, 160);
  658. ASSERT_EQ(20U, signature.size());
  659. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  660. }
  661. TEST_P(SigningOperationsTest, HmacSha224Success) {
  662. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  663. .HmacKey(128)
  664. .Digest(KM_DIGEST_SHA_2_224)
  665. .Authorization(TAG_MIN_MAC_LENGTH, 160)));
  666. string message = "12345678901234567890123456789012";
  667. string signature;
  668. MacMessage(message, &signature, 224);
  669. ASSERT_EQ(28U, signature.size());
  670. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  671. }
  672. TEST_P(SigningOperationsTest, HmacSha256Success) {
  673. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  674. .HmacKey(128)
  675. .Digest(KM_DIGEST_SHA_2_256)
  676. .Authorization(TAG_MIN_MAC_LENGTH, 256)));
  677. string message = "12345678901234567890123456789012";
  678. string signature;
  679. MacMessage(message, &signature, 256);
  680. ASSERT_EQ(32U, signature.size());
  681. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  682. }
  683. TEST_P(SigningOperationsTest, HmacSha384Success) {
  684. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  685. .HmacKey(128)
  686. .Digest(KM_DIGEST_SHA_2_384)
  687. .Authorization(TAG_MIN_MAC_LENGTH, 384)));
  688. string message = "12345678901234567890123456789012";
  689. string signature;
  690. MacMessage(message, &signature, 384);
  691. ASSERT_EQ(48U, signature.size());
  692. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  693. }
  694. TEST_P(SigningOperationsTest, HmacSha512Success) {
  695. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  696. .HmacKey(128)
  697. .Digest(KM_DIGEST_SHA_2_512)
  698. .Authorization(TAG_MIN_MAC_LENGTH, 384)));
  699. string message = "12345678901234567890123456789012";
  700. string signature;
  701. MacMessage(message, &signature, 512);
  702. ASSERT_EQ(64U, signature.size());
  703. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  704. }
  705. TEST_P(SigningOperationsTest, HmacLengthInKey) {
  706. // TODO(swillden): unified API should generate an error on key generation.
  707. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  708. .HmacKey(128)
  709. .Digest(KM_DIGEST_SHA_2_256)
  710. .Authorization(TAG_MIN_MAC_LENGTH, 128)));
  711. string message = "12345678901234567890123456789012";
  712. string signature;
  713. MacMessage(message, &signature, 160);
  714. ASSERT_EQ(20U, signature.size());
  715. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  716. }
  717. TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
  718. string key(20, 0xaa);
  719. string message(50, 0xdd);
  720. uint8_t sha_224_expected[] = {
  721. 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
  722. 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
  723. };
  724. uint8_t sha_256_expected[] = {
  725. 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
  726. 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
  727. 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
  728. };
  729. uint8_t sha_384_expected[] = {
  730. 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
  731. 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
  732. 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
  733. 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
  734. };
  735. uint8_t sha_512_expected[] = {
  736. 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
  737. 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
  738. 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
  739. 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
  740. 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
  741. };
  742. CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
  743. CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
  744. CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
  745. CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
  746. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  747. }
  748. TEST_P(SigningOperationsTest, HmacRfc4231TestCase4) {
  749. uint8_t key_data[25] = {
  750. 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
  751. 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19,
  752. };
  753. string key = make_string(key_data);
  754. string message(50, 0xcd);
  755. uint8_t sha_224_expected[] = {
  756. 0x6c, 0x11, 0x50, 0x68, 0x74, 0x01, 0x3c, 0xac, 0x6a, 0x2a, 0xbc, 0x1b, 0xb3, 0x82,
  757. 0x62, 0x7c, 0xec, 0x6a, 0x90, 0xd8, 0x6e, 0xfc, 0x01, 0x2d, 0xe7, 0xaf, 0xec, 0x5a,
  758. };
  759. uint8_t sha_256_expected[] = {
  760. 0x82, 0x55, 0x8a, 0x38, 0x9a, 0x44, 0x3c, 0x0e, 0xa4, 0xcc, 0x81,
  761. 0x98, 0x99, 0xf2, 0x08, 0x3a, 0x85, 0xf0, 0xfa, 0xa3, 0xe5, 0x78,
  762. 0xf8, 0x07, 0x7a, 0x2e, 0x3f, 0xf4, 0x67, 0x29, 0x66, 0x5b,
  763. };
  764. uint8_t sha_384_expected[] = {
  765. 0x3e, 0x8a, 0x69, 0xb7, 0x78, 0x3c, 0x25, 0x85, 0x19, 0x33, 0xab, 0x62,
  766. 0x90, 0xaf, 0x6c, 0xa7, 0x7a, 0x99, 0x81, 0x48, 0x08, 0x50, 0x00, 0x9c,
  767. 0xc5, 0x57, 0x7c, 0x6e, 0x1f, 0x57, 0x3b, 0x4e, 0x68, 0x01, 0xdd, 0x23,
  768. 0xc4, 0xa7, 0xd6, 0x79, 0xcc, 0xf8, 0xa3, 0x86, 0xc6, 0x74, 0xcf, 0xfb,
  769. };
  770. uint8_t sha_512_expected[] = {
  771. 0xb0, 0xba, 0x46, 0x56, 0x37, 0x45, 0x8c, 0x69, 0x90, 0xe5, 0xa8, 0xc5, 0xf6,
  772. 0x1d, 0x4a, 0xf7, 0xe5, 0x76, 0xd9, 0x7f, 0xf9, 0x4b, 0x87, 0x2d, 0xe7, 0x6f,
  773. 0x80, 0x50, 0x36, 0x1e, 0xe3, 0xdb, 0xa9, 0x1c, 0xa5, 0xc1, 0x1a, 0xa2, 0x5e,
  774. 0xb4, 0xd6, 0x79, 0x27, 0x5c, 0xc5, 0x78, 0x80, 0x63, 0xa5, 0xf1, 0x97, 0x41,
  775. 0x12, 0x0c, 0x4f, 0x2d, 0xe2, 0xad, 0xeb, 0xeb, 0x10, 0xa2, 0x98, 0xdd,
  776. };
  777. CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
  778. CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
  779. CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
  780. CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
  781. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  782. }
  783. TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
  784. string key(20, 0x0c);
  785. string message = "Test With Truncation";
  786. uint8_t sha_224_expected[] = {
  787. 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
  788. 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
  789. };
  790. uint8_t sha_256_expected[] = {
  791. 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
  792. 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
  793. };
  794. uint8_t sha_384_expected[] = {
  795. 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
  796. 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
  797. };
  798. uint8_t sha_512_expected[] = {
  799. 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
  800. 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
  801. };
  802. CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
  803. CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
  804. CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
  805. CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
  806. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  807. }
  808. TEST_P(SigningOperationsTest, HmacRfc4231TestCase6) {
  809. string key(131, 0xaa);
  810. string message = "Test Using Larger Than Block-Size Key - Hash Key First";
  811. uint8_t sha_224_expected[] = {
  812. 0x95, 0xe9, 0xa0, 0xdb, 0x96, 0x20, 0x95, 0xad, 0xae, 0xbe, 0x9b, 0x2d, 0x6f, 0x0d,
  813. 0xbc, 0xe2, 0xd4, 0x99, 0xf1, 0x12, 0xf2, 0xd2, 0xb7, 0x27, 0x3f, 0xa6, 0x87, 0x0e,
  814. };
  815. uint8_t sha_256_expected[] = {
  816. 0x60, 0xe4, 0x31, 0x59, 0x1e, 0xe0, 0xb6, 0x7f, 0x0d, 0x8a, 0x26,
  817. 0xaa, 0xcb, 0xf5, 0xb7, 0x7f, 0x8e, 0x0b, 0xc6, 0x21, 0x37, 0x28,
  818. 0xc5, 0x14, 0x05, 0x46, 0x04, 0x0f, 0x0e, 0xe3, 0x7f, 0x54,
  819. };
  820. uint8_t sha_384_expected[] = {
  821. 0x4e, 0xce, 0x08, 0x44, 0x85, 0x81, 0x3e, 0x90, 0x88, 0xd2, 0xc6, 0x3a,
  822. 0x04, 0x1b, 0xc5, 0xb4, 0x4f, 0x9e, 0xf1, 0x01, 0x2a, 0x2b, 0x58, 0x8f,
  823. 0x3c, 0xd1, 0x1f, 0x05, 0x03, 0x3a, 0xc4, 0xc6, 0x0c, 0x2e, 0xf6, 0xab,
  824. 0x40, 0x30, 0xfe, 0x82, 0x96, 0x24, 0x8d, 0xf1, 0x63, 0xf4, 0x49, 0x52,
  825. };
  826. uint8_t sha_512_expected[] = {
  827. 0x80, 0xb2, 0x42, 0x63, 0xc7, 0xc1, 0xa3, 0xeb, 0xb7, 0x14, 0x93, 0xc1, 0xdd,
  828. 0x7b, 0xe8, 0xb4, 0x9b, 0x46, 0xd1, 0xf4, 0x1b, 0x4a, 0xee, 0xc1, 0x12, 0x1b,
  829. 0x01, 0x37, 0x83, 0xf8, 0xf3, 0x52, 0x6b, 0x56, 0xd0, 0x37, 0xe0, 0x5f, 0x25,
  830. 0x98, 0xbd, 0x0f, 0xd2, 0x21, 0x5d, 0x6a, 0x1e, 0x52, 0x95, 0xe6, 0x4f, 0x73,
  831. 0xf6, 0x3f, 0x0a, 0xec, 0x8b, 0x91, 0x5a, 0x98, 0x5d, 0x78, 0x65, 0x98,
  832. };
  833. CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
  834. CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
  835. CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
  836. CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
  837. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  838. }
  839. TEST_P(SigningOperationsTest, HmacRfc4231TestCase7) {
  840. string key(131, 0xaa);
  841. string message = "This is a test using a larger than block-size key and a larger than "
  842. "block-size data. The key needs to be hashed before being used by the HMAC "
  843. "algorithm.";
  844. uint8_t sha_224_expected[] = {
  845. 0x3a, 0x85, 0x41, 0x66, 0xac, 0x5d, 0x9f, 0x02, 0x3f, 0x54, 0xd5, 0x17, 0xd0, 0xb3,
  846. 0x9d, 0xbd, 0x94, 0x67, 0x70, 0xdb, 0x9c, 0x2b, 0x95, 0xc9, 0xf6, 0xf5, 0x65, 0xd1,
  847. };
  848. uint8_t sha_256_expected[] = {
  849. 0x9b, 0x09, 0xff, 0xa7, 0x1b, 0x94, 0x2f, 0xcb, 0x27, 0x63, 0x5f,
  850. 0xbc, 0xd5, 0xb0, 0xe9, 0x44, 0xbf, 0xdc, 0x63, 0x64, 0x4f, 0x07,
  851. 0x13, 0x93, 0x8a, 0x7f, 0x51, 0x53, 0x5c, 0x3a, 0x35, 0xe2,
  852. };
  853. uint8_t sha_384_expected[] = {
  854. 0x66, 0x17, 0x17, 0x8e, 0x94, 0x1f, 0x02, 0x0d, 0x35, 0x1e, 0x2f, 0x25,
  855. 0x4e, 0x8f, 0xd3, 0x2c, 0x60, 0x24, 0x20, 0xfe, 0xb0, 0xb8, 0xfb, 0x9a,
  856. 0xdc, 0xce, 0xbb, 0x82, 0x46, 0x1e, 0x99, 0xc5, 0xa6, 0x78, 0xcc, 0x31,
  857. 0xe7, 0x99, 0x17, 0x6d, 0x38, 0x60, 0xe6, 0x11, 0x0c, 0x46, 0x52, 0x3e,
  858. };
  859. uint8_t sha_512_expected[] = {
  860. 0xe3, 0x7b, 0x6a, 0x77, 0x5d, 0xc8, 0x7d, 0xba, 0xa4, 0xdf, 0xa9, 0xf9, 0x6e,
  861. 0x5e, 0x3f, 0xfd, 0xde, 0xbd, 0x71, 0xf8, 0x86, 0x72, 0x89, 0x86, 0x5d, 0xf5,
  862. 0xa3, 0x2d, 0x20, 0xcd, 0xc9, 0x44, 0xb6, 0x02, 0x2c, 0xac, 0x3c, 0x49, 0x82,
  863. 0xb1, 0x0d, 0x5e, 0xeb, 0x55, 0xc3, 0xe4, 0xde, 0x15, 0x13, 0x46, 0x76, 0xfb,
  864. 0x6d, 0xe0, 0x44, 0x60, 0x65, 0xc9, 0x74, 0x40, 0xfa, 0x8c, 0x6a, 0x58,
  865. };
  866. CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
  867. CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
  868. CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
  869. CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
  870. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  871. }
  872. TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
  873. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  874. .HmacKey(128)
  875. .Digest(KM_DIGEST_SHA_2_256)
  876. .Authorization(TAG_MIN_MAC_LENGTH, 256)));
  877. AuthorizationSet begin_params(client_params());
  878. begin_params.push_back(TAG_MAC_LENGTH, 264);
  879. begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
  880. ASSERT_EQ(KM_ERROR_UNSUPPORTED_MAC_LENGTH,
  881. BeginOperation(KM_PURPOSE_SIGN, begin_params, nullptr /* output_params */));
  882. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  883. }
  884. TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
  885. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  886. .HmacKey(128)
  887. .Digest(KM_DIGEST_SHA_2_256)
  888. .Authorization(TAG_MIN_MAC_LENGTH, 128)));
  889. AuthorizationSet begin_params(client_params());
  890. begin_params.push_back(TAG_MAC_LENGTH, 120);
  891. begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
  892. ASSERT_EQ(KM_ERROR_INVALID_MAC_LENGTH,
  893. BeginOperation(KM_PURPOSE_SIGN, begin_params, nullptr /* output_params */));
  894. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  895. }
  896. // TODO(swillden): Add more verification failure tests.
  897. typedef Keymaster2Test VerificationOperationsTest;
  898. INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, VerificationOperationsTest, test_params);
  899. TEST_P(VerificationOperationsTest, RsaSuccess) {
  900. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  901. .RsaSigningKey(256, 3)
  902. .Digest(KM_DIGEST_NONE)
  903. .Padding(KM_PAD_NONE)));
  904. string message = "12345678901234567890123456789012";
  905. string signature;
  906. SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
  907. VerifyMessage(message, signature, KM_DIGEST_NONE, KM_PAD_NONE);
  908. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  909. EXPECT_EQ(4, GetParam()->keymaster0_calls());
  910. }
  911. TEST_P(VerificationOperationsTest, RsaPssSha256Success) {
  912. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  913. .RsaSigningKey(768, 3)
  914. .Digest(KM_DIGEST_SHA_2_256)
  915. .Padding(KM_PAD_RSA_PSS)));
  916. // Use large message, which won't work without digesting.
  917. string message(1024, 'a');
  918. string signature;
  919. SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PSS);
  920. VerifyMessage(message, signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PSS);
  921. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  922. EXPECT_EQ(4, GetParam()->keymaster0_calls());
  923. }
  924. TEST_P(VerificationOperationsTest, RsaPssSha224Success) {
  925. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  926. .RsaSigningKey(512, 3)
  927. .Digest(KM_DIGEST_SHA_2_224)
  928. .Padding(KM_PAD_RSA_PSS)));
  929. // Use large message, which won't work without digesting.
  930. string message(1024, 'a');
  931. string signature;
  932. SignMessage(message, &signature, KM_DIGEST_SHA_2_224, KM_PAD_RSA_PSS);
  933. VerifyMessage(message, signature, KM_DIGEST_SHA_2_224, KM_PAD_RSA_PSS);
  934. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  935. EXPECT_EQ(4, GetParam()->keymaster0_calls());
  936. // Verify with OpenSSL.
  937. string pubkey;
  938. EXPECT_EQ(KM_ERROR_OK, ExportKey(KM_KEY_FORMAT_X509, &pubkey));
  939. const uint8_t* p = reinterpret_cast<const uint8_t*>(pubkey.data());
  940. unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(
  941. d2i_PUBKEY(nullptr /* alloc new */, &p, pubkey.size()));
  942. ASSERT_TRUE(pkey.get());
  943. EVP_MD_CTX digest_ctx;
  944. EVP_MD_CTX_init(&digest_ctx);
  945. EVP_PKEY_CTX* pkey_ctx;
  946. EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, EVP_sha224(), nullptr /* engine */,
  947. pkey.get()));
  948. EXPECT_EQ(1, EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING));
  949. EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(), message.size()));
  950. EXPECT_EQ(1,
  951. EVP_DigestVerifyFinal(&digest_ctx, reinterpret_cast<const uint8_t*>(signature.data()),
  952. signature.size()));
  953. EVP_MD_CTX_cleanup(&digest_ctx);
  954. }
  955. TEST_P(VerificationOperationsTest, RsaPssSha256CorruptSignature) {
  956. GenerateKey(AuthorizationSetBuilder()
  957. .RsaSigningKey(768, 3)
  958. .Digest(KM_DIGEST_SHA_2_256)
  959. .Padding(KM_PAD_RSA_PSS));
  960. string message(1024, 'a');
  961. string signature;
  962. SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PSS);
  963. ++signature[signature.size() / 2];
  964. AuthorizationSet begin_params(client_params());
  965. begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
  966. begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PSS);
  967. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
  968. string result;
  969. EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(message, signature, &result));
  970. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  971. EXPECT_EQ(4, GetParam()->keymaster0_calls());
  972. }
  973. TEST_P(VerificationOperationsTest, RsaPssSha256CorruptInput) {
  974. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  975. .RsaSigningKey(768, 3)
  976. .Digest(KM_DIGEST_SHA_2_256)
  977. .Padding(KM_PAD_RSA_PSS)));
  978. // Use large message, which won't work without digesting.
  979. string message(1024, 'a');
  980. string signature;
  981. SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PSS);
  982. ++message[message.size() / 2];
  983. AuthorizationSet begin_params(client_params());
  984. begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
  985. begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PSS);
  986. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
  987. string result;
  988. EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(message, signature, &result));
  989. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  990. EXPECT_EQ(4, GetParam()->keymaster0_calls());
  991. }
  992. TEST_P(VerificationOperationsTest, RsaPkcs1Sha256Success) {
  993. GenerateKey(AuthorizationSetBuilder()
  994. .RsaSigningKey(512, 3)
  995. .Digest(KM_DIGEST_SHA_2_256)
  996. .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN));
  997. string message(1024, 'a');
  998. string signature;
  999. SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PKCS1_1_5_SIGN);
  1000. VerifyMessage(message, signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PKCS1_1_5_SIGN);
  1001. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  1002. EXPECT_EQ(4, GetParam()->keymaster0_calls());
  1003. }
  1004. TEST_P(VerificationOperationsTest, RsaPks1Sha224Success) {
  1005. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  1006. .RsaSigningKey(512, 3)
  1007. .Digest(KM_DIGEST_SHA_2_224)
  1008. .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
  1009. // Use large message, which won't work without digesting.
  1010. string message(1024, 'a');
  1011. string signature;
  1012. SignMessage(message, &signature, KM_DIGEST_SHA_2_224, KM_PAD_RSA_PKCS1_1_5_SIGN);
  1013. VerifyMessage(message, signature, KM_DIGEST_SHA_2_224, KM_PAD_RSA_PKCS1_1_5_SIGN);
  1014. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  1015. EXPECT_EQ(4, GetParam()->keymaster0_calls());
  1016. // Verify with OpenSSL.
  1017. string pubkey;
  1018. EXPECT_EQ(KM_ERROR_OK, ExportKey(KM_KEY_FORMAT_X509, &pubkey));
  1019. const uint8_t* p = reinterpret_cast<const uint8_t*>(pubkey.data());
  1020. unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(
  1021. d2i_PUBKEY(nullptr /* alloc new */, &p, pubkey.size()));
  1022. ASSERT_TRUE(pkey.get());
  1023. EVP_MD_CTX digest_ctx;
  1024. EVP_MD_CTX_init(&digest_ctx);
  1025. EVP_PKEY_CTX* pkey_ctx;
  1026. EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, EVP_sha224(), nullptr /* engine */,
  1027. pkey.get()));
  1028. EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(), message.size()));
  1029. EXPECT_EQ(1,
  1030. EVP_DigestVerifyFinal(&digest_ctx, reinterpret_cast<const uint8_t*>(signature.data()),
  1031. signature.size()));
  1032. EVP_MD_CTX_cleanup(&digest_ctx);
  1033. }
  1034. TEST_P(VerificationOperationsTest, RsaPkcs1Sha256CorruptSignature) {
  1035. GenerateKey(AuthorizationSetBuilder()
  1036. .RsaSigningKey(512, 3)
  1037. .Digest(KM_DIGEST_SHA_2_256)
  1038. .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN));
  1039. string message(1024, 'a');
  1040. string signature;
  1041. SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PKCS1_1_5_SIGN);
  1042. ++signature[signature.size() / 2];
  1043. AuthorizationSet begin_params(client_params());
  1044. begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
  1045. begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
  1046. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
  1047. string result;
  1048. EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(message, signature, &result));
  1049. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  1050. EXPECT_EQ(4, GetParam()->keymaster0_calls());
  1051. }
  1052. TEST_P(VerificationOperationsTest, RsaPkcs1Sha256CorruptInput) {
  1053. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  1054. .RsaSigningKey(512, 3)
  1055. .Digest(KM_DIGEST_SHA_2_256)
  1056. .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
  1057. // Use large message, which won't work without digesting.
  1058. string message(1024, 'a');
  1059. string signature;
  1060. SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PKCS1_1_5_SIGN);
  1061. ++message[message.size() / 2];
  1062. AuthorizationSet begin_params(client_params());
  1063. begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
  1064. begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
  1065. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
  1066. string result;
  1067. EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(message, signature, &result));
  1068. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  1069. EXPECT_EQ(4, GetParam()->keymaster0_calls());
  1070. }
  1071. TEST_P(VerificationOperationsTest, RsaAllDigestAndPadCombinations) {
  1072. vector<keymaster_digest_t> digests = {
  1073. KM_DIGEST_NONE, KM_DIGEST_MD5, KM_DIGEST_SHA1, KM_DIGEST_SHA_2_224,
  1074. KM_DIGEST_SHA_2_256, KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512,
  1075. };
  1076. vector<keymaster_padding_t> padding_modes{
  1077. KM_PAD_NONE, KM_PAD_RSA_PKCS1_1_5_SIGN, KM_PAD_RSA_PSS,
  1078. };
  1079. int trial_count = 0;
  1080. for (keymaster_padding_t padding_mode : padding_modes) {
  1081. for (keymaster_digest_t digest : digests) {
  1082. if (digest != KM_DIGEST_NONE && padding_mode == KM_PAD_NONE)
  1083. // Digesting requires padding
  1084. continue;
  1085. // Compute key & message size that will work.
  1086. size_t key_bits = 0;
  1087. size_t message_len = 1000;
  1088. if (digest == KM_DIGEST_NONE) {
  1089. key_bits = 256;
  1090. switch (padding_mode) {
  1091. case KM_PAD_NONE:
  1092. // Match key size.
  1093. message_len = key_bits / 8;
  1094. break;
  1095. case KM_PAD_RSA_PKCS1_1_5_SIGN:
  1096. message_len = key_bits / 8 - 11;
  1097. break;
  1098. case KM_PAD_RSA_PSS:
  1099. // PSS requires a digest.
  1100. continue;
  1101. default:
  1102. FAIL() << "Missing padding";
  1103. break;
  1104. }
  1105. } else {
  1106. size_t digest_bits;
  1107. switch (digest) {
  1108. case KM_DIGEST_MD5:
  1109. digest_bits = 128;
  1110. break;
  1111. case KM_DIGEST_SHA1:
  1112. digest_bits = 160;
  1113. break;
  1114. case KM_DIGEST_SHA_2_224:
  1115. digest_bits = 224;
  1116. break;
  1117. case KM_DIGEST_SHA_2_256:
  1118. digest_bits = 256;
  1119. break;
  1120. case KM_DIGEST_SHA_2_384:
  1121. digest_bits = 384;
  1122. break;
  1123. case KM_DIGEST_SHA_2_512:
  1124. digest_bits = 512;
  1125. break;
  1126. default:
  1127. FAIL() << "Missing digest";
  1128. }
  1129. switch (padding_mode) {
  1130. case KM_PAD_RSA_PKCS1_1_5_SIGN:
  1131. key_bits = digest_bits + 8 * (11 + 19);
  1132. break;
  1133. case KM_PAD_RSA_PSS:
  1134. key_bits = digest_bits * 2 + 2 * 8;
  1135. break;
  1136. default:
  1137. FAIL() << "Missing padding";
  1138. break;
  1139. }
  1140. }
  1141. // Round up to the nearest multiple of 128.
  1142. key_bits = (key_bits + 127) / 128 * 128;
  1143. GenerateKey(AuthorizationSetBuilder()
  1144. .RsaSigningKey(key_bits, 3)
  1145. .Digest(digest)
  1146. .Padding(padding_mode));
  1147. string message(message_len, 'a');
  1148. string signature;
  1149. SignMessage(message, &signature, digest, padding_mode);
  1150. VerifyMessage(message, signature, digest, padding_mode);
  1151. ++trial_count;
  1152. }
  1153. }
  1154. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  1155. EXPECT_EQ(trial_count * 4, GetParam()->keymaster0_calls());
  1156. }
  1157. TEST_P(VerificationOperationsTest, EcdsaSuccess) {
  1158. ASSERT_EQ(KM_ERROR_OK,
  1159. GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(KM_DIGEST_NONE)));
  1160. string message = "12345678901234567890123456789012";
  1161. string signature;
  1162. SignMessage(message, &signature, KM_DIGEST_NONE);
  1163. VerifyMessage(message, signature, KM_DIGEST_NONE);
  1164. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
  1165. EXPECT_EQ(4, GetParam()->keymaster0_calls());
  1166. }
  1167. TEST_P(VerificationOperationsTest, EcdsaTooShort) {
  1168. ASSERT_EQ(KM_ERROR_OK,
  1169. GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(KM_DIGEST_NONE)));
  1170. string message = "12345678901234567890";
  1171. string signature;
  1172. SignMessage(message, &signature, KM_DIGEST_NONE);
  1173. VerifyMessage(message, signature, KM_DIGEST_NONE);
  1174. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
  1175. EXPECT_EQ(4, GetParam()->keymaster0_calls());
  1176. }
  1177. TEST_P(VerificationOperationsTest, EcdsaSlightlyTooLong) {
  1178. ASSERT_EQ(KM_ERROR_OK,
  1179. GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(521).Digest(KM_DIGEST_NONE)));
  1180. string message(66, 'a');
  1181. string signature;
  1182. SignMessage(message, &signature, KM_DIGEST_NONE);
  1183. VerifyMessage(message, signature, KM_DIGEST_NONE);
  1184. // Modifying low-order bits doesn't matter, because they didn't get signed. Ugh.
  1185. message[65] ^= 7;
  1186. VerifyMessage(message, signature, KM_DIGEST_NONE);
  1187. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
  1188. EXPECT_EQ(5, GetParam()->keymaster0_calls());
  1189. }
  1190. TEST_P(VerificationOperationsTest, EcdsaSha256Success) {
  1191. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  1192. .EcdsaSigningKey(256)
  1193. .Digest(KM_DIGEST_SHA_2_256)
  1194. .Digest(KM_DIGEST_NONE)));
  1195. string message = "12345678901234567890123456789012";
  1196. string signature;
  1197. SignMessage(message, &signature, KM_DIGEST_SHA_2_256);
  1198. VerifyMessage(message, signature, KM_DIGEST_SHA_2_256);
  1199. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
  1200. EXPECT_EQ(4, GetParam()->keymaster0_calls());
  1201. // Just for giggles, try verifying with the wrong digest.
  1202. AuthorizationSet begin_params(client_params());
  1203. begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
  1204. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
  1205. string result;
  1206. EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(message, signature, &result));
  1207. }
  1208. TEST_P(VerificationOperationsTest, EcdsaSha224Success) {
  1209. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(
  1210. KM_DIGEST_SHA_2_224)));
  1211. string message = "12345678901234567890123456789012";
  1212. string signature;
  1213. SignMessage(message, &signature, KM_DIGEST_SHA_2_224);
  1214. VerifyMessage(message, signature, KM_DIGEST_SHA_2_224);
  1215. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
  1216. EXPECT_EQ(4, GetParam()->keymaster0_calls());
  1217. // Just for giggles, try verifying with the wrong digest.
  1218. AuthorizationSet begin_params(client_params());
  1219. begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
  1220. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
  1221. string result;
  1222. EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(message, signature, &result));
  1223. }
  1224. TEST_P(VerificationOperationsTest, EcdsaAllDigestsAndKeySizes) {
  1225. keymaster_digest_t digests[] = {
  1226. KM_DIGEST_SHA1, KM_DIGEST_SHA_2_224, KM_DIGEST_SHA_2_256,
  1227. KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512,
  1228. };
  1229. size_t key_sizes[] = {224, 256, 384, 521};
  1230. string message = "1234567890";
  1231. string signature;
  1232. for (auto key_size : key_sizes) {
  1233. SCOPED_TRACE(testing::Message() << "Key size: " << key_size);
  1234. AuthorizationSetBuilder builder;
  1235. builder.EcdsaSigningKey(key_size);
  1236. for (auto digest : digests)
  1237. builder.Digest(digest);
  1238. ASSERT_EQ(KM_ERROR_OK, GenerateKey(builder));
  1239. for (auto digest : digests) {
  1240. SCOPED_TRACE(testing::Message() << "Digest: " << digest);
  1241. SignMessage(message, &signature, digest);
  1242. VerifyMessage(message, signature, digest);
  1243. }
  1244. }
  1245. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
  1246. EXPECT_EQ(static_cast<int>(array_length(key_sizes) * (1 + 3 * array_length(digests))),
  1247. GetParam()->keymaster0_calls());
  1248. }
  1249. TEST_P(VerificationOperationsTest, HmacSha1Success) {
  1250. GenerateKey(AuthorizationSetBuilder()
  1251. .HmacKey(128)
  1252. .Digest(KM_DIGEST_SHA1)
  1253. .Authorization(TAG_MIN_MAC_LENGTH, 128));
  1254. string message = "123456789012345678901234567890123456789012345678";
  1255. string signature;
  1256. MacMessage(message, &signature, 160);
  1257. VerifyMac(message, signature);
  1258. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  1259. }
  1260. TEST_P(VerificationOperationsTest, HmacSha224Success) {
  1261. GenerateKey(AuthorizationSetBuilder()
  1262. .HmacKey(128)
  1263. .Digest(KM_DIGEST_SHA_2_224)
  1264. .Authorization(TAG_MIN_MAC_LENGTH, 128));
  1265. string message = "123456789012345678901234567890123456789012345678";
  1266. string signature;
  1267. MacMessage(message, &signature, 224);
  1268. VerifyMac(message, signature);
  1269. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  1270. }
  1271. TEST_P(VerificationOperationsTest, HmacSha256Success) {
  1272. GenerateKey(AuthorizationSetBuilder()
  1273. .HmacKey(128)
  1274. .Digest(KM_DIGEST_SHA_2_256)
  1275. .Authorization(TAG_MIN_MAC_LENGTH, 128));
  1276. string message = "123456789012345678901234567890123456789012345678";
  1277. string signature;
  1278. MacMessage(message, &signature, 256);
  1279. VerifyMac(message, signature);
  1280. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  1281. }
  1282. TEST_P(VerificationOperationsTest, HmacSha256TooShortMac) {
  1283. GenerateKey(AuthorizationSetBuilder()
  1284. .HmacKey(128)
  1285. .Digest(KM_DIGEST_SHA_2_256)
  1286. .Authorization(TAG_MIN_MAC_LENGTH, 128));
  1287. string message = "123456789012345678901234567890123456789012345678";
  1288. string signature;
  1289. MacMessage(message, &signature, 256);
  1290. // Shorten to 128 bits, should still work.
  1291. signature.resize(128 / 8);
  1292. VerifyMac(message, signature);
  1293. // Drop one more byte.
  1294. signature.resize(signature.length() - 1);
  1295. AuthorizationSet begin_params(client_params());
  1296. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
  1297. string result;
  1298. EXPECT_EQ(KM_ERROR_INVALID_MAC_LENGTH, FinishOperation(message, signature, &result));
  1299. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  1300. }
  1301. TEST_P(VerificationOperationsTest, HmacSha384Success) {
  1302. GenerateKey(AuthorizationSetBuilder()
  1303. .HmacKey(128)
  1304. .Digest(KM_DIGEST_SHA_2_384)
  1305. .Authorization(TAG_MIN_MAC_LENGTH, 128));
  1306. string message = "123456789012345678901234567890123456789012345678";
  1307. string signature;
  1308. MacMessage(message, &signature, 384);
  1309. VerifyMac(message, signature);
  1310. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  1311. }
  1312. TEST_P(VerificationOperationsTest, HmacSha512Success) {
  1313. GenerateKey(AuthorizationSetBuilder()
  1314. .HmacKey(128)
  1315. .Digest(KM_DIGEST_SHA_2_512)
  1316. .Authorization(TAG_MIN_MAC_LENGTH, 128));
  1317. string message = "123456789012345678901234567890123456789012345678";
  1318. string signature;
  1319. MacMessage(message, &signature, 512);
  1320. VerifyMac(message, signature);
  1321. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  1322. }
  1323. typedef Keymaster2Test ExportKeyTest;
  1324. INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, ExportKeyTest, test_params);
  1325. TEST_P(ExportKeyTest, RsaSuccess) {
  1326. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  1327. .RsaSigningKey(256, 3)
  1328. .Digest(KM_DIGEST_NONE)
  1329. .Padding(KM_PAD_NONE)));
  1330. string export_data;
  1331. ASSERT_EQ(KM_ERROR_OK, ExportKey(KM_KEY_FORMAT_X509, &export_data));
  1332. EXPECT_GT(export_data.length(), 0U);
  1333. // TODO(swillden): Verify that the exported key is actually usable to verify signatures.
  1334. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  1335. EXPECT_EQ(2, GetParam()->keymaster0_calls());
  1336. }
  1337. TEST_P(ExportKeyTest, EcdsaSuccess) {
  1338. ASSERT_EQ(KM_ERROR_OK,
  1339. GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(KM_DIGEST_NONE)));
  1340. string export_data;
  1341. ASSERT_EQ(KM_ERROR_OK, ExportKey(KM_KEY_FORMAT_X509, &export_data));
  1342. EXPECT_GT(export_data.length(), 0U);
  1343. // TODO(swillden): Verify that the exported key is actually usable to verify signatures.
  1344. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
  1345. EXPECT_EQ(2, GetParam()->keymaster0_calls());
  1346. }
  1347. TEST_P(ExportKeyTest, RsaUnsupportedKeyFormat) {
  1348. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  1349. .RsaSigningKey(256, 3)
  1350. .Digest(KM_DIGEST_NONE)
  1351. .Padding(KM_PAD_NONE)));
  1352. string export_data;
  1353. ASSERT_EQ(KM_ERROR_UNSUPPORTED_KEY_FORMAT, ExportKey(KM_KEY_FORMAT_PKCS8, &export_data));
  1354. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  1355. EXPECT_EQ(2, GetParam()->keymaster0_calls());
  1356. }
  1357. TEST_P(ExportKeyTest, RsaCorruptedKeyBlob) {
  1358. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  1359. .RsaSigningKey(256, 3)
  1360. .Digest(KM_DIGEST_NONE)
  1361. .Padding(KM_PAD_NONE)));
  1362. corrupt_key_blob();
  1363. string export_data;
  1364. ASSERT_EQ(KM_ERROR_INVALID_KEY_BLOB, ExportKey(KM_KEY_FORMAT_X509, &export_data));
  1365. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  1366. EXPECT_EQ(2, GetParam()->keymaster0_calls());
  1367. }
  1368. TEST_P(ExportKeyTest, AesKeyExportFails) {
  1369. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().AesEncryptionKey(128)));
  1370. string export_data;
  1371. EXPECT_EQ(KM_ERROR_UNSUPPORTED_KEY_FORMAT, ExportKey(KM_KEY_FORMAT_X509, &export_data));
  1372. EXPECT_EQ(KM_ERROR_UNSUPPORTED_KEY_FORMAT, ExportKey(KM_KEY_FORMAT_PKCS8, &export_data));
  1373. EXPECT_EQ(KM_ERROR_UNSUPPORTED_KEY_FORMAT, ExportKey(KM_KEY_FORMAT_RAW, &export_data));
  1374. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  1375. }
  1376. static string read_file(const string& file_name) {
  1377. ifstream file_stream(file_name, std::ios::binary);
  1378. istreambuf_iterator<char> file_begin(file_stream);
  1379. istreambuf_iterator<char> file_end;
  1380. return string(file_begin, file_end);
  1381. }
  1382. typedef Keymaster2Test ImportKeyTest;
  1383. INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, ImportKeyTest, test_params);
  1384. TEST_P(ImportKeyTest, RsaSuccess) {
  1385. string pk8_key = read_file("rsa_privkey_pk8.der");
  1386. ASSERT_EQ(633U, pk8_key.size());
  1387. ASSERT_EQ(KM_ERROR_OK, ImportKey(AuthorizationSetBuilder()
  1388. .RsaSigningKey(1024, 65537)
  1389. .Digest(KM_DIGEST_NONE)
  1390. .Padding(KM_PAD_NONE),
  1391. KM_KEY_FORMAT_PKCS8, pk8_key));
  1392. // Check values derived from the key.
  1393. EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA) ? hw_enforced()
  1394. : sw_enforced(),
  1395. TAG_ALGORITHM, KM_ALGORITHM_RSA));
  1396. EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA) ? hw_enforced()
  1397. : sw_enforced(),
  1398. TAG_KEY_SIZE, 1024));
  1399. EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA) ? hw_enforced()
  1400. : sw_enforced(),
  1401. TAG_RSA_PUBLIC_EXPONENT, 65537U));
  1402. // And values provided by AndroidKeymaster
  1403. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  1404. EXPECT_TRUE(contains(hw_enforced(), TAG_ORIGIN, KM_ORIGIN_UNKNOWN));
  1405. else
  1406. EXPECT_TRUE(contains(sw_enforced(), TAG_ORIGIN, KM_ORIGIN_IMPORTED));
  1407. EXPECT_TRUE(contains(sw_enforced(), KM_TAG_CREATION_DATETIME));
  1408. string message(1024 / 8, 'a');
  1409. string signature;
  1410. SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
  1411. VerifyMessage(message, signature, KM_DIGEST_NONE, KM_PAD_NONE);
  1412. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  1413. EXPECT_EQ(4, GetParam()->keymaster0_calls());
  1414. }
  1415. TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
  1416. string pk8_key = read_file("rsa_privkey_pk8.der");
  1417. ASSERT_EQ(633U, pk8_key.size());
  1418. ASSERT_EQ(KM_ERROR_IMPORT_PARAMETER_MISMATCH,
  1419. ImportKey(AuthorizationSetBuilder()
  1420. .RsaSigningKey(2048 /* Doesn't match key */, 3)
  1421. .Digest(KM_DIGEST_NONE)
  1422. .Padding(KM_PAD_NONE),
  1423. KM_KEY_FORMAT_PKCS8, pk8_key));
  1424. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  1425. }
  1426. TEST_P(ImportKeyTest, RsaPublicExponenMismatch) {
  1427. string pk8_key = read_file("rsa_privkey_pk8.der");
  1428. ASSERT_EQ(633U, pk8_key.size());
  1429. ASSERT_EQ(KM_ERROR_IMPORT_PARAMETER_MISMATCH,
  1430. ImportKey(AuthorizationSetBuilder()
  1431. .RsaSigningKey(256, 3 /* Doesnt' match key */)
  1432. .Digest(KM_DIGEST_NONE)
  1433. .Padding(KM_PAD_NONE),
  1434. KM_KEY_FORMAT_PKCS8, pk8_key));
  1435. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  1436. }
  1437. TEST_P(ImportKeyTest, EcdsaSuccess) {
  1438. string pk8_key = read_file("ec_privkey_pk8.der");
  1439. ASSERT_EQ(138U, pk8_key.size());
  1440. ASSERT_EQ(KM_ERROR_OK,
  1441. ImportKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(KM_DIGEST_NONE),
  1442. KM_KEY_FORMAT_PKCS8, pk8_key));
  1443. // Check values derived from the key.
  1444. EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC) ? hw_enforced()
  1445. : sw_enforced(),
  1446. TAG_ALGORITHM, KM_ALGORITHM_EC));
  1447. EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC) ? hw_enforced()
  1448. : sw_enforced(),
  1449. TAG_KEY_SIZE, 256));
  1450. // And values provided by AndroidKeymaster
  1451. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
  1452. EXPECT_TRUE(contains(hw_enforced(), TAG_ORIGIN, KM_ORIGIN_UNKNOWN));
  1453. else
  1454. EXPECT_TRUE(contains(sw_enforced(), TAG_ORIGIN, KM_ORIGIN_IMPORTED));
  1455. EXPECT_TRUE(contains(sw_enforced(), KM_TAG_CREATION_DATETIME));
  1456. string message(32, 'a');
  1457. string signature;
  1458. SignMessage(message, &signature, KM_DIGEST_NONE);
  1459. VerifyMessage(message, signature, KM_DIGEST_NONE);
  1460. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
  1461. EXPECT_EQ(4, GetParam()->keymaster0_calls());
  1462. }
  1463. TEST_P(ImportKeyTest, EcdsaSizeSpecified) {
  1464. string pk8_key = read_file("ec_privkey_pk8.der");
  1465. ASSERT_EQ(138U, pk8_key.size());
  1466. ASSERT_EQ(KM_ERROR_OK,
  1467. ImportKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(KM_DIGEST_NONE),
  1468. KM_KEY_FORMAT_PKCS8, pk8_key));
  1469. // Check values derived from the key.
  1470. EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC) ? hw_enforced()
  1471. : sw_enforced(),
  1472. TAG_ALGORITHM, KM_ALGORITHM_EC));
  1473. EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC) ? hw_enforced()
  1474. : sw_enforced(),
  1475. TAG_KEY_SIZE, 256));
  1476. // And values provided by AndroidKeymaster
  1477. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
  1478. EXPECT_TRUE(contains(hw_enforced(), TAG_ORIGIN, KM_ORIGIN_UNKNOWN));
  1479. else
  1480. EXPECT_TRUE(contains(sw_enforced(), TAG_ORIGIN, KM_ORIGIN_IMPORTED));
  1481. EXPECT_TRUE(contains(sw_enforced(), KM_TAG_CREATION_DATETIME));
  1482. string message(32, 'a');
  1483. string signature;
  1484. SignMessage(message, &signature, KM_DIGEST_NONE);
  1485. VerifyMessage(message, signature, KM_DIGEST_NONE);
  1486. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
  1487. EXPECT_EQ(4, GetParam()->keymaster0_calls());
  1488. }
  1489. TEST_P(ImportKeyTest, EcdsaSizeMismatch) {
  1490. string pk8_key = read_file("ec_privkey_pk8.der");
  1491. ASSERT_EQ(138U, pk8_key.size());
  1492. ASSERT_EQ(KM_ERROR_IMPORT_PARAMETER_MISMATCH,
  1493. ImportKey(AuthorizationSetBuilder()
  1494. .EcdsaSigningKey(224 /* Doesn't match key */)
  1495. .Digest(KM_DIGEST_NONE),
  1496. KM_KEY_FORMAT_PKCS8, pk8_key));
  1497. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  1498. }
  1499. TEST_P(ImportKeyTest, AesKeySuccess) {
  1500. char key_data[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  1501. string key(key_data, sizeof(key_data));
  1502. ASSERT_EQ(KM_ERROR_OK,
  1503. ImportKey(AuthorizationSetBuilder().AesEncryptionKey(128).EcbMode().Authorization(
  1504. TAG_PADDING, KM_PAD_PKCS7),
  1505. KM_KEY_FORMAT_RAW, key));
  1506. EXPECT_TRUE(contains(sw_enforced(), TAG_ORIGIN, KM_ORIGIN_IMPORTED));
  1507. EXPECT_TRUE(contains(sw_enforced(), KM_TAG_CREATION_DATETIME));
  1508. string message = "Hello World!";
  1509. string ciphertext = EncryptMessage(message, KM_MODE_ECB, KM_PAD_PKCS7);
  1510. string plaintext = DecryptMessage(ciphertext, KM_MODE_ECB, KM_PAD_PKCS7);
  1511. EXPECT_EQ(message, plaintext);
  1512. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  1513. }
  1514. TEST_P(ImportKeyTest, HmacSha256KeySuccess) {
  1515. char key_data[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  1516. string key(key_data, sizeof(key_data));
  1517. ASSERT_EQ(KM_ERROR_OK, ImportKey(AuthorizationSetBuilder()
  1518. .HmacKey(sizeof(key_data) * 8)
  1519. .Digest(KM_DIGEST_SHA_2_256)
  1520. .Authorization(TAG_MIN_MAC_LENGTH, 256),
  1521. KM_KEY_FORMAT_RAW, key));
  1522. EXPECT_TRUE(contains(sw_enforced(), TAG_ORIGIN, KM_ORIGIN_IMPORTED));
  1523. EXPECT_TRUE(contains(sw_enforced(), KM_TAG_CREATION_DATETIME));
  1524. string message = "Hello World!";
  1525. string signature;
  1526. MacMessage(message, &signature, 256);
  1527. VerifyMac(message, signature);
  1528. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  1529. }
  1530. string wrapped_key = hex2str(
  1531. "3082017302010004820100A2B7988012A043CE83E762A4E4D3C86D578B2E1EA5E04138353114A816951308E3222AFA"
  1532. "D86CA141C581198E65BC56D9EEDC5B555713BE2C20948DD076AB4980305871317F89DD3A7A67FBBB7AACF6941C06B2"
  1533. "65396D894A6DCC7B9FB152FFA8CBF44FF8063748795F3FB506DF8718535289E759075A13A5DDC83EF8470549AA7794"
  1534. "3AFBACF6CF82DCE3751E05BFE05F30B998D73E23611E6EAEFC2A497E097A895C4242607B472AE8F19DA77A9A5A4786"
  1535. "75541FC813C9213B5CE8C2E598BFBBCD1B369E3D7AEC0274F9B79118D8AA5FBB7634EBD3C4C2AF3B5DA483DF2CFDF1"
  1536. "E68A3BFC7B6C0D503AF88E82C9EE841A278B144FF8D39F2DB2ACE9415C120190040CD796B02C370F1FA4CC0124F130"
  1537. "280201033023A1083106020100020101A203020120A30402020100A4053103020101A60531030201400420CCD54085"
  1538. "5F833A5E1480BFD2D36FAF3AEEE15DF5BEABE2691BC82DDE2A7AA91004107CB81BDDCD09E8F4DF575726279F3229");
  1539. string wrapped_key_masked = hex2str(
  1540. "30820173020100048201008CBEE0DC600215FFC85FC26B57DD2331DDF5D3E106C0A68BFEF167AFD428041D9B7C3316"
  1541. "110BBB914A86FC24D4EF5C6A4673C9B3CC914C7806453650753B5130C4FE72264A52C1A270286032513F24EB3E033A"
  1542. "BCC26A9D6AEFD0D0AD3E922E4E737ECDAD3C4DF2ABDB416378E67381BE0391175EC8F05FDFBC3794B7D0D88298010F"
  1543. "E9B6F788BC049D874575D2D4C33DB582B113694738A9151BBC7603D3556B26FEC0279EE1C1CA44D6F7F91F4C424912"
  1544. "7F9CC3232DE8B0AEFFD5AFAD4C3D5B846FD26873315606F6457BC19447FD7C6431550D6E6592A0555E61C7A021D149"
  1545. "BCEE7A858DD6D4A8E230C6015EEDF0A58F4CAA8A6D0E3A1E3794CAEE7854CE92040C6D9721D08589581AB49204A330"
  1546. "280201033023A1083106020100020101A203020120A30402020100A4053103020101A60531030201400420A61C6E24"
  1547. "7E25B3E6E69AA78EB03C2D4AC20D1F99A9A024A76F35C8E2CAB9B68D04101FF7A0E793B9EE4AECEBB9AC4C545254");
  1548. string wrapping_key = hex2str(
  1549. "308204be020100300d06092a864886f70d0101010500048204a8308204a40201000282010100aec367931d8900ce56"
  1550. "b0067f7d70e1fc653f3f34d194c1fed50018fb43db937b06e673a837313d56b1c725150a3fef86acbddc41bb759c28"
  1551. "54eae32d35841efb5c18d82bc90a1cb5c1d55adf245b02911f0b7cda88c421ff0ebafe7c0d23be312d7bd5921ffaea"
  1552. "1347c157406fef718f682643e4e5d33c6703d61c0cf7ac0bf4645c11f5c1374c3886427411c449796792e0bef75dec"
  1553. "858a2123c36753e02a95a96d7c454b504de385a642e0dfc3e60ac3a7ee4991d0d48b0172a95f9536f02ba13cecccb9"
  1554. "2b727db5c27e5b2f5cec09600b286af5cf14c42024c61ddfe71c2a8d7458f185234cb00e01d282f10f8fc6721d2aed"
  1555. "3f4833cca2bd8fa62821dd55020301000102820100431447b6251908112b1ee76f99f3711a52b6630960046c2de70d"
  1556. "e188d833f8b8b91e4d785caeeeaf4f0f74414e2cda40641f7fe24f14c67a88959bdb27766df9e710b630a03adc683b"
  1557. "5d2c43080e52bee71e9eaeb6de297a5fea1072070d181c822bccff087d63c940ba8a45f670feb29fb4484d1c95e6d2"
  1558. "579ba02aae0a00900c3ebf490e3d2cd7ee8d0e20c536e4dc5a5097272888cddd7e91f228b1c4d7474c55b8fcd618c4"
  1559. "a957bbddd5ad7407cc312d8d98a5caf7e08f4a0d6b45bb41c652659d5a5ba05b663737a8696281865ba20fbdd7f851"
  1560. "e6c56e8cbe0ddbbf24dc03b2d2cb4c3d540fb0af52e034a2d06698b128e5f101e3b51a34f8d8b4f8618102818100de"
  1561. "392e18d682c829266cc3454e1d6166242f32d9a1d10577753e904ea7d08bff841be5bac82a164c5970007047b8c517"
  1562. "db8f8f84e37bd5988561bdf503d4dc2bdb38f885434ae42c355f725c9a60f91f0788e1f1a97223b524b5357fdf72e2"
  1563. "f696bab7d78e32bf92ba8e1864eab1229e91346130748a6e3c124f9149d71c743502818100c95387c0f9d35f137b57"
  1564. "d0d65c397c5e21cc251e47008ed62a542409c8b6b6ac7f8967b3863ca645fcce49582a9aa17349db6c4a95affdae0d"
  1565. "ae612e1afac99ed39a2d934c880440aed8832f9843163a47f27f392199dc1202f9a0f9bd08308007cb1e4e7f583093"
  1566. "66a7de25f7c3c9b880677c068e1be936e81288815252a8a102818057ff8ca1895080b2cae486ef0adfd791fb0235c0"
  1567. "b8b36cd6c136e52e4085f4ea5a063212a4f105a3764743e53281988aba073f6e0027298e1c4378556e0efca0e14ece"
  1568. "1af76ad0b030f27af6f0ab35fb73a060d8b1a0e142fa2647e93b32e36d8282ae0a4de50ab7afe85500a16f43a64719"
  1569. "d6e2b9439823719cd08bcd03178102818100ba73b0bb28e3f81e9bd1c568713b101241acc607976c4ddccc90e65b65"
  1570. "56ca31516058f92b6e09f3b160ff0e374ec40d78ae4d4979fde6ac06a1a400c61dd31254186af30b22c10582a8a43e"
  1571. "34fe949c5f3b9755bae7baa7b7b7a6bd03b38cef55c86885fc6c1978b9cee7ef33da507c9df6b9277cff1e6aaa5d57"
  1572. "aca528466102818100c931617c77829dfb1270502be9195c8f2830885f57dba869536811e6864236d0c4736a0008a1"
  1573. "45af36b8357a7c3d139966d04c4e00934ea1aede3bb6b8ec841dc95e3f579751e2bfdfe27ae778983f959356210723"
  1574. "287b0affcc9f727044d48c373f1babde0724fa17a4fd4da0902c7c9b9bf27ba61be6ad02dfddda8f4e6822");
  1575. string zero_masking_key =
  1576. hex2str("0000000000000000000000000000000000000000000000000000000000000000");
  1577. string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
  1578. class ImportWrappedKeyTest : public testing::Test {
  1579. public:
  1580. ImportWrappedKeyTest() : keymaster_(new PureSoftKeymasterContext(), 16) {}
  1581. protected:
  1582. void SetUp() override {
  1583. ConfigureRequest configReq;
  1584. configReq.os_version = kOsVersion;
  1585. configReq.os_patchlevel = kOsPatchLevel;
  1586. ConfigureResponse configRsp;
  1587. keymaster_.Configure(configReq, &configRsp);
  1588. EXPECT_EQ(KM_ERROR_OK, configRsp.error);
  1589. }
  1590. keymaster_error_t BeginOperation(keymaster_purpose_t purpose,
  1591. const AuthorizationSet& input_set) {
  1592. BeginOperationRequest req;
  1593. req.purpose = purpose;
  1594. req.SetKeyMaterial(blob_);
  1595. req.additional_params = input_set;
  1596. BeginOperationResponse rsp;
  1597. keymaster_.BeginOperation(req, &rsp);
  1598. op_handle_ = rsp.op_handle;
  1599. return rsp.error;
  1600. }
  1601. keymaster_error_t FinishOperation(const string& input, string* output) {
  1602. FinishOperationRequest req;
  1603. req.op_handle = op_handle_;
  1604. req.input.Reinitialize(input.data(), input.size());
  1605. FinishOperationResponse rsp;
  1606. keymaster_.FinishOperation(req, &rsp);
  1607. if (output) {
  1608. *output = string(reinterpret_cast<const char*>(rsp.output.peek_read()),
  1609. rsp.output.available_read());
  1610. }
  1611. return rsp.error;
  1612. }
  1613. string ProcessMessage(keymaster_purpose_t purpose, const string& message,
  1614. const AuthorizationSet& begin_params) {
  1615. EXPECT_EQ(KM_ERROR_OK, BeginOperation(purpose, begin_params));
  1616. string result;
  1617. EXPECT_EQ(KM_ERROR_OK, FinishOperation(message, &result));
  1618. return result;
  1619. }
  1620. AndroidKeymaster keymaster_;
  1621. KeymasterKeyBlob blob_;
  1622. uint64_t op_handle_;
  1623. };
  1624. TEST_F(ImportWrappedKeyTest, GoldenKeySuccess) {
  1625. ImportKeyRequest import_request;
  1626. auto import_params = AuthorizationSetBuilder()
  1627. .RsaEncryptionKey(2048, 65537)
  1628. .Digest(KM_DIGEST_SHA1)
  1629. .Padding(KM_PAD_RSA_OAEP)
  1630. .Authorization(TAG_PURPOSE, KM_PURPOSE_WRAP)
  1631. .build();
  1632. import_request.key_description.Reinitialize(import_params);
  1633. import_request.SetKeyMaterial(reinterpret_cast<const uint8_t*>(wrapping_key.c_str()),
  1634. wrapping_key.size());
  1635. import_request.key_format = KM_KEY_FORMAT_PKCS8;
  1636. ImportKeyResponse import_response;
  1637. keymaster_.ImportKey(import_request, &import_response);
  1638. ASSERT_EQ(import_response.error, KM_ERROR_OK);
  1639. ImportWrappedKeyRequest request;
  1640. KeymasterKeyBlob wrapped_key_blob(reinterpret_cast<const uint8_t*>(wrapped_key.c_str()),
  1641. wrapped_key.size());
  1642. request.SetKeyMaterial(wrapped_key_blob, import_response.key_blob);
  1643. request.SetMaskingKeyMaterial(reinterpret_cast<const uint8_t*>(zero_masking_key.c_str()),
  1644. zero_masking_key.size());
  1645. ImportWrappedKeyResponse response;
  1646. keymaster_.ImportWrappedKey(request, &response);
  1647. EXPECT_EQ(response.error, KM_ERROR_OK);
  1648. // Check that the tags from the wrapped auth list were imported correctly
  1649. ASSERT_EQ(response.key_blob.key_material_size > 0, true);
  1650. ASSERT_EQ(response.unenforced.Contains(TAG_ALGORITHM), true);
  1651. ASSERT_EQ(response.unenforced.Contains(TAG_KEY_SIZE), true);
  1652. ASSERT_EQ(response.unenforced.Contains(TAG_PURPOSE), true);
  1653. ASSERT_EQ(response.unenforced.Contains(TAG_BLOCK_MODE), true);
  1654. blob_ = move(response.key_blob);
  1655. string message = "Hello World!";
  1656. auto params = AuthorizationSetBuilder().BlockMode(KM_MODE_ECB).Padding(KM_PAD_PKCS7).build();
  1657. string ciphertext = ProcessMessage(KM_PURPOSE_ENCRYPT, message, params);
  1658. string plaintext = ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext, params);
  1659. EXPECT_EQ(message, plaintext);
  1660. }
  1661. TEST_F(ImportWrappedKeyTest, SuccessMaskingKey) {
  1662. ImportKeyRequest import_request;
  1663. auto import_params = AuthorizationSetBuilder()
  1664. .RsaEncryptionKey(2048, 65537)
  1665. .Digest(KM_DIGEST_SHA1)
  1666. .Padding(KM_PAD_RSA_OAEP)
  1667. .Authorization(TAG_PURPOSE, KM_PURPOSE_WRAP)
  1668. .build();
  1669. import_request.key_description.Reinitialize(import_params);
  1670. import_request.SetKeyMaterial(reinterpret_cast<const uint8_t*>(wrapping_key.c_str()),
  1671. wrapping_key.size());
  1672. import_request.key_format = KM_KEY_FORMAT_PKCS8;
  1673. ImportKeyResponse import_response;
  1674. keymaster_.ImportKey(import_request, &import_response);
  1675. EXPECT_EQ(import_response.error, KM_ERROR_OK);
  1676. if (import_response.error != KM_ERROR_OK) return;
  1677. ImportWrappedKeyRequest request;
  1678. KeymasterKeyBlob wrapped_key_blob(reinterpret_cast<const uint8_t*>(wrapped_key_masked.c_str()),
  1679. wrapped_key_masked.size());
  1680. request.SetKeyMaterial(wrapped_key_blob, import_response.key_blob);
  1681. request.SetMaskingKeyMaterial(reinterpret_cast<const uint8_t*>(masking_key.c_str()),
  1682. masking_key.size());
  1683. ImportWrappedKeyResponse response;
  1684. keymaster_.ImportWrappedKey(request, &response);
  1685. EXPECT_EQ(response.error, KM_ERROR_OK);
  1686. }
  1687. TEST_F(ImportWrappedKeyTest, WrongMaskingKey) {
  1688. ImportKeyRequest import_request;
  1689. auto import_params = AuthorizationSetBuilder()
  1690. .RsaEncryptionKey(2048, 65537)
  1691. .Digest(KM_DIGEST_SHA1)
  1692. .Padding(KM_PAD_RSA_OAEP)
  1693. .Authorization(TAG_PURPOSE, KM_PURPOSE_WRAP)
  1694. .build();
  1695. import_request.key_description.Reinitialize(import_params);
  1696. import_request.SetKeyMaterial(reinterpret_cast<const uint8_t*>(wrapping_key.c_str()),
  1697. wrapping_key.size());
  1698. import_request.key_format = KM_KEY_FORMAT_PKCS8;
  1699. ImportKeyResponse import_response;
  1700. keymaster_.ImportKey(import_request, &import_response);
  1701. EXPECT_EQ(import_response.error, KM_ERROR_OK);
  1702. if (import_response.error != KM_ERROR_OK) return;
  1703. ImportWrappedKeyRequest request;
  1704. KeymasterKeyBlob wrapped_key_blob(reinterpret_cast<const uint8_t*>(wrapped_key_masked.c_str()),
  1705. wrapped_key_masked.size());
  1706. request.SetKeyMaterial(wrapped_key_blob, import_response.key_blob);
  1707. request.SetMaskingKeyMaterial(reinterpret_cast<const uint8_t*>(zero_masking_key.c_str()),
  1708. zero_masking_key.size());
  1709. ImportWrappedKeyResponse response;
  1710. keymaster_.ImportWrappedKey(request, &response);
  1711. EXPECT_EQ(response.error, KM_ERROR_VERIFICATION_FAILED);
  1712. }
  1713. TEST_F(ImportWrappedKeyTest, WrongPurpose) {
  1714. ImportKeyRequest import_request;
  1715. auto import_params = AuthorizationSetBuilder()
  1716. .RsaEncryptionKey(2048, 65537)
  1717. .Digest(KM_DIGEST_SHA1)
  1718. .Padding(KM_PAD_RSA_OAEP)
  1719. .build();
  1720. import_request.key_description.Reinitialize(import_params);
  1721. import_request.SetKeyMaterial(reinterpret_cast<const uint8_t*>(wrapping_key.c_str()),
  1722. wrapping_key.size());
  1723. import_request.key_format = KM_KEY_FORMAT_PKCS8;
  1724. ImportKeyResponse import_response;
  1725. keymaster_.ImportKey(import_request, &import_response);
  1726. EXPECT_EQ(import_response.error, KM_ERROR_OK);
  1727. if (import_response.error != KM_ERROR_OK) return;
  1728. ImportWrappedKeyRequest request;
  1729. KeymasterKeyBlob wrapped_key_blob(reinterpret_cast<const uint8_t*>(wrapped_key.c_str()),
  1730. wrapped_key.size());
  1731. request.SetKeyMaterial(wrapped_key_blob, import_response.key_blob);
  1732. ImportWrappedKeyResponse response;
  1733. keymaster_.ImportWrappedKey(request, &response);
  1734. EXPECT_EQ(response.error, KM_ERROR_INCOMPATIBLE_PURPOSE);
  1735. }
  1736. typedef Keymaster2Test EncryptionOperationsTest;
  1737. INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, EncryptionOperationsTest, test_params);
  1738. TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
  1739. ASSERT_EQ(KM_ERROR_OK,
  1740. GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(256, 3).Padding(KM_PAD_NONE)));
  1741. string message = "12345678901234567890123456789012";
  1742. string ciphertext1 = EncryptMessage(string(message), KM_PAD_NONE);
  1743. EXPECT_EQ(256U / 8, ciphertext1.size());
  1744. string ciphertext2 = EncryptMessage(string(message), KM_PAD_NONE);
  1745. EXPECT_EQ(256U / 8, ciphertext2.size());
  1746. // Unpadded RSA is deterministic
  1747. EXPECT_EQ(ciphertext1, ciphertext2);
  1748. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  1749. EXPECT_EQ(3, GetParam()->keymaster0_calls());
  1750. }
  1751. TEST_P(EncryptionOperationsTest, RsaNoPaddingTooShort) {
  1752. ASSERT_EQ(KM_ERROR_OK,
  1753. GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(256, 3).Padding(KM_PAD_NONE)));
  1754. string message = "1";
  1755. string ciphertext = EncryptMessage(message, KM_PAD_NONE);
  1756. EXPECT_EQ(256U / 8, ciphertext.size());
  1757. string expected_plaintext = string(256 / 8 - 1, 0) + message;
  1758. string plaintext = DecryptMessage(ciphertext, KM_PAD_NONE);
  1759. EXPECT_EQ(expected_plaintext, plaintext);
  1760. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  1761. EXPECT_EQ(4, GetParam()->keymaster0_calls());
  1762. }
  1763. TEST_P(EncryptionOperationsTest, RsaNoPaddingTooLong) {
  1764. ASSERT_EQ(KM_ERROR_OK,
  1765. GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(256, 3).Padding(KM_PAD_NONE)));
  1766. string message = "123456789012345678901234567890123";
  1767. AuthorizationSet begin_params(client_params());
  1768. begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
  1769. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
  1770. string result;
  1771. size_t input_consumed;
  1772. EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, UpdateOperation(message, &result, &input_consumed));
  1773. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  1774. EXPECT_EQ(2, GetParam()->keymaster0_calls());
  1775. }
  1776. TEST_P(EncryptionOperationsTest, RsaNoPaddingLargerThanModulus) {
  1777. ASSERT_EQ(KM_ERROR_OK,
  1778. GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(256, 3).Padding(KM_PAD_NONE)));
  1779. string exported;
  1780. ASSERT_EQ(KM_ERROR_OK, ExportKey(KM_KEY_FORMAT_X509, &exported));
  1781. const uint8_t* p = reinterpret_cast<const uint8_t*>(exported.data());
  1782. unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(
  1783. d2i_PUBKEY(nullptr /* alloc new */, &p, exported.size()));
  1784. unique_ptr<RSA, RSA_Delete> rsa(EVP_PKEY_get1_RSA(pkey.get()));
  1785. size_t modulus_len = BN_num_bytes(rsa->n);
  1786. ASSERT_EQ(256U / 8, modulus_len);
  1787. unique_ptr<uint8_t[]> modulus_buf(new uint8_t[modulus_len]);
  1788. BN_bn2bin(rsa->n, modulus_buf.get());
  1789. // The modulus is too big to encrypt.
  1790. string message(reinterpret_cast<const char*>(modulus_buf.get()), modulus_len);
  1791. AuthorizationSet begin_params(client_params());
  1792. begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
  1793. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
  1794. string result;
  1795. size_t input_consumed;
  1796. EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
  1797. EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, FinishOperation(&result));
  1798. // One smaller than the modulus is okay.
  1799. BN_sub(rsa->n, rsa->n, BN_value_one());
  1800. modulus_len = BN_num_bytes(rsa->n);
  1801. ASSERT_EQ(256U / 8, modulus_len);
  1802. BN_bn2bin(rsa->n, modulus_buf.get());
  1803. message = string(reinterpret_cast<const char*>(modulus_buf.get()), modulus_len);
  1804. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
  1805. EXPECT_EQ(KM_ERROR_OK, FinishOperation(message, "", &result));
  1806. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  1807. EXPECT_EQ(4, GetParam()->keymaster0_calls());
  1808. }
  1809. TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
  1810. size_t key_size = 768;
  1811. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  1812. .RsaEncryptionKey(key_size, 3)
  1813. .Padding(KM_PAD_RSA_OAEP)
  1814. .Digest(KM_DIGEST_SHA_2_256)));
  1815. string message = "Hello";
  1816. string ciphertext1 = EncryptMessage(string(message), KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
  1817. EXPECT_EQ(key_size / 8, ciphertext1.size());
  1818. string ciphertext2 = EncryptMessage(string(message), KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
  1819. EXPECT_EQ(key_size / 8, ciphertext2.size());
  1820. // OAEP randomizes padding so every result should be different.
  1821. EXPECT_NE(ciphertext1, ciphertext2);
  1822. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  1823. EXPECT_EQ(3, GetParam()->keymaster0_calls());
  1824. }
  1825. TEST_P(EncryptionOperationsTest, RsaOaepSha224Success) {
  1826. size_t key_size = 768;
  1827. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  1828. .RsaEncryptionKey(key_size, 3)
  1829. .Padding(KM_PAD_RSA_OAEP)
  1830. .Digest(KM_DIGEST_SHA_2_224)));
  1831. string message = "Hello";
  1832. string ciphertext1 = EncryptMessage(string(message), KM_DIGEST_SHA_2_224, KM_PAD_RSA_OAEP);
  1833. EXPECT_EQ(key_size / 8, ciphertext1.size());
  1834. string ciphertext2 = EncryptMessage(string(message), KM_DIGEST_SHA_2_224, KM_PAD_RSA_OAEP);
  1835. EXPECT_EQ(key_size / 8, ciphertext2.size());
  1836. // OAEP randomizes padding so every result should be different.
  1837. EXPECT_NE(ciphertext1, ciphertext2);
  1838. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  1839. EXPECT_EQ(3, GetParam()->keymaster0_calls());
  1840. }
  1841. TEST_P(EncryptionOperationsTest, RsaOaepRoundTrip) {
  1842. size_t key_size = 768;
  1843. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  1844. .RsaEncryptionKey(key_size, 3)
  1845. .Padding(KM_PAD_RSA_OAEP)
  1846. .Digest(KM_DIGEST_SHA_2_256)));
  1847. string message = "Hello World!";
  1848. string ciphertext = EncryptMessage(string(message), KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
  1849. EXPECT_EQ(key_size / 8, ciphertext.size());
  1850. string plaintext = DecryptMessage(ciphertext, KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
  1851. EXPECT_EQ(message, plaintext);
  1852. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  1853. EXPECT_EQ(4, GetParam()->keymaster0_calls());
  1854. }
  1855. TEST_P(EncryptionOperationsTest, RsaOaepSha224RoundTrip) {
  1856. size_t key_size = 768;
  1857. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  1858. .RsaEncryptionKey(key_size, 3)
  1859. .Padding(KM_PAD_RSA_OAEP)
  1860. .Digest(KM_DIGEST_SHA_2_224)));
  1861. string message = "Hello World!";
  1862. string ciphertext = EncryptMessage(string(message), KM_DIGEST_SHA_2_224, KM_PAD_RSA_OAEP);
  1863. EXPECT_EQ(key_size / 8, ciphertext.size());
  1864. string plaintext = DecryptMessage(ciphertext, KM_DIGEST_SHA_2_224, KM_PAD_RSA_OAEP);
  1865. EXPECT_EQ(message, plaintext);
  1866. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  1867. EXPECT_EQ(4, GetParam()->keymaster0_calls());
  1868. }
  1869. TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
  1870. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  1871. .RsaEncryptionKey(512, 3)
  1872. .Padding(KM_PAD_RSA_OAEP)
  1873. .Digest(KM_DIGEST_NONE)));
  1874. string message = "Hello World!";
  1875. AuthorizationSet begin_params(client_params());
  1876. begin_params.push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
  1877. begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
  1878. EXPECT_EQ(KM_ERROR_INCOMPATIBLE_DIGEST, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
  1879. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  1880. EXPECT_EQ(2, GetParam()->keymaster0_calls());
  1881. }
  1882. TEST_P(EncryptionOperationsTest, RsaOaepUnauthorizedDigest) {
  1883. if (GetParam()->minimal_digest_set())
  1884. // We don't have two supported digests, so we can't try authorizing one and using another.
  1885. return;
  1886. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  1887. .RsaEncryptionKey(512, 3)
  1888. .Padding(KM_PAD_RSA_OAEP)
  1889. .Digest(KM_DIGEST_SHA_2_256)));
  1890. string message = "Hello World!";
  1891. // Works because encryption is a public key operation.
  1892. EncryptMessage(string(message), KM_DIGEST_SHA1, KM_PAD_RSA_OAEP);
  1893. AuthorizationSet begin_params(client_params());
  1894. begin_params.push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
  1895. begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA1);
  1896. EXPECT_EQ(KM_ERROR_INCOMPATIBLE_DIGEST, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
  1897. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  1898. EXPECT_EQ(3, GetParam()->keymaster0_calls());
  1899. }
  1900. TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
  1901. if (GetParam()->minimal_digest_set())
  1902. // We don't have two supported digests, so we can't try encrypting with one and decrypting
  1903. // with another.
  1904. return;
  1905. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  1906. .RsaEncryptionKey(768, 3)
  1907. .Padding(KM_PAD_RSA_OAEP)
  1908. .Digest(KM_DIGEST_SHA_2_256)
  1909. .Digest(KM_DIGEST_SHA_2_384)));
  1910. string message = "Hello World!";
  1911. string ciphertext = EncryptMessage(string(message), KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
  1912. string result;
  1913. size_t input_consumed;
  1914. AuthorizationSet begin_params(client_params());
  1915. begin_params.push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
  1916. begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_384);
  1917. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
  1918. EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext, &result, &input_consumed));
  1919. EXPECT_EQ(KM_ERROR_UNKNOWN_ERROR, FinishOperation(&result));
  1920. EXPECT_EQ(0U, result.size());
  1921. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  1922. EXPECT_EQ(4, GetParam()->keymaster0_calls());
  1923. }
  1924. TEST_P(EncryptionOperationsTest, RsaOaepTooLarge) {
  1925. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  1926. .RsaEncryptionKey(512, 3)
  1927. .Padding(KM_PAD_RSA_OAEP)
  1928. .Digest(KM_DIGEST_SHA1)));
  1929. string message = "12345678901234567890123";
  1930. string result;
  1931. size_t input_consumed;
  1932. AuthorizationSet begin_params(client_params());
  1933. begin_params.push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
  1934. begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA1);
  1935. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
  1936. EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
  1937. EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, FinishOperation(&result));
  1938. EXPECT_EQ(0U, result.size());
  1939. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  1940. EXPECT_EQ(2, GetParam()->keymaster0_calls());
  1941. }
  1942. TEST_P(EncryptionOperationsTest, RsaOaepCorruptedDecrypt) {
  1943. size_t key_size = 768;
  1944. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  1945. .RsaEncryptionKey(768, 3)
  1946. .Padding(KM_PAD_RSA_OAEP)
  1947. .Digest(KM_DIGEST_SHA_2_256)));
  1948. string message = "Hello World!";
  1949. string ciphertext = EncryptMessage(string(message), KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
  1950. EXPECT_EQ(key_size / 8, ciphertext.size());
  1951. // Corrupt the ciphertext
  1952. ciphertext[key_size / 8 / 2]++;
  1953. string result;
  1954. size_t input_consumed;
  1955. AuthorizationSet begin_params(client_params());
  1956. begin_params.push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
  1957. begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
  1958. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
  1959. EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext, &result, &input_consumed));
  1960. EXPECT_EQ(KM_ERROR_UNKNOWN_ERROR, FinishOperation(&result));
  1961. EXPECT_EQ(0U, result.size());
  1962. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  1963. EXPECT_EQ(4, GetParam()->keymaster0_calls());
  1964. }
  1965. TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
  1966. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(512, 3).Padding(
  1967. KM_PAD_RSA_PKCS1_1_5_ENCRYPT)));
  1968. string message = "Hello World!";
  1969. string ciphertext1 = EncryptMessage(message, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
  1970. EXPECT_EQ(512U / 8, ciphertext1.size());
  1971. string ciphertext2 = EncryptMessage(message, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
  1972. EXPECT_EQ(512U / 8, ciphertext2.size());
  1973. // PKCS1 v1.5 randomizes padding so every result should be different.
  1974. EXPECT_NE(ciphertext1, ciphertext2);
  1975. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  1976. EXPECT_EQ(3, GetParam()->keymaster0_calls());
  1977. }
  1978. TEST_P(EncryptionOperationsTest, RsaPkcs1RoundTrip) {
  1979. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(512, 3).Padding(
  1980. KM_PAD_RSA_PKCS1_1_5_ENCRYPT)));
  1981. string message = "Hello World!";
  1982. string ciphertext = EncryptMessage(message, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
  1983. EXPECT_EQ(512U / 8, ciphertext.size());
  1984. string plaintext = DecryptMessage(ciphertext, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
  1985. EXPECT_EQ(message, plaintext);
  1986. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  1987. EXPECT_EQ(4, GetParam()->keymaster0_calls());
  1988. }
  1989. TEST_P(EncryptionOperationsTest, RsaRoundTripAllCombinations) {
  1990. size_t key_size = 2048;
  1991. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  1992. .RsaEncryptionKey(key_size, 3)
  1993. .Padding(KM_PAD_RSA_PKCS1_1_5_ENCRYPT)
  1994. .Padding(KM_PAD_RSA_OAEP)
  1995. .Digest(KM_DIGEST_NONE)
  1996. .Digest(KM_DIGEST_MD5)
  1997. .Digest(KM_DIGEST_SHA1)
  1998. .Digest(KM_DIGEST_SHA_2_224)
  1999. .Digest(KM_DIGEST_SHA_2_256)
  2000. .Digest(KM_DIGEST_SHA_2_384)
  2001. .Digest(KM_DIGEST_SHA_2_512)));
  2002. string message = "Hello World!";
  2003. keymaster_padding_t padding_modes[] = {KM_PAD_RSA_OAEP, KM_PAD_RSA_PKCS1_1_5_ENCRYPT};
  2004. keymaster_digest_t digests[] = {
  2005. KM_DIGEST_NONE, KM_DIGEST_MD5, KM_DIGEST_SHA1, KM_DIGEST_SHA_2_224,
  2006. KM_DIGEST_SHA_2_256, KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512,
  2007. };
  2008. for (auto padding : padding_modes)
  2009. for (auto digest : digests) {
  2010. if (padding == KM_PAD_RSA_OAEP && digest == KM_DIGEST_NONE)
  2011. // OAEP requires a digest.
  2012. continue;
  2013. string ciphertext = EncryptMessage(message, digest, padding);
  2014. EXPECT_EQ(key_size / 8, ciphertext.size());
  2015. string plaintext = DecryptMessage(ciphertext, digest, padding);
  2016. EXPECT_EQ(message, plaintext);
  2017. }
  2018. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  2019. EXPECT_EQ(40, GetParam()->keymaster0_calls());
  2020. }
  2021. TEST_P(EncryptionOperationsTest, RsaPkcs1TooLarge) {
  2022. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(512, 3).Padding(
  2023. KM_PAD_RSA_PKCS1_1_5_ENCRYPT)));
  2024. string message = "123456789012345678901234567890123456789012345678901234";
  2025. string result;
  2026. size_t input_consumed;
  2027. AuthorizationSet begin_params(client_params());
  2028. begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
  2029. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
  2030. EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
  2031. EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, FinishOperation(&result));
  2032. EXPECT_EQ(0U, result.size());
  2033. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  2034. EXPECT_EQ(2, GetParam()->keymaster0_calls());
  2035. }
  2036. TEST_P(EncryptionOperationsTest, RsaPkcs1CorruptedDecrypt) {
  2037. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(512, 3).Padding(
  2038. KM_PAD_RSA_PKCS1_1_5_ENCRYPT)));
  2039. string message = "Hello World!";
  2040. string ciphertext = EncryptMessage(string(message), KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
  2041. EXPECT_EQ(512U / 8, ciphertext.size());
  2042. // Corrupt the ciphertext
  2043. ciphertext[512 / 8 / 2]++;
  2044. string result;
  2045. size_t input_consumed;
  2046. AuthorizationSet begin_params(client_params());
  2047. begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
  2048. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
  2049. EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext, &result, &input_consumed));
  2050. EXPECT_EQ(KM_ERROR_UNKNOWN_ERROR, FinishOperation(&result));
  2051. EXPECT_EQ(0U, result.size());
  2052. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  2053. EXPECT_EQ(4, GetParam()->keymaster0_calls());
  2054. }
  2055. TEST_P(EncryptionOperationsTest, RsaEncryptWithSigningKey) {
  2056. ASSERT_EQ(KM_ERROR_OK,
  2057. GenerateKey(AuthorizationSetBuilder().RsaSigningKey(256, 3).Padding(KM_PAD_NONE)));
  2058. AuthorizationSet begin_params(client_params());
  2059. begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
  2060. ASSERT_EQ(KM_ERROR_INCOMPATIBLE_PURPOSE, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
  2061. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  2062. EXPECT_EQ(2, GetParam()->keymaster0_calls());
  2063. }
  2064. TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
  2065. ASSERT_EQ(KM_ERROR_OK,
  2066. GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(KM_DIGEST_NONE)));
  2067. ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_ENCRYPT));
  2068. ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_DECRYPT));
  2069. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
  2070. EXPECT_EQ(3, GetParam()->keymaster0_calls());
  2071. }
  2072. TEST_P(EncryptionOperationsTest, HmacEncrypt) {
  2073. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  2074. .HmacKey(128)
  2075. .Digest(KM_DIGEST_SHA_2_256)
  2076. .Padding(KM_PAD_NONE)
  2077. .Authorization(TAG_MIN_MAC_LENGTH, 128)));
  2078. ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_ENCRYPT));
  2079. ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_DECRYPT));
  2080. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  2081. }
  2082. TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
  2083. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  2084. .AesEncryptionKey(128)
  2085. .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
  2086. .Padding(KM_PAD_NONE)));
  2087. // Two-block message.
  2088. string message = "12345678901234567890123456789012";
  2089. string ciphertext1 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
  2090. EXPECT_EQ(message.size(), ciphertext1.size());
  2091. string ciphertext2 = EncryptMessage(string(message), KM_MODE_ECB, KM_PAD_NONE);
  2092. EXPECT_EQ(message.size(), ciphertext2.size());
  2093. // ECB is deterministic.
  2094. EXPECT_EQ(ciphertext1, ciphertext2);
  2095. string plaintext = DecryptMessage(ciphertext1, KM_MODE_ECB, KM_PAD_NONE);
  2096. EXPECT_EQ(message, plaintext);
  2097. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  2098. }
  2099. TEST_P(EncryptionOperationsTest, AesEcbNotAuthorized) {
  2100. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  2101. .AesEncryptionKey(128)
  2102. .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
  2103. .Padding(KM_PAD_NONE)));
  2104. // Two-block message.
  2105. string message = "12345678901234567890123456789012";
  2106. AuthorizationSet begin_params(client_params());
  2107. begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
  2108. begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
  2109. EXPECT_EQ(KM_ERROR_INCOMPATIBLE_BLOCK_MODE, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
  2110. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  2111. }
  2112. TEST_P(EncryptionOperationsTest, AesEcbNoPaddingWrongInputSize) {
  2113. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  2114. .AesEncryptionKey(128)
  2115. .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
  2116. .Padding(KM_PAD_NONE)));
  2117. // Message is slightly shorter than two blocks.
  2118. string message = "1234567890123456789012345678901";
  2119. AuthorizationSet begin_params(client_params());
  2120. begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
  2121. begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
  2122. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
  2123. string ciphertext;
  2124. EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, FinishOperation(message, "", &ciphertext));
  2125. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  2126. }
  2127. TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
  2128. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  2129. .AesEncryptionKey(128)
  2130. .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
  2131. .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
  2132. // Try various message lengths; all should work.
  2133. for (size_t i = 0; i < 32; ++i) {
  2134. string message(i, 'a');
  2135. string ciphertext = EncryptMessage(message, KM_MODE_ECB, KM_PAD_PKCS7);
  2136. EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
  2137. string plaintext = DecryptMessage(ciphertext, KM_MODE_ECB, KM_PAD_PKCS7);
  2138. EXPECT_EQ(message, plaintext);
  2139. }
  2140. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  2141. }
  2142. TEST_P(EncryptionOperationsTest, AesEcbNoPaddingKeyWithPkcs7Padding) {
  2143. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  2144. .AesEncryptionKey(128)
  2145. .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
  2146. .Authorization(TAG_PADDING, KM_PAD_NONE)));
  2147. // Try various message lengths; all should fail.
  2148. for (size_t i = 0; i < 32; ++i) {
  2149. AuthorizationSet begin_params(client_params());
  2150. begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
  2151. begin_params.push_back(TAG_PADDING, KM_PAD_PKCS7);
  2152. EXPECT_EQ(KM_ERROR_INCOMPATIBLE_PADDING_MODE,
  2153. BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
  2154. }
  2155. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  2156. }
  2157. TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
  2158. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  2159. .AesEncryptionKey(128)
  2160. .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
  2161. .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
  2162. string message = "a";
  2163. string ciphertext = EncryptMessage(message, KM_MODE_ECB, KM_PAD_PKCS7);
  2164. EXPECT_EQ(16U, ciphertext.size());
  2165. EXPECT_NE(ciphertext, message);
  2166. ++ciphertext[ciphertext.size() / 2];
  2167. AuthorizationSet begin_params(client_params());
  2168. begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
  2169. begin_params.push_back(TAG_PADDING, KM_PAD_PKCS7);
  2170. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
  2171. string plaintext;
  2172. size_t input_consumed;
  2173. EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext, &plaintext, &input_consumed));
  2174. EXPECT_EQ(ciphertext.size(), input_consumed);
  2175. EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, FinishOperation(&plaintext));
  2176. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  2177. }
  2178. TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
  2179. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  2180. .AesEncryptionKey(128)
  2181. .Authorization(TAG_BLOCK_MODE, KM_MODE_CTR)
  2182. .Padding(KM_PAD_NONE)));
  2183. string message = "123";
  2184. string iv1;
  2185. string ciphertext1 = EncryptMessage(message, KM_MODE_CTR, KM_PAD_NONE, &iv1);
  2186. EXPECT_EQ(message.size(), ciphertext1.size());
  2187. EXPECT_EQ(16U, iv1.size());
  2188. string iv2;
  2189. string ciphertext2 = EncryptMessage(message, KM_MODE_CTR, KM_PAD_NONE, &iv2);
  2190. EXPECT_EQ(message.size(), ciphertext2.size());
  2191. EXPECT_EQ(16U, iv2.size());
  2192. // IVs should be random, so ciphertexts should differ.
  2193. EXPECT_NE(iv1, iv2);
  2194. EXPECT_NE(ciphertext1, ciphertext2);
  2195. string plaintext = DecryptMessage(ciphertext1, KM_MODE_CTR, KM_PAD_NONE, iv1);
  2196. EXPECT_EQ(message, plaintext);
  2197. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  2198. }
  2199. TEST_P(EncryptionOperationsTest, AesCtrIncremental) {
  2200. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  2201. .AesEncryptionKey(128)
  2202. .Authorization(TAG_BLOCK_MODE, KM_MODE_CTR)
  2203. .Padding(KM_PAD_NONE)));
  2204. int increment = 15;
  2205. string message(239, 'a');
  2206. AuthorizationSet input_params(client_params());
  2207. input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CTR);
  2208. input_params.push_back(TAG_PADDING, KM_PAD_NONE);
  2209. AuthorizationSet output_params;
  2210. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, input_params, &output_params));
  2211. string ciphertext;
  2212. size_t input_consumed;
  2213. for (size_t i = 0; i < message.size(); i += increment)
  2214. EXPECT_EQ(KM_ERROR_OK,
  2215. UpdateOperation(message.substr(i, increment), &ciphertext, &input_consumed));
  2216. EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
  2217. EXPECT_EQ(message.size(), ciphertext.size());
  2218. // Move TAG_NONCE into input_params
  2219. input_params.Reinitialize(output_params);
  2220. input_params.push_back(client_params());
  2221. input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CTR);
  2222. input_params.push_back(TAG_PADDING, KM_PAD_NONE);
  2223. output_params.Clear();
  2224. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, input_params, &output_params));
  2225. string plaintext;
  2226. for (size_t i = 0; i < ciphertext.size(); i += increment)
  2227. EXPECT_EQ(KM_ERROR_OK,
  2228. UpdateOperation(ciphertext.substr(i, increment), &plaintext, &input_consumed));
  2229. EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
  2230. EXPECT_EQ(ciphertext.size(), plaintext.size());
  2231. EXPECT_EQ(message, plaintext);
  2232. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  2233. }
  2234. struct AesCtrSp80038aTestVector {
  2235. const char* key;
  2236. const char* nonce;
  2237. const char* plaintext;
  2238. const char* ciphertext;
  2239. };
  2240. // These test vectors are taken from
  2241. // http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
  2242. static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
  2243. // AES-128
  2244. {
  2245. "2b7e151628aed2a6abf7158809cf4f3c", "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
  2246. "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
  2247. "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
  2248. "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
  2249. "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
  2250. },
  2251. // AES-192
  2252. {
  2253. "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b", "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
  2254. "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
  2255. "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
  2256. "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
  2257. "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
  2258. },
  2259. // AES-256
  2260. {
  2261. "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
  2262. "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
  2263. "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
  2264. "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
  2265. "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
  2266. "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
  2267. },
  2268. };
  2269. TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
  2270. for (size_t i = 0; i < 3; i++) {
  2271. const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
  2272. const string key = hex2str(test.key);
  2273. const string nonce = hex2str(test.nonce);
  2274. const string plaintext = hex2str(test.plaintext);
  2275. const string ciphertext = hex2str(test.ciphertext);
  2276. CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
  2277. }
  2278. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  2279. }
  2280. TEST_P(EncryptionOperationsTest, AesCtrInvalidPaddingMode) {
  2281. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  2282. .AesEncryptionKey(128)
  2283. .Authorization(TAG_BLOCK_MODE, KM_MODE_CTR)
  2284. .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
  2285. AuthorizationSet begin_params(client_params());
  2286. begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_CTR);
  2287. begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
  2288. EXPECT_EQ(KM_ERROR_INCOMPATIBLE_PADDING_MODE, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
  2289. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  2290. }
  2291. TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
  2292. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  2293. .AesEncryptionKey(128)
  2294. .Authorization(TAG_BLOCK_MODE, KM_MODE_CTR)
  2295. .Authorization(TAG_CALLER_NONCE)
  2296. .Padding(KM_PAD_NONE)));
  2297. AuthorizationSet input_params(client_params());
  2298. input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CTR);
  2299. input_params.push_back(TAG_PADDING, KM_PAD_NONE);
  2300. input_params.push_back(TAG_NONCE, "123", 3);
  2301. EXPECT_EQ(KM_ERROR_INVALID_NONCE, BeginOperation(KM_PURPOSE_ENCRYPT, input_params));
  2302. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  2303. }
  2304. TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
  2305. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  2306. .AesEncryptionKey(128)
  2307. .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
  2308. .Padding(KM_PAD_NONE)));
  2309. // Two-block message.
  2310. string message = "12345678901234567890123456789012";
  2311. string iv1;
  2312. string ciphertext1 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv1);
  2313. EXPECT_EQ(message.size(), ciphertext1.size());
  2314. string iv2;
  2315. string ciphertext2 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv2);
  2316. EXPECT_EQ(message.size(), ciphertext2.size());
  2317. // IVs should be random, so ciphertexts should differ.
  2318. EXPECT_NE(iv1, iv2);
  2319. EXPECT_NE(ciphertext1, ciphertext2);
  2320. string plaintext = DecryptMessage(ciphertext1, KM_MODE_CBC, KM_PAD_NONE, iv1);
  2321. EXPECT_EQ(message, plaintext);
  2322. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  2323. }
  2324. TEST_P(EncryptionOperationsTest, AesCallerNonce) {
  2325. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  2326. .AesEncryptionKey(128)
  2327. .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
  2328. .Authorization(TAG_CALLER_NONCE)
  2329. .Padding(KM_PAD_NONE)));
  2330. string message = "12345678901234567890123456789012";
  2331. string iv1;
  2332. // Don't specify nonce, should get a random one.
  2333. string ciphertext1 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv1);
  2334. EXPECT_EQ(message.size(), ciphertext1.size());
  2335. EXPECT_EQ(16U, iv1.size());
  2336. string plaintext = DecryptMessage(ciphertext1, KM_MODE_CBC, KM_PAD_NONE, iv1);
  2337. EXPECT_EQ(message, plaintext);
  2338. // Now specify a nonce, should also work.
  2339. AuthorizationSet input_params(client_params());
  2340. AuthorizationSet update_params;
  2341. AuthorizationSet output_params;
  2342. input_params.push_back(TAG_NONCE, "abcdefghijklmnop", 16);
  2343. input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
  2344. input_params.push_back(TAG_PADDING, KM_PAD_NONE);
  2345. string ciphertext2 =
  2346. ProcessMessage(KM_PURPOSE_ENCRYPT, message, input_params, update_params, &output_params);
  2347. // Decrypt with correct nonce.
  2348. plaintext = ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext2, input_params, update_params,
  2349. &output_params);
  2350. EXPECT_EQ(message, plaintext);
  2351. // Now try with wrong nonce.
  2352. input_params.Reinitialize(client_params());
  2353. input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
  2354. input_params.push_back(TAG_PADDING, KM_PAD_NONE);
  2355. input_params.push_back(TAG_NONCE, "aaaaaaaaaaaaaaaa", 16);
  2356. plaintext = ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext2, input_params, update_params,
  2357. &output_params);
  2358. EXPECT_NE(message, plaintext);
  2359. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  2360. }
  2361. TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
  2362. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  2363. .AesEncryptionKey(128)
  2364. .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
  2365. .Padding(KM_PAD_NONE)));
  2366. string message = "12345678901234567890123456789012";
  2367. string iv1;
  2368. // Don't specify nonce, should get a random one.
  2369. string ciphertext1 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv1);
  2370. EXPECT_EQ(message.size(), ciphertext1.size());
  2371. EXPECT_EQ(16U, iv1.size());
  2372. string plaintext = DecryptMessage(ciphertext1, KM_MODE_CBC, KM_PAD_NONE, iv1);
  2373. EXPECT_EQ(message, plaintext);
  2374. // Now specify a nonce, should fail.
  2375. AuthorizationSet input_params(client_params());
  2376. AuthorizationSet update_params;
  2377. AuthorizationSet output_params;
  2378. input_params.push_back(TAG_NONCE, "abcdefghijklmnop", 16);
  2379. input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
  2380. input_params.push_back(TAG_PADDING, KM_PAD_NONE);
  2381. EXPECT_EQ(KM_ERROR_CALLER_NONCE_PROHIBITED,
  2382. BeginOperation(KM_PURPOSE_ENCRYPT, input_params, &output_params));
  2383. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  2384. }
  2385. TEST_P(EncryptionOperationsTest, AesCbcIncrementalNoPadding) {
  2386. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  2387. .AesEncryptionKey(128)
  2388. .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
  2389. .Padding(KM_PAD_NONE)));
  2390. int increment = 15;
  2391. string message(240, 'a');
  2392. AuthorizationSet input_params(client_params());
  2393. input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
  2394. input_params.push_back(TAG_PADDING, KM_PAD_NONE);
  2395. AuthorizationSet output_params;
  2396. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, input_params, &output_params));
  2397. string ciphertext;
  2398. size_t input_consumed;
  2399. for (size_t i = 0; i < message.size(); i += increment)
  2400. EXPECT_EQ(KM_ERROR_OK,
  2401. UpdateOperation(message.substr(i, increment), &ciphertext, &input_consumed));
  2402. EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
  2403. EXPECT_EQ(message.size(), ciphertext.size());
  2404. // Move TAG_NONCE into input_params
  2405. input_params.Reinitialize(output_params);
  2406. input_params.push_back(client_params());
  2407. input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
  2408. input_params.push_back(TAG_PADDING, KM_PAD_NONE);
  2409. output_params.Clear();
  2410. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, input_params, &output_params));
  2411. string plaintext;
  2412. for (size_t i = 0; i < ciphertext.size(); i += increment)
  2413. EXPECT_EQ(KM_ERROR_OK,
  2414. UpdateOperation(ciphertext.substr(i, increment), &plaintext, &input_consumed));
  2415. EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
  2416. EXPECT_EQ(ciphertext.size(), plaintext.size());
  2417. EXPECT_EQ(message, plaintext);
  2418. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  2419. }
  2420. TEST_P(EncryptionOperationsTest, AesCbcPkcs7Padding) {
  2421. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  2422. .AesEncryptionKey(128)
  2423. .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
  2424. .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
  2425. // Try various message lengths; all should work.
  2426. for (size_t i = 0; i < 32; ++i) {
  2427. string message(i, 'a');
  2428. string iv;
  2429. string ciphertext = EncryptMessage(message, KM_MODE_CBC, KM_PAD_PKCS7, &iv);
  2430. EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
  2431. string plaintext = DecryptMessage(ciphertext, KM_MODE_CBC, KM_PAD_PKCS7, iv);
  2432. EXPECT_EQ(message, plaintext);
  2433. }
  2434. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  2435. }
  2436. TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
  2437. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  2438. .AesEncryptionKey(128)
  2439. .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
  2440. .Authorization(TAG_PADDING, KM_PAD_NONE)
  2441. .Authorization(TAG_MIN_MAC_LENGTH, 128)));
  2442. string aad = "foobar";
  2443. string message = "123456789012345678901234567890123456";
  2444. AuthorizationSet begin_params(client_params());
  2445. begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
  2446. begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
  2447. begin_params.push_back(TAG_MAC_LENGTH, 128);
  2448. AuthorizationSet update_params;
  2449. update_params.push_back(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
  2450. // Encrypt
  2451. AuthorizationSet begin_out_params;
  2452. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
  2453. string ciphertext;
  2454. size_t input_consumed;
  2455. AuthorizationSet update_out_params;
  2456. EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
  2457. &input_consumed));
  2458. EXPECT_EQ(message.size(), input_consumed);
  2459. EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
  2460. // Grab nonce
  2461. EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
  2462. begin_params.push_back(begin_out_params);
  2463. // Decrypt.
  2464. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
  2465. string plaintext;
  2466. EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
  2467. &plaintext, &input_consumed));
  2468. EXPECT_EQ(ciphertext.size(), input_consumed);
  2469. EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
  2470. EXPECT_EQ(message, plaintext);
  2471. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  2472. }
  2473. TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
  2474. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  2475. .AesEncryptionKey(128)
  2476. .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
  2477. .Authorization(TAG_PADDING, KM_PAD_NONE)
  2478. .Authorization(TAG_MIN_MAC_LENGTH, 128)));
  2479. string aad = "foobar";
  2480. string message = "123456789012345678901234567890123456";
  2481. AuthorizationSet begin_params(client_params());
  2482. begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
  2483. begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
  2484. begin_params.push_back(TAG_MAC_LENGTH, 96);
  2485. AuthorizationSet update_params;
  2486. update_params.push_back(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
  2487. AuthorizationSet begin_out_params;
  2488. EXPECT_EQ(KM_ERROR_INVALID_MAC_LENGTH,
  2489. BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
  2490. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  2491. }
  2492. TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
  2493. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  2494. .AesEncryptionKey(128)
  2495. .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
  2496. .Authorization(TAG_PADDING, KM_PAD_NONE)
  2497. .Authorization(TAG_MIN_MAC_LENGTH, 128)));
  2498. string aad = "foobar";
  2499. string message = "123456789012345678901234567890123456";
  2500. AuthorizationSet begin_params(client_params());
  2501. begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
  2502. begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
  2503. begin_params.push_back(TAG_MAC_LENGTH, 128);
  2504. AuthorizationSet update_params;
  2505. update_params.push_back(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
  2506. // Encrypt
  2507. AuthorizationSet begin_out_params;
  2508. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
  2509. string ciphertext;
  2510. size_t input_consumed;
  2511. AuthorizationSet update_out_params;
  2512. EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
  2513. &input_consumed));
  2514. EXPECT_EQ(message.size(), input_consumed);
  2515. EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
  2516. // Grab nonce
  2517. EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
  2518. begin_params.Reinitialize(client_params());
  2519. begin_params.push_back(begin_out_params);
  2520. begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
  2521. begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
  2522. begin_params.push_back(TAG_MAC_LENGTH, 96);
  2523. // Decrypt.
  2524. EXPECT_EQ(KM_ERROR_INVALID_MAC_LENGTH, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
  2525. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  2526. }
  2527. TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
  2528. uint8_t nonce[] = {
  2529. 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
  2530. };
  2531. uint8_t ciphertext[] = {
  2532. 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc, 0xd2, 0xcb, 0x16,
  2533. 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78, 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a,
  2534. 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d, 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76,
  2535. 0x76, 0x5e, 0xfb, 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
  2536. 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
  2537. };
  2538. string ciphertext_str(reinterpret_cast<char*>(ciphertext), sizeof(ciphertext));
  2539. AuthorizationSet begin_params(client_params());
  2540. begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
  2541. begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
  2542. begin_params.push_back(TAG_MAC_LENGTH, 128);
  2543. begin_params.push_back(TAG_NONCE, nonce, sizeof(nonce));
  2544. string plaintext;
  2545. size_t input_consumed;
  2546. // Import correct key and decrypt
  2547. uint8_t good_key[] = {
  2548. 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
  2549. 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
  2550. };
  2551. string good_key_str(reinterpret_cast<char*>(good_key), sizeof(good_key));
  2552. ASSERT_EQ(KM_ERROR_OK, ImportKey(AuthorizationSetBuilder()
  2553. .AesEncryptionKey(128)
  2554. .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
  2555. .Authorization(TAG_PADDING, KM_PAD_NONE)
  2556. .Authorization(TAG_CALLER_NONCE)
  2557. .Authorization(TAG_MIN_MAC_LENGTH, 128),
  2558. KM_KEY_FORMAT_RAW, good_key_str));
  2559. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
  2560. EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext_str, &plaintext, &input_consumed));
  2561. EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
  2562. // Import bad key and decrypt
  2563. uint8_t bad_key[] = {
  2564. 0xbb, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
  2565. 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
  2566. };
  2567. string bad_key_str(reinterpret_cast<char*>(bad_key), sizeof(bad_key));
  2568. ASSERT_EQ(KM_ERROR_OK, ImportKey(AuthorizationSetBuilder()
  2569. .AesEncryptionKey(128)
  2570. .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
  2571. .Authorization(TAG_PADDING, KM_PAD_NONE)
  2572. .Authorization(TAG_MIN_MAC_LENGTH, 128),
  2573. KM_KEY_FORMAT_RAW, bad_key_str));
  2574. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
  2575. EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext_str, &plaintext, &input_consumed));
  2576. EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(&plaintext));
  2577. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  2578. }
  2579. TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
  2580. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  2581. .AesEncryptionKey(128)
  2582. .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
  2583. .Authorization(TAG_PADDING, KM_PAD_NONE)
  2584. .Authorization(TAG_MIN_MAC_LENGTH, 128)));
  2585. string aad = "123456789012345678";
  2586. string empty_message;
  2587. AuthorizationSet begin_params(client_params());
  2588. begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
  2589. begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
  2590. begin_params.push_back(TAG_MAC_LENGTH, 128);
  2591. AuthorizationSet update_params;
  2592. update_params.push_back(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
  2593. // Encrypt
  2594. AuthorizationSet begin_out_params;
  2595. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
  2596. string ciphertext;
  2597. size_t input_consumed;
  2598. AuthorizationSet update_out_params;
  2599. EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, empty_message, &update_out_params,
  2600. &ciphertext, &input_consumed));
  2601. EXPECT_EQ(0U, input_consumed);
  2602. EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
  2603. // Grab nonce
  2604. EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
  2605. begin_params.push_back(begin_out_params);
  2606. // Decrypt.
  2607. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
  2608. string plaintext;
  2609. EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
  2610. &plaintext, &input_consumed));
  2611. EXPECT_EQ(ciphertext.size(), input_consumed);
  2612. EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
  2613. EXPECT_EQ(empty_message, plaintext);
  2614. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  2615. }
  2616. TEST_P(EncryptionOperationsTest, AesGcmIncremental) {
  2617. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  2618. .AesEncryptionKey(128)
  2619. .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
  2620. .Authorization(TAG_PADDING, KM_PAD_NONE)
  2621. .Authorization(TAG_MIN_MAC_LENGTH, 128)));
  2622. AuthorizationSet begin_params(client_params());
  2623. begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
  2624. begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
  2625. begin_params.push_back(TAG_MAC_LENGTH, 128);
  2626. AuthorizationSet update_params;
  2627. update_params.push_back(TAG_ASSOCIATED_DATA, "b", 1);
  2628. // Encrypt
  2629. AuthorizationSet begin_out_params;
  2630. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
  2631. string ciphertext;
  2632. size_t input_consumed;
  2633. AuthorizationSet update_out_params;
  2634. // Send AAD, incrementally
  2635. for (int i = 0; i < 1000; ++i) {
  2636. EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, "", &update_out_params, &ciphertext,
  2637. &input_consumed));
  2638. EXPECT_EQ(0U, input_consumed);
  2639. EXPECT_EQ(0U, ciphertext.size());
  2640. }
  2641. // Now send data, incrementally, no data.
  2642. AuthorizationSet empty_params;
  2643. for (int i = 0; i < 1000; ++i) {
  2644. EXPECT_EQ(KM_ERROR_OK, UpdateOperation(empty_params, "a", &update_out_params, &ciphertext,
  2645. &input_consumed));
  2646. EXPECT_EQ(1U, input_consumed);
  2647. }
  2648. EXPECT_EQ(1000U, ciphertext.size());
  2649. // And finish.
  2650. EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
  2651. EXPECT_EQ(1016U, ciphertext.size());
  2652. // Grab nonce
  2653. EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
  2654. begin_params.push_back(begin_out_params);
  2655. // Decrypt.
  2656. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
  2657. string plaintext;
  2658. // Send AAD, incrementally, no data
  2659. for (int i = 0; i < 1000; ++i) {
  2660. EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, "", &update_out_params, &plaintext,
  2661. &input_consumed));
  2662. EXPECT_EQ(0U, input_consumed);
  2663. EXPECT_EQ(0U, plaintext.size());
  2664. }
  2665. // Now send data, incrementally.
  2666. for (size_t i = 0; i < ciphertext.length(); ++i) {
  2667. EXPECT_EQ(KM_ERROR_OK, UpdateOperation(empty_params, string(ciphertext.data() + i, 1),
  2668. &update_out_params, &plaintext, &input_consumed));
  2669. EXPECT_EQ(1U, input_consumed);
  2670. }
  2671. EXPECT_EQ(1000U, plaintext.size());
  2672. EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
  2673. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  2674. }
  2675. TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
  2676. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  2677. .AesEncryptionKey(128)
  2678. .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
  2679. .Authorization(TAG_PADDING, KM_PAD_NONE)
  2680. .Authorization(TAG_MIN_MAC_LENGTH, 128)));
  2681. string message = "123456789012345678901234567890123456";
  2682. AuthorizationSet begin_params(client_params());
  2683. begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
  2684. begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
  2685. begin_params.push_back(TAG_MAC_LENGTH, 128);
  2686. AuthorizationSet begin_out_params;
  2687. AuthorizationSet update_params;
  2688. update_params.push_back(TAG_ASSOCIATED_DATA, "foo", 3);
  2689. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
  2690. // No data, AAD only.
  2691. string ciphertext;
  2692. size_t input_consumed;
  2693. AuthorizationSet update_out_params;
  2694. EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, "" /* message */, &update_out_params,
  2695. &ciphertext, &input_consumed));
  2696. EXPECT_EQ(0U, input_consumed);
  2697. // AAD and data.
  2698. EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
  2699. &input_consumed));
  2700. EXPECT_EQ(message.size(), input_consumed);
  2701. EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
  2702. // Grab nonce.
  2703. EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
  2704. begin_params.push_back(begin_out_params);
  2705. // Decrypt
  2706. update_params.Clear();
  2707. update_params.push_back(TAG_ASSOCIATED_DATA, "foofoo", 6);
  2708. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
  2709. string plaintext;
  2710. EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
  2711. &plaintext, &input_consumed));
  2712. EXPECT_EQ(ciphertext.size(), input_consumed);
  2713. EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
  2714. EXPECT_EQ(message, plaintext);
  2715. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  2716. }
  2717. TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
  2718. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  2719. .AesEncryptionKey(128)
  2720. .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
  2721. .Authorization(TAG_PADDING, KM_PAD_NONE)
  2722. .Authorization(TAG_MIN_MAC_LENGTH, 128)));
  2723. string message = "12345678901234567890123456789012";
  2724. AuthorizationSet begin_params(client_params());
  2725. begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
  2726. begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
  2727. begin_params.push_back(TAG_MAC_LENGTH, 128);
  2728. AuthorizationSet update_params;
  2729. update_params.push_back(TAG_ASSOCIATED_DATA, "foobar", 6);
  2730. AuthorizationSet finish_params;
  2731. AuthorizationSet finish_out_params;
  2732. // Encrypt
  2733. AuthorizationSet begin_out_params;
  2734. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
  2735. AuthorizationSet update_out_params;
  2736. string ciphertext;
  2737. size_t input_consumed;
  2738. EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
  2739. &input_consumed));
  2740. EXPECT_EQ(message.size(), input_consumed);
  2741. EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
  2742. // Grab nonce
  2743. EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
  2744. begin_params.push_back(begin_out_params);
  2745. update_params.Clear();
  2746. update_params.push_back(TAG_ASSOCIATED_DATA, "barfoo" /* Wrong AAD */, 6);
  2747. // Decrypt.
  2748. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params, &begin_out_params));
  2749. string plaintext;
  2750. EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
  2751. &plaintext, &input_consumed));
  2752. EXPECT_EQ(ciphertext.size(), input_consumed);
  2753. EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(&plaintext));
  2754. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  2755. }
  2756. TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
  2757. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  2758. .AesEncryptionKey(128)
  2759. .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
  2760. .Authorization(TAG_PADDING, KM_PAD_NONE)
  2761. .Authorization(TAG_MIN_MAC_LENGTH, 128)));
  2762. string message = "12345678901234567890123456789012";
  2763. AuthorizationSet begin_params(client_params());
  2764. begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
  2765. begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
  2766. begin_params.push_back(TAG_MAC_LENGTH, 128);
  2767. AuthorizationSet update_params;
  2768. update_params.push_back(TAG_ASSOCIATED_DATA, "foobar", 6);
  2769. // Encrypt
  2770. AuthorizationSet begin_out_params;
  2771. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
  2772. AuthorizationSet update_out_params;
  2773. string ciphertext;
  2774. size_t input_consumed;
  2775. EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
  2776. &input_consumed));
  2777. EXPECT_EQ(message.size(), input_consumed);
  2778. EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
  2779. begin_params.push_back(TAG_NONCE, "123456789012", 12);
  2780. // Decrypt
  2781. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params, &begin_out_params));
  2782. string plaintext;
  2783. EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
  2784. &plaintext, &input_consumed));
  2785. EXPECT_EQ(ciphertext.size(), input_consumed);
  2786. EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(&plaintext));
  2787. // With wrong nonce, should have gotten garbage plaintext.
  2788. EXPECT_NE(message, plaintext);
  2789. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  2790. }
  2791. TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
  2792. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  2793. .AesEncryptionKey(128)
  2794. .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
  2795. .Authorization(TAG_PADDING, KM_PAD_NONE)
  2796. .Authorization(TAG_MIN_MAC_LENGTH, 128)));
  2797. string aad = "foobar";
  2798. string message = "123456789012345678901234567890123456";
  2799. AuthorizationSet begin_params(client_params());
  2800. begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
  2801. begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
  2802. begin_params.push_back(TAG_MAC_LENGTH, 128);
  2803. AuthorizationSet begin_out_params;
  2804. AuthorizationSet update_params;
  2805. update_params.push_back(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
  2806. // Encrypt
  2807. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
  2808. AuthorizationSet update_out_params;
  2809. string ciphertext;
  2810. size_t input_consumed;
  2811. EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
  2812. &input_consumed));
  2813. EXPECT_EQ(message.size(), input_consumed);
  2814. EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
  2815. // Corrupt tag
  2816. (*ciphertext.rbegin())++;
  2817. // Grab nonce.
  2818. EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
  2819. begin_params.push_back(begin_out_params);
  2820. // Decrypt.
  2821. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params, &begin_out_params));
  2822. string plaintext;
  2823. EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
  2824. &plaintext, &input_consumed));
  2825. EXPECT_EQ(ciphertext.size(), input_consumed);
  2826. EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(&plaintext));
  2827. EXPECT_EQ(message, plaintext);
  2828. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  2829. }
  2830. TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
  2831. auto auths = AuthorizationSetBuilder()
  2832. .TripleDesEncryptionKey(112)
  2833. .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
  2834. .Padding(KM_PAD_NONE);
  2835. ASSERT_EQ(KM_ERROR_OK, GenerateKey(auths));
  2836. // Two-block message.
  2837. string message = "1234567890123456";
  2838. string ciphertext1 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
  2839. EXPECT_EQ(message.size(), ciphertext1.size());
  2840. string ciphertext2 = EncryptMessage(string(message), KM_MODE_ECB, KM_PAD_NONE);
  2841. EXPECT_EQ(message.size(), ciphertext2.size());
  2842. // ECB is deterministic.
  2843. EXPECT_EQ(ciphertext1, ciphertext2);
  2844. string plaintext = DecryptMessage(ciphertext1, KM_MODE_ECB, KM_PAD_NONE);
  2845. EXPECT_EQ(message, plaintext);
  2846. }
  2847. TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
  2848. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  2849. .TripleDesEncryptionKey(112)
  2850. .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
  2851. .Padding(KM_PAD_NONE)));
  2852. // Two-block message.
  2853. string message = "1234567890123456";
  2854. AuthorizationSet begin_params(client_params());
  2855. begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
  2856. begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
  2857. EXPECT_EQ(KM_ERROR_INCOMPATIBLE_BLOCK_MODE, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
  2858. }
  2859. TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingWrongInputSize) {
  2860. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  2861. .TripleDesEncryptionKey(112)
  2862. .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
  2863. .Padding(KM_PAD_NONE)));
  2864. // Message is slightly shorter than two blocks.
  2865. string message = "123456789012345";
  2866. AuthorizationSet begin_params(client_params());
  2867. begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
  2868. begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
  2869. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
  2870. string ciphertext;
  2871. EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, FinishOperation(message, "", &ciphertext));
  2872. }
  2873. TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
  2874. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  2875. .TripleDesEncryptionKey(112)
  2876. .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
  2877. .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
  2878. // Try various message lengths; all should work.
  2879. for (size_t i = 0; i < 32; ++i) {
  2880. string message(i, 'a');
  2881. string ciphertext = EncryptMessage(message, KM_MODE_ECB, KM_PAD_PKCS7);
  2882. EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
  2883. string plaintext = DecryptMessage(ciphertext, KM_MODE_ECB, KM_PAD_PKCS7);
  2884. EXPECT_EQ(message, plaintext);
  2885. }
  2886. }
  2887. TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
  2888. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  2889. .TripleDesEncryptionKey(112)
  2890. .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
  2891. .Authorization(TAG_PADDING, KM_PAD_NONE)));
  2892. // Try various message lengths; all should fail.
  2893. for (size_t i = 0; i < 32; ++i) {
  2894. AuthorizationSet begin_params(client_params());
  2895. begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
  2896. begin_params.push_back(TAG_PADDING, KM_PAD_PKCS7);
  2897. EXPECT_EQ(KM_ERROR_INCOMPATIBLE_PADDING_MODE,
  2898. BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
  2899. }
  2900. }
  2901. TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
  2902. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  2903. .TripleDesEncryptionKey(112)
  2904. .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
  2905. .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
  2906. string message = "a";
  2907. string ciphertext = EncryptMessage(message, KM_MODE_ECB, KM_PAD_PKCS7);
  2908. EXPECT_EQ(8U, ciphertext.size());
  2909. EXPECT_NE(ciphertext, message);
  2910. ++ciphertext[ciphertext.size() / 2];
  2911. AuthorizationSet begin_params(client_params());
  2912. begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
  2913. begin_params.push_back(TAG_PADDING, KM_PAD_PKCS7);
  2914. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
  2915. string plaintext;
  2916. size_t input_consumed;
  2917. EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext, &plaintext, &input_consumed));
  2918. EXPECT_EQ(ciphertext.size(), input_consumed);
  2919. EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, FinishOperation(&plaintext));
  2920. }
  2921. struct TripleDesTestVector {
  2922. const char* name;
  2923. const keymaster_purpose_t purpose;
  2924. const keymaster_block_mode_t block_mode;
  2925. const keymaster_padding_t padding_mode;
  2926. const char* key;
  2927. const char* iv;
  2928. const char* input;
  2929. const char* output;
  2930. };
  2931. // These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all of
  2932. // the NIST vectors are multiples of the block size.
  2933. static const TripleDesTestVector kTripleDesTestVectors[] = {
  2934. {
  2935. "TECBMMT2 Encrypt 0", KM_PURPOSE_ENCRYPT, KM_MODE_ECB, KM_PAD_NONE,
  2936. "ad192fd064b5579e7a4fb3c8f794f22a", // key
  2937. "", // IV
  2938. "13bad542f3652d67", // input
  2939. "908e543cf2cb254f", // output
  2940. },
  2941. {
  2942. "TECBMMT2 Encrypt 0 PKCS7", KM_PURPOSE_ENCRYPT, KM_MODE_ECB, KM_PAD_PKCS7,
  2943. "ad192fd064b5579e7a4fb3c8f794f22a", // key
  2944. "", // IV
  2945. "13bad542f3652d6700", // input
  2946. "908e543cf2cb254fc40165289a89008c", // output
  2947. },
  2948. {
  2949. "TECBMMT2 Encrypt 0 PKCS7 decrypted", KM_PURPOSE_DECRYPT, KM_MODE_ECB, KM_PAD_PKCS7,
  2950. "ad192fd064b5579e7a4fb3c8f794f22a", // key
  2951. "", // IV
  2952. "908e543cf2cb254fc40165289a89008c", // input
  2953. "13bad542f3652d6700", // output
  2954. },
  2955. {
  2956. "TECBMMT2 Encrypt 1", KM_PURPOSE_ENCRYPT, KM_MODE_ECB, KM_PAD_NONE,
  2957. "259df16e7af804fe83b90e9bf7c7e557", // key
  2958. "", // IV
  2959. "a4619c433bbd6787c07c81728f9ac9fa", // input
  2960. "9e06de155c483c6bcfd834dbc8bd5830", // output
  2961. },
  2962. {
  2963. "TECBMMT2 Decrypt 0", KM_PURPOSE_DECRYPT, KM_MODE_ECB, KM_PAD_NONE,
  2964. "b32ff42092024adf2076b9d3d9f19e6d", // key
  2965. "", // IV
  2966. "2f3f2a49bba807a5", // input
  2967. "2249973fa135fb52", // output
  2968. },
  2969. {
  2970. "TECBMMT2 Decrypt 1", KM_PURPOSE_DECRYPT, KM_MODE_ECB, KM_PAD_NONE,
  2971. "023dfbe6621aa17cc219eae9cdecd923", // key
  2972. "", // IV
  2973. "54045dc71d8d565b227ec19f06fef912", // input
  2974. "9b071622181e6412de6066429401410d", // output
  2975. },
  2976. {
  2977. "TECBMMT3 Encrypt 0", KM_PURPOSE_ENCRYPT, KM_MODE_ECB, KM_PAD_NONE,
  2978. "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
  2979. "", // IV
  2980. "329d86bdf1bc5af4", // input
  2981. "d946c2756d78633f", // output
  2982. },
  2983. {
  2984. "TECBMMT3 Encrypt 1", KM_PURPOSE_ENCRYPT, KM_MODE_ECB, KM_PAD_NONE,
  2985. "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
  2986. "", // IV
  2987. "6b1540781b01ce1997adae102dbf3c5b", // input
  2988. "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
  2989. },
  2990. {
  2991. "TECBMMT3 Decrypt 0", KM_PURPOSE_DECRYPT, KM_MODE_ECB, KM_PAD_NONE,
  2992. "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
  2993. "", // IV
  2994. "6daad94ce08acfe7", // input
  2995. "660e7d32dcc90e79", // output
  2996. },
  2997. {
  2998. "TECBMMT3 Decrypt 1", KM_PURPOSE_DECRYPT, KM_MODE_ECB, KM_PAD_NONE,
  2999. "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
  3000. "", // IV
  3001. "e9653a0a1f05d31b9acd12d73aa9879d", // input
  3002. "9b2ae9d998efe62f1b592e7e1df8ff38", // output
  3003. },
  3004. {
  3005. "TCBCMMT2 Encrypt 0", KM_PURPOSE_ENCRYPT, KM_MODE_CBC, KM_PAD_NONE,
  3006. "34a41a8c293176c1b30732ecfe38ae8a", // key
  3007. "f55b4855228bd0b4", // IV
  3008. "7dd880d2a9ab411c", // input
  3009. "c91892948b6cadb4", // output
  3010. },
  3011. {
  3012. "TCBCMMT2 Encrypt 1", KM_PURPOSE_ENCRYPT, KM_MODE_CBC, KM_PAD_NONE,
  3013. "70a88fa1dfb9942fa77f40157ffef2ad", // key
  3014. "ece08ce2fdc6ce80", // IV
  3015. "bc225304d5a3a5c9918fc5006cbc40cc", // input
  3016. "27f67dc87af7ddb4b68f63fa7c2d454a", // output
  3017. },
  3018. {
  3019. "TCBCMMT2 Decrypt 0", KM_PURPOSE_DECRYPT, KM_MODE_CBC, KM_PAD_NONE,
  3020. "4ff47fda89209bda8c85f7fe80192007", // key
  3021. "d5bc4891dabe48b9", // IV
  3022. "7e154b28c353adef", // input
  3023. "712b961ea9a1d0af", // output
  3024. },
  3025. {
  3026. "TCBCMMT2 Decrypt 1", KM_PURPOSE_DECRYPT, KM_MODE_CBC, KM_PAD_NONE,
  3027. "464092cdbf736d38fb1fe6a12a94ae0e", // key
  3028. "5423455f00023b01", // IV
  3029. "3f6050b74ed64416bc23d53b0469ed7a", // input
  3030. "9cbe7d1b5cdd1864c3095ba810575960", // output
  3031. },
  3032. {
  3033. "TCBCMMT3 Encrypt 0", KM_PURPOSE_ENCRYPT, KM_MODE_CBC, KM_PAD_NONE,
  3034. "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
  3035. "43f791134c5647ba", // IV
  3036. "dcc153cef81d6f24", // input
  3037. "92538bd8af18d3ba", // output
  3038. },
  3039. {
  3040. "TCBCMMT3 Encrypt 1", KM_PURPOSE_ENCRYPT, KM_MODE_CBC, KM_PAD_NONE,
  3041. "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
  3042. "c2e999cb6249023c", // IV
  3043. "c689aee38a301bb316da75db36f110b5", // input
  3044. "e9afaba5ec75ea1bbe65506655bb4ecb", // output
  3045. },
  3046. {
  3047. "TCBCMMT3 Encrypt 1 PKCS7 variant", KM_PURPOSE_ENCRYPT, KM_MODE_CBC, KM_PAD_PKCS7,
  3048. "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
  3049. "c2e999cb6249023c", // IV
  3050. "c689aee38a301bb316da75db36f110b500", // input
  3051. "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
  3052. },
  3053. {
  3054. "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KM_PURPOSE_DECRYPT, KM_MODE_CBC, KM_PAD_PKCS7,
  3055. "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
  3056. "c2e999cb6249023c", // IV
  3057. "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
  3058. "c689aee38a301bb316da75db36f110b500", // output
  3059. },
  3060. {
  3061. "TCBCMMT3 Decrypt 0", KM_PURPOSE_DECRYPT, KM_MODE_CBC, KM_PAD_NONE,
  3062. "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
  3063. "41746c7e442d3681", // IV
  3064. "c53a7b0ec40600fe", // input
  3065. "d4f00eb455de1034", // output
  3066. },
  3067. {
  3068. "TCBCMMT3 Decrypt 1", KM_PURPOSE_DECRYPT, KM_MODE_CBC, KM_PAD_NONE,
  3069. "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
  3070. "3982bc02c3727d45", // IV
  3071. "6006f10adef52991fcc777a1238bbb65", // input
  3072. "edae09288e9e3bc05746d872b48e3b29", // output
  3073. },
  3074. };
  3075. TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
  3076. for (auto& test : array_range(kTripleDesTestVectors)) {
  3077. SCOPED_TRACE(test.name);
  3078. CheckTripleDesTestVector(test.purpose, test.block_mode, test.padding_mode,
  3079. hex2str(test.key), hex2str(test.iv), hex2str(test.input),
  3080. hex2str(test.output));
  3081. }
  3082. }
  3083. TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
  3084. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  3085. .TripleDesEncryptionKey(112)
  3086. .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
  3087. .Padding(KM_PAD_NONE)));
  3088. // Two-block message.
  3089. string message = "1234567890123456";
  3090. string iv1;
  3091. string ciphertext1 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv1);
  3092. EXPECT_EQ(message.size(), ciphertext1.size());
  3093. string iv2;
  3094. string ciphertext2 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv2);
  3095. EXPECT_EQ(message.size(), ciphertext2.size());
  3096. // IVs should be random, so ciphertexts should differ.
  3097. EXPECT_NE(iv1, iv2);
  3098. EXPECT_NE(ciphertext1, ciphertext2);
  3099. string plaintext = DecryptMessage(ciphertext1, KM_MODE_CBC, KM_PAD_NONE, iv1);
  3100. EXPECT_EQ(message, plaintext);
  3101. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  3102. }
  3103. TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
  3104. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  3105. .TripleDesEncryptionKey(112)
  3106. .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
  3107. .Authorization(TAG_CALLER_NONCE)
  3108. .Padding(KM_PAD_NONE)));
  3109. string message = "1234567890123456";
  3110. string iv1;
  3111. // Don't specify IV, should get a random one.
  3112. string ciphertext1 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv1);
  3113. EXPECT_EQ(message.size(), ciphertext1.size());
  3114. EXPECT_EQ(8U, iv1.size());
  3115. string plaintext = DecryptMessage(ciphertext1, KM_MODE_CBC, KM_PAD_NONE, iv1);
  3116. EXPECT_EQ(message, plaintext);
  3117. // Now specify an IV, should also work.
  3118. AuthorizationSet input_params(client_params());
  3119. AuthorizationSet update_params;
  3120. AuthorizationSet output_params;
  3121. input_params.push_back(TAG_NONCE, "abcdefgh", 8);
  3122. input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
  3123. input_params.push_back(TAG_PADDING, KM_PAD_NONE);
  3124. string ciphertext2 =
  3125. ProcessMessage(KM_PURPOSE_ENCRYPT, message, input_params, update_params, &output_params);
  3126. // Decrypt with correct IV.
  3127. plaintext = ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext2, input_params, update_params,
  3128. &output_params);
  3129. EXPECT_EQ(message, plaintext);
  3130. // Now try with wrong IV.
  3131. input_params.Reinitialize(client_params());
  3132. input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
  3133. input_params.push_back(TAG_PADDING, KM_PAD_NONE);
  3134. input_params.push_back(TAG_NONCE, "aaaaaaaa", 8);
  3135. plaintext = ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext2, input_params, update_params,
  3136. &output_params);
  3137. EXPECT_NE(message, plaintext);
  3138. }
  3139. TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
  3140. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  3141. .TripleDesEncryptionKey(112)
  3142. .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
  3143. .Padding(KM_PAD_NONE)));
  3144. string message = "12345678901234567890123456789012";
  3145. string iv1;
  3146. // Don't specify nonce, should get a random one.
  3147. string ciphertext1 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv1);
  3148. EXPECT_EQ(message.size(), ciphertext1.size());
  3149. EXPECT_EQ(8U, iv1.size());
  3150. string plaintext = DecryptMessage(ciphertext1, KM_MODE_CBC, KM_PAD_NONE, iv1);
  3151. EXPECT_EQ(message, plaintext);
  3152. // Now specify a nonce, should fail.
  3153. AuthorizationSet input_params(client_params());
  3154. AuthorizationSet update_params;
  3155. AuthorizationSet output_params;
  3156. input_params.push_back(TAG_NONCE, "abcdefgh", 8);
  3157. input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
  3158. input_params.push_back(TAG_PADDING, KM_PAD_NONE);
  3159. EXPECT_EQ(KM_ERROR_CALLER_NONCE_PROHIBITED,
  3160. BeginOperation(KM_PURPOSE_ENCRYPT, input_params, &output_params));
  3161. }
  3162. TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
  3163. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  3164. .TripleDesEncryptionKey(112)
  3165. .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
  3166. .Padding(KM_PAD_NONE)));
  3167. // Two-block message.
  3168. string message = "1234567890123456";
  3169. AuthorizationSet begin_params(client_params());
  3170. begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
  3171. begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
  3172. EXPECT_EQ(KM_ERROR_INCOMPATIBLE_BLOCK_MODE, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
  3173. }
  3174. TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingWrongInputSize) {
  3175. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  3176. .TripleDesEncryptionKey(112)
  3177. .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
  3178. .Padding(KM_PAD_NONE)));
  3179. // Message is slightly shorter than two blocks.
  3180. string message = "123456789012345";
  3181. AuthorizationSet begin_params(client_params());
  3182. begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
  3183. begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
  3184. AuthorizationSet output_params;
  3185. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &output_params));
  3186. string ciphertext;
  3187. EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, FinishOperation(message, "", &ciphertext));
  3188. }
  3189. TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
  3190. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  3191. .TripleDesEncryptionKey(112)
  3192. .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
  3193. .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
  3194. // Try various message lengths; all should work.
  3195. for (size_t i = 0; i < 32; ++i) {
  3196. string message(i, 'a');
  3197. string iv;
  3198. string ciphertext = EncryptMessage(message, KM_MODE_CBC, KM_PAD_PKCS7, &iv);
  3199. EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
  3200. string plaintext = DecryptMessage(ciphertext, KM_MODE_CBC, KM_PAD_PKCS7, iv);
  3201. EXPECT_EQ(message, plaintext);
  3202. }
  3203. }
  3204. TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
  3205. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  3206. .TripleDesEncryptionKey(112)
  3207. .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
  3208. .Authorization(TAG_PADDING, KM_PAD_NONE)));
  3209. // Try various message lengths; all should fail.
  3210. for (size_t i = 0; i < 32; ++i) {
  3211. AuthorizationSet begin_params(client_params());
  3212. begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
  3213. begin_params.push_back(TAG_PADDING, KM_PAD_PKCS7);
  3214. EXPECT_EQ(KM_ERROR_INCOMPATIBLE_PADDING_MODE,
  3215. BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
  3216. }
  3217. }
  3218. TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
  3219. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  3220. .TripleDesEncryptionKey(112)
  3221. .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
  3222. .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
  3223. string message = "a";
  3224. string iv;
  3225. string ciphertext = EncryptMessage(message, KM_MODE_CBC, KM_PAD_PKCS7, &iv);
  3226. EXPECT_EQ(8U, ciphertext.size());
  3227. EXPECT_NE(ciphertext, message);
  3228. ++ciphertext[ciphertext.size() / 2];
  3229. AuthorizationSet begin_params(client_params());
  3230. begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
  3231. begin_params.push_back(TAG_PADDING, KM_PAD_PKCS7);
  3232. begin_params.push_back(TAG_NONCE, iv.data(), iv.size());
  3233. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
  3234. string plaintext;
  3235. size_t input_consumed;
  3236. EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext, &plaintext, &input_consumed));
  3237. EXPECT_EQ(ciphertext.size(), input_consumed);
  3238. EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, FinishOperation(&plaintext));
  3239. }
  3240. TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
  3241. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  3242. .TripleDesEncryptionKey(112)
  3243. .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
  3244. .Padding(KM_PAD_NONE)));
  3245. int increment = 7;
  3246. string message(240, 'a');
  3247. AuthorizationSet input_params(client_params());
  3248. input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
  3249. input_params.push_back(TAG_PADDING, KM_PAD_NONE);
  3250. AuthorizationSet output_params;
  3251. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, input_params, &output_params));
  3252. string ciphertext;
  3253. size_t input_consumed;
  3254. for (size_t i = 0; i < message.size(); i += increment)
  3255. EXPECT_EQ(KM_ERROR_OK,
  3256. UpdateOperation(message.substr(i, increment), &ciphertext, &input_consumed));
  3257. EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
  3258. EXPECT_EQ(message.size(), ciphertext.size());
  3259. // Move TAG_NONCE into input_params
  3260. input_params.Reinitialize(output_params);
  3261. input_params.push_back(client_params());
  3262. input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
  3263. input_params.push_back(TAG_PADDING, KM_PAD_NONE);
  3264. output_params.Clear();
  3265. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, input_params, &output_params));
  3266. string plaintext;
  3267. for (size_t i = 0; i < ciphertext.size(); i += increment)
  3268. EXPECT_EQ(KM_ERROR_OK,
  3269. UpdateOperation(ciphertext.substr(i, increment), &plaintext, &input_consumed));
  3270. EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
  3271. EXPECT_EQ(ciphertext.size(), plaintext.size());
  3272. EXPECT_EQ(message, plaintext);
  3273. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  3274. }
  3275. typedef Keymaster2Test MaxOperationsTest;
  3276. INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, MaxOperationsTest, test_params);
  3277. TEST_P(MaxOperationsTest, TestLimit) {
  3278. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  3279. .AesEncryptionKey(128)
  3280. .EcbMode()
  3281. .Authorization(TAG_PADDING, KM_PAD_NONE)
  3282. .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
  3283. string message = "1234567890123456";
  3284. string ciphertext1 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
  3285. string ciphertext2 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
  3286. string ciphertext3 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
  3287. // Fourth time should fail.
  3288. AuthorizationSet begin_params(client_params());
  3289. begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
  3290. begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
  3291. EXPECT_EQ(KM_ERROR_KEY_MAX_OPS_EXCEEDED, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
  3292. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  3293. }
  3294. TEST_P(MaxOperationsTest, TestAbort) {
  3295. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  3296. .AesEncryptionKey(128)
  3297. .EcbMode()
  3298. .Authorization(TAG_PADDING, KM_PAD_NONE)
  3299. .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
  3300. string message = "1234567890123456";
  3301. string ciphertext1 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
  3302. string ciphertext2 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
  3303. string ciphertext3 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
  3304. // Fourth time should fail.
  3305. AuthorizationSet begin_params(client_params());
  3306. begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
  3307. begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
  3308. EXPECT_EQ(KM_ERROR_KEY_MAX_OPS_EXCEEDED, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
  3309. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  3310. }
  3311. typedef Keymaster2Test AddEntropyTest;
  3312. INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, AddEntropyTest, test_params);
  3313. TEST_P(AddEntropyTest, AddEntropy) {
  3314. // There's no obvious way to test that entropy is actually added, but we can test that the API
  3315. // doesn't blow up or return an error.
  3316. EXPECT_EQ(KM_ERROR_OK,
  3317. device()->add_rng_entropy(device(), reinterpret_cast<const uint8_t*>("foo"), 3));
  3318. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  3319. }
  3320. typedef Keymaster2Test AttestationTest;
  3321. INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, AttestationTest, test_params);
  3322. static X509* parse_cert_blob(const keymaster_blob_t& blob) {
  3323. const uint8_t* p = blob.data;
  3324. return d2i_X509(nullptr, &p, blob.data_length);
  3325. }
  3326. static bool verify_chain(const keymaster_cert_chain_t& chain) {
  3327. for (size_t i = 0; i < chain.entry_count - 1; ++i) {
  3328. keymaster_blob_t& key_cert_blob = chain.entries[i];
  3329. keymaster_blob_t& signing_cert_blob = chain.entries[i + 1];
  3330. X509_Ptr key_cert(parse_cert_blob(key_cert_blob));
  3331. X509_Ptr signing_cert(parse_cert_blob(signing_cert_blob));
  3332. EXPECT_TRUE(!!key_cert.get() && !!signing_cert.get());
  3333. if (!key_cert.get() || !signing_cert.get())
  3334. return false;
  3335. EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
  3336. EXPECT_TRUE(!!signing_pubkey.get());
  3337. if (!signing_pubkey.get())
  3338. return false;
  3339. EXPECT_EQ(1, X509_verify(key_cert.get(), signing_pubkey.get()))
  3340. << "Verification of certificate " << i << " failed";
  3341. }
  3342. return true;
  3343. }
  3344. // Extract attestation record from cert. Returned object is still part of cert; don't free it
  3345. // separately.
  3346. static ASN1_OCTET_STRING* get_attestation_record(X509* certificate) {
  3347. ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */));
  3348. EXPECT_TRUE(!!oid.get());
  3349. if (!oid.get())
  3350. return nullptr;
  3351. int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */);
  3352. EXPECT_NE(-1, location);
  3353. if (location == -1)
  3354. return nullptr;
  3355. X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location);
  3356. EXPECT_TRUE(!!attest_rec_ext);
  3357. if (!attest_rec_ext)
  3358. return nullptr;
  3359. ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext);
  3360. EXPECT_TRUE(!!attest_rec);
  3361. return attest_rec;
  3362. }
  3363. static bool verify_attestation_record(const string& challenge, const string& attestation_app_id,
  3364. AuthorizationSet expected_sw_enforced,
  3365. AuthorizationSet expected_tee_enforced,
  3366. uint32_t expected_keymaster_version,
  3367. keymaster_security_level_t expected_keymaster_security_level,
  3368. const keymaster_blob_t& attestation_cert) {
  3369. X509_Ptr cert(parse_cert_blob(attestation_cert));
  3370. EXPECT_TRUE(!!cert.get());
  3371. if (!cert.get())
  3372. return false;
  3373. ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
  3374. EXPECT_TRUE(!!attest_rec);
  3375. if (!attest_rec)
  3376. return false;
  3377. AuthorizationSet att_sw_enforced;
  3378. AuthorizationSet att_tee_enforced;
  3379. uint32_t att_attestation_version;
  3380. uint32_t att_keymaster_version;
  3381. keymaster_security_level_t att_attestation_security_level;
  3382. keymaster_security_level_t att_keymaster_security_level;
  3383. keymaster_blob_t att_challenge = {};
  3384. keymaster_blob_t att_unique_id = {};
  3385. EXPECT_EQ(KM_ERROR_OK, parse_attestation_record(
  3386. attest_rec->data, attest_rec->length, &att_attestation_version,
  3387. &att_attestation_security_level, &att_keymaster_version,
  3388. &att_keymaster_security_level, &att_challenge, &att_sw_enforced,
  3389. &att_tee_enforced, &att_unique_id));
  3390. EXPECT_EQ(2U, att_attestation_version);
  3391. EXPECT_EQ(KM_SECURITY_LEVEL_SOFTWARE, att_attestation_security_level);
  3392. EXPECT_EQ(expected_keymaster_version, att_keymaster_version);
  3393. EXPECT_EQ(expected_keymaster_security_level, att_keymaster_security_level);
  3394. EXPECT_EQ(challenge.length(), att_challenge.data_length);
  3395. EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data, challenge.length()));
  3396. // Add TAG_USER_ID to the relevant attestation list, because user IDs are not included in
  3397. // attestations, since they're meaningless off-device.
  3398. uint32_t user_id;
  3399. if (expected_sw_enforced.GetTagValue(TAG_USER_ID, &user_id))
  3400. att_sw_enforced.push_back(TAG_USER_ID, user_id);
  3401. if (expected_tee_enforced.GetTagValue(TAG_USER_ID, &user_id))
  3402. att_tee_enforced.push_back(TAG_USER_ID, user_id);
  3403. // Add TAG_INCLUDE_UNIQUE_ID to the relevant attestation list, because that tag is not included
  3404. // in the attestation.
  3405. if (expected_sw_enforced.GetTagValue(TAG_INCLUDE_UNIQUE_ID))
  3406. att_sw_enforced.push_back(TAG_INCLUDE_UNIQUE_ID);
  3407. if (expected_tee_enforced.GetTagValue(TAG_INCLUDE_UNIQUE_ID))
  3408. att_tee_enforced.push_back(TAG_INCLUDE_UNIQUE_ID);
  3409. // Add TAG_ATTESTATION_APPLICATION_ID to the expected sw-enforced list.
  3410. expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, attestation_app_id.data(),
  3411. attestation_app_id.size());
  3412. att_sw_enforced.Sort();
  3413. expected_sw_enforced.Sort();
  3414. EXPECT_EQ(expected_sw_enforced, att_sw_enforced);
  3415. att_tee_enforced.Sort();
  3416. expected_tee_enforced.Sort();
  3417. EXPECT_EQ(expected_tee_enforced, att_tee_enforced);
  3418. delete[] att_challenge.data;
  3419. delete[] att_unique_id.data;
  3420. return true;
  3421. }
  3422. TEST_P(AttestationTest, RsaAttestation) {
  3423. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  3424. .RsaSigningKey(256, 3)
  3425. .Digest(KM_DIGEST_NONE)
  3426. .Padding(KM_PAD_NONE)
  3427. .Authorization(TAG_INCLUDE_UNIQUE_ID)));
  3428. keymaster_cert_chain_t cert_chain;
  3429. EXPECT_EQ(KM_ERROR_OK, AttestKey("challenge", "attest_app_id", &cert_chain));
  3430. ASSERT_EQ(3U, cert_chain.entry_count);
  3431. EXPECT_TRUE(verify_chain(cert_chain));
  3432. uint32_t expected_keymaster_version;
  3433. keymaster_security_level_t expected_keymaster_security_level;
  3434. // TODO(swillden): Add a test KM1 that claims to be hardware.
  3435. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA)) {
  3436. expected_keymaster_version = 0;
  3437. expected_keymaster_security_level = KM_SECURITY_LEVEL_TRUSTED_ENVIRONMENT;
  3438. } else {
  3439. expected_keymaster_version = 3;
  3440. expected_keymaster_security_level = KM_SECURITY_LEVEL_SOFTWARE;
  3441. }
  3442. EXPECT_TRUE(verify_attestation_record(
  3443. "challenge", "attest_app_id", sw_enforced(), hw_enforced(), expected_keymaster_version,
  3444. expected_keymaster_security_level, cert_chain.entries[0]));
  3445. keymaster_free_cert_chain(&cert_chain);
  3446. }
  3447. TEST_P(AttestationTest, EcAttestation) {
  3448. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(
  3449. KM_DIGEST_SHA_2_256)));
  3450. uint32_t expected_keymaster_version;
  3451. keymaster_security_level_t expected_keymaster_security_level;
  3452. // TODO(swillden): Add a test KM1 that claims to be hardware.
  3453. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC)) {
  3454. expected_keymaster_version = 0;
  3455. expected_keymaster_security_level = KM_SECURITY_LEVEL_TRUSTED_ENVIRONMENT;
  3456. } else {
  3457. expected_keymaster_version = 3;
  3458. expected_keymaster_security_level = KM_SECURITY_LEVEL_SOFTWARE;
  3459. }
  3460. keymaster_cert_chain_t cert_chain;
  3461. EXPECT_EQ(KM_ERROR_OK, AttestKey("challenge", "attest_app_id", &cert_chain));
  3462. ASSERT_EQ(3U, cert_chain.entry_count);
  3463. EXPECT_TRUE(verify_chain(cert_chain));
  3464. EXPECT_TRUE(verify_attestation_record(
  3465. "challenge", "attest_app_id", sw_enforced(), hw_enforced(), expected_keymaster_version,
  3466. expected_keymaster_security_level, cert_chain.entries[0]));
  3467. keymaster_free_cert_chain(&cert_chain);
  3468. }
  3469. typedef Keymaster2Test KeyUpgradeTest;
  3470. INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, KeyUpgradeTest, test_params);
  3471. TEST_P(KeyUpgradeTest, AesVersionUpgrade) {
  3472. GetParam()->keymaster_context()->SetSystemVersion(1, 1);
  3473. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
  3474. .AesEncryptionKey(128)
  3475. .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
  3476. .Padding(KM_PAD_NONE)));
  3477. // Key should operate fine.
  3478. string message = "1234567890123456";
  3479. string ciphertext = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
  3480. EXPECT_EQ(message, DecryptMessage(ciphertext, KM_MODE_ECB, KM_PAD_NONE));
  3481. // Increase patch level. Key usage should fail with KM_ERROR_KEY_REQUIRES_UPGRADE.
  3482. GetParam()->keymaster_context()->SetSystemVersion(1, 2);
  3483. AuthorizationSet begin_params(client_params());
  3484. begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
  3485. begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
  3486. if (GetParam()->is_keymaster1_hw()) {
  3487. // Keymaster1 hardware can't support version binding. The key will work regardless
  3488. // of system version. Just abort the remainder of the test.
  3489. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
  3490. EXPECT_EQ(KM_ERROR_OK, AbortOperation());
  3491. return;
  3492. }
  3493. EXPECT_EQ(KM_ERROR_KEY_REQUIRES_UPGRADE, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
  3494. // Getting characteristics should also fail
  3495. EXPECT_EQ(KM_ERROR_KEY_REQUIRES_UPGRADE, GetCharacteristics());
  3496. // Upgrade key.
  3497. EXPECT_EQ(KM_ERROR_OK, UpgradeKey(client_params()));
  3498. // Key should work again
  3499. ciphertext = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
  3500. EXPECT_EQ(message, DecryptMessage(ciphertext, KM_MODE_ECB, KM_PAD_NONE));
  3501. // Decrease patch level. Key usage should fail with KM_ERROR_INVALID_KEY_BLOB.
  3502. GetParam()->keymaster_context()->SetSystemVersion(1, 1);
  3503. EXPECT_EQ(KM_ERROR_INVALID_KEY_BLOB, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
  3504. EXPECT_EQ(KM_ERROR_INVALID_KEY_BLOB, GetCharacteristics());
  3505. // Upgrade should fail
  3506. EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, UpgradeKey(client_params()));
  3507. EXPECT_EQ(0, GetParam()->keymaster0_calls());
  3508. }
  3509. TEST_P(KeyUpgradeTest, RsaVersionUpgrade) {
  3510. GetParam()->keymaster_context()->SetSystemVersion(1, 1);
  3511. ASSERT_EQ(KM_ERROR_OK,
  3512. GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(256, 3).Padding(KM_PAD_NONE)));
  3513. // Key should operate fine.
  3514. string message = "12345678901234567890123456789012";
  3515. string ciphertext = EncryptMessage(message, KM_PAD_NONE);
  3516. EXPECT_EQ(message, DecryptMessage(ciphertext, KM_PAD_NONE));
  3517. // Increase patch level. Key usage should fail with KM_ERROR_KEY_REQUIRES_UPGRADE.
  3518. GetParam()->keymaster_context()->SetSystemVersion(1, 2);
  3519. AuthorizationSet begin_params(client_params());
  3520. begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
  3521. if (GetParam()->is_keymaster1_hw()) {
  3522. // Keymaster1 hardware can't support version binding. The key will work regardless
  3523. // of system version. Just abort the remainder of the test.
  3524. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
  3525. EXPECT_EQ(KM_ERROR_OK, AbortOperation());
  3526. return;
  3527. }
  3528. EXPECT_EQ(KM_ERROR_KEY_REQUIRES_UPGRADE, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
  3529. // Getting characteristics should also fail
  3530. EXPECT_EQ(KM_ERROR_KEY_REQUIRES_UPGRADE, GetCharacteristics());
  3531. // Upgrade key.
  3532. EXPECT_EQ(KM_ERROR_OK, UpgradeKey(client_params()));
  3533. // Key should work again
  3534. ciphertext = EncryptMessage(message, KM_PAD_NONE);
  3535. EXPECT_EQ(message, DecryptMessage(ciphertext, KM_PAD_NONE));
  3536. // Decrease patch level. Key usage should fail with KM_ERROR_INVALID_KEY_BLOB.
  3537. GetParam()->keymaster_context()->SetSystemVersion(1, 1);
  3538. EXPECT_EQ(KM_ERROR_INVALID_KEY_BLOB, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
  3539. EXPECT_EQ(KM_ERROR_INVALID_KEY_BLOB, GetCharacteristics());
  3540. // Upgrade should fail
  3541. EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, UpgradeKey(client_params()));
  3542. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
  3543. EXPECT_EQ(7, GetParam()->keymaster0_calls());
  3544. }
  3545. TEST_P(KeyUpgradeTest, EcVersionUpgrade) {
  3546. GetParam()->keymaster_context()->SetSystemVersion(1, 1);
  3547. ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(
  3548. KM_DIGEST_SHA_2_256)));
  3549. // Key should operate fine.
  3550. string message = "1234567890123456";
  3551. string signature;
  3552. SignMessage(message, &signature, KM_DIGEST_SHA_2_256);
  3553. VerifyMessage(message, signature, KM_DIGEST_SHA_2_256);
  3554. // Increase patch level. Key usage should fail with KM_ERROR_KEY_REQUIRES_UPGRADE.
  3555. GetParam()->keymaster_context()->SetSystemVersion(1, 2);
  3556. AuthorizationSet begin_params(client_params());
  3557. begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
  3558. if (GetParam()->is_keymaster1_hw()) {
  3559. // Keymaster1 hardware can't support version binding. The key will work regardless
  3560. // of system version. Just abort the remainder of the test.
  3561. EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
  3562. EXPECT_EQ(KM_ERROR_OK, AbortOperation());
  3563. return;
  3564. }
  3565. EXPECT_EQ(KM_ERROR_KEY_REQUIRES_UPGRADE, BeginOperation(KM_PURPOSE_SIGN, begin_params));
  3566. // Getting characteristics should also fail
  3567. EXPECT_EQ(KM_ERROR_KEY_REQUIRES_UPGRADE, GetCharacteristics());
  3568. // Upgrade key.
  3569. EXPECT_EQ(KM_ERROR_OK, UpgradeKey(client_params()));
  3570. // Key should work again
  3571. SignMessage(message, &signature, KM_DIGEST_SHA_2_256);
  3572. VerifyMessage(message, signature, KM_DIGEST_SHA_2_256);
  3573. // Decrease patch level. Key usage should fail with KM_ERROR_INVALID_KEY_BLOB.
  3574. GetParam()->keymaster_context()->SetSystemVersion(1, 1);
  3575. EXPECT_EQ(KM_ERROR_INVALID_KEY_BLOB, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
  3576. EXPECT_EQ(KM_ERROR_INVALID_KEY_BLOB, GetCharacteristics());
  3577. // Upgrade should fail
  3578. EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, UpgradeKey(client_params()));
  3579. if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
  3580. EXPECT_EQ(7, GetParam()->keymaster0_calls());
  3581. }
  3582. TEST(SoftKeymasterWrapperTest, CheckKeymaster2Device) {
  3583. // Make a good fake device, and wrap it.
  3584. SoftKeymasterDevice* good_fake(new SoftKeymasterDevice(new TestKeymasterContext));
  3585. // Wrap it and check it.
  3586. SoftKeymasterDevice* good_fake_wrapper(new SoftKeymasterDevice(new TestKeymasterContext));
  3587. good_fake_wrapper->SetHardwareDevice(good_fake->keymaster_device());
  3588. EXPECT_TRUE(good_fake_wrapper->Keymaster1DeviceIsGood());
  3589. // Close and clean up wrapper and wrapped
  3590. good_fake_wrapper->keymaster_device()->common.close(good_fake_wrapper->hw_device());
  3591. // Make a "bad" (doesn't support all digests) device;
  3592. keymaster1_device_t* sha256_only_fake = make_device_sha256_only(
  3593. (new SoftKeymasterDevice(new TestKeymasterContext("256")))->keymaster_device());
  3594. // Wrap it and check it.
  3595. SoftKeymasterDevice* sha256_only_fake_wrapper(
  3596. (new SoftKeymasterDevice(new TestKeymasterContext)));
  3597. sha256_only_fake_wrapper->SetHardwareDevice(sha256_only_fake);
  3598. EXPECT_FALSE(sha256_only_fake_wrapper->Keymaster1DeviceIsGood());
  3599. // Close and clean up wrapper and wrapped
  3600. sha256_only_fake_wrapper->keymaster_device()->common.close(
  3601. sha256_only_fake_wrapper->hw_device());
  3602. }
  3603. class HmacKeySharingTest : public ::testing::Test {
  3604. protected:
  3605. using KeymasterVec = std::vector<std::unique_ptr<AndroidKeymaster>>;
  3606. using ParamsVec = std::vector<HmacSharingParameters>;
  3607. using ByteString = std::basic_string<uint8_t>;
  3608. using NonceVec = std::vector<ByteString>;
  3609. using ResponseVec = std::vector<ComputeSharedHmacResponse>;
  3610. KeymasterVec CreateKeymasters(size_t count) {
  3611. KeymasterVec keymasters;
  3612. for (size_t i = 0; i < count; ++i) {
  3613. keymasters.push_back(make_unique<AndroidKeymaster>(new TestKeymasterContext, 16));
  3614. }
  3615. return keymasters;
  3616. }
  3617. ParamsVec GetHmacSharingParameters(const KeymasterVec& keymasters) {
  3618. ParamsVec paramsVec;
  3619. for (auto& keymaster : keymasters) {
  3620. auto result = keymaster->GetHmacSharingParameters();
  3621. EXPECT_EQ(KM_ERROR_OK, result.error);
  3622. if (result.error == KM_ERROR_OK) paramsVec.push_back(move(result.params));
  3623. }
  3624. return paramsVec;
  3625. }
  3626. template <size_t N> ByteString ToByteString(const uint8_t (&a)[N]) { return ByteString(a, N); }
  3627. ByteString ToByteString(const keymaster_blob_t& b) { return ByteString(b.data, b.data_length); }
  3628. NonceVec CopyNonces(const ParamsVec& paramsVec) {
  3629. NonceVec nonces;
  3630. for (auto& param : paramsVec) {
  3631. nonces.push_back(ToByteString(param.nonce));
  3632. }
  3633. return nonces;
  3634. }
  3635. ResponseVec ComputeSharedHmac(const KeymasterVec& keymasters, const ParamsVec& paramsVec) {
  3636. ComputeSharedHmacRequest req;
  3637. req.params_array.params_array = const_cast<HmacSharingParameters*>(paramsVec.data());
  3638. auto prevent_deletion_of_paramsVec_data =
  3639. finally([&]() { req.params_array.params_array = nullptr; });
  3640. req.params_array.num_params = paramsVec.size();
  3641. ResponseVec responses;
  3642. for (auto& keymaster : keymasters) {
  3643. responses.push_back(keymaster->ComputeSharedHmac(req));
  3644. }
  3645. return responses;
  3646. }
  3647. bool VerifyResponses(const ByteString& expected, const ResponseVec& responses) {
  3648. for (auto& response : responses) {
  3649. EXPECT_EQ(KM_ERROR_OK, response.error);
  3650. auto this_sharing_check = ToByteString(response.sharing_check);
  3651. EXPECT_EQ(expected, this_sharing_check) << "Sharing check values should match.";
  3652. if (response.error != KM_ERROR_OK || expected != this_sharing_check) {
  3653. return false;
  3654. }
  3655. }
  3656. return true;
  3657. }
  3658. };
  3659. TEST_F(HmacKeySharingTest, GetParametersIdempotency) {
  3660. AndroidKeymaster keymaster(new TestKeymasterContext, 16);
  3661. ParamsVec paramsVec;
  3662. auto result1 = keymaster.GetHmacSharingParameters();
  3663. EXPECT_EQ(KM_ERROR_OK, result1.error);
  3664. paramsVec.push_back(std::move(result1.params));
  3665. auto result2 = keymaster.GetHmacSharingParameters();
  3666. EXPECT_EQ(KM_ERROR_OK, result2.error);
  3667. paramsVec.push_back(std::move(result2.params));
  3668. ASSERT_EQ(ToByteString(paramsVec[0].seed), ToByteString(paramsVec[1].seed))
  3669. << "A given keymaster should always return the same seed.";
  3670. EXPECT_EQ(ToByteString(paramsVec[0].nonce), ToByteString(paramsVec[1].nonce))
  3671. << "A given keymaster should always return the same nonce until restart.";
  3672. }
  3673. TEST_F(HmacKeySharingTest, ComputeSharedHmac) {
  3674. // ComputeSharedHmac should work with any number of participants; we just test 1 through 4.
  3675. for (size_t keymaster_count = 1; keymaster_count <= 4; ++keymaster_count) {
  3676. SCOPED_TRACE(testing::Message() << keymaster_count << " keymaster instances");
  3677. auto keymasters = CreateKeymasters(keymaster_count);
  3678. auto params = GetHmacSharingParameters(keymasters);
  3679. ASSERT_EQ(keymaster_count, params.size())
  3680. << "One or more keymasters failed to provide parameters.";
  3681. auto nonces = CopyNonces(params);
  3682. EXPECT_EQ(keymaster_count, nonces.size()) << "We should have a nonce per keymaster.";
  3683. std::sort(nonces.begin(), nonces.end());
  3684. std::unique(nonces.begin(), nonces.end());
  3685. EXPECT_EQ(keymaster_count, nonces.size()) << "Nonces should all be unique.";
  3686. auto responses = ComputeSharedHmac(keymasters, params);
  3687. ASSERT_EQ(keymaster_count, responses.size());
  3688. ASSERT_TRUE(VerifyResponses(ToByteString(responses[0].sharing_check), responses));
  3689. }
  3690. }
  3691. TEST_F(HmacKeySharingTest, ComputeSharedHmacTwice) {
  3692. for (size_t keymaster_count = 1; keymaster_count <= 4; ++keymaster_count) {
  3693. SCOPED_TRACE(testing::Message() << keymaster_count << " keymaster instances");
  3694. auto keymasters = CreateKeymasters(keymaster_count);
  3695. auto params = GetHmacSharingParameters(keymasters);
  3696. ASSERT_EQ(keymaster_count, params.size())
  3697. << "One or more keymasters failed to provide parameters.";
  3698. auto responses = ComputeSharedHmac(keymasters, params);
  3699. ASSERT_EQ(keymaster_count, responses.size());
  3700. ByteString sharing_check_value = ToByteString(responses[0].sharing_check);
  3701. ASSERT_TRUE(VerifyResponses(sharing_check_value, responses));
  3702. params = GetHmacSharingParameters(keymasters);
  3703. ASSERT_EQ(keymaster_count, params.size())
  3704. << "One or more keymasters failed to provide parameters.";
  3705. responses = ComputeSharedHmac(keymasters, params);
  3706. // Verify against first check value; we should get the same one every time, because each
  3707. // keymaster instance returns the same seed every time, and the same nonce until restart.
  3708. ASSERT_TRUE(VerifyResponses(sharing_check_value, responses));
  3709. }
  3710. }
  3711. TEST_F(HmacKeySharingTest, ComputeSharedHmacCorruptNonce) {
  3712. constexpr size_t keymaster_count = 4;
  3713. auto keymasters = CreateKeymasters(keymaster_count);
  3714. auto params = GetHmacSharingParameters(keymasters);
  3715. ASSERT_EQ(keymaster_count, params.size())
  3716. << "One or more keymasters failed to provide parameters.";
  3717. // All should be well in the normal case
  3718. auto responses = ComputeSharedHmac(keymasters, params);
  3719. ASSERT_EQ(keymaster_count, responses.size());
  3720. ByteString sharing_check_value = ToByteString(responses[0].sharing_check);
  3721. ASSERT_TRUE(VerifyResponses(sharing_check_value, responses));
  3722. // Pick a random param, a random byte within the param's nonce, and a random bit within
  3723. // the byte. Flip that bit.
  3724. size_t param_to_tweak = rand() % params.size();
  3725. uint8_t byte_to_tweak = rand() % sizeof(params[param_to_tweak].nonce);
  3726. uint8_t bit_to_tweak = rand() % 8;
  3727. params[param_to_tweak].nonce[byte_to_tweak] ^= (1 << bit_to_tweak);
  3728. responses = ComputeSharedHmac(keymasters, params);
  3729. EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, responses[param_to_tweak].error)
  3730. << "Keymaster that provided tweaked response should fail to compute HMAC key";
  3731. for (size_t i = 0; i < responses.size(); ++i) {
  3732. if (i != param_to_tweak) {
  3733. EXPECT_EQ(KM_ERROR_OK, responses[i].error) << "Others should succeed";
  3734. EXPECT_NE(sharing_check_value, ToByteString(responses[i].sharing_check))
  3735. << "Others should calculate a different HMAC key, due to the tweaked nonce.";
  3736. }
  3737. }
  3738. }
  3739. TEST_F(HmacKeySharingTest, ComputeSharedHmacCorruptSeed) {
  3740. constexpr size_t keymaster_count = 4;
  3741. auto keymasters = CreateKeymasters(keymaster_count);
  3742. auto params = GetHmacSharingParameters(keymasters);
  3743. ASSERT_EQ(keymaster_count, params.size())
  3744. << "One or more keymasters failed to provide parameters.";
  3745. // All should be well in the normal case
  3746. auto responses = ComputeSharedHmac(keymasters, params);
  3747. ASSERT_EQ(keymaster_count, responses.size());
  3748. ByteString sharing_check_value = ToByteString(responses[0].sharing_check);
  3749. ASSERT_TRUE(VerifyResponses(sharing_check_value, responses));
  3750. // Pick a random param and modify the seed.
  3751. auto param_to_tweak = rand() & params.size();
  3752. constexpr uint8_t wrong_seed_value[] = {0xF, 0x0, 0x0};
  3753. params[param_to_tweak].SetSeed({wrong_seed_value, sizeof(wrong_seed_value)});
  3754. auto prevent_deletion_of_wrong_seed =
  3755. finally([&]() { params[param_to_tweak].seed.data = nullptr; });
  3756. responses = ComputeSharedHmac(keymasters, params);
  3757. EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, responses[param_to_tweak].error)
  3758. << "Keymaster that provided tweaked response should fail to compute HMAC key";
  3759. for (size_t i = 0; i < responses.size(); ++i) {
  3760. if (i != param_to_tweak) {
  3761. EXPECT_EQ(KM_ERROR_OK, responses[i].error) << "Others should succeed";
  3762. EXPECT_NE(sharing_check_value, ToByteString(responses[i].sharing_check))
  3763. << "Others should calculate a different HMAC key, due to the tweaked seed.";
  3764. }
  3765. }
  3766. }
  3767. } // namespace test
  3768. } // namespace keymaster