wc_pkcs11.c 135 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935
  1. /* wc_pkcs11.c
  2. *
  3. * Copyright (C) 2006-2023 wolfSSL Inc.
  4. *
  5. * This file is part of wolfSSL.
  6. *
  7. * wolfSSL is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * wolfSSL is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
  20. */
  21. #ifdef HAVE_CONFIG_H
  22. #include <config.h>
  23. #endif
  24. #include <wolfssl/wolfcrypt/settings.h>
  25. #ifdef HAVE_PKCS11
  26. #ifndef HAVE_PKCS11_STATIC
  27. #include <dlfcn.h>
  28. #endif
  29. #include <wolfssl/wolfcrypt/wc_pkcs11.h>
  30. #include <wolfssl/wolfcrypt/error-crypt.h>
  31. #include <wolfssl/wolfcrypt/asn.h>
  32. #include <wolfssl/wolfcrypt/logging.h>
  33. #ifndef NO_RSA
  34. #include <wolfssl/wolfcrypt/rsa.h>
  35. #endif
  36. #ifdef NO_INLINE
  37. #include <wolfssl/wolfcrypt/misc.h>
  38. #else
  39. #define WOLFSSL_MISC_INCLUDED
  40. #include <wolfcrypt/src/misc.c>
  41. #endif
  42. #ifndef WOLFSSL_HAVE_ECC_KEY_GET_PRIV
  43. /* FIPS build has replaced ecc.h. */
  44. #define wc_ecc_key_get_priv(key) (&((key)->k))
  45. #define WOLFSSL_HAVE_ECC_KEY_GET_PRIV
  46. #endif
  47. #if defined(NO_PKCS11_RSA) && !defined(NO_RSA)
  48. #define NO_RSA
  49. #endif
  50. #if defined(NO_PKCS11_ECC) && defined(HAVE_ECC)
  51. #undef HAVE_ECC
  52. #endif
  53. #if defined(NO_PKCS11_AES) && !defined(NO_AES)
  54. #define NO_AES
  55. #endif
  56. #if defined(NO_PKCS11_AESGCM) && defined(HAVE_AESGCM)
  57. #undef HAVE_AESGCM
  58. #endif
  59. #if defined(NO_PKCS11_AESCBC) && defined(HAVE_AES_CBC)
  60. #undef HAVE_AES_CBC
  61. #endif
  62. #if defined(NO_PKCS11_HMAC) && !defined(NO_HMAC)
  63. #define NO_HMAC
  64. #endif
  65. #if defined(NO_PKCS11_RNG) && !defined(WC_NO_RNG)
  66. #define WC_NO_RNG
  67. #endif
  68. /* Maximim length of the EC parameter string. */
  69. #define MAX_EC_PARAM_LEN 16
  70. #if defined(HAVE_ECC) && !defined(NO_PKCS11_ECDH)
  71. /* Pointer to false required for templates. */
  72. static CK_BBOOL ckFalse = CK_FALSE;
  73. #endif
  74. #if !defined(NO_RSA) || defined(HAVE_ECC) || (!defined(NO_AES) && \
  75. (defined(HAVE_AESGCM) || defined(HAVE_AES_CBC))) || !defined(NO_HMAC)
  76. /* Pointer to true required for templates. */
  77. static CK_BBOOL ckTrue = CK_TRUE;
  78. #endif
  79. #ifndef NO_RSA
  80. /* Pointer to RSA key type required for templates. */
  81. static CK_KEY_TYPE rsaKeyType = CKK_RSA;
  82. #endif
  83. #ifdef HAVE_ECC
  84. /* Pointer to EC key type required for templates. */
  85. static CK_KEY_TYPE ecKeyType = CKK_EC;
  86. #endif
  87. #if !defined(NO_RSA) || defined(HAVE_ECC)
  88. /* Pointer to public key class required for templates. */
  89. static CK_OBJECT_CLASS pubKeyClass = CKO_PUBLIC_KEY;
  90. /* Pointer to private key class required for templates. */
  91. static CK_OBJECT_CLASS privKeyClass = CKO_PRIVATE_KEY;
  92. #endif
  93. #if (!defined(NO_AES) && (defined(HAVE_AESGCM) || defined(HAVE_AES_CBC))) || \
  94. !defined(NO_HMAC) || (defined(HAVE_ECC) && !defined(NO_PKCS11_ECDH))
  95. /* Pointer to secret key class required for templates. */
  96. static CK_OBJECT_CLASS secretKeyClass = CKO_SECRET_KEY;
  97. #endif
  98. #ifdef WOLFSSL_DEBUG_PKCS11
  99. /* Enable logging of PKCS#11 calls and return value. */
  100. #define PKCS11_RV(op, rv) pkcs11_rv(op, rv)
  101. /* Enable logging of PKCS#11 calls and value. */
  102. #define PKCS11_VAL(op, val) pkcs11_val(op, val)
  103. /* Enable logging of PKCS#11 template. */
  104. #define PKCS11_DUMP_TEMPLATE(name, templ, cnt) \
  105. pkcs11_dump_template(name, templ, cnt)
  106. /* Formats of template items - used to instruct how to log information. */
  107. enum PKCS11_TYPE_FORMATS {
  108. PKCS11_FMT_BOOLEAN,
  109. PKCS11_FMT_CLASS,
  110. PKCS11_FMT_KEY_TYPE,
  111. PKCS11_FMT_STRING,
  112. PKCS11_FMT_NUMBER,
  113. PKCS11_FMT_DATA,
  114. PKCS11_FMT_POINTER
  115. };
  116. /* Information for logging a template item. */
  117. static struct PKCS11_TYPE_STR {
  118. /** Attribute type in template. */
  119. CK_ATTRIBUTE_TYPE type;
  120. /** String to log corresponding to attribute type. */
  121. const char* str;
  122. /** Format of data associated with template item. */
  123. int format;
  124. } typeStr[] = {
  125. { CKA_CLASS, "CKA_CLASS", PKCS11_FMT_CLASS },
  126. { CKA_TOKEN, "CKA_TOKEN", PKCS11_FMT_POINTER },
  127. { CKA_PRIVATE, "CKA_PRIVATE", PKCS11_FMT_BOOLEAN },
  128. { CKA_LABEL, "CKA_LABEL", PKCS11_FMT_STRING },
  129. { CKA_VALUE, "CKA_VALUE", PKCS11_FMT_DATA },
  130. { CKA_OBJECT_ID, "CKA_OBJECT_ID", PKCS11_FMT_POINTER },
  131. { CKA_KEY_TYPE, "CKA_KEY_TYPE", PKCS11_FMT_KEY_TYPE },
  132. { CKA_ID, "CKA_ID", PKCS11_FMT_DATA },
  133. { CKA_SENSITIVE, "CKA_SENSITIVE", PKCS11_FMT_BOOLEAN },
  134. { CKA_ENCRYPT, "CKA_ENCRYPT", PKCS11_FMT_BOOLEAN },
  135. { CKA_DECRYPT, "CKA_DECRYPT", PKCS11_FMT_BOOLEAN },
  136. { CKA_SIGN, "CKA_SIGN", PKCS11_FMT_BOOLEAN },
  137. { CKA_VERIFY, "CKA_VERIFY", PKCS11_FMT_BOOLEAN },
  138. { CKA_DERIVE, "CKA_DERIVE", PKCS11_FMT_BOOLEAN },
  139. { CKA_MODULUS_BITS, "CKA_MODULUS_BITS", PKCS11_FMT_NUMBER },
  140. { CKA_MODULUS, "CKA_MODULUS", PKCS11_FMT_DATA },
  141. { CKA_PUBLIC_EXPONENT, "CKA_PUBLIC_EXPONENT", PKCS11_FMT_DATA },
  142. { CKA_PRIVATE_EXPONENT, "CKA_PRIVATE_EXPONENT", PKCS11_FMT_DATA },
  143. { CKA_PRIME_1, "CKA_PRIME_1", PKCS11_FMT_DATA },
  144. { CKA_PRIME_2, "CKA_PRIME_2", PKCS11_FMT_DATA },
  145. { CKA_EXPONENT_1, "CKA_EXPONENT_1", PKCS11_FMT_DATA },
  146. { CKA_EXPONENT_2, "CKA_EXPONENT_2", PKCS11_FMT_DATA },
  147. { CKA_VALUE_LEN, "CKA_VALUE_LEN", PKCS11_FMT_NUMBER },
  148. { CKA_COEFFICIENT, "CKA_COEFFICIENT", PKCS11_FMT_DATA },
  149. { CKA_EXTRACTABLE, "CKA_EXTRACTABLE", PKCS11_FMT_BOOLEAN },
  150. { CKA_EC_PARAMS, "CKA_EC_PARAMS", PKCS11_FMT_DATA },
  151. { CKA_EC_POINT, "CKA_EC_POINT", PKCS11_FMT_DATA },
  152. };
  153. /* Count of known attribute types for logging. */
  154. #define PKCS11_TYPE_STR_CNT ((int)(sizeof(typeStr) / sizeof(*typeStr)))
  155. /*
  156. * Dump/log the PKCS #11 template.
  157. *
  158. * This is only for debugging purposes. Only the values needed are recognised.
  159. *
  160. * @param [in] name PKCS #11 template name.
  161. * @param [in] templ PKCS #11 template to dump.
  162. * @param [in] cnt Count of template entries.
  163. */
  164. static void pkcs11_dump_template(const char* name, CK_ATTRIBUTE* templ,
  165. CK_ULONG cnt)
  166. {
  167. CK_ULONG i;
  168. int j;
  169. char line[80];
  170. char type[25];
  171. int format;
  172. CK_KEY_TYPE keyType;
  173. CK_OBJECT_CLASS keyClass;
  174. WOLFSSL_MSG(name);
  175. for (i = 0; i < cnt; i++) {
  176. format = PKCS11_FMT_POINTER;
  177. for (j = 0; j < PKCS11_TYPE_STR_CNT; j++) {
  178. if (templ[i].type == typeStr[j].type) {
  179. XSNPRINTF(type, sizeof(type), "%s", typeStr[j].str);
  180. format = typeStr[j].format;
  181. break;
  182. }
  183. }
  184. if (j == PKCS11_TYPE_STR_CNT) {
  185. XSNPRINTF(type, sizeof(type), "%08lxUL", templ[i].type);
  186. }
  187. switch (format) {
  188. case PKCS11_FMT_BOOLEAN:
  189. #if !defined(NO_RSA) || defined(HAVE_ECC) || (!defined(NO_AES) && \
  190. (defined(HAVE_AESGCM) || defined(HAVE_AES_CBC))) || !defined(NO_HMAC)
  191. if (templ[i].pValue == &ckTrue) {
  192. XSNPRINTF(line, sizeof(line), "%25s: TRUE", type);
  193. WOLFSSL_MSG(line);
  194. }
  195. else
  196. #endif
  197. #if defined(HAVE_ECC) && !defined(NO_PKCS11_ECDH)
  198. if (templ[i].pValue == &ckFalse) {
  199. XSNPRINTF(line, sizeof(line), "%25s: FALSE", type);
  200. WOLFSSL_MSG(line);
  201. }
  202. else
  203. #endif
  204. {
  205. XSNPRINTF(line, sizeof(line), "%25s: INVALID (%p)", type,
  206. templ[i].pValue);
  207. WOLFSSL_MSG(line);
  208. }
  209. break;
  210. case PKCS11_FMT_CLASS:
  211. keyClass = *(CK_OBJECT_CLASS*)templ[i].pValue;
  212. if (keyClass == CKO_PUBLIC_KEY) {
  213. XSNPRINTF(line, sizeof(line), "%25s: PUBLIC", type);
  214. WOLFSSL_MSG(line);
  215. }
  216. else if (keyClass == CKO_PRIVATE_KEY) {
  217. XSNPRINTF(line, sizeof(line), "%25s: PRIVATE", type);
  218. WOLFSSL_MSG(line);
  219. }
  220. else if (keyClass == CKO_SECRET_KEY) {
  221. XSNPRINTF(line, sizeof(line), "%25s: SECRET", type);
  222. WOLFSSL_MSG(line);
  223. }
  224. else
  225. {
  226. XSNPRINTF(line, sizeof(line), "%25s: UNKNOWN (%p)", type,
  227. templ[i].pValue);
  228. WOLFSSL_MSG(line);
  229. }
  230. break;
  231. case PKCS11_FMT_KEY_TYPE:
  232. keyType = *(CK_KEY_TYPE*)templ[i].pValue;
  233. switch (keyType) {
  234. case CKK_RSA:
  235. XSNPRINTF(line, sizeof(line), "%25s: RSA", type);
  236. break;
  237. case CKK_DH:
  238. XSNPRINTF(line, sizeof(line), "%25s: DH", type);
  239. break;
  240. case CKK_EC:
  241. XSNPRINTF(line, sizeof(line), "%25s: EC", type);
  242. break;
  243. case CKK_GENERIC_SECRET:
  244. XSNPRINTF(line, sizeof(line), "%25s: GENERIC_SECRET", type);
  245. break;
  246. case CKK_AES:
  247. XSNPRINTF(line, sizeof(line), "%25s: AES", type);
  248. break;
  249. case CKK_MD5_HMAC:
  250. XSNPRINTF(line, sizeof(line), "%25s: MD5_HMAC", type);
  251. break;
  252. case CKK_SHA_1_HMAC:
  253. XSNPRINTF(line, sizeof(line), "%25s: SHA_1_HMAC", type);
  254. break;
  255. case CKK_SHA256_HMAC:
  256. XSNPRINTF(line, sizeof(line), "%25s: SHA256_HMAC", type);
  257. break;
  258. case CKK_SHA384_HMAC:
  259. XSNPRINTF(line, sizeof(line), "%25s: SHA384_HMAC", type);
  260. break;
  261. case CKK_SHA512_HMAC:
  262. XSNPRINTF(line, sizeof(line), "%25s: SHA512_HMAC", type);
  263. break;
  264. case CKK_SHA224_HMAC:
  265. XSNPRINTF(line, sizeof(line), "%25s: SHA224_HMAC", type);
  266. break;
  267. default:
  268. XSNPRINTF(line, sizeof(line), "%25s: UNKNOWN (%08lx)", type,
  269. keyType);
  270. break;
  271. }
  272. WOLFSSL_MSG(line);
  273. break;
  274. case PKCS11_FMT_STRING:
  275. XSNPRINTF(line, sizeof(line), "%25s: %s", type,
  276. (char*)templ[i].pValue);
  277. WOLFSSL_MSG(line);
  278. break;
  279. case PKCS11_FMT_NUMBER:
  280. if (templ[i].ulValueLen <= 1) {
  281. XSNPRINTF(line, sizeof(line), "%25s: 0x%02x (%d)", type,
  282. *(byte*)templ[i].pValue, *(byte*)templ[i].pValue);
  283. }
  284. else if (templ[i].ulValueLen <= 2) {
  285. XSNPRINTF(line, sizeof(line), "%25s: 0x%04x (%d)", type,
  286. *(word16*)templ[i].pValue, *(word16*)templ[i].pValue);
  287. }
  288. else if (templ[i].ulValueLen <= 4) {
  289. XSNPRINTF(line, sizeof(line), "%25s: 0x%08x (%d)", type,
  290. *(word32*)templ[i].pValue, *(word32*)templ[i].pValue);
  291. }
  292. else if (templ[i].ulValueLen <= 8) {
  293. XSNPRINTF(line, sizeof(line), "%25s: 0x%016lx (%ld)", type,
  294. *(word64*)templ[i].pValue, *(word64*)templ[i].pValue);
  295. }
  296. else {
  297. XSNPRINTF(line, sizeof(line), "%25s: INVALID (%ld)", type,
  298. templ[i].ulValueLen);
  299. }
  300. WOLFSSL_MSG(line);
  301. break;
  302. case PKCS11_FMT_DATA:
  303. XSNPRINTF(line, sizeof(line), "%25s: %ld", type,
  304. templ[i].ulValueLen);
  305. WOLFSSL_MSG(line);
  306. if (templ[i].pValue == NULL) {
  307. XSNPRINTF(line, sizeof(line), "%27s(nil)", "");
  308. WOLFSSL_MSG(line);
  309. break;
  310. }
  311. XSNPRINTF(line, sizeof(line), "%27s", "");
  312. for (j = 0; j < (int)templ[i].ulValueLen && j < 80; j++) {
  313. char hex[6];
  314. XSNPRINTF(hex, sizeof(hex), "0x%02x,",
  315. ((byte*)templ[i].pValue)[j]);
  316. XSTRNCAT(line, hex, 5);
  317. if ((j % 8) == 7) {
  318. WOLFSSL_MSG(line);
  319. XSNPRINTF(line, sizeof(line), "%27s", "");
  320. }
  321. }
  322. if (j == (int)templ[i].ulValueLen) {
  323. if ((j % 8) != 0) {
  324. WOLFSSL_MSG(line);
  325. }
  326. }
  327. else if (j < (int)templ[i].ulValueLen) {
  328. XSNPRINTF(line, sizeof(line), "%27s...", "");
  329. WOLFSSL_MSG(line);
  330. }
  331. break;
  332. case PKCS11_FMT_POINTER:
  333. XSNPRINTF(line, sizeof(line), "%25s: %p %ld", type, templ[i].pValue,
  334. templ[i].ulValueLen);
  335. WOLFSSL_MSG(line);
  336. break;
  337. }
  338. }
  339. }
  340. /*
  341. * Log a PKCS #11 return value with the name of function called.
  342. *
  343. * This is only for debugging purposes. Only the values needed are recognized.
  344. *
  345. * @param [in] op PKCS #11 operation that was attempted.
  346. * @param [in] rv PKCS #11 return value.
  347. */
  348. static void pkcs11_rv(const char* op, CK_RV rv)
  349. {
  350. char line[80];
  351. if (rv == CKR_OK) {
  352. XSNPRINTF(line, 80, "%s: OK", op);
  353. }
  354. else if (rv == CKR_MECHANISM_INVALID) {
  355. XSNPRINTF(line, 80, "%s: MECHANISM_INVALID", op);
  356. }
  357. else if (rv == CKR_SIGNATURE_INVALID) {
  358. XSNPRINTF(line, 80, "%s: SIGNATURE_INVALID", op);
  359. }
  360. else {
  361. XSNPRINTF(line, 80, "%s: %08lxUL (FAILED)", op, rv);
  362. }
  363. WOLFSSL_MSG(line);
  364. }
  365. /*
  366. * Log a value from a PKCS #11 operation.
  367. *
  368. * This is only for debugging purposes.
  369. *
  370. * @param [in] op PKCS #11 operation that was attempted.
  371. * @param [in] val Value to log.
  372. */
  373. static void pkcs11_val(const char* op, CK_ULONG val)
  374. {
  375. char line[80];
  376. XSNPRINTF(line, 80, "%s: %ld", op, val);
  377. WOLFSSL_MSG(line);
  378. }
  379. #else
  380. /* Disable logging of PKCS#11 calls and return value. */
  381. #define PKCS11_RV(op, ev) WC_DO_NOTHING
  382. /* Disable logging of PKCS#11 calls and value. */
  383. #define PKCS11_VAL(op, val) WC_DO_NOTHING
  384. /* Disable logging of PKCS#11 template. */
  385. #define PKCS11_DUMP_TEMPLATE(name, templ, cnt) WC_DO_NOTHING
  386. #endif
  387. /**
  388. * Load library, get function list and initialize PKCS#11.
  389. *
  390. * @param [in] dev Device object.
  391. * @param [in] library Library name including path.
  392. * @param [in] heap Heap hint.
  393. * @return BAD_FUNC_ARG when dev or library are NULL pointers.
  394. * @return BAD_PATH_ERROR when dynamic library cannot be opened.
  395. * @return WC_INIT_E when the initialization PKCS#11 fails.
  396. * @return WC_HW_E when unable to get PKCS#11 function list.
  397. * @return 0 on success.
  398. */
  399. int wc_Pkcs11_Initialize(Pkcs11Dev* dev, const char* library, void* heap)
  400. {
  401. return wc_Pkcs11_Initialize_ex(dev, library, heap, NULL);
  402. }
  403. /**
  404. * Load library, get function list and initialize PKCS#11.
  405. *
  406. * @param [in] dev Device object.
  407. * @param [in] library Library name including path.
  408. * @param [in] heap Heap hint.
  409. * @param [out] rvp PKCS#11 return value. Last return value seen.
  410. * May be NULL.
  411. * @return BAD_FUNC_ARG when dev or library are NULL pointers.
  412. * @return BAD_PATH_ERROR when dynamic library cannot be opened.
  413. * @return WC_INIT_E when the initialization PKCS#11 fails.
  414. * @return WC_HW_E when unable to get PKCS#11 function list.
  415. * @return 0 on success.
  416. */
  417. int wc_Pkcs11_Initialize_ex(Pkcs11Dev* dev, const char* library, void* heap,
  418. CK_RV* rvp)
  419. {
  420. int ret = 0;
  421. CK_RV rv = CKR_OK;
  422. #ifndef HAVE_PKCS11_STATIC
  423. void* func;
  424. #endif
  425. CK_C_INITIALIZE_ARGS args;
  426. if (dev == NULL || library == NULL)
  427. ret = BAD_FUNC_ARG;
  428. if (ret == 0) {
  429. dev->heap = heap;
  430. #ifndef HAVE_PKCS11_STATIC
  431. dev->dlHandle = dlopen(library, RTLD_NOW | RTLD_LOCAL);
  432. if (dev->dlHandle == NULL) {
  433. WOLFSSL_MSG(dlerror());
  434. ret = BAD_PATH_ERROR;
  435. }
  436. }
  437. if (ret == 0) {
  438. dev->func = NULL;
  439. func = dlsym(dev->dlHandle, "C_GetFunctionList");
  440. if (func == NULL) {
  441. WOLFSSL_MSG(dlerror());
  442. ret = WC_HW_E;
  443. }
  444. }
  445. if (ret == 0) {
  446. rv = ((CK_C_GetFunctionList)func)(&dev->func);
  447. #else
  448. rv = C_GetFunctionList(&dev->func);
  449. #endif
  450. if (rv != CKR_OK) {
  451. PKCS11_RV("CK_C_GetFunctionList", ret);
  452. ret = WC_HW_E;
  453. }
  454. }
  455. if (ret == 0) {
  456. XMEMSET(&args, 0x00, sizeof(args));
  457. args.flags = CKF_OS_LOCKING_OK;
  458. rv = dev->func->C_Initialize(&args);
  459. if (rv != CKR_OK) {
  460. PKCS11_RV("C_Initialize", ret);
  461. ret = WC_INIT_E;
  462. }
  463. }
  464. if (rvp != NULL) {
  465. *rvp = rv;
  466. }
  467. if (ret != 0) {
  468. wc_Pkcs11_Finalize(dev);
  469. }
  470. return ret;
  471. }
  472. /**
  473. * Close the Pkcs#11 library.
  474. *
  475. * @param [in] dev Device object.
  476. */
  477. void wc_Pkcs11_Finalize(Pkcs11Dev* dev)
  478. {
  479. if (dev != NULL
  480. #ifndef HAVE_PKCS11_STATIC
  481. && dev->dlHandle != NULL
  482. #endif
  483. ) {
  484. if (dev->func != NULL) {
  485. dev->func->C_Finalize(NULL);
  486. dev->func = NULL;
  487. }
  488. #ifndef HAVE_PKCS11_STATIC
  489. dlclose(dev->dlHandle);
  490. dev->dlHandle = NULL;
  491. #endif
  492. }
  493. }
  494. /* lookup by token name and return slotId or (-1) if not found */
  495. static int Pkcs11Slot_FindByTokenName(Pkcs11Dev* dev,
  496. const char* tokenName, size_t tokenNameSz)
  497. {
  498. CK_RV rv;
  499. CK_ULONG slotCnt = 0;
  500. CK_TOKEN_INFO tinfo;
  501. int slotId = -1;
  502. rv = dev->func->C_GetSlotList(CK_TRUE, NULL, &slotCnt);
  503. if (rv == CKR_OK) {
  504. for (slotId = 0; slotId < (int)slotCnt; slotId++) {
  505. rv = dev->func->C_GetTokenInfo(slotId, &tinfo);
  506. PKCS11_RV("C_GetTokenInfo", rv);
  507. if (rv == CKR_OK &&
  508. XMEMCMP(tinfo.label, tokenName, tokenNameSz) == 0) {
  509. return slotId;
  510. }
  511. }
  512. }
  513. return -1;
  514. }
  515. /* lookup by slotId or tokenName */
  516. static int Pkcs11Token_Init(Pkcs11Token* token, Pkcs11Dev* dev, int slotId,
  517. const char* tokenName, size_t tokenNameSz)
  518. {
  519. int ret = 0;
  520. CK_RV rv;
  521. CK_SLOT_ID* slot = NULL;
  522. CK_ULONG slotCnt = 0;
  523. if (token == NULL || dev == NULL) {
  524. ret = BAD_FUNC_ARG;
  525. }
  526. if (ret == 0) {
  527. if (slotId < 0) {
  528. rv = dev->func->C_GetSlotList(CK_TRUE, NULL, &slotCnt);
  529. PKCS11_RV("C_GetSlotList", rv);
  530. if (rv != CKR_OK) {
  531. ret = WC_HW_E;
  532. }
  533. if (ret == 0) {
  534. slot = (CK_SLOT_ID*)XMALLOC(slotCnt * sizeof(*slot), dev->heap,
  535. DYNAMIC_TYPE_TMP_BUFFER);
  536. if (slot == NULL)
  537. ret = MEMORY_E;
  538. }
  539. if (ret == 0) {
  540. rv = dev->func->C_GetSlotList(CK_TRUE, slot, &slotCnt);
  541. PKCS11_RV("C_GetSlotList", rv);
  542. if (rv != CKR_OK) {
  543. ret = WC_HW_E;
  544. }
  545. }
  546. if (ret == 0) {
  547. if (tokenName != NULL && tokenNameSz > 0) {
  548. /* find based on token name */
  549. slotId = Pkcs11Slot_FindByTokenName(dev,
  550. tokenName, tokenNameSz);
  551. }
  552. else {
  553. /* Use first available slot with a token. */
  554. slotId = (int)slot[0];
  555. }
  556. }
  557. }
  558. else {
  559. /* verify slotId is valid */
  560. CK_SLOT_INFO sinfo;
  561. rv = dev->func->C_GetSlotInfo(slotId, &sinfo);
  562. PKCS11_RV("C_GetSlotInfo", rv);
  563. if (rv != CKR_OK) {
  564. ret = WC_INIT_E;
  565. }
  566. }
  567. }
  568. if (ret == 0) {
  569. token->func = dev->func;
  570. token->slotId = (CK_SLOT_ID)slotId;
  571. token->handle = NULL_PTR;
  572. token->userPin = NULL_PTR;
  573. token->userPinSz = 0;
  574. token->userPinLogin = 0;
  575. }
  576. if (slot != NULL) {
  577. XFREE(slot, dev->heap, DYNAMIC_TYPE_TMP_BUFFER);
  578. }
  579. return ret;
  580. }
  581. /**
  582. * Set up a token for use. Lookup by slotId or tokenName. Set User PIN.
  583. *
  584. * @param [in] token Token object.
  585. * @param [in] dev PKCS#11 device object.
  586. * @param [in] slotId Slot number of the token.<br>
  587. * Passing -1 uses the first available slot.
  588. * @param [in] tokenName Name of token to initialize (optional)
  589. * @param [in] userPin PIN to use to login as user.
  590. * @param [in] userPinSz Number of bytes in PIN.
  591. * @return BAD_FUNC_ARG when token, dev and/or tokenName is NULL.
  592. * @return WC_INIT_E when initializing token fails.
  593. * @return WC_HW_E when another PKCS#11 library call fails.
  594. * @return 0 on success.
  595. */
  596. int wc_Pkcs11Token_Init(Pkcs11Token* token, Pkcs11Dev* dev, int slotId,
  597. const char* tokenName, const unsigned char* userPin, int userPinSz)
  598. {
  599. int ret;
  600. size_t tokenNameSz = 0;
  601. if (tokenName != NULL) {
  602. tokenNameSz = XSTRLEN(tokenName);
  603. }
  604. ret = Pkcs11Token_Init(token, dev, slotId, tokenName, tokenNameSz);
  605. if (ret == 0) {
  606. token->userPin = (CK_UTF8CHAR_PTR)userPin;
  607. token->userPinSz = (CK_ULONG)userPinSz;
  608. token->userPinLogin = 1;
  609. }
  610. return ret;
  611. }
  612. /**
  613. * Set up a token for use. Lookup by slotId or tokenName.
  614. *
  615. * @param [in] token Token object.
  616. * @param [in] dev PKCS#11 device object.
  617. * @param [in] slotId Slot number of the token.<br>
  618. * Passing -1 uses the first available slot.
  619. * @param [in] tokenName Name of token to initialize (optional)
  620. * @return BAD_FUNC_ARG when token, dev and/or tokenName is NULL.
  621. * @return WC_INIT_E when initializing token fails.
  622. * @return WC_HW_E when another PKCS#11 library call fails.
  623. * @return 0 on success.
  624. */
  625. int wc_Pkcs11Token_Init_NoLogin(Pkcs11Token* token, Pkcs11Dev* dev, int slotId,
  626. const char* tokenName)
  627. {
  628. size_t tokenNameSz = 0;
  629. if (tokenName != NULL) {
  630. tokenNameSz = XSTRLEN(tokenName);
  631. }
  632. return Pkcs11Token_Init(token, dev, slotId, tokenName, tokenNameSz);
  633. }
  634. /**
  635. * Set up a token for use. Lookup by slotId or tokenName/size. Set User PIN.
  636. *
  637. * @param [in] token Token object.
  638. * @param [in] dev PKCS#11 device object.
  639. * @param [in] tokenName Name of token to initialize.
  640. * @param [in] tokenNameSz Name size for token
  641. * @param [in] userPin PIN to use to login as user.
  642. * @param [in] userPinSz Number of bytes in PIN.
  643. * @return BAD_FUNC_ARG when token, dev and/or tokenName is NULL.
  644. * @return WC_INIT_E when initializing token fails.
  645. * @return WC_HW_E when another PKCS#11 library call fails.
  646. * @return 0 on success.
  647. */
  648. int wc_Pkcs11Token_InitName(Pkcs11Token* token, Pkcs11Dev* dev,
  649. const char* tokenName, int tokenNameSz,
  650. const unsigned char* userPin, int userPinSz)
  651. {
  652. int ret = Pkcs11Token_Init(token, dev, -1, tokenName, (size_t)tokenNameSz);
  653. if (ret == 0) {
  654. token->userPin = (CK_UTF8CHAR_PTR)userPin;
  655. token->userPinSz = (CK_ULONG)userPinSz;
  656. token->userPinLogin = 1;
  657. }
  658. return ret;
  659. }
  660. /**
  661. * Set up a token for use. Lookup by slotId or tokenName/size.
  662. *
  663. * @param [in] token Token object.
  664. * @param [in] dev PKCS#11 device object.
  665. * @param [in] tokenName Name of token to initialize.
  666. * @param [in] tokenNameSz Name size for token
  667. * @param [in] userPin PIN to use to login as user.
  668. * @param [in] userPinSz Number of bytes in PIN.
  669. * @return BAD_FUNC_ARG when token, dev and/or tokenName is NULL.
  670. * @return WC_INIT_E when initializing token fails.
  671. * @return WC_HW_E when another PKCS#11 library call fails.
  672. * @return 0 on success.
  673. */
  674. int wc_Pkcs11Token_InitName_NoLogin(Pkcs11Token* token, Pkcs11Dev* dev,
  675. const char* tokenName, int tokenNameSz)
  676. {
  677. return Pkcs11Token_Init(token, dev, -1, tokenName, (size_t)tokenNameSz);
  678. }
  679. /**
  680. * Finalize token.
  681. * Closes all sessions on token.
  682. *
  683. * @param [in] token Token object.
  684. */
  685. void wc_Pkcs11Token_Final(Pkcs11Token* token)
  686. {
  687. if (token != NULL && token->func != NULL) {
  688. token->func->C_CloseAllSessions(token->slotId);
  689. token->handle = NULL_PTR;
  690. ForceZero(token->userPin, (word32)token->userPinSz);
  691. }
  692. }
  693. /**
  694. * Open a session on a token.
  695. *
  696. * @param [in] token Token object.
  697. * @param [in] session Session object.
  698. * @param [in] readWrite Boolean indicating to open session for Read/Write.
  699. * @return BAD_FUNC_ARG when token or session is NULL.
  700. * @return WC_HW_E when opening the session fails.
  701. * @return 0 on success.
  702. */
  703. static int Pkcs11OpenSession(Pkcs11Token* token, Pkcs11Session* session,
  704. int readWrite)
  705. {
  706. int ret = 0;
  707. CK_RV rv;
  708. if (token == NULL || session == NULL)
  709. ret = BAD_FUNC_ARG;
  710. if (ret == 0) {
  711. if (token->handle != NULL_PTR)
  712. session->handle = token->handle;
  713. else {
  714. /* Create a new session. */
  715. CK_FLAGS flags = CKF_SERIAL_SESSION;
  716. if (readWrite)
  717. flags |= CKF_RW_SESSION;
  718. rv = token->func->C_OpenSession(token->slotId, flags,
  719. (CK_VOID_PTR)NULL, (CK_NOTIFY)NULL,
  720. &session->handle);
  721. PKCS11_RV("C_OpenSession", rv);
  722. if (rv != CKR_OK) {
  723. ret = WC_HW_E;
  724. }
  725. if (ret == 0 && token->userPinLogin) {
  726. rv = token->func->C_Login(session->handle, CKU_USER,
  727. token->userPin, token->userPinSz);
  728. PKCS11_RV("C_Login", rv);
  729. if (rv != CKR_OK) {
  730. ret = WC_HW_E;
  731. }
  732. }
  733. }
  734. }
  735. if (ret == 0) {
  736. session->func = token->func;
  737. session->slotId = token->slotId;
  738. }
  739. return ret;
  740. }
  741. /**
  742. * Close a session on a token.
  743. * Won't close a session created externally.
  744. *
  745. * @param [in] token Token object.
  746. * @param [in] session Session object.
  747. */
  748. static void Pkcs11CloseSession(Pkcs11Token* token, Pkcs11Session* session)
  749. {
  750. if (token != NULL && session != NULL && token->handle != session->handle) {
  751. if (token->userPin != NULL)
  752. session->func->C_Logout(session->handle);
  753. session->func->C_CloseSession(session->handle);
  754. }
  755. }
  756. /**
  757. * Open a session on the token to be used for all operations.
  758. *
  759. * @param [in] token Token object.
  760. * @param [in] readWrite Boolean indicating to open session for Read/Write.
  761. * @return BAD_FUNC_ARG when token is NULL.
  762. * @return WC_HW_E when opening the session fails.
  763. * @return 0 on success.
  764. */
  765. int wc_Pkcs11Token_Open(Pkcs11Token* token, int readWrite)
  766. {
  767. int ret = 0;
  768. Pkcs11Session session;
  769. if (token == NULL)
  770. ret = BAD_FUNC_ARG;
  771. if (ret == 0) {
  772. ret = Pkcs11OpenSession(token, &session, readWrite);
  773. token->handle = session.handle;
  774. }
  775. return ret;
  776. }
  777. /**
  778. * Close the token's session.
  779. * All object, like keys, will be destroyed.
  780. *
  781. * @param [in] token Token object.
  782. */
  783. void wc_Pkcs11Token_Close(Pkcs11Token* token)
  784. {
  785. Pkcs11Session session;
  786. if (token != NULL) {
  787. session.func = token->func;
  788. session.handle = token->handle;
  789. token->handle = NULL_PTR;
  790. Pkcs11CloseSession(token, &session);
  791. }
  792. }
  793. #if (!defined(NO_AES) && (defined(HAVE_AESGCM) || defined(HAVE_AES_CBC))) || \
  794. !defined(NO_HMAC)
  795. /*
  796. * Create a secret key.
  797. *
  798. * @param [out] key Handle to key object.
  799. * @param [in] session Session object.
  800. * @param [in] keyType Type of secret key to create.
  801. * @param [in] data Data of the secret key.
  802. * @param [in] len Length of data in bytes.
  803. * @param [in] id Identifier to set against key.
  804. * @param [in] idLen Length of identifier.
  805. * @param [in] label Label to set against key.
  806. * @param [in] labelLen Length of label.
  807. * @param [in] op Operation to support with key.
  808. * @return WC_HW_E when another PKCS#11 library call fails.
  809. * @return 0 on success.
  810. */
  811. static int Pkcs11CreateSecretKey(CK_OBJECT_HANDLE* key, Pkcs11Session* session,
  812. CK_KEY_TYPE keyType, unsigned char* data,
  813. int len, unsigned char* id, int idLen,
  814. char* label, int labelLen, int op)
  815. {
  816. int ret = 0;
  817. CK_RV rv;
  818. /* Empty entries for optional label/ID. */
  819. CK_ATTRIBUTE keyTemplateEncDec[] = {
  820. { CKA_CLASS, &secretKeyClass, sizeof(secretKeyClass) },
  821. { CKA_KEY_TYPE, &keyType, sizeof(keyType) },
  822. { CKA_ENCRYPT, &ckTrue, sizeof(ckTrue) },
  823. { CKA_DECRYPT, &ckTrue, sizeof(ckTrue) },
  824. { CKA_VALUE, NULL, 0 },
  825. { 0, NULL, 0 },
  826. { 0, NULL, 0 }
  827. };
  828. /* Empty entries for optional label/ID. */
  829. CK_ATTRIBUTE keyTemplateSignVfy[] = {
  830. { CKA_CLASS, &secretKeyClass, sizeof(secretKeyClass) },
  831. { CKA_KEY_TYPE, &keyType, sizeof(keyType) },
  832. { CKA_SIGN, &ckTrue, sizeof(ckTrue) },
  833. { CKA_VERIFY, &ckTrue, sizeof(ckTrue) },
  834. { CKA_VALUE, NULL, 0 },
  835. { 0, NULL, 0 },
  836. { 0, NULL, 0 }
  837. };
  838. CK_ATTRIBUTE* keyTemplate = NULL;
  839. /* 5 mandatory entries + 2 optional. */
  840. int keyTmplCnt = 5;
  841. WOLFSSL_MSG("PKCS#11: Create Secret Key");
  842. if (op == CKA_ENCRYPT || op == CKA_DECRYPT) {
  843. keyTemplate = keyTemplateEncDec;
  844. }
  845. else if (op == CKA_SIGN) {
  846. keyTemplate = keyTemplateSignVfy;
  847. }
  848. else {
  849. WOLFSSL_MSG("PKCS#11: Invalid operation type");
  850. ret = WC_HW_E;
  851. }
  852. if (ret == 0) {
  853. /* Set the secret to store. */
  854. keyTemplate[keyTmplCnt-1].pValue = data;
  855. keyTemplate[keyTmplCnt-1].ulValueLen = (CK_ULONG)len;
  856. if (labelLen > 0) {
  857. keyTemplate[keyTmplCnt].type = CKA_LABEL;
  858. keyTemplate[keyTmplCnt].pValue = label;
  859. keyTemplate[keyTmplCnt].ulValueLen = labelLen;
  860. keyTmplCnt++;
  861. }
  862. if (idLen > 0) {
  863. keyTemplate[keyTmplCnt].type = CKA_ID;
  864. keyTemplate[keyTmplCnt].pValue = id;
  865. keyTemplate[keyTmplCnt].ulValueLen = idLen;
  866. keyTmplCnt++;
  867. }
  868. PKCS11_DUMP_TEMPLATE("Secret Key", keyTemplate, keyTmplCnt);
  869. /* Create an object containing key data for device to use. */
  870. rv = session->func->C_CreateObject(session->handle, keyTemplate,
  871. keyTmplCnt, key);
  872. PKCS11_RV("C_CreateObject", rv);
  873. if (rv != CKR_OK) {
  874. ret = WC_HW_E;
  875. }
  876. }
  877. return ret;
  878. }
  879. #endif
  880. #ifndef NO_RSA
  881. /**
  882. * Create a PKCS#11 object containing the RSA private key data.
  883. *
  884. * @param [out] privateKey Handle to private key object.
  885. * @param [in] session Session object.
  886. * @param [in] rsaKey RSA key with private key data.
  887. * @return WC_HW_E when a PKCS#11 library call fails.
  888. * @return 0 on success.
  889. */
  890. static int Pkcs11CreateRsaPrivateKey(CK_OBJECT_HANDLE* privateKey,
  891. Pkcs11Session* session,
  892. RsaKey* rsaKey, int permanent)
  893. {
  894. int ret = 0;
  895. CK_RV rv;
  896. /* Empty entries for optional label/ID. */
  897. CK_ATTRIBUTE keyTemplate[] = {
  898. { CKA_CLASS, &privKeyClass, sizeof(privKeyClass) },
  899. { CKA_KEY_TYPE, &rsaKeyType, sizeof(rsaKeyType) },
  900. { CKA_DECRYPT, &ckTrue, sizeof(ckTrue) },
  901. { CKA_SIGN, &ckTrue, sizeof(ckTrue) },
  902. { CKA_MODULUS, NULL, 0 },
  903. { CKA_PRIVATE_EXPONENT, NULL, 0 },
  904. { CKA_PRIME_1, NULL, 0 },
  905. { CKA_PRIME_2, NULL, 0 },
  906. { CKA_EXPONENT_1, NULL, 0 },
  907. { CKA_EXPONENT_2, NULL, 0 },
  908. { CKA_COEFFICIENT, NULL, 0 },
  909. { CKA_PUBLIC_EXPONENT, NULL, 0 },
  910. { 0, NULL, 0 },
  911. { 0, NULL, 0 }
  912. };
  913. /* Mandatory entries + 2 optional. */
  914. CK_ULONG keyTmplCnt = sizeof(keyTemplate) / sizeof(*keyTemplate) - 2;
  915. /* Set the modulus and private key data. */
  916. keyTemplate[ 4].pValue = rsaKey->n.raw.buf;
  917. keyTemplate[ 4].ulValueLen = rsaKey->n.raw.len;
  918. keyTemplate[ 5].pValue = rsaKey->d.raw.buf;
  919. keyTemplate[ 5].ulValueLen = rsaKey->d.raw.len;
  920. keyTemplate[ 6].pValue = rsaKey->p.raw.buf;
  921. keyTemplate[ 6].ulValueLen = rsaKey->p.raw.len;
  922. keyTemplate[ 7].pValue = rsaKey->q.raw.buf;
  923. keyTemplate[ 7].ulValueLen = rsaKey->q.raw.len;
  924. keyTemplate[ 8].pValue = rsaKey->dP.raw.buf;
  925. keyTemplate[ 8].ulValueLen = rsaKey->dP.raw.len;
  926. keyTemplate[ 9].pValue = rsaKey->dQ.raw.buf;
  927. keyTemplate[ 9].ulValueLen = rsaKey->dQ.raw.len;
  928. keyTemplate[10].pValue = rsaKey->u.raw.buf;
  929. keyTemplate[10].ulValueLen = rsaKey->u.raw.len;
  930. keyTemplate[11].pValue = rsaKey->e.raw.buf;
  931. keyTemplate[11].ulValueLen = rsaKey->e.raw.len;
  932. if (permanent && rsaKey->labelLen > 0) {
  933. keyTemplate[keyTmplCnt].type = CKA_LABEL;
  934. keyTemplate[keyTmplCnt].pValue = rsaKey->label;
  935. keyTemplate[keyTmplCnt].ulValueLen = rsaKey->labelLen;
  936. keyTmplCnt++;
  937. }
  938. if (permanent && rsaKey->idLen > 0) {
  939. keyTemplate[keyTmplCnt].type = CKA_ID;
  940. keyTemplate[keyTmplCnt].pValue = rsaKey->id;
  941. keyTemplate[keyTmplCnt].ulValueLen = rsaKey->idLen;
  942. keyTmplCnt++;
  943. }
  944. PKCS11_DUMP_TEMPLATE("RSA Private Key", keyTemplate, keyTmplCnt);
  945. rv = session->func->C_CreateObject(session->handle, keyTemplate, keyTmplCnt,
  946. privateKey);
  947. PKCS11_RV("C_CreateObject", rv);
  948. if (rv != CKR_OK) {
  949. ret = WC_HW_E;
  950. }
  951. return ret;
  952. }
  953. #endif
  954. #ifdef HAVE_ECC
  955. /**
  956. * Set the ECC parameters into the template.
  957. *
  958. * @param [in] key ECC key.
  959. * @param [in] tmpl PKCS#11 template.
  960. * @param [in] idx Index of template to put parameters into.
  961. * @return NOT_COMPILED_IN when the EC parameters are not known.
  962. * @return 0 on success.
  963. */
  964. static int Pkcs11EccSetParams(ecc_key* key, CK_ATTRIBUTE* tmpl, int idx)
  965. {
  966. int ret = 0;
  967. if (key->dp != NULL && key->dp->oid != NULL) {
  968. unsigned char* derParams = tmpl[idx].pValue;
  969. /* ASN.1 encoding: OBJ + ecc parameters OID */
  970. tmpl[idx].ulValueLen = key->dp->oidSz + 2;
  971. derParams[0] = ASN_OBJECT_ID;
  972. derParams[1] = key->dp->oidSz;
  973. XMEMCPY(derParams + 2, key->dp->oid, key->dp->oidSz);
  974. }
  975. else
  976. ret = NOT_COMPILED_IN;
  977. return ret;
  978. }
  979. /**
  980. * Create a PKCS#11 object containing the ECC public key data.
  981. * Encode the public key as an OCTET_STRING of the encoded point.
  982. *
  983. * @param [out] publicKey Handle to public key object.
  984. * @param [in] session Session object.
  985. * @param [in] public_key ECC public key.
  986. * @param [in] operation Cryptographic operation key is to be used for.
  987. * @return WC_HW_E when a PKCS#11 library call fails.
  988. * @return MEMORY_E when a memory allocation fails.
  989. * @return 0 on success.
  990. */
  991. static int Pkcs11CreateEccPublicKey(CK_OBJECT_HANDLE* publicKey,
  992. Pkcs11Session* session,
  993. ecc_key* public_key,
  994. CK_ATTRIBUTE_TYPE operation)
  995. {
  996. int ret = 0;
  997. int i;
  998. unsigned char* ecPoint = NULL;
  999. word32 len;
  1000. CK_RV rv;
  1001. CK_UTF8CHAR params[MAX_EC_PARAM_LEN];
  1002. /* Empty entries for optional label/ID. */
  1003. CK_ATTRIBUTE keyTemplate[] = {
  1004. { CKA_CLASS, &pubKeyClass, sizeof(pubKeyClass) },
  1005. { CKA_KEY_TYPE, &ecKeyType, sizeof(ecKeyType) },
  1006. { operation, &ckTrue, sizeof(ckTrue) },
  1007. { CKA_EC_PARAMS, params, 0 },
  1008. { CKA_EC_POINT, NULL, 0 },
  1009. { 0, NULL, 0 },
  1010. { 0, NULL, 0 }
  1011. };
  1012. /* Mandatory entries + 2 optional. */
  1013. CK_ULONG keyTmplCnt = sizeof(keyTemplate) / sizeof(*keyTemplate) - 2;
  1014. if (public_key->labelLen > 0) {
  1015. keyTemplate[keyTmplCnt].type = CKA_LABEL;
  1016. keyTemplate[keyTmplCnt].pValue = public_key->label;
  1017. keyTemplate[keyTmplCnt].ulValueLen = public_key->labelLen;
  1018. keyTmplCnt++;
  1019. }
  1020. if (public_key->idLen > 0) {
  1021. keyTemplate[keyTmplCnt].type = CKA_ID;
  1022. keyTemplate[keyTmplCnt].pValue = public_key->id;
  1023. keyTemplate[keyTmplCnt].ulValueLen = public_key->idLen;
  1024. keyTmplCnt++;
  1025. }
  1026. ret = Pkcs11EccSetParams(public_key, keyTemplate, 3);
  1027. if (ret == 0) {
  1028. /* ASN1 encoded: OCT + uncompressed point */
  1029. len = 3 + 1 + 2 * public_key->dp->size;
  1030. ecPoint = (unsigned char*)XMALLOC(len, public_key->heap,
  1031. DYNAMIC_TYPE_ECC);
  1032. if (ecPoint == NULL)
  1033. ret = MEMORY_E;
  1034. }
  1035. if (ret == 0) {
  1036. len -= 3;
  1037. i = 0;
  1038. ecPoint[i++] = ASN_OCTET_STRING;
  1039. if (len >= ASN_LONG_LENGTH)
  1040. ecPoint[i++] = ASN_LONG_LENGTH | 1;
  1041. ecPoint[i++] = len;
  1042. if (public_key->type == 0)
  1043. public_key->type = ECC_PUBLICKEY;
  1044. PRIVATE_KEY_UNLOCK();
  1045. ret = wc_ecc_export_x963(public_key, ecPoint + i, &len);
  1046. PRIVATE_KEY_LOCK();
  1047. }
  1048. if (ret == 0) {
  1049. keyTemplate[4].pValue = ecPoint;
  1050. keyTemplate[4].ulValueLen = len + i;
  1051. PKCS11_DUMP_TEMPLATE("Ec Public Key", keyTemplate, keyTmplCnt);
  1052. rv = session->func->C_CreateObject(session->handle, keyTemplate,
  1053. keyTmplCnt, publicKey);
  1054. PKCS11_RV("C_CreateObject", rv);
  1055. if (rv != CKR_OK) {
  1056. ret = WC_HW_E;
  1057. }
  1058. }
  1059. if (ecPoint != NULL)
  1060. XFREE(ecPoint, public_key->heap, DYNAMIC_TYPE_ECC);
  1061. return ret;
  1062. }
  1063. /**
  1064. * Create a PKCS#11 object containing the ECC private key data.
  1065. *
  1066. * @param privateKey [out] Handle to private key object.
  1067. * @param session [in] Session object.
  1068. * @param private_key [in] ECC private key.
  1069. * @param operation [in] Cryptographic operation key is to be used for.
  1070. * @return WC_HW_E when a PKCS#11 library call fails.
  1071. * @return 0 on success.
  1072. */
  1073. static int Pkcs11CreateEccPrivateKey(CK_OBJECT_HANDLE* privateKey,
  1074. Pkcs11Session* session,
  1075. ecc_key* private_key,
  1076. CK_ATTRIBUTE_TYPE operation)
  1077. {
  1078. int ret = 0;
  1079. CK_RV rv;
  1080. CK_UTF8CHAR params[MAX_EC_PARAM_LEN];
  1081. /* Empty entries for optional label/ID. */
  1082. CK_ATTRIBUTE keyTemplate[] = {
  1083. { CKA_CLASS, &privKeyClass, sizeof(privKeyClass) },
  1084. { CKA_KEY_TYPE, &ecKeyType, sizeof(ecKeyType) },
  1085. { operation, &ckTrue, sizeof(ckTrue) },
  1086. { CKA_EC_PARAMS, params, 0 },
  1087. { CKA_VALUE, NULL, 0 },
  1088. { 0, NULL, 0 },
  1089. { 0, NULL, 0 }
  1090. };
  1091. /* Mandatory entries + 2 optional. */
  1092. CK_ULONG keyTmplCnt = sizeof(keyTemplate) / sizeof(*keyTemplate) - 2;
  1093. if (private_key->labelLen > 0) {
  1094. keyTemplate[keyTmplCnt].type = CKA_LABEL;
  1095. keyTemplate[keyTmplCnt].pValue = private_key->label;
  1096. keyTemplate[keyTmplCnt].ulValueLen = private_key->labelLen;
  1097. keyTmplCnt++;
  1098. }
  1099. if (private_key->idLen > 0) {
  1100. keyTemplate[keyTmplCnt].type = CKA_ID;
  1101. keyTemplate[keyTmplCnt].pValue = private_key->id;
  1102. keyTemplate[keyTmplCnt].ulValueLen = private_key->idLen;
  1103. keyTmplCnt++;
  1104. }
  1105. ret = Pkcs11EccSetParams(private_key, keyTemplate, 3);
  1106. if (ret == 0) {
  1107. keyTemplate[4].pValue = wc_ecc_key_get_priv(private_key)->raw.buf;
  1108. keyTemplate[4].ulValueLen = wc_ecc_key_get_priv(private_key)->raw.len;
  1109. PKCS11_DUMP_TEMPLATE("Ec Private Key", keyTemplate, keyTmplCnt);
  1110. rv = session->func->C_CreateObject(session->handle, keyTemplate,
  1111. keyTmplCnt, privateKey);
  1112. PKCS11_RV("C_CreateObject", rv);
  1113. if (rv != CKR_OK) {
  1114. ret = WC_HW_E;
  1115. }
  1116. }
  1117. return ret;
  1118. }
  1119. #endif
  1120. #if !defined(NO_RSA) || defined(HAVE_ECC) || (!defined(NO_AES) && \
  1121. (defined(HAVE_AESGCM) || defined(HAVE_AES_CBC))) || !defined(NO_HMAC)
  1122. /**
  1123. * Check if mechanism is available in session on token.
  1124. *
  1125. * @param [in] session Session object.
  1126. * @param [in] mech Mechanism to look for.
  1127. * @return NOT_COMPILED_IN when mechanism not available.
  1128. * @return 0 when mechanism is available.
  1129. */
  1130. static int Pkcs11MechAvail(Pkcs11Session* session, CK_MECHANISM_TYPE mech)
  1131. {
  1132. int ret = 0;
  1133. CK_RV rv;
  1134. CK_MECHANISM_INFO mechInfo;
  1135. rv = session->func->C_GetMechanismInfo(session->slotId, mech, &mechInfo);
  1136. PKCS11_RV("C_GetMechanismInfo", rv);
  1137. if (rv != CKR_OK) {
  1138. ret = NOT_COMPILED_IN;
  1139. }
  1140. return ret;
  1141. }
  1142. #endif
  1143. #ifndef NO_HMAC
  1144. /**
  1145. * Return the mechanism type and key type for the digest type when using HMAC.
  1146. *
  1147. * @param [in] macType Digest type - e.g. WC_SHA256.
  1148. * @param [in] mechType Mechanism type - e.g. CKM_SHA256_HMAC.
  1149. * @param [in] keyType Key type - e.g. CKK_SHA256_HMAC.
  1150. * @return NOT_COMPILED_IN if the digest algorithm isn't recognised.
  1151. * @return 0 otherwise.
  1152. */
  1153. static int Pkcs11HmacTypes(int macType, int* mechType, int* keyType)
  1154. {
  1155. int ret = 0;
  1156. switch (macType)
  1157. {
  1158. #ifndef NO_MD5
  1159. case WC_MD5:
  1160. *mechType = CKM_MD5_HMAC;
  1161. *keyType = CKK_MD5_HMAC;
  1162. break;
  1163. #endif
  1164. #ifndef NO_SHA
  1165. case WC_SHA:
  1166. *mechType = CKM_SHA_1_HMAC;
  1167. *keyType = CKK_SHA_1_HMAC;
  1168. break;
  1169. #endif
  1170. #ifdef WOLFSSL_SHA224
  1171. case WC_SHA224:
  1172. *mechType = CKM_SHA224_HMAC;
  1173. *keyType = CKK_SHA224_HMAC;
  1174. break;
  1175. #endif
  1176. #ifndef NO_SHA256
  1177. case WC_SHA256:
  1178. *mechType = CKM_SHA256_HMAC;
  1179. *keyType = CKK_SHA256_HMAC;
  1180. break;
  1181. #endif
  1182. #ifdef WOLFSSL_SHA384
  1183. case WC_SHA384:
  1184. *mechType = CKM_SHA384_HMAC;
  1185. *keyType = CKK_SHA384_HMAC;
  1186. break;
  1187. #endif
  1188. #ifdef WOLFSSL_SHA512
  1189. case WC_SHA512:
  1190. *mechType = CKM_SHA512_HMAC;
  1191. *keyType = CKK_SHA512_HMAC;
  1192. break;
  1193. #endif
  1194. default:
  1195. ret = NOT_COMPILED_IN;
  1196. break;
  1197. }
  1198. return ret;
  1199. }
  1200. #endif
  1201. /**
  1202. * Store the private key on the token in the session.
  1203. *
  1204. * @param [in] token Token to store private key on.
  1205. * @param [in] type Key type.
  1206. * @param [in] clear Clear out the private data from software key.
  1207. * @param [in] key Key type specific object.
  1208. * @return NOT_COMPILED_IN when mechanism not available.
  1209. * @return 0 on success.
  1210. */
  1211. int wc_Pkcs11StoreKey(Pkcs11Token* token, int type, int clear, void* key)
  1212. {
  1213. int ret = 0;
  1214. Pkcs11Session session;
  1215. CK_OBJECT_HANDLE privKey = NULL_PTR;
  1216. ret = Pkcs11OpenSession(token, &session, 1);
  1217. if (ret == 0) {
  1218. switch (type) {
  1219. #if !defined(NO_AES) && defined(HAVE_AESGCM)
  1220. case PKCS11_KEY_TYPE_AES_GCM: {
  1221. Aes* aes = (Aes*)key;
  1222. ret = Pkcs11MechAvail(&session, CKM_AES_GCM);
  1223. if (ret == 0) {
  1224. ret = Pkcs11CreateSecretKey(&privKey, &session, CKK_AES,
  1225. (unsigned char*)aes->devKey,
  1226. aes->keylen,
  1227. (unsigned char*)aes->id,
  1228. aes->idLen, aes->label,
  1229. aes->labelLen, CKA_ENCRYPT);
  1230. }
  1231. if (ret == 0 && clear)
  1232. ForceZero(aes->devKey, aes->keylen);
  1233. break;
  1234. }
  1235. #endif
  1236. #if !defined(NO_AES) && defined(HAVE_AES_CBC)
  1237. case PKCS11_KEY_TYPE_AES_CBC: {
  1238. Aes* aes = (Aes*)key;
  1239. ret = Pkcs11MechAvail(&session, CKM_AES_CBC);
  1240. if (ret == 0) {
  1241. ret = Pkcs11CreateSecretKey(&privKey, &session, CKK_AES,
  1242. (unsigned char*)aes->devKey,
  1243. aes->keylen,
  1244. (unsigned char*)aes->id,
  1245. aes->idLen, aes->label,
  1246. aes->labelLen, CKA_ENCRYPT);
  1247. }
  1248. if (ret == 0 && clear)
  1249. ForceZero(aes->devKey, aes->keylen);
  1250. break;
  1251. }
  1252. #endif
  1253. #ifndef NO_HMAC
  1254. case PKCS11_KEY_TYPE_HMAC: {
  1255. Hmac* hmac = (Hmac*)key;
  1256. int mechType;
  1257. int keyType;
  1258. ret = Pkcs11HmacTypes(hmac->macType, &mechType, &keyType);
  1259. if (ret == NOT_COMPILED_IN)
  1260. break;
  1261. if (ret == 0)
  1262. ret = Pkcs11MechAvail(&session, mechType);
  1263. if (ret == 0) {
  1264. ret = Pkcs11CreateSecretKey(&privKey, &session, keyType,
  1265. (unsigned char*)hmac->keyRaw,
  1266. hmac->keyLen,
  1267. (unsigned char*)hmac->id,
  1268. hmac->idLen, hmac->label,
  1269. hmac->labelLen, CKA_SIGN);
  1270. if (ret == WC_HW_E) {
  1271. ret = Pkcs11CreateSecretKey(&privKey, &session,
  1272. CKK_GENERIC_SECRET,
  1273. (unsigned char*)hmac->keyRaw,
  1274. hmac->keyLen,
  1275. (unsigned char*)hmac->id,
  1276. hmac->idLen, hmac->label,
  1277. hmac->labelLen, CKA_SIGN);
  1278. }
  1279. }
  1280. break;
  1281. }
  1282. #endif
  1283. #ifndef NO_RSA
  1284. case PKCS11_KEY_TYPE_RSA: {
  1285. RsaKey* rsaKey = (RsaKey*)key;
  1286. ret = Pkcs11MechAvail(&session, CKM_RSA_X_509);
  1287. if (ret == 0)
  1288. ret = Pkcs11CreateRsaPrivateKey(&privKey, &session, rsaKey,
  1289. 1);
  1290. if (ret == 0 && clear) {
  1291. mp_forcezero(&rsaKey->u);
  1292. mp_forcezero(&rsaKey->dQ);
  1293. mp_forcezero(&rsaKey->dP);
  1294. mp_forcezero(&rsaKey->q);
  1295. mp_forcezero(&rsaKey->p);
  1296. mp_forcezero(&rsaKey->d);
  1297. }
  1298. break;
  1299. }
  1300. #endif
  1301. #ifdef HAVE_ECC
  1302. case PKCS11_KEY_TYPE_EC: {
  1303. ecc_key* eccKey = (ecc_key*)key;
  1304. int ret2 = NOT_COMPILED_IN;
  1305. #ifndef NO_PKCS11_ECDH
  1306. if ((eccKey->flags & WC_ECC_FLAG_DEC_SIGN) == 0) {
  1307. /* Try ECDH mechanism first. */
  1308. ret = Pkcs11MechAvail(&session, CKM_ECDH1_DERIVE);
  1309. if (ret == 0) {
  1310. ret = Pkcs11CreateEccPrivateKey(&privKey, &session,
  1311. eccKey, CKA_DERIVE);
  1312. }
  1313. }
  1314. #endif
  1315. if (ret == 0 || ret == NOT_COMPILED_IN) {
  1316. /* Try ECDSA mechanism next. */
  1317. ret2 = Pkcs11MechAvail(&session, CKM_ECDSA);
  1318. if (ret2 == 0) {
  1319. ret2 = Pkcs11CreateEccPrivateKey(&privKey, &session,
  1320. eccKey, CKA_SIGN);
  1321. if (ret2 == 0) {
  1322. CK_OBJECT_HANDLE pubKey = NULL_PTR;
  1323. /* Store public key for validation with cert. */
  1324. ret2 = Pkcs11CreateEccPublicKey(&pubKey, &session,
  1325. eccKey, CKA_VERIFY);
  1326. }
  1327. }
  1328. /* OK for this to fail if set for ECDH. */
  1329. if (ret == NOT_COMPILED_IN)
  1330. ret = ret2;
  1331. }
  1332. if (ret == 0 && clear)
  1333. mp_forcezero(wc_ecc_key_get_priv(eccKey));
  1334. break;
  1335. }
  1336. #endif
  1337. default:
  1338. ret = NOT_COMPILED_IN;
  1339. break;
  1340. }
  1341. Pkcs11CloseSession(token, &session);
  1342. }
  1343. (void)privKey;
  1344. (void)clear;
  1345. (void)key;
  1346. return ret;
  1347. }
  1348. #if !defined(NO_RSA) || defined(HAVE_ECC) || (!defined(NO_AES) && \
  1349. (defined(HAVE_AESGCM) || defined(HAVE_AES_CBC))) || !defined(NO_HMAC)
  1350. /**
  1351. * Find the PKCS#11 object containing key data using template.
  1352. *
  1353. * @param [out] key Handle to key object.
  1354. * @param [in] session Session object.
  1355. * @param [in] keyTemplate PKCS #11 template to use in search.
  1356. * @param [in] keyTmplCnt Count of entries in PKCS #11 template.
  1357. * @param [out] count Number of keys matching template.
  1358. * @return WC_HW_E when a PKCS#11 library call fails.
  1359. * @return 0 on success.
  1360. */
  1361. static int Pkcs11FindKeyByTemplate(CK_OBJECT_HANDLE* key,
  1362. Pkcs11Session* session,
  1363. CK_ATTRIBUTE *keyTemplate,
  1364. CK_ULONG keyTmplCnt,
  1365. CK_ULONG *count)
  1366. {
  1367. int ret = 0;
  1368. CK_RV rv;
  1369. WOLFSSL_MSG("PKCS#11: Find Key By Template");
  1370. PKCS11_DUMP_TEMPLATE("Find Key", keyTemplate, keyTmplCnt);
  1371. rv = session->func->C_FindObjectsInit(session->handle, keyTemplate,
  1372. keyTmplCnt);
  1373. PKCS11_RV("C_FindObjectsInit", rv);
  1374. if (rv != CKR_OK) {
  1375. ret = WC_HW_E;
  1376. }
  1377. if (ret == 0) {
  1378. rv = session->func->C_FindObjects(session->handle, key, 1, count);
  1379. PKCS11_RV("C_FindObjects", rv);
  1380. PKCS11_VAL("C_FindObjects Count", *count);
  1381. if (rv != CKR_OK) {
  1382. ret = WC_HW_E;
  1383. }
  1384. rv = session->func->C_FindObjectsFinal(session->handle);
  1385. PKCS11_RV("C_FindObjectsFinal", rv);
  1386. if (rv != CKR_OK) {
  1387. ret = WC_HW_E;
  1388. }
  1389. }
  1390. return ret;
  1391. }
  1392. /**
  1393. * Find the PKCS#11 object containing the private key data by label.
  1394. *
  1395. * @param [out] key Handle to key object.
  1396. * @param [in] keyClass Public or private key class.
  1397. * @param [in] keyType Type of key.
  1398. * @param [in] session Session object.
  1399. * @param [in] id Identifier set against a key.
  1400. * @param [in] idLen Length of identifier.
  1401. * @return WC_HW_E when a PKCS#11 library call fails.
  1402. * @return 0 on success.
  1403. */
  1404. static int Pkcs11FindKeyByLabel(CK_OBJECT_HANDLE* key, CK_OBJECT_CLASS keyClass,
  1405. CK_KEY_TYPE keyType, Pkcs11Session* session,
  1406. char* label, int labelLen)
  1407. {
  1408. int ret = 0;
  1409. CK_ULONG count;
  1410. CK_ATTRIBUTE keyTemplate[] = {
  1411. { CKA_CLASS, &keyClass, sizeof(keyClass) },
  1412. { CKA_KEY_TYPE, &keyType, sizeof(keyType) },
  1413. { CKA_LABEL, label, (CK_ULONG)labelLen }
  1414. };
  1415. CK_ULONG keyTmplCnt = sizeof(keyTemplate) / sizeof(*keyTemplate);
  1416. WOLFSSL_MSG("PKCS#11: Find Key By Label");
  1417. ret = Pkcs11FindKeyByTemplate(key, session, keyTemplate, keyTmplCnt,
  1418. &count);
  1419. if (ret == 0 && count == 0)
  1420. ret = WC_HW_E;
  1421. return ret;
  1422. }
  1423. /**
  1424. * Find the PKCS#11 object containing the private key data by ID.
  1425. *
  1426. * @param [out] key Handle to key object.
  1427. * @param [in] keyClass Public or private key class.
  1428. * @param [in] keyType Type of key.
  1429. * @param [in] session Session object.
  1430. * @param [in] id Identifier set against a key.
  1431. * @param [in] idLen Length of identifier.
  1432. * @return WC_HW_E when a PKCS#11 library call fails.
  1433. * @return 0 on success.
  1434. */
  1435. static int Pkcs11FindKeyById(CK_OBJECT_HANDLE* key, CK_OBJECT_CLASS keyClass,
  1436. CK_KEY_TYPE keyType, Pkcs11Session* session,
  1437. byte* id, int idLen)
  1438. {
  1439. int ret = 0;
  1440. CK_ULONG count;
  1441. CK_ATTRIBUTE keyTemplate[] = {
  1442. #ifndef WC_PKCS11_FIND_WITH_ID_ONLY
  1443. { CKA_CLASS, &keyClass, sizeof(keyClass) },
  1444. { CKA_KEY_TYPE, &keyType, sizeof(keyType) },
  1445. #endif
  1446. { CKA_ID, id, (CK_ULONG)idLen }
  1447. };
  1448. CK_ULONG keyTmplCnt = sizeof(keyTemplate) / sizeof(*keyTemplate);
  1449. WOLFSSL_MSG("PKCS#11: Find Key By Id");
  1450. ret = Pkcs11FindKeyByTemplate(key, session, keyTemplate, keyTmplCnt,
  1451. &count);
  1452. if (ret == 0 && count == 0)
  1453. ret = WC_HW_E;
  1454. return ret;
  1455. }
  1456. #endif
  1457. #ifndef NO_RSA
  1458. /**
  1459. * Find the PKCS#11 object containing the RSA public or private key data with
  1460. * the modulus specified.
  1461. *
  1462. * @param [out] key Handle to key object.
  1463. * @param [in] keyClass Public or private key class.
  1464. * @param [in] session Session object.
  1465. * @param [in] rsaKey RSA key with modulus to search on.
  1466. * @return WC_HW_E when a PKCS#11 library call fails.
  1467. * @return 0 on success.
  1468. */
  1469. static int Pkcs11FindRsaKey(CK_OBJECT_HANDLE* key, CK_OBJECT_CLASS keyClass,
  1470. Pkcs11Session* session, RsaKey* rsaKey)
  1471. {
  1472. CK_ULONG count;
  1473. CK_ATTRIBUTE keyTemplate[] = {
  1474. { CKA_CLASS, &keyClass, sizeof(keyClass) },
  1475. { CKA_KEY_TYPE, &rsaKeyType, sizeof(rsaKeyType) },
  1476. { CKA_MODULUS, NULL, 0 },
  1477. };
  1478. CK_ULONG keyTmplCnt = sizeof(keyTemplate) / sizeof(*keyTemplate);
  1479. /* Set the modulus. */
  1480. keyTemplate[2].pValue = rsaKey->n.raw.buf;
  1481. keyTemplate[2].ulValueLen = rsaKey->n.raw.len;
  1482. return Pkcs11FindKeyByTemplate(key, session, keyTemplate, keyTmplCnt,
  1483. &count);
  1484. }
  1485. /**
  1486. * Make a handle to a public RSA key.
  1487. *
  1488. * @param [in] session Session object.
  1489. * @param [in] rsaKey RSA key with modulus to search on.
  1490. * @param [in] sessionKey Whether to create a session key.
  1491. * @param [out] publicKey Handle to public key object.
  1492. */
  1493. static int Pkcs11RsaPublicKey(Pkcs11Session* session, RsaKey* rsaKey,
  1494. int sessionKey, CK_OBJECT_HANDLE* publicKey)
  1495. {
  1496. int ret = 0;
  1497. CK_RV rv;
  1498. CK_ATTRIBUTE keyTemplate[] = {
  1499. { CKA_CLASS, &pubKeyClass, sizeof(pubKeyClass) },
  1500. { CKA_KEY_TYPE, &rsaKeyType, sizeof(rsaKeyType) },
  1501. { CKA_ENCRYPT, &ckTrue, sizeof(ckTrue) },
  1502. { CKA_MODULUS, NULL, 0 },
  1503. { CKA_PUBLIC_EXPONENT, NULL, 0 }
  1504. };
  1505. CK_ULONG keyTmplCnt = sizeof(keyTemplate) / sizeof(*keyTemplate);
  1506. if (sessionKey) {
  1507. /* Set the modulus and public exponent data. */
  1508. keyTemplate[3].pValue = rsaKey->n.raw.buf;
  1509. keyTemplate[3].ulValueLen = rsaKey->n.raw.len;
  1510. keyTemplate[4].pValue = rsaKey->e.raw.buf;
  1511. keyTemplate[4].ulValueLen = rsaKey->e.raw.len;
  1512. PKCS11_DUMP_TEMPLATE("RSA Public Key", keyTemplate, keyTmplCnt);
  1513. /* Create an object containing public key data for device to use. */
  1514. rv = session->func->C_CreateObject(session->handle, keyTemplate,
  1515. keyTmplCnt, publicKey);
  1516. PKCS11_RV("C_CreateObject", rv);
  1517. if (rv != CKR_OK) {
  1518. ret = WC_HW_E;
  1519. }
  1520. }
  1521. else if (rsaKey->labelLen > 0) {
  1522. ret = Pkcs11FindKeyByLabel(publicKey, CKO_PUBLIC_KEY, CKK_RSA,
  1523. session, rsaKey->label, rsaKey->labelLen);
  1524. }
  1525. else {
  1526. ret = Pkcs11FindKeyById(publicKey, CKO_PUBLIC_KEY, CKK_RSA,
  1527. session, rsaKey->id, rsaKey->idLen);
  1528. }
  1529. return ret;
  1530. }
  1531. /**
  1532. * Get the RSA public key data from the PKCS#11 object.
  1533. *
  1534. * @param [in] key RSA key to put the data into.
  1535. * @param [in] session Session object.
  1536. * @param [in] pubkey Public key object.
  1537. * @return WC_HW_E when a PKCS#11 library call fails.
  1538. * @return MEMORY_E when a memory allocation fails.
  1539. * @return 0 on success.
  1540. */
  1541. static int Pkcs11GetRsaPublicKey(RsaKey* key, Pkcs11Session* session,
  1542. CK_OBJECT_HANDLE pubKey)
  1543. {
  1544. int ret = 0;
  1545. unsigned char* mod = NULL;
  1546. unsigned char* exp = NULL;
  1547. int modSz, expSz;
  1548. CK_ATTRIBUTE tmpl[] = {
  1549. { CKA_MODULUS, NULL_PTR, 0 },
  1550. { CKA_PUBLIC_EXPONENT, NULL_PTR, 0 }
  1551. };
  1552. CK_ULONG tmplCnt = sizeof(tmpl) / sizeof(*tmpl);
  1553. CK_RV rv;
  1554. PKCS11_DUMP_TEMPLATE("Get RSA Public Key Length", tmpl, tmplCnt);
  1555. rv = session->func->C_GetAttributeValue(session->handle, pubKey, tmpl,
  1556. tmplCnt);
  1557. PKCS11_RV("C_GetAttributeValue", rv);
  1558. if (rv != CKR_OK) {
  1559. ret = WC_HW_E;
  1560. }
  1561. PKCS11_DUMP_TEMPLATE("RSA Public Key Length", tmpl, tmplCnt);
  1562. if (ret == 0) {
  1563. modSz = (int)tmpl[0].ulValueLen;
  1564. expSz = (int)tmpl[1].ulValueLen;
  1565. mod = (unsigned char*)XMALLOC(modSz, key->heap,
  1566. DYNAMIC_TYPE_TMP_BUFFER);
  1567. if (mod == NULL)
  1568. ret = MEMORY_E;
  1569. }
  1570. if (ret == 0) {
  1571. exp = (unsigned char*)XMALLOC(expSz, key->heap,
  1572. DYNAMIC_TYPE_TMP_BUFFER);
  1573. if (exp == NULL)
  1574. ret = MEMORY_E;
  1575. }
  1576. if (ret == 0) {
  1577. tmpl[0].pValue = mod;
  1578. tmpl[1].pValue = exp;
  1579. PKCS11_DUMP_TEMPLATE("Get RSA Public Key", tmpl, tmplCnt);
  1580. rv = session->func->C_GetAttributeValue(session->handle, pubKey,
  1581. tmpl, tmplCnt);
  1582. PKCS11_RV("C_GetAttributeValue", rv);
  1583. if (rv != CKR_OK) {
  1584. ret = WC_HW_E;
  1585. }
  1586. PKCS11_DUMP_TEMPLATE("RSA Public Key", tmpl, tmplCnt);
  1587. }
  1588. if (ret == 0)
  1589. ret = wc_RsaPublicKeyDecodeRaw(mod, modSz, exp, expSz, key);
  1590. if (exp != NULL)
  1591. XFREE(exp, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  1592. if (mod != NULL)
  1593. XFREE(mod, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  1594. return ret;
  1595. }
  1596. /**
  1597. * Get the RSA modulus size in bytes from the PKCS#11 object.
  1598. *
  1599. * @param [in] session Session object.
  1600. * @param [in] pubkey Public key object.
  1601. * @param [out] modSize Size of the modulus in bytes.
  1602. * @return WC_HW_E when a PKCS#11 library call fails.
  1603. * @return MEMORY_E when a memory allocation fails.
  1604. * @return 0 on success.
  1605. */
  1606. static int Pkcs11GetRsaModulusSize(Pkcs11Session* session,
  1607. CK_OBJECT_HANDLE pubKey, int* modSize)
  1608. {
  1609. int ret = 0;
  1610. CK_ATTRIBUTE tmpl[] = {
  1611. { CKA_MODULUS, NULL_PTR, 0 }
  1612. };
  1613. CK_ULONG tmplCnt = sizeof(tmpl) / sizeof(*tmpl);
  1614. CK_RV rv;
  1615. PKCS11_DUMP_TEMPLATE("Get RSA Modulus Length", tmpl, tmplCnt);
  1616. rv = session->func->C_GetAttributeValue(session->handle, pubKey, tmpl,
  1617. tmplCnt);
  1618. PKCS11_RV("C_GetAttributeValue", rv);
  1619. if (rv != CKR_OK) {
  1620. ret = WC_HW_E;
  1621. }
  1622. PKCS11_DUMP_TEMPLATE("RSA Modulus Length", tmpl, tmplCnt);
  1623. if (ret == 0) {
  1624. *modSize = (int)tmpl[0].ulValueLen;
  1625. }
  1626. return ret;
  1627. }
  1628. /**
  1629. * Make a handle to a private RSA key.
  1630. *
  1631. * @param [in] session Session object.
  1632. * @param [in] rsaKey RSA key with modulus to search on.
  1633. * @param [in] sessionKey Whether to create a session key.
  1634. * @param [out] publicKey Handle to private key object.
  1635. */
  1636. static int Pkcs11RsaPrivateKey(Pkcs11Session* session, RsaKey* rsaKey,
  1637. int sessionKey, CK_OBJECT_HANDLE* privateKey)
  1638. {
  1639. int ret;
  1640. if (sessionKey) {
  1641. ret = Pkcs11CreateRsaPrivateKey(privateKey, session, rsaKey, 0);
  1642. }
  1643. else if (rsaKey->labelLen > 0) {
  1644. ret = Pkcs11FindKeyByLabel(privateKey, CKO_PRIVATE_KEY, CKK_RSA,
  1645. session, rsaKey->label, rsaKey->labelLen);
  1646. }
  1647. else if (rsaKey->idLen > 0) {
  1648. ret = Pkcs11FindKeyById(privateKey, CKO_PRIVATE_KEY, CKK_RSA, session,
  1649. rsaKey->id, rsaKey->idLen);
  1650. }
  1651. else {
  1652. ret = Pkcs11FindRsaKey(privateKey, CKO_PRIVATE_KEY, session, rsaKey);
  1653. }
  1654. if ((ret == 0) && (!sessionKey)) {
  1655. ret = Pkcs11GetRsaPublicKey(rsaKey, session, *privateKey);
  1656. }
  1657. return ret;
  1658. }
  1659. /**
  1660. * Exponentiate the input with the public part of the RSA key.
  1661. * Used in public encrypt and decrypt.
  1662. *
  1663. * @param [in] session Session object.
  1664. * @param [in] info Cryptographic operation data.
  1665. * @return WC_HW_E when a PKCS#11 library call fails.
  1666. * 0 on success.
  1667. */
  1668. static int Pkcs11RsaEncrypt(Pkcs11Session* session, wc_CryptoInfo* info,
  1669. CK_OBJECT_HANDLE key)
  1670. {
  1671. int ret = 0;
  1672. CK_RV rv;
  1673. CK_MECHANISM mech;
  1674. CK_ULONG outLen;
  1675. WOLFSSL_MSG("PKCS#11: RSA Public Key Operation");
  1676. if (info->pk.rsa.outLen == NULL) {
  1677. ret = BAD_FUNC_ARG;
  1678. }
  1679. if (ret == 0) {
  1680. /* Raw RSA encrypt/decrypt operation. */
  1681. mech.mechanism = CKM_RSA_X_509;
  1682. mech.ulParameterLen = 0;
  1683. mech.pParameter = NULL;
  1684. rv = session->func->C_EncryptInit(session->handle, &mech, key);
  1685. PKCS11_RV("C_EncryptInit", rv);
  1686. if (rv != CKR_OK) {
  1687. ret = WC_HW_E;
  1688. }
  1689. }
  1690. if (ret == 0) {
  1691. outLen = (CK_ULONG)*info->pk.rsa.outLen;
  1692. rv = session->func->C_Encrypt(session->handle,
  1693. (CK_BYTE_PTR)info->pk.rsa.in, info->pk.rsa.inLen,
  1694. info->pk.rsa.out, &outLen);
  1695. PKCS11_RV("C_Encrypt", rv);
  1696. if (rv != CKR_OK) {
  1697. ret = WC_HW_E;
  1698. }
  1699. }
  1700. if (ret == 0) {
  1701. *info->pk.rsa.outLen = (word32)outLen;
  1702. }
  1703. return ret;
  1704. }
  1705. /**
  1706. * Exponentiate the input with the private part of the RSA key.
  1707. * Used in private encrypt and decrypt.
  1708. *
  1709. * @param [in] session Session object.
  1710. * @param [in] info Cryptographic operation data.
  1711. * @param [in] func Function to perform - decrypt or sign.
  1712. * @return WC_HW_E when a PKCS#11 library call fails.
  1713. * @return 0 on success.
  1714. */
  1715. static int Pkcs11RsaDecrypt(Pkcs11Session* session, wc_CryptoInfo* info,
  1716. CK_OBJECT_HANDLE key)
  1717. {
  1718. int ret = 0;
  1719. CK_RV rv;
  1720. CK_MECHANISM mech;
  1721. CK_ULONG outLen;
  1722. WOLFSSL_MSG("PKCS#11: RSA Private Key Operation");
  1723. if (info->pk.rsa.outLen == NULL) {
  1724. ret = BAD_FUNC_ARG;
  1725. }
  1726. if (ret == 0) {
  1727. /* Raw RSA encrypt/decrypt operation. */
  1728. mech.mechanism = CKM_RSA_X_509;
  1729. mech.ulParameterLen = 0;
  1730. mech.pParameter = NULL;
  1731. rv = session->func->C_DecryptInit(session->handle, &mech, key);
  1732. PKCS11_RV("C_DecryptInit", rv);
  1733. if (rv != CKR_OK) {
  1734. ret = WC_HW_E;
  1735. }
  1736. }
  1737. if (ret == 0) {
  1738. PKCS11_VAL("C_Decrypt inLen", info->pk.rsa.inLen);
  1739. PKCS11_VAL("C_Decrypt outLen", *info->pk.rsa.outLen);
  1740. outLen = (CK_ULONG)*info->pk.rsa.outLen;
  1741. rv = session->func->C_Decrypt(session->handle,
  1742. (CK_BYTE_PTR)info->pk.rsa.in, info->pk.rsa.inLen,
  1743. info->pk.rsa.out, &outLen);
  1744. PKCS11_RV("C_Decrypt", rv);
  1745. if (rv != CKR_OK) {
  1746. ret = WC_HW_E;
  1747. }
  1748. }
  1749. if (ret == 0) {
  1750. *info->pk.rsa.outLen = (word32)outLen;
  1751. }
  1752. return ret;
  1753. }
  1754. /**
  1755. * Exponentiate the input with the private part of the RSA key.
  1756. * Used in private encrypt and decrypt.
  1757. *
  1758. * @param [in] session Session object.
  1759. * @param [in] info Cryptographic operation data.
  1760. * @param [in] func Function to perform - decrypt or sign.
  1761. * @return WC_HW_E when a PKCS#11 library call fails.
  1762. * @return 0 on success.
  1763. */
  1764. static int Pkcs11RsaSign(Pkcs11Session* session, wc_CryptoInfo* info,
  1765. CK_OBJECT_HANDLE key)
  1766. {
  1767. int ret = 0;
  1768. CK_RV rv;
  1769. CK_MECHANISM mech;
  1770. CK_ULONG outLen;
  1771. WOLFSSL_MSG("PKCS#11: RSA Private Key Operation");
  1772. if (info->pk.rsa.outLen == NULL) {
  1773. ret = BAD_FUNC_ARG;
  1774. }
  1775. if (ret == 0) {
  1776. /* Raw RSA encrypt/decrypt operation. */
  1777. mech.mechanism = CKM_RSA_X_509;
  1778. mech.ulParameterLen = 0;
  1779. mech.pParameter = NULL;
  1780. rv = session->func->C_SignInit(session->handle, &mech, key);
  1781. PKCS11_RV("C_SignInit", rv);
  1782. if (rv != CKR_OK) {
  1783. ret = WC_HW_E;
  1784. }
  1785. }
  1786. if (ret == 0) {
  1787. PKCS11_VAL("C_Sign inLen", info->pk.rsa.inLen);
  1788. PKCS11_VAL("C_Sign outLen", *info->pk.rsa.outLen);
  1789. outLen = (CK_ULONG)*info->pk.rsa.outLen;
  1790. rv = session->func->C_Sign(session->handle,
  1791. (CK_BYTE_PTR)info->pk.rsa.in, info->pk.rsa.inLen,
  1792. info->pk.rsa.out, &outLen);
  1793. PKCS11_RV("C_Sign", rv);
  1794. if (rv != CKR_OK) {
  1795. ret = WC_HW_E;
  1796. }
  1797. }
  1798. if (ret == 0)
  1799. *info->pk.rsa.outLen = (word32)outLen;
  1800. return ret;
  1801. }
  1802. /**
  1803. * Perform an RSA operation.
  1804. *
  1805. * @param [in] session Session object.
  1806. * @param [in] info Cryptographic operation data.
  1807. * @return WC_HW_E when a PKCS#11 library call fails.
  1808. * @return 0 on success.
  1809. */
  1810. static int Pkcs11Rsa(Pkcs11Session* session, wc_CryptoInfo* info)
  1811. {
  1812. int ret = 0;
  1813. CK_RV rv;
  1814. CK_MECHANISM_INFO mechInfo;
  1815. int sessionKey = 0;
  1816. CK_OBJECT_HANDLE key;
  1817. RsaKey* rsaKey = info->pk.rsa.key;
  1818. int type = info->pk.rsa.type;
  1819. /* Check operation is supported. */
  1820. rv = session->func->C_GetMechanismInfo(session->slotId, CKM_RSA_X_509,
  1821. &mechInfo);
  1822. PKCS11_RV("C_GetMechanismInfo", rv);
  1823. if (rv != CKR_OK) {
  1824. ret = NOT_COMPILED_IN;
  1825. }
  1826. if (ret == 0) {
  1827. if ((type == RSA_PUBLIC_ENCRYPT) || (type == RSA_PUBLIC_DECRYPT)) {
  1828. sessionKey = !mp_iszero(&rsaKey->e);
  1829. /* Make a handle to a public key. */
  1830. ret = Pkcs11RsaPublicKey(session, rsaKey, sessionKey, &key);
  1831. }
  1832. else {
  1833. sessionKey = !mp_iszero(&rsaKey->d);
  1834. /* Make a handle to a private key. */
  1835. ret = Pkcs11RsaPrivateKey(session, rsaKey, sessionKey, &key);
  1836. }
  1837. if (type == RSA_PUBLIC_ENCRYPT) {
  1838. WOLFSSL_MSG("PKCS#11: Public Encrypt");
  1839. if ((mechInfo.flags & CKF_ENCRYPT) != 0) {
  1840. ret = Pkcs11RsaEncrypt(session, info, key);
  1841. }
  1842. else {
  1843. ret = NOT_COMPILED_IN;
  1844. }
  1845. }
  1846. else if (type == RSA_PUBLIC_DECRYPT) {
  1847. WOLFSSL_MSG("PKCS#11: Public Decrypt");
  1848. if ((mechInfo.flags & CKF_DECRYPT) != 0) {
  1849. ret = Pkcs11RsaEncrypt(session, info, key);
  1850. }
  1851. else {
  1852. ret = NOT_COMPILED_IN;
  1853. }
  1854. }
  1855. else if (type == RSA_PRIVATE_DECRYPT) {
  1856. WOLFSSL_MSG("PKCS#11: Private Decrypt");
  1857. if ((mechInfo.flags & CKF_DECRYPT) != 0) {
  1858. ret = Pkcs11RsaDecrypt(session, info, key);
  1859. }
  1860. else {
  1861. ret = Pkcs11RsaSign(session, info, key);
  1862. }
  1863. }
  1864. else if (type == RSA_PRIVATE_ENCRYPT) {
  1865. WOLFSSL_MSG("PKCS#11: Private Encrypt");
  1866. if ((mechInfo.flags & CKF_SIGN) != 0) {
  1867. ret = Pkcs11RsaSign(session, info, key);
  1868. }
  1869. else {
  1870. ret = Pkcs11RsaDecrypt(session, info, key);
  1871. }
  1872. }
  1873. }
  1874. if (sessionKey) {
  1875. session->func->C_DestroyObject(session->handle, key);
  1876. }
  1877. return ret;
  1878. }
  1879. #ifdef WOLFSSL_KEY_GEN
  1880. /**
  1881. * Perform an RSA key generation operation.
  1882. * The private key data stays on the device.
  1883. *
  1884. * @param [in] session Session object.
  1885. * @param [in] info Cryptographic operation data.
  1886. * @return WC_HW_E when a PKCS#11 library call fails.
  1887. * @return 0 on success.
  1888. */
  1889. static int Pkcs11RsaKeyGen(Pkcs11Session* session, wc_CryptoInfo* info)
  1890. {
  1891. int ret = 0;
  1892. RsaKey* key = info->pk.rsakg.key;
  1893. CK_RV rv;
  1894. CK_ULONG bits = info->pk.rsakg.size;
  1895. CK_OBJECT_HANDLE pubKey = NULL_PTR, privKey = NULL_PTR;
  1896. CK_MECHANISM mech;
  1897. static CK_BYTE pub_exp[] = { 0x01, 0x00, 0x01, 0x00 };
  1898. CK_ATTRIBUTE pubKeyTmpl[] = {
  1899. { CKA_MODULUS_BITS, &bits, sizeof(bits) },
  1900. { CKA_ENCRYPT, &ckTrue, sizeof(ckTrue) },
  1901. { CKA_VERIFY, &ckTrue, sizeof(ckTrue) },
  1902. { CKA_PUBLIC_EXPONENT, &pub_exp, sizeof(pub_exp) }
  1903. };
  1904. CK_ULONG pubTmplCnt = sizeof(pubKeyTmpl)/sizeof(*pubKeyTmpl);
  1905. /* Empty entries for optional label/ID. */
  1906. CK_ATTRIBUTE privKeyTmpl[] = {
  1907. { CKA_DECRYPT, &ckTrue, sizeof(ckTrue) },
  1908. { CKA_SIGN, &ckTrue, sizeof(ckTrue) },
  1909. { 0, NULL, 0 },
  1910. { 0, NULL, 0 }
  1911. };
  1912. /* 2 mandatory entries + 2 optional. */
  1913. int privTmplCnt = 2;
  1914. int i;
  1915. ret = Pkcs11MechAvail(session, CKM_RSA_PKCS_KEY_PAIR_GEN);
  1916. if (ret == 0) {
  1917. WOLFSSL_MSG("PKCS#11: RSA Key Generation Operation");
  1918. /* Most commonly used public exponent value (array initialized). */
  1919. if (info->pk.rsakg.e != WC_RSA_EXPONENT) {
  1920. for (i = 0; i < (int)sizeof(pub_exp); i++)
  1921. pub_exp[i] = (info->pk.rsakg.e >> (8 * i)) & 0xff;
  1922. }
  1923. for (i = (int)sizeof(pub_exp) - 1; pub_exp[i] == 0; i--) {
  1924. }
  1925. pubKeyTmpl[3].ulValueLen = i + 1;
  1926. if (key->labelLen != 0) {
  1927. privKeyTmpl[privTmplCnt].type = CKA_LABEL;
  1928. privKeyTmpl[privTmplCnt].pValue = key->label;
  1929. privKeyTmpl[privTmplCnt].ulValueLen = key->labelLen;
  1930. privTmplCnt++;
  1931. }
  1932. if (key->idLen != 0) {
  1933. privKeyTmpl[privTmplCnt].type = CKA_ID;
  1934. privKeyTmpl[privTmplCnt].pValue = key->id;
  1935. privKeyTmpl[privTmplCnt].ulValueLen = key->idLen;
  1936. privTmplCnt++;
  1937. }
  1938. mech.mechanism = CKM_RSA_PKCS_KEY_PAIR_GEN;
  1939. mech.ulParameterLen = 0;
  1940. mech.pParameter = NULL;
  1941. PKCS11_DUMP_TEMPLATE("Public Key", pubKeyTmpl, pubTmplCnt);
  1942. PKCS11_DUMP_TEMPLATE("Private Key", privKeyTmpl, privTmplCnt);
  1943. rv = session->func->C_GenerateKeyPair(session->handle, &mech,
  1944. pubKeyTmpl, pubTmplCnt,
  1945. privKeyTmpl, privTmplCnt,
  1946. &pubKey, &privKey);
  1947. PKCS11_RV("C_GenerateKeyPair", rv);
  1948. if (rv != CKR_OK) {
  1949. ret = -1;
  1950. }
  1951. }
  1952. if (ret == 0)
  1953. ret = Pkcs11GetRsaPublicKey(key, session, pubKey);
  1954. if (pubKey != NULL_PTR)
  1955. ret = (int)session->func->C_DestroyObject(session->handle, pubKey);
  1956. if (ret != 0 && privKey != NULL_PTR)
  1957. ret = (int)session->func->C_DestroyObject(session->handle, privKey);
  1958. return ret;
  1959. }
  1960. #endif /* WOLFSSL_KEY_GEN */
  1961. #endif /* !NO_RSA */
  1962. #ifdef HAVE_ECC
  1963. /**
  1964. * Find the PKCS#11 object containing the ECC public or private key data.
  1965. * Search for public key by public point.
  1966. *
  1967. * @param [out] key Handle to key object.
  1968. * @param [in] keyClass Public or private key class.
  1969. * @param [in] session Session object.
  1970. * @param [in] eccKey ECC key with parameters.
  1971. * @return WC_HW_E when a PKCS#11 library call fails.
  1972. * @return MEMORY_E when a memory allocation fails.
  1973. * @return 0 on success.
  1974. */
  1975. static int Pkcs11FindEccKey(CK_OBJECT_HANDLE* key, CK_OBJECT_CLASS keyClass,
  1976. Pkcs11Session* session, ecc_key* eccKey,
  1977. int op)
  1978. {
  1979. int ret = 0;
  1980. int i;
  1981. unsigned char* ecPoint = NULL;
  1982. word32 len = 0;
  1983. CK_RV rv;
  1984. CK_ULONG count;
  1985. CK_UTF8CHAR params[MAX_EC_PARAM_LEN];
  1986. CK_ATTRIBUTE keyTemplate[] = {
  1987. { CKA_CLASS, &keyClass, sizeof(keyClass) },
  1988. { CKA_KEY_TYPE, &ecKeyType, sizeof(ecKeyType) },
  1989. { CKA_EC_PARAMS, params, 0 },
  1990. { op, &ckTrue, sizeof(ckTrue) },
  1991. { CKA_EC_POINT, NULL, 0 },
  1992. };
  1993. CK_ULONG attrCnt = 4;
  1994. ret = Pkcs11EccSetParams(eccKey, keyTemplate, 2);
  1995. if (ret == 0 && keyClass == CKO_PUBLIC_KEY) {
  1996. /* ASN1 encoded: OCT + uncompressed point */
  1997. len = 3 + 1 + 2 * eccKey->dp->size;
  1998. ecPoint = (unsigned char*)XMALLOC(len, eccKey->heap, DYNAMIC_TYPE_ECC);
  1999. if (ecPoint == NULL)
  2000. ret = MEMORY_E;
  2001. }
  2002. if (ret == 0 && keyClass == CKO_PUBLIC_KEY) {
  2003. len -= 3;
  2004. i = 0;
  2005. ecPoint[i++] = ASN_OCTET_STRING;
  2006. if (len >= ASN_LONG_LENGTH)
  2007. ecPoint[i++] = (ASN_LONG_LENGTH | 1);
  2008. ecPoint[i++] = len;
  2009. if (eccKey->type == 0)
  2010. eccKey->type = ECC_PUBLICKEY;
  2011. PRIVATE_KEY_UNLOCK();
  2012. ret = wc_ecc_export_x963(eccKey, ecPoint + i, &len);
  2013. PRIVATE_KEY_LOCK();
  2014. }
  2015. if (ret == 0 && keyClass == CKO_PUBLIC_KEY) {
  2016. keyTemplate[attrCnt].pValue = ecPoint;
  2017. keyTemplate[attrCnt].ulValueLen = len + i;
  2018. attrCnt++;
  2019. }
  2020. if (ret == 0) {
  2021. PKCS11_DUMP_TEMPLATE("Find Ec Key", keyTemplate, attrCnt);
  2022. rv = session->func->C_FindObjectsInit(session->handle, keyTemplate,
  2023. attrCnt);
  2024. PKCS11_RV("C_FindObjectsInit", rv);
  2025. if (rv != CKR_OK) {
  2026. ret = WC_HW_E;
  2027. }
  2028. }
  2029. if (ret == 0) {
  2030. rv = session->func->C_FindObjects(session->handle, key, 1, &count);
  2031. PKCS11_RV("C_FindObjects", rv);
  2032. PKCS11_VAL("C_FindObjects Count", count);
  2033. if (rv != CKR_OK) {
  2034. ret = WC_HW_E;
  2035. }
  2036. rv = session->func->C_FindObjectsFinal(session->handle);
  2037. PKCS11_RV("C_FindObjectsFinal", rv);
  2038. if (rv != CKR_OK) {
  2039. ret = WC_HW_E;
  2040. }
  2041. }
  2042. if (ecPoint != NULL)
  2043. XFREE(ecPoint, eccKey->heap, DYNAMIC_TYPE_ECC);
  2044. return ret;
  2045. }
  2046. /**
  2047. * Gets the public key data from the PKCS#11 object and puts into the ECC key.
  2048. *
  2049. * @param [in] key ECC public key.
  2050. * @param [in] session Session object.
  2051. * @param [in] pubKey ECC public key PKCS#11 object.
  2052. * @return WC_HW_E when a PKCS#11 library call fails.
  2053. * @return MEMORY_E when a memory allocation fails.
  2054. * @return 0 on success.
  2055. */
  2056. static int Pkcs11GetEccPublicKey(ecc_key* key, Pkcs11Session* session,
  2057. CK_OBJECT_HANDLE pubKey)
  2058. {
  2059. int ret = 0;
  2060. word32 i = 0;
  2061. int curveIdx;
  2062. unsigned char* point = NULL;
  2063. int pointSz = 0;
  2064. byte tag;
  2065. CK_RV rv;
  2066. CK_ATTRIBUTE tmpl[] = {
  2067. { CKA_EC_POINT, NULL_PTR, 0 },
  2068. };
  2069. CK_ULONG tmplCnt = sizeof(tmpl) / sizeof(*tmpl);
  2070. rv = session->func->C_GetAttributeValue(session->handle, pubKey, tmpl,
  2071. tmplCnt);
  2072. PKCS11_RV("C_GetAttributeValue", rv);
  2073. if (rv != CKR_OK) {
  2074. ret = WC_HW_E;
  2075. }
  2076. if (ret == 0) {
  2077. pointSz = (int)tmpl[0].ulValueLen;
  2078. point = (unsigned char*)XMALLOC(pointSz, key->heap, DYNAMIC_TYPE_ECC);
  2079. if (point == NULL)
  2080. ret = MEMORY_E;
  2081. }
  2082. if (ret == 0) {
  2083. tmpl[0].pValue = point;
  2084. PKCS11_DUMP_TEMPLATE("Get Ec Public Key", tmpl, tmplCnt);
  2085. rv = session->func->C_GetAttributeValue(session->handle, pubKey,
  2086. tmpl, tmplCnt);
  2087. PKCS11_RV("C_GetAttributeValue", rv);
  2088. if (rv != CKR_OK) {
  2089. ret = WC_HW_E;
  2090. }
  2091. PKCS11_DUMP_TEMPLATE("Ec Public Key", tmpl, tmplCnt);
  2092. }
  2093. /* Make sure the data is big enough for ASN.1: OCT + uncompressed point */
  2094. if (ret == 0 && pointSz < key->dp->size * 2 + 1 + 2)
  2095. ret = ASN_PARSE_E;
  2096. /* Step over the OCTET_STRING wrapper. */
  2097. if (ret == 0 && GetASNTag(point, &i, &tag, pointSz) != 0)
  2098. ret = ASN_PARSE_E;
  2099. if (ret == 0 && tag != ASN_OCTET_STRING)
  2100. ret = ASN_PARSE_E;
  2101. if (ret == 0 && point[i] >= ASN_LONG_LENGTH) {
  2102. if (point[i++] != (ASN_LONG_LENGTH | 1))
  2103. ret = ASN_PARSE_E;
  2104. else if (pointSz < key->dp->size * 2 + 1 + 3)
  2105. ret = ASN_PARSE_E;
  2106. }
  2107. if (ret == 0 && point[i++] != key->dp->size * 2 + 1)
  2108. ret = ASN_PARSE_E;
  2109. if (ret == 0) {
  2110. curveIdx = wc_ecc_get_curve_idx(key->dp->id);
  2111. ret = wc_ecc_import_point_der(point + i, pointSz - i, curveIdx,
  2112. &key->pubkey);
  2113. }
  2114. /* make sure the ecc_key type has been set */
  2115. if (ret == 0 && key->type == 0) {
  2116. key->type = ECC_PUBLICKEY;
  2117. }
  2118. if (point != NULL)
  2119. XFREE(point, key->heap, DYNAMIC_TYPE_ECC);
  2120. return ret;
  2121. }
  2122. #ifndef NO_PKCS11_EC_KEYGEN
  2123. /**
  2124. * Perform an ECC key generation operation.
  2125. * The private key data stays on the device.
  2126. *
  2127. * @param [in] session Session object.
  2128. * @param [in] info Cryptographic operation data.
  2129. * @return WC_HW_E when a PKCS#11 library call fails.
  2130. * @return 0 on success.
  2131. */
  2132. static int Pkcs11EcKeyGen(Pkcs11Session* session, wc_CryptoInfo* info)
  2133. {
  2134. int ret = 0;
  2135. ecc_key* key = info->pk.eckg.key;
  2136. CK_RV rv;
  2137. CK_OBJECT_HANDLE pubKey = NULL_PTR, privKey = NULL_PTR;
  2138. CK_MECHANISM mech;
  2139. CK_UTF8CHAR params[MAX_EC_PARAM_LEN];
  2140. CK_ATTRIBUTE pubKeyTmpl[] = {
  2141. { CKA_EC_PARAMS, params, 0 },
  2142. { CKA_VERIFY, &ckTrue, sizeof(ckTrue) },
  2143. { CKA_ENCRYPT, &ckTrue, sizeof(ckTrue) },
  2144. };
  2145. int pubTmplCnt = 1;
  2146. /* Empty entries for optional label/ID. */
  2147. CK_ATTRIBUTE privKeyTmplDerive[] = {
  2148. { CKA_DERIVE, &ckTrue, sizeof(ckTrue) },
  2149. { 0, NULL, 0 },
  2150. { 0, NULL, 0 },
  2151. };
  2152. /* Empty entries for optional label/ID. */
  2153. CK_ATTRIBUTE privKeyTmplEncSign[] = {
  2154. { CKA_SIGN, &ckTrue, sizeof(ckTrue) },
  2155. { CKA_DECRYPT, &ckTrue, sizeof(ckTrue) },
  2156. { 0, NULL, 0 },
  2157. { 0, NULL, 0 },
  2158. };
  2159. CK_ATTRIBUTE* privKeyTmpl = privKeyTmplDerive;
  2160. /* Mandatory entries + 2 optional. */
  2161. int privTmplCnt = 1;
  2162. ret = Pkcs11MechAvail(session, CKM_EC_KEY_PAIR_GEN);
  2163. if (ret == 0) {
  2164. WOLFSSL_MSG("PKCS#11: EC Key Generation Operation");
  2165. ret = Pkcs11EccSetParams(key, pubKeyTmpl, 0);
  2166. }
  2167. if (ret == 0) {
  2168. /* Default is to use for derivation. */
  2169. if ((key->flags & WC_ECC_FLAG_DEC_SIGN) == WC_ECC_FLAG_DEC_SIGN) {
  2170. privKeyTmpl = privKeyTmplEncSign;
  2171. privTmplCnt = 2;
  2172. pubTmplCnt = 2;
  2173. }
  2174. if (key->labelLen != 0) {
  2175. privKeyTmpl[privTmplCnt].type = CKA_LABEL;
  2176. privKeyTmpl[privTmplCnt].pValue = key->label;
  2177. privKeyTmpl[privTmplCnt].ulValueLen = key->labelLen;
  2178. privTmplCnt++;
  2179. }
  2180. if (key->idLen != 0) {
  2181. privKeyTmpl[privTmplCnt].type = CKA_ID;
  2182. privKeyTmpl[privTmplCnt].pValue = key->id;
  2183. privKeyTmpl[privTmplCnt].ulValueLen = key->idLen;
  2184. privTmplCnt++;
  2185. }
  2186. mech.mechanism = CKM_EC_KEY_PAIR_GEN;
  2187. mech.ulParameterLen = 0;
  2188. mech.pParameter = NULL;
  2189. PKCS11_DUMP_TEMPLATE("Ec Private", privKeyTmpl, privTmplCnt);
  2190. PKCS11_DUMP_TEMPLATE("Ec Public", pubKeyTmpl, pubTmplCnt);
  2191. rv = session->func->C_GenerateKeyPair(session->handle, &mech,
  2192. pubKeyTmpl, pubTmplCnt,
  2193. privKeyTmpl, privTmplCnt,
  2194. &pubKey, &privKey);
  2195. PKCS11_RV("C_GenerateKeyPair", rv);
  2196. if (rv != CKR_OK) {
  2197. ret = -1;
  2198. }
  2199. }
  2200. if (ret == 0)
  2201. ret = Pkcs11GetEccPublicKey(key, session, pubKey);
  2202. if (pubKey != NULL_PTR)
  2203. session->func->C_DestroyObject(session->handle, pubKey);
  2204. if (ret != 0 && privKey != NULL_PTR)
  2205. session->func->C_DestroyObject(session->handle, privKey);
  2206. return ret;
  2207. }
  2208. #endif
  2209. #ifndef NO_PKCS11_ECDH
  2210. /**
  2211. * Extracts the secret key data from the PKCS#11 object.
  2212. *
  2213. * @param [in] session Session object.
  2214. * @param [in] secret PKCS#11 object with the secret key data.
  2215. * @param [in] out Buffer to hold secret data.
  2216. * @param [in,out] outLen On in, length of buffer.
  2217. * On out, the length of data in buffer.
  2218. * @return WC_HW_E when a PKCS#11 library call fails.
  2219. * @return 0 on success.
  2220. */
  2221. static int Pkcs11ExtractSecret(Pkcs11Session* session, CK_OBJECT_HANDLE secret,
  2222. byte* out, word32* outLen)
  2223. {
  2224. int ret = 0;
  2225. CK_ATTRIBUTE tmpl[] = {
  2226. {CKA_VALUE, NULL_PTR, 0}
  2227. };
  2228. CK_ULONG tmplCnt = sizeof(tmpl) / sizeof(*tmpl);
  2229. CK_RV rv;
  2230. PKCS11_DUMP_TEMPLATE("Get Secret Length", tmpl, tmplCnt);
  2231. rv = session->func->C_GetAttributeValue(session->handle, secret, tmpl,
  2232. tmplCnt);
  2233. PKCS11_RV("C_GetAttributeValue", rv);
  2234. if (rv != CKR_OK) {
  2235. ret = WC_HW_E;
  2236. }
  2237. PKCS11_DUMP_TEMPLATE("Secret Length", tmpl, tmplCnt);
  2238. if (ret == 0) {
  2239. if (tmpl[0].ulValueLen > *outLen)
  2240. ret = BUFFER_E;
  2241. }
  2242. if (ret == 0) {
  2243. tmpl[0].pValue = out;
  2244. PKCS11_DUMP_TEMPLATE("Get Secret", tmpl, tmplCnt);
  2245. rv = session->func->C_GetAttributeValue(session->handle, secret,
  2246. tmpl, tmplCnt);
  2247. PKCS11_RV("C_GetAttributeValue", rv);
  2248. if (rv != CKR_OK) {
  2249. ret = WC_HW_E;
  2250. }
  2251. PKCS11_DUMP_TEMPLATE("Secret", tmpl, tmplCnt);
  2252. *outLen = (word32)tmpl[0].ulValueLen;
  2253. }
  2254. return ret;
  2255. }
  2256. /**
  2257. * Performs the ECDH secret generation operation.
  2258. *
  2259. * @param [in] session Session object.
  2260. * @param [in] info Cryptographic operation data.
  2261. * @return WC_HW_E when a PKCS#11 library call fails.
  2262. * 0 on success.
  2263. */
  2264. static int Pkcs11ECDH(Pkcs11Session* session, wc_CryptoInfo* info)
  2265. {
  2266. int ret = 0;
  2267. int sessionKey = 0;
  2268. unsigned char* point = NULL;
  2269. word32 pointLen;
  2270. CK_RV rv;
  2271. CK_KEY_TYPE keyType = CKK_GENERIC_SECRET;
  2272. CK_MECHANISM mech;
  2273. CK_ECDH1_DERIVE_PARAMS params;
  2274. CK_OBJECT_HANDLE privateKey = NULL_PTR;
  2275. CK_OBJECT_HANDLE secret = CK_INVALID_HANDLE;
  2276. CK_ULONG secSz;
  2277. CK_ATTRIBUTE tmpl[] = {
  2278. { CKA_CLASS, &secretKeyClass, sizeof(secretKeyClass) },
  2279. { CKA_KEY_TYPE, &keyType, sizeof(keyType) },
  2280. { CKA_PRIVATE, &ckFalse, sizeof(ckFalse) },
  2281. { CKA_SENSITIVE, &ckFalse, sizeof(ckFalse) },
  2282. { CKA_EXTRACTABLE, &ckTrue, sizeof(ckTrue) },
  2283. { CKA_VALUE_LEN, &secSz, sizeof(secSz) }
  2284. };
  2285. CK_ULONG tmplCnt = sizeof(tmpl) / sizeof(*tmpl);
  2286. ret = Pkcs11MechAvail(session, CKM_ECDH1_DERIVE);
  2287. if (ret == 0 && info->pk.ecdh.outlen == NULL) {
  2288. ret = BAD_FUNC_ARG;
  2289. }
  2290. if (ret == 0) {
  2291. WOLFSSL_MSG("PKCS#11: EC Key Derivation Operation");
  2292. if ((sessionKey = !mp_iszero(
  2293. wc_ecc_key_get_priv(info->pk.ecdh.private_key))))
  2294. ret = Pkcs11CreateEccPrivateKey(&privateKey, session,
  2295. info->pk.ecdh.private_key, CKA_DERIVE);
  2296. else if (info->pk.ecdh.private_key->labelLen > 0) {
  2297. ret = Pkcs11FindKeyByLabel(&privateKey, CKO_PRIVATE_KEY, CKK_EC,
  2298. session,
  2299. info->pk.ecdh.private_key->label,
  2300. info->pk.ecdh.private_key->labelLen);
  2301. }
  2302. else if (info->pk.ecdh.private_key->idLen > 0) {
  2303. ret = Pkcs11FindKeyById(&privateKey, CKO_PRIVATE_KEY, CKK_EC,
  2304. session, info->pk.ecdh.private_key->id,
  2305. info->pk.ecdh.private_key->idLen);
  2306. }
  2307. else {
  2308. ret = Pkcs11FindEccKey(&privateKey, CKO_PRIVATE_KEY, session,
  2309. info->pk.ecdh.public_key, CKA_DERIVE);
  2310. }
  2311. }
  2312. if (ret == 0) {
  2313. PRIVATE_KEY_UNLOCK();
  2314. ret = wc_ecc_export_x963(info->pk.ecdh.public_key, NULL, &pointLen);
  2315. PRIVATE_KEY_LOCK();
  2316. if (ret == LENGTH_ONLY_E) {
  2317. point = (unsigned char*)XMALLOC(pointLen,
  2318. info->pk.ecdh.public_key->heap,
  2319. DYNAMIC_TYPE_ECC_BUFFER);
  2320. PRIVATE_KEY_UNLOCK();
  2321. ret = wc_ecc_export_x963(info->pk.ecdh.public_key, point,
  2322. &pointLen);
  2323. PRIVATE_KEY_LOCK();
  2324. }
  2325. }
  2326. if (ret == 0) {
  2327. secSz = *info->pk.ecdh.outlen;
  2328. if (secSz > (CK_ULONG)info->pk.ecdh.private_key->dp->size)
  2329. secSz = info->pk.ecdh.private_key->dp->size;
  2330. params.kdf = CKD_NULL;
  2331. params.pSharedData = NULL;
  2332. params.ulSharedDataLen = 0;
  2333. params.pPublicData = point;
  2334. params.ulPublicDataLen = pointLen;
  2335. mech.mechanism = CKM_ECDH1_DERIVE;
  2336. mech.ulParameterLen = sizeof(params);
  2337. mech.pParameter = &params;
  2338. PKCS11_DUMP_TEMPLATE("ECDH key", tmpl, tmplCnt);
  2339. rv = session->func->C_DeriveKey(session->handle, &mech, privateKey,
  2340. tmpl, tmplCnt, &secret);
  2341. PKCS11_RV("C_DeriveKey", rv);
  2342. if (rv != CKR_OK) {
  2343. ret = WC_HW_E;
  2344. }
  2345. }
  2346. if (ret == 0) {
  2347. ret = Pkcs11ExtractSecret(session, secret, info->pk.ecdh.out,
  2348. info->pk.ecdh.outlen);
  2349. }
  2350. if (sessionKey)
  2351. session->func->C_DestroyObject(session->handle, privateKey);
  2352. if (point != NULL)
  2353. XFREE(point, info->pk.ecdh.public_key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  2354. return ret;
  2355. }
  2356. #endif
  2357. /**
  2358. * Encode, in place, the ECDSA signature.
  2359. * Two fixed width values into ASN.1 DER encoded SEQ { INT, INT }
  2360. *
  2361. * @param [in,out] sig Signature data.
  2362. * @param [in] sz Size of original signature data.
  2363. * @return Length of the ASN.1 DER encoded signature.
  2364. */
  2365. static word32 Pkcs11ECDSASig_Encode(byte* sig, word32 sz)
  2366. {
  2367. word32 rHigh, sHigh, seqLen;
  2368. word32 rStart = 0, sStart = 0;
  2369. word32 sigSz, rSz, rLen, sSz, sLen;
  2370. word32 i;
  2371. /* Find first byte of data in r and s. */
  2372. while (rStart < sz - 1 && sig[rStart] == 0x00)
  2373. rStart++;
  2374. while (sStart < sz - 1 && sig[sz + sStart] == 0x00)
  2375. sStart++;
  2376. /* Check if 0 needs to be prepended to make integer a positive number. */
  2377. rHigh = sig[rStart] >> 7;
  2378. sHigh = sig[sz + sStart] >> 7;
  2379. /* Calculate length of integer to put into ASN.1 encoding. */
  2380. rLen = sz - rStart;
  2381. sLen = sz - sStart;
  2382. /* r and s: INT (2 bytes) + [ 0x00 ] + integer */
  2383. rSz = 2 + rHigh + rLen;
  2384. sSz = 2 + sHigh + sLen;
  2385. /* Calculate the complete ASN.1 DER encoded size. */
  2386. sigSz = rSz + sSz;
  2387. if (sigSz >= ASN_LONG_LENGTH)
  2388. seqLen = 3;
  2389. else
  2390. seqLen = 2;
  2391. /* Move s and then r integers into their final places. */
  2392. XMEMMOVE(sig + seqLen + rSz + (sSz - sLen), sig + sz + sStart, sLen);
  2393. XMEMMOVE(sig + seqLen + (rSz - rLen), sig + rStart, rLen);
  2394. /* Put the ASN.1 DER encoding around data. */
  2395. i = 0;
  2396. sig[i++] = ASN_CONSTRUCTED | ASN_SEQUENCE;
  2397. if (seqLen == 3)
  2398. sig[i++] = ASN_LONG_LENGTH | 0x01;
  2399. sig[i++] = sigSz;
  2400. sig[i++] = ASN_INTEGER;
  2401. sig[i++] = rHigh + (sz - rStart);
  2402. if (rHigh)
  2403. sig[i++] = 0x00;
  2404. i += sz - rStart;
  2405. sig[i++] = ASN_INTEGER;
  2406. sig[i++] = sHigh + (sz - sStart);
  2407. if (sHigh)
  2408. sig[i] = 0x00;
  2409. return seqLen + sigSz;
  2410. }
  2411. /**
  2412. * Decode the ECDSA signature.
  2413. * ASN.1 DER encode SEQ { INT, INT } converted to two fixed with values.
  2414. *
  2415. * @param [in] in ASN.1 DER encoded signature.
  2416. * @param [in] inSz Size of ASN.1 signature.
  2417. * @param [in] sig Output buffer.
  2418. * @param [in] sz Size of output buffer.
  2419. * @return ASN_PARSE_E when the ASN.1 encoding is invalid.
  2420. * @return 0 on success.
  2421. */
  2422. static int Pkcs11ECDSASig_Decode(const byte* in, word32 inSz, byte* sig,
  2423. word32 sz)
  2424. {
  2425. int ret = 0;
  2426. word32 i = 0;
  2427. byte tag;
  2428. int len, seqLen = 2;
  2429. /* Make sure zeros in place when decoding short integers. */
  2430. XMEMSET(sig, 0, sz * 2);
  2431. /* Check min data for: SEQ + INT. */
  2432. if (inSz < 5)
  2433. ret = ASN_PARSE_E;
  2434. /* Check SEQ */
  2435. if (ret == 0 && in[i++] != (ASN_CONSTRUCTED | ASN_SEQUENCE))
  2436. ret = ASN_PARSE_E;
  2437. if (ret == 0 && in[i] >= ASN_LONG_LENGTH) {
  2438. if (in[i] != (ASN_LONG_LENGTH | 0x01))
  2439. ret = ASN_PARSE_E;
  2440. else {
  2441. i++;
  2442. seqLen++;
  2443. }
  2444. }
  2445. if (ret == 0 && in[i++] != inSz - seqLen)
  2446. ret = ASN_PARSE_E;
  2447. /* Check INT */
  2448. if (ret == 0 && GetASNTag(in, &i, &tag, inSz) != 0)
  2449. ret = ASN_PARSE_E;
  2450. if (ret == 0 && tag != ASN_INTEGER)
  2451. ret = ASN_PARSE_E;
  2452. if (ret == 0 && (len = in[i++]) > sz + 1)
  2453. ret = ASN_PARSE_E;
  2454. /* Check there is space for INT data */
  2455. if (ret == 0 && i + len > inSz)
  2456. ret = ASN_PARSE_E;
  2457. if (ret == 0) {
  2458. /* Skip leading zero */
  2459. if (in[i] == 0x00) {
  2460. i++;
  2461. len--;
  2462. }
  2463. /* Copy r into sig. */
  2464. XMEMCPY(sig + sz - len, in + i, len);
  2465. i += len;
  2466. }
  2467. /* Check min data for: INT. */
  2468. if (ret == 0 && i + 2 > inSz)
  2469. ret = ASN_PARSE_E;
  2470. /* Check INT */
  2471. if (ret == 0 && GetASNTag(in, &i, &tag, inSz) != 0)
  2472. ret = ASN_PARSE_E;
  2473. if (ret == 0 && tag != ASN_INTEGER)
  2474. ret = ASN_PARSE_E;
  2475. if (ret == 0 && (len = in[i++]) > sz + 1)
  2476. ret = ASN_PARSE_E;
  2477. /* Check there is space for INT data */
  2478. if (ret == 0 && i + len > inSz)
  2479. ret = ASN_PARSE_E;
  2480. if (ret == 0) {
  2481. /* Skip leading zero */
  2482. if (in[i] == 0x00) {
  2483. i++;
  2484. len--;
  2485. }
  2486. /* Copy s into sig. */
  2487. XMEMCPY(sig + sz + sz - len, in + i, len);
  2488. }
  2489. return ret;
  2490. }
  2491. /**
  2492. * Get the parameters from the private key on the device.
  2493. *
  2494. * @param [in] session Session object.
  2495. * @param [in] privKey PKCS #11 object handle of private key..
  2496. * @param [in] key Ecc key to set parameters against.
  2497. * @return WC_HW_E when a PKCS#11 library call fails.
  2498. * @return 0 on success.
  2499. */
  2500. static int Pkcs11GetEccParams(Pkcs11Session* session, CK_OBJECT_HANDLE privKey,
  2501. ecc_key* key)
  2502. {
  2503. int ret = 0;
  2504. int curveId;
  2505. CK_RV rv;
  2506. byte oid[16];
  2507. CK_ATTRIBUTE template[] = {
  2508. { CKA_EC_PARAMS, (CK_VOID_PTR)oid, sizeof(oid) }
  2509. };
  2510. PKCS11_DUMP_TEMPLATE("Get Ec Params", template, 1);
  2511. rv = session->func->C_GetAttributeValue(session->handle, privKey, template,
  2512. 1);
  2513. PKCS11_RV("C_GetAttributeValue", rv);
  2514. if (rv != CKR_OK) {
  2515. ret = WC_HW_E;
  2516. }
  2517. PKCS11_DUMP_TEMPLATE("Ec Params", template, 1);
  2518. if (ret == 0) {
  2519. /* PKCS #11 wraps the OID in ASN.1 */
  2520. curveId = wc_ecc_get_curve_id_from_oid(oid + 2,
  2521. (word32)template[0].ulValueLen - 2);
  2522. if (curveId == ECC_CURVE_INVALID)
  2523. ret = WC_HW_E;
  2524. }
  2525. if (ret == 0)
  2526. ret = wc_ecc_set_curve(key, 0, curveId);
  2527. return ret;
  2528. }
  2529. /**
  2530. * Performs the ECDSA signing operation.
  2531. *
  2532. * @param session [in] Session object.
  2533. * @param info [in] Cryptographic operation data.
  2534. * @return WC_HW_E when a PKCS#11 library call fails.
  2535. * @return 0 on success.
  2536. */
  2537. static int Pkcs11ECDSA_Sign(Pkcs11Session* session, wc_CryptoInfo* info)
  2538. {
  2539. int ret = 0;
  2540. int sessionKey = 0;
  2541. word32 sz;
  2542. CK_RV rv;
  2543. CK_ULONG outLen;
  2544. CK_MECHANISM mech;
  2545. CK_MECHANISM_INFO mechInfo;
  2546. CK_OBJECT_HANDLE privateKey = NULL_PTR;
  2547. /* Check operation is supported. */
  2548. rv = session->func->C_GetMechanismInfo(session->slotId, CKM_ECDSA,
  2549. &mechInfo);
  2550. PKCS11_RV("C_GetMechanismInfo", rv);
  2551. if (rv != CKR_OK || (mechInfo.flags & CKF_SIGN) == 0)
  2552. ret = NOT_COMPILED_IN;
  2553. if (ret == 0 && info->pk.eccsign.outlen == NULL) {
  2554. ret = BAD_FUNC_ARG;
  2555. }
  2556. if (ret == 0 && info->pk.eccsign.out == NULL) {
  2557. ret = BAD_FUNC_ARG;
  2558. }
  2559. if (ret == 0) {
  2560. WOLFSSL_MSG("PKCS#11: EC Signing Operation");
  2561. if ((sessionKey = !mp_iszero(
  2562. wc_ecc_key_get_priv(info->pk.eccsign.key))))
  2563. ret = Pkcs11CreateEccPrivateKey(&privateKey, session,
  2564. info->pk.eccsign.key, CKA_SIGN);
  2565. else if (info->pk.eccsign.key->labelLen > 0) {
  2566. ret = Pkcs11FindKeyByLabel(&privateKey, CKO_PRIVATE_KEY, CKK_EC,
  2567. session, info->pk.eccsign.key->label,
  2568. info->pk.eccsign.key->labelLen);
  2569. if (ret == 0 && info->pk.eccsign.key->dp == NULL) {
  2570. ret = Pkcs11GetEccParams(session, privateKey,
  2571. info->pk.eccsign.key);
  2572. }
  2573. }
  2574. else if (info->pk.eccsign.key->idLen > 0) {
  2575. ret = Pkcs11FindKeyById(&privateKey, CKO_PRIVATE_KEY, CKK_EC,
  2576. session, info->pk.eccsign.key->id,
  2577. info->pk.eccsign.key->idLen);
  2578. if (ret == 0 && info->pk.eccsign.key->dp == NULL) {
  2579. ret = Pkcs11GetEccParams(session, privateKey,
  2580. info->pk.eccsign.key);
  2581. }
  2582. }
  2583. else {
  2584. ret = Pkcs11FindEccKey(&privateKey, CKO_PRIVATE_KEY, session,
  2585. info->pk.eccsign.key, CKA_SIGN);
  2586. }
  2587. }
  2588. if (ret == 0) {
  2589. sz = info->pk.eccsign.key->dp->size;
  2590. /* Maximum encoded size is two ordinates + 8 bytes of ASN.1. */
  2591. if (*info->pk.eccsign.outlen < (word32)wc_ecc_sig_size_calc(sz))
  2592. ret = BUFFER_E;
  2593. }
  2594. if (ret == 0) {
  2595. mech.mechanism = CKM_ECDSA;
  2596. mech.ulParameterLen = 0;
  2597. mech.pParameter = NULL;
  2598. rv = session->func->C_SignInit(session->handle, &mech, privateKey);
  2599. PKCS11_RV("C_SignInit", rv);
  2600. if (rv != CKR_OK) {
  2601. ret = WC_HW_E;
  2602. }
  2603. }
  2604. if (ret == 0) {
  2605. outLen = *info->pk.eccsign.outlen;
  2606. rv = session->func->C_Sign(session->handle,
  2607. (CK_BYTE_PTR)info->pk.eccsign.in,
  2608. info->pk.eccsign.inlen, info->pk.eccsign.out,
  2609. &outLen);
  2610. PKCS11_RV("C_Sign", rv);
  2611. if (rv != CKR_OK) {
  2612. ret = WC_HW_E;
  2613. }
  2614. }
  2615. if (ret == 0) {
  2616. *info->pk.eccsign.outlen = Pkcs11ECDSASig_Encode(info->pk.eccsign.out,
  2617. sz);
  2618. }
  2619. if (sessionKey)
  2620. session->func->C_DestroyObject(session->handle, privateKey);
  2621. return ret;
  2622. }
  2623. /**
  2624. * Performs the ECDSA verification operation.
  2625. *
  2626. * @param [in] session Session object.
  2627. * @param [in] info Cryptographic operation data.
  2628. * @return WC_HW_E when a PKCS#11 library call fails.
  2629. * @return MEMORY_E when a memory allocation fails.
  2630. * @return 0 on success.
  2631. */
  2632. static int Pkcs11ECDSA_Verify(Pkcs11Session* session, wc_CryptoInfo* info)
  2633. {
  2634. int ret = 0;
  2635. CK_RV rv;
  2636. CK_MECHANISM mech;
  2637. CK_MECHANISM_INFO mechInfo;
  2638. CK_OBJECT_HANDLE publicKey = NULL_PTR;
  2639. unsigned char* sig = NULL;
  2640. word32 sz = info->pk.eccverify.key->dp->size;
  2641. /* Check operation is supported. */
  2642. rv = session->func->C_GetMechanismInfo(session->slotId, CKM_ECDSA,
  2643. &mechInfo);
  2644. PKCS11_RV("C_GetMechanismInfo", rv);
  2645. if (rv != CKR_OK || (mechInfo.flags & CKF_VERIFY) == 0)
  2646. ret = NOT_COMPILED_IN;
  2647. if (ret == 0 && info->pk.eccverify.res == NULL) {
  2648. ret = BAD_FUNC_ARG;
  2649. }
  2650. if (ret == 0) {
  2651. WOLFSSL_MSG("PKCS#11: EC Verification Operation");
  2652. ret = Pkcs11CreateEccPublicKey(&publicKey, session,
  2653. info->pk.eccverify.key, CKA_VERIFY);
  2654. }
  2655. if (ret == 0) {
  2656. sig = (unsigned char *)XMALLOC(sz * 2, info->pk.eccverify.key->heap,
  2657. DYNAMIC_TYPE_TMP_BUFFER);
  2658. if (sig == NULL)
  2659. ret = MEMORY_E;
  2660. }
  2661. if (ret == 0) {
  2662. ret = Pkcs11ECDSASig_Decode(info->pk.eccverify.sig,
  2663. info->pk.eccverify.siglen, sig, sz);
  2664. }
  2665. if (ret == 0) {
  2666. mech.mechanism = CKM_ECDSA;
  2667. mech.ulParameterLen = 0;
  2668. mech.pParameter = NULL;
  2669. rv = session->func->C_VerifyInit(session->handle, &mech, publicKey);
  2670. PKCS11_RV("C_VerifyInit", rv);
  2671. if (rv != CKR_OK) {
  2672. ret = WC_HW_E;
  2673. }
  2674. }
  2675. if (ret == 0) {
  2676. *info->pk.eccverify.res = 0;
  2677. rv = session->func->C_Verify(session->handle,
  2678. (CK_BYTE_PTR)info->pk.eccverify.hash,
  2679. info->pk.eccverify.hashlen,
  2680. (CK_BYTE_PTR)sig, sz * 2);
  2681. PKCS11_RV("C_Verify", rv);
  2682. if (rv == CKR_SIGNATURE_INVALID) {
  2683. }
  2684. else if (rv != CKR_OK)
  2685. ret = WC_HW_E;
  2686. else
  2687. *info->pk.eccverify.res = 1;
  2688. }
  2689. if (publicKey != NULL_PTR)
  2690. session->func->C_DestroyObject(session->handle, publicKey);
  2691. if (sig != NULL)
  2692. XFREE(sig, info->pk.eccverify.key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  2693. return ret;
  2694. }
  2695. #endif
  2696. #ifndef NO_RSA
  2697. /**
  2698. * Check the private RSA key matches the public key.
  2699. *
  2700. * @param [in] priv RSA private key.
  2701. * @param [in] publicKey Encoded RSA public key.
  2702. * @param [in] pubKeySize Length of encoded RSA public key.
  2703. * @return MEMORY_E when a memory allocation fails.
  2704. * @return MP_CMP_E when the public parts are different.
  2705. * @return 0 on success.
  2706. */
  2707. static int wc_Pkcs11CheckPrivKey_Rsa(RsaKey* priv,
  2708. const unsigned char* publicKey, word32 pubKeySize)
  2709. {
  2710. int ret = 0;
  2711. #ifdef WOLFSSL_SMALL_STACK
  2712. RsaKey* pub = NULL;
  2713. #else
  2714. RsaKey pub[1];
  2715. #endif
  2716. word32 keyIdx = 0;
  2717. #ifdef WOLFSSL_SMALL_STACK
  2718. pub = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL, DYNAMIC_TYPE_RSA);
  2719. if (pub == NULL) {
  2720. ret = MEMORY_E;
  2721. }
  2722. #endif
  2723. if ((ret == 0) && (ret = wc_InitRsaKey(pub, NULL)) == 0) {
  2724. if (ret == 0) {
  2725. ret = wc_RsaPublicKeyDecode(publicKey, &keyIdx, pub, pubKeySize);
  2726. }
  2727. if (ret == 0) {
  2728. /* both keys extracted successfully now check n and e
  2729. * values are the same. This is dereferencing RsaKey */
  2730. if (mp_cmp(&(priv->n), &(pub->n)) != MP_EQ ||
  2731. mp_cmp(&(priv->e), &(pub->e)) != MP_EQ) {
  2732. ret = MP_CMP_E;
  2733. }
  2734. else
  2735. ret = 0;
  2736. }
  2737. wc_FreeRsaKey(pub);
  2738. }
  2739. #ifdef WOLFSSL_SMALL_STACK
  2740. if (pub != NULL) {
  2741. XFREE(pub, NULL, DYNAMIC_TYPE_RSA);
  2742. }
  2743. #endif
  2744. return ret;
  2745. }
  2746. /**
  2747. * Checks the RSA private key matches the RSA public key.
  2748. *
  2749. * @param [in] session Session object.
  2750. * @param [in] info Cryptographic operation data.
  2751. * @return WC_HW_E when a PKCS#11 library call fails.
  2752. * @return MEMORY_E when a memory allocation fails.
  2753. * @return MP_CMP_E when the public parts are different.
  2754. * @return 0 on success.
  2755. */
  2756. static int Pkcs11RsaCheckPrivKey(Pkcs11Session* session, wc_CryptoInfo* info)
  2757. {
  2758. int ret = 0;
  2759. CK_OBJECT_HANDLE privateKey;
  2760. RsaKey* priv = info->pk.rsa_check.key;
  2761. if (mp_iszero(&priv->n) || mp_iszero(&priv->e)) {
  2762. /* Get the RSA private key object. */
  2763. if (priv->labelLen > 0) {
  2764. ret = Pkcs11FindKeyByLabel(&privateKey, CKO_PRIVATE_KEY,
  2765. CKK_RSA, session, priv->label,
  2766. priv->labelLen);
  2767. }
  2768. else if (priv->idLen > 0) {
  2769. ret = Pkcs11FindKeyById(&privateKey, CKO_PRIVATE_KEY, CKK_RSA,
  2770. session, priv->id, priv->idLen);
  2771. }
  2772. else {
  2773. ret = Pkcs11FindRsaKey(&privateKey, CKO_PRIVATE_KEY, session, priv);
  2774. }
  2775. if (ret == 0) {
  2776. /* Extract the public key components. */
  2777. ret = Pkcs11GetRsaPublicKey(priv, session, privateKey);
  2778. }
  2779. }
  2780. if (ret == 0) {
  2781. /* Compare the extracted public parts with the public key. */
  2782. ret = wc_Pkcs11CheckPrivKey_Rsa(priv, info->pk.rsa_check.pubKey,
  2783. info->pk.rsa_check.pubKeySz);
  2784. }
  2785. return ret;
  2786. }
  2787. /**
  2788. * Get the size of the RSA key in bytes.
  2789. *
  2790. * @param [in] session Session object.
  2791. * @param [in] info Cryptographic operation data.
  2792. * @return WC_HW_E when a PKCS#11 library call fails.
  2793. * @return NOT_COMPILED_IN when no modulus, label or id.
  2794. * @return 0 on success.
  2795. */
  2796. static int Pkcs11RsaGetSize(Pkcs11Session* session, wc_CryptoInfo* info)
  2797. {
  2798. int ret = 0;
  2799. CK_OBJECT_HANDLE privateKey;
  2800. const RsaKey* priv = info->pk.rsa_get_size.key;
  2801. if (!mp_iszero(&priv->n)) {
  2802. /* Use the key's modulus MP integer to determine size. */
  2803. *info->pk.rsa_get_size.keySize = mp_unsigned_bin_size(&priv->n);
  2804. }
  2805. else {
  2806. /* Get the RSA private key object. */
  2807. if (priv->labelLen > 0) {
  2808. ret = Pkcs11FindKeyByLabel(&privateKey, CKO_PRIVATE_KEY,
  2809. CKK_RSA, session, (char*)priv->label,
  2810. priv->labelLen);
  2811. }
  2812. else if (priv->idLen > 0) {
  2813. ret = Pkcs11FindKeyById(&privateKey, CKO_PRIVATE_KEY, CKK_RSA,
  2814. session, (unsigned char*)priv->id,
  2815. priv->idLen);
  2816. }
  2817. else {
  2818. /* Lookup is by modulus which is not present. */
  2819. ret = NOT_COMPILED_IN;
  2820. }
  2821. if (ret == 0) {
  2822. /* Lookup the modulus size in bytes. */
  2823. ret = Pkcs11GetRsaModulusSize(session, privateKey,
  2824. info->pk.rsa_get_size.keySize);
  2825. }
  2826. }
  2827. return ret;
  2828. }
  2829. #endif
  2830. #ifdef HAVE_ECC
  2831. /**
  2832. * Check the private ECC key matches the public key.
  2833. * Do this by looking up the public key data from the associated public key.
  2834. * The public key object handle is passed in for the private key.
  2835. *
  2836. * @param [in] privateKey Handle to private key object.
  2837. * @param [in] publicKey Encoded EC public key.
  2838. * @param [in] pubKeySize Length of encoded EC public key.
  2839. * @return MEMORY_E when a memory allocation fails.
  2840. * @return MP_CMP_E when the public parts are different.
  2841. * @return 0 on success.
  2842. */
  2843. static int wc_Pkcs11CheckPrivKey_Ecc(ecc_key* priv,
  2844. const unsigned char* publicKey, word32 pubKeySize)
  2845. {
  2846. int ret = 0;
  2847. #ifdef WOLFSSL_SMALL_STACK
  2848. ecc_key* pub = NULL;
  2849. #else
  2850. ecc_key pub[1];
  2851. #endif
  2852. word32 keyIdx = 0;
  2853. #ifdef WOLFSSL_SMALL_STACK
  2854. pub = (ecc_key*)XMALLOC(sizeof(ecc_key), NULL, DYNAMIC_TYPE_ECC);
  2855. if (pub == NULL) {
  2856. ret = MEMORY_E;
  2857. }
  2858. #endif
  2859. if ((ret == 0) && (ret = wc_ecc_init(pub)) == 0) {
  2860. ret = wc_EccPublicKeyDecode(publicKey, &keyIdx, pub, pubKeySize);
  2861. if (ret == 0) {
  2862. /* both keys extracted successfully now check curve and
  2863. * pubkey. */
  2864. if ((pub->idx != priv->idx) || (wc_ecc_cmp_point(&priv->pubkey,
  2865. &pub->pubkey) != MP_EQ)) {
  2866. ret = MP_CMP_E;
  2867. }
  2868. else {
  2869. ret = 0;
  2870. }
  2871. }
  2872. wc_ecc_free(pub);
  2873. }
  2874. #ifdef WOLFSSL_SMALL_STACK
  2875. if (pub != NULL) {
  2876. XFREE(pub, NULL, DYNAMIC_TYPE_ECC);
  2877. }
  2878. #endif
  2879. return ret;
  2880. }
  2881. /**
  2882. * Checks the ECC private key matches the ECC public key.
  2883. *
  2884. * @param [in] session Session object.
  2885. * @param [in] info Cryptographic operation data.
  2886. * @return WC_HW_E when a PKCS#11 library call fails.
  2887. * @return MEMORY_E when a memory allocation fails.
  2888. * @return MEMORY_E when a memory allocation fails.
  2889. * @return MP_CMP_E when the public parts are different.
  2890. * @return 0 on success.
  2891. */
  2892. static int Pkcs11EccCheckPrivKey(Pkcs11Session* session, wc_CryptoInfo* info)
  2893. {
  2894. int ret = 0;
  2895. ecc_key* priv = info->pk.ecc_check.key;
  2896. CK_OBJECT_HANDLE privateKey;
  2897. if (mp_iszero(priv->pubkey.x) || mp_iszero(priv->pubkey.y)) {
  2898. /* Get the public key object as the private key object doesn't have
  2899. * the public point stored in it.
  2900. */
  2901. if (priv->labelLen > 0) {
  2902. ret = Pkcs11FindKeyByLabel(&privateKey, CKO_PUBLIC_KEY, CKK_EC,
  2903. session, priv->label, priv->labelLen);
  2904. }
  2905. else if (priv->idLen > 0) {
  2906. ret = Pkcs11FindKeyById(&privateKey, CKO_PUBLIC_KEY, CKK_EC,
  2907. session, priv->id, priv->idLen);
  2908. }
  2909. else {
  2910. ret = Pkcs11FindEccKey(&privateKey, CKO_PUBLIC_KEY, session, priv,
  2911. CKA_SIGN);
  2912. }
  2913. if (ret == 0 && priv->dp == NULL) {
  2914. /* Extract the group id. */
  2915. ret = Pkcs11GetEccParams(session, privateKey, priv);
  2916. }
  2917. if (ret == 0) {
  2918. /* Extract the public point. */
  2919. ret = Pkcs11GetEccPublicKey(priv, session, privateKey);
  2920. }
  2921. }
  2922. if (ret == 0) {
  2923. /* Compare the extracted public parts with the public key. */
  2924. ret = wc_Pkcs11CheckPrivKey_Ecc(priv, info->pk.ecc_check.pubKey,
  2925. info->pk.ecc_check.pubKeySz);
  2926. }
  2927. return ret;
  2928. }
  2929. #endif
  2930. #if !defined(NO_AES) && defined(HAVE_AESGCM)
  2931. /**
  2932. * Performs the AES-GCM encryption operation.
  2933. *
  2934. * @param [in] session Session object.
  2935. * @param [in] info Cryptographic operation data.
  2936. * @return WC_HW_E when a PKCS#11 library call fails.
  2937. * @return MEMORY_E when a memory allocation fails.
  2938. * @return 0 on success.
  2939. */
  2940. static int Pkcs11AesGcmEncrypt(Pkcs11Session* session, wc_CryptoInfo* info)
  2941. {
  2942. int ret = 0;
  2943. CK_RV rv;
  2944. Aes* aes = info->cipher.aesgcm_enc.aes;
  2945. CK_GCM_PARAMS params;
  2946. CK_MECHANISM_INFO mechInfo;
  2947. CK_OBJECT_HANDLE key = NULL_PTR;
  2948. CK_MECHANISM mech;
  2949. CK_ULONG outLen;
  2950. /* Check operation is supported. */
  2951. rv = session->func->C_GetMechanismInfo(session->slotId, CKM_AES_GCM,
  2952. &mechInfo);
  2953. PKCS11_RV("C_GetMechanismInfo", rv);
  2954. if (rv != CKR_OK || (mechInfo.flags & CKF_ENCRYPT) == 0)
  2955. ret = NOT_COMPILED_IN;
  2956. if (ret == 0) {
  2957. WOLFSSL_MSG("PKCS#11: AES-GCM Encryption Operation");
  2958. /* Create a private key object or find by label or id. */
  2959. if (aes->idLen == 0 && aes->labelLen == 0) {
  2960. ret = Pkcs11CreateSecretKey(&key, session, CKK_AES,
  2961. (unsigned char*)aes->devKey,
  2962. aes->keylen, NULL, 0, NULL, 0,
  2963. CKA_ENCRYPT);
  2964. }
  2965. else if (aes->labelLen != 0) {
  2966. ret = Pkcs11FindKeyByLabel(&key, CKO_SECRET_KEY, CKK_AES, session,
  2967. aes->label, aes->labelLen);
  2968. }
  2969. else {
  2970. ret = Pkcs11FindKeyById(&key, CKO_SECRET_KEY, CKK_AES, session,
  2971. aes->id, aes->idLen);
  2972. }
  2973. }
  2974. if (ret == 0) {
  2975. params.pIv = (CK_BYTE_PTR)info->cipher.aesgcm_enc.iv;
  2976. params.ulIvLen = info->cipher.aesgcm_enc.ivSz;
  2977. params.pAAD = (CK_BYTE_PTR)info->cipher.aesgcm_enc.authIn;
  2978. params.ulAADLen = info->cipher.aesgcm_enc.authInSz;
  2979. params.ulTagBits = info->cipher.aesgcm_enc.authTagSz * 8;
  2980. mech.mechanism = CKM_AES_GCM;
  2981. mech.ulParameterLen = sizeof(params);
  2982. mech.pParameter = &params;
  2983. rv = session->func->C_EncryptInit(session->handle, &mech, key);
  2984. PKCS11_RV("C_EncryptInit", rv);
  2985. if (rv != CKR_OK) {
  2986. ret = WC_HW_E;
  2987. }
  2988. }
  2989. if (ret == 0) {
  2990. outLen = info->cipher.aesgcm_enc.sz;
  2991. rv = session->func->C_EncryptUpdate(session->handle,
  2992. (CK_BYTE_PTR)info->cipher.aesgcm_enc.in,
  2993. info->cipher.aesgcm_enc.sz,
  2994. info->cipher.aesgcm_enc.out,
  2995. &outLen);
  2996. PKCS11_RV("C_EncryptUpdate", rv);
  2997. if (rv != CKR_OK) {
  2998. ret = WC_HW_E;
  2999. }
  3000. }
  3001. if (ret == 0) {
  3002. /* Authentication tag comes out in final block. */
  3003. outLen = info->cipher.aesgcm_enc.authTagSz;
  3004. rv = session->func->C_EncryptFinal(session->handle,
  3005. info->cipher.aesgcm_enc.authTag,
  3006. &outLen);
  3007. PKCS11_RV("C_EncryptFinal", rv);
  3008. if (rv != CKR_OK) {
  3009. ret = WC_HW_E;
  3010. }
  3011. }
  3012. if (aes->idLen == 0 && aes->labelLen == 0 && key != NULL_PTR)
  3013. session->func->C_DestroyObject(session->handle, key);
  3014. return ret;
  3015. }
  3016. /**
  3017. * Performs the AES-GCM decryption operation.
  3018. *
  3019. * @param [in] session Session object.
  3020. * @param [in] info Cryptographic operation data.
  3021. * @return WC_HW_E when a PKCS#11 library call fails.
  3022. * @return MEMORY_E when a memory allocation fails.
  3023. * @return 0 on success.
  3024. */
  3025. static int Pkcs11AesGcmDecrypt(Pkcs11Session* session, wc_CryptoInfo* info)
  3026. {
  3027. int ret = 0;
  3028. CK_RV rv;
  3029. Aes* aes = info->cipher.aesgcm_enc.aes;
  3030. CK_GCM_PARAMS params;
  3031. CK_MECHANISM_INFO mechInfo;
  3032. CK_OBJECT_HANDLE key = NULL_PTR;
  3033. CK_MECHANISM mech;
  3034. CK_ULONG outLen;
  3035. word32 len;
  3036. /* Check operation is supported. */
  3037. rv = session->func->C_GetMechanismInfo(session->slotId, CKM_AES_GCM,
  3038. &mechInfo);
  3039. PKCS11_RV("C_GetMechanismInfo", rv);
  3040. if (rv != CKR_OK || (mechInfo.flags & CKF_DECRYPT) == 0)
  3041. ret = NOT_COMPILED_IN;
  3042. if (ret == 0) {
  3043. WOLFSSL_MSG("PKCS#11: AES-GCM Decryption Operation");
  3044. /* Create a private key object or find by id. */
  3045. if (aes->idLen == 0 && aes->labelLen == 0) {
  3046. ret = Pkcs11CreateSecretKey(&key, session, CKK_AES,
  3047. (unsigned char*)aes->devKey,
  3048. aes->keylen, NULL, 0, NULL, 0,
  3049. CKA_DECRYPT);
  3050. }
  3051. else if (aes->labelLen != 0) {
  3052. ret = Pkcs11FindKeyByLabel(&key, CKO_SECRET_KEY, CKK_AES, session,
  3053. aes->label, aes->labelLen);
  3054. }
  3055. else {
  3056. ret = Pkcs11FindKeyById(&key, CKO_SECRET_KEY, CKK_AES, session,
  3057. aes->id, aes->idLen);
  3058. }
  3059. }
  3060. if (ret == 0) {
  3061. params.pIv = (CK_BYTE_PTR)info->cipher.aesgcm_dec.iv;
  3062. params.ulIvLen = info->cipher.aesgcm_dec.ivSz;
  3063. params.pAAD = (CK_BYTE_PTR)info->cipher.aesgcm_dec.authIn;
  3064. params.ulAADLen = info->cipher.aesgcm_dec.authInSz;
  3065. params.ulTagBits = info->cipher.aesgcm_dec.authTagSz * 8;
  3066. mech.mechanism = CKM_AES_GCM;
  3067. mech.ulParameterLen = sizeof(params);
  3068. mech.pParameter = &params;
  3069. rv = session->func->C_DecryptInit(session->handle, &mech, key);
  3070. PKCS11_RV("C_DecryptInit", rv);
  3071. if (rv != CKR_OK) {
  3072. ret = WC_HW_E;
  3073. }
  3074. }
  3075. if (ret == 0) {
  3076. outLen = len = info->cipher.aesgcm_dec.sz;
  3077. rv = session->func->C_DecryptUpdate(session->handle,
  3078. (CK_BYTE_PTR)info->cipher.aesgcm_dec.in,
  3079. info->cipher.aesgcm_dec.sz,
  3080. info->cipher.aesgcm_dec.out,
  3081. &outLen);
  3082. PKCS11_RV("C_DecryptUpdate", rv);
  3083. if (rv != CKR_OK) {
  3084. ret = WC_HW_E;
  3085. }
  3086. }
  3087. if (ret == 0) {
  3088. /* Put authentication tag in as encrypted data. */
  3089. outLen = len = (len + info->cipher.aesgcm_dec.authTagSz -
  3090. (word32)outLen);
  3091. rv = session->func->C_DecryptUpdate(session->handle,
  3092. (CK_BYTE_PTR)info->cipher.aesgcm_dec.authTag,
  3093. info->cipher.aesgcm_dec.authTagSz,
  3094. info->cipher.aesgcm_dec.out,
  3095. &outLen);
  3096. PKCS11_RV("C_DecryptUpdate", rv);
  3097. if (rv != CKR_OK) {
  3098. ret = WC_HW_E;
  3099. }
  3100. }
  3101. if (ret == 0) {
  3102. outLen = len = (len - (word32)outLen);
  3103. /* Decrypted data comes out now. */
  3104. rv = session->func->C_DecryptFinal(session->handle,
  3105. info->cipher.aesgcm_dec.out,
  3106. &outLen);
  3107. PKCS11_RV("C_DecryptFinal", rv);
  3108. if (rv != CKR_OK) {
  3109. ret = WC_HW_E;
  3110. }
  3111. }
  3112. if (aes->idLen == 0 && aes->labelLen == 0 && key != NULL_PTR)
  3113. session->func->C_DestroyObject(session->handle, key);
  3114. return ret;
  3115. }
  3116. #endif
  3117. #if !defined(NO_AES) && defined(HAVE_AES_CBC)
  3118. /**
  3119. * Performs the AES-CBC encryption operation.
  3120. *
  3121. * @param [in] session Session object.
  3122. * @param [in] info Cryptographic operation data.
  3123. * @return WC_HW_E when a PKCS#11 library call fails.
  3124. * @return MEMORY_E when a memory allocation fails.
  3125. * @return 0 on success.
  3126. */
  3127. static int Pkcs11AesCbcEncrypt(Pkcs11Session* session, wc_CryptoInfo* info)
  3128. {
  3129. int ret = 0;
  3130. CK_RV rv;
  3131. Aes* aes = info->cipher.aescbc.aes;
  3132. CK_MECHANISM_INFO mechInfo;
  3133. CK_OBJECT_HANDLE key = NULL_PTR;
  3134. CK_MECHANISM mech;
  3135. CK_ULONG outLen;
  3136. /* Check operation is supported. */
  3137. rv = session->func->C_GetMechanismInfo(session->slotId, CKM_AES_CBC,
  3138. &mechInfo);
  3139. PKCS11_RV("C_GetMechanismInfo", rv);
  3140. if (rv != CKR_OK || (mechInfo.flags & CKF_ENCRYPT) == 0)
  3141. ret = NOT_COMPILED_IN;
  3142. if (ret == 0) {
  3143. WOLFSSL_MSG("PKCS#11: AES-CBC Encryption Operation");
  3144. /* Create a private key object or find by id. */
  3145. if (aes->idLen == 0 && aes->labelLen == 0) {
  3146. ret = Pkcs11CreateSecretKey(&key, session, CKK_AES,
  3147. (unsigned char*)aes->devKey,
  3148. aes->keylen, NULL, 0, NULL, 0,
  3149. CKA_ENCRYPT);
  3150. }
  3151. else if (aes->labelLen != 0) {
  3152. ret = Pkcs11FindKeyByLabel(&key, CKO_SECRET_KEY, CKK_AES, session,
  3153. aes->label, aes->labelLen);
  3154. }
  3155. else {
  3156. ret = Pkcs11FindKeyById(&key, CKO_SECRET_KEY, CKK_AES, session,
  3157. aes->id, aes->idLen);
  3158. }
  3159. }
  3160. if (ret == 0) {
  3161. mech.mechanism = CKM_AES_CBC;
  3162. mech.ulParameterLen = AES_BLOCK_SIZE;
  3163. mech.pParameter = (CK_BYTE_PTR)info->cipher.aescbc.aes->reg;
  3164. rv = session->func->C_EncryptInit(session->handle, &mech, key);
  3165. PKCS11_RV("C_EncryptInit", rv);
  3166. if (rv != CKR_OK) {
  3167. ret = WC_HW_E;
  3168. }
  3169. }
  3170. if (ret == 0) {
  3171. outLen = info->cipher.aescbc.sz;
  3172. rv = session->func->C_Encrypt(session->handle,
  3173. (CK_BYTE_PTR)info->cipher.aescbc.in,
  3174. info->cipher.aescbc.sz,
  3175. info->cipher.aescbc.out,
  3176. &outLen);
  3177. PKCS11_RV("C_Encrypt", rv);
  3178. if (rv != CKR_OK) {
  3179. ret = WC_HW_E;
  3180. }
  3181. }
  3182. if (aes->idLen == 0 && aes->labelLen == 0 && key != NULL_PTR)
  3183. session->func->C_DestroyObject(session->handle, key);
  3184. return ret;
  3185. }
  3186. /**
  3187. * Performs the AES-CBC decryption operation.
  3188. *
  3189. * @param [in] session Session object.
  3190. * @param [in] info Cryptographic operation data.
  3191. * @return WC_HW_E when a PKCS#11 library call fails.
  3192. * @return MEMORY_E when a memory allocation fails.
  3193. * @return 0 on success.
  3194. */
  3195. static int Pkcs11AesCbcDecrypt(Pkcs11Session* session, wc_CryptoInfo* info)
  3196. {
  3197. int ret = 0;
  3198. CK_RV rv;
  3199. Aes* aes = info->cipher.aescbc.aes;
  3200. CK_MECHANISM_INFO mechInfo;
  3201. CK_OBJECT_HANDLE key = NULL_PTR;
  3202. CK_MECHANISM mech;
  3203. CK_ULONG outLen;
  3204. /* Check operation is supported. */
  3205. rv = session->func->C_GetMechanismInfo(session->slotId, CKM_AES_CBC,
  3206. &mechInfo);
  3207. PKCS11_RV("C_GetMechanismInfo", rv);
  3208. if (rv != CKR_OK || (mechInfo.flags & CKF_DECRYPT) == 0)
  3209. ret = NOT_COMPILED_IN;
  3210. if (ret == 0) {
  3211. WOLFSSL_MSG("PKCS#11: AES-CBC Decryption Operation");
  3212. /* Create a private key object or find by id. */
  3213. if (aes->idLen == 0 && aes->labelLen == 0) {
  3214. ret = Pkcs11CreateSecretKey(&key, session, CKK_AES,
  3215. (unsigned char*)aes->devKey,
  3216. aes->keylen, NULL, 0, NULL, 0,
  3217. CKA_DECRYPT);
  3218. }
  3219. else if (aes->labelLen != 0) {
  3220. ret = Pkcs11FindKeyByLabel(&key, CKO_SECRET_KEY, CKK_AES, session,
  3221. aes->label, aes->labelLen);
  3222. }
  3223. else {
  3224. ret = Pkcs11FindKeyById(&key, CKO_SECRET_KEY, CKK_AES, session,
  3225. aes->id, aes->idLen);
  3226. }
  3227. }
  3228. if (ret == 0) {
  3229. mech.mechanism = CKM_AES_CBC;
  3230. mech.ulParameterLen = AES_BLOCK_SIZE;
  3231. mech.pParameter = (CK_BYTE_PTR)info->cipher.aescbc.aes->reg;
  3232. rv = session->func->C_DecryptInit(session->handle, &mech, key);
  3233. PKCS11_RV("C_DecryptInit", rv);
  3234. if (rv != CKR_OK) {
  3235. ret = WC_HW_E;
  3236. }
  3237. }
  3238. if (ret == 0) {
  3239. outLen = info->cipher.aescbc.sz;
  3240. rv = session->func->C_Decrypt(session->handle,
  3241. (CK_BYTE_PTR)info->cipher.aescbc.in,
  3242. info->cipher.aescbc.sz,
  3243. info->cipher.aescbc.out,
  3244. &outLen);
  3245. PKCS11_RV("C_Decrypt", rv);
  3246. if (rv != CKR_OK) {
  3247. ret = WC_HW_E;
  3248. }
  3249. }
  3250. if (aes->idLen == 0 && aes->labelLen == 0 && key != NULL_PTR)
  3251. session->func->C_DestroyObject(session->handle, key);
  3252. return ret;
  3253. }
  3254. #endif
  3255. #ifndef NO_HMAC
  3256. /**
  3257. * Updates or calculates the HMAC of the data.
  3258. *
  3259. * @param [in] session Session object.
  3260. * @param [in] info Cryptographic operation data.
  3261. * @return WC_HW_E when a PKCS#11 library call fails.
  3262. * @return 0 on success.
  3263. */
  3264. static int Pkcs11Hmac(Pkcs11Session* session, wc_CryptoInfo* info)
  3265. {
  3266. int ret = 0;
  3267. CK_RV rv;
  3268. Hmac* hmac = info->hmac.hmac;
  3269. CK_MECHANISM_INFO mechInfo;
  3270. CK_OBJECT_HANDLE key = NULL_PTR;
  3271. CK_MECHANISM mech;
  3272. CK_ULONG outLen;
  3273. int mechType;
  3274. int keyType;
  3275. if (hmac->innerHashKeyed == WC_HMAC_INNER_HASH_KEYED_SW)
  3276. ret = NOT_COMPILED_IN;
  3277. if (ret == 0)
  3278. ret = Pkcs11HmacTypes(info->hmac.macType, &mechType, &keyType);
  3279. if (ret == 0) {
  3280. /* Check operation is supported. */
  3281. rv = session->func->C_GetMechanismInfo(session->slotId, mechType,
  3282. &mechInfo);
  3283. PKCS11_RV("C_GetMechanismInfo", rv);
  3284. if (rv != CKR_OK || (mechInfo.flags & CKF_SIGN) == 0)
  3285. ret = NOT_COMPILED_IN;
  3286. }
  3287. /* Check whether key been used to initialized. */
  3288. if (ret == 0 && !hmac->innerHashKeyed) {
  3289. WOLFSSL_MSG("PKCS#11: HMAC Init");
  3290. /* Check device supports key length. */
  3291. if (mechInfo.ulMaxKeySize > 0 &&
  3292. (hmac->keyLen < mechInfo.ulMinKeySize ||
  3293. hmac->keyLen > mechInfo.ulMaxKeySize)) {
  3294. WOLFSSL_MSG("PKCS#11: Key Length not supported");
  3295. ret = NOT_COMPILED_IN;
  3296. }
  3297. /* Create a private key object or find by id. */
  3298. if (ret == 0 && hmac->idLen == 0 && hmac->labelLen == 0) {
  3299. ret = Pkcs11CreateSecretKey(&key, session, keyType,
  3300. (unsigned char*)hmac->keyRaw, hmac->keyLen,
  3301. NULL, 0, NULL, 0, CKA_SIGN);
  3302. if (ret == WC_HW_E) {
  3303. ret = Pkcs11CreateSecretKey(&key, session, CKK_GENERIC_SECRET,
  3304. (unsigned char*)hmac->keyRaw, hmac->keyLen,
  3305. NULL, 0, NULL, 0, CKA_SIGN);
  3306. }
  3307. }
  3308. else if (ret == 0 && hmac->labelLen != 0) {
  3309. ret = Pkcs11FindKeyByLabel(&key, CKO_SECRET_KEY, keyType, session,
  3310. hmac->label, hmac->labelLen);
  3311. if (ret == WC_HW_E) {
  3312. ret = Pkcs11FindKeyByLabel(&key, CKO_SECRET_KEY,
  3313. CKK_GENERIC_SECRET, session,
  3314. hmac->label, hmac->labelLen);
  3315. }
  3316. }
  3317. else if (ret == 0) {
  3318. ret = Pkcs11FindKeyById(&key, CKO_SECRET_KEY, keyType, session,
  3319. hmac->id, hmac->idLen);
  3320. if (ret == WC_HW_E) {
  3321. ret = Pkcs11FindKeyById(&key, CKO_SECRET_KEY,
  3322. CKK_GENERIC_SECRET, session, hmac->id,
  3323. hmac->idLen);
  3324. }
  3325. }
  3326. /* Initialize HMAC operation */
  3327. if (ret == 0) {
  3328. mech.mechanism = mechType;
  3329. mech.ulParameterLen = 0;
  3330. mech.pParameter = NULL;
  3331. rv = session->func->C_SignInit(session->handle, &mech, key);
  3332. PKCS11_RV("C_SignInit", rv);
  3333. if (rv != CKR_OK) {
  3334. ret = WC_HW_E;
  3335. }
  3336. }
  3337. /* Don't initialize HMAC again if this succeeded */
  3338. if (ret == 0)
  3339. hmac->innerHashKeyed = WC_HMAC_INNER_HASH_KEYED_DEV;
  3340. }
  3341. /* Update the HMAC if input data passed in. */
  3342. if (ret == 0 && info->hmac.inSz > 0) {
  3343. WOLFSSL_MSG("PKCS#11: HMAC Update");
  3344. rv = session->func->C_SignUpdate(session->handle,
  3345. (CK_BYTE_PTR)info->hmac.in,
  3346. info->hmac.inSz);
  3347. PKCS11_RV("C_SignUpdate", rv);
  3348. /* Some algorithm implementations only support C_Sign. */
  3349. if (rv == CKR_MECHANISM_INVALID) {
  3350. WOLFSSL_MSG("PKCS#11: HMAC Update/Final not supported");
  3351. ret = NOT_COMPILED_IN;
  3352. /* Allow software implementation to set key. */
  3353. hmac->innerHashKeyed = 0;
  3354. }
  3355. else if (rv != CKR_OK)
  3356. ret = WC_HW_E;
  3357. }
  3358. /* Calculate the HMAC result if output buffer specified. */
  3359. if (ret == 0 && info->hmac.digest != NULL) {
  3360. WOLFSSL_MSG("PKCS#11: HMAC Final");
  3361. outLen = WC_MAX_DIGEST_SIZE;
  3362. rv = session->func->C_SignFinal(session->handle,
  3363. (CK_BYTE_PTR)info->hmac.digest,
  3364. &outLen);
  3365. PKCS11_RV("C_SignFinal", rv);
  3366. /* Some algorithm implementations only support C_Sign. */
  3367. if (rv != CKR_OK) {
  3368. ret = WC_HW_E;
  3369. }
  3370. else
  3371. hmac->innerHashKeyed = 0;
  3372. }
  3373. if (hmac->idLen == 0 && hmac->labelLen == 0 && key != NULL_PTR)
  3374. session->func->C_DestroyObject(session->handle, key);
  3375. return ret;
  3376. }
  3377. #endif
  3378. #ifndef WC_NO_RNG
  3379. #ifndef HAVE_HASHDRBG
  3380. /**
  3381. * Performs random number generation.
  3382. *
  3383. * @param [in] session Session object.
  3384. * @param [in] info Cryptographic operation data.
  3385. * @return WC_HW_E when a PKCS#11 library call fails.
  3386. * @return 0 on success.
  3387. */
  3388. static int Pkcs11RandomBlock(Pkcs11Session* session, wc_CryptoInfo* info)
  3389. {
  3390. int ret = 0;
  3391. CK_RV rv;
  3392. WOLFSSL_MSG("PKCS#11: Generate Random for Block");
  3393. rv = session->func->C_GenerateRandom(session->handle, info->rng.out,
  3394. info->rng.sz);
  3395. PKCS11_RV("C_GenerateRandom", rv);
  3396. if (rv != CKR_OK) {
  3397. ret = WC_HW_E;
  3398. }
  3399. return ret;
  3400. }
  3401. #endif
  3402. /**
  3403. * Generates entropy (seed) data.
  3404. *
  3405. * @param [in] session Session object.
  3406. * @param [in] info Cryptographic operation data.
  3407. * @return WC_HW_E when a PKCS#11 library call fails.
  3408. * @return 0 on success.
  3409. */
  3410. static int Pkcs11RandomSeed(Pkcs11Session* session, wc_CryptoInfo* info)
  3411. {
  3412. int ret = 0;
  3413. CK_RV rv;
  3414. WOLFSSL_MSG("PKCS#11: Generate Random for Seed");
  3415. rv = session->func->C_GenerateRandom(session->handle, info->seed.seed,
  3416. info->seed.sz);
  3417. PKCS11_RV("C_GenerateRandom", rv);
  3418. if (rv != CKR_OK) {
  3419. ret = WC_HW_E;
  3420. }
  3421. return ret;
  3422. }
  3423. #endif
  3424. /**
  3425. * Perform a cryptographic operation using PKCS#11 device.
  3426. *
  3427. * @param [in] devId Device identifier.
  3428. * @param [in] info Cryptographic operation data.
  3429. * @param [in] ctx Context data for device - the token object.
  3430. * @return WC_HW_E when a PKCS#11 library call fails.
  3431. * @return 0 on success.
  3432. */
  3433. int wc_Pkcs11_CryptoDevCb(int devId, wc_CryptoInfo* info, void* ctx)
  3434. {
  3435. int ret = 0;
  3436. Pkcs11Token* token = (Pkcs11Token*)ctx;
  3437. Pkcs11Session session;
  3438. int readWrite = 0;
  3439. if (devId <= INVALID_DEVID || info == NULL || ctx == NULL)
  3440. ret = BAD_FUNC_ARG;
  3441. /* Open and close a session around each operation as the operation may not
  3442. * be compiled in.
  3443. */
  3444. if (ret == 0) {
  3445. if (info->algo_type == WC_ALGO_TYPE_PK) {
  3446. #if !defined(NO_RSA) || defined(HAVE_ECC)
  3447. switch (info->pk.type) {
  3448. #ifndef NO_RSA
  3449. case WC_PK_TYPE_RSA:
  3450. ret = Pkcs11OpenSession(token, &session, readWrite);
  3451. if (ret == 0) {
  3452. ret = Pkcs11Rsa(&session, info);
  3453. Pkcs11CloseSession(token, &session);
  3454. }
  3455. break;
  3456. #ifdef WOLFSSL_KEY_GEN
  3457. case WC_PK_TYPE_RSA_KEYGEN:
  3458. ret = Pkcs11OpenSession(token, &session, readWrite);
  3459. if (ret == 0) {
  3460. ret = Pkcs11RsaKeyGen(&session, info);
  3461. Pkcs11CloseSession(token, &session);
  3462. }
  3463. break;
  3464. #endif
  3465. case WC_PK_TYPE_RSA_CHECK_PRIV_KEY:
  3466. ret = Pkcs11OpenSession(token, &session, readWrite);
  3467. if (ret == 0) {
  3468. ret = Pkcs11RsaCheckPrivKey(&session, info);
  3469. Pkcs11CloseSession(token, &session);
  3470. }
  3471. break;
  3472. case WC_PK_TYPE_RSA_GET_SIZE:
  3473. ret = Pkcs11OpenSession(token, &session, readWrite);
  3474. if (ret == 0) {
  3475. ret = Pkcs11RsaGetSize(&session, info);
  3476. Pkcs11CloseSession(token, &session);
  3477. }
  3478. break;
  3479. #endif
  3480. #ifdef HAVE_ECC
  3481. #ifndef NO_PKCS11_EC_KEYGEN
  3482. case WC_PK_TYPE_EC_KEYGEN:
  3483. ret = Pkcs11OpenSession(token, &session, readWrite);
  3484. if (ret == 0) {
  3485. ret = Pkcs11EcKeyGen(&session, info);
  3486. Pkcs11CloseSession(token, &session);
  3487. }
  3488. break;
  3489. #endif
  3490. #ifndef NO_PKCS11_ECDH
  3491. case WC_PK_TYPE_ECDH:
  3492. ret = Pkcs11OpenSession(token, &session, readWrite);
  3493. if (ret == 0) {
  3494. ret = Pkcs11ECDH(&session, info);
  3495. Pkcs11CloseSession(token, &session);
  3496. }
  3497. break;
  3498. #endif
  3499. case WC_PK_TYPE_ECDSA_SIGN:
  3500. ret = Pkcs11OpenSession(token, &session, readWrite);
  3501. if (ret == 0) {
  3502. ret = Pkcs11ECDSA_Sign(&session, info);
  3503. Pkcs11CloseSession(token, &session);
  3504. }
  3505. break;
  3506. case WC_PK_TYPE_ECDSA_VERIFY:
  3507. ret = Pkcs11OpenSession(token, &session, readWrite);
  3508. if (ret == 0) {
  3509. ret = Pkcs11ECDSA_Verify(&session, info);
  3510. Pkcs11CloseSession(token, &session);
  3511. }
  3512. break;
  3513. case WC_PK_TYPE_EC_CHECK_PRIV_KEY:
  3514. ret = Pkcs11OpenSession(token, &session, readWrite);
  3515. if (ret == 0) {
  3516. ret = Pkcs11EccCheckPrivKey(&session, info);
  3517. Pkcs11CloseSession(token, &session);
  3518. }
  3519. break;
  3520. #endif
  3521. default:
  3522. ret = NOT_COMPILED_IN;
  3523. break;
  3524. }
  3525. #else
  3526. ret = NOT_COMPILED_IN;
  3527. #endif /* !NO_RSA || HAVE_ECC */
  3528. }
  3529. else if (info->algo_type == WC_ALGO_TYPE_CIPHER) {
  3530. #ifndef NO_AES
  3531. switch (info->cipher.type) {
  3532. #ifdef HAVE_AESGCM
  3533. case WC_CIPHER_AES_GCM:
  3534. if (info->cipher.enc) {
  3535. ret = Pkcs11OpenSession(token, &session, readWrite);
  3536. if (ret == 0) {
  3537. ret = Pkcs11AesGcmEncrypt(&session, info);
  3538. Pkcs11CloseSession(token, &session);
  3539. }
  3540. }
  3541. else {
  3542. ret = Pkcs11OpenSession(token, &session, readWrite);
  3543. if (ret == 0) {
  3544. ret = Pkcs11AesGcmDecrypt(&session, info);
  3545. Pkcs11CloseSession(token, &session);
  3546. }
  3547. }
  3548. break;
  3549. #endif
  3550. #ifdef HAVE_AES_CBC
  3551. case WC_CIPHER_AES_CBC:
  3552. if (info->cipher.enc) {
  3553. ret = Pkcs11OpenSession(token, &session, readWrite);
  3554. if (ret == 0) {
  3555. ret = Pkcs11AesCbcEncrypt(&session, info);
  3556. Pkcs11CloseSession(token, &session);
  3557. }
  3558. }
  3559. else {
  3560. ret = Pkcs11OpenSession(token, &session, readWrite);
  3561. if (ret == 0) {
  3562. ret = Pkcs11AesCbcDecrypt(&session, info);
  3563. Pkcs11CloseSession(token, &session);
  3564. }
  3565. }
  3566. break;
  3567. #endif
  3568. }
  3569. #else
  3570. ret = NOT_COMPILED_IN;
  3571. #endif
  3572. }
  3573. else if (info->algo_type == WC_ALGO_TYPE_HMAC) {
  3574. #ifndef NO_HMAC
  3575. ret = Pkcs11OpenSession(token, &session, readWrite);
  3576. if (ret == 0) {
  3577. ret = Pkcs11Hmac(&session, info);
  3578. Pkcs11CloseSession(token, &session);
  3579. }
  3580. #else
  3581. ret = NOT_COMPILED_IN;
  3582. #endif
  3583. }
  3584. else if (info->algo_type == WC_ALGO_TYPE_RNG) {
  3585. #if !defined(WC_NO_RNG) && !defined(HAVE_HASHDRBG)
  3586. ret = Pkcs11OpenSession(token, &session, readWrite);
  3587. if (ret == 0) {
  3588. ret = Pkcs11RandomBlock(&session, info);
  3589. Pkcs11CloseSession(token, &session);
  3590. }
  3591. #else
  3592. ret = NOT_COMPILED_IN;
  3593. #endif
  3594. }
  3595. else if (info->algo_type == WC_ALGO_TYPE_SEED) {
  3596. #ifndef WC_NO_RNG
  3597. ret = Pkcs11OpenSession(token, &session, readWrite);
  3598. if (ret == 0) {
  3599. ret = Pkcs11RandomSeed(&session, info);
  3600. Pkcs11CloseSession(token, &session);
  3601. }
  3602. #else
  3603. ret = NOT_COMPILED_IN;
  3604. #endif
  3605. }
  3606. else
  3607. ret = NOT_COMPILED_IN;
  3608. }
  3609. return ret;
  3610. }
  3611. #endif /* HAVE_PKCS11 */