wc_pkcs11.c 135 KB

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