_hashopenssl.c 60 KB

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