| 1 | """ |
| 2 | Provides _compare_digest method, which is a safe comparing to prevent timing |
| 3 | attacks for the hmac module. |
| 4 | """ |
| 5 | import py |
| 6 | |
| 7 | from rpython.rtyper.lltypesystem import lltype, rffi |
| 8 | from rpython.translator import cdir |
| 9 | from rpython.translator.tool.cbuild import ExternalCompilationInfo |
| 10 | |
| 11 | from pypy.interpreter.error import OperationError, oefmt |
| 12 | from pypy.interpreter.unicodehelper import encode |
| 13 | |
| 14 | cwd = py.path.local(__file__).dirpath() |
| 15 | eci = ExternalCompilationInfo( |
| 16 | includes=[cwd.join('tscmp.h')], |
| 17 | include_dirs=[str(cwd), cdir], |
| 18 | separate_module_files=[cwd.join('tscmp.c')]) |
| 19 | |
| 20 | |
| 21 | def llexternal(*args, **kwargs): |
| 22 | kwargs.setdefault('compilation_info', eci) |
| 23 | kwargs.setdefault('sandboxsafe', True) |
| 24 | return rffi.llexternal(*args, **kwargs) |
| 25 | |
| 26 | |
| 27 | pypy_tscmp = llexternal( |
| 28 | 'pypy_tscmp', |
| 29 | [rffi.CCHARP, rffi.CCHARP, rffi.SIGNED, rffi.SIGNED], |
| 30 | rffi.INT) |
| 31 | |
| 32 | |
| 33 | def compare_digest(space, w_a, w_b): |
| 34 | """compare_digest(a, b) -> bool |
| 35 | |
| 36 | Return 'a == b'. This function uses an approach designed to prevent |
| 37 | timing analysis, making it appropriate for cryptography. a and b |
| 38 | must both be of the same type: either str (ASCII only), or any type |
| 39 | that supports the buffer protocol (e.g. bytes). |
| 40 | |
| 41 | Note: If a and b are of different lengths, or if an error occurs, a |
| 42 | timing attack could theoretically reveal information about the types |
| 43 | and lengths of a and b--but not their values. |
| 44 | |
| 45 | XXX note that here the strings have to have the same length as UTF8, |
| 46 | not only as unicode. Not sure how to do better |
| 47 | """ |
| 48 | if (space.isinstance_w(w_a, space.w_unicode) and |
| 49 | space.isinstance_w(w_b, space.w_unicode)): |
| 50 | try: |
| 51 | w_a = encode(space, w_a, 'ascii') |
| 52 | w_b = encode(space, w_b, 'ascii') |
| 53 | except OperationError as e: |
| 54 | if not e.match(space, space.w_UnicodeEncodeError): |
| 55 | raise |
| 56 | raise oefmt(space.w_TypeError, |
| 57 | "comparing strings with non-ASCII characters is not " |
| 58 | "supported") |
| 59 | return compare_digest_buffer(space, w_a, w_b) |
| 60 | |
| 61 | |
| 62 | def compare_digest_buffer(space, w_a, w_b): |
| 63 | a = space.charbuf_w(w_a) |
| 64 | b = space.charbuf_w(w_b) |
| 65 | return space.newbool(_compare_two_strings(a, b)) |
| 66 | |
| 67 | def _compare_two_strings(a, b): |
| 68 | with rffi.scoped_nonmovingbuffer(a) as a_buf: |
| 69 | with rffi.scoped_nonmovingbuffer(b) as b_buf: |
| 70 | result = pypy_tscmp(a_buf, b_buf, len(a), len(b)) |
| 71 | return rffi.cast(lltype.Bool, result) |