1 /* SHA1 module */
2 
3 /* This module provides an interface to the SHA1 algorithm */
4 
5 /* See below for information about the original code this module was
6    based upon. Additional work performed by:
7 
8    Andrew Kuchling ([email protected])
9    Greg Stein ([email protected])
10    Trevor Perrin ([email protected])
11 
12    Copyright (C) 2005-2007   Gregory P. Smith ([email protected])
13    Licensed to PSF under a Contributor Agreement.
14 
15 */
16 
17 /* SHA1 objects */
18 #ifndef Py_BUILD_CORE_BUILTIN
19 #  define Py_BUILD_CORE_MODULE 1
20 #endif
21 
22 #include "Python.h"
23 #include "hashlib.h"
24 #include "pycore_strhex.h"        // _Py_strhex()
25 
26 /*[clinic input]
27 module _sha1
28 class SHA1Type "SHA1object *" "&PyType_Type"
29 [clinic start generated code]*/
30 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=3dc9a20d1becb759]*/
31 
32 /* Some useful types */
33 
34 #if SIZEOF_INT == 4
35 typedef unsigned int SHA1_INT32;        /* 32-bit integer */
36 typedef long long SHA1_INT64;        /* 64-bit integer */
37 #else
38 /* not defined. compilation will die. */
39 #endif
40 
41 /* The SHA1 block size and message digest sizes, in bytes */
42 
43 #define SHA1_BLOCKSIZE    64
44 #define SHA1_DIGESTSIZE   20
45 
46 /* The structure for storing SHA1 info */
47 
48 struct sha1_state {
49     SHA1_INT64 length;
50     SHA1_INT32 state[5], curlen;
51     unsigned char buf[SHA1_BLOCKSIZE];
52 };
53 
54 typedef struct {
55     PyObject_HEAD
56 
57     struct sha1_state hash_state;
58 } SHA1object;
59 
60 #include "clinic/sha1module.c.h"
61 
62 /* ------------------------------------------------------------------------
63  *
64  * This code for the SHA1 algorithm was noted as public domain. The
65  * original headers are pasted below.
66  *
67  * Several changes have been made to make it more compatible with the
68  * Python environment and desired interface.
69  *
70  */
71 
72 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
73  *
74  * LibTomCrypt is a library that provides various cryptographic
75  * algorithms in a highly modular and flexible manner.
76  *
77  * The library is free for all purposes without any express
78  * guarantee it works.
79  *
80  * Tom St Denis, [email protected], https://www.libtom.net
81  */
82 
83 /* rotate the hard way (platform optimizations could be done) */
84 #define ROL(x, y) ( (((unsigned long)(x)<<(unsigned long)((y)&31)) | (((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL)
85 #define ROLc(x, y) ( (((unsigned long)(x)<<(unsigned long)((y)&31)) | (((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL)
86 
87 /* Endian Neutral macros that work on all platforms */
88 
89 #define STORE32H(x, y)                                                                     \
90      { (y)[0] = (unsigned char)(((x)>>24)&255); (y)[1] = (unsigned char)(((x)>>16)&255);   \
91        (y)[2] = (unsigned char)(((x)>>8)&255); (y)[3] = (unsigned char)((x)&255); }
92 
93 #define LOAD32H(x, y)                            \
94      { x = ((unsigned long)((y)[0] & 255)<<24) | \
95            ((unsigned long)((y)[1] & 255)<<16) | \
96            ((unsigned long)((y)[2] & 255)<<8)  | \
97            ((unsigned long)((y)[3] & 255)); }
98 
99 #define STORE64H(x, y)                                                                     \
100    { (y)[0] = (unsigned char)(((x)>>56)&255); (y)[1] = (unsigned char)(((x)>>48)&255);     \
101      (y)[2] = (unsigned char)(((x)>>40)&255); (y)[3] = (unsigned char)(((x)>>32)&255);     \
102      (y)[4] = (unsigned char)(((x)>>24)&255); (y)[5] = (unsigned char)(((x)>>16)&255);     \
103      (y)[6] = (unsigned char)(((x)>>8)&255); (y)[7] = (unsigned char)((x)&255); }
104 
105 
106 /* SHA1 macros */
107 
108 #define F0(x,y,z)  (z ^ (x & (y ^ z)))
109 #define F1(x,y,z)  (x ^ y ^ z)
110 #define F2(x,y,z)  ((x & y) | (z & (x | y)))
111 #define F3(x,y,z)  (x ^ y ^ z)
112 
sha1_compress(struct sha1_state * sha1,unsigned char * buf)113 static void sha1_compress(struct sha1_state *sha1, unsigned char *buf)
114 {
115     SHA1_INT32 a,b,c,d,e,W[80],i;
116 
117     /* copy the state into 512-bits into W[0..15] */
118     for (i = 0; i < 16; i++) {
119         LOAD32H(W[i], buf + (4*i));
120     }
121 
122     /* copy state */
123     a = sha1->state[0];
124     b = sha1->state[1];
125     c = sha1->state[2];
126     d = sha1->state[3];
127     e = sha1->state[4];
128 
129     /* expand it */
130     for (i = 16; i < 80; i++) {
131         W[i] = ROL(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1);
132     }
133 
134     /* compress */
135     /* round one */
136     #define FF_0(a,b,c,d,e,i) e = (ROLc(a, 5) + F0(b,c,d) + e + W[i] + 0x5a827999UL); b = ROLc(b, 30);
137     #define FF_1(a,b,c,d,e,i) e = (ROLc(a, 5) + F1(b,c,d) + e + W[i] + 0x6ed9eba1UL); b = ROLc(b, 30);
138     #define FF_2(a,b,c,d,e,i) e = (ROLc(a, 5) + F2(b,c,d) + e + W[i] + 0x8f1bbcdcUL); b = ROLc(b, 30);
139     #define FF_3(a,b,c,d,e,i) e = (ROLc(a, 5) + F3(b,c,d) + e + W[i] + 0xca62c1d6UL); b = ROLc(b, 30);
140 
141     for (i = 0; i < 20; ) {
142        FF_0(a,b,c,d,e,i++);
143        FF_0(e,a,b,c,d,i++);
144        FF_0(d,e,a,b,c,i++);
145        FF_0(c,d,e,a,b,i++);
146        FF_0(b,c,d,e,a,i++);
147     }
148 
149     /* round two */
150     for (; i < 40; )  {
151        FF_1(a,b,c,d,e,i++);
152        FF_1(e,a,b,c,d,i++);
153        FF_1(d,e,a,b,c,i++);
154        FF_1(c,d,e,a,b,i++);
155        FF_1(b,c,d,e,a,i++);
156     }
157 
158     /* round three */
159     for (; i < 60; )  {
160        FF_2(a,b,c,d,e,i++);
161        FF_2(e,a,b,c,d,i++);
162        FF_2(d,e,a,b,c,i++);
163        FF_2(c,d,e,a,b,i++);
164        FF_2(b,c,d,e,a,i++);
165     }
166 
167     /* round four */
168     for (; i < 80; )  {
169        FF_3(a,b,c,d,e,i++);
170        FF_3(e,a,b,c,d,i++);
171        FF_3(d,e,a,b,c,i++);
172        FF_3(c,d,e,a,b,i++);
173        FF_3(b,c,d,e,a,i++);
174     }
175 
176     #undef FF_0
177     #undef FF_1
178     #undef FF_2
179     #undef FF_3
180 
181     /* store */
182     sha1->state[0] = sha1->state[0] + a;
183     sha1->state[1] = sha1->state[1] + b;
184     sha1->state[2] = sha1->state[2] + c;
185     sha1->state[3] = sha1->state[3] + d;
186     sha1->state[4] = sha1->state[4] + e;
187 }
188 
189 /**
190    Initialize the hash state
191    @param sha1   The hash state you wish to initialize
192 */
193 static void
sha1_init(struct sha1_state * sha1)194 sha1_init(struct sha1_state *sha1)
195 {
196    assert(sha1 != NULL);
197    sha1->state[0] = 0x67452301UL;
198    sha1->state[1] = 0xefcdab89UL;
199    sha1->state[2] = 0x98badcfeUL;
200    sha1->state[3] = 0x10325476UL;
201    sha1->state[4] = 0xc3d2e1f0UL;
202    sha1->curlen = 0;
203    sha1->length = 0;
204 }
205 
206 /**
207    Process a block of memory though the hash
208    @param sha1   The hash state
209    @param in     The data to hash
210    @param inlen  The length of the data (octets)
211 */
212 static void
sha1_process(struct sha1_state * sha1,const unsigned char * in,Py_ssize_t inlen)213 sha1_process(struct sha1_state *sha1,
214                   const unsigned char *in, Py_ssize_t inlen)
215 {
216     Py_ssize_t n;
217 
218     assert(sha1 != NULL);
219     assert(in != NULL);
220     assert(sha1->curlen <= sizeof(sha1->buf));
221 
222     while (inlen > 0) {
223         if (sha1->curlen == 0 && inlen >= SHA1_BLOCKSIZE) {
224            sha1_compress(sha1, (unsigned char *)in);
225            sha1->length   += SHA1_BLOCKSIZE * 8;
226            in             += SHA1_BLOCKSIZE;
227            inlen          -= SHA1_BLOCKSIZE;
228         } else {
229            n = Py_MIN(inlen, (Py_ssize_t)(SHA1_BLOCKSIZE - sha1->curlen));
230            memcpy(sha1->buf + sha1->curlen, in, (size_t)n);
231            sha1->curlen   += (SHA1_INT32)n;
232            in             += n;
233            inlen          -= n;
234            if (sha1->curlen == SHA1_BLOCKSIZE) {
235               sha1_compress(sha1, sha1->buf);
236               sha1->length += 8*SHA1_BLOCKSIZE;
237               sha1->curlen = 0;
238            }
239        }
240     }
241 }
242 
243 /**
244    Terminate the hash to get the digest
245    @param sha1  The hash state
246    @param out [out] The destination of the hash (20 bytes)
247 */
248 static void
sha1_done(struct sha1_state * sha1,unsigned char * out)249 sha1_done(struct sha1_state *sha1, unsigned char *out)
250 {
251     int i;
252 
253     assert(sha1 != NULL);
254     assert(out != NULL);
255     assert(sha1->curlen < sizeof(sha1->buf));
256 
257     /* increase the length of the message */
258     sha1->length += sha1->curlen * 8;
259 
260     /* append the '1' bit */
261     sha1->buf[sha1->curlen++] = (unsigned char)0x80;
262 
263     /* if the length is currently above 56 bytes we append zeros
264      * then compress.  Then we can fall back to padding zeros and length
265      * encoding like normal.
266      */
267     if (sha1->curlen > 56) {
268         while (sha1->curlen < 64) {
269             sha1->buf[sha1->curlen++] = (unsigned char)0;
270         }
271         sha1_compress(sha1, sha1->buf);
272         sha1->curlen = 0;
273     }
274 
275     /* pad up to 56 bytes of zeroes */
276     while (sha1->curlen < 56) {
277         sha1->buf[sha1->curlen++] = (unsigned char)0;
278     }
279 
280     /* store length */
281     STORE64H(sha1->length, sha1->buf+56);
282     sha1_compress(sha1, sha1->buf);
283 
284     /* copy output */
285     for (i = 0; i < 5; i++) {
286         STORE32H(sha1->state[i], out+(4*i));
287     }
288 }
289 
290 
291 /* .Source: /cvs/libtom/libtomcrypt/src/hashes/sha1.c,v $ */
292 /* .Revision: 1.10 $ */
293 /* .Date: 2007/05/12 14:25:28 $ */
294 
295 /*
296  * End of copied SHA1 code.
297  *
298  * ------------------------------------------------------------------------
299  */
300 
301 typedef struct {
302     PyTypeObject* sha1_type;
303 } SHA1State;
304 
305 static inline SHA1State*
sha1_get_state(PyObject * module)306 sha1_get_state(PyObject *module)
307 {
308     void *state = PyModule_GetState(module);
309     assert(state != NULL);
310     return (SHA1State *)state;
311 }
312 
313 static SHA1object *
newSHA1object(SHA1State * st)314 newSHA1object(SHA1State *st)
315 {
316     SHA1object *sha = (SHA1object *)PyObject_GC_New(SHA1object, st->sha1_type);
317     PyObject_GC_Track(sha);
318     return sha;
319 }
320 
321 
322 /* Internal methods for a hash object */
323 static int
SHA1_traverse(PyObject * ptr,visitproc visit,void * arg)324 SHA1_traverse(PyObject *ptr, visitproc visit, void *arg)
325 {
326     Py_VISIT(Py_TYPE(ptr));
327     return 0;
328 }
329 
330 static void
SHA1_dealloc(PyObject * ptr)331 SHA1_dealloc(PyObject *ptr)
332 {
333     PyTypeObject *tp = Py_TYPE(ptr);
334     PyObject_GC_UnTrack(ptr);
335     PyObject_GC_Del(ptr);
336     Py_DECREF(tp);
337 }
338 
339 
340 /* External methods for a hash object */
341 
342 /*[clinic input]
343 SHA1Type.copy
344 
345     cls: defining_class
346 
347 Return a copy of the hash object.
348 [clinic start generated code]*/
349 
350 static PyObject *
SHA1Type_copy_impl(SHA1object * self,PyTypeObject * cls)351 SHA1Type_copy_impl(SHA1object *self, PyTypeObject *cls)
352 /*[clinic end generated code: output=b32d4461ce8bc7a7 input=6c22e66fcc34c58e]*/
353 {
354     SHA1State *st = PyType_GetModuleState(cls);
355 
356     SHA1object *newobj;
357     if ((newobj = newSHA1object(st)) == NULL)
358         return NULL;
359 
360     newobj->hash_state = self->hash_state;
361     return (PyObject *)newobj;
362 }
363 
364 /*[clinic input]
365 SHA1Type.digest
366 
367 Return the digest value as a bytes object.
368 [clinic start generated code]*/
369 
370 static PyObject *
SHA1Type_digest_impl(SHA1object * self)371 SHA1Type_digest_impl(SHA1object *self)
372 /*[clinic end generated code: output=2f05302a7aa2b5cb input=13824b35407444bd]*/
373 {
374     unsigned char digest[SHA1_DIGESTSIZE];
375     struct sha1_state temp;
376 
377     temp = self->hash_state;
378     sha1_done(&temp, digest);
379     return PyBytes_FromStringAndSize((const char *)digest, SHA1_DIGESTSIZE);
380 }
381 
382 /*[clinic input]
383 SHA1Type.hexdigest
384 
385 Return the digest value as a string of hexadecimal digits.
386 [clinic start generated code]*/
387 
388 static PyObject *
SHA1Type_hexdigest_impl(SHA1object * self)389 SHA1Type_hexdigest_impl(SHA1object *self)
390 /*[clinic end generated code: output=4161fd71e68c6659 input=97691055c0c74ab0]*/
391 {
392     unsigned char digest[SHA1_DIGESTSIZE];
393     struct sha1_state temp;
394 
395     /* Get the raw (binary) digest value */
396     temp = self->hash_state;
397     sha1_done(&temp, digest);
398 
399     return _Py_strhex((const char *)digest, SHA1_DIGESTSIZE);
400 }
401 
402 /*[clinic input]
403 SHA1Type.update
404 
405     obj: object
406     /
407 
408 Update this hash object's state with the provided string.
409 [clinic start generated code]*/
410 
411 static PyObject *
SHA1Type_update(SHA1object * self,PyObject * obj)412 SHA1Type_update(SHA1object *self, PyObject *obj)
413 /*[clinic end generated code: output=d9902f0e5015e9ae input=aad8e07812edbba3]*/
414 {
415     Py_buffer buf;
416 
417     GET_BUFFER_VIEW_OR_ERROUT(obj, &buf);
418 
419     sha1_process(&self->hash_state, buf.buf, buf.len);
420 
421     PyBuffer_Release(&buf);
422     Py_RETURN_NONE;
423 }
424 
425 static PyMethodDef SHA1_methods[] = {
426     SHA1TYPE_COPY_METHODDEF
427     SHA1TYPE_DIGEST_METHODDEF
428     SHA1TYPE_HEXDIGEST_METHODDEF
429     SHA1TYPE_UPDATE_METHODDEF
430     {NULL,        NULL}         /* sentinel */
431 };
432 
433 static PyObject *
SHA1_get_block_size(PyObject * self,void * closure)434 SHA1_get_block_size(PyObject *self, void *closure)
435 {
436     return PyLong_FromLong(SHA1_BLOCKSIZE);
437 }
438 
439 static PyObject *
SHA1_get_name(PyObject * self,void * closure)440 SHA1_get_name(PyObject *self, void *closure)
441 {
442     return PyUnicode_FromStringAndSize("sha1", 4);
443 }
444 
445 static PyObject *
sha1_get_digest_size(PyObject * self,void * closure)446 sha1_get_digest_size(PyObject *self, void *closure)
447 {
448     return PyLong_FromLong(SHA1_DIGESTSIZE);
449 }
450 
451 static PyGetSetDef SHA1_getseters[] = {
452     {"block_size",
453      (getter)SHA1_get_block_size, NULL,
454      NULL,
455      NULL},
456     {"name",
457      (getter)SHA1_get_name, NULL,
458      NULL,
459      NULL},
460     {"digest_size",
461      (getter)sha1_get_digest_size, NULL,
462      NULL,
463      NULL},
464     {NULL}  /* Sentinel */
465 };
466 
467 static PyType_Slot sha1_type_slots[] = {
468     {Py_tp_dealloc, SHA1_dealloc},
469     {Py_tp_methods, SHA1_methods},
470     {Py_tp_getset, SHA1_getseters},
471     {Py_tp_traverse, SHA1_traverse},
472     {0,0}
473 };
474 
475 static PyType_Spec sha1_type_spec = {
476     .name = "_sha1.sha1",
477     .basicsize =  sizeof(SHA1object),
478     .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION |
479               Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_HAVE_GC),
480     .slots = sha1_type_slots
481 };
482 
483 /* The single module-level function: new() */
484 
485 /*[clinic input]
486 _sha1.sha1
487 
488     string: object(c_default="NULL") = b''
489     *
490     usedforsecurity: bool = True
491 
492 Return a new SHA1 hash object; optionally initialized with a string.
493 [clinic start generated code]*/
494 
495 static PyObject *
_sha1_sha1_impl(PyObject * module,PyObject * string,int usedforsecurity)496 _sha1_sha1_impl(PyObject *module, PyObject *string, int usedforsecurity)
497 /*[clinic end generated code: output=6f8b3af05126e18e input=bd54b68e2bf36a8a]*/
498 {
499     SHA1object *new;
500     Py_buffer buf;
501 
502     if (string)
503         GET_BUFFER_VIEW_OR_ERROUT(string, &buf);
504 
505     SHA1State *st = sha1_get_state(module);
506     if ((new = newSHA1object(st)) == NULL) {
507         if (string)
508             PyBuffer_Release(&buf);
509         return NULL;
510     }
511 
512     sha1_init(&new->hash_state);
513 
514     if (PyErr_Occurred()) {
515         Py_DECREF(new);
516         if (string)
517             PyBuffer_Release(&buf);
518         return NULL;
519     }
520     if (string) {
521         sha1_process(&new->hash_state, buf.buf, buf.len);
522         PyBuffer_Release(&buf);
523     }
524 
525     return (PyObject *)new;
526 }
527 
528 
529 /* List of functions exported by this module */
530 
531 static struct PyMethodDef SHA1_functions[] = {
532     _SHA1_SHA1_METHODDEF
533     {NULL,      NULL}            /* Sentinel */
534 };
535 
536 static int
_sha1_traverse(PyObject * module,visitproc visit,void * arg)537 _sha1_traverse(PyObject *module, visitproc visit, void *arg)
538 {
539     SHA1State *state = sha1_get_state(module);
540     Py_VISIT(state->sha1_type);
541     return 0;
542 }
543 
544 static int
_sha1_clear(PyObject * module)545 _sha1_clear(PyObject *module)
546 {
547     SHA1State *state = sha1_get_state(module);
548     Py_CLEAR(state->sha1_type);
549     return 0;
550 }
551 
552 static void
_sha1_free(void * module)553 _sha1_free(void *module)
554 {
555     _sha1_clear((PyObject *)module);
556 }
557 
558 static int
_sha1_exec(PyObject * module)559 _sha1_exec(PyObject *module)
560 {
561     SHA1State* st = sha1_get_state(module);
562 
563     st->sha1_type = (PyTypeObject *)PyType_FromModuleAndSpec(
564         module, &sha1_type_spec, NULL);
565 
566     if (st->sha1_type == NULL) {
567         return -1;
568     }
569 
570     Py_INCREF(st->sha1_type);
571     if (PyModule_AddObject(module,
572                            "SHA1Type",
573                            (PyObject *)st->sha1_type) < 0) {
574         Py_DECREF(st->sha1_type);
575         return -1;
576     }
577 
578     return 0;
579 }
580 
581 
582 /* Initialize this module. */
583 
584 static PyModuleDef_Slot _sha1_slots[] = {
585     {Py_mod_exec, _sha1_exec},
586     {0, NULL}
587 };
588 
589 static struct PyModuleDef _sha1module = {
590         PyModuleDef_HEAD_INIT,
591         .m_name = "_sha1",
592         .m_size = sizeof(SHA1State),
593         .m_methods = SHA1_functions,
594         .m_slots = _sha1_slots,
595         .m_traverse = _sha1_traverse,
596         .m_clear = _sha1_clear,
597         .m_free = _sha1_free
598 };
599 
600 PyMODINIT_FUNC
PyInit__sha1(void)601 PyInit__sha1(void)
602 {
603     return PyModuleDef_Init(&_sha1module);
604 }
605