wc_pkcs11.c 129 KB

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