_hashopenssl.c 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340
  1. /* Module that wraps all OpenSSL hash algorithms */
  2. /*
  3. * Copyright (C) 2005-2010 Gregory P. Smith (greg@krypto.org)
  4. * Licensed to PSF under a Contributor Agreement.
  5. *
  6. * Derived from a skeleton of shamodule.c containing work performed by:
  7. *
  8. * Andrew Kuchling (amk@amk.ca)
  9. * Greg Stein (gstein@lyra.org)
  10. *
  11. */
  12. /* Don't warn about deprecated functions, */
  13. #ifndef OPENSSL_API_COMPAT
  14. // 0x10101000L == 1.1.1, 30000 == 3.0.0
  15. #define OPENSSL_API_COMPAT 0x10101000L
  16. #endif
  17. #define OPENSSL_NO_DEPRECATED 1
  18. #ifndef Py_BUILD_CORE_BUILTIN
  19. # define Py_BUILD_CORE_MODULE 1
  20. #endif
  21. #define PY_SSIZE_T_CLEAN
  22. #include "Python.h"
  23. #include "pycore_hashtable.h"
  24. #include "hashlib.h"
  25. #include "pycore_strhex.h" // _Py_strhex()
  26. /* EVP is the preferred interface to hashing in OpenSSL */
  27. #include <openssl/evp.h>
  28. #include <openssl/hmac.h>
  29. #include <openssl/crypto.h> // FIPS_mode()
  30. /* We use the object interface to discover what hashes OpenSSL supports. */
  31. #include <openssl/objects.h>
  32. #include <openssl/err.h>
  33. #ifndef OPENSSL_THREADS
  34. # error "OPENSSL_THREADS is not defined, Python requires thread-safe OpenSSL"
  35. #endif
  36. #define MUNCH_SIZE INT_MAX
  37. #define PY_OPENSSL_HAS_SCRYPT 1
  38. #if defined(NID_sha3_224) && defined(NID_sha3_256) && defined(NID_sha3_384) && defined(NID_sha3_512)
  39. #define PY_OPENSSL_HAS_SHA3 1
  40. #endif
  41. #if defined(NID_shake128) || defined(NID_shake256)
  42. #define PY_OPENSSL_HAS_SHAKE 1
  43. #endif
  44. #if defined(NID_blake2s256) || defined(NID_blake2b512)
  45. #define PY_OPENSSL_HAS_BLAKE2 1
  46. #endif
  47. #if OPENSSL_VERSION_NUMBER >= 0x30000000L
  48. #define PY_EVP_MD EVP_MD
  49. #define PY_EVP_MD_fetch(algorithm, properties) EVP_MD_fetch(NULL, algorithm, properties)
  50. #define PY_EVP_MD_up_ref(md) EVP_MD_up_ref(md)
  51. #define PY_EVP_MD_free(md) EVP_MD_free(md)
  52. #else
  53. #define PY_EVP_MD const EVP_MD
  54. #define PY_EVP_MD_fetch(algorithm, properties) EVP_get_digestbyname(algorithm)
  55. #define PY_EVP_MD_up_ref(md) do {} while(0)
  56. #define PY_EVP_MD_free(md) do {} while(0)
  57. #endif
  58. /* hash alias map and fast lookup
  59. *
  60. * Map between Python's preferred names and OpenSSL internal names. Maintain
  61. * cache of fetched EVP MD objects. The EVP_get_digestbyname() and
  62. * EVP_MD_fetch() API calls have a performance impact.
  63. *
  64. * The py_hashentry_t items are stored in a _Py_hashtable_t with py_name and
  65. * py_alias as keys.
  66. */
  67. enum Py_hash_type {
  68. Py_ht_evp, // usedforsecurity=True / default
  69. Py_ht_evp_nosecurity, // usedforsecurity=False
  70. Py_ht_mac, // HMAC
  71. Py_ht_pbkdf2, // PKBDF2
  72. };
  73. typedef struct {
  74. const char *py_name;
  75. const char *py_alias;
  76. const char *ossl_name;
  77. int ossl_nid;
  78. int refcnt;
  79. PY_EVP_MD *evp;
  80. PY_EVP_MD *evp_nosecurity;
  81. } py_hashentry_t;
  82. // Fundamental to TLS, assumed always present in any libcrypto:
  83. #define Py_hash_md5 "md5"
  84. #define Py_hash_sha1 "sha1"
  85. #define Py_hash_sha224 "sha224"
  86. #define Py_hash_sha256 "sha256"
  87. #define Py_hash_sha384 "sha384"
  88. #define Py_hash_sha512 "sha512"
  89. // Not all OpenSSL-like libcrypto libraries provide these:
  90. #if defined(NID_sha512_224)
  91. # define Py_hash_sha512_224 "sha512_224"
  92. #endif
  93. #if defined(NID_sha512_256)
  94. # define Py_hash_sha512_256 "sha512_256"
  95. #endif
  96. #if defined(NID_sha3_224)
  97. # define Py_hash_sha3_224 "sha3_224"
  98. #endif
  99. #if defined(NID_sha3_256)
  100. # define Py_hash_sha3_256 "sha3_256"
  101. #endif
  102. #if defined(NID_sha3_384)
  103. # define Py_hash_sha3_384 "sha3_384"
  104. #endif
  105. #if defined(NID_sha3_512)
  106. # define Py_hash_sha3_512 "sha3_512"
  107. #endif
  108. #if defined(NID_shake128)
  109. # define Py_hash_shake_128 "shake_128"
  110. #endif
  111. #if defined(NID_shake256)
  112. # define Py_hash_shake_256 "shake_256"
  113. #endif
  114. #if defined(NID_blake2s256)
  115. # define Py_hash_blake2s "blake2s"
  116. #endif
  117. #if defined(NID_blake2b512)
  118. # define Py_hash_blake2b "blake2b"
  119. #endif
  120. #define PY_HASH_ENTRY(py_name, py_alias, ossl_name, ossl_nid) \
  121. {py_name, py_alias, ossl_name, ossl_nid, 0, NULL, NULL}
  122. static const py_hashentry_t py_hashes[] = {
  123. /* md5 */
  124. PY_HASH_ENTRY(Py_hash_md5, "MD5", SN_md5, NID_md5),
  125. /* sha1 */
  126. PY_HASH_ENTRY(Py_hash_sha1, "SHA1", SN_sha1, NID_sha1),
  127. /* sha2 family */
  128. PY_HASH_ENTRY(Py_hash_sha224, "SHA224", SN_sha224, NID_sha224),
  129. PY_HASH_ENTRY(Py_hash_sha256, "SHA256", SN_sha256, NID_sha256),
  130. PY_HASH_ENTRY(Py_hash_sha384, "SHA384", SN_sha384, NID_sha384),
  131. PY_HASH_ENTRY(Py_hash_sha512, "SHA512", SN_sha512, NID_sha512),
  132. /* truncated sha2 */
  133. #ifdef Py_hash_sha512_224
  134. PY_HASH_ENTRY(Py_hash_sha512_224, "SHA512_224", SN_sha512_224, NID_sha512_224),
  135. #endif
  136. #ifdef Py_hash_sha512_256
  137. PY_HASH_ENTRY(Py_hash_sha512_256, "SHA512_256", SN_sha512_256, NID_sha512_256),
  138. #endif
  139. /* sha3 */
  140. #ifdef Py_hash_sha3_224
  141. PY_HASH_ENTRY(Py_hash_sha3_224, NULL, SN_sha3_224, NID_sha3_224),
  142. #endif
  143. #ifdef Py_hash_sha3_256
  144. PY_HASH_ENTRY(Py_hash_sha3_256, NULL, SN_sha3_256, NID_sha3_256),
  145. #endif
  146. #ifdef Py_hash_sha3_384
  147. PY_HASH_ENTRY(Py_hash_sha3_384, NULL, SN_sha3_384, NID_sha3_384),
  148. #endif
  149. #ifdef Py_hash_sha3_512
  150. PY_HASH_ENTRY(Py_hash_sha3_512, NULL, SN_sha3_512, NID_sha3_512),
  151. #endif
  152. /* sha3 shake */
  153. #ifdef Py_hash_shake_128
  154. PY_HASH_ENTRY(Py_hash_shake_128, NULL, SN_shake128, NID_shake128),
  155. #endif
  156. #ifdef Py_hash_shake_256
  157. PY_HASH_ENTRY(Py_hash_shake_256, NULL, SN_shake256, NID_shake256),
  158. #endif
  159. /* blake2 digest */
  160. #ifdef Py_hash_blake2s
  161. PY_HASH_ENTRY(Py_hash_blake2s, "blake2s256", SN_blake2s256, NID_blake2s256),
  162. #endif
  163. #ifdef Py_hash_blake2b
  164. PY_HASH_ENTRY(Py_hash_blake2b, "blake2b512", SN_blake2b512, NID_blake2b512),
  165. #endif
  166. PY_HASH_ENTRY(NULL, NULL, NULL, 0),
  167. };
  168. static Py_uhash_t
  169. py_hashentry_t_hash_name(const void *key) {
  170. return _Py_HashBytes(key, strlen((const char *)key));
  171. }
  172. static int
  173. py_hashentry_t_compare_name(const void *key1, const void *key2) {
  174. return strcmp((const char *)key1, (const char *)key2) == 0;
  175. }
  176. static void
  177. py_hashentry_t_destroy_value(void *entry) {
  178. py_hashentry_t *h = (py_hashentry_t *)entry;
  179. if (--(h->refcnt) == 0) {
  180. if (h->evp != NULL) {
  181. PY_EVP_MD_free(h->evp);
  182. h->evp = NULL;
  183. }
  184. if (h->evp_nosecurity != NULL) {
  185. PY_EVP_MD_free(h->evp_nosecurity);
  186. h->evp_nosecurity = NULL;
  187. }
  188. PyMem_Free(entry);
  189. }
  190. }
  191. static _Py_hashtable_t *
  192. py_hashentry_table_new(void) {
  193. _Py_hashtable_t *ht = _Py_hashtable_new_full(
  194. py_hashentry_t_hash_name,
  195. py_hashentry_t_compare_name,
  196. NULL,
  197. py_hashentry_t_destroy_value,
  198. NULL
  199. );
  200. if (ht == NULL) {
  201. return NULL;
  202. }
  203. for (const py_hashentry_t *h = py_hashes; h->py_name != NULL; h++) {
  204. py_hashentry_t *entry = (py_hashentry_t *)PyMem_Malloc(sizeof(py_hashentry_t));
  205. if (entry == NULL) {
  206. goto error;
  207. }
  208. memcpy(entry, h, sizeof(py_hashentry_t));
  209. if (_Py_hashtable_set(ht, (const void*)entry->py_name, (void*)entry) < 0) {
  210. PyMem_Free(entry);
  211. goto error;
  212. }
  213. entry->refcnt = 1;
  214. if (h->py_alias != NULL) {
  215. if (_Py_hashtable_set(ht, (const void*)entry->py_alias, (void*)entry) < 0) {
  216. PyMem_Free(entry);
  217. goto error;
  218. }
  219. entry->refcnt++;
  220. }
  221. }
  222. return ht;
  223. error:
  224. _Py_hashtable_destroy(ht);
  225. return NULL;
  226. }
  227. /* Module state */
  228. static PyModuleDef _hashlibmodule;
  229. typedef struct {
  230. PyTypeObject *EVPtype;
  231. PyTypeObject *HMACtype;
  232. #ifdef PY_OPENSSL_HAS_SHAKE
  233. PyTypeObject *EVPXOFtype;
  234. #endif
  235. PyObject *constructs;
  236. PyObject *unsupported_digestmod_error;
  237. _Py_hashtable_t *hashtable;
  238. } _hashlibstate;
  239. static inline _hashlibstate*
  240. get_hashlib_state(PyObject *module)
  241. {
  242. void *state = PyModule_GetState(module);
  243. assert(state != NULL);
  244. return (_hashlibstate *)state;
  245. }
  246. typedef struct {
  247. PyObject_HEAD
  248. EVP_MD_CTX *ctx; /* OpenSSL message digest context */
  249. // Prevents undefined behavior via multiple threads entering the C API.
  250. // The lock will be NULL before threaded access has been enabled.
  251. PyThread_type_lock lock; /* OpenSSL context lock */
  252. } EVPobject;
  253. typedef struct {
  254. PyObject_HEAD
  255. HMAC_CTX *ctx; /* OpenSSL hmac context */
  256. // Prevents undefined behavior via multiple threads entering the C API.
  257. // The lock will be NULL before threaded access has been enabled.
  258. PyThread_type_lock lock; /* HMAC context lock */
  259. } HMACobject;
  260. #include "clinic/_hashopenssl.c.h"
  261. /*[clinic input]
  262. module _hashlib
  263. class _hashlib.HASH "EVPobject *" "((_hashlibstate *)PyModule_GetState(module))->EVPtype"
  264. class _hashlib.HASHXOF "EVPobject *" "((_hashlibstate *)PyModule_GetState(module))->EVPXOFtype"
  265. class _hashlib.HMAC "HMACobject *" "((_hashlibstate *)PyModule_GetState(module))->HMACtype"
  266. [clinic start generated code]*/
  267. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=7df1bcf6f75cb8ef]*/
  268. /* LCOV_EXCL_START */
  269. static PyObject *
  270. _setException(PyObject *exc, const char* altmsg, ...)
  271. {
  272. unsigned long errcode = ERR_peek_last_error();
  273. const char *lib, *func, *reason;
  274. va_list vargs;
  275. va_start(vargs, altmsg);
  276. if (!errcode) {
  277. if (altmsg == NULL) {
  278. PyErr_SetString(exc, "no reason supplied");
  279. } else {
  280. PyErr_FormatV(exc, altmsg, vargs);
  281. }
  282. va_end(vargs);
  283. return NULL;
  284. }
  285. va_end(vargs);
  286. ERR_clear_error();
  287. /* ERR_ERROR_STRING(3) ensures that the messages below are ASCII */
  288. lib = ERR_lib_error_string(errcode);
  289. func = ERR_func_error_string(errcode);
  290. reason = ERR_reason_error_string(errcode);
  291. if (lib && func) {
  292. PyErr_Format(exc, "[%s: %s] %s", lib, func, reason);
  293. }
  294. else if (lib) {
  295. PyErr_Format(exc, "[%s] %s", lib, reason);
  296. }
  297. else {
  298. PyErr_SetString(exc, reason);
  299. }
  300. return NULL;
  301. }
  302. /* LCOV_EXCL_STOP */
  303. static PyObject*
  304. py_digest_name(const EVP_MD *md)
  305. {
  306. int nid = EVP_MD_nid(md);
  307. const char *name = NULL;
  308. const py_hashentry_t *h;
  309. for (h = py_hashes; h->py_name != NULL; h++) {
  310. if (h->ossl_nid == nid) {
  311. name = h->py_name;
  312. break;
  313. }
  314. }
  315. if (name == NULL) {
  316. /* Ignore aliased names and only use long, lowercase name. The aliases
  317. * pollute the list and OpenSSL appears to have its own definition of
  318. * alias as the resulting list still contains duplicate and alternate
  319. * names for several algorithms.
  320. */
  321. name = OBJ_nid2ln(nid);
  322. if (name == NULL)
  323. name = OBJ_nid2sn(nid);
  324. }
  325. return PyUnicode_FromString(name);
  326. }
  327. /* Get EVP_MD by HID and purpose */
  328. static PY_EVP_MD*
  329. py_digest_by_name(PyObject *module, const char *name, enum Py_hash_type py_ht)
  330. {
  331. PY_EVP_MD *digest = NULL;
  332. _hashlibstate *state = get_hashlib_state(module);
  333. py_hashentry_t *entry = (py_hashentry_t *)_Py_hashtable_get(
  334. state->hashtable, (const void*)name
  335. );
  336. if (entry != NULL) {
  337. switch (py_ht) {
  338. case Py_ht_evp:
  339. case Py_ht_mac:
  340. case Py_ht_pbkdf2:
  341. if (entry->evp == NULL) {
  342. entry->evp = PY_EVP_MD_fetch(entry->ossl_name, NULL);
  343. }
  344. digest = entry->evp;
  345. break;
  346. case Py_ht_evp_nosecurity:
  347. if (entry->evp_nosecurity == NULL) {
  348. entry->evp_nosecurity = PY_EVP_MD_fetch(entry->ossl_name, "-fips");
  349. }
  350. digest = entry->evp_nosecurity;
  351. break;
  352. }
  353. if (digest != NULL) {
  354. PY_EVP_MD_up_ref(digest);
  355. }
  356. } else {
  357. // Fall back for looking up an unindexed OpenSSL specific name.
  358. switch (py_ht) {
  359. case Py_ht_evp:
  360. case Py_ht_mac:
  361. case Py_ht_pbkdf2:
  362. digest = PY_EVP_MD_fetch(name, NULL);
  363. break;
  364. case Py_ht_evp_nosecurity:
  365. digest = PY_EVP_MD_fetch(name, "-fips");
  366. break;
  367. }
  368. }
  369. if (digest == NULL) {
  370. _setException(state->unsupported_digestmod_error, "unsupported hash type %s", name);
  371. return NULL;
  372. }
  373. return digest;
  374. }
  375. /* Get digest EVP from object
  376. *
  377. * * string
  378. * * _hashopenssl builtin function
  379. *
  380. * on error returns NULL with exception set.
  381. */
  382. static PY_EVP_MD*
  383. py_digest_by_digestmod(PyObject *module, PyObject *digestmod, enum Py_hash_type py_ht) {
  384. PY_EVP_MD* evp;
  385. PyObject *name_obj = NULL;
  386. const char *name;
  387. if (PyUnicode_Check(digestmod)) {
  388. name_obj = digestmod;
  389. } else {
  390. _hashlibstate *state = get_hashlib_state(module);
  391. // borrowed ref
  392. name_obj = PyDict_GetItemWithError(state->constructs, digestmod);
  393. }
  394. if (name_obj == NULL) {
  395. if (!PyErr_Occurred()) {
  396. _hashlibstate *state = get_hashlib_state(module);
  397. PyErr_Format(
  398. state->unsupported_digestmod_error,
  399. "Unsupported digestmod %R", digestmod);
  400. }
  401. return NULL;
  402. }
  403. name = PyUnicode_AsUTF8(name_obj);
  404. if (name == NULL) {
  405. return NULL;
  406. }
  407. evp = py_digest_by_name(module, name, py_ht);
  408. if (evp == NULL) {
  409. return NULL;
  410. }
  411. return evp;
  412. }
  413. static EVPobject *
  414. newEVPobject(PyTypeObject *type)
  415. {
  416. EVPobject *retval = (EVPobject *)PyObject_New(EVPobject, type);
  417. if (retval == NULL) {
  418. return NULL;
  419. }
  420. retval->lock = NULL;
  421. retval->ctx = EVP_MD_CTX_new();
  422. if (retval->ctx == NULL) {
  423. Py_DECREF(retval);
  424. PyErr_NoMemory();
  425. return NULL;
  426. }
  427. return retval;
  428. }
  429. static int
  430. EVP_hash(EVPobject *self, const void *vp, Py_ssize_t len)
  431. {
  432. unsigned int process;
  433. const unsigned char *cp = (const unsigned char *)vp;
  434. while (0 < len) {
  435. if (len > (Py_ssize_t)MUNCH_SIZE)
  436. process = MUNCH_SIZE;
  437. else
  438. process = Py_SAFE_DOWNCAST(len, Py_ssize_t, unsigned int);
  439. if (!EVP_DigestUpdate(self->ctx, (const void*)cp, process)) {
  440. _setException(PyExc_ValueError, NULL);
  441. return -1;
  442. }
  443. len -= process;
  444. cp += process;
  445. }
  446. return 0;
  447. }
  448. /* Internal methods for a hash object */
  449. static void
  450. EVP_dealloc(EVPobject *self)
  451. {
  452. PyTypeObject *tp = Py_TYPE(self);
  453. if (self->lock != NULL)
  454. PyThread_free_lock(self->lock);
  455. EVP_MD_CTX_free(self->ctx);
  456. PyObject_Free(self);
  457. Py_DECREF(tp);
  458. }
  459. static int
  460. locked_EVP_MD_CTX_copy(EVP_MD_CTX *new_ctx_p, EVPobject *self)
  461. {
  462. int result;
  463. ENTER_HASHLIB(self);
  464. result = EVP_MD_CTX_copy(new_ctx_p, self->ctx);
  465. LEAVE_HASHLIB(self);
  466. return result;
  467. }
  468. /* External methods for a hash object */
  469. /*[clinic input]
  470. _hashlib.HASH.copy as EVP_copy
  471. Return a copy of the hash object.
  472. [clinic start generated code]*/
  473. static PyObject *
  474. EVP_copy_impl(EVPobject *self)
  475. /*[clinic end generated code: output=b370c21cdb8ca0b4 input=31455b6a3e638069]*/
  476. {
  477. EVPobject *newobj;
  478. if ((newobj = newEVPobject(Py_TYPE(self))) == NULL)
  479. return NULL;
  480. if (!locked_EVP_MD_CTX_copy(newobj->ctx, self)) {
  481. Py_DECREF(newobj);
  482. return _setException(PyExc_ValueError, NULL);
  483. }
  484. return (PyObject *)newobj;
  485. }
  486. /*[clinic input]
  487. _hashlib.HASH.digest as EVP_digest
  488. Return the digest value as a bytes object.
  489. [clinic start generated code]*/
  490. static PyObject *
  491. EVP_digest_impl(EVPobject *self)
  492. /*[clinic end generated code: output=0f6a3a0da46dc12d input=03561809a419bf00]*/
  493. {
  494. unsigned char digest[EVP_MAX_MD_SIZE];
  495. EVP_MD_CTX *temp_ctx;
  496. PyObject *retval;
  497. unsigned int digest_size;
  498. temp_ctx = EVP_MD_CTX_new();
  499. if (temp_ctx == NULL) {
  500. PyErr_NoMemory();
  501. return NULL;
  502. }
  503. if (!locked_EVP_MD_CTX_copy(temp_ctx, self)) {
  504. return _setException(PyExc_ValueError, NULL);
  505. }
  506. digest_size = EVP_MD_CTX_size(temp_ctx);
  507. if (!EVP_DigestFinal(temp_ctx, digest, NULL)) {
  508. _setException(PyExc_ValueError, NULL);
  509. return NULL;
  510. }
  511. retval = PyBytes_FromStringAndSize((const char *)digest, digest_size);
  512. EVP_MD_CTX_free(temp_ctx);
  513. return retval;
  514. }
  515. /*[clinic input]
  516. _hashlib.HASH.hexdigest as EVP_hexdigest
  517. Return the digest value as a string of hexadecimal digits.
  518. [clinic start generated code]*/
  519. static PyObject *
  520. EVP_hexdigest_impl(EVPobject *self)
  521. /*[clinic end generated code: output=18e6decbaf197296 input=aff9cf0e4c741a9a]*/
  522. {
  523. unsigned char digest[EVP_MAX_MD_SIZE];
  524. EVP_MD_CTX *temp_ctx;
  525. unsigned int digest_size;
  526. temp_ctx = EVP_MD_CTX_new();
  527. if (temp_ctx == NULL) {
  528. PyErr_NoMemory();
  529. return NULL;
  530. }
  531. /* Get the raw (binary) digest value */
  532. if (!locked_EVP_MD_CTX_copy(temp_ctx, self)) {
  533. return _setException(PyExc_ValueError, NULL);
  534. }
  535. digest_size = EVP_MD_CTX_size(temp_ctx);
  536. if (!EVP_DigestFinal(temp_ctx, digest, NULL)) {
  537. _setException(PyExc_ValueError, NULL);
  538. return NULL;
  539. }
  540. EVP_MD_CTX_free(temp_ctx);
  541. return _Py_strhex((const char *)digest, (Py_ssize_t)digest_size);
  542. }
  543. /*[clinic input]
  544. _hashlib.HASH.update as EVP_update
  545. obj: object
  546. /
  547. Update this hash object's state with the provided string.
  548. [clinic start generated code]*/
  549. static PyObject *
  550. EVP_update(EVPobject *self, PyObject *obj)
  551. /*[clinic end generated code: output=ec1d55ed2432e966 input=9b30ec848f015501]*/
  552. {
  553. int result;
  554. Py_buffer view;
  555. GET_BUFFER_VIEW_OR_ERROUT(obj, &view);
  556. if (self->lock == NULL && view.len >= HASHLIB_GIL_MINSIZE) {
  557. self->lock = PyThread_allocate_lock();
  558. /* fail? lock = NULL and we fail over to non-threaded code. */
  559. }
  560. if (self->lock != NULL) {
  561. Py_BEGIN_ALLOW_THREADS
  562. PyThread_acquire_lock(self->lock, 1);
  563. result = EVP_hash(self, view.buf, view.len);
  564. PyThread_release_lock(self->lock);
  565. Py_END_ALLOW_THREADS
  566. } else {
  567. result = EVP_hash(self, view.buf, view.len);
  568. }
  569. PyBuffer_Release(&view);
  570. if (result == -1)
  571. return NULL;
  572. Py_RETURN_NONE;
  573. }
  574. static PyMethodDef EVP_methods[] = {
  575. EVP_UPDATE_METHODDEF
  576. EVP_DIGEST_METHODDEF
  577. EVP_HEXDIGEST_METHODDEF
  578. EVP_COPY_METHODDEF
  579. {NULL, NULL} /* sentinel */
  580. };
  581. static PyObject *
  582. EVP_get_block_size(EVPobject *self, void *closure)
  583. {
  584. long block_size;
  585. block_size = EVP_MD_CTX_block_size(self->ctx);
  586. return PyLong_FromLong(block_size);
  587. }
  588. static PyObject *
  589. EVP_get_digest_size(EVPobject *self, void *closure)
  590. {
  591. long size;
  592. size = EVP_MD_CTX_size(self->ctx);
  593. return PyLong_FromLong(size);
  594. }
  595. static PyObject *
  596. EVP_get_name(EVPobject *self, void *closure)
  597. {
  598. return py_digest_name(EVP_MD_CTX_md(self->ctx));
  599. }
  600. static PyGetSetDef EVP_getseters[] = {
  601. {"digest_size",
  602. (getter)EVP_get_digest_size, NULL,
  603. NULL,
  604. NULL},
  605. {"block_size",
  606. (getter)EVP_get_block_size, NULL,
  607. NULL,
  608. NULL},
  609. {"name",
  610. (getter)EVP_get_name, NULL,
  611. NULL,
  612. PyDoc_STR("algorithm name.")},
  613. {NULL} /* Sentinel */
  614. };
  615. static PyObject *
  616. EVP_repr(EVPobject *self)
  617. {
  618. PyObject *name_obj, *repr;
  619. name_obj = py_digest_name(EVP_MD_CTX_md(self->ctx));
  620. if (!name_obj) {
  621. return NULL;
  622. }
  623. repr = PyUnicode_FromFormat("<%U %s object @ %p>",
  624. name_obj, Py_TYPE(self)->tp_name, self);
  625. Py_DECREF(name_obj);
  626. return repr;
  627. }
  628. PyDoc_STRVAR(hashtype_doc,
  629. "HASH(name, string=b\'\')\n"
  630. "--\n"
  631. "\n"
  632. "A hash is an object used to calculate a checksum of a string of information.\n"
  633. "\n"
  634. "Methods:\n"
  635. "\n"
  636. "update() -- updates the current digest with an additional string\n"
  637. "digest() -- return the current digest value\n"
  638. "hexdigest() -- return the current digest as a string of hexadecimal digits\n"
  639. "copy() -- return a copy of the current hash object\n"
  640. "\n"
  641. "Attributes:\n"
  642. "\n"
  643. "name -- the hash algorithm being used by this object\n"
  644. "digest_size -- number of bytes in this hashes output");
  645. static PyType_Slot EVPtype_slots[] = {
  646. {Py_tp_dealloc, EVP_dealloc},
  647. {Py_tp_repr, EVP_repr},
  648. {Py_tp_doc, (char *)hashtype_doc},
  649. {Py_tp_methods, EVP_methods},
  650. {Py_tp_getset, EVP_getseters},
  651. {0, 0},
  652. };
  653. static PyType_Spec EVPtype_spec = {
  654. "_hashlib.HASH", /*tp_name*/
  655. sizeof(EVPobject), /*tp_basicsize*/
  656. 0, /*tp_itemsize*/
  657. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION | Py_TPFLAGS_IMMUTABLETYPE,
  658. EVPtype_slots
  659. };
  660. #ifdef PY_OPENSSL_HAS_SHAKE
  661. /*[clinic input]
  662. _hashlib.HASHXOF.digest as EVPXOF_digest
  663. length: Py_ssize_t
  664. Return the digest value as a bytes object.
  665. [clinic start generated code]*/
  666. static PyObject *
  667. EVPXOF_digest_impl(EVPobject *self, Py_ssize_t length)
  668. /*[clinic end generated code: output=ef9320c23280efad input=816a6537cea3d1db]*/
  669. {
  670. EVP_MD_CTX *temp_ctx;
  671. PyObject *retval = PyBytes_FromStringAndSize(NULL, length);
  672. if (retval == NULL) {
  673. return NULL;
  674. }
  675. temp_ctx = EVP_MD_CTX_new();
  676. if (temp_ctx == NULL) {
  677. Py_DECREF(retval);
  678. PyErr_NoMemory();
  679. return NULL;
  680. }
  681. if (!locked_EVP_MD_CTX_copy(temp_ctx, self)) {
  682. Py_DECREF(retval);
  683. EVP_MD_CTX_free(temp_ctx);
  684. return _setException(PyExc_ValueError, NULL);
  685. }
  686. if (!EVP_DigestFinalXOF(temp_ctx,
  687. (unsigned char*)PyBytes_AS_STRING(retval),
  688. length)) {
  689. Py_DECREF(retval);
  690. EVP_MD_CTX_free(temp_ctx);
  691. _setException(PyExc_ValueError, NULL);
  692. return NULL;
  693. }
  694. EVP_MD_CTX_free(temp_ctx);
  695. return retval;
  696. }
  697. /*[clinic input]
  698. _hashlib.HASHXOF.hexdigest as EVPXOF_hexdigest
  699. length: Py_ssize_t
  700. Return the digest value as a string of hexadecimal digits.
  701. [clinic start generated code]*/
  702. static PyObject *
  703. EVPXOF_hexdigest_impl(EVPobject *self, Py_ssize_t length)
  704. /*[clinic end generated code: output=eb3e6ee7788bf5b2 input=5f9d6a8f269e34df]*/
  705. {
  706. unsigned char *digest;
  707. EVP_MD_CTX *temp_ctx;
  708. PyObject *retval;
  709. digest = (unsigned char*)PyMem_Malloc(length);
  710. if (digest == NULL) {
  711. PyErr_NoMemory();
  712. return NULL;
  713. }
  714. temp_ctx = EVP_MD_CTX_new();
  715. if (temp_ctx == NULL) {
  716. PyMem_Free(digest);
  717. PyErr_NoMemory();
  718. return NULL;
  719. }
  720. /* Get the raw (binary) digest value */
  721. if (!locked_EVP_MD_CTX_copy(temp_ctx, self)) {
  722. PyMem_Free(digest);
  723. EVP_MD_CTX_free(temp_ctx);
  724. return _setException(PyExc_ValueError, NULL);
  725. }
  726. if (!EVP_DigestFinalXOF(temp_ctx, digest, length)) {
  727. PyMem_Free(digest);
  728. EVP_MD_CTX_free(temp_ctx);
  729. _setException(PyExc_ValueError, NULL);
  730. return NULL;
  731. }
  732. EVP_MD_CTX_free(temp_ctx);
  733. retval = _Py_strhex((const char *)digest, length);
  734. PyMem_Free(digest);
  735. return retval;
  736. }
  737. static PyMethodDef EVPXOF_methods[] = {
  738. EVPXOF_DIGEST_METHODDEF
  739. EVPXOF_HEXDIGEST_METHODDEF
  740. {NULL, NULL} /* sentinel */
  741. };
  742. static PyObject *
  743. EVPXOF_get_digest_size(EVPobject *self, void *closure)
  744. {
  745. return PyLong_FromLong(0);
  746. }
  747. static PyGetSetDef EVPXOF_getseters[] = {
  748. {"digest_size",
  749. (getter)EVPXOF_get_digest_size, NULL,
  750. NULL,
  751. NULL},
  752. {NULL} /* Sentinel */
  753. };
  754. PyDoc_STRVAR(hashxoftype_doc,
  755. "HASHXOF(name, string=b\'\')\n"
  756. "--\n"
  757. "\n"
  758. "A hash is an object used to calculate a checksum of a string of information.\n"
  759. "\n"
  760. "Methods:\n"
  761. "\n"
  762. "update() -- updates the current digest with an additional string\n"
  763. "digest(length) -- return the current digest value\n"
  764. "hexdigest(length) -- return the current digest as a string of hexadecimal digits\n"
  765. "copy() -- return a copy of the current hash object\n"
  766. "\n"
  767. "Attributes:\n"
  768. "\n"
  769. "name -- the hash algorithm being used by this object\n"
  770. "digest_size -- number of bytes in this hashes output");
  771. static PyType_Slot EVPXOFtype_slots[] = {
  772. {Py_tp_doc, (char *)hashxoftype_doc},
  773. {Py_tp_methods, EVPXOF_methods},
  774. {Py_tp_getset, EVPXOF_getseters},
  775. {0, 0},
  776. };
  777. static PyType_Spec EVPXOFtype_spec = {
  778. "_hashlib.HASHXOF", /*tp_name*/
  779. sizeof(EVPobject), /*tp_basicsize*/
  780. 0, /*tp_itemsize*/
  781. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION | Py_TPFLAGS_IMMUTABLETYPE,
  782. EVPXOFtype_slots
  783. };
  784. #endif
  785. static PyObject*
  786. py_evp_fromname(PyObject *module, const char *digestname, PyObject *data_obj,
  787. int usedforsecurity)
  788. {
  789. Py_buffer view = { 0 };
  790. PY_EVP_MD *digest = NULL;
  791. PyTypeObject *type;
  792. EVPobject *self = NULL;
  793. if (data_obj != NULL) {
  794. GET_BUFFER_VIEW_OR_ERROUT(data_obj, &view);
  795. }
  796. digest = py_digest_by_name(
  797. module, digestname, usedforsecurity ? Py_ht_evp : Py_ht_evp_nosecurity
  798. );
  799. if (digest == NULL) {
  800. goto exit;
  801. }
  802. if ((EVP_MD_flags(digest) & EVP_MD_FLAG_XOF) == EVP_MD_FLAG_XOF) {
  803. type = get_hashlib_state(module)->EVPXOFtype;
  804. } else {
  805. type = get_hashlib_state(module)->EVPtype;
  806. }
  807. self = newEVPobject(type);
  808. if (self == NULL) {
  809. goto exit;
  810. }
  811. #if defined(EVP_MD_CTX_FLAG_NON_FIPS_ALLOW) && OPENSSL_VERSION_NUMBER < 0x30000000L
  812. // In OpenSSL 1.1.1 the non FIPS allowed flag is context specific while
  813. // in 3.0.0 it is a different EVP_MD provider.
  814. if (!usedforsecurity) {
  815. EVP_MD_CTX_set_flags(self->ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
  816. }
  817. #endif
  818. int result = EVP_DigestInit_ex(self->ctx, digest, NULL);
  819. if (!result) {
  820. _setException(PyExc_ValueError, NULL);
  821. Py_CLEAR(self);
  822. goto exit;
  823. }
  824. if (view.buf && view.len) {
  825. if (view.len >= HASHLIB_GIL_MINSIZE) {
  826. /* We do not initialize self->lock here as this is the constructor
  827. * where it is not yet possible to have concurrent access. */
  828. Py_BEGIN_ALLOW_THREADS
  829. result = EVP_hash(self, view.buf, view.len);
  830. Py_END_ALLOW_THREADS
  831. } else {
  832. result = EVP_hash(self, view.buf, view.len);
  833. }
  834. if (result == -1) {
  835. Py_CLEAR(self);
  836. goto exit;
  837. }
  838. }
  839. exit:
  840. if (data_obj != NULL) {
  841. PyBuffer_Release(&view);
  842. }
  843. if (digest != NULL) {
  844. PY_EVP_MD_free(digest);
  845. }
  846. return (PyObject *)self;
  847. }
  848. /* The module-level function: new() */
  849. /*[clinic input]
  850. _hashlib.new as EVP_new
  851. name as name_obj: object
  852. string as data_obj: object(c_default="NULL") = b''
  853. *
  854. usedforsecurity: bool = True
  855. Return a new hash object using the named algorithm.
  856. An optional string argument may be provided and will be
  857. automatically hashed.
  858. The MD5 and SHA1 algorithms are always supported.
  859. [clinic start generated code]*/
  860. static PyObject *
  861. EVP_new_impl(PyObject *module, PyObject *name_obj, PyObject *data_obj,
  862. int usedforsecurity)
  863. /*[clinic end generated code: output=ddd5053f92dffe90 input=c24554d0337be1b0]*/
  864. {
  865. char *name;
  866. if (!PyArg_Parse(name_obj, "s", &name)) {
  867. PyErr_SetString(PyExc_TypeError, "name must be a string");
  868. return NULL;
  869. }
  870. return py_evp_fromname(module, name, data_obj, usedforsecurity);
  871. }
  872. /*[clinic input]
  873. _hashlib.openssl_md5
  874. string as data_obj: object(py_default="b''") = NULL
  875. *
  876. usedforsecurity: bool = True
  877. Returns a md5 hash object; optionally initialized with a string
  878. [clinic start generated code]*/
  879. static PyObject *
  880. _hashlib_openssl_md5_impl(PyObject *module, PyObject *data_obj,
  881. int usedforsecurity)
  882. /*[clinic end generated code: output=87b0186440a44f8c input=990e36d5e689b16e]*/
  883. {
  884. return py_evp_fromname(module, Py_hash_md5, data_obj, usedforsecurity);
  885. }
  886. /*[clinic input]
  887. _hashlib.openssl_sha1
  888. string as data_obj: object(py_default="b''") = NULL
  889. *
  890. usedforsecurity: bool = True
  891. Returns a sha1 hash object; optionally initialized with a string
  892. [clinic start generated code]*/
  893. static PyObject *
  894. _hashlib_openssl_sha1_impl(PyObject *module, PyObject *data_obj,
  895. int usedforsecurity)
  896. /*[clinic end generated code: output=6813024cf690670d input=948f2f4b6deabc10]*/
  897. {
  898. return py_evp_fromname(module, Py_hash_sha1, data_obj, usedforsecurity);
  899. }
  900. /*[clinic input]
  901. _hashlib.openssl_sha224
  902. string as data_obj: object(py_default="b''") = NULL
  903. *
  904. usedforsecurity: bool = True
  905. Returns a sha224 hash object; optionally initialized with a string
  906. [clinic start generated code]*/
  907. static PyObject *
  908. _hashlib_openssl_sha224_impl(PyObject *module, PyObject *data_obj,
  909. int usedforsecurity)
  910. /*[clinic end generated code: output=a2dfe7cc4eb14ebb input=f9272821fadca505]*/
  911. {
  912. return py_evp_fromname(module, Py_hash_sha224, data_obj, usedforsecurity);
  913. }
  914. /*[clinic input]
  915. _hashlib.openssl_sha256
  916. string as data_obj: object(py_default="b''") = NULL
  917. *
  918. usedforsecurity: bool = True
  919. Returns a sha256 hash object; optionally initialized with a string
  920. [clinic start generated code]*/
  921. static PyObject *
  922. _hashlib_openssl_sha256_impl(PyObject *module, PyObject *data_obj,
  923. int usedforsecurity)
  924. /*[clinic end generated code: output=1f874a34870f0a68 input=549fad9d2930d4c5]*/
  925. {
  926. return py_evp_fromname(module, Py_hash_sha256, data_obj, usedforsecurity);
  927. }
  928. /*[clinic input]
  929. _hashlib.openssl_sha384
  930. string as data_obj: object(py_default="b''") = NULL
  931. *
  932. usedforsecurity: bool = True
  933. Returns a sha384 hash object; optionally initialized with a string
  934. [clinic start generated code]*/
  935. static PyObject *
  936. _hashlib_openssl_sha384_impl(PyObject *module, PyObject *data_obj,
  937. int usedforsecurity)
  938. /*[clinic end generated code: output=58529eff9ca457b2 input=48601a6e3bf14ad7]*/
  939. {
  940. return py_evp_fromname(module, Py_hash_sha384, data_obj, usedforsecurity);
  941. }
  942. /*[clinic input]
  943. _hashlib.openssl_sha512
  944. string as data_obj: object(py_default="b''") = NULL
  945. *
  946. usedforsecurity: bool = True
  947. Returns a sha512 hash object; optionally initialized with a string
  948. [clinic start generated code]*/
  949. static PyObject *
  950. _hashlib_openssl_sha512_impl(PyObject *module, PyObject *data_obj,
  951. int usedforsecurity)
  952. /*[clinic end generated code: output=2c744c9e4a40d5f6 input=c5c46a2a817aa98f]*/
  953. {
  954. return py_evp_fromname(module, Py_hash_sha512, data_obj, usedforsecurity);
  955. }
  956. #ifdef PY_OPENSSL_HAS_SHA3
  957. /*[clinic input]
  958. _hashlib.openssl_sha3_224
  959. string as data_obj: object(py_default="b''") = NULL
  960. *
  961. usedforsecurity: bool = True
  962. Returns a sha3-224 hash object; optionally initialized with a string
  963. [clinic start generated code]*/
  964. static PyObject *
  965. _hashlib_openssl_sha3_224_impl(PyObject *module, PyObject *data_obj,
  966. int usedforsecurity)
  967. /*[clinic end generated code: output=144641c1d144b974 input=e3a01b2888916157]*/
  968. {
  969. return py_evp_fromname(module, Py_hash_sha3_224, data_obj, usedforsecurity);
  970. }
  971. /*[clinic input]
  972. _hashlib.openssl_sha3_256
  973. string as data_obj: object(py_default="b''") = NULL
  974. *
  975. usedforsecurity: bool = True
  976. Returns a sha3-256 hash object; optionally initialized with a string
  977. [clinic start generated code]*/
  978. static PyObject *
  979. _hashlib_openssl_sha3_256_impl(PyObject *module, PyObject *data_obj,
  980. int usedforsecurity)
  981. /*[clinic end generated code: output=c61f1ab772d06668 input=e2908126c1b6deed]*/
  982. {
  983. return py_evp_fromname(module, Py_hash_sha3_256, data_obj , usedforsecurity);
  984. }
  985. /*[clinic input]
  986. _hashlib.openssl_sha3_384
  987. string as data_obj: object(py_default="b''") = NULL
  988. *
  989. usedforsecurity: bool = True
  990. Returns a sha3-384 hash object; optionally initialized with a string
  991. [clinic start generated code]*/
  992. static PyObject *
  993. _hashlib_openssl_sha3_384_impl(PyObject *module, PyObject *data_obj,
  994. int usedforsecurity)
  995. /*[clinic end generated code: output=f68e4846858cf0ee input=ec0edf5c792f8252]*/
  996. {
  997. return py_evp_fromname(module, Py_hash_sha3_384, data_obj , usedforsecurity);
  998. }
  999. /*[clinic input]
  1000. _hashlib.openssl_sha3_512
  1001. string as data_obj: object(py_default="b''") = NULL
  1002. *
  1003. usedforsecurity: bool = True
  1004. Returns a sha3-512 hash object; optionally initialized with a string
  1005. [clinic start generated code]*/
  1006. static PyObject *
  1007. _hashlib_openssl_sha3_512_impl(PyObject *module, PyObject *data_obj,
  1008. int usedforsecurity)
  1009. /*[clinic end generated code: output=2eede478c159354a input=64e2cc0c094d56f4]*/
  1010. {
  1011. return py_evp_fromname(module, Py_hash_sha3_512, data_obj , usedforsecurity);
  1012. }
  1013. #endif /* PY_OPENSSL_HAS_SHA3 */
  1014. #ifdef PY_OPENSSL_HAS_SHAKE
  1015. /*[clinic input]
  1016. _hashlib.openssl_shake_128
  1017. string as data_obj: object(py_default="b''") = NULL
  1018. *
  1019. usedforsecurity: bool = True
  1020. Returns a shake-128 variable hash object; optionally initialized with a string
  1021. [clinic start generated code]*/
  1022. static PyObject *
  1023. _hashlib_openssl_shake_128_impl(PyObject *module, PyObject *data_obj,
  1024. int usedforsecurity)
  1025. /*[clinic end generated code: output=bc49cdd8ada1fa97 input=6c9d67440eb33ec8]*/
  1026. {
  1027. return py_evp_fromname(module, Py_hash_shake_128, data_obj , usedforsecurity);
  1028. }
  1029. /*[clinic input]
  1030. _hashlib.openssl_shake_256
  1031. string as data_obj: object(py_default="b''") = NULL
  1032. *
  1033. usedforsecurity: bool = True
  1034. Returns a shake-256 variable hash object; optionally initialized with a string
  1035. [clinic start generated code]*/
  1036. static PyObject *
  1037. _hashlib_openssl_shake_256_impl(PyObject *module, PyObject *data_obj,
  1038. int usedforsecurity)
  1039. /*[clinic end generated code: output=358d213be8852df7 input=479cbe9fefd4a9f8]*/
  1040. {
  1041. return py_evp_fromname(module, Py_hash_shake_256, data_obj , usedforsecurity);
  1042. }
  1043. #endif /* PY_OPENSSL_HAS_SHAKE */
  1044. /*[clinic input]
  1045. _hashlib.pbkdf2_hmac as pbkdf2_hmac
  1046. hash_name: str
  1047. password: Py_buffer
  1048. salt: Py_buffer
  1049. iterations: long
  1050. dklen as dklen_obj: object = None
  1051. Password based key derivation function 2 (PKCS #5 v2.0) with HMAC as pseudorandom function.
  1052. [clinic start generated code]*/
  1053. static PyObject *
  1054. pbkdf2_hmac_impl(PyObject *module, const char *hash_name,
  1055. Py_buffer *password, Py_buffer *salt, long iterations,
  1056. PyObject *dklen_obj)
  1057. /*[clinic end generated code: output=144b76005416599b input=ed3ab0d2d28b5d5c]*/
  1058. {
  1059. PyObject *key_obj = NULL;
  1060. char *key;
  1061. long dklen;
  1062. int retval;
  1063. PY_EVP_MD *digest = py_digest_by_name(module, hash_name, Py_ht_pbkdf2);
  1064. if (digest == NULL) {
  1065. goto end;
  1066. }
  1067. if (password->len > INT_MAX) {
  1068. PyErr_SetString(PyExc_OverflowError,
  1069. "password is too long.");
  1070. goto end;
  1071. }
  1072. if (salt->len > INT_MAX) {
  1073. PyErr_SetString(PyExc_OverflowError,
  1074. "salt is too long.");
  1075. goto end;
  1076. }
  1077. if (iterations < 1) {
  1078. PyErr_SetString(PyExc_ValueError,
  1079. "iteration value must be greater than 0.");
  1080. goto end;
  1081. }
  1082. if (iterations > INT_MAX) {
  1083. PyErr_SetString(PyExc_OverflowError,
  1084. "iteration value is too great.");
  1085. goto end;
  1086. }
  1087. if (dklen_obj == Py_None) {
  1088. dklen = EVP_MD_size(digest);
  1089. } else {
  1090. dklen = PyLong_AsLong(dklen_obj);
  1091. if ((dklen == -1) && PyErr_Occurred()) {
  1092. goto end;
  1093. }
  1094. }
  1095. if (dklen < 1) {
  1096. PyErr_SetString(PyExc_ValueError,
  1097. "key length must be greater than 0.");
  1098. goto end;
  1099. }
  1100. if (dklen > INT_MAX) {
  1101. /* INT_MAX is always smaller than dkLen max (2^32 - 1) * hLen */
  1102. PyErr_SetString(PyExc_OverflowError,
  1103. "key length is too great.");
  1104. goto end;
  1105. }
  1106. key_obj = PyBytes_FromStringAndSize(NULL, dklen);
  1107. if (key_obj == NULL) {
  1108. goto end;
  1109. }
  1110. key = PyBytes_AS_STRING(key_obj);
  1111. Py_BEGIN_ALLOW_THREADS
  1112. retval = PKCS5_PBKDF2_HMAC((char*)password->buf, (int)password->len,
  1113. (unsigned char *)salt->buf, (int)salt->len,
  1114. iterations, digest, dklen,
  1115. (unsigned char *)key);
  1116. Py_END_ALLOW_THREADS
  1117. if (!retval) {
  1118. Py_CLEAR(key_obj);
  1119. _setException(PyExc_ValueError, NULL);
  1120. goto end;
  1121. }
  1122. end:
  1123. if (digest != NULL) {
  1124. PY_EVP_MD_free(digest);
  1125. }
  1126. return key_obj;
  1127. }
  1128. #ifdef PY_OPENSSL_HAS_SCRYPT
  1129. /* XXX: Parameters salt, n, r and p should be required keyword-only parameters.
  1130. They are optional in the Argument Clinic declaration only due to a
  1131. limitation of PyArg_ParseTupleAndKeywords. */
  1132. /*[clinic input]
  1133. _hashlib.scrypt
  1134. password: Py_buffer
  1135. *
  1136. salt: Py_buffer = None
  1137. n as n_obj: object(subclass_of='&PyLong_Type') = None
  1138. r as r_obj: object(subclass_of='&PyLong_Type') = None
  1139. p as p_obj: object(subclass_of='&PyLong_Type') = None
  1140. maxmem: long = 0
  1141. dklen: long = 64
  1142. scrypt password-based key derivation function.
  1143. [clinic start generated code]*/
  1144. static PyObject *
  1145. _hashlib_scrypt_impl(PyObject *module, Py_buffer *password, Py_buffer *salt,
  1146. PyObject *n_obj, PyObject *r_obj, PyObject *p_obj,
  1147. long maxmem, long dklen)
  1148. /*[clinic end generated code: output=14849e2aa2b7b46c input=48a7d63bf3f75c42]*/
  1149. {
  1150. PyObject *key_obj = NULL;
  1151. char *key;
  1152. int retval;
  1153. unsigned long n, r, p;
  1154. if (password->len > INT_MAX) {
  1155. PyErr_SetString(PyExc_OverflowError,
  1156. "password is too long.");
  1157. return NULL;
  1158. }
  1159. if (salt->buf == NULL) {
  1160. PyErr_SetString(PyExc_TypeError,
  1161. "salt is required");
  1162. return NULL;
  1163. }
  1164. if (salt->len > INT_MAX) {
  1165. PyErr_SetString(PyExc_OverflowError,
  1166. "salt is too long.");
  1167. return NULL;
  1168. }
  1169. n = PyLong_AsUnsignedLong(n_obj);
  1170. if (n == (unsigned long) -1 && PyErr_Occurred()) {
  1171. PyErr_SetString(PyExc_TypeError,
  1172. "n is required and must be an unsigned int");
  1173. return NULL;
  1174. }
  1175. if (n < 2 || n & (n - 1)) {
  1176. PyErr_SetString(PyExc_ValueError,
  1177. "n must be a power of 2.");
  1178. return NULL;
  1179. }
  1180. r = PyLong_AsUnsignedLong(r_obj);
  1181. if (r == (unsigned long) -1 && PyErr_Occurred()) {
  1182. PyErr_SetString(PyExc_TypeError,
  1183. "r is required and must be an unsigned int");
  1184. return NULL;
  1185. }
  1186. p = PyLong_AsUnsignedLong(p_obj);
  1187. if (p == (unsigned long) -1 && PyErr_Occurred()) {
  1188. PyErr_SetString(PyExc_TypeError,
  1189. "p is required and must be an unsigned int");
  1190. return NULL;
  1191. }
  1192. if (maxmem < 0 || maxmem > INT_MAX) {
  1193. /* OpenSSL 1.1.0 restricts maxmem to 32 MiB. It may change in the
  1194. future. The maxmem constant is private to OpenSSL. */
  1195. PyErr_Format(PyExc_ValueError,
  1196. "maxmem must be positive and smaller than %d",
  1197. INT_MAX);
  1198. return NULL;
  1199. }
  1200. if (dklen < 1 || dklen > INT_MAX) {
  1201. PyErr_Format(PyExc_ValueError,
  1202. "dklen must be greater than 0 and smaller than %d",
  1203. INT_MAX);
  1204. return NULL;
  1205. }
  1206. /* let OpenSSL validate the rest */
  1207. retval = EVP_PBE_scrypt(NULL, 0, NULL, 0, n, r, p, maxmem, NULL, 0);
  1208. if (!retval) {
  1209. _setException(PyExc_ValueError, "Invalid parameter combination for n, r, p, maxmem.");
  1210. return NULL;
  1211. }
  1212. key_obj = PyBytes_FromStringAndSize(NULL, dklen);
  1213. if (key_obj == NULL) {
  1214. return NULL;
  1215. }
  1216. key = PyBytes_AS_STRING(key_obj);
  1217. Py_BEGIN_ALLOW_THREADS
  1218. retval = EVP_PBE_scrypt(
  1219. (const char*)password->buf, (size_t)password->len,
  1220. (const unsigned char *)salt->buf, (size_t)salt->len,
  1221. n, r, p, maxmem,
  1222. (unsigned char *)key, (size_t)dklen
  1223. );
  1224. Py_END_ALLOW_THREADS
  1225. if (!retval) {
  1226. Py_CLEAR(key_obj);
  1227. _setException(PyExc_ValueError, NULL);
  1228. return NULL;
  1229. }
  1230. return key_obj;
  1231. }
  1232. #endif /* PY_OPENSSL_HAS_SCRYPT */
  1233. /* Fast HMAC for hmac.digest()
  1234. */
  1235. /*[clinic input]
  1236. _hashlib.hmac_digest as _hashlib_hmac_singleshot
  1237. key: Py_buffer
  1238. msg: Py_buffer
  1239. digest: object
  1240. Single-shot HMAC.
  1241. [clinic start generated code]*/
  1242. static PyObject *
  1243. _hashlib_hmac_singleshot_impl(PyObject *module, Py_buffer *key,
  1244. Py_buffer *msg, PyObject *digest)
  1245. /*[clinic end generated code: output=82f19965d12706ac input=0a0790cc3db45c2e]*/
  1246. {
  1247. unsigned char md[EVP_MAX_MD_SIZE] = {0};
  1248. unsigned int md_len = 0;
  1249. unsigned char *result;
  1250. PY_EVP_MD *evp;
  1251. if (key->len > INT_MAX) {
  1252. PyErr_SetString(PyExc_OverflowError,
  1253. "key is too long.");
  1254. return NULL;
  1255. }
  1256. if (msg->len > INT_MAX) {
  1257. PyErr_SetString(PyExc_OverflowError,
  1258. "msg is too long.");
  1259. return NULL;
  1260. }
  1261. evp = py_digest_by_digestmod(module, digest, Py_ht_mac);
  1262. if (evp == NULL) {
  1263. return NULL;
  1264. }
  1265. Py_BEGIN_ALLOW_THREADS
  1266. result = HMAC(
  1267. evp,
  1268. (const void*)key->buf, (int)key->len,
  1269. (const unsigned char*)msg->buf, (int)msg->len,
  1270. md, &md_len
  1271. );
  1272. Py_END_ALLOW_THREADS
  1273. PY_EVP_MD_free(evp);
  1274. if (result == NULL) {
  1275. _setException(PyExc_ValueError, NULL);
  1276. return NULL;
  1277. }
  1278. return PyBytes_FromStringAndSize((const char*)md, md_len);
  1279. }
  1280. /* OpenSSL-based HMAC implementation
  1281. */
  1282. static int _hmac_update(HMACobject*, PyObject*);
  1283. /*[clinic input]
  1284. _hashlib.hmac_new
  1285. key: Py_buffer
  1286. msg as msg_obj: object(c_default="NULL") = b''
  1287. digestmod: object(c_default="NULL") = None
  1288. Return a new hmac object.
  1289. [clinic start generated code]*/
  1290. static PyObject *
  1291. _hashlib_hmac_new_impl(PyObject *module, Py_buffer *key, PyObject *msg_obj,
  1292. PyObject *digestmod)
  1293. /*[clinic end generated code: output=c20d9e4d9ed6d219 input=5f4071dcc7f34362]*/
  1294. {
  1295. PyTypeObject *type = get_hashlib_state(module)->HMACtype;
  1296. PY_EVP_MD *digest;
  1297. HMAC_CTX *ctx = NULL;
  1298. HMACobject *self = NULL;
  1299. int r;
  1300. if (key->len > INT_MAX) {
  1301. PyErr_SetString(PyExc_OverflowError,
  1302. "key is too long.");
  1303. return NULL;
  1304. }
  1305. if (digestmod == NULL) {
  1306. PyErr_SetString(
  1307. PyExc_TypeError, "Missing required parameter 'digestmod'.");
  1308. return NULL;
  1309. }
  1310. digest = py_digest_by_digestmod(module, digestmod, Py_ht_mac);
  1311. if (digest == NULL) {
  1312. return NULL;
  1313. }
  1314. ctx = HMAC_CTX_new();
  1315. if (ctx == NULL) {
  1316. _setException(PyExc_ValueError, NULL);
  1317. goto error;
  1318. }
  1319. r = HMAC_Init_ex(
  1320. ctx,
  1321. (const char*)key->buf,
  1322. (int)key->len,
  1323. digest,
  1324. NULL /*impl*/);
  1325. PY_EVP_MD_free(digest);
  1326. if (r == 0) {
  1327. _setException(PyExc_ValueError, NULL);
  1328. goto error;
  1329. }
  1330. self = (HMACobject *)PyObject_New(HMACobject, type);
  1331. if (self == NULL) {
  1332. goto error;
  1333. }
  1334. self->ctx = ctx;
  1335. self->lock = NULL;
  1336. if ((msg_obj != NULL) && (msg_obj != Py_None)) {
  1337. if (!_hmac_update(self, msg_obj))
  1338. goto error;
  1339. }
  1340. return (PyObject*)self;
  1341. error:
  1342. if (ctx) HMAC_CTX_free(ctx);
  1343. if (self) PyObject_Free(self);
  1344. return NULL;
  1345. }
  1346. /* helper functions */
  1347. static int
  1348. locked_HMAC_CTX_copy(HMAC_CTX *new_ctx_p, HMACobject *self)
  1349. {
  1350. int result;
  1351. ENTER_HASHLIB(self);
  1352. result = HMAC_CTX_copy(new_ctx_p, self->ctx);
  1353. LEAVE_HASHLIB(self);
  1354. return result;
  1355. }
  1356. static unsigned int
  1357. _hmac_digest_size(HMACobject *self)
  1358. {
  1359. unsigned int digest_size = EVP_MD_size(HMAC_CTX_get_md(self->ctx));
  1360. assert(digest_size <= EVP_MAX_MD_SIZE);
  1361. return digest_size;
  1362. }
  1363. static int
  1364. _hmac_update(HMACobject *self, PyObject *obj)
  1365. {
  1366. int r;
  1367. Py_buffer view = {0};
  1368. GET_BUFFER_VIEW_OR_ERROR(obj, &view, return 0);
  1369. if (self->lock == NULL && view.len >= HASHLIB_GIL_MINSIZE) {
  1370. self->lock = PyThread_allocate_lock();
  1371. /* fail? lock = NULL and we fail over to non-threaded code. */
  1372. }
  1373. if (self->lock != NULL) {
  1374. Py_BEGIN_ALLOW_THREADS
  1375. PyThread_acquire_lock(self->lock, 1);
  1376. r = HMAC_Update(self->ctx, (const unsigned char*)view.buf, view.len);
  1377. PyThread_release_lock(self->lock);
  1378. Py_END_ALLOW_THREADS
  1379. } else {
  1380. r = HMAC_Update(self->ctx, (const unsigned char*)view.buf, view.len);
  1381. }
  1382. PyBuffer_Release(&view);
  1383. if (r == 0) {
  1384. _setException(PyExc_ValueError, NULL);
  1385. return 0;
  1386. }
  1387. return 1;
  1388. }
  1389. /*[clinic input]
  1390. _hashlib.HMAC.copy
  1391. Return a copy ("clone") of the HMAC object.
  1392. [clinic start generated code]*/
  1393. static PyObject *
  1394. _hashlib_HMAC_copy_impl(HMACobject *self)
  1395. /*[clinic end generated code: output=29aa28b452833127 input=e2fa6a05db61a4d6]*/
  1396. {
  1397. HMACobject *retval;
  1398. HMAC_CTX *ctx = HMAC_CTX_new();
  1399. if (ctx == NULL) {
  1400. return _setException(PyExc_ValueError, NULL);
  1401. }
  1402. if (!locked_HMAC_CTX_copy(ctx, self)) {
  1403. HMAC_CTX_free(ctx);
  1404. return _setException(PyExc_ValueError, NULL);
  1405. }
  1406. retval = (HMACobject *)PyObject_New(HMACobject, Py_TYPE(self));
  1407. if (retval == NULL) {
  1408. HMAC_CTX_free(ctx);
  1409. return NULL;
  1410. }
  1411. retval->ctx = ctx;
  1412. retval->lock = NULL;
  1413. return (PyObject *)retval;
  1414. }
  1415. static void
  1416. _hmac_dealloc(HMACobject *self)
  1417. {
  1418. PyTypeObject *tp = Py_TYPE(self);
  1419. if (self->lock != NULL) {
  1420. PyThread_free_lock(self->lock);
  1421. }
  1422. HMAC_CTX_free(self->ctx);
  1423. PyObject_Free(self);
  1424. Py_DECREF(tp);
  1425. }
  1426. static PyObject *
  1427. _hmac_repr(HMACobject *self)
  1428. {
  1429. PyObject *digest_name = py_digest_name(HMAC_CTX_get_md(self->ctx));
  1430. if (digest_name == NULL) {
  1431. return NULL;
  1432. }
  1433. PyObject *repr = PyUnicode_FromFormat(
  1434. "<%U HMAC object @ %p>", digest_name, self
  1435. );
  1436. Py_DECREF(digest_name);
  1437. return repr;
  1438. }
  1439. /*[clinic input]
  1440. _hashlib.HMAC.update
  1441. msg: object
  1442. Update the HMAC object with msg.
  1443. [clinic start generated code]*/
  1444. static PyObject *
  1445. _hashlib_HMAC_update_impl(HMACobject *self, PyObject *msg)
  1446. /*[clinic end generated code: output=f31f0ace8c625b00 input=1829173bb3cfd4e6]*/
  1447. {
  1448. if (!_hmac_update(self, msg)) {
  1449. return NULL;
  1450. }
  1451. Py_RETURN_NONE;
  1452. }
  1453. static int
  1454. _hmac_digest(HMACobject *self, unsigned char *buf, unsigned int len)
  1455. {
  1456. HMAC_CTX *temp_ctx = HMAC_CTX_new();
  1457. if (temp_ctx == NULL) {
  1458. PyErr_NoMemory();
  1459. return 0;
  1460. }
  1461. if (!locked_HMAC_CTX_copy(temp_ctx, self)) {
  1462. _setException(PyExc_ValueError, NULL);
  1463. return 0;
  1464. }
  1465. int r = HMAC_Final(temp_ctx, buf, &len);
  1466. HMAC_CTX_free(temp_ctx);
  1467. if (r == 0) {
  1468. _setException(PyExc_ValueError, NULL);
  1469. return 0;
  1470. }
  1471. return 1;
  1472. }
  1473. /*[clinic input]
  1474. _hashlib.HMAC.digest
  1475. Return the digest of the bytes passed to the update() method so far.
  1476. [clinic start generated code]*/
  1477. static PyObject *
  1478. _hashlib_HMAC_digest_impl(HMACobject *self)
  1479. /*[clinic end generated code: output=1b1424355af7a41e input=bff07f74da318fb4]*/
  1480. {
  1481. unsigned char digest[EVP_MAX_MD_SIZE];
  1482. unsigned int digest_size = _hmac_digest_size(self);
  1483. if (digest_size == 0) {
  1484. return _setException(PyExc_ValueError, NULL);
  1485. }
  1486. int r = _hmac_digest(self, digest, digest_size);
  1487. if (r == 0) {
  1488. return NULL;
  1489. }
  1490. return PyBytes_FromStringAndSize((const char *)digest, digest_size);
  1491. }
  1492. /*[clinic input]
  1493. _hashlib.HMAC.hexdigest
  1494. Return hexadecimal digest of the bytes passed to the update() method so far.
  1495. This may be used to exchange the value safely in email or other non-binary
  1496. environments.
  1497. [clinic start generated code]*/
  1498. static PyObject *
  1499. _hashlib_HMAC_hexdigest_impl(HMACobject *self)
  1500. /*[clinic end generated code: output=80d825be1eaae6a7 input=5abc42702874ddcf]*/
  1501. {
  1502. unsigned char digest[EVP_MAX_MD_SIZE];
  1503. unsigned int digest_size = _hmac_digest_size(self);
  1504. if (digest_size == 0) {
  1505. return _setException(PyExc_ValueError, NULL);
  1506. }
  1507. int r = _hmac_digest(self, digest, digest_size);
  1508. if (r == 0) {
  1509. return NULL;
  1510. }
  1511. return _Py_strhex((const char *)digest, digest_size);
  1512. }
  1513. static PyObject *
  1514. _hashlib_hmac_get_digest_size(HMACobject *self, void *closure)
  1515. {
  1516. unsigned int digest_size = _hmac_digest_size(self);
  1517. if (digest_size == 0) {
  1518. return _setException(PyExc_ValueError, NULL);
  1519. }
  1520. return PyLong_FromLong(digest_size);
  1521. }
  1522. static PyObject *
  1523. _hashlib_hmac_get_block_size(HMACobject *self, void *closure)
  1524. {
  1525. const EVP_MD *md = HMAC_CTX_get_md(self->ctx);
  1526. if (md == NULL) {
  1527. return _setException(PyExc_ValueError, NULL);
  1528. }
  1529. return PyLong_FromLong(EVP_MD_block_size(md));
  1530. }
  1531. static PyObject *
  1532. _hashlib_hmac_get_name(HMACobject *self, void *closure)
  1533. {
  1534. PyObject *digest_name = py_digest_name(HMAC_CTX_get_md(self->ctx));
  1535. if (digest_name == NULL) {
  1536. return NULL;
  1537. }
  1538. PyObject *name = PyUnicode_FromFormat("hmac-%U", digest_name);
  1539. Py_DECREF(digest_name);
  1540. return name;
  1541. }
  1542. static PyMethodDef HMAC_methods[] = {
  1543. _HASHLIB_HMAC_UPDATE_METHODDEF
  1544. _HASHLIB_HMAC_DIGEST_METHODDEF
  1545. _HASHLIB_HMAC_HEXDIGEST_METHODDEF
  1546. _HASHLIB_HMAC_COPY_METHODDEF
  1547. {NULL, NULL} /* sentinel */
  1548. };
  1549. static PyGetSetDef HMAC_getset[] = {
  1550. {"digest_size", (getter)_hashlib_hmac_get_digest_size, NULL, NULL, NULL},
  1551. {"block_size", (getter)_hashlib_hmac_get_block_size, NULL, NULL, NULL},
  1552. {"name", (getter)_hashlib_hmac_get_name, NULL, NULL, NULL},
  1553. {NULL} /* Sentinel */
  1554. };
  1555. PyDoc_STRVAR(hmactype_doc,
  1556. "The object used to calculate HMAC of a message.\n\
  1557. \n\
  1558. Methods:\n\
  1559. \n\
  1560. update() -- updates the current digest with an additional string\n\
  1561. digest() -- return the current digest value\n\
  1562. hexdigest() -- return the current digest as a string of hexadecimal digits\n\
  1563. copy() -- return a copy of the current hash object\n\
  1564. \n\
  1565. Attributes:\n\
  1566. \n\
  1567. name -- the name, including the hash algorithm used by this object\n\
  1568. digest_size -- number of bytes in digest() output\n");
  1569. static PyType_Slot HMACtype_slots[] = {
  1570. {Py_tp_doc, (char *)hmactype_doc},
  1571. {Py_tp_repr, (reprfunc)_hmac_repr},
  1572. {Py_tp_dealloc,(destructor)_hmac_dealloc},
  1573. {Py_tp_methods, HMAC_methods},
  1574. {Py_tp_getset, HMAC_getset},
  1575. {0, NULL}
  1576. };
  1577. PyType_Spec HMACtype_spec = {
  1578. "_hashlib.HMAC", /* name */
  1579. sizeof(HMACobject), /* basicsize */
  1580. .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION | Py_TPFLAGS_IMMUTABLETYPE,
  1581. .slots = HMACtype_slots,
  1582. };
  1583. /* State for our callback function so that it can accumulate a result. */
  1584. typedef struct _internal_name_mapper_state {
  1585. PyObject *set;
  1586. int error;
  1587. } _InternalNameMapperState;
  1588. /* A callback function to pass to OpenSSL's OBJ_NAME_do_all(...) */
  1589. static void
  1590. #if OPENSSL_VERSION_NUMBER >= 0x30000000L
  1591. _openssl_hash_name_mapper(EVP_MD *md, void *arg)
  1592. #else
  1593. _openssl_hash_name_mapper(const EVP_MD *md, const char *from,
  1594. const char *to, void *arg)
  1595. #endif
  1596. {
  1597. _InternalNameMapperState *state = (_InternalNameMapperState *)arg;
  1598. PyObject *py_name;
  1599. assert(state != NULL);
  1600. // ignore all undefined providers
  1601. if ((md == NULL) || (EVP_MD_nid(md) == NID_undef)) {
  1602. return;
  1603. }
  1604. py_name = py_digest_name(md);
  1605. if (py_name == NULL) {
  1606. state->error = 1;
  1607. } else {
  1608. if (PySet_Add(state->set, py_name) != 0) {
  1609. state->error = 1;
  1610. }
  1611. Py_DECREF(py_name);
  1612. }
  1613. }
  1614. /* Ask OpenSSL for a list of supported ciphers, filling in a Python set. */
  1615. static int
  1616. hashlib_md_meth_names(PyObject *module)
  1617. {
  1618. _InternalNameMapperState state = {
  1619. .set = PyFrozenSet_New(NULL),
  1620. .error = 0
  1621. };
  1622. if (state.set == NULL) {
  1623. return -1;
  1624. }
  1625. #if OPENSSL_VERSION_NUMBER >= 0x30000000L
  1626. // get algorithms from all activated providers in default context
  1627. EVP_MD_do_all_provided(NULL, &_openssl_hash_name_mapper, &state);
  1628. #else
  1629. EVP_MD_do_all(&_openssl_hash_name_mapper, &state);
  1630. #endif
  1631. if (state.error) {
  1632. Py_DECREF(state.set);
  1633. return -1;
  1634. }
  1635. if (PyModule_AddObject(module, "openssl_md_meth_names", state.set) < 0) {
  1636. Py_DECREF(state.set);
  1637. return -1;
  1638. }
  1639. return 0;
  1640. }
  1641. /*[clinic input]
  1642. _hashlib.get_fips_mode -> int
  1643. Determine the OpenSSL FIPS mode of operation.
  1644. For OpenSSL 3.0.0 and newer it returns the state of the default provider
  1645. in the default OSSL context. It's not quite the same as FIPS_mode() but good
  1646. enough for unittests.
  1647. Effectively any non-zero return value indicates FIPS mode;
  1648. values other than 1 may have additional significance.
  1649. [clinic start generated code]*/
  1650. static int
  1651. _hashlib_get_fips_mode_impl(PyObject *module)
  1652. /*[clinic end generated code: output=87eece1bab4d3fa9 input=2db61538c41c6fef]*/
  1653. {
  1654. #if OPENSSL_VERSION_NUMBER >= 0x30000000L
  1655. return EVP_default_properties_is_fips_enabled(NULL);
  1656. #else
  1657. ERR_clear_error();
  1658. int result = FIPS_mode();
  1659. if (result == 0) {
  1660. // "If the library was built without support of the FIPS Object Module,
  1661. // then the function will return 0 with an error code of
  1662. // CRYPTO_R_FIPS_MODE_NOT_SUPPORTED (0x0f06d065)."
  1663. // But 0 is also a valid result value.
  1664. unsigned long errcode = ERR_peek_last_error();
  1665. if (errcode) {
  1666. _setException(PyExc_ValueError, NULL);
  1667. return -1;
  1668. }
  1669. }
  1670. return result;
  1671. #endif
  1672. }
  1673. static int
  1674. _tscmp(const unsigned char *a, const unsigned char *b,
  1675. Py_ssize_t len_a, Py_ssize_t len_b)
  1676. {
  1677. /* loop count depends on length of b. Might leak very little timing
  1678. * information if sizes are different.
  1679. */
  1680. Py_ssize_t length = len_b;
  1681. const void *left = a;
  1682. const void *right = b;
  1683. int result = 0;
  1684. if (len_a != length) {
  1685. left = b;
  1686. result = 1;
  1687. }
  1688. result |= CRYPTO_memcmp(left, right, length);
  1689. return (result == 0);
  1690. }
  1691. /* NOTE: Keep in sync with _operator.c implementation. */
  1692. /*[clinic input]
  1693. _hashlib.compare_digest
  1694. a: object
  1695. b: object
  1696. /
  1697. Return 'a == b'.
  1698. This function uses an approach designed to prevent
  1699. timing analysis, making it appropriate for cryptography.
  1700. a and b must both be of the same type: either str (ASCII only),
  1701. or any bytes-like object.
  1702. Note: If a and b are of different lengths, or if an error occurs,
  1703. a timing attack could theoretically reveal information about the
  1704. types and lengths of a and b--but not their values.
  1705. [clinic start generated code]*/
  1706. static PyObject *
  1707. _hashlib_compare_digest_impl(PyObject *module, PyObject *a, PyObject *b)
  1708. /*[clinic end generated code: output=6f1c13927480aed9 input=9c40c6e566ca12f5]*/
  1709. {
  1710. int rc;
  1711. /* ASCII unicode string */
  1712. if(PyUnicode_Check(a) && PyUnicode_Check(b)) {
  1713. if (PyUnicode_READY(a) == -1 || PyUnicode_READY(b) == -1) {
  1714. return NULL;
  1715. }
  1716. if (!PyUnicode_IS_ASCII(a) || !PyUnicode_IS_ASCII(b)) {
  1717. PyErr_SetString(PyExc_TypeError,
  1718. "comparing strings with non-ASCII characters is "
  1719. "not supported");
  1720. return NULL;
  1721. }
  1722. rc = _tscmp(PyUnicode_DATA(a),
  1723. PyUnicode_DATA(b),
  1724. PyUnicode_GET_LENGTH(a),
  1725. PyUnicode_GET_LENGTH(b));
  1726. }
  1727. /* fallback to buffer interface for bytes, bytearray and other */
  1728. else {
  1729. Py_buffer view_a;
  1730. Py_buffer view_b;
  1731. if (PyObject_CheckBuffer(a) == 0 && PyObject_CheckBuffer(b) == 0) {
  1732. PyErr_Format(PyExc_TypeError,
  1733. "unsupported operand types(s) or combination of types: "
  1734. "'%.100s' and '%.100s'",
  1735. Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
  1736. return NULL;
  1737. }
  1738. if (PyObject_GetBuffer(a, &view_a, PyBUF_SIMPLE) == -1) {
  1739. return NULL;
  1740. }
  1741. if (view_a.ndim > 1) {
  1742. PyErr_SetString(PyExc_BufferError,
  1743. "Buffer must be single dimension");
  1744. PyBuffer_Release(&view_a);
  1745. return NULL;
  1746. }
  1747. if (PyObject_GetBuffer(b, &view_b, PyBUF_SIMPLE) == -1) {
  1748. PyBuffer_Release(&view_a);
  1749. return NULL;
  1750. }
  1751. if (view_b.ndim > 1) {
  1752. PyErr_SetString(PyExc_BufferError,
  1753. "Buffer must be single dimension");
  1754. PyBuffer_Release(&view_a);
  1755. PyBuffer_Release(&view_b);
  1756. return NULL;
  1757. }
  1758. rc = _tscmp((const unsigned char*)view_a.buf,
  1759. (const unsigned char*)view_b.buf,
  1760. view_a.len,
  1761. view_b.len);
  1762. PyBuffer_Release(&view_a);
  1763. PyBuffer_Release(&view_b);
  1764. }
  1765. return PyBool_FromLong(rc);
  1766. }
  1767. /* List of functions exported by this module */
  1768. static struct PyMethodDef EVP_functions[] = {
  1769. EVP_NEW_METHODDEF
  1770. PBKDF2_HMAC_METHODDEF
  1771. _HASHLIB_SCRYPT_METHODDEF
  1772. _HASHLIB_GET_FIPS_MODE_METHODDEF
  1773. _HASHLIB_COMPARE_DIGEST_METHODDEF
  1774. _HASHLIB_HMAC_SINGLESHOT_METHODDEF
  1775. _HASHLIB_HMAC_NEW_METHODDEF
  1776. _HASHLIB_OPENSSL_MD5_METHODDEF
  1777. _HASHLIB_OPENSSL_SHA1_METHODDEF
  1778. _HASHLIB_OPENSSL_SHA224_METHODDEF
  1779. _HASHLIB_OPENSSL_SHA256_METHODDEF
  1780. _HASHLIB_OPENSSL_SHA384_METHODDEF
  1781. _HASHLIB_OPENSSL_SHA512_METHODDEF
  1782. _HASHLIB_OPENSSL_SHA3_224_METHODDEF
  1783. _HASHLIB_OPENSSL_SHA3_256_METHODDEF
  1784. _HASHLIB_OPENSSL_SHA3_384_METHODDEF
  1785. _HASHLIB_OPENSSL_SHA3_512_METHODDEF
  1786. _HASHLIB_OPENSSL_SHAKE_128_METHODDEF
  1787. _HASHLIB_OPENSSL_SHAKE_256_METHODDEF
  1788. {NULL, NULL} /* Sentinel */
  1789. };
  1790. /* Initialize this module. */
  1791. static int
  1792. hashlib_traverse(PyObject *m, visitproc visit, void *arg)
  1793. {
  1794. _hashlibstate *state = get_hashlib_state(m);
  1795. Py_VISIT(state->EVPtype);
  1796. Py_VISIT(state->HMACtype);
  1797. #ifdef PY_OPENSSL_HAS_SHAKE
  1798. Py_VISIT(state->EVPXOFtype);
  1799. #endif
  1800. Py_VISIT(state->constructs);
  1801. Py_VISIT(state->unsupported_digestmod_error);
  1802. return 0;
  1803. }
  1804. static int
  1805. hashlib_clear(PyObject *m)
  1806. {
  1807. _hashlibstate *state = get_hashlib_state(m);
  1808. Py_CLEAR(state->EVPtype);
  1809. Py_CLEAR(state->HMACtype);
  1810. #ifdef PY_OPENSSL_HAS_SHAKE
  1811. Py_CLEAR(state->EVPXOFtype);
  1812. #endif
  1813. Py_CLEAR(state->constructs);
  1814. Py_CLEAR(state->unsupported_digestmod_error);
  1815. if (state->hashtable != NULL) {
  1816. _Py_hashtable_destroy(state->hashtable);
  1817. state->hashtable = NULL;
  1818. }
  1819. return 0;
  1820. }
  1821. static void
  1822. hashlib_free(void *m)
  1823. {
  1824. hashlib_clear((PyObject *)m);
  1825. }
  1826. /* Py_mod_exec functions */
  1827. static int
  1828. hashlib_init_hashtable(PyObject *module)
  1829. {
  1830. _hashlibstate *state = get_hashlib_state(module);
  1831. state->hashtable = py_hashentry_table_new();
  1832. if (state->hashtable == NULL) {
  1833. PyErr_NoMemory();
  1834. return -1;
  1835. }
  1836. return 0;
  1837. }
  1838. static int
  1839. hashlib_init_evptype(PyObject *module)
  1840. {
  1841. _hashlibstate *state = get_hashlib_state(module);
  1842. state->EVPtype = (PyTypeObject *)PyType_FromSpec(&EVPtype_spec);
  1843. if (state->EVPtype == NULL) {
  1844. return -1;
  1845. }
  1846. if (PyModule_AddType(module, state->EVPtype) < 0) {
  1847. return -1;
  1848. }
  1849. return 0;
  1850. }
  1851. static int
  1852. hashlib_init_evpxoftype(PyObject *module)
  1853. {
  1854. #ifdef PY_OPENSSL_HAS_SHAKE
  1855. _hashlibstate *state = get_hashlib_state(module);
  1856. if (state->EVPtype == NULL) {
  1857. return -1;
  1858. }
  1859. state->EVPXOFtype = (PyTypeObject *)PyType_FromSpecWithBases(
  1860. &EVPXOFtype_spec, (PyObject *)state->EVPtype
  1861. );
  1862. if (state->EVPXOFtype == NULL) {
  1863. return -1;
  1864. }
  1865. if (PyModule_AddType(module, state->EVPXOFtype) < 0) {
  1866. return -1;
  1867. }
  1868. #endif
  1869. return 0;
  1870. }
  1871. static int
  1872. hashlib_init_hmactype(PyObject *module)
  1873. {
  1874. _hashlibstate *state = get_hashlib_state(module);
  1875. state->HMACtype = (PyTypeObject *)PyType_FromSpec(&HMACtype_spec);
  1876. if (state->HMACtype == NULL) {
  1877. return -1;
  1878. }
  1879. if (PyModule_AddType(module, state->HMACtype) < 0) {
  1880. return -1;
  1881. }
  1882. return 0;
  1883. }
  1884. static int
  1885. hashlib_init_constructors(PyObject *module)
  1886. {
  1887. /* Create dict from builtin openssl_hash functions to name
  1888. * {_hashlib.openssl_sha256: "sha256", ...}
  1889. */
  1890. PyModuleDef *mdef;
  1891. PyMethodDef *fdef;
  1892. PyObject *proxy;
  1893. PyObject *func, *name_obj;
  1894. _hashlibstate *state = get_hashlib_state(module);
  1895. mdef = PyModule_GetDef(module);
  1896. if (mdef == NULL) {
  1897. return -1;
  1898. }
  1899. state->constructs = PyDict_New();
  1900. if (state->constructs == NULL) {
  1901. return -1;
  1902. }
  1903. for (fdef = mdef->m_methods; fdef->ml_name != NULL; fdef++) {
  1904. if (strncmp(fdef->ml_name, "openssl_", 8)) {
  1905. continue;
  1906. }
  1907. name_obj = PyUnicode_FromString(fdef->ml_name + 8);
  1908. if (name_obj == NULL) {
  1909. return -1;
  1910. }
  1911. func = PyObject_GetAttrString(module, fdef->ml_name);
  1912. if (func == NULL) {
  1913. Py_DECREF(name_obj);
  1914. return -1;
  1915. }
  1916. int rc = PyDict_SetItem(state->constructs, func, name_obj);
  1917. Py_DECREF(func);
  1918. Py_DECREF(name_obj);
  1919. if (rc < 0) {
  1920. return -1;
  1921. }
  1922. }
  1923. proxy = PyDictProxy_New(state->constructs);
  1924. if (proxy == NULL) {
  1925. return -1;
  1926. }
  1927. int rc = PyModule_AddObjectRef(module, "_constructors", proxy);
  1928. Py_DECREF(proxy);
  1929. if (rc < 0) {
  1930. return -1;
  1931. }
  1932. return 0;
  1933. }
  1934. static int
  1935. hashlib_exception(PyObject *module)
  1936. {
  1937. _hashlibstate *state = get_hashlib_state(module);
  1938. state->unsupported_digestmod_error = PyErr_NewException(
  1939. "_hashlib.UnsupportedDigestmodError", PyExc_ValueError, NULL);
  1940. if (state->unsupported_digestmod_error == NULL) {
  1941. return -1;
  1942. }
  1943. if (PyModule_AddObjectRef(module, "UnsupportedDigestmodError",
  1944. state->unsupported_digestmod_error) < 0) {
  1945. return -1;
  1946. }
  1947. return 0;
  1948. }
  1949. static PyModuleDef_Slot hashlib_slots[] = {
  1950. {Py_mod_exec, hashlib_init_hashtable},
  1951. {Py_mod_exec, hashlib_init_evptype},
  1952. {Py_mod_exec, hashlib_init_evpxoftype},
  1953. {Py_mod_exec, hashlib_init_hmactype},
  1954. {Py_mod_exec, hashlib_md_meth_names},
  1955. {Py_mod_exec, hashlib_init_constructors},
  1956. {Py_mod_exec, hashlib_exception},
  1957. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  1958. {0, NULL}
  1959. };
  1960. static struct PyModuleDef _hashlibmodule = {
  1961. PyModuleDef_HEAD_INIT,
  1962. .m_name = "_hashlib",
  1963. .m_doc = "OpenSSL interface for hashlib module",
  1964. .m_size = sizeof(_hashlibstate),
  1965. .m_methods = EVP_functions,
  1966. .m_slots = hashlib_slots,
  1967. .m_traverse = hashlib_traverse,
  1968. .m_clear = hashlib_clear,
  1969. .m_free = hashlib_free
  1970. };
  1971. PyMODINIT_FUNC
  1972. PyInit__hashlib(void)
  1973. {
  1974. return PyModuleDef_Init(&_hashlibmodule);
  1975. }