Skip to content

Commit afb5e27

Browse files
committed
Fix side-channel leakage in RSA decryption
1 parent ee91c67 commit afb5e27

File tree

17 files changed

+350
-35
lines changed

17 files changed

+350
-35
lines changed

lib/Crypto/Cipher/PKCS1_OAEP.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -167,10 +167,8 @@ def decrypt(self, ciphertext):
167167
raise ValueError("Ciphertext with incorrect length.")
168168
# Step 2a (O2SIP)
169169
ct_int = bytes_to_long(ciphertext)
170-
# Step 2b (RSADP)
171-
m_int = self._key._decrypt(ct_int)
172-
# Complete step 2c (I2OSP)
173-
em = long_to_bytes(m_int, k)
170+
# Step 2b (RSADP) and step 2c (I2OSP)
171+
em = self._key._decrypt(ct_int)
174172
# Step 3a
175173
lHash = self._hashObj.new(self._label).digest()
176174
# Step 3b

lib/Crypto/Cipher/PKCS1_v1_5.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -176,11 +176,8 @@ def decrypt(self, ciphertext, sentinel, expected_pt_len=0):
176176
# Step 2a (O2SIP)
177177
ct_int = bytes_to_long(ciphertext)
178178

179-
# Step 2b (RSADP)
180-
m_int = self._key._decrypt(ct_int)
181-
182-
# Complete step 2c (I2OSP)
183-
em = long_to_bytes(m_int, k)
179+
# Step 2b (RSADP) and Step 2c (I2OSP)
180+
em = self._key._decrypt(ct_int)
184181

185182
# Step 3 (not constant time when the sentinel is not a byte string)
186183
output = bytes(bytearray(k))

lib/Crypto/Math/_IntegerBase.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -390,3 +390,23 @@ def random_range(cls, **kwargs):
390390
)
391391
return norm_candidate + min_inclusive
392392

393+
@staticmethod
394+
@abc.abstractmethod
395+
def _mult_modulo_bytes(term1, term2, modulus):
396+
"""Multiply two integers, take the modulo, and encode as big endian.
397+
This specialized method is used for RSA decryption.
398+
399+
Args:
400+
term1 : integer
401+
The first term of the multiplication, non-negative.
402+
term2 : integer
403+
The second term of the multiplication, non-negative.
404+
modulus: integer
405+
The modulus, a positive odd number.
406+
:Returns:
407+
A byte string, with the result of the modular multiplication
408+
encoded in big endian mode.
409+
It is as long as the modulus would be, with zero padding
410+
on the left if needed.
411+
"""
412+
pass

lib/Crypto/Math/_IntegerBase.pyi

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,4 +60,8 @@ class IntegerBase:
6060
def random(cls, **kwargs: Union[int,RandFunc]) -> IntegerBase : ...
6161
@classmethod
6262
def random_range(cls, **kwargs: Union[int,RandFunc]) -> IntegerBase : ...
63+
@staticmethod
64+
def _mult_modulo_bytes(term1: Union[IntegerBase, int],
65+
term2: Union[IntegerBase, int],
66+
modulus: Union[IntegerBase, int]) -> bytes: ...
6367

lib/Crypto/Math/_IntegerCustom.py

Lines changed: 50 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -41,12 +41,18 @@
4141
from Crypto.Random.random import getrandbits
4242

4343
c_defs = """
44-
int monty_pow(const uint8_t *base,
45-
const uint8_t *exp,
46-
const uint8_t *modulus,
47-
uint8_t *out,
48-
size_t len,
49-
uint64_t seed);
44+
int monty_pow(uint8_t *out,
45+
const uint8_t *base,
46+
const uint8_t *exp,
47+
const uint8_t *modulus,
48+
size_t len,
49+
uint64_t seed);
50+
51+
int monty_multiply(uint8_t *out,
52+
const uint8_t *term1,
53+
const uint8_t *term2,
54+
const uint8_t *modulus,
55+
size_t len);
5056
"""
5157

5258

@@ -116,3 +122,41 @@ def inplace_pow(self, exponent, modulus=None):
116122
result = bytes_to_long(get_raw_buffer(out))
117123
self._value = result
118124
return self
125+
126+
@staticmethod
127+
def _mult_modulo_bytes(term1, term2, modulus):
128+
129+
# With modular reduction
130+
mod_value = int(modulus)
131+
if mod_value < 0:
132+
raise ValueError("Modulus must be positive")
133+
if mod_value == 0:
134+
raise ZeroDivisionError("Modulus cannot be zero")
135+
136+
# C extension only works with odd moduli
137+
if (mod_value & 1) == 0:
138+
raise ValueError("Odd modulus is required")
139+
140+
# C extension only works with non-negative terms smaller than modulus
141+
if term1 >= mod_value or term1 < 0:
142+
term1 %= mod_value
143+
if term2 >= mod_value or term2 < 0:
144+
term2 %= mod_value
145+
146+
modulus_b = long_to_bytes(mod_value)
147+
numbers_len = len(modulus_b)
148+
term1_b = long_to_bytes(term1, numbers_len)
149+
term2_b = long_to_bytes(term2, numbers_len)
150+
out = create_string_buffer(numbers_len)
151+
152+
error = _raw_montgomery.monty_multiply(
153+
out,
154+
term1_b,
155+
term2_b,
156+
modulus_b,
157+
c_size_t(numbers_len)
158+
)
159+
if error:
160+
raise ValueError("monty_multiply failed with error: %d" % error)
161+
162+
return get_raw_buffer(out)

