You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

461 lines
15 KiB

  1. # Copyright 2011 Sybren A. Stüvel <sybren@stuvel.eu>
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # https://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Functions for PKCS#1 version 1.5 encryption and signing
  15. This module implements certain functionality from PKCS#1 version 1.5. For a
  16. very clear example, read http://www.di-mgt.com.au/rsa_alg.html#pkcs1schemes
  17. At least 8 bytes of random padding is used when encrypting a message. This makes
  18. these methods much more secure than the ones in the ``rsa`` module.
  19. WARNING: this module leaks information when decryption fails. The exceptions
  20. that are raised contain the Python traceback information, which can be used to
  21. deduce where in the process the failure occurred. DO NOT PASS SUCH INFORMATION
  22. to your users.
  23. """
  24. import hashlib
  25. import os
  26. import sys
  27. import typing
  28. from . import common, transform, core, key
  29. # ASN.1 codes that describe the hash algorithm used.
  30. HASH_ASN1 = {
  31. 'MD5': b'\x30\x20\x30\x0c\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x05\x05\x00\x04\x10',
  32. 'SHA-1': b'\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14',
  33. 'SHA-224': b'\x30\x2d\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x04\x05\x00\x04\x1c',
  34. 'SHA-256': b'\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x05\x00\x04\x20',
  35. 'SHA-384': b'\x30\x41\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02\x05\x00\x04\x30',
  36. 'SHA-512': b'\x30\x51\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03\x05\x00\x04\x40',
  37. }
  38. HASH_METHODS = {
  39. 'MD5': hashlib.md5,
  40. 'SHA-1': hashlib.sha1,
  41. 'SHA-224': hashlib.sha224,
  42. 'SHA-256': hashlib.sha256,
  43. 'SHA-384': hashlib.sha384,
  44. 'SHA-512': hashlib.sha512,
  45. }
  46. if sys.version_info >= (3, 6):
  47. # Python 3.6 introduced SHA3 support.
  48. HASH_ASN1.update({
  49. 'SHA3-256': b'\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x08\x05\x00\x04\x20',
  50. 'SHA3-384': b'\x30\x41\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x09\x05\x00\x04\x30',
  51. 'SHA3-512': b'\x30\x51\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x0a\x05\x00\x04\x40',
  52. })
  53. HASH_METHODS.update({
  54. 'SHA3-256': hashlib.sha3_256,
  55. 'SHA3-384': hashlib.sha3_384,
  56. 'SHA3-512': hashlib.sha3_512,
  57. })
  58. class CryptoError(Exception):
  59. """Base class for all exceptions in this module."""
  60. class DecryptionError(CryptoError):
  61. """Raised when decryption fails."""
  62. class VerificationError(CryptoError):
  63. """Raised when verification fails."""
  64. def _pad_for_encryption(message: bytes, target_length: int) -> bytes:
  65. r"""Pads the message for encryption, returning the padded message.
  66. :return: 00 02 RANDOM_DATA 00 MESSAGE
  67. >>> block = _pad_for_encryption(b'hello', 16)
  68. >>> len(block)
  69. 16
  70. >>> block[0:2]
  71. b'\x00\x02'
  72. >>> block[-6:]
  73. b'\x00hello'
  74. """
  75. max_msglength = target_length - 11
  76. msglength = len(message)
  77. if msglength > max_msglength:
  78. raise OverflowError('%i bytes needed for message, but there is only'
  79. ' space for %i' % (msglength, max_msglength))
  80. # Get random padding
  81. padding = b''
  82. padding_length = target_length - msglength - 3
  83. # We remove 0-bytes, so we'll end up with less padding than we've asked for,
  84. # so keep adding data until we're at the correct length.
  85. while len(padding) < padding_length:
  86. needed_bytes = padding_length - len(padding)
  87. # Always read at least 8 bytes more than we need, and trim off the rest
  88. # after removing the 0-bytes. This increases the chance of getting
  89. # enough bytes, especially when needed_bytes is small
  90. new_padding = os.urandom(needed_bytes + 5)
  91. new_padding = new_padding.replace(b'\x00', b'')
  92. padding = padding + new_padding[:needed_bytes]
  93. assert len(padding) == padding_length
  94. return b''.join([b'\x00\x02',
  95. padding,
  96. b'\x00',
  97. message])
  98. def _pad_for_signing(message: bytes, target_length: int) -> bytes:
  99. r"""Pads the message for signing, returning the padded message.
  100. The padding is always a repetition of FF bytes.
  101. :return: 00 01 PADDING 00 MESSAGE
  102. >>> block = _pad_for_signing(b'hello', 16)
  103. >>> len(block)
  104. 16
  105. >>> block[0:2]
  106. b'\x00\x01'
  107. >>> block[-6:]
  108. b'\x00hello'
  109. >>> block[2:-6]
  110. b'\xff\xff\xff\xff\xff\xff\xff\xff'
  111. """
  112. max_msglength = target_length - 11
  113. msglength = len(message)
  114. if msglength > max_msglength:
  115. raise OverflowError('%i bytes needed for message, but there is only'
  116. ' space for %i' % (msglength, max_msglength))
  117. padding_length = target_length - msglength - 3
  118. return b''.join([b'\x00\x01',
  119. padding_length * b'\xff',
  120. b'\x00',
  121. message])
  122. def encrypt(message: bytes, pub_key: key.PublicKey) -> bytes:
  123. """Encrypts the given message using PKCS#1 v1.5
  124. :param message: the message to encrypt. Must be a byte string no longer than
  125. ``k-11`` bytes, where ``k`` is the number of bytes needed to encode
  126. the ``n`` component of the public key.
  127. :param pub_key: the :py:class:`rsa.PublicKey` to encrypt with.
  128. :raise OverflowError: when the message is too large to fit in the padded
  129. block.
  130. >>> from rsa import key, common
  131. >>> (pub_key, priv_key) = key.newkeys(256)
  132. >>> message = b'hello'
  133. >>> crypto = encrypt(message, pub_key)
  134. The crypto text should be just as long as the public key 'n' component:
  135. >>> len(crypto) == common.byte_size(pub_key.n)
  136. True
  137. """
  138. keylength = common.byte_size(pub_key.n)
  139. padded = _pad_for_encryption(message, keylength)
  140. payload = transform.bytes2int(padded)
  141. encrypted = core.encrypt_int(payload, pub_key.e, pub_key.n)
  142. block = transform.int2bytes(encrypted, keylength)
  143. return block
  144. def decrypt(crypto: bytes, priv_key: key.PrivateKey) -> bytes:
  145. r"""Decrypts the given message using PKCS#1 v1.5
  146. The decryption is considered 'failed' when the resulting cleartext doesn't
  147. start with the bytes 00 02, or when the 00 byte between the padding and
  148. the message cannot be found.
  149. :param crypto: the crypto text as returned by :py:func:`rsa.encrypt`
  150. :param priv_key: the :py:class:`rsa.PrivateKey` to decrypt with.
  151. :raise DecryptionError: when the decryption fails. No details are given as
  152. to why the code thinks the decryption fails, as this would leak
  153. information about the private key.
  154. >>> import rsa
  155. >>> (pub_key, priv_key) = rsa.newkeys(256)
  156. It works with strings:
  157. >>> crypto = encrypt(b'hello', pub_key)
  158. >>> decrypt(crypto, priv_key)
  159. b'hello'
  160. And with binary data:
  161. >>> crypto = encrypt(b'\x00\x00\x00\x00\x01', pub_key)
  162. >>> decrypt(crypto, priv_key)
  163. b'\x00\x00\x00\x00\x01'
  164. Altering the encrypted information will *likely* cause a
  165. :py:class:`rsa.pkcs1.DecryptionError`. If you want to be *sure*, use
  166. :py:func:`rsa.sign`.
  167. .. warning::
  168. Never display the stack trace of a
  169. :py:class:`rsa.pkcs1.DecryptionError` exception. It shows where in the
  170. code the exception occurred, and thus leaks information about the key.
  171. It's only a tiny bit of information, but every bit makes cracking the
  172. keys easier.
  173. >>> crypto = encrypt(b'hello', pub_key)
  174. >>> crypto = crypto[0:5] + b'X' + crypto[6:] # change a byte
  175. >>> decrypt(crypto, priv_key)
  176. Traceback (most recent call last):
  177. ...
  178. rsa.pkcs1.DecryptionError: Decryption failed
  179. """
  180. blocksize = common.byte_size(priv_key.n)
  181. encrypted = transform.bytes2int(crypto)
  182. decrypted = priv_key.blinded_decrypt(encrypted)
  183. cleartext = transform.int2bytes(decrypted, blocksize)
  184. # Detect leading zeroes in the crypto. These are not reflected in the
  185. # encrypted value (as leading zeroes do not influence the value of an
  186. # integer). This fixes CVE-2020-13757.
  187. if len(crypto) > blocksize:
  188. raise DecryptionError('Decryption failed')
  189. # If we can't find the cleartext marker, decryption failed.
  190. if cleartext[0:2] != b'\x00\x02':
  191. raise DecryptionError('Decryption failed')
  192. # Find the 00 separator between the padding and the message
  193. try:
  194. sep_idx = cleartext.index(b'\x00', 2)
  195. except ValueError:
  196. raise DecryptionError('Decryption failed')
  197. return cleartext[sep_idx + 1:]
  198. def sign_hash(hash_value: bytes, priv_key: key.PrivateKey, hash_method: str) -> bytes:
  199. """Signs a precomputed hash with the private key.
  200. Hashes the message, then signs the hash with the given key. This is known
  201. as a "detached signature", because the message itself isn't altered.
  202. :param hash_value: A precomputed hash to sign (ignores message).
  203. :param priv_key: the :py:class:`rsa.PrivateKey` to sign with
  204. :param hash_method: the hash method used on the message. Use 'MD5', 'SHA-1',
  205. 'SHA-224', SHA-256', 'SHA-384' or 'SHA-512'.
  206. :return: a message signature block.
  207. :raise OverflowError: if the private key is too small to contain the
  208. requested hash.
  209. """
  210. # Get the ASN1 code for this hash method
  211. if hash_method not in HASH_ASN1:
  212. raise ValueError('Invalid hash method: %s' % hash_method)
  213. asn1code = HASH_ASN1[hash_method]
  214. # Encrypt the hash with the private key
  215. cleartext = asn1code + hash_value
  216. keylength = common.byte_size(priv_key.n)
  217. padded = _pad_for_signing(cleartext, keylength)
  218. payload = transform.bytes2int(padded)
  219. encrypted = priv_key.blinded_encrypt(payload)
  220. block = transform.int2bytes(encrypted, keylength)
  221. return block
  222. def sign(message: bytes, priv_key: key.PrivateKey, hash_method: str) -> bytes:
  223. """Signs the message with the private key.
  224. Hashes the message, then signs the hash with the given key. This is known
  225. as a "detached signature", because the message itself isn't altered.
  226. :param message: the message to sign. Can be an 8-bit string or a file-like
  227. object. If ``message`` has a ``read()`` method, it is assumed to be a
  228. file-like object.
  229. :param priv_key: the :py:class:`rsa.PrivateKey` to sign with
  230. :param hash_method: the hash method used on the message. Use 'MD5', 'SHA-1',
  231. 'SHA-224', SHA-256', 'SHA-384' or 'SHA-512'.
  232. :return: a message signature block.
  233. :raise OverflowError: if the private key is too small to contain the
  234. requested hash.
  235. """
  236. msg_hash = compute_hash(message, hash_method)
  237. return sign_hash(msg_hash, priv_key, hash_method)
  238. def verify(message: bytes, signature: bytes, pub_key: key.PublicKey) -> str:
  239. """Verifies that the signature matches the message.
  240. The hash method is detected automatically from the signature.
  241. :param message: the signed message. Can be an 8-bit string or a file-like
  242. object. If ``message`` has a ``read()`` method, it is assumed to be a
  243. file-like object.
  244. :param signature: the signature block, as created with :py:func:`rsa.sign`.
  245. :param pub_key: the :py:class:`rsa.PublicKey` of the person signing the message.
  246. :raise VerificationError: when the signature doesn't match the message.
  247. :returns: the name of the used hash.
  248. """
  249. keylength = common.byte_size(pub_key.n)
  250. encrypted = transform.bytes2int(signature)
  251. decrypted = core.decrypt_int(encrypted, pub_key.e, pub_key.n)
  252. clearsig = transform.int2bytes(decrypted, keylength)
  253. # Get the hash method
  254. method_name = _find_method_hash(clearsig)
  255. message_hash = compute_hash(message, method_name)
  256. # Reconstruct the expected padded hash
  257. cleartext = HASH_ASN1[method_name] + message_hash
  258. expected = _pad_for_signing(cleartext, keylength)
  259. if len(signature) != keylength:
  260. raise VerificationError('Verification failed')
  261. # Compare with the signed one
  262. if expected != clearsig:
  263. raise VerificationError('Verification failed')
  264. return method_name
  265. def find_signature_hash(signature: bytes, pub_key: key.PublicKey) -> str:
  266. """Returns the hash name detected from the signature.
  267. If you also want to verify the message, use :py:func:`rsa.verify()` instead.
  268. It also returns the name of the used hash.
  269. :param signature: the signature block, as created with :py:func:`rsa.sign`.
  270. :param pub_key: the :py:class:`rsa.PublicKey` of the person signing the message.
  271. :returns: the name of the used hash.
  272. """
  273. keylength = common.byte_size(pub_key.n)
  274. encrypted = transform.bytes2int(signature)
  275. decrypted = core.decrypt_int(encrypted, pub_key.e, pub_key.n)
  276. clearsig = transform.int2bytes(decrypted, keylength)
  277. return _find_method_hash(clearsig)
  278. def yield_fixedblocks(infile: typing.BinaryIO, blocksize: int) -> typing.Iterator[bytes]:
  279. """Generator, yields each block of ``blocksize`` bytes in the input file.
  280. :param infile: file to read and separate in blocks.
  281. :param blocksize: block size in bytes.
  282. :returns: a generator that yields the contents of each block
  283. """
  284. while True:
  285. block = infile.read(blocksize)
  286. read_bytes = len(block)
  287. if read_bytes == 0:
  288. break
  289. yield block
  290. if read_bytes < blocksize:
  291. break
  292. def compute_hash(message: typing.Union[bytes, typing.BinaryIO], method_name: str) -> bytes:
  293. """Returns the message digest.
  294. :param message: the signed message. Can be an 8-bit string or a file-like
  295. object. If ``message`` has a ``read()`` method, it is assumed to be a
  296. file-like object.
  297. :param method_name: the hash method, must be a key of
  298. :py:const:`HASH_METHODS`.
  299. """
  300. if method_name not in HASH_METHODS:
  301. raise ValueError('Invalid hash method: %s' % method_name)
  302. method = HASH_METHODS[method_name]
  303. hasher = method()
  304. if isinstance(message, bytes):
  305. hasher.update(message)
  306. else:
  307. assert hasattr(message, 'read') and hasattr(message.read, '__call__')
  308. # read as 1K blocks
  309. for block in yield_fixedblocks(message, 1024):
  310. hasher.update(block)
  311. return hasher.digest()
  312. def _find_method_hash(clearsig: bytes) -> str:
  313. """Finds the hash method.
  314. :param clearsig: full padded ASN1 and hash.
  315. :return: the used hash method.
  316. :raise VerificationFailed: when the hash method cannot be found
  317. """
  318. for (hashname, asn1code) in HASH_ASN1.items():
  319. if asn1code in clearsig:
  320. return hashname
  321. raise VerificationError('Verification failed')
  322. __all__ = ['encrypt', 'decrypt', 'sign', 'verify',
  323. 'DecryptionError', 'VerificationError', 'CryptoError']
  324. if __name__ == '__main__':
  325. print('Running doctests 1000x or until failure')
  326. import doctest
  327. for count in range(1000):
  328. (failures, tests) = doctest.testmod()
  329. if failures:
  330. break
  331. if count % 100 == 0 and count:
  332. print('%i times' % count)
  333. print('Doctests done')