pubkey.c 112 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213
  1. /* pubkey.c - pubkey dispatcher
  2. * Copyright (C) 1998, 1999, 2000, 2002, 2003, 2005,
  3. * 2007, 2008, 2011 Free Software Foundation, Inc.
  4. *
  5. * This file is part of Libgcrypt.
  6. *
  7. * Libgcrypt is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU Lesser general Public License as
  9. * published by the Free Software Foundation; either version 2.1 of
  10. * the License, or (at your option) any later version.
  11. *
  12. * Libgcrypt 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 Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with this program; if not, see <http://www.gnu.org/licenses/>.
  19. */
  20. #include <config.h>
  21. #include <stdio.h>
  22. #include <stdlib.h>
  23. #include <string.h>
  24. #include <errno.h>
  25. #include "g10lib.h"
  26. #include "mpi.h"
  27. #include "cipher.h"
  28. #include "ath.h"
  29. static gcry_err_code_t pubkey_decrypt (int algo, gcry_mpi_t *result,
  30. gcry_mpi_t *data, gcry_mpi_t *skey,
  31. int flags);
  32. static gcry_err_code_t pubkey_sign (int algo, gcry_mpi_t *resarr,
  33. gcry_mpi_t hash, gcry_mpi_t *skey);
  34. static gcry_err_code_t pubkey_verify (int algo, gcry_mpi_t hash,
  35. gcry_mpi_t *data, gcry_mpi_t *pkey,
  36. int (*cmp) (void *, gcry_mpi_t),
  37. void *opaque);
  38. /* A dummy extraspec so that we do not need to tests the extraspec
  39. field from the module specification against NULL and instead
  40. directly test the respective fields of extraspecs. */
  41. static pk_extra_spec_t dummy_extra_spec;
  42. /* This is the list of the default public-key ciphers included in
  43. libgcrypt. FIPS_ALLOWED indicated whether the algorithm is used in
  44. FIPS mode. */
  45. static struct pubkey_table_entry
  46. {
  47. gcry_pk_spec_t *pubkey;
  48. pk_extra_spec_t *extraspec;
  49. unsigned int algorithm;
  50. int fips_allowed;
  51. } pubkey_table[] =
  52. {
  53. #if USE_RSA
  54. { &_gcry_pubkey_spec_rsa,
  55. &_gcry_pubkey_extraspec_rsa, GCRY_PK_RSA, 1},
  56. #endif
  57. #if USE_ELGAMAL
  58. { &_gcry_pubkey_spec_elg,
  59. &_gcry_pubkey_extraspec_elg, GCRY_PK_ELG },
  60. { &_gcry_pubkey_spec_elg,
  61. &_gcry_pubkey_extraspec_elg, GCRY_PK_ELG_E },
  62. #endif
  63. #if USE_DSA
  64. { &_gcry_pubkey_spec_dsa,
  65. &_gcry_pubkey_extraspec_dsa, GCRY_PK_DSA, 1 },
  66. #endif
  67. #if USE_ECC
  68. { &_gcry_pubkey_spec_ecdsa,
  69. &_gcry_pubkey_extraspec_ecdsa, GCRY_PK_ECDSA, 0 },
  70. { &_gcry_pubkey_spec_ecdh,
  71. &_gcry_pubkey_extraspec_ecdsa, GCRY_PK_ECDH, 0 },
  72. #endif
  73. { NULL, 0 },
  74. };
  75. /* List of registered ciphers. */
  76. static gcry_module_t pubkeys_registered;
  77. /* This is the lock protecting PUBKEYS_REGISTERED. */
  78. static ath_mutex_t pubkeys_registered_lock = ATH_MUTEX_INITIALIZER;;
  79. /* Flag to check whether the default pubkeys have already been
  80. registered. */
  81. static int default_pubkeys_registered;
  82. /* Convenient macro for registering the default digests. */
  83. #define REGISTER_DEFAULT_PUBKEYS \
  84. do \
  85. { \
  86. ath_mutex_lock (&pubkeys_registered_lock); \
  87. if (! default_pubkeys_registered) \
  88. { \
  89. pk_register_default (); \
  90. default_pubkeys_registered = 1; \
  91. } \
  92. ath_mutex_unlock (&pubkeys_registered_lock); \
  93. } \
  94. while (0)
  95. /* These dummy functions are used in case a cipher implementation
  96. refuses to provide it's own functions. */
  97. static gcry_err_code_t
  98. dummy_generate (int algorithm, unsigned int nbits, unsigned long dummy,
  99. gcry_mpi_t *skey, gcry_mpi_t **retfactors)
  100. {
  101. (void)algorithm;
  102. (void)nbits;
  103. (void)dummy;
  104. (void)skey;
  105. (void)retfactors;
  106. fips_signal_error ("using dummy public key function");
  107. return GPG_ERR_NOT_IMPLEMENTED;
  108. }
  109. static gcry_err_code_t
  110. dummy_check_secret_key (int algorithm, gcry_mpi_t *skey)
  111. {
  112. (void)algorithm;
  113. (void)skey;
  114. fips_signal_error ("using dummy public key function");
  115. return GPG_ERR_NOT_IMPLEMENTED;
  116. }
  117. static gcry_err_code_t
  118. dummy_encrypt (int algorithm, gcry_mpi_t *resarr, gcry_mpi_t data,
  119. gcry_mpi_t *pkey, int flags)
  120. {
  121. (void)algorithm;
  122. (void)resarr;
  123. (void)data;
  124. (void)pkey;
  125. (void)flags;
  126. fips_signal_error ("using dummy public key function");
  127. return GPG_ERR_NOT_IMPLEMENTED;
  128. }
  129. static gcry_err_code_t
  130. dummy_decrypt (int algorithm, gcry_mpi_t *result, gcry_mpi_t *data,
  131. gcry_mpi_t *skey, int flags)
  132. {
  133. (void)algorithm;
  134. (void)result;
  135. (void)data;
  136. (void)skey;
  137. (void)flags;
  138. fips_signal_error ("using dummy public key function");
  139. return GPG_ERR_NOT_IMPLEMENTED;
  140. }
  141. static gcry_err_code_t
  142. dummy_sign (int algorithm, gcry_mpi_t *resarr, gcry_mpi_t data,
  143. gcry_mpi_t *skey)
  144. {
  145. (void)algorithm;
  146. (void)resarr;
  147. (void)data;
  148. (void)skey;
  149. fips_signal_error ("using dummy public key function");
  150. return GPG_ERR_NOT_IMPLEMENTED;
  151. }
  152. static gcry_err_code_t
  153. dummy_verify (int algorithm, gcry_mpi_t hash, gcry_mpi_t *data,
  154. gcry_mpi_t *pkey,
  155. int (*cmp) (void *, gcry_mpi_t), void *opaquev)
  156. {
  157. (void)algorithm;
  158. (void)hash;
  159. (void)data;
  160. (void)pkey;
  161. (void)cmp;
  162. (void)opaquev;
  163. fips_signal_error ("using dummy public key function");
  164. return GPG_ERR_NOT_IMPLEMENTED;
  165. }
  166. static unsigned
  167. dummy_get_nbits (int algorithm, gcry_mpi_t *pkey)
  168. {
  169. (void)algorithm;
  170. (void)pkey;
  171. fips_signal_error ("using dummy public key function");
  172. return 0;
  173. }
  174. /* Internal function. Register all the pubkeys included in
  175. PUBKEY_TABLE. Returns zero on success or an error code. */
  176. static void
  177. pk_register_default (void)
  178. {
  179. gcry_err_code_t err = 0;
  180. int i;
  181. for (i = 0; (! err) && pubkey_table[i].pubkey; i++)
  182. {
  183. #define pubkey_use_dummy(func) \
  184. if (! pubkey_table[i].pubkey->func) \
  185. pubkey_table[i].pubkey->func = dummy_##func;
  186. pubkey_use_dummy (generate);
  187. pubkey_use_dummy (check_secret_key);
  188. pubkey_use_dummy (encrypt);
  189. pubkey_use_dummy (decrypt);
  190. pubkey_use_dummy (sign);
  191. pubkey_use_dummy (verify);
  192. pubkey_use_dummy (get_nbits);
  193. #undef pubkey_use_dummy
  194. err = _gcry_module_add (&pubkeys_registered,
  195. pubkey_table[i].algorithm,
  196. (void *) pubkey_table[i].pubkey,
  197. (void *) pubkey_table[i].extraspec,
  198. NULL);
  199. }
  200. if (err)
  201. BUG ();
  202. }
  203. /* Internal callback function. Used via _gcry_module_lookup. */
  204. static int
  205. gcry_pk_lookup_func_name (void *spec, void *data)
  206. {
  207. gcry_pk_spec_t *pubkey = (gcry_pk_spec_t *) spec;
  208. char *name = (char *) data;
  209. const char **aliases = pubkey->aliases;
  210. int ret = stricmp (name, pubkey->name);
  211. while (ret && *aliases)
  212. ret = stricmp (name, *aliases++);
  213. return ! ret;
  214. }
  215. /* Internal function. Lookup a pubkey entry by it's name. */
  216. static gcry_module_t
  217. gcry_pk_lookup_name (const char *name)
  218. {
  219. gcry_module_t pubkey;
  220. pubkey = _gcry_module_lookup (pubkeys_registered, (void *) name,
  221. gcry_pk_lookup_func_name);
  222. return pubkey;
  223. }
  224. /* Register a new pubkey module whose specification can be found in
  225. PUBKEY. On success, a new algorithm ID is stored in ALGORITHM_ID
  226. and a pointer representhing this module is stored in MODULE. */
  227. gcry_error_t
  228. _gcry_pk_register (gcry_pk_spec_t *pubkey,
  229. pk_extra_spec_t *extraspec,
  230. unsigned int *algorithm_id,
  231. gcry_module_t *module)
  232. {
  233. gcry_err_code_t err = GPG_ERR_NO_ERROR;
  234. gcry_module_t mod;
  235. /* We do not support module loading in fips mode. */
  236. if (fips_mode ())
  237. return gpg_error (GPG_ERR_NOT_SUPPORTED);
  238. ath_mutex_lock (&pubkeys_registered_lock);
  239. err = _gcry_module_add (&pubkeys_registered, 0,
  240. (void *) pubkey,
  241. (void *)(extraspec? extraspec : &dummy_extra_spec),
  242. &mod);
  243. ath_mutex_unlock (&pubkeys_registered_lock);
  244. if (! err)
  245. {
  246. *module = mod;
  247. *algorithm_id = mod->mod_id;
  248. }
  249. return err;
  250. }
  251. /* Unregister the pubkey identified by ID, which must have been
  252. registered with gcry_pk_register. */
  253. void
  254. gcry_pk_unregister (gcry_module_t module)
  255. {
  256. ath_mutex_lock (&pubkeys_registered_lock);
  257. _gcry_module_release (module);
  258. ath_mutex_unlock (&pubkeys_registered_lock);
  259. }
  260. static void
  261. release_mpi_array (gcry_mpi_t *array)
  262. {
  263. for (; *array; array++)
  264. {
  265. mpi_free(*array);
  266. *array = NULL;
  267. }
  268. }
  269. /****************
  270. * Map a string to the pubkey algo
  271. */
  272. int
  273. gcry_pk_map_name (const char *string)
  274. {
  275. gcry_module_t pubkey;
  276. int algorithm = 0;
  277. if (!string)
  278. return 0;
  279. REGISTER_DEFAULT_PUBKEYS;
  280. ath_mutex_lock (&pubkeys_registered_lock);
  281. pubkey = gcry_pk_lookup_name (string);
  282. if (pubkey)
  283. {
  284. algorithm = pubkey->mod_id;
  285. _gcry_module_release (pubkey);
  286. }
  287. ath_mutex_unlock (&pubkeys_registered_lock);
  288. return algorithm;
  289. }
  290. /* Map the public key algorithm whose ID is contained in ALGORITHM to
  291. a string representation of the algorithm name. For unknown
  292. algorithm IDs this functions returns "?". */
  293. const char *
  294. gcry_pk_algo_name (int algorithm)
  295. {
  296. gcry_module_t pubkey;
  297. const char *name;
  298. REGISTER_DEFAULT_PUBKEYS;
  299. ath_mutex_lock (&pubkeys_registered_lock);
  300. pubkey = _gcry_module_lookup_id (pubkeys_registered, algorithm);
  301. if (pubkey)
  302. {
  303. name = ((gcry_pk_spec_t *) pubkey->spec)->name;
  304. _gcry_module_release (pubkey);
  305. }
  306. else
  307. name = "?";
  308. ath_mutex_unlock (&pubkeys_registered_lock);
  309. return name;
  310. }
  311. /* A special version of gcry_pk_algo name to return the first aliased
  312. name of the algorithm. This is required to adhere to the spki
  313. specs where the algorithm names are lowercase. */
  314. const char *
  315. _gcry_pk_aliased_algo_name (int algorithm)
  316. {
  317. const char *name = NULL;
  318. gcry_module_t module;
  319. REGISTER_DEFAULT_PUBKEYS;
  320. ath_mutex_lock (&pubkeys_registered_lock);
  321. module = _gcry_module_lookup_id (pubkeys_registered, algorithm);
  322. if (module)
  323. {
  324. gcry_pk_spec_t *pubkey = (gcry_pk_spec_t *) module->spec;
  325. name = pubkey->aliases? *pubkey->aliases : NULL;
  326. if (!name || !*name)
  327. name = pubkey->name;
  328. _gcry_module_release (module);
  329. }
  330. ath_mutex_unlock (&pubkeys_registered_lock);
  331. return name;
  332. }
  333. static void
  334. disable_pubkey_algo (int algorithm)
  335. {
  336. gcry_module_t pubkey;
  337. ath_mutex_lock (&pubkeys_registered_lock);
  338. pubkey = _gcry_module_lookup_id (pubkeys_registered, algorithm);
  339. if (pubkey)
  340. {
  341. if (! (pubkey-> flags & FLAG_MODULE_DISABLED))
  342. pubkey->flags |= FLAG_MODULE_DISABLED;
  343. _gcry_module_release (pubkey);
  344. }
  345. ath_mutex_unlock (&pubkeys_registered_lock);
  346. }
  347. /****************
  348. * A USE of 0 means: don't care.
  349. */
  350. static gcry_err_code_t
  351. check_pubkey_algo (int algorithm, unsigned use)
  352. {
  353. gcry_err_code_t err = GPG_ERR_NO_ERROR;
  354. gcry_pk_spec_t *pubkey;
  355. gcry_module_t module;
  356. REGISTER_DEFAULT_PUBKEYS;
  357. ath_mutex_lock (&pubkeys_registered_lock);
  358. module = _gcry_module_lookup_id (pubkeys_registered, algorithm);
  359. if (module)
  360. {
  361. pubkey = (gcry_pk_spec_t *) module->spec;
  362. if (((use & GCRY_PK_USAGE_SIGN)
  363. && (! (pubkey->use & GCRY_PK_USAGE_SIGN)))
  364. || ((use & GCRY_PK_USAGE_ENCR)
  365. && (! (pubkey->use & GCRY_PK_USAGE_ENCR))))
  366. err = GPG_ERR_WRONG_PUBKEY_ALGO;
  367. else if (module->flags & FLAG_MODULE_DISABLED)
  368. err = GPG_ERR_PUBKEY_ALGO;
  369. _gcry_module_release (module);
  370. }
  371. else
  372. err = GPG_ERR_PUBKEY_ALGO;
  373. ath_mutex_unlock (&pubkeys_registered_lock);
  374. return err;
  375. }
  376. /****************
  377. * Return the number of public key material numbers
  378. */
  379. static int
  380. pubkey_get_npkey (int algorithm)
  381. {
  382. gcry_module_t pubkey;
  383. int npkey = 0;
  384. REGISTER_DEFAULT_PUBKEYS;
  385. ath_mutex_lock (&pubkeys_registered_lock);
  386. pubkey = _gcry_module_lookup_id (pubkeys_registered, algorithm);
  387. if (pubkey)
  388. {
  389. npkey = strlen (((gcry_pk_spec_t *) pubkey->spec)->elements_pkey);
  390. _gcry_module_release (pubkey);
  391. }
  392. ath_mutex_unlock (&pubkeys_registered_lock);
  393. return npkey;
  394. }
  395. /****************
  396. * Return the number of secret key material numbers
  397. */
  398. static int
  399. pubkey_get_nskey (int algorithm)
  400. {
  401. gcry_module_t pubkey;
  402. int nskey = 0;
  403. REGISTER_DEFAULT_PUBKEYS;
  404. ath_mutex_lock (&pubkeys_registered_lock);
  405. pubkey = _gcry_module_lookup_id (pubkeys_registered, algorithm);
  406. if (pubkey)
  407. {
  408. nskey = strlen (((gcry_pk_spec_t *) pubkey->spec)->elements_skey);
  409. _gcry_module_release (pubkey);
  410. }
  411. ath_mutex_unlock (&pubkeys_registered_lock);
  412. return nskey;
  413. }
  414. /****************
  415. * Return the number of signature material numbers
  416. */
  417. static int
  418. pubkey_get_nsig (int algorithm)
  419. {
  420. gcry_module_t pubkey;
  421. int nsig = 0;
  422. REGISTER_DEFAULT_PUBKEYS;
  423. ath_mutex_lock (&pubkeys_registered_lock);
  424. pubkey = _gcry_module_lookup_id (pubkeys_registered, algorithm);
  425. if (pubkey)
  426. {
  427. nsig = strlen (((gcry_pk_spec_t *) pubkey->spec)->elements_sig);
  428. _gcry_module_release (pubkey);
  429. }
  430. ath_mutex_unlock (&pubkeys_registered_lock);
  431. return nsig;
  432. }
  433. /****************
  434. * Return the number of encryption material numbers
  435. */
  436. static int
  437. pubkey_get_nenc (int algorithm)
  438. {
  439. gcry_module_t pubkey;
  440. int nenc = 0;
  441. REGISTER_DEFAULT_PUBKEYS;
  442. ath_mutex_lock (&pubkeys_registered_lock);
  443. pubkey = _gcry_module_lookup_id (pubkeys_registered, algorithm);
  444. if (pubkey)
  445. {
  446. nenc = strlen (((gcry_pk_spec_t *) pubkey->spec)->elements_enc);
  447. _gcry_module_release (pubkey);
  448. }
  449. ath_mutex_unlock (&pubkeys_registered_lock);
  450. return nenc;
  451. }
  452. /* Generate a new public key with algorithm ALGORITHM of size NBITS
  453. and return it at SKEY. USE_E depends on the ALGORITHM. GENPARMS
  454. is passed to the algorithm module if it features an extended
  455. generation function. RETFACTOR is used by some algorithms to
  456. return certain additional information which are in general not
  457. required.
  458. The function returns the error code number or 0 on success. */
  459. static gcry_err_code_t
  460. pubkey_generate (int algorithm,
  461. unsigned int nbits,
  462. unsigned long use_e,
  463. gcry_sexp_t genparms,
  464. gcry_mpi_t *skey, gcry_mpi_t **retfactors,
  465. gcry_sexp_t *r_extrainfo)
  466. {
  467. gcry_err_code_t ec = GPG_ERR_PUBKEY_ALGO;
  468. gcry_module_t pubkey;
  469. REGISTER_DEFAULT_PUBKEYS;
  470. ath_mutex_lock (&pubkeys_registered_lock);
  471. pubkey = _gcry_module_lookup_id (pubkeys_registered, algorithm);
  472. if (pubkey)
  473. {
  474. pk_extra_spec_t *extraspec = pubkey->extraspec;
  475. if (extraspec && extraspec->ext_generate)
  476. {
  477. /* Use the extended generate function. */
  478. ec = extraspec->ext_generate
  479. (algorithm, nbits, use_e, genparms, skey, retfactors, r_extrainfo);
  480. }
  481. else
  482. {
  483. /* Use the standard generate function. */
  484. ec = ((gcry_pk_spec_t *) pubkey->spec)->generate
  485. (algorithm, nbits, use_e, skey, retfactors);
  486. }
  487. _gcry_module_release (pubkey);
  488. }
  489. ath_mutex_unlock (&pubkeys_registered_lock);
  490. return ec;
  491. }
  492. static gcry_err_code_t
  493. pubkey_check_secret_key (int algorithm, gcry_mpi_t *skey)
  494. {
  495. gcry_err_code_t err = GPG_ERR_PUBKEY_ALGO;
  496. gcry_module_t pubkey;
  497. REGISTER_DEFAULT_PUBKEYS;
  498. ath_mutex_lock (&pubkeys_registered_lock);
  499. pubkey = _gcry_module_lookup_id (pubkeys_registered, algorithm);
  500. if (pubkey)
  501. {
  502. err = ((gcry_pk_spec_t *) pubkey->spec)->check_secret_key
  503. (algorithm, skey);
  504. _gcry_module_release (pubkey);
  505. }
  506. ath_mutex_unlock (&pubkeys_registered_lock);
  507. return err;
  508. }
  509. /****************
  510. * This is the interface to the public key encryption. Encrypt DATA
  511. * with PKEY and put it into RESARR which should be an array of MPIs
  512. * of size PUBKEY_MAX_NENC (or less if the algorithm allows this -
  513. * check with pubkey_get_nenc() )
  514. */
  515. static gcry_err_code_t
  516. pubkey_encrypt (int algorithm, gcry_mpi_t *resarr, gcry_mpi_t data,
  517. gcry_mpi_t *pkey, int flags)
  518. {
  519. gcry_pk_spec_t *pubkey;
  520. gcry_module_t module;
  521. gcry_err_code_t rc;
  522. int i;
  523. /* Note: In fips mode DBG_CIPHER will enver evaluate to true but as
  524. an extra failsafe protection we explicitly test for fips mode
  525. here. */
  526. if (DBG_CIPHER && !fips_mode ())
  527. {
  528. log_debug ("pubkey_encrypt: algo=%d\n", algorithm);
  529. for(i = 0; i < pubkey_get_npkey (algorithm); i++)
  530. log_mpidump (" pkey:", pkey[i]);
  531. log_mpidump (" data:", data);
  532. }
  533. ath_mutex_lock (&pubkeys_registered_lock);
  534. module = _gcry_module_lookup_id (pubkeys_registered, algorithm);
  535. if (module)
  536. {
  537. pubkey = (gcry_pk_spec_t *) module->spec;
  538. rc = pubkey->encrypt (algorithm, resarr, data, pkey, flags);
  539. _gcry_module_release (module);
  540. goto ready;
  541. }
  542. rc = GPG_ERR_PUBKEY_ALGO;
  543. ready:
  544. ath_mutex_unlock (&pubkeys_registered_lock);
  545. if (!rc && DBG_CIPHER && !fips_mode ())
  546. {
  547. for(i = 0; i < pubkey_get_nenc (algorithm); i++)
  548. log_mpidump(" encr:", resarr[i] );
  549. }
  550. return rc;
  551. }
  552. /****************
  553. * This is the interface to the public key decryption.
  554. * ALGO gives the algorithm to use and this implicitly determines
  555. * the size of the arrays.
  556. * result is a pointer to a mpi variable which will receive a
  557. * newly allocated mpi or NULL in case of an error.
  558. */
  559. static gcry_err_code_t
  560. pubkey_decrypt (int algorithm, gcry_mpi_t *result, gcry_mpi_t *data,
  561. gcry_mpi_t *skey, int flags)
  562. {
  563. gcry_pk_spec_t *pubkey;
  564. gcry_module_t module;
  565. gcry_err_code_t rc;
  566. int i;
  567. *result = NULL; /* so the caller can always do a mpi_free */
  568. if (DBG_CIPHER && !fips_mode ())
  569. {
  570. log_debug ("pubkey_decrypt: algo=%d\n", algorithm);
  571. for(i = 0; i < pubkey_get_nskey (algorithm); i++)
  572. log_mpidump (" skey:", skey[i]);
  573. for(i = 0; i < pubkey_get_nenc (algorithm); i++)
  574. log_mpidump (" data:", data[i]);
  575. }
  576. ath_mutex_lock (&pubkeys_registered_lock);
  577. module = _gcry_module_lookup_id (pubkeys_registered, algorithm);
  578. if (module)
  579. {
  580. pubkey = (gcry_pk_spec_t *) module->spec;
  581. rc = pubkey->decrypt (algorithm, result, data, skey, flags);
  582. _gcry_module_release (module);
  583. goto ready;
  584. }
  585. rc = GPG_ERR_PUBKEY_ALGO;
  586. ready:
  587. ath_mutex_unlock (&pubkeys_registered_lock);
  588. if (!rc && DBG_CIPHER && !fips_mode ())
  589. log_mpidump (" plain:", *result);
  590. return rc;
  591. }
  592. /****************
  593. * This is the interface to the public key signing.
  594. * Sign data with skey and put the result into resarr which
  595. * should be an array of MPIs of size PUBKEY_MAX_NSIG (or less if the
  596. * algorithm allows this - check with pubkey_get_nsig() )
  597. */
  598. static gcry_err_code_t
  599. pubkey_sign (int algorithm, gcry_mpi_t *resarr, gcry_mpi_t data,
  600. gcry_mpi_t *skey)
  601. {
  602. gcry_pk_spec_t *pubkey;
  603. gcry_module_t module;
  604. gcry_err_code_t rc;
  605. int i;
  606. if (DBG_CIPHER && !fips_mode ())
  607. {
  608. log_debug ("pubkey_sign: algo=%d\n", algorithm);
  609. for(i = 0; i < pubkey_get_nskey (algorithm); i++)
  610. log_mpidump (" skey:", skey[i]);
  611. log_mpidump(" data:", data );
  612. }
  613. ath_mutex_lock (&pubkeys_registered_lock);
  614. module = _gcry_module_lookup_id (pubkeys_registered, algorithm);
  615. if (module)
  616. {
  617. pubkey = (gcry_pk_spec_t *) module->spec;
  618. rc = pubkey->sign (algorithm, resarr, data, skey);
  619. _gcry_module_release (module);
  620. goto ready;
  621. }
  622. rc = GPG_ERR_PUBKEY_ALGO;
  623. ready:
  624. ath_mutex_unlock (&pubkeys_registered_lock);
  625. if (!rc && DBG_CIPHER && !fips_mode ())
  626. for (i = 0; i < pubkey_get_nsig (algorithm); i++)
  627. log_mpidump (" sig:", resarr[i]);
  628. return rc;
  629. }
  630. /****************
  631. * Verify a public key signature.
  632. * Return 0 if the signature is good
  633. */
  634. static gcry_err_code_t
  635. pubkey_verify (int algorithm, gcry_mpi_t hash, gcry_mpi_t *data,
  636. gcry_mpi_t *pkey,
  637. int (*cmp)(void *, gcry_mpi_t), void *opaquev)
  638. {
  639. gcry_pk_spec_t *pubkey;
  640. gcry_module_t module;
  641. gcry_err_code_t rc;
  642. int i;
  643. if (DBG_CIPHER && !fips_mode ())
  644. {
  645. log_debug ("pubkey_verify: algo=%d\n", algorithm);
  646. for (i = 0; i < pubkey_get_npkey (algorithm); i++)
  647. log_mpidump (" pkey", pkey[i]);
  648. for (i = 0; i < pubkey_get_nsig (algorithm); i++)
  649. log_mpidump (" sig", data[i]);
  650. log_mpidump (" hash", hash);
  651. }
  652. ath_mutex_lock (&pubkeys_registered_lock);
  653. module = _gcry_module_lookup_id (pubkeys_registered, algorithm);
  654. if (module)
  655. {
  656. pubkey = (gcry_pk_spec_t *) module->spec;
  657. rc = pubkey->verify (algorithm, hash, data, pkey, cmp, opaquev);
  658. _gcry_module_release (module);
  659. goto ready;
  660. }
  661. rc = GPG_ERR_PUBKEY_ALGO;
  662. ready:
  663. ath_mutex_unlock (&pubkeys_registered_lock);
  664. return rc;
  665. }
  666. /* Turn VALUE into an octet string and store it in an allocated buffer
  667. at R_FRAME or - if R_RAME is NULL - copy it into the caller
  668. provided buffer SPACE; either SPACE or R_FRAME may be used. If
  669. SPACE if not NULL, the caller must provide a buffer of at least
  670. NBYTES. If the resulting octet string is shorter than NBYTES pad
  671. it to the left with zeroes. If VALUE does not fit into NBYTES
  672. return an error code. */
  673. static gpg_err_code_t
  674. octet_string_from_mpi (unsigned char **r_frame, void *space,
  675. gcry_mpi_t value, size_t nbytes)
  676. {
  677. gpg_err_code_t rc;
  678. size_t nframe, noff, n;
  679. unsigned char *frame;
  680. if (!r_frame == !space)
  681. return GPG_ERR_INV_ARG; /* Only one may be used. */
  682. if (r_frame)
  683. *r_frame = NULL;
  684. rc = gcry_err_code (gcry_mpi_print (GCRYMPI_FMT_USG,
  685. NULL, 0, &nframe, value));
  686. if (rc)
  687. return rc;
  688. if (nframe > nbytes)
  689. return GPG_ERR_TOO_LARGE; /* Value too long to fit into NBYTES. */
  690. noff = (nframe < nbytes)? nbytes - nframe : 0;
  691. n = nframe + noff;
  692. if (space)
  693. frame = space;
  694. else
  695. {
  696. frame = mpi_is_secure (value)? gcry_malloc_secure (n) : gcry_malloc (n);
  697. if (!frame)
  698. {
  699. rc = gpg_err_code_from_syserror ();
  700. return rc;
  701. }
  702. }
  703. if (noff)
  704. memset (frame, 0, noff);
  705. nframe += noff;
  706. rc = gcry_err_code (gcry_mpi_print (GCRYMPI_FMT_USG,
  707. frame+noff, nframe-noff, NULL, value));
  708. if (rc)
  709. {
  710. gcry_free (frame);
  711. return rc;
  712. }
  713. if (r_frame)
  714. *r_frame = frame;
  715. return 0;
  716. }
  717. /* Encode {VALUE,VALUELEN} for an NBITS keys using the pkcs#1 block
  718. type 2 padding. On sucess the result is stored as a new MPI at
  719. R_RESULT. On error the value at R_RESULT is undefined.
  720. If {RANDOM_OVERRIDE, RANDOM_OVERRIDE_LEN} is given it is used as
  721. the seed instead of using a random string for it. This feature is
  722. only useful for regression tests. Note that this value may not
  723. contain zero bytes.
  724. We encode the value in this way:
  725. 0 2 RND(n bytes) 0 VALUE
  726. 0 is a marker we unfortunately can't encode because we return an
  727. MPI which strips all leading zeroes.
  728. 2 is the block type.
  729. RND are non-zero random bytes.
  730. (Note that OpenPGP includes the cipher algorithm and a checksum in
  731. VALUE; the caller needs to prepare the value accordingly.)
  732. */
  733. static gcry_err_code_t
  734. pkcs1_encode_for_encryption (gcry_mpi_t *r_result, unsigned int nbits,
  735. const unsigned char *value, size_t valuelen,
  736. const unsigned char *random_override,
  737. size_t random_override_len)
  738. {
  739. gcry_err_code_t rc = 0;
  740. gcry_error_t err;
  741. unsigned char *frame = NULL;
  742. size_t nframe = (nbits+7) / 8;
  743. int i;
  744. size_t n;
  745. unsigned char *p;
  746. if (valuelen + 7 > nframe || !nframe)
  747. {
  748. /* Can't encode a VALUELEN value in a NFRAME bytes frame. */
  749. return GPG_ERR_TOO_SHORT; /* The key is too short. */
  750. }
  751. if ( !(frame = gcry_malloc_secure (nframe)))
  752. return gpg_err_code_from_syserror ();
  753. n = 0;
  754. frame[n++] = 0;
  755. frame[n++] = 2; /* block type */
  756. i = nframe - 3 - valuelen;
  757. gcry_assert (i > 0);
  758. if (random_override)
  759. {
  760. int j;
  761. if (random_override_len != i)
  762. {
  763. gcry_free (frame);
  764. return GPG_ERR_INV_ARG;
  765. }
  766. /* Check that random does not include a zero byte. */
  767. for (j=0; j < random_override_len; j++)
  768. if (!random_override[j])
  769. {
  770. gcry_free (frame);
  771. return GPG_ERR_INV_ARG;
  772. }
  773. memcpy (frame + n, random_override, random_override_len);
  774. n += random_override_len;
  775. }
  776. else
  777. {
  778. p = gcry_random_bytes_secure (i, GCRY_STRONG_RANDOM);
  779. /* Replace zero bytes by new values. */
  780. for (;;)
  781. {
  782. int j, k;
  783. unsigned char *pp;
  784. /* Count the zero bytes. */
  785. for (j=k=0; j < i; j++)
  786. {
  787. if (!p[j])
  788. k++;
  789. }
  790. if (!k)
  791. break; /* Okay: no (more) zero bytes. */
  792. k += k/128 + 3; /* Better get some more. */
  793. pp = gcry_random_bytes_secure (k, GCRY_STRONG_RANDOM);
  794. for (j=0; j < i && k; )
  795. {
  796. if (!p[j])
  797. p[j] = pp[--k];
  798. if (p[j])
  799. j++;
  800. }
  801. gcry_free (pp);
  802. }
  803. memcpy (frame+n, p, i);
  804. n += i;
  805. gcry_free (p);
  806. }
  807. frame[n++] = 0;
  808. memcpy (frame+n, value, valuelen);
  809. n += valuelen;
  810. gcry_assert (n == nframe);
  811. err = gcry_mpi_scan (r_result, GCRYMPI_FMT_USG, frame, n, &nframe);
  812. if (err)
  813. rc = gcry_err_code (err);
  814. else if (DBG_CIPHER)
  815. log_mpidump ("PKCS#1 block type 2 encoded data", *r_result);
  816. gcry_free (frame);
  817. return rc;
  818. }
  819. /* Decode a plaintext in VALUE assuming pkcs#1 block type 2 padding.
  820. NBITS is the size of the secret key. On success the result is
  821. stored as a newly allocated buffer at R_RESULT and its valid length at
  822. R_RESULTLEN. On error NULL is stored at R_RESULT. */
  823. static gcry_err_code_t
  824. pkcs1_decode_for_encryption (unsigned char **r_result, size_t *r_resultlen,
  825. unsigned int nbits, gcry_mpi_t value)
  826. {
  827. gcry_error_t err;
  828. unsigned char *frame = NULL;
  829. size_t nframe = (nbits+7) / 8;
  830. size_t n;
  831. *r_result = NULL;
  832. if ( !(frame = gcry_malloc_secure (nframe)))
  833. return gpg_err_code_from_syserror ();
  834. err = gcry_mpi_print (GCRYMPI_FMT_USG, frame, nframe, &n, value);
  835. if (err)
  836. {
  837. gcry_free (frame);
  838. return gcry_err_code (err);
  839. }
  840. nframe = n; /* Set NFRAME to the actual length. */
  841. /* FRAME = 0x00 || 0x02 || PS || 0x00 || M
  842. pkcs#1 requires that the first byte is zero. Our MPIs usually
  843. strip leading zero bytes; thus we are not able to detect them.
  844. However due to the way gcry_mpi_print is implemented we may see
  845. leading zero bytes nevertheless. We handle this by making the
  846. first zero byte optional. */
  847. if (nframe < 4)
  848. {
  849. gcry_free (frame);
  850. return GPG_ERR_ENCODING_PROBLEM; /* Too short. */
  851. }
  852. n = 0;
  853. if (!frame[0])
  854. n++;
  855. if (frame[n++] != 0x02)
  856. {
  857. gcry_free (frame);
  858. return GPG_ERR_ENCODING_PROBLEM; /* Wrong block type. */
  859. }
  860. /* Skip the non-zero random bytes and the terminating zero byte. */
  861. for (; n < nframe && frame[n] != 0x00; n++)
  862. ;
  863. if (n+1 >= nframe)
  864. {
  865. gcry_free (frame);
  866. return GPG_ERR_ENCODING_PROBLEM; /* No zero byte. */
  867. }
  868. n++; /* Skip the zero byte. */
  869. /* To avoid an extra allocation we reuse the frame buffer. The only
  870. caller of this function will anyway free the result soon. */
  871. memmove (frame, frame + n, nframe - n);
  872. *r_result = frame;
  873. *r_resultlen = nframe - n;
  874. if (DBG_CIPHER)
  875. log_printhex ("value extracted from PKCS#1 block type 2 encoded data:",
  876. *r_result, *r_resultlen);
  877. return 0;
  878. }
  879. /* Encode {VALUE,VALUELEN} for an NBITS keys and hash algorith ALGO
  880. using the pkcs#1 block type 1 padding. On success the result is
  881. stored as a new MPI at R_RESULT. On error the value at R_RESULT is
  882. undefined.
  883. We encode the value in this way:
  884. 0 1 PAD(n bytes) 0 ASN(asnlen bytes) VALUE(valuelen bytes)
  885. 0 is a marker we unfortunately can't encode because we return an
  886. MPI which strips all leading zeroes.
  887. 1 is the block type.
  888. PAD consists of 0xff bytes.
  889. 0 marks the end of the padding.
  890. ASN is the DER encoding of the hash algorithm; along with the VALUE
  891. it yields a valid DER encoding.
  892. (Note that PGP prior to version 2.3 encoded the message digest as:
  893. 0 1 MD(16 bytes) 0 PAD(n bytes) 1
  894. The MD is always 16 bytes here because it's always MD5. GnuPG
  895. does not not support pre-v2.3 signatures, but I'm including this
  896. comment so the information is easily found if needed.)
  897. */
  898. static gcry_err_code_t
  899. pkcs1_encode_for_signature (gcry_mpi_t *r_result, unsigned int nbits,
  900. const unsigned char *value, size_t valuelen,
  901. int algo)
  902. {
  903. gcry_err_code_t rc = 0;
  904. gcry_error_t err;
  905. byte asn[100];
  906. byte *frame = NULL;
  907. size_t nframe = (nbits+7) / 8;
  908. int i;
  909. size_t n;
  910. size_t asnlen, dlen;
  911. asnlen = DIM(asn);
  912. dlen = gcry_md_get_algo_dlen (algo);
  913. if (gcry_md_algo_info (algo, GCRYCTL_GET_ASNOID, asn, &asnlen))
  914. {
  915. /* We don't have yet all of the above algorithms. */
  916. return GPG_ERR_NOT_IMPLEMENTED;
  917. }
  918. if ( valuelen != dlen )
  919. {
  920. /* Hash value does not match the length of digest for
  921. the given algorithm. */
  922. return GPG_ERR_CONFLICT;
  923. }
  924. if ( !dlen || dlen + asnlen + 4 > nframe)
  925. {
  926. /* Can't encode an DLEN byte digest MD into an NFRAME byte
  927. frame. */
  928. return GPG_ERR_TOO_SHORT;
  929. }
  930. if ( !(frame = gcry_malloc (nframe)) )
  931. return gpg_err_code_from_syserror ();
  932. /* Assemble the pkcs#1 block type 1. */
  933. n = 0;
  934. frame[n++] = 0;
  935. frame[n++] = 1; /* block type */
  936. i = nframe - valuelen - asnlen - 3 ;
  937. gcry_assert (i > 1);
  938. memset (frame+n, 0xff, i );
  939. n += i;
  940. frame[n++] = 0;
  941. memcpy (frame+n, asn, asnlen);
  942. n += asnlen;
  943. memcpy (frame+n, value, valuelen );
  944. n += valuelen;
  945. gcry_assert (n == nframe);
  946. /* Convert it into an MPI. */
  947. err = gcry_mpi_scan (r_result, GCRYMPI_FMT_USG, frame, n, &nframe);
  948. if (err)
  949. rc = gcry_err_code (err);
  950. else if (DBG_CIPHER)
  951. log_mpidump ("PKCS#1 block type 1 encoded data", *r_result);
  952. gcry_free (frame);
  953. return rc;
  954. }
  955. /* Mask generation function for OAEP. See RFC-3447 B.2.1. */
  956. static gcry_err_code_t
  957. mgf1 (unsigned char *output, size_t outlen, unsigned char *seed, size_t seedlen,
  958. int algo)
  959. {
  960. size_t dlen, nbytes, n;
  961. int idx;
  962. gcry_md_hd_t hd;
  963. gcry_error_t err;
  964. err = gcry_md_open (&hd, algo, 0);
  965. if (err)
  966. return gpg_err_code (err);
  967. dlen = gcry_md_get_algo_dlen (algo);
  968. /* We skip step 1 which would be assert(OUTLEN <= 2^32). The loop
  969. in step 3 is merged with step 4 by concatenating no more octets
  970. than what would fit into OUTPUT. The ceiling for the counter IDX
  971. is implemented indirectly. */
  972. nbytes = 0; /* Step 2. */
  973. idx = 0;
  974. while ( nbytes < outlen )
  975. {
  976. unsigned char c[4], *digest;
  977. if (idx)
  978. gcry_md_reset (hd);
  979. c[0] = (idx >> 24) & 0xFF;
  980. c[1] = (idx >> 16) & 0xFF;
  981. c[2] = (idx >> 8) & 0xFF;
  982. c[3] = idx & 0xFF;
  983. idx++;
  984. gcry_md_write (hd, seed, seedlen);
  985. gcry_md_write (hd, c, 4);
  986. digest = gcry_md_read (hd, 0);
  987. n = (outlen - nbytes < dlen)? (outlen - nbytes) : dlen;
  988. memcpy (output+nbytes, digest, n);
  989. nbytes += n;
  990. }
  991. gcry_md_close (hd);
  992. return GPG_ERR_NO_ERROR;
  993. }
  994. /* RFC-3447 (pkcs#1 v2.1) OAEP encoding. NBITS is the length of the
  995. key measured in bits. ALGO is the hash function; it must be a
  996. valid and usable algorithm. {VALUE,VALUELEN} is the message to
  997. encrypt. {LABEL,LABELLEN} is the optional label to be associated
  998. with the message, if LABEL is NULL the default is to use the empty
  999. string as label. On success the encoded ciphertext is returned at
  1000. R_RESULT.
  1001. If {RANDOM_OVERRIDE, RANDOM_OVERRIDE_LEN} is given it is used as
  1002. the seed instead of using a random string for it. This feature is
  1003. only useful for regression tests.
  1004. Here is figure 1 from the RFC depicting the process:
  1005. +----------+---------+-------+
  1006. DB = | lHash | PS | M |
  1007. +----------+---------+-------+
  1008. |
  1009. +----------+ V
  1010. | seed |--> MGF ---> xor
  1011. +----------+ |
  1012. | |
  1013. +--+ V |
  1014. |00| xor <----- MGF <-----|
  1015. +--+ | |
  1016. | | |
  1017. V V V
  1018. +--+----------+----------------------------+
  1019. EM = |00|maskedSeed| maskedDB |
  1020. +--+----------+----------------------------+
  1021. */
  1022. static gcry_err_code_t
  1023. oaep_encode (gcry_mpi_t *r_result, unsigned int nbits, int algo,
  1024. const unsigned char *value, size_t valuelen,
  1025. const unsigned char *label, size_t labellen,
  1026. const void *random_override, size_t random_override_len)
  1027. {
  1028. gcry_err_code_t rc = 0;
  1029. gcry_error_t err;
  1030. unsigned char *frame = NULL;
  1031. size_t nframe = (nbits+7) / 8;
  1032. unsigned char *p;
  1033. size_t hlen;
  1034. size_t n;
  1035. *r_result = NULL;
  1036. /* Set defaults for LABEL. */
  1037. if (!label || !labellen)
  1038. {
  1039. label = (const unsigned char*)"";
  1040. labellen = 0;
  1041. }
  1042. hlen = gcry_md_get_algo_dlen (algo);
  1043. /* We skip step 1a which would be to check that LABELLEN is not
  1044. greater than 2^61-1. See rfc-3447 7.1.1. */
  1045. /* Step 1b. Note that the obsolete rfc-2437 uses the check:
  1046. valuelen > nframe - 2 * hlen - 1 . */
  1047. if (valuelen > nframe - 2 * hlen - 2 || !nframe)
  1048. {
  1049. /* Can't encode a VALUELEN value in a NFRAME bytes frame. */
  1050. return GPG_ERR_TOO_SHORT; /* The key is too short. */
  1051. }
  1052. /* Allocate the frame. */
  1053. frame = gcry_calloc_secure (1, nframe);
  1054. if (!frame)
  1055. return gpg_err_code_from_syserror ();
  1056. /* Step 2a: Compute the hash of the label. We store it in the frame
  1057. where later the maskedDB will commence. */
  1058. gcry_md_hash_buffer (algo, frame + 1 + hlen, label, labellen);
  1059. /* Step 2b: Set octet string to zero. */
  1060. /* This has already been done while allocating FRAME. */
  1061. /* Step 2c: Create DB by concatenating lHash, PS, 0x01 and M. */
  1062. n = nframe - valuelen - 1;
  1063. frame[n] = 0x01;
  1064. memcpy (frame + n + 1, value, valuelen);
  1065. /* Step 3d: Generate seed. We store it where the maskedSeed will go
  1066. later. */
  1067. if (random_override)
  1068. {
  1069. if (random_override_len != hlen)
  1070. {
  1071. gcry_free (frame);
  1072. return GPG_ERR_INV_ARG;
  1073. }
  1074. memcpy (frame + 1, random_override, hlen);
  1075. }
  1076. else
  1077. gcry_randomize (frame + 1, hlen, GCRY_STRONG_RANDOM);
  1078. /* Step 2e and 2f: Create maskedDB. */
  1079. {
  1080. unsigned char *dmask;
  1081. dmask = gcry_malloc_secure (nframe - hlen - 1);
  1082. if (!dmask)
  1083. {
  1084. rc = gpg_err_code_from_syserror ();
  1085. gcry_free (frame);
  1086. return rc;
  1087. }
  1088. rc = mgf1 (dmask, nframe - hlen - 1, frame+1, hlen, algo);
  1089. if (rc)
  1090. {
  1091. gcry_free (dmask);
  1092. gcry_free (frame);
  1093. return rc;
  1094. }
  1095. for (n = 1 + hlen, p = dmask; n < nframe; n++)
  1096. frame[n] ^= *p++;
  1097. gcry_free (dmask);
  1098. }
  1099. /* Step 2g and 2h: Create maskedSeed. */
  1100. {
  1101. unsigned char *smask;
  1102. smask = gcry_malloc_secure (hlen);
  1103. if (!smask)
  1104. {
  1105. rc = gpg_err_code_from_syserror ();
  1106. gcry_free (frame);
  1107. return rc;
  1108. }
  1109. rc = mgf1 (smask, hlen, frame + 1 + hlen, nframe - hlen - 1, algo);
  1110. if (rc)
  1111. {
  1112. gcry_free (smask);
  1113. gcry_free (frame);
  1114. return rc;
  1115. }
  1116. for (n = 1, p = smask; n < 1 + hlen; n++)
  1117. frame[n] ^= *p++;
  1118. gcry_free (smask);
  1119. }
  1120. /* Step 2i: Concatenate 0x00, maskedSeed and maskedDB. */
  1121. /* This has already been done by using in-place operations. */
  1122. /* Convert the stuff into an MPI as expected by the caller. */
  1123. err = gcry_mpi_scan (r_result, GCRYMPI_FMT_USG, frame, nframe, NULL);
  1124. if (err)
  1125. rc = gcry_err_code (err);
  1126. else if (DBG_CIPHER)
  1127. log_mpidump ("OAEP encoded data", *r_result);
  1128. gcry_free (frame);
  1129. return rc;
  1130. }
  1131. /* RFC-3447 (pkcs#1 v2.1) OAEP decoding. NBITS is the length of the
  1132. key measured in bits. ALGO is the hash function; it must be a
  1133. valid and usable algorithm. VALUE is the raw decrypted message
  1134. {LABEL,LABELLEN} is the optional label to be associated with the
  1135. message, if LABEL is NULL the default is to use the empty string as
  1136. label. On success the plaintext is returned as a newly allocated
  1137. buffer at R_RESULT; its valid length is stored at R_RESULTLEN. On
  1138. error NULL is stored at R_RESULT. */
  1139. static gcry_err_code_t
  1140. oaep_decode (unsigned char **r_result, size_t *r_resultlen,
  1141. unsigned int nbits, int algo,
  1142. gcry_mpi_t value, const unsigned char *label, size_t labellen)
  1143. {
  1144. gcry_err_code_t rc;
  1145. unsigned char *frame = NULL; /* Encoded messages (EM). */
  1146. unsigned char *masked_seed; /* Points into FRAME. */
  1147. unsigned char *masked_db; /* Points into FRAME. */
  1148. unsigned char *seed = NULL; /* Allocated space for the seed and DB. */
  1149. unsigned char *db; /* Points into SEED. */
  1150. unsigned char *lhash = NULL; /* Hash of the label. */
  1151. size_t nframe; /* Length of the ciphertext (EM). */
  1152. size_t hlen; /* Length of the hash digest. */
  1153. size_t db_len; /* Length of DB and masked_db. */
  1154. size_t nkey = (nbits+7)/8; /* Length of the key in bytes. */
  1155. int failed = 0; /* Error indicator. */
  1156. size_t n;
  1157. *r_result = NULL;
  1158. /* This code is implemented as described by rfc-3447 7.1.2. */
  1159. /* Set defaults for LABEL. */
  1160. if (!label || !labellen)
  1161. {
  1162. label = (const unsigned char*)"";
  1163. labellen = 0;
  1164. }
  1165. /* Get the length of the digest. */
  1166. hlen = gcry_md_get_algo_dlen (algo);
  1167. /* Hash the label right away. */
  1168. lhash = gcry_malloc (hlen);
  1169. if (!lhash)
  1170. return gpg_err_code_from_syserror ();
  1171. gcry_md_hash_buffer (algo, lhash, label, labellen);
  1172. /* Turn the MPI into an octet string. If the octet string is
  1173. shorter than the key we pad it to the left with zeroes. This may
  1174. happen due to the leading zero in OAEP frames and due to the
  1175. following random octets (seed^mask) which may have leading zero
  1176. bytes. This all is needed to cope with our leading zeroes
  1177. suppressing MPI implementation. The code implictly implements
  1178. Step 1b (bail out if NFRAME != N). */
  1179. rc = octet_string_from_mpi (&frame, NULL, value, nkey);
  1180. if (rc)
  1181. {
  1182. gcry_free (lhash);
  1183. return GPG_ERR_ENCODING_PROBLEM;
  1184. }
  1185. nframe = nkey;
  1186. /* Step 1c: Check that the key is long enough. */
  1187. if ( nframe < 2 * hlen + 2 )
  1188. {
  1189. gcry_free (frame);
  1190. gcry_free (lhash);
  1191. return GPG_ERR_ENCODING_PROBLEM;
  1192. }
  1193. /* Step 2 has already been done by the caller and the
  1194. gcry_mpi_aprint above. */
  1195. /* Allocate space for SEED and DB. */
  1196. seed = gcry_malloc_secure (nframe - 1);
  1197. if (!seed)
  1198. {
  1199. rc = gpg_err_code_from_syserror ();
  1200. gcry_free (frame);
  1201. gcry_free (lhash);
  1202. return rc;
  1203. }
  1204. db = seed + hlen;
  1205. /* To avoid choosen ciphertext attacks from now on we make sure to
  1206. run all code even in the error case; this avoids possible timing
  1207. attacks as described by Manger. */
  1208. /* Step 3a: Hash the label. */
  1209. /* This has already been done. */
  1210. /* Step 3b: Separate the encoded message. */
  1211. masked_seed = frame + 1;
  1212. masked_db = frame + 1 + hlen;
  1213. db_len = nframe - 1 - hlen;
  1214. /* Step 3c and 3d: seed = maskedSeed ^ mgf(maskedDB, hlen). */
  1215. if (mgf1 (seed, hlen, masked_db, db_len, algo))
  1216. failed = 1;
  1217. for (n = 0; n < hlen; n++)
  1218. seed[n] ^= masked_seed[n];
  1219. /* Step 3e and 3f: db = maskedDB ^ mgf(seed, db_len). */
  1220. if (mgf1 (db, db_len, seed, hlen, algo))
  1221. failed = 1;
  1222. for (n = 0; n < db_len; n++)
  1223. db[n] ^= masked_db[n];
  1224. /* Step 3g: Check lhash, an possible empty padding string terminated
  1225. by 0x01 and the first byte of EM being 0. */
  1226. if (memcmp (lhash, db, hlen))
  1227. failed = 1;
  1228. for (n = hlen; n < db_len; n++)
  1229. if (db[n] == 0x01)
  1230. break;
  1231. if (n == db_len)
  1232. failed = 1;
  1233. if (frame[0])
  1234. failed = 1;
  1235. gcry_free (lhash);
  1236. gcry_free (frame);
  1237. if (failed)
  1238. {
  1239. gcry_free (seed);
  1240. return GPG_ERR_ENCODING_PROBLEM;
  1241. }
  1242. /* Step 4: Output M. */
  1243. /* To avoid an extra allocation we reuse the seed buffer. The only
  1244. caller of this function will anyway free the result soon. */
  1245. n++;
  1246. memmove (seed, db + n, db_len - n);
  1247. *r_result = seed;
  1248. *r_resultlen = db_len - n;
  1249. seed = NULL;
  1250. if (DBG_CIPHER)
  1251. log_printhex ("value extracted from OAEP encoded data:",
  1252. *r_result, *r_resultlen);
  1253. return 0;
  1254. }
  1255. /* RFC-3447 (pkcs#1 v2.1) PSS encoding. Encode {VALUE,VALUELEN} for
  1256. an NBITS key. Note that VALUE is already the mHash from the
  1257. picture below. ALGO is a valid hash algorithm and SALTLEN is the
  1258. length of salt to be used. On success the result is stored as a
  1259. new MPI at R_RESULT. On error the value at R_RESULT is undefined.
  1260. If {RANDOM_OVERRIDE, RANDOM_OVERRIDE_LEN} is given it is used as
  1261. the salt instead of using a random string for the salt. This
  1262. feature is only useful for regression tests.
  1263. Here is figure 2 from the RFC (errata 595 applied) depicting the
  1264. process:
  1265. +-----------+
  1266. | M |
  1267. +-----------+
  1268. |
  1269. V
  1270. Hash
  1271. |
  1272. V
  1273. +--------+----------+----------+
  1274. M' = |Padding1| mHash | salt |
  1275. +--------+----------+----------+
  1276. |
  1277. +--------+----------+ V
  1278. DB = |Padding2| salt | Hash
  1279. +--------+----------+ |
  1280. | |
  1281. V | +----+
  1282. xor <--- MGF <---| |0xbc|
  1283. | | +----+
  1284. | | |
  1285. V V V
  1286. +-------------------+----------+----+
  1287. EM = | maskedDB | H |0xbc|
  1288. +-------------------+----------+----+
  1289. */
  1290. static gcry_err_code_t
  1291. pss_encode (gcry_mpi_t *r_result, unsigned int nbits, int algo,
  1292. const unsigned char *value, size_t valuelen, int saltlen,
  1293. const void *random_override, size_t random_override_len)
  1294. {
  1295. gcry_err_code_t rc = 0;
  1296. gcry_error_t err;
  1297. size_t hlen; /* Length of the hash digest. */
  1298. unsigned char *em = NULL; /* Encoded message. */
  1299. size_t emlen = (nbits+7)/8; /* Length in bytes of EM. */
  1300. unsigned char *h; /* Points into EM. */
  1301. unsigned char *buf = NULL; /* Help buffer. */
  1302. size_t buflen; /* Length of BUF. */
  1303. unsigned char *mhash; /* Points into BUF. */
  1304. unsigned char *salt; /* Points into BUF. */
  1305. unsigned char *dbmask; /* Points into BUF. */
  1306. unsigned char *p;
  1307. size_t n;
  1308. /* This code is implemented as described by rfc-3447 9.1.1. */
  1309. /* Get the length of the digest. */
  1310. hlen = gcry_md_get_algo_dlen (algo);
  1311. gcry_assert (hlen); /* We expect a valid ALGO here. */
  1312. /* Allocate a help buffer and setup some pointers. */
  1313. buflen = 8 + hlen + saltlen + (emlen - hlen - 1);
  1314. buf = gcry_malloc (buflen);
  1315. if (!buf)
  1316. {
  1317. rc = gpg_err_code_from_syserror ();
  1318. goto leave;
  1319. }
  1320. mhash = buf + 8;
  1321. salt = mhash + hlen;
  1322. dbmask= salt + saltlen;
  1323. /* Step 2: That would be: mHash = Hash(M) but our input is already
  1324. mHash thus we do only a consistency check and copy to MHASH. */
  1325. if (valuelen != hlen)
  1326. {
  1327. rc = GPG_ERR_INV_LENGTH;
  1328. goto leave;
  1329. }
  1330. memcpy (mhash, value, hlen);
  1331. /* Step 3: Check length constraints. */
  1332. if (emlen < hlen + saltlen + 2)
  1333. {
  1334. rc = GPG_ERR_TOO_SHORT;
  1335. goto leave;
  1336. }
  1337. /* Allocate space for EM. */
  1338. em = gcry_malloc (emlen);
  1339. if (!em)
  1340. {
  1341. rc = gpg_err_code_from_syserror ();
  1342. goto leave;
  1343. }
  1344. h = em + emlen - 1 - hlen;
  1345. /* Step 4: Create a salt. */
  1346. if (saltlen)
  1347. {
  1348. if (random_override)
  1349. {
  1350. if (random_override_len != saltlen)
  1351. {
  1352. rc = GPG_ERR_INV_ARG;
  1353. goto leave;
  1354. }
  1355. memcpy (salt, random_override, saltlen);
  1356. }
  1357. else
  1358. gcry_randomize (salt, saltlen, GCRY_STRONG_RANDOM);
  1359. }
  1360. /* Step 5 and 6: M' = Hash(Padding1 || mHash || salt). */
  1361. memset (buf, 0, 8); /* Padding. */
  1362. gcry_md_hash_buffer (algo, h, buf, 8 + hlen + saltlen);
  1363. /* Step 7 and 8: DB = PS || 0x01 || salt. */
  1364. /* Note that we use EM to store DB and later Xor in-place. */
  1365. p = em + emlen - 1 - hlen - saltlen - 1;
  1366. memset (em, 0, p - em);
  1367. *p++ = 0x01;
  1368. memcpy (p, salt, saltlen);
  1369. /* Step 9: dbmask = MGF(H, emlen - hlen - 1). */
  1370. mgf1 (dbmask, emlen - hlen - 1, h, hlen, algo);
  1371. /* Step 10: maskedDB = DB ^ dbMask */
  1372. for (n = 0, p = dbmask; n < emlen - hlen - 1; n++, p++)
  1373. em[n] ^= *p;
  1374. /* Step 11: Set the leftmost bits to zero. */
  1375. em[0] &= 0xFF >> (8 * emlen - nbits);
  1376. /* Step 12: EM = maskedDB || H || 0xbc. */
  1377. em[emlen-1] = 0xbc;
  1378. /* Convert EM into an MPI. */
  1379. err = gcry_mpi_scan (r_result, GCRYMPI_FMT_USG, em, emlen, NULL);
  1380. if (err)
  1381. rc = gcry_err_code (err);
  1382. else if (DBG_CIPHER)
  1383. log_mpidump ("PSS encoded data", *r_result);
  1384. leave:
  1385. if (em)
  1386. {
  1387. wipememory (em, emlen);
  1388. gcry_free (em);
  1389. }
  1390. if (buf)
  1391. {
  1392. wipememory (buf, buflen);
  1393. gcry_free (buf);
  1394. }
  1395. return rc;
  1396. }
  1397. /* Verify a signature assuming PSS padding. VALUE is the hash of the
  1398. message (mHash) encoded as an MPI; its length must match the digest
  1399. length of ALGO. ENCODED is the output of the RSA public key
  1400. function (EM). NBITS is the size of the public key. ALGO is the
  1401. hash algorithm and SALTLEN is the length of the used salt. The
  1402. function returns 0 on success or on error code. */
  1403. static gcry_err_code_t
  1404. pss_verify (gcry_mpi_t value, gcry_mpi_t encoded, unsigned int nbits, int algo,
  1405. size_t saltlen)
  1406. {
  1407. gcry_err_code_t rc = 0;
  1408. size_t hlen; /* Length of the hash digest. */
  1409. unsigned char *em = NULL; /* Encoded message. */
  1410. size_t emlen = (nbits+7)/8; /* Length in bytes of EM. */
  1411. unsigned char *salt; /* Points into EM. */
  1412. unsigned char *h; /* Points into EM. */
  1413. unsigned char *buf = NULL; /* Help buffer. */
  1414. size_t buflen; /* Length of BUF. */
  1415. unsigned char *dbmask; /* Points into BUF. */
  1416. unsigned char *mhash; /* Points into BUF. */
  1417. unsigned char *p;
  1418. size_t n;
  1419. /* This code is implemented as described by rfc-3447 9.1.2. */
  1420. /* Get the length of the digest. */
  1421. hlen = gcry_md_get_algo_dlen (algo);
  1422. gcry_assert (hlen); /* We expect a valid ALGO here. */
  1423. /* Allocate a help buffer and setup some pointers.
  1424. This buffer is used for two purposes:
  1425. +------------------------------+-------+
  1426. 1. | dbmask | mHash |
  1427. +------------------------------+-------+
  1428. emlen - hlen - 1 hlen
  1429. +----------+-------+---------+-+-------+
  1430. 2. | padding1 | mHash | salt | | mHash |
  1431. +----------+-------+---------+-+-------+
  1432. 8 hlen saltlen hlen
  1433. */
  1434. buflen = 8 + hlen + saltlen;
  1435. if (buflen < emlen - hlen - 1)
  1436. buflen = emlen - hlen - 1;
  1437. buflen += hlen;
  1438. buf = gcry_malloc (buflen);
  1439. if (!buf)
  1440. {
  1441. rc = gpg_err_code_from_syserror ();
  1442. goto leave;
  1443. }
  1444. dbmask = buf;
  1445. mhash = buf + buflen - hlen;
  1446. /* Step 2: That would be: mHash = Hash(M) but our input is already
  1447. mHash thus we only need to convert VALUE into MHASH. */
  1448. rc = octet_string_from_mpi (NULL, mhash, value, hlen);
  1449. if (rc)
  1450. goto leave;
  1451. /* Convert the signature into an octet string. */
  1452. rc = octet_string_from_mpi (&em, NULL, encoded, emlen);
  1453. if (rc)
  1454. goto leave;
  1455. /* Step 3: Check length of EM. Because we internally use MPI
  1456. functions we can't do this properly; EMLEN is always the length
  1457. of the key because octet_string_from_mpi needs to left pad the
  1458. result with zero to cope with the fact that our MPIs suppress all
  1459. leading zeroes. Thus what we test here are merely the digest and
  1460. salt lengths to the key. */
  1461. if (emlen < hlen + saltlen + 2)
  1462. {
  1463. rc = GPG_ERR_TOO_SHORT; /* For the hash and saltlen. */
  1464. goto leave;
  1465. }
  1466. /* Step 4: Check last octet. */
  1467. if (em[emlen - 1] != 0xbc)
  1468. {
  1469. rc = GPG_ERR_BAD_SIGNATURE;
  1470. goto leave;
  1471. }
  1472. /* Step 5: Split EM. */
  1473. h = em + emlen - 1 - hlen;
  1474. /* Step 6: Check the leftmost bits. */
  1475. if ((em[0] & ~(0xFF >> (8 * emlen - nbits))))
  1476. {
  1477. rc = GPG_ERR_BAD_SIGNATURE;
  1478. goto leave;
  1479. }
  1480. /* Step 7: dbmask = MGF(H, emlen - hlen - 1). */
  1481. mgf1 (dbmask, emlen - hlen - 1, h, hlen, algo);
  1482. /* Step 8: maskedDB = DB ^ dbMask. */
  1483. for (n = 0, p = dbmask; n < emlen - hlen - 1; n++, p++)
  1484. em[n] ^= *p;
  1485. /* Step 9: Set leftmost bits in DB to zero. */
  1486. em[0] &= 0xFF >> (8 * emlen - nbits);
  1487. /* Step 10: Check the padding of DB. */
  1488. for (n = 0; n < emlen - hlen - saltlen - 2 && !em[n]; n++)
  1489. ;
  1490. if (n != emlen - hlen - saltlen - 2 || em[n++] != 1)
  1491. {
  1492. rc = GPG_ERR_BAD_SIGNATURE;
  1493. goto leave;
  1494. }
  1495. /* Step 11: Extract salt from DB. */
  1496. salt = em + n;
  1497. /* Step 12: M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt */
  1498. memset (buf, 0, 8);
  1499. memcpy (buf+8, mhash, hlen);
  1500. memcpy (buf+8+hlen, salt, saltlen);
  1501. /* Step 13: H' = Hash(M'). */
  1502. gcry_md_hash_buffer (algo, buf, buf, 8 + hlen + saltlen);
  1503. /* Step 14: Check H == H'. */
  1504. rc = memcmp (h, buf, hlen) ? GPG_ERR_BAD_SIGNATURE : GPG_ERR_NO_ERROR;
  1505. leave:
  1506. if (em)
  1507. {
  1508. wipememory (em, emlen);
  1509. gcry_free (em);
  1510. }
  1511. if (buf)
  1512. {
  1513. wipememory (buf, buflen);
  1514. gcry_free (buf);
  1515. }
  1516. return rc;
  1517. }
  1518. /* Callback for the pubkey algorithm code to verify PSS signatures.
  1519. OPAQUE is the data provided by the actual caller. The meaning of
  1520. TMP depends on the actual algorithm (but there is only RSA); now
  1521. for RSA it is the output of running the public key function on the
  1522. input. */
  1523. static int
  1524. pss_verify_cmp (void *opaque, gcry_mpi_t tmp)
  1525. {
  1526. struct pk_encoding_ctx *ctx = opaque;
  1527. gcry_mpi_t hash = ctx->verify_arg;
  1528. return pss_verify (hash, tmp, ctx->nbits - 1, ctx->hash_algo, ctx->saltlen);
  1529. }
  1530. /* Internal function. */
  1531. static gcry_err_code_t
  1532. sexp_elements_extract (gcry_sexp_t key_sexp, const char *element_names,
  1533. gcry_mpi_t *elements, const char *algo_name)
  1534. {
  1535. gcry_err_code_t err = 0;
  1536. int i, idx;
  1537. const char *name;
  1538. gcry_sexp_t list;
  1539. for (name = element_names, idx = 0; *name && !err; name++, idx++)
  1540. {
  1541. list = gcry_sexp_find_token (key_sexp, name, 1);
  1542. if (!list)
  1543. elements[idx] = NULL;
  1544. else
  1545. {
  1546. elements[idx] = gcry_sexp_nth_mpi (list, 1, GCRYMPI_FMT_USG);
  1547. gcry_sexp_release (list);
  1548. if (!elements[idx])
  1549. err = GPG_ERR_INV_OBJ;
  1550. }
  1551. }
  1552. if (!err)
  1553. {
  1554. /* Check that all elements are available. */
  1555. for (name = element_names, idx = 0; *name; name++, idx++)
  1556. if (!elements[idx])
  1557. break;
  1558. if (*name)
  1559. {
  1560. err = GPG_ERR_NO_OBJ;
  1561. /* Some are missing. Before bailing out we test for
  1562. optional parameters. */
  1563. if (algo_name && !strcmp (algo_name, "RSA")
  1564. && !strcmp (element_names, "nedpqu") )
  1565. {
  1566. /* This is RSA. Test whether we got N, E and D and that
  1567. the optional P, Q and U are all missing. */
  1568. if (elements[0] && elements[1] && elements[2]
  1569. && !elements[3] && !elements[4] && !elements[5])
  1570. err = 0;
  1571. }
  1572. }
  1573. }
  1574. if (err)
  1575. {
  1576. for (i = 0; i < idx; i++)
  1577. if (elements[i])
  1578. gcry_free (elements[i]);
  1579. }
  1580. return err;
  1581. }
  1582. /* Internal function used for ecc. Note, that this function makes use
  1583. of its intimate knowledge about the ECC parameters from ecc.c. */
  1584. static gcry_err_code_t
  1585. sexp_elements_extract_ecc (gcry_sexp_t key_sexp, const char *element_names,
  1586. gcry_mpi_t *elements, pk_extra_spec_t *extraspec)
  1587. {
  1588. gcry_err_code_t err = 0;
  1589. int idx;
  1590. const char *name;
  1591. gcry_sexp_t list;
  1592. /* Clear the array for easier error cleanup. */
  1593. for (name = element_names, idx = 0; *name; name++, idx++)
  1594. elements[idx] = NULL;
  1595. gcry_assert (idx >= 5); /* We know that ECC has at least 5 elements
  1596. (params only) or 6 (full public key). */
  1597. if (idx == 5)
  1598. elements[5] = NULL; /* Extra clear for the params only case. */
  1599. /* Init the array with the available curve parameters. */
  1600. for (name = element_names, idx = 0; *name && !err; name++, idx++)
  1601. {
  1602. list = gcry_sexp_find_token (key_sexp, name, 1);
  1603. if (!list)
  1604. elements[idx] = NULL;
  1605. else
  1606. {
  1607. elements[idx] = gcry_sexp_nth_mpi (list, 1, GCRYMPI_FMT_USG);
  1608. gcry_sexp_release (list);
  1609. if (!elements[idx])
  1610. {
  1611. err = GPG_ERR_INV_OBJ;
  1612. goto leave;
  1613. }
  1614. }
  1615. }
  1616. /* Check whether a curve parameter has been given and then fill any
  1617. missing elements. */
  1618. list = gcry_sexp_find_token (key_sexp, "curve", 5);
  1619. if (list)
  1620. {
  1621. if (extraspec->get_param)
  1622. {
  1623. char *curve;
  1624. gcry_mpi_t params[6];
  1625. for (idx = 0; idx < DIM(params); idx++)
  1626. params[idx] = NULL;
  1627. curve = _gcry_sexp_nth_string (list, 1);
  1628. gcry_sexp_release (list);
  1629. if (!curve)
  1630. {
  1631. /* No curve name given (or out of core). */
  1632. err = GPG_ERR_INV_OBJ;
  1633. goto leave;
  1634. }
  1635. err = extraspec->get_param (curve, params);
  1636. gcry_free (curve);
  1637. if (err)
  1638. goto leave;
  1639. for (idx = 0; idx < DIM(params); idx++)
  1640. {
  1641. if (!elements[idx])
  1642. elements[idx] = params[idx];
  1643. else
  1644. mpi_free (params[idx]);
  1645. }
  1646. }
  1647. else
  1648. {
  1649. gcry_sexp_release (list);
  1650. err = GPG_ERR_INV_OBJ; /* "curve" given but ECC not supported. */
  1651. goto leave;
  1652. }
  1653. }
  1654. /* Check that all parameters are known. */
  1655. for (name = element_names, idx = 0; *name; name++, idx++)
  1656. if (!elements[idx])
  1657. {
  1658. err = GPG_ERR_NO_OBJ;
  1659. goto leave;
  1660. }
  1661. leave:
  1662. if (err)
  1663. {
  1664. for (name = element_names, idx = 0; *name; name++, idx++)
  1665. if (elements[idx])
  1666. gcry_free (elements[idx]);
  1667. }
  1668. return err;
  1669. }
  1670. /****************
  1671. * Convert a S-Exp with either a private or a public key to our
  1672. * internal format. Currently we do only support the following
  1673. * algorithms:
  1674. * dsa
  1675. * rsa
  1676. * openpgp-dsa
  1677. * openpgp-rsa
  1678. * openpgp-elg
  1679. * openpgp-elg-sig
  1680. * ecdsa
  1681. * ecdh
  1682. * Provide a SE with the first element be either "private-key" or
  1683. * or "public-key". It is followed by a list with its first element
  1684. * be one of the above algorithm identifiers and the remaning
  1685. * elements are pairs with parameter-id and value.
  1686. * NOTE: we look through the list to find a list beginning with
  1687. * "private-key" or "public-key" - the first one found is used.
  1688. *
  1689. * If OVERRIDE_ELEMS is not NULL those elems override the parameter
  1690. * specification taken from the module. This ise used by
  1691. * gcry_pk_get_curve.
  1692. *
  1693. * Returns: A pointer to an allocated array of MPIs if the return value is
  1694. * zero; the caller has to release this array.
  1695. *
  1696. * Example of a DSA public key:
  1697. * (private-key
  1698. * (dsa
  1699. * (p <mpi>)
  1700. * (g <mpi>)
  1701. * (y <mpi>)
  1702. * (x <mpi>)
  1703. * )
  1704. * )
  1705. * The <mpi> are expected to be in GCRYMPI_FMT_USG
  1706. */
  1707. static gcry_err_code_t
  1708. sexp_to_key (gcry_sexp_t sexp, int want_private, const char *override_elems,
  1709. gcry_mpi_t **retarray, gcry_module_t *retalgo)
  1710. {
  1711. gcry_err_code_t err = 0;
  1712. gcry_sexp_t list, l2;
  1713. char *name;
  1714. const char *elems;
  1715. gcry_mpi_t *array;
  1716. gcry_module_t module;
  1717. gcry_pk_spec_t *pubkey;
  1718. pk_extra_spec_t *extraspec;
  1719. int is_ecc;
  1720. /* Check that the first element is valid. */
  1721. list = gcry_sexp_find_token (sexp,
  1722. want_private? "private-key":"public-key", 0);
  1723. if (!list)
  1724. return GPG_ERR_INV_OBJ; /* Does not contain a key object. */
  1725. l2 = gcry_sexp_cadr( list );
  1726. gcry_sexp_release ( list );
  1727. list = l2;
  1728. name = _gcry_sexp_nth_string (list, 0);
  1729. if (!name)
  1730. {
  1731. gcry_sexp_release ( list );
  1732. return GPG_ERR_INV_OBJ; /* Invalid structure of object. */
  1733. }
  1734. ath_mutex_lock (&pubkeys_registered_lock);
  1735. module = gcry_pk_lookup_name (name);
  1736. ath_mutex_unlock (&pubkeys_registered_lock);
  1737. /* Fixme: We should make sure that an ECC key is always named "ecc"
  1738. and not "ecdsa". "ecdsa" should be used for the signature
  1739. itself. We need a function to test whether an algorithm given
  1740. with a key is compatible with an application of the key (signing,
  1741. encryption). For RSA this is easy, but ECC is the first
  1742. algorithm which has many flavours. */
  1743. is_ecc = ( !strcmp (name, "ecdsa")
  1744. || !strcmp (name, "ecdh")
  1745. || !strcmp (name, "ecc") );
  1746. gcry_free (name);
  1747. if (!module)
  1748. {
  1749. gcry_sexp_release (list);
  1750. return GPG_ERR_PUBKEY_ALGO; /* Unknown algorithm. */
  1751. }
  1752. else
  1753. {
  1754. pubkey = (gcry_pk_spec_t *) module->spec;
  1755. extraspec = module->extraspec;
  1756. }
  1757. if (override_elems)
  1758. elems = override_elems;
  1759. else if (want_private)
  1760. elems = pubkey->elements_skey;
  1761. else
  1762. elems = pubkey->elements_pkey;
  1763. array = gcry_calloc (strlen (elems) + 1, sizeof (*array));
  1764. if (!array)
  1765. err = gpg_err_code_from_syserror ();
  1766. if (!err)
  1767. {
  1768. if (is_ecc)
  1769. err = sexp_elements_extract_ecc (list, elems, array, extraspec);
  1770. else
  1771. err = sexp_elements_extract (list, elems, array, pubkey->name);
  1772. }
  1773. gcry_sexp_release (list);
  1774. if (err)
  1775. {
  1776. gcry_free (array);
  1777. ath_mutex_lock (&pubkeys_registered_lock);
  1778. _gcry_module_release (module);
  1779. ath_mutex_unlock (&pubkeys_registered_lock);
  1780. }
  1781. else
  1782. {
  1783. *retarray = array;
  1784. *retalgo = module;
  1785. }
  1786. return err;
  1787. }
  1788. static gcry_err_code_t
  1789. sexp_to_sig (gcry_sexp_t sexp, gcry_mpi_t **retarray,
  1790. gcry_module_t *retalgo)
  1791. {
  1792. gcry_err_code_t err = 0;
  1793. gcry_sexp_t list, l2;
  1794. char *name;
  1795. const char *elems;
  1796. gcry_mpi_t *array;
  1797. gcry_module_t module;
  1798. gcry_pk_spec_t *pubkey;
  1799. /* Check that the first element is valid. */
  1800. list = gcry_sexp_find_token( sexp, "sig-val" , 0 );
  1801. if (!list)
  1802. return GPG_ERR_INV_OBJ; /* Does not contain a signature value object. */
  1803. l2 = gcry_sexp_nth (list, 1);
  1804. if (!l2)
  1805. {
  1806. gcry_sexp_release (list);
  1807. return GPG_ERR_NO_OBJ; /* No cadr for the sig object. */
  1808. }
  1809. name = _gcry_sexp_nth_string (l2, 0);
  1810. if (!name)
  1811. {
  1812. gcry_sexp_release (list);
  1813. gcry_sexp_release (l2);
  1814. return GPG_ERR_INV_OBJ; /* Invalid structure of object. */
  1815. }
  1816. else if (!strcmp (name, "flags"))
  1817. {
  1818. /* Skip flags, since they are not used but here just for the
  1819. sake of consistent S-expressions. */
  1820. gcry_free (name);
  1821. gcry_sexp_release (l2);
  1822. l2 = gcry_sexp_nth (list, 2);
  1823. if (!l2)
  1824. {
  1825. gcry_sexp_release (list);
  1826. return GPG_ERR_INV_OBJ;
  1827. }
  1828. name = _gcry_sexp_nth_string (l2, 0);
  1829. }
  1830. ath_mutex_lock (&pubkeys_registered_lock);
  1831. module = gcry_pk_lookup_name (name);
  1832. ath_mutex_unlock (&pubkeys_registered_lock);
  1833. gcry_free (name);
  1834. name = NULL;
  1835. if (!module)
  1836. {
  1837. gcry_sexp_release (l2);
  1838. gcry_sexp_release (list);
  1839. return GPG_ERR_PUBKEY_ALGO; /* Unknown algorithm. */
  1840. }
  1841. else
  1842. pubkey = (gcry_pk_spec_t *) module->spec;
  1843. elems = pubkey->elements_sig;
  1844. array = gcry_calloc (strlen (elems) + 1 , sizeof *array );
  1845. if (!array)
  1846. err = gpg_err_code_from_syserror ();
  1847. if (!err)
  1848. err = sexp_elements_extract (list, elems, array, NULL);
  1849. gcry_sexp_release (l2);
  1850. gcry_sexp_release (list);
  1851. if (err)
  1852. {
  1853. ath_mutex_lock (&pubkeys_registered_lock);
  1854. _gcry_module_release (module);
  1855. ath_mutex_unlock (&pubkeys_registered_lock);
  1856. gcry_free (array);
  1857. }
  1858. else
  1859. {
  1860. *retarray = array;
  1861. *retalgo = module;
  1862. }
  1863. return err;
  1864. }
  1865. static inline int
  1866. get_hash_algo (const char *s, size_t n)
  1867. {
  1868. static const struct { const char *name; int algo; } hashnames[] = {
  1869. { "sha1", GCRY_MD_SHA1 },
  1870. { "md5", GCRY_MD_MD5 },
  1871. { "sha256", GCRY_MD_SHA256 },
  1872. { "ripemd160", GCRY_MD_RMD160 },
  1873. { "rmd160", GCRY_MD_RMD160 },
  1874. { "sha384", GCRY_MD_SHA384 },
  1875. { "sha512", GCRY_MD_SHA512 },
  1876. { "sha224", GCRY_MD_SHA224 },
  1877. { "md2", GCRY_MD_MD2 },
  1878. { "md4", GCRY_MD_MD4 },
  1879. { "tiger", GCRY_MD_TIGER },
  1880. { "haval", GCRY_MD_HAVAL },
  1881. { NULL, 0 }
  1882. };
  1883. int algo;
  1884. int i;
  1885. for (i=0; hashnames[i].name; i++)
  1886. {
  1887. if ( strlen (hashnames[i].name) == n
  1888. && !memcmp (hashnames[i].name, s, n))
  1889. break;
  1890. }
  1891. if (hashnames[i].name)
  1892. algo = hashnames[i].algo;
  1893. else
  1894. {
  1895. /* In case of not listed or dynamically allocated hash
  1896. algorithm we fall back to this somewhat slower
  1897. method. Further, it also allows to use OIDs as
  1898. algorithm names. */
  1899. char *tmpname;
  1900. tmpname = gcry_malloc (n+1);
  1901. if (!tmpname)
  1902. algo = 0; /* Out of core - silently give up. */
  1903. else
  1904. {
  1905. memcpy (tmpname, s, n);
  1906. tmpname[n] = 0;
  1907. algo = gcry_md_map_name (tmpname);
  1908. gcry_free (tmpname);
  1909. }
  1910. }
  1911. return algo;
  1912. }
  1913. /****************
  1914. * Take sexp and return an array of MPI as used for our internal decrypt
  1915. * function.
  1916. * s_data = (enc-val
  1917. * [(flags [raw, pkcs1, oaep, no-blinding])]
  1918. * [(hash-algo <algo>)]
  1919. * [(label <label>)]
  1920. * (<algo>
  1921. * (<param_name1> <mpi>)
  1922. * ...
  1923. * (<param_namen> <mpi>)
  1924. * ))
  1925. * HASH-ALGO and LABEL are specific to OAEP.
  1926. * RET_MODERN is set to true when at least an empty flags list has been found.
  1927. * CTX is used to return encoding information; it may be NULL in which
  1928. * case raw encoding is used.
  1929. */
  1930. static gcry_err_code_t
  1931. sexp_to_enc (gcry_sexp_t sexp, gcry_mpi_t **retarray, gcry_module_t *retalgo,
  1932. int *ret_modern, int *flags, struct pk_encoding_ctx *ctx)
  1933. {
  1934. gcry_err_code_t err = 0;
  1935. gcry_sexp_t list = NULL, l2 = NULL;
  1936. gcry_pk_spec_t *pubkey = NULL;
  1937. gcry_module_t module = NULL;
  1938. char *name = NULL;
  1939. size_t n;
  1940. int parsed_flags = 0;
  1941. const char *elems;
  1942. gcry_mpi_t *array = NULL;
  1943. *ret_modern = 0;
  1944. /* Check that the first element is valid. */
  1945. list = gcry_sexp_find_token (sexp, "enc-val" , 0);
  1946. if (!list)
  1947. {
  1948. err = GPG_ERR_INV_OBJ; /* Does not contain an encrypted value object. */
  1949. goto leave;
  1950. }
  1951. l2 = gcry_sexp_nth (list, 1);
  1952. if (!l2)
  1953. {
  1954. err = GPG_ERR_NO_OBJ; /* No cdr for the data object. */
  1955. goto leave;
  1956. }
  1957. /* Extract identifier of sublist. */
  1958. name = _gcry_sexp_nth_string (l2, 0);
  1959. if (!name)
  1960. {
  1961. err = GPG_ERR_INV_OBJ; /* Invalid structure of object. */
  1962. goto leave;
  1963. }
  1964. if (!strcmp (name, "flags"))
  1965. {
  1966. /* There is a flags element - process it. */
  1967. const char *s;
  1968. int i;
  1969. *ret_modern = 1;
  1970. for (i = gcry_sexp_length (l2) - 1; i > 0; i--)
  1971. {
  1972. s = gcry_sexp_nth_data (l2, i, &n);
  1973. if (! s)
  1974. ; /* Not a data element - ignore. */
  1975. else if (n == 3 && !memcmp (s, "raw", 3)
  1976. && ctx->encoding == PUBKEY_ENC_UNKNOWN)
  1977. ctx->encoding = PUBKEY_ENC_RAW;
  1978. else if (n == 5 && !memcmp (s, "pkcs1", 5)
  1979. && ctx->encoding == PUBKEY_ENC_UNKNOWN)
  1980. ctx->encoding = PUBKEY_ENC_PKCS1;
  1981. else if (n == 4 && !memcmp (s, "oaep", 4)
  1982. && ctx->encoding == PUBKEY_ENC_UNKNOWN)
  1983. ctx->encoding = PUBKEY_ENC_OAEP;
  1984. else if (n == 3 && !memcmp (s, "pss", 3)
  1985. && ctx->encoding == PUBKEY_ENC_UNKNOWN)
  1986. {
  1987. err = GPG_ERR_CONFLICT;
  1988. goto leave;
  1989. }
  1990. else if (n == 11 && ! memcmp (s, "no-blinding", 11))
  1991. parsed_flags |= PUBKEY_FLAG_NO_BLINDING;
  1992. else
  1993. {
  1994. err = GPG_ERR_INV_FLAG;
  1995. goto leave;
  1996. }
  1997. }
  1998. gcry_sexp_release (l2);
  1999. /* Get the OAEP parameters HASH-ALGO and LABEL, if any. */
  2000. if (ctx->encoding == PUBKEY_ENC_OAEP)
  2001. {
  2002. /* Get HASH-ALGO. */
  2003. l2 = gcry_sexp_find_token (list, "hash-algo", 0);
  2004. if (l2)
  2005. {
  2006. s = gcry_sexp_nth_data (l2, 1, &n);
  2007. if (!s)
  2008. err = GPG_ERR_NO_OBJ;
  2009. else
  2010. {
  2011. ctx->hash_algo = get_hash_algo (s, n);
  2012. if (!ctx->hash_algo)
  2013. err = GPG_ERR_DIGEST_ALGO;
  2014. }
  2015. gcry_sexp_release (l2);
  2016. if (err)
  2017. goto leave;
  2018. }
  2019. /* Get LABEL. */
  2020. l2 = gcry_sexp_find_token (list, "label", 0);
  2021. if (l2)
  2022. {
  2023. s = gcry_sexp_nth_data (l2, 1, &n);
  2024. if (!s)
  2025. err = GPG_ERR_NO_OBJ;
  2026. else if (n > 0)
  2027. {
  2028. ctx->label = gcry_malloc (n);
  2029. if (!ctx->label)
  2030. err = gpg_err_code_from_syserror ();
  2031. else
  2032. {
  2033. memcpy (ctx->label, s, n);
  2034. ctx->labellen = n;
  2035. }
  2036. }
  2037. gcry_sexp_release (l2);
  2038. if (err)
  2039. goto leave;
  2040. }
  2041. }
  2042. /* Get the next which has the actual data - skip HASH-ALGO and LABEL. */
  2043. for (i = 2; (l2 = gcry_sexp_nth (list, i)) != NULL; i++)
  2044. {
  2045. s = gcry_sexp_nth_data (l2, 0, &n);
  2046. if (!(n == 9 && !memcmp (s, "hash-algo", 9))
  2047. && !(n == 5 && !memcmp (s, "label", 5))
  2048. && !(n == 15 && !memcmp (s, "random-override", 15)))
  2049. break;
  2050. gcry_sexp_release (l2);
  2051. }
  2052. if (!l2)
  2053. {
  2054. err = GPG_ERR_NO_OBJ; /* No cdr for the data object. */
  2055. goto leave;
  2056. }
  2057. /* Extract sublist identifier. */
  2058. gcry_free (name);
  2059. name = _gcry_sexp_nth_string (l2, 0);
  2060. if (!name)
  2061. {
  2062. err = GPG_ERR_INV_OBJ; /* Invalid structure of object. */
  2063. goto leave;
  2064. }
  2065. gcry_sexp_release (list);
  2066. list = l2;
  2067. l2 = NULL;
  2068. }
  2069. ath_mutex_lock (&pubkeys_registered_lock);
  2070. module = gcry_pk_lookup_name (name);
  2071. ath_mutex_unlock (&pubkeys_registered_lock);
  2072. if (!module)
  2073. {
  2074. err = GPG_ERR_PUBKEY_ALGO; /* Unknown algorithm. */
  2075. goto leave;
  2076. }
  2077. pubkey = (gcry_pk_spec_t *) module->spec;
  2078. elems = pubkey->elements_enc;
  2079. array = gcry_calloc (strlen (elems) + 1, sizeof (*array));
  2080. if (!array)
  2081. {
  2082. err = gpg_err_code_from_syserror ();
  2083. goto leave;
  2084. }
  2085. err = sexp_elements_extract (list, elems, array, NULL);
  2086. leave:
  2087. gcry_sexp_release (list);
  2088. gcry_sexp_release (l2);
  2089. gcry_free (name);
  2090. if (err)
  2091. {
  2092. ath_mutex_lock (&pubkeys_registered_lock);
  2093. _gcry_module_release (module);
  2094. ath_mutex_unlock (&pubkeys_registered_lock);
  2095. gcry_free (array);
  2096. gcry_free (ctx->label);
  2097. ctx->label = NULL;
  2098. }
  2099. else
  2100. {
  2101. *retarray = array;
  2102. *retalgo = module;
  2103. *flags = parsed_flags;
  2104. }
  2105. return err;
  2106. }
  2107. /* Take the hash value and convert into an MPI, suitable for
  2108. passing to the low level functions. We currently support the
  2109. old style way of passing just a MPI and the modern interface which
  2110. allows to pass flags so that we can choose between raw and pkcs1
  2111. padding - may be more padding options later.
  2112. (<mpi>)
  2113. or
  2114. (data
  2115. [(flags [raw, pkcs1, oaep, pss, no-blinding])]
  2116. [(hash <algo> <value>)]
  2117. [(value <text>)]
  2118. [(hash-algo <algo>)]
  2119. [(label <label>)]
  2120. [(salt-length <length>)]
  2121. [(random-override <data>)]
  2122. )
  2123. Either the VALUE or the HASH element must be present for use
  2124. with signatures. VALUE is used for encryption.
  2125. HASH-ALGO and LABEL are specific to OAEP.
  2126. SALT-LENGTH is for PSS.
  2127. RANDOM-OVERRIDE is used to replace random nonces for regression
  2128. testing. */
  2129. static gcry_err_code_t
  2130. sexp_data_to_mpi (gcry_sexp_t input, gcry_mpi_t *ret_mpi,
  2131. struct pk_encoding_ctx *ctx)
  2132. {
  2133. gcry_err_code_t rc = 0;
  2134. gcry_sexp_t ldata, lhash, lvalue;
  2135. int i;
  2136. size_t n;
  2137. const char *s;
  2138. int unknown_flag=0;
  2139. int parsed_flags = 0;
  2140. *ret_mpi = NULL;
  2141. ldata = gcry_sexp_find_token (input, "data", 0);
  2142. if (!ldata)
  2143. { /* assume old style */
  2144. *ret_mpi = gcry_sexp_nth_mpi (input, 0, 0);
  2145. return *ret_mpi ? GPG_ERR_NO_ERROR : GPG_ERR_INV_OBJ;
  2146. }
  2147. /* see whether there is a flags object */
  2148. {
  2149. gcry_sexp_t lflags = gcry_sexp_find_token (ldata, "flags", 0);
  2150. if (lflags)
  2151. { /* parse the flags list. */
  2152. for (i=gcry_sexp_length (lflags)-1; i > 0; i--)
  2153. {
  2154. s = gcry_sexp_nth_data (lflags, i, &n);
  2155. if (!s)
  2156. ; /* not a data element*/
  2157. else if ( n == 3 && !memcmp (s, "raw", 3)
  2158. && ctx->encoding == PUBKEY_ENC_UNKNOWN)
  2159. ctx->encoding = PUBKEY_ENC_RAW;
  2160. else if ( n == 5 && !memcmp (s, "pkcs1", 5)
  2161. && ctx->encoding == PUBKEY_ENC_UNKNOWN)
  2162. ctx->encoding = PUBKEY_ENC_PKCS1;
  2163. else if ( n == 4 && !memcmp (s, "oaep", 4)
  2164. && ctx->encoding == PUBKEY_ENC_UNKNOWN)
  2165. ctx->encoding = PUBKEY_ENC_OAEP;
  2166. else if ( n == 3 && !memcmp (s, "pss", 3)
  2167. && ctx->encoding == PUBKEY_ENC_UNKNOWN)
  2168. ctx->encoding = PUBKEY_ENC_PSS;
  2169. else if (n == 11 && ! memcmp (s, "no-blinding", 11))
  2170. parsed_flags |= PUBKEY_FLAG_NO_BLINDING;
  2171. else
  2172. unknown_flag = 1;
  2173. }
  2174. gcry_sexp_release (lflags);
  2175. }
  2176. }
  2177. if (ctx->encoding == PUBKEY_ENC_UNKNOWN)
  2178. ctx->encoding = PUBKEY_ENC_RAW; /* default to raw */
  2179. /* Get HASH or MPI */
  2180. lhash = gcry_sexp_find_token (ldata, "hash", 0);
  2181. lvalue = lhash? NULL : gcry_sexp_find_token (ldata, "value", 0);
  2182. if (!(!lhash ^ !lvalue))
  2183. rc = GPG_ERR_INV_OBJ; /* none or both given */
  2184. else if (unknown_flag)
  2185. rc = GPG_ERR_INV_FLAG;
  2186. else if (ctx->encoding == PUBKEY_ENC_RAW && lvalue)
  2187. {
  2188. *ret_mpi = gcry_sexp_nth_mpi (lvalue, 1, GCRYMPI_FMT_USG);
  2189. if (!*ret_mpi)
  2190. rc = GPG_ERR_INV_OBJ;
  2191. }
  2192. else if (ctx->encoding == PUBKEY_ENC_PKCS1 && lvalue
  2193. && ctx->op == PUBKEY_OP_ENCRYPT)
  2194. {
  2195. const void * value;
  2196. size_t valuelen;
  2197. gcry_sexp_t list;
  2198. void *random_override = NULL;
  2199. size_t random_override_len = 0;
  2200. if ( !(value=gcry_sexp_nth_data (lvalue, 1, &valuelen)) || !valuelen )
  2201. rc = GPG_ERR_INV_OBJ;
  2202. else
  2203. {
  2204. /* Get optional RANDOM-OVERRIDE. */
  2205. list = gcry_sexp_find_token (ldata, "random-override", 0);
  2206. if (list)
  2207. {
  2208. s = gcry_sexp_nth_data (list, 1, &n);
  2209. if (!s)
  2210. rc = GPG_ERR_NO_OBJ;
  2211. else if (n > 0)
  2212. {
  2213. random_override = gcry_malloc (n);
  2214. if (!random_override)
  2215. rc = gpg_err_code_from_syserror ();
  2216. else
  2217. {
  2218. memcpy (random_override, s, n);
  2219. random_override_len = n;
  2220. }
  2221. }
  2222. gcry_sexp_release (list);
  2223. if (rc)
  2224. goto leave;
  2225. }
  2226. rc = pkcs1_encode_for_encryption (ret_mpi, ctx->nbits,
  2227. value, valuelen,
  2228. random_override,
  2229. random_override_len);
  2230. gcry_free (random_override);
  2231. }
  2232. }
  2233. else if (ctx->encoding == PUBKEY_ENC_PKCS1 && lhash
  2234. && (ctx->op == PUBKEY_OP_SIGN || ctx->op == PUBKEY_OP_VERIFY))
  2235. {
  2236. if (gcry_sexp_length (lhash) != 3)
  2237. rc = GPG_ERR_INV_OBJ;
  2238. else if ( !(s=gcry_sexp_nth_data (lhash, 1, &n)) || !n )
  2239. rc = GPG_ERR_INV_OBJ;
  2240. else
  2241. {
  2242. const void * value;
  2243. size_t valuelen;
  2244. ctx->hash_algo = get_hash_algo (s, n);
  2245. if (!ctx->hash_algo)
  2246. rc = GPG_ERR_DIGEST_ALGO;
  2247. else if ( !(value=gcry_sexp_nth_data (lhash, 2, &valuelen))
  2248. || !valuelen )
  2249. rc = GPG_ERR_INV_OBJ;
  2250. else
  2251. rc = pkcs1_encode_for_signature (ret_mpi, ctx->nbits,
  2252. value, valuelen,
  2253. ctx->hash_algo);
  2254. }
  2255. }
  2256. else if (ctx->encoding == PUBKEY_ENC_OAEP && lvalue
  2257. && ctx->op == PUBKEY_OP_ENCRYPT)
  2258. {
  2259. const void * value;
  2260. size_t valuelen;
  2261. if ( !(value=gcry_sexp_nth_data (lvalue, 1, &valuelen)) || !valuelen )
  2262. rc = GPG_ERR_INV_OBJ;
  2263. else
  2264. {
  2265. gcry_sexp_t list;
  2266. void *random_override = NULL;
  2267. size_t random_override_len = 0;
  2268. /* Get HASH-ALGO. */
  2269. list = gcry_sexp_find_token (ldata, "hash-algo", 0);
  2270. if (list)
  2271. {
  2272. s = gcry_sexp_nth_data (list, 1, &n);
  2273. if (!s)
  2274. rc = GPG_ERR_NO_OBJ;
  2275. else
  2276. {
  2277. ctx->hash_algo = get_hash_algo (s, n);
  2278. if (!ctx->hash_algo)
  2279. rc = GPG_ERR_DIGEST_ALGO;
  2280. }
  2281. gcry_sexp_release (list);
  2282. if (rc)
  2283. goto leave;
  2284. }
  2285. /* Get LABEL. */
  2286. list = gcry_sexp_find_token (ldata, "label", 0);
  2287. if (list)
  2288. {
  2289. s = gcry_sexp_nth_data (list, 1, &n);
  2290. if (!s)
  2291. rc = GPG_ERR_NO_OBJ;
  2292. else if (n > 0)
  2293. {
  2294. ctx->label = gcry_malloc (n);
  2295. if (!ctx->label)
  2296. rc = gpg_err_code_from_syserror ();
  2297. else
  2298. {
  2299. memcpy (ctx->label, s, n);
  2300. ctx->labellen = n;
  2301. }
  2302. }
  2303. gcry_sexp_release (list);
  2304. if (rc)
  2305. goto leave;
  2306. }
  2307. /* Get optional RANDOM-OVERRIDE. */
  2308. list = gcry_sexp_find_token (ldata, "random-override", 0);
  2309. if (list)
  2310. {
  2311. s = gcry_sexp_nth_data (list, 1, &n);
  2312. if (!s)
  2313. rc = GPG_ERR_NO_OBJ;
  2314. else if (n > 0)
  2315. {
  2316. random_override = gcry_malloc (n);
  2317. if (!random_override)
  2318. rc = gpg_err_code_from_syserror ();
  2319. else
  2320. {
  2321. memcpy (random_override, s, n);
  2322. random_override_len = n;
  2323. }
  2324. }
  2325. gcry_sexp_release (list);
  2326. if (rc)
  2327. goto leave;
  2328. }
  2329. rc = oaep_encode (ret_mpi, ctx->nbits, ctx->hash_algo,
  2330. value, valuelen,
  2331. ctx->label, ctx->labellen,
  2332. random_override, random_override_len);
  2333. gcry_free (random_override);
  2334. }
  2335. }
  2336. else if (ctx->encoding == PUBKEY_ENC_PSS && lhash
  2337. && ctx->op == PUBKEY_OP_SIGN)
  2338. {
  2339. if (gcry_sexp_length (lhash) != 3)
  2340. rc = GPG_ERR_INV_OBJ;
  2341. else if ( !(s=gcry_sexp_nth_data (lhash, 1, &n)) || !n )
  2342. rc = GPG_ERR_INV_OBJ;
  2343. else
  2344. {
  2345. const void * value;
  2346. size_t valuelen;
  2347. void *random_override = NULL;
  2348. size_t random_override_len = 0;
  2349. ctx->hash_algo = get_hash_algo (s, n);
  2350. if (!ctx->hash_algo)
  2351. rc = GPG_ERR_DIGEST_ALGO;
  2352. else if ( !(value=gcry_sexp_nth_data (lhash, 2, &valuelen))
  2353. || !valuelen )
  2354. rc = GPG_ERR_INV_OBJ;
  2355. else
  2356. {
  2357. gcry_sexp_t list;
  2358. /* Get SALT-LENGTH. */
  2359. list = gcry_sexp_find_token (ldata, "salt-length", 0);
  2360. if (list)
  2361. {
  2362. s = gcry_sexp_nth_data (list, 1, &n);
  2363. if (!s)
  2364. {
  2365. rc = GPG_ERR_NO_OBJ;
  2366. goto leave;
  2367. }
  2368. ctx->saltlen = (unsigned int)strtoul (s, NULL, 10);
  2369. gcry_sexp_release (list);
  2370. }
  2371. /* Get optional RANDOM-OVERRIDE. */
  2372. list = gcry_sexp_find_token (ldata, "random-override", 0);
  2373. if (list)
  2374. {
  2375. s = gcry_sexp_nth_data (list, 1, &n);
  2376. if (!s)
  2377. rc = GPG_ERR_NO_OBJ;
  2378. else if (n > 0)
  2379. {
  2380. random_override = gcry_malloc (n);
  2381. if (!random_override)
  2382. rc = gpg_err_code_from_syserror ();
  2383. else
  2384. {
  2385. memcpy (random_override, s, n);
  2386. random_override_len = n;
  2387. }
  2388. }
  2389. gcry_sexp_release (list);
  2390. if (rc)
  2391. goto leave;
  2392. }
  2393. /* Encode the data. (NBITS-1 is due to 8.1.1, step 1.) */
  2394. rc = pss_encode (ret_mpi, ctx->nbits - 1, ctx->hash_algo,
  2395. value, valuelen, ctx->saltlen,
  2396. random_override, random_override_len);
  2397. gcry_free (random_override);
  2398. }
  2399. }
  2400. }
  2401. else if (ctx->encoding == PUBKEY_ENC_PSS && lhash
  2402. && ctx->op == PUBKEY_OP_VERIFY)
  2403. {
  2404. if (gcry_sexp_length (lhash) != 3)
  2405. rc = GPG_ERR_INV_OBJ;
  2406. else if ( !(s=gcry_sexp_nth_data (lhash, 1, &n)) || !n )
  2407. rc = GPG_ERR_INV_OBJ;
  2408. else
  2409. {
  2410. ctx->hash_algo = get_hash_algo (s, n);
  2411. if (!ctx->hash_algo)
  2412. rc = GPG_ERR_DIGEST_ALGO;
  2413. else
  2414. {
  2415. *ret_mpi = gcry_sexp_nth_mpi (lhash, 2, GCRYMPI_FMT_USG);
  2416. if (!*ret_mpi)
  2417. rc = GPG_ERR_INV_OBJ;
  2418. ctx->verify_cmp = pss_verify_cmp;
  2419. ctx->verify_arg = *ret_mpi;
  2420. }
  2421. }
  2422. }
  2423. else
  2424. rc = GPG_ERR_CONFLICT;
  2425. leave:
  2426. gcry_sexp_release (ldata);
  2427. gcry_sexp_release (lhash);
  2428. gcry_sexp_release (lvalue);
  2429. if (!rc)
  2430. ctx->flags = parsed_flags;
  2431. else
  2432. {
  2433. gcry_free (ctx->label);
  2434. ctx->label = NULL;
  2435. }
  2436. return rc;
  2437. }
  2438. static void
  2439. init_encoding_ctx (struct pk_encoding_ctx *ctx, enum pk_operation op,
  2440. unsigned int nbits)
  2441. {
  2442. ctx->op = op;
  2443. ctx->nbits = nbits;
  2444. ctx->encoding = PUBKEY_ENC_UNKNOWN;
  2445. ctx->flags = 0;
  2446. ctx->hash_algo = GCRY_MD_SHA1;
  2447. ctx->label = NULL;
  2448. ctx->labellen = 0;
  2449. ctx->saltlen = 20;
  2450. ctx->verify_cmp = NULL;
  2451. ctx->verify_arg = NULL;
  2452. }
  2453. /*
  2454. Do a PK encrypt operation
  2455. Caller has to provide a public key as the SEXP pkey and data as a
  2456. SEXP with just one MPI in it. Alternatively S_DATA might be a
  2457. complex S-Expression, similar to the one used for signature
  2458. verification. This provides a flag which allows to handle PKCS#1
  2459. block type 2 padding. The function returns a sexp which may be
  2460. passed to to pk_decrypt.
  2461. Returns: 0 or an errorcode.
  2462. s_data = See comment for sexp_data_to_mpi
  2463. s_pkey = <key-as-defined-in-sexp_to_key>
  2464. r_ciph = (enc-val
  2465. (<algo>
  2466. (<param_name1> <mpi>)
  2467. ...
  2468. (<param_namen> <mpi>)
  2469. ))
  2470. */
  2471. gcry_error_t
  2472. gcry_pk_encrypt (gcry_sexp_t *r_ciph, gcry_sexp_t s_data, gcry_sexp_t s_pkey)
  2473. {
  2474. gcry_mpi_t *pkey = NULL, data = NULL, *ciph = NULL;
  2475. const char *algo_name, *algo_elems;
  2476. struct pk_encoding_ctx ctx;
  2477. gcry_err_code_t rc;
  2478. gcry_pk_spec_t *pubkey = NULL;
  2479. gcry_module_t module = NULL;
  2480. *r_ciph = NULL;
  2481. REGISTER_DEFAULT_PUBKEYS;
  2482. /* Get the key. */
  2483. rc = sexp_to_key (s_pkey, 0, NULL, &pkey, &module);
  2484. if (rc)
  2485. goto leave;
  2486. gcry_assert (module);
  2487. pubkey = (gcry_pk_spec_t *) module->spec;
  2488. /* If aliases for the algorithm name exists, take the first one
  2489. instead of the regular name to adhere to SPKI conventions. We
  2490. assume that the first alias name is the lowercase version of the
  2491. regular one. This change is required for compatibility with
  2492. 1.1.12 generated S-expressions. */
  2493. algo_name = pubkey->aliases? *pubkey->aliases : NULL;
  2494. if (!algo_name || !*algo_name)
  2495. algo_name = pubkey->name;
  2496. algo_elems = pubkey->elements_enc;
  2497. /* Get the stuff we want to encrypt. */
  2498. init_encoding_ctx (&ctx, PUBKEY_OP_ENCRYPT, gcry_pk_get_nbits (s_pkey));
  2499. rc = sexp_data_to_mpi (s_data, &data, &ctx);
  2500. if (rc)
  2501. goto leave;
  2502. /* Now we can encrypt DATA to CIPH. */
  2503. ciph = gcry_calloc (strlen (algo_elems) + 1, sizeof (*ciph));
  2504. if (!ciph)
  2505. {
  2506. rc = gpg_err_code_from_syserror ();
  2507. goto leave;
  2508. }
  2509. rc = pubkey_encrypt (module->mod_id, ciph, data, pkey, ctx.flags);
  2510. mpi_free (data);
  2511. data = NULL;
  2512. if (rc)
  2513. goto leave;
  2514. /* We did it. Now build the return list */
  2515. if (ctx.encoding == PUBKEY_ENC_OAEP
  2516. || ctx.encoding == PUBKEY_ENC_PKCS1)
  2517. {
  2518. /* We need to make sure to return the correct length to avoid
  2519. problems with missing leading zeroes. We know that this
  2520. encoding does only make sense with RSA thus we don't need to
  2521. build the S-expression on the fly. */
  2522. unsigned char *em;
  2523. size_t emlen = (ctx.nbits+7)/8;
  2524. rc = octet_string_from_mpi (&em, NULL, ciph[0], emlen);
  2525. if (rc)
  2526. goto leave;
  2527. rc = gcry_err_code (gcry_sexp_build (r_ciph, NULL,
  2528. "(enc-val(%s(a%b)))",
  2529. algo_name, (int)emlen, em));
  2530. gcry_free (em);
  2531. if (rc)
  2532. goto leave;
  2533. }
  2534. else
  2535. {
  2536. char *string, *p;
  2537. int i;
  2538. size_t nelem = strlen (algo_elems);
  2539. size_t needed = 19 + strlen (algo_name) + (nelem * 5);
  2540. void **arg_list;
  2541. /* Build the string. */
  2542. string = p = gcry_malloc (needed);
  2543. if (!string)
  2544. {
  2545. rc = gpg_err_code_from_syserror ();
  2546. goto leave;
  2547. }
  2548. p = stpcpy ( p, "(enc-val(" );
  2549. p = stpcpy ( p, algo_name );
  2550. for (i=0; algo_elems[i]; i++ )
  2551. {
  2552. *p++ = '(';
  2553. *p++ = algo_elems[i];
  2554. p = stpcpy ( p, "%m)" );
  2555. }
  2556. strcpy ( p, "))" );
  2557. /* And now the ugly part: We don't have a function to pass an
  2558. * array to a format string, so we have to do it this way :-(. */
  2559. /* FIXME: There is now such a format specifier, so we can
  2560. change the code to be more clear. */
  2561. arg_list = calloc (nelem, sizeof *arg_list);
  2562. if (!arg_list)
  2563. {
  2564. rc = gpg_err_code_from_syserror ();
  2565. goto leave;
  2566. }
  2567. for (i = 0; i < nelem; i++)
  2568. arg_list[i] = ciph + i;
  2569. rc = gcry_sexp_build_array (r_ciph, NULL, string, arg_list);
  2570. free (arg_list);
  2571. if (rc)
  2572. BUG ();
  2573. gcry_free (string);
  2574. }
  2575. leave:
  2576. if (pkey)
  2577. {
  2578. release_mpi_array (pkey);
  2579. gcry_free (pkey);
  2580. }
  2581. if (ciph)
  2582. {
  2583. release_mpi_array (ciph);
  2584. gcry_free (ciph);
  2585. }
  2586. if (module)
  2587. {
  2588. ath_mutex_lock (&pubkeys_registered_lock);
  2589. _gcry_module_release (module);
  2590. ath_mutex_unlock (&pubkeys_registered_lock);
  2591. }
  2592. gcry_free (ctx.label);
  2593. return gcry_error (rc);
  2594. }
  2595. /*
  2596. Do a PK decrypt operation
  2597. Caller has to provide a secret key as the SEXP skey and data in a
  2598. format as created by gcry_pk_encrypt. For historic reasons the
  2599. function returns simply an MPI as an S-expression part; this is
  2600. deprecated and the new method should be used which returns a real
  2601. S-expressionl this is selected by adding at least an empty flags
  2602. list to S_DATA.
  2603. Returns: 0 or an errorcode.
  2604. s_data = (enc-val
  2605. [(flags [raw, pkcs1, oaep])]
  2606. (<algo>
  2607. (<param_name1> <mpi>)
  2608. ...
  2609. (<param_namen> <mpi>)
  2610. ))
  2611. s_skey = <key-as-defined-in-sexp_to_key>
  2612. r_plain= Either an incomplete S-expression without the parentheses
  2613. or if the flags list is used (even if empty) a real S-expression:
  2614. (value PLAIN). In raw mode (or no flags given) the returned value
  2615. is to be interpreted as a signed MPI, thus it may have an extra
  2616. leading zero octet even if not included in the original data.
  2617. With pkcs1 or oaep decoding enabled the returned value is a
  2618. verbatim octet string.
  2619. */
  2620. gcry_error_t
  2621. gcry_pk_decrypt (gcry_sexp_t *r_plain, gcry_sexp_t s_data, gcry_sexp_t s_skey)
  2622. {
  2623. gcry_mpi_t *skey = NULL, *data = NULL, plain = NULL;
  2624. unsigned char *unpad = NULL;
  2625. size_t unpadlen = 0;
  2626. int modern, flags;
  2627. struct pk_encoding_ctx ctx;
  2628. gcry_err_code_t rc;
  2629. gcry_module_t module_enc = NULL, module_key = NULL;
  2630. *r_plain = NULL;
  2631. ctx.label = NULL;
  2632. REGISTER_DEFAULT_PUBKEYS;
  2633. rc = sexp_to_key (s_skey, 1, NULL, &skey, &module_key);
  2634. if (rc)
  2635. goto leave;
  2636. init_encoding_ctx (&ctx, PUBKEY_OP_DECRYPT, gcry_pk_get_nbits (s_skey));
  2637. rc = sexp_to_enc (s_data, &data, &module_enc, &modern, &flags, &ctx);
  2638. if (rc)
  2639. goto leave;
  2640. if (module_key->mod_id != module_enc->mod_id)
  2641. {
  2642. rc = GPG_ERR_CONFLICT; /* Key algo does not match data algo. */
  2643. goto leave;
  2644. }
  2645. rc = pubkey_decrypt (module_key->mod_id, &plain, data, skey, flags);
  2646. if (rc)
  2647. goto leave;
  2648. /* Do un-padding if necessary. */
  2649. switch (ctx.encoding)
  2650. {
  2651. case PUBKEY_ENC_PKCS1:
  2652. rc = pkcs1_decode_for_encryption (&unpad, &unpadlen,
  2653. gcry_pk_get_nbits (s_skey), plain);
  2654. mpi_free (plain);
  2655. plain = NULL;
  2656. if (!rc)
  2657. rc = gcry_err_code (gcry_sexp_build (r_plain, NULL, "(value %b)",
  2658. (int)unpadlen, unpad));
  2659. break;
  2660. case PUBKEY_ENC_OAEP:
  2661. rc = oaep_decode (&unpad, &unpadlen,
  2662. gcry_pk_get_nbits (s_skey), ctx.hash_algo,
  2663. plain, ctx.label, ctx.labellen);
  2664. mpi_free (plain);
  2665. plain = NULL;
  2666. if (!rc)
  2667. rc = gcry_err_code (gcry_sexp_build (r_plain, NULL, "(value %b)",
  2668. (int)unpadlen, unpad));
  2669. break;
  2670. default:
  2671. /* Raw format. For backward compatibility we need to assume a
  2672. signed mpi by using the sexp format string "%m". */
  2673. rc = gcry_err_code (gcry_sexp_build
  2674. (r_plain, NULL, modern? "(value %m)" : "%m", plain));
  2675. break;
  2676. }
  2677. leave:
  2678. gcry_free (unpad);
  2679. if (skey)
  2680. {
  2681. release_mpi_array (skey);
  2682. gcry_free (skey);
  2683. }
  2684. mpi_free (plain);
  2685. if (data)
  2686. {
  2687. release_mpi_array (data);
  2688. gcry_free (data);
  2689. }
  2690. if (module_key || module_enc)
  2691. {
  2692. ath_mutex_lock (&pubkeys_registered_lock);
  2693. if (module_key)
  2694. _gcry_module_release (module_key);
  2695. if (module_enc)
  2696. _gcry_module_release (module_enc);
  2697. ath_mutex_unlock (&pubkeys_registered_lock);
  2698. }
  2699. gcry_free (ctx.label);
  2700. return gcry_error (rc);
  2701. }
  2702. /*
  2703. Create a signature.
  2704. Caller has to provide a secret key as the SEXP skey and data
  2705. expressed as a SEXP list hash with only one element which should
  2706. instantly be available as a MPI. Alternatively the structure given
  2707. below may be used for S_HASH, it provides the abiliy to pass flags
  2708. to the operation; the flags defined by now are "pkcs1" which does
  2709. PKCS#1 block type 1 style padding and "pss" for PSS encoding.
  2710. Returns: 0 or an errorcode.
  2711. In case of 0 the function returns a new SEXP with the
  2712. signature value; the structure of this signature depends on the
  2713. other arguments but is always suitable to be passed to
  2714. gcry_pk_verify
  2715. s_hash = See comment for sexp_data_to_mpi
  2716. s_skey = <key-as-defined-in-sexp_to_key>
  2717. r_sig = (sig-val
  2718. (<algo>
  2719. (<param_name1> <mpi>)
  2720. ...
  2721. (<param_namen> <mpi>))
  2722. [(hash algo)])
  2723. Note that (hash algo) in R_SIG is not used.
  2724. */
  2725. gcry_error_t
  2726. gcry_pk_sign (gcry_sexp_t *r_sig, gcry_sexp_t s_hash, gcry_sexp_t s_skey)
  2727. {
  2728. gcry_mpi_t *skey = NULL, hash = NULL, *result = NULL;
  2729. gcry_pk_spec_t *pubkey = NULL;
  2730. gcry_module_t module = NULL;
  2731. const char *algo_name, *algo_elems;
  2732. struct pk_encoding_ctx ctx;
  2733. int i;
  2734. gcry_err_code_t rc;
  2735. *r_sig = NULL;
  2736. REGISTER_DEFAULT_PUBKEYS;
  2737. rc = sexp_to_key (s_skey, 1, NULL, &skey, &module);
  2738. if (rc)
  2739. goto leave;
  2740. gcry_assert (module);
  2741. pubkey = (gcry_pk_spec_t *) module->spec;
  2742. algo_name = pubkey->aliases? *pubkey->aliases : NULL;
  2743. if (!algo_name || !*algo_name)
  2744. algo_name = pubkey->name;
  2745. algo_elems = pubkey->elements_sig;
  2746. /* Get the stuff we want to sign. Note that pk_get_nbits does also
  2747. work on a private key. */
  2748. init_encoding_ctx (&ctx, PUBKEY_OP_SIGN, gcry_pk_get_nbits (s_skey));
  2749. rc = sexp_data_to_mpi (s_hash, &hash, &ctx);
  2750. if (rc)
  2751. goto leave;
  2752. result = gcry_calloc (strlen (algo_elems) + 1, sizeof (*result));
  2753. if (!result)
  2754. {
  2755. rc = gpg_err_code_from_syserror ();
  2756. goto leave;
  2757. }
  2758. rc = pubkey_sign (module->mod_id, result, hash, skey);
  2759. if (rc)
  2760. goto leave;
  2761. if (ctx.encoding == PUBKEY_ENC_PSS
  2762. || ctx.encoding == PUBKEY_ENC_PKCS1)
  2763. {
  2764. /* We need to make sure to return the correct length to avoid
  2765. problems with missing leading zeroes. We know that this
  2766. encoding does only make sense with RSA thus we don't need to
  2767. build the S-expression on the fly. */
  2768. unsigned char *em;
  2769. size_t emlen = (ctx.nbits+7)/8;
  2770. rc = octet_string_from_mpi (&em, NULL, result[0], emlen);
  2771. if (rc)
  2772. goto leave;
  2773. rc = gcry_err_code (gcry_sexp_build (r_sig, NULL,
  2774. "(sig-val(%s(s%b)))",
  2775. algo_name, (int)emlen, em));
  2776. gcry_free (em);
  2777. if (rc)
  2778. goto leave;
  2779. }
  2780. else
  2781. {
  2782. /* General purpose output encoding. Do it on the fly. */
  2783. char *string, *p;
  2784. size_t nelem, needed = strlen (algo_name) + 20;
  2785. void **arg_list;
  2786. nelem = strlen (algo_elems);
  2787. /* Count elements, so that we can allocate enough space. */
  2788. needed += 10 * nelem;
  2789. /* Build the string. */
  2790. string = p = gcry_malloc (needed);
  2791. if (!string)
  2792. {
  2793. rc = gpg_err_code_from_syserror ();
  2794. goto leave;
  2795. }
  2796. p = stpcpy (p, "(sig-val(");
  2797. p = stpcpy (p, algo_name);
  2798. for (i = 0; algo_elems[i]; i++)
  2799. {
  2800. *p++ = '(';
  2801. *p++ = algo_elems[i];
  2802. p = stpcpy (p, "%M)");
  2803. }
  2804. strcpy (p, "))");
  2805. arg_list = calloc (nelem, sizeof *arg_list);
  2806. if (!arg_list)
  2807. {
  2808. rc = gpg_err_code_from_syserror ();
  2809. goto leave;
  2810. }
  2811. for (i = 0; i < nelem; i++)
  2812. arg_list[i] = result + i;
  2813. rc = gcry_sexp_build_array (r_sig, NULL, string, arg_list);
  2814. free (arg_list);
  2815. if (rc)
  2816. BUG ();
  2817. gcry_free (string);
  2818. }
  2819. leave:
  2820. if (skey)
  2821. {
  2822. release_mpi_array (skey);
  2823. gcry_free (skey);
  2824. }
  2825. if (hash)
  2826. mpi_free (hash);
  2827. if (result)
  2828. {
  2829. release_mpi_array (result);
  2830. gcry_free (result);
  2831. }
  2832. return gcry_error (rc);
  2833. }
  2834. /*
  2835. Verify a signature.
  2836. Caller has to supply the public key pkey, the signature sig and his
  2837. hashvalue data. Public key has to be a standard public key given
  2838. as an S-Exp, sig is a S-Exp as returned from gcry_pk_sign and data
  2839. must be an S-Exp like the one in sign too. */
  2840. gcry_error_t
  2841. gcry_pk_verify (gcry_sexp_t s_sig, gcry_sexp_t s_hash, gcry_sexp_t s_pkey)
  2842. {
  2843. gcry_module_t module_key = NULL, module_sig = NULL;
  2844. gcry_mpi_t *pkey = NULL, hash = NULL, *sig = NULL;
  2845. struct pk_encoding_ctx ctx;
  2846. gcry_err_code_t rc;
  2847. REGISTER_DEFAULT_PUBKEYS;
  2848. rc = sexp_to_key (s_pkey, 0, NULL, &pkey, &module_key);
  2849. if (rc)
  2850. goto leave;
  2851. rc = sexp_to_sig (s_sig, &sig, &module_sig);
  2852. if (rc)
  2853. goto leave;
  2854. /* Fixme: Check that the algorithm of S_SIG is compatible to the one
  2855. of S_PKEY. */
  2856. if (module_key->mod_id != module_sig->mod_id)
  2857. {
  2858. rc = GPG_ERR_CONFLICT;
  2859. goto leave;
  2860. }
  2861. /* Get the stuff we want to verify. */
  2862. init_encoding_ctx (&ctx, PUBKEY_OP_VERIFY, gcry_pk_get_nbits (s_pkey));
  2863. rc = sexp_data_to_mpi (s_hash, &hash, &ctx);
  2864. if (rc)
  2865. goto leave;
  2866. rc = pubkey_verify (module_key->mod_id, hash, sig, pkey,
  2867. ctx.verify_cmp, &ctx);
  2868. leave:
  2869. if (pkey)
  2870. {
  2871. release_mpi_array (pkey);
  2872. gcry_free (pkey);
  2873. }
  2874. if (sig)
  2875. {
  2876. release_mpi_array (sig);
  2877. gcry_free (sig);
  2878. }
  2879. if (hash)
  2880. mpi_free (hash);
  2881. if (module_key || module_sig)
  2882. {
  2883. ath_mutex_lock (&pubkeys_registered_lock);
  2884. if (module_key)
  2885. _gcry_module_release (module_key);
  2886. if (module_sig)
  2887. _gcry_module_release (module_sig);
  2888. ath_mutex_unlock (&pubkeys_registered_lock);
  2889. }
  2890. return gcry_error (rc);
  2891. }
  2892. /*
  2893. Test a key.
  2894. This may be used either for a public or a secret key to see whether
  2895. the internal structure is okay.
  2896. Returns: 0 or an errorcode.
  2897. s_key = <key-as-defined-in-sexp_to_key> */
  2898. gcry_error_t
  2899. gcry_pk_testkey (gcry_sexp_t s_key)
  2900. {
  2901. gcry_module_t module = NULL;
  2902. gcry_mpi_t *key = NULL;
  2903. gcry_err_code_t rc;
  2904. REGISTER_DEFAULT_PUBKEYS;
  2905. /* Note we currently support only secret key checking. */
  2906. rc = sexp_to_key (s_key, 1, NULL, &key, &module);
  2907. if (! rc)
  2908. {
  2909. rc = pubkey_check_secret_key (module->mod_id, key);
  2910. release_mpi_array (key);
  2911. gcry_free (key);
  2912. }
  2913. return gcry_error (rc);
  2914. }
  2915. /*
  2916. Create a public key pair and return it in r_key.
  2917. How the key is created depends on s_parms:
  2918. (genkey
  2919. (algo
  2920. (parameter_name_1 ....)
  2921. ....
  2922. (parameter_name_n ....)
  2923. ))
  2924. The key is returned in a format depending on the
  2925. algorithm. Both, private and secret keys are returned
  2926. and optionally some additional informatin.
  2927. For elgamal we return this structure:
  2928. (key-data
  2929. (public-key
  2930. (elg
  2931. (p <mpi>)
  2932. (g <mpi>)
  2933. (y <mpi>)
  2934. )
  2935. )
  2936. (private-key
  2937. (elg
  2938. (p <mpi>)
  2939. (g <mpi>)
  2940. (y <mpi>)
  2941. (x <mpi>)
  2942. )
  2943. )
  2944. (misc-key-info
  2945. (pm1-factors n1 n2 ... nn)
  2946. ))
  2947. */
  2948. gcry_error_t
  2949. gcry_pk_genkey (gcry_sexp_t *r_key, gcry_sexp_t s_parms)
  2950. {
  2951. gcry_pk_spec_t *pubkey = NULL;
  2952. gcry_module_t module = NULL;
  2953. gcry_sexp_t list = NULL;
  2954. gcry_sexp_t l2 = NULL;
  2955. gcry_sexp_t l3 = NULL;
  2956. char *name = NULL;
  2957. size_t n;
  2958. gcry_err_code_t rc = GPG_ERR_NO_ERROR;
  2959. int i, j;
  2960. const char *algo_name = NULL;
  2961. int algo;
  2962. const char *sec_elems = NULL, *pub_elems = NULL;
  2963. gcry_mpi_t skey[12];
  2964. gcry_mpi_t *factors = NULL;
  2965. gcry_sexp_t extrainfo = NULL;
  2966. unsigned int nbits = 0;
  2967. unsigned long use_e = 0;
  2968. skey[0] = NULL;
  2969. *r_key = NULL;
  2970. REGISTER_DEFAULT_PUBKEYS;
  2971. list = gcry_sexp_find_token (s_parms, "genkey", 0);
  2972. if (!list)
  2973. {
  2974. rc = GPG_ERR_INV_OBJ; /* Does not contain genkey data. */
  2975. goto leave;
  2976. }
  2977. l2 = gcry_sexp_cadr (list);
  2978. gcry_sexp_release (list);
  2979. list = l2;
  2980. l2 = NULL;
  2981. if (! list)
  2982. {
  2983. rc = GPG_ERR_NO_OBJ; /* No cdr for the genkey. */
  2984. goto leave;
  2985. }
  2986. name = _gcry_sexp_nth_string (list, 0);
  2987. if (!name)
  2988. {
  2989. rc = GPG_ERR_INV_OBJ; /* Algo string missing. */
  2990. goto leave;
  2991. }
  2992. ath_mutex_lock (&pubkeys_registered_lock);
  2993. module = gcry_pk_lookup_name (name);
  2994. ath_mutex_unlock (&pubkeys_registered_lock);
  2995. gcry_free (name);
  2996. name = NULL;
  2997. if (!module)
  2998. {
  2999. rc = GPG_ERR_PUBKEY_ALGO; /* Unknown algorithm. */
  3000. goto leave;
  3001. }
  3002. pubkey = (gcry_pk_spec_t *) module->spec;
  3003. algo = module->mod_id;
  3004. algo_name = pubkey->aliases? *pubkey->aliases : NULL;
  3005. if (!algo_name || !*algo_name)
  3006. algo_name = pubkey->name;
  3007. pub_elems = pubkey->elements_pkey;
  3008. sec_elems = pubkey->elements_skey;
  3009. if (strlen (sec_elems) >= DIM(skey))
  3010. BUG ();
  3011. /* Handle the optional rsa-use-e element. Actually this belong into
  3012. the algorithm module but we have this parameter in the public
  3013. module API, so we need to parse it right here. */
  3014. l2 = gcry_sexp_find_token (list, "rsa-use-e", 0);
  3015. if (l2)
  3016. {
  3017. char buf[50];
  3018. const char *s;
  3019. s = gcry_sexp_nth_data (l2, 1, &n);
  3020. if ( !s || n >= DIM (buf) - 1 )
  3021. {
  3022. rc = GPG_ERR_INV_OBJ; /* No value or value too large. */
  3023. goto leave;
  3024. }
  3025. memcpy (buf, s, n);
  3026. buf[n] = 0;
  3027. use_e = strtoul (buf, NULL, 0);
  3028. gcry_sexp_release (l2);
  3029. l2 = NULL;
  3030. }
  3031. else
  3032. use_e = 65537; /* Not given, use the value generated by old versions. */
  3033. /* Get the "nbits" parameter. */
  3034. l2 = gcry_sexp_find_token (list, "nbits", 0);
  3035. if (l2)
  3036. {
  3037. char buf[50];
  3038. const char *s;
  3039. s = gcry_sexp_nth_data (l2, 1, &n);
  3040. if (!s || n >= DIM (buf) - 1 )
  3041. {
  3042. rc = GPG_ERR_INV_OBJ; /* NBITS given without a cdr. */
  3043. goto leave;
  3044. }
  3045. memcpy (buf, s, n);
  3046. buf[n] = 0;
  3047. nbits = (unsigned int)strtoul (buf, NULL, 0);
  3048. gcry_sexp_release (l2); l2 = NULL;
  3049. }
  3050. else
  3051. nbits = 0;
  3052. /* Pass control to the algorithm module. */
  3053. rc = pubkey_generate (module->mod_id, nbits, use_e, list, skey,
  3054. &factors, &extrainfo);
  3055. gcry_sexp_release (list); list = NULL;
  3056. if (rc)
  3057. goto leave;
  3058. /* Key generation succeeded: Build an S-expression. */
  3059. {
  3060. char *string, *p;
  3061. size_t nelem=0, nelem_cp = 0, needed=0;
  3062. gcry_mpi_t mpis[30];
  3063. int percent_s_idx = -1;
  3064. /* Estimate size of format string. */
  3065. nelem = strlen (pub_elems) + strlen (sec_elems);
  3066. if (factors)
  3067. {
  3068. for (i = 0; factors[i]; i++)
  3069. nelem++;
  3070. }
  3071. nelem_cp = nelem;
  3072. needed += nelem * 10;
  3073. /* (+5 is for EXTRAINFO ("%S")). */
  3074. needed += 2 * strlen (algo_name) + 300 + 5;
  3075. if (nelem > DIM (mpis))
  3076. BUG ();
  3077. /* Build the string. */
  3078. nelem = 0;
  3079. string = p = gcry_malloc (needed);
  3080. if (!string)
  3081. {
  3082. rc = gpg_err_code_from_syserror ();
  3083. goto leave;
  3084. }
  3085. p = stpcpy (p, "(key-data");
  3086. p = stpcpy (p, "(public-key(");
  3087. p = stpcpy (p, algo_name);
  3088. for(i = 0; pub_elems[i]; i++)
  3089. {
  3090. *p++ = '(';
  3091. *p++ = pub_elems[i];
  3092. p = stpcpy (p, "%m)");
  3093. mpis[nelem++] = skey[i];
  3094. }
  3095. if (extrainfo && (algo == GCRY_PK_ECDSA || algo == GCRY_PK_ECDH))
  3096. {
  3097. /* Very ugly hack to insert the used curve parameter into the
  3098. list of public key parameters. */
  3099. percent_s_idx = nelem;
  3100. p = stpcpy (p, "%S");
  3101. }
  3102. p = stpcpy (p, "))");
  3103. p = stpcpy (p, "(private-key(");
  3104. p = stpcpy (p, algo_name);
  3105. for (i = 0; sec_elems[i]; i++)
  3106. {
  3107. *p++ = '(';
  3108. *p++ = sec_elems[i];
  3109. p = stpcpy (p, "%m)");
  3110. mpis[nelem++] = skey[i];
  3111. }
  3112. p = stpcpy (p, "))");
  3113. /* Hack to make release_mpi_array() work. */
  3114. skey[i] = NULL;
  3115. if (extrainfo && percent_s_idx == -1)
  3116. {
  3117. /* If we have extrainfo we should not have any factors. */
  3118. p = stpcpy (p, "%S");
  3119. }
  3120. else if (factors && factors[0])
  3121. {
  3122. p = stpcpy (p, "(misc-key-info(pm1-factors");
  3123. for(i = 0; factors[i]; i++)
  3124. {
  3125. p = stpcpy (p, "%m");
  3126. mpis[nelem++] = factors[i];
  3127. }
  3128. p = stpcpy (p, "))");
  3129. }
  3130. strcpy (p, ")");
  3131. gcry_assert (p - string < needed);
  3132. while (nelem < DIM (mpis))
  3133. mpis[nelem++] = NULL;
  3134. {
  3135. int elem_n = strlen (pub_elems) + strlen (sec_elems);
  3136. void **arg_list;
  3137. /* Allocate one extra for EXTRAINFO ("%S"). */
  3138. arg_list = gcry_calloc (nelem_cp+1, sizeof *arg_list);
  3139. if (!arg_list)
  3140. {
  3141. rc = gpg_err_code_from_syserror ();
  3142. goto leave;
  3143. }
  3144. for (i = j = 0; i < elem_n; i++)
  3145. {
  3146. if (i == percent_s_idx)
  3147. arg_list[j++] = &extrainfo;
  3148. arg_list[j++] = mpis + i;
  3149. }
  3150. if (extrainfo && percent_s_idx == -1)
  3151. arg_list[j] = &extrainfo;
  3152. else if (factors && factors[0])
  3153. {
  3154. for (; i < nelem_cp; i++)
  3155. arg_list[j++] = factors + i - elem_n;
  3156. }
  3157. rc = gcry_sexp_build_array (r_key, NULL, string, arg_list);
  3158. gcry_free (arg_list);
  3159. if (rc)
  3160. BUG ();
  3161. gcry_assert (DIM (mpis) == 30); /* Reminder to make sure that
  3162. the array gets increased if
  3163. new parameters are added. */
  3164. }
  3165. gcry_free (string);
  3166. }
  3167. leave:
  3168. gcry_free (name);
  3169. gcry_sexp_release (extrainfo);
  3170. release_mpi_array (skey);
  3171. /* Don't free SKEY itself, it is an stack allocated array. */
  3172. if (factors)
  3173. {
  3174. release_mpi_array ( factors );
  3175. gcry_free (factors);
  3176. }
  3177. gcry_sexp_release (l3);
  3178. gcry_sexp_release (l2);
  3179. gcry_sexp_release (list);
  3180. if (module)
  3181. {
  3182. ath_mutex_lock (&pubkeys_registered_lock);
  3183. _gcry_module_release (module);
  3184. ath_mutex_unlock (&pubkeys_registered_lock);
  3185. }
  3186. return gcry_error (rc);
  3187. }
  3188. /*
  3189. Get the number of nbits from the public key.
  3190. Hmmm: Should we have really this function or is it better to have a
  3191. more general function to retrieve different properties of the key? */
  3192. unsigned int
  3193. gcry_pk_get_nbits (gcry_sexp_t key)
  3194. {
  3195. gcry_module_t module = NULL;
  3196. gcry_pk_spec_t *pubkey;
  3197. gcry_mpi_t *keyarr = NULL;
  3198. unsigned int nbits = 0;
  3199. gcry_err_code_t rc;
  3200. REGISTER_DEFAULT_PUBKEYS;
  3201. rc = sexp_to_key (key, 0, NULL, &keyarr, &module);
  3202. if (rc == GPG_ERR_INV_OBJ)
  3203. rc = sexp_to_key (key, 1, NULL, &keyarr, &module);
  3204. if (rc)
  3205. return 0; /* Error - 0 is a suitable indication for that. */
  3206. pubkey = (gcry_pk_spec_t *) module->spec;
  3207. nbits = (*pubkey->get_nbits) (module->mod_id, keyarr);
  3208. ath_mutex_lock (&pubkeys_registered_lock);
  3209. _gcry_module_release (module);
  3210. ath_mutex_unlock (&pubkeys_registered_lock);
  3211. release_mpi_array (keyarr);
  3212. gcry_free (keyarr);
  3213. return nbits;
  3214. }
  3215. /* Return the so called KEYGRIP which is the SHA-1 hash of the public
  3216. key parameters expressed in a way depending on the algorithm.
  3217. ARRAY must either be 20 bytes long or NULL; in the latter case a
  3218. newly allocated array of that size is returned, otherwise ARRAY or
  3219. NULL is returned to indicate an error which is most likely an
  3220. unknown algorithm. The function accepts public or secret keys. */
  3221. unsigned char *
  3222. gcry_pk_get_keygrip (gcry_sexp_t key, unsigned char *array)
  3223. {
  3224. gcry_sexp_t list = NULL, l2 = NULL;
  3225. gcry_pk_spec_t *pubkey = NULL;
  3226. gcry_module_t module = NULL;
  3227. pk_extra_spec_t *extraspec;
  3228. const char *s;
  3229. char *name = NULL;
  3230. int idx;
  3231. const char *elems;
  3232. gcry_md_hd_t md = NULL;
  3233. int okay = 0;
  3234. REGISTER_DEFAULT_PUBKEYS;
  3235. /* Check that the first element is valid. */
  3236. list = gcry_sexp_find_token (key, "public-key", 0);
  3237. if (! list)
  3238. list = gcry_sexp_find_token (key, "private-key", 0);
  3239. if (! list)
  3240. list = gcry_sexp_find_token (key, "protected-private-key", 0);
  3241. if (! list)
  3242. list = gcry_sexp_find_token (key, "shadowed-private-key", 0);
  3243. if (! list)
  3244. return NULL; /* No public- or private-key object. */
  3245. l2 = gcry_sexp_cadr (list);
  3246. gcry_sexp_release (list);
  3247. list = l2;
  3248. l2 = NULL;
  3249. name = _gcry_sexp_nth_string (list, 0);
  3250. if (!name)
  3251. goto fail; /* Invalid structure of object. */
  3252. ath_mutex_lock (&pubkeys_registered_lock);
  3253. module = gcry_pk_lookup_name (name);
  3254. ath_mutex_unlock (&pubkeys_registered_lock);
  3255. if (!module)
  3256. goto fail; /* Unknown algorithm. */
  3257. pubkey = (gcry_pk_spec_t *) module->spec;
  3258. extraspec = module->extraspec;
  3259. elems = pubkey->elements_grip;
  3260. if (!elems)
  3261. goto fail; /* No grip parameter. */
  3262. if (gcry_md_open (&md, GCRY_MD_SHA1, 0))
  3263. goto fail;
  3264. if (extraspec && extraspec->comp_keygrip)
  3265. {
  3266. /* Module specific method to compute a keygrip. */
  3267. if (extraspec->comp_keygrip (md, list))
  3268. goto fail;
  3269. }
  3270. else
  3271. {
  3272. /* Generic method to compute a keygrip. */
  3273. for (idx = 0, s = elems; *s; s++, idx++)
  3274. {
  3275. const char *data;
  3276. size_t datalen;
  3277. char buf[30];
  3278. l2 = gcry_sexp_find_token (list, s, 1);
  3279. if (! l2)
  3280. goto fail;
  3281. data = gcry_sexp_nth_data (l2, 1, &datalen);
  3282. if (! data)
  3283. goto fail;
  3284. snprintf (buf, sizeof buf, "(1:%c%u:", *s, (unsigned int)datalen);
  3285. gcry_md_write (md, buf, strlen (buf));
  3286. gcry_md_write (md, data, datalen);
  3287. gcry_sexp_release (l2);
  3288. l2 = NULL;
  3289. gcry_md_write (md, ")", 1);
  3290. }
  3291. }
  3292. if (!array)
  3293. {
  3294. array = gcry_malloc (20);
  3295. if (! array)
  3296. goto fail;
  3297. }
  3298. memcpy (array, gcry_md_read (md, GCRY_MD_SHA1), 20);
  3299. okay = 1;
  3300. fail:
  3301. gcry_free (name);
  3302. gcry_sexp_release (l2);
  3303. gcry_md_close (md);
  3304. gcry_sexp_release (list);
  3305. return okay? array : NULL;
  3306. }
  3307. const char *
  3308. gcry_pk_get_curve (gcry_sexp_t key, int iterator, unsigned int *r_nbits)
  3309. {
  3310. gcry_mpi_t *pkey = NULL;
  3311. gcry_sexp_t list = NULL;
  3312. gcry_sexp_t l2;
  3313. gcry_module_t module = NULL;
  3314. pk_extra_spec_t *extraspec;
  3315. char *name = NULL;
  3316. const char *result = NULL;
  3317. int want_private = 1;
  3318. if (r_nbits)
  3319. *r_nbits = 0;
  3320. REGISTER_DEFAULT_PUBKEYS;
  3321. if (key)
  3322. {
  3323. iterator = 0;
  3324. /* Check that the first element is valid. */
  3325. list = gcry_sexp_find_token (key, "public-key", 0);
  3326. if (list)
  3327. want_private = 0;
  3328. if (!list)
  3329. list = gcry_sexp_find_token (key, "private-key", 0);
  3330. if (!list)
  3331. return NULL; /* No public- or private-key object. */
  3332. l2 = gcry_sexp_cadr (list);
  3333. gcry_sexp_release (list);
  3334. list = l2;
  3335. l2 = NULL;
  3336. name = _gcry_sexp_nth_string (list, 0);
  3337. if (!name)
  3338. goto leave; /* Invalid structure of object. */
  3339. /* Get the key. We pass the names of the parameters for
  3340. override_elems; this allows to call this function without the
  3341. actual public key parameter. */
  3342. if (sexp_to_key (key, want_private, "pabgn", &pkey, &module))
  3343. goto leave;
  3344. }
  3345. else
  3346. {
  3347. ath_mutex_lock (&pubkeys_registered_lock);
  3348. module = gcry_pk_lookup_name ("ecc");
  3349. ath_mutex_unlock (&pubkeys_registered_lock);
  3350. if (!module)
  3351. goto leave;
  3352. }
  3353. extraspec = module->extraspec;
  3354. if (!extraspec || !extraspec->get_curve)
  3355. goto leave;
  3356. result = extraspec->get_curve (pkey, iterator, r_nbits);
  3357. leave:
  3358. if (pkey)
  3359. {
  3360. release_mpi_array (pkey);
  3361. gcry_free (pkey);
  3362. }
  3363. if (module)
  3364. {
  3365. ath_mutex_lock (&pubkeys_registered_lock);
  3366. _gcry_module_release (module);
  3367. ath_mutex_unlock (&pubkeys_registered_lock);
  3368. }
  3369. gcry_free (name);
  3370. gcry_sexp_release (list);
  3371. return result;
  3372. }
  3373. gcry_sexp_t
  3374. gcry_pk_get_param (int algo, const char *name)
  3375. {
  3376. gcry_module_t module = NULL;
  3377. pk_extra_spec_t *extraspec;
  3378. gcry_sexp_t result = NULL;
  3379. if (algo != GCRY_PK_ECDSA && algo != GCRY_PK_ECDH)
  3380. return NULL;
  3381. REGISTER_DEFAULT_PUBKEYS;
  3382. ath_mutex_lock (&pubkeys_registered_lock);
  3383. module = gcry_pk_lookup_name ("ecc");
  3384. ath_mutex_unlock (&pubkeys_registered_lock);
  3385. if (module)
  3386. {
  3387. extraspec = module->extraspec;
  3388. if (extraspec && extraspec->get_curve_param)
  3389. result = extraspec->get_curve_param (name);
  3390. ath_mutex_lock (&pubkeys_registered_lock);
  3391. _gcry_module_release (module);
  3392. ath_mutex_unlock (&pubkeys_registered_lock);
  3393. }
  3394. return result;
  3395. }
  3396. gcry_error_t
  3397. gcry_pk_ctl (int cmd, void *buffer, size_t buflen)
  3398. {
  3399. gcry_err_code_t err = GPG_ERR_NO_ERROR;
  3400. REGISTER_DEFAULT_PUBKEYS;
  3401. switch (cmd)
  3402. {
  3403. case GCRYCTL_DISABLE_ALGO:
  3404. /* This one expects a buffer pointing to an integer with the
  3405. algo number. */
  3406. if ((! buffer) || (buflen != sizeof (int)))
  3407. err = GPG_ERR_INV_ARG;
  3408. else
  3409. disable_pubkey_algo (*((int *) buffer));
  3410. break;
  3411. default:
  3412. err = GPG_ERR_INV_OP;
  3413. }
  3414. return gcry_error (err);
  3415. }
  3416. /* Return information about the given algorithm
  3417. WHAT selects the kind of information returned:
  3418. GCRYCTL_TEST_ALGO:
  3419. Returns 0 when the specified algorithm is available for use.
  3420. Buffer must be NULL, nbytes may have the address of a variable
  3421. with the required usage of the algorithm. It may be 0 for don't
  3422. care or a combination of the GCRY_PK_USAGE_xxx flags;
  3423. GCRYCTL_GET_ALGO_USAGE:
  3424. Return the usage flags for the given algo. An invalid algo
  3425. returns 0. Disabled algos are ignored here because we
  3426. only want to know whether the algo is at all capable of
  3427. the usage.
  3428. Note: Because this function is in most cases used to return an
  3429. integer value, we can make it easier for the caller to just look at
  3430. the return value. The caller will in all cases consult the value
  3431. and thereby detecting whether a error occurred or not (i.e. while
  3432. checking the block size) */
  3433. gcry_error_t
  3434. gcry_pk_algo_info (int algorithm, int what, void *buffer, size_t *nbytes)
  3435. {
  3436. gcry_err_code_t err = GPG_ERR_NO_ERROR;
  3437. switch (what)
  3438. {
  3439. case GCRYCTL_TEST_ALGO:
  3440. {
  3441. int use = nbytes ? *nbytes : 0;
  3442. if (buffer)
  3443. err = GPG_ERR_INV_ARG;
  3444. else if (check_pubkey_algo (algorithm, use))
  3445. err = GPG_ERR_PUBKEY_ALGO;
  3446. break;
  3447. }
  3448. case GCRYCTL_GET_ALGO_USAGE:
  3449. {
  3450. gcry_module_t pubkey;
  3451. int use = 0;
  3452. REGISTER_DEFAULT_PUBKEYS;
  3453. ath_mutex_lock (&pubkeys_registered_lock);
  3454. pubkey = _gcry_module_lookup_id (pubkeys_registered, algorithm);
  3455. if (pubkey)
  3456. {
  3457. use = ((gcry_pk_spec_t *) pubkey->spec)->use;
  3458. _gcry_module_release (pubkey);
  3459. }
  3460. ath_mutex_unlock (&pubkeys_registered_lock);
  3461. /* FIXME? */
  3462. *nbytes = use;
  3463. break;
  3464. }
  3465. case GCRYCTL_GET_ALGO_NPKEY:
  3466. {
  3467. /* FIXME? */
  3468. int npkey = pubkey_get_npkey (algorithm);
  3469. *nbytes = npkey;
  3470. break;
  3471. }
  3472. case GCRYCTL_GET_ALGO_NSKEY:
  3473. {
  3474. /* FIXME? */
  3475. int nskey = pubkey_get_nskey (algorithm);
  3476. *nbytes = nskey;
  3477. break;
  3478. }
  3479. case GCRYCTL_GET_ALGO_NSIGN:
  3480. {
  3481. /* FIXME? */
  3482. int nsign = pubkey_get_nsig (algorithm);
  3483. *nbytes = nsign;
  3484. break;
  3485. }
  3486. case GCRYCTL_GET_ALGO_NENCR:
  3487. {
  3488. /* FIXME? */
  3489. int nencr = pubkey_get_nenc (algorithm);
  3490. *nbytes = nencr;
  3491. break;
  3492. }
  3493. default:
  3494. err = GPG_ERR_INV_OP;
  3495. }
  3496. return gcry_error (err);
  3497. }
  3498. /* Explicitly initialize this module. */
  3499. gcry_err_code_t
  3500. _gcry_pk_init (void)
  3501. {
  3502. gcry_err_code_t err = GPG_ERR_NO_ERROR;
  3503. REGISTER_DEFAULT_PUBKEYS;
  3504. return err;
  3505. }
  3506. gcry_err_code_t
  3507. _gcry_pk_module_lookup (int algorithm, gcry_module_t *module)
  3508. {
  3509. gcry_err_code_t err = GPG_ERR_NO_ERROR;
  3510. gcry_module_t pubkey;
  3511. REGISTER_DEFAULT_PUBKEYS;
  3512. ath_mutex_lock (&pubkeys_registered_lock);
  3513. pubkey = _gcry_module_lookup_id (pubkeys_registered, algorithm);
  3514. if (pubkey)
  3515. *module = pubkey;
  3516. else
  3517. err = GPG_ERR_PUBKEY_ALGO;
  3518. ath_mutex_unlock (&pubkeys_registered_lock);
  3519. return err;
  3520. }
  3521. void
  3522. _gcry_pk_module_release (gcry_module_t module)
  3523. {
  3524. ath_mutex_lock (&pubkeys_registered_lock);
  3525. _gcry_module_release (module);
  3526. ath_mutex_unlock (&pubkeys_registered_lock);
  3527. }
  3528. /* Get a list consisting of the IDs of the loaded pubkey modules. If
  3529. LIST is zero, write the number of loaded pubkey modules to
  3530. LIST_LENGTH and return. If LIST is non-zero, the first
  3531. *LIST_LENGTH algorithm IDs are stored in LIST, which must be of
  3532. according size. In case there are less pubkey modules than
  3533. *LIST_LENGTH, *LIST_LENGTH is updated to the correct number. */
  3534. gcry_error_t
  3535. gcry_pk_list (int *list, int *list_length)
  3536. {
  3537. gcry_err_code_t err = GPG_ERR_NO_ERROR;
  3538. ath_mutex_lock (&pubkeys_registered_lock);
  3539. err = _gcry_module_list (pubkeys_registered, list, list_length);
  3540. ath_mutex_unlock (&pubkeys_registered_lock);
  3541. return err;
  3542. }
  3543. /* Run the selftests for pubkey algorithm ALGO with optional reporting
  3544. function REPORT. */
  3545. gpg_error_t
  3546. _gcry_pk_selftest (int algo, int extended, selftest_report_func_t report)
  3547. {
  3548. gcry_module_t module = NULL;
  3549. pk_extra_spec_t *extraspec = NULL;
  3550. gcry_err_code_t ec = 0;
  3551. REGISTER_DEFAULT_PUBKEYS;
  3552. ath_mutex_lock (&pubkeys_registered_lock);
  3553. module = _gcry_module_lookup_id (pubkeys_registered, algo);
  3554. if (module && !(module->flags & FLAG_MODULE_DISABLED))
  3555. extraspec = module->extraspec;
  3556. ath_mutex_unlock (&pubkeys_registered_lock);
  3557. if (extraspec && extraspec->selftest)
  3558. ec = extraspec->selftest (algo, extended, report);
  3559. else
  3560. {
  3561. ec = GPG_ERR_PUBKEY_ALGO;
  3562. if (report)
  3563. report ("pubkey", algo, "module",
  3564. module && !(module->flags & FLAG_MODULE_DISABLED)?
  3565. "no selftest available" :
  3566. module? "algorithm disabled" : "algorithm not found");
  3567. }
  3568. if (module)
  3569. {
  3570. ath_mutex_lock (&pubkeys_registered_lock);
  3571. _gcry_module_release (module);
  3572. ath_mutex_unlock (&pubkeys_registered_lock);
  3573. }
  3574. return gpg_error (ec);
  3575. }
  3576. /* This function is only used by ac.c! */
  3577. gcry_err_code_t
  3578. _gcry_pk_get_elements (int algo, char **enc, char **sig)
  3579. {
  3580. gcry_module_t pubkey;
  3581. gcry_pk_spec_t *spec;
  3582. gcry_err_code_t err;
  3583. char *enc_cp;
  3584. char *sig_cp;
  3585. REGISTER_DEFAULT_PUBKEYS;
  3586. enc_cp = NULL;
  3587. sig_cp = NULL;
  3588. spec = NULL;
  3589. pubkey = _gcry_module_lookup_id (pubkeys_registered, algo);
  3590. if (! pubkey)
  3591. {
  3592. err = GPG_ERR_INTERNAL;
  3593. goto out;
  3594. }
  3595. spec = pubkey->spec;
  3596. if (enc)
  3597. {
  3598. enc_cp = strdup (spec->elements_enc);
  3599. if (! enc_cp)
  3600. {
  3601. err = gpg_err_code_from_syserror ();
  3602. goto out;
  3603. }
  3604. }
  3605. if (sig)
  3606. {
  3607. sig_cp = strdup (spec->elements_sig);
  3608. if (! sig_cp)
  3609. {
  3610. err = gpg_err_code_from_syserror ();
  3611. goto out;
  3612. }
  3613. }
  3614. if (enc)
  3615. *enc = enc_cp;
  3616. if (sig)
  3617. *sig = sig_cp;
  3618. err = 0;
  3619. out:
  3620. _gcry_module_release (pubkey);
  3621. if (err)
  3622. {
  3623. free (enc_cp);
  3624. free (sig_cp);
  3625. }
  3626. return err;
  3627. }