lib/Crypto/Math/_IntegerGMP.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -749,6 +749,26 @@ def jacobi_symbol(a, n):
749749
raise ValueError("n must be positive odd for the Jacobi symbol")
750750
return _gmp.mpz_jacobi(a._mpz_p, n._mpz_p)
751751

752+
@staticmethod
753+
def _mult_modulo_bytes(term1, term2, modulus):
754+
if not isinstance(term1, IntegerGMP):
755+
term1 = IntegerGMP(term1)
756+
if not isinstance(term2, IntegerGMP):
757+
term2 = IntegerGMP(term2)
758+
if not isinstance(modulus, IntegerGMP):
759+
modulus = IntegerGMP(modulus)
760+
761+
if modulus < 0:
762+
raise ValueError("Modulus must be positive")
763+
if modulus == 0:
764+
raise ZeroDivisionError("Modulus cannot be zero")
765+
if (modulus & 1) == 0:
766+
raise ValueError("Odd modulus is required")
767+
768+
numbers_len = len(modulus.to_bytes())
769+
result = ((term1 * term2) % modulus).to_bytes(numbers_len)
770+
return result
771+
752772
# Clean-up
753773
def __del__(self):
754774

lib/Crypto/Math/_IntegerNative.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -368,3 +368,15 @@ def jacobi_symbol(a, n):
368368
n1 = n % a1
369369
# Step 8
370370
return s * IntegerNative.jacobi_symbol(n1, a1)
371+
372+
@staticmethod
373+
def _mult_modulo_bytes(term1, term2, modulus):
374+
if modulus < 0:
375+
raise ValueError("Modulus must be positive")
376+
if modulus == 0:
377+
raise ZeroDivisionError("Modulus cannot be zero")
378+
if (modulus & 1) == 0:
379+
raise ValueError("Odd modulus is required")
380+
381+
number_len = len(long_to_bytes(modulus))
382+
return long_to_bytes((term1 * term2) % modulus, number_len)

lib/Crypto/PublicKey/RSA.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
from Crypto import Random
3939
from Crypto.Util.py3compat import tobytes, bord, tostr
4040
from Crypto.Util.asn1 import DerSequence, DerNull
41+
from Crypto.Util.number import bytes_to_long
4142

4243
from Crypto.Math.Numbers import Integer
4344
from Crypto.Math.Primality import (test_probable_prime,
@@ -198,10 +199,11 @@ def _decrypt(self, ciphertext):
198199
h = ((m2 - m1) * self._u) % self._q
199200
mp = h * self._p + m1
200201
# Step 4: Compute m = m' * (r**(-1)) mod n
201-
result = (r.inverse(self._n) * mp) % self._n
202-
# Verify no faults occurred
203-
if ciphertext != pow(result, self._e, self._n):
204-
raise ValueError("Fault detected in RSA decryption")
202+
# then encode into a big endian byte string
203+
result = Integer._mult_modulo_bytes(
204+
r.inverse(self._n),
205+
mp,
206+
self._n)
205207
return result
206208

207209
def has_private(self):

lib/Crypto/SelfTest/Math/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,11 @@ def get_tests(config={}):
3838
from Crypto.SelfTest.Math import test_Numbers
3939
from Crypto.SelfTest.Math import test_Primality
4040
from Crypto.SelfTest.Math import test_modexp
41+
from Crypto.SelfTest.Math import test_modmult
4142
tests += test_Numbers.get_tests(config=config)
4243
tests += test_Primality.get_tests(config=config)
4344
tests += test_modexp.get_tests(config=config)
45+
tests += test_modmult.get_tests(config=config)
4446
return tests
4547

4648
if __name__ == '__main__':

lib/Crypto/SelfTest/Math/test_Numbers.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -696,6 +696,34 @@ def test_hex(self):
696696
v1, = self.Integers(0x10)
697697
self.assertEqual(hex(v1), "0x10")
698698

699+
def test_mult_modulo_bytes(self):
700+
modmult = self.Integer._mult_modulo_bytes
701+
702+
res = modmult(4, 5, 19)
703+
self.assertEqual(res, b'\x01')
704+
705+
res = modmult(4 - 19, 5, 19)
706+
self.assertEqual(res, b'\x01')
707+
708+
res = modmult(4, 5 - 19, 19)
709+
self.assertEqual(res, b'\x01')
710+
711+
res = modmult(4 + 19, 5, 19)
712+
self.assertEqual(res, b'\x01')
713+
714+
res = modmult(4, 5 + 19, 19)
715+
self.assertEqual(res, b'\x01')
716+
717+
modulus = 2**512 - 1 # 64 bytes
718+
t1 = 13**100
719+
t2 = 17**100
720+
expect = b"\xfa\xb2\x11\x87\xc3(y\x07\xf8\xf1n\xdepq\x0b\xca\xf3\xd3B,\xef\xf2\xfbf\xcc)\x8dZ*\x95\x98r\x96\xa8\xd5\xc3}\xe2q:\xa2'z\xf48\xde%\xef\t\x07\xbc\xc4[C\x8bUE2\x90\xef\x81\xaa:\x08"
721+
self.assertEqual(expect, modmult(t1, t2, modulus))
722+
723+
self.assertRaises(ZeroDivisionError, modmult, 4, 5, 0)
724+
self.assertRaises(ValueError, modmult, 4, 5, -1)
725+
self.assertRaises(ValueError, modmult, 4, 5, 4)
726+
699727

700728
class TestIntegerInt(TestIntegerBase):
701729

0 commit comments

Comments
 (0)