← Posts

Diffie-Hellman Revisited: Small Subgroup Confinement

Cryptopals Set 8 | Problem 57

One of the pitfalls of rolling your own crypto can be generating your own parameters to be used in a tried and tested cryptographic algorithm. Take Diffe-Hellman[1] (DH), which has been in use for decades and has secured countless data. The obvious way to mess up DH params is to generate parameters that are too small and can be brute forced. The more subtle way to mess up is to generate parameters whose algebraic structure can be exploited to recover secret material efficiently.

Mathematical Foundations

In DH we have a couple of parameters that we need to select:

We then use these parameters to establish a shared secret between Alice and Bob using DH. Alice selects a secret a and Bob selects a secret b. Both these secrets are integers in the range [0, q-1][2]. Alice sends A = g^a mod p to Bob and Bob sends B = g^b mod p. Alice then computes B^a mod p = g^(ba) mod p and Bob computes A^b mod p = g^(ab) mod p, which are equivalent and constitute the shared secret. Note that p, g and q are publicly known. A and B should also be considered non-secret material.


  from random import randint

  class DH:
      def __init__(self, g: int, p: int, q: int):
          self.g = g
          self.p = p
          self.secret = randint(0, q-1)
      
      def public_key(self) -> int:
          return pow(self.g, self.secret, self.p)
      
      def shared_secret(self, other_public_key: int) -> int:
          return pow(other_public_key, self.secret, self.p)
  

If q is equivalent to p-1 then g can generate every element in the multiplicative group of integers mod p[3]. If q is less than p-1 then g generates a subgroup of the multiplicative group of integers mod p. This means that all elements of the subgroup are part of the multiplicative group, but the subgroup is strictly smaller. In fact, the subgroup will have exactly q elements.

As an example, suppose p = 7. This means our multiplicative group mod 7 is {1,2,3,4,5,6}[4]. We examine two generators, g = 3 and g = 2. In the case of g = 3 we have the following values that can be generated:


  3^1 mod 7 = 3
  3^2 mod 7 = 2
  3^3 mod 7 = 6
  3^4 mod 7 = 4
  3^5 mod 7 = 5
  3^6 mod 7 = 1
  

Once we hit 1 the sequence of values repeats. Note that q = 6 = p-1 so g = 3 generates the full multiplicative group mod 7. Let's take a look at g = 2:


  2^1 mod 7 = 2
  2^2 mod 7 = 4
  2^3 mod 7 = 1
  

In this case we have a subgroup {1,2,4} of size q = 3 generated by g = 2. If you want to experiment a bit with changing g and p to see how the generated groups change you can use the code below:


  from math import gcd

  def gen(g: int, p: int):
      if gcd(g, p) != 1:
          raise ValueError("g and p must be coprime")

      g %= p
      current_element = g
      group = {g}

      while current_element != 1:
          current_element = (current_element * g) % p
          group.add(current_element)
      
      print(f"Generated group = {group}")
      print(f"Group order = {len(group)}")
  

Attack Outline

Suppose that we have a protocol where we establish a shared secret with Bob using DH. Bob then uses the shared secret, let's call it k, as the key for generating a tag using the HMAC algorithm. He then sends us back the message m the HMAC was computed on and the tag t for that message. We can then use our shared secret to recompute the tag from the message. This allows us to establish that we have derived the same shared secret via DH without actually sending the secret over the wire.


  from hashlib import sha3_256
  from hmac import HMAC
  from math import ceil

  class Bob:
      def __init__(self, dh: DH):
          self.dh = dh
      
      def protocol(self, A: int) -> tuple[bytes, bytes]:
          k = self.dh.shared_secret(A)
          m = b"crazy flamboyant for the rap enjoyment"
          return mac(k, m)

  def mac(k: int, m: bytes) -> tuple[bytes, bytes]:
      k_bytes = _int_to_bytes(k)
      t = HMAC(k_bytes, m, sha3_256).digest()
      return (m, t)

  def _int_to_bytes(k: int) -> bytes:
      byte_size = ceil(k.bit_length() / 8)
      return k.to_bytes(byte_size, byteorder="big")
  

Recall that k = A^b mod p where A is the value we sent Bob in DH and b is Bob's secret value. It is possible in principle to recover b from (m, t) alone. All we need to do is select a trial value b', compute k' from it, and then use that to compute (m, t') and check if t == t'. If they are equal then we have recovered Bob's secret.


  # the runtime of this is O(n) where n = size of the group generated by A (mod p)
  def recover_partial_secret(A: int, p: int, m: bytes, t: bytes) -> int:
      b_candidate = 0
      k = pow(A, b_candidate, p)

      while mac(k, m) != (m, t):
          b_candidate += 1
          k = pow(A, b_candidate, p)
      
      return b_candidate
  

Usually this doesn't work because q is a very large number and b is in the range [0, q-1] so the computational complexity of brute forcing b is beyond modern hardware. But what if q was smaller? We control the value A that is exponentiated by b. What if we pick A such that it is in a small subgroup of order r that is small enough to brute force? While b is still in a large range, we note that A^b = A^(b mod r) mod p when A is an element of order r. This means we can recover a residue of b via brute force, b' = b mod q'. If we find enough residues in small subgroups we can, as we will later explain, efficiently combine these residues to find the value of b.

Finding Small Subgroups

To find a generator for a small subgroup we can use a randomized algorithm. We make a couple of assumptions to simplify our algorithm. The first is that p is prime (as is always the case in finite field DH). The second is that the order of the small subgroup is also prime[5]. With these assumptions, we can find a generator g for a subgroup mod p of order r as follows.


  from random import randint

  def generator_for_prime_order(r: int, p: int) -> int:
      quotient, remainder = divmod(p-1, r)
      
      if remainder != 0:
          raise ValueError("r must divide p-1 evenly")

      g = 1
      while g == 1:
          base = randint(2, p)
          g = pow(base, quotient, p)
      
      return g
  

We can sanity check this by using the above function to get a generator and then passing that into gen to verify that the generated group has the expected order. In the example below I chose a prime p = 213805068284015711499317585976785698439 where p-1 has many small prime factors, such as 2 and 11.


  In [1]: p = 213805068284015711499317585976785698439

  In [2]: generator_for_prime_order(2, p)
  Out[2]: 213805068284015711499317585976785698438

  In [3]: gen(213805068284015711499317585976785698438, p)
  Generated group = {1, 213805068284015711499317585976785698438}
  Group order = 2

  In [4]: generator_for_prime_order(11, p)
  Out[4]: 172688298635200804456358272893647959426

  In [5]: gen(172688298635200804456358272893647959426, p)
  Generated group = {
      1,
      114313924126624421023355314422864464407,
      42088317979469771369843435831493310509,
      158052057595742800888737621965230343596,
      4960179566542870140212017683612337426,
      163005579791176722571832134134208489267,
      178253737649802770985133790007018474291,
      48125637134144004543912107768856378339,
      158084267376638300263889684017296590058,
      172688298635200804456358272893647959426,
      29453341564736091253313551159700144875
  }
  Group order = 11
  

Constructing the Full Attack

We now have almost all the tools we need to launch a full secret key recovery attack. Let's use the following DH parameters -

I haven't picked these at random. In fact, I have carefully selected p such that p is prime and q = p-1 has many small prime factors.

Note that, for the parameters Bob uses, I have picked g = 11. This is a generator that does have order q.

  In [1]: from functools import reduce

  In [2]: from operator import mul

  In [3]: p = 213805068284015711499317585976785698439

  In [4]: q_factors = [2, 11, 41, 79, 97, 109, 127, 277, 349, 359, 389, 499, 653, 787, 821, 839, 937]

  In [5]: p-1 == reduce(mul, q_factors)
  Out[5]: True
  

Each of those prime factors is a small subgroup that we can force Bob into by sending him an A that is in the small subgroup when he runs protocol. We can find a suitable A by using generator_for_prime_order.


  def recover_residue(bob: Bob, r: int) -> int:
      p = bob.dh.p
      A = generator_for_prime_order(r, p)
      m, t = bob.protocol(A)
      partial = recover_partial_secret(A, p, m, t)
      return partial
  

We now know the value of Bob's secret mod r. We can sanity check this by computing Bob's actual secret mod r and comparing it against the residue we recover.


  In [1]: dh = DH(2, p, p-1)

  In [2]: bob = Bob(dh)

  In [3]: recover_residue(bob, 11)
  Out[3]: 9

  In [4]: bob.dh.secret % 11
  Out[4]: 9
  

Okay, that's great, but what do we do with all these residues that we have that are much smaller than the keyspace for Bob's actual secret? Allow me to introduce you to the Chinese Remainder Theorem (CRT). The gist of the CRT is that if you have a modulus N = m_1 * m_2 * ... * m_n, a value x in [0, N-1], congruences x mod m_i for each factor of N, and all moduli m_i are pairwise coprime, then you can use the congruences to recover x mod N. In our case N = q = p-1 and the factors of N are the orders of all the small subgroups. The congruences are all of the residues we have recovered in those small subgroups. The moduli are trivially pairwise coprime as the moduli are all prime.


  from dataclasses import dataclass

  @dataclass
  class Congruence:
      x: int
      m: int

  def crt(cs: list[Congruence]) -> int:
      if len(cs) == 1:
          return cs[0].x

      x, m = cs[0].x, cs[0].m

      for i in range(1, len(cs)):
          u, v, d = extended_gcd(m, cs[i].m)
          if d > 1:
              raise ValueError(f'{m} and {cs[i].m} are not coprime')

          x = u * m * cs[i].x + v * cs[i].m * x
          m = m * cs[i].m
          x = x % m

          if x < 0:
              x += m

      return x

  def extended_gcd(a: int, b: int) -> tuple[int, int, int]:
      u, d = 1, a
      if b == 0:
          return u, 0, d

      v1, v3 = 0, b

      while v3 != 0:
          q, t3 = d // v3, d % v3
          t1 = u - q*v1
          u, d, v1, v3 = v1, v3, t1, t3

      return u, (d - a * u) // b, d
  

We can now take all of our residues to perform a full key recovery.


  def dh_small_subgroup():
      p = 213805068284015711499317585976785698439
      g = 11
      q = p - 1

      dh = DH(g, p, q)
      bob = Bob(dh)

      rs = [
          2, 11, 41, 79, 97, 109, 127, 277, 349, 
          359, 389, 499, 653, 787, 821, 839, 937
      ]
      recovered = recover_key(bob, rs)

      print(f"Recovered = {recovered}")
      print(f"Matches Bob's actual key = {bob.dh.secret == recovered}")


  def recover_key(bob: Bob, rs: list[int]) -> int:
      congruences: list[Congruence] = []
      
      for r in rs:
          residue = recover_residue(bob, r)
          congruence = Congruence(x=residue, m=r)
          congruences.append(congruence)
      
      return crt(congruences)
  

  In [1] dh_small_subgroup()
  Recovered = 168822618882275023570782651995175611167
  Matches Bob's actual key = True
  

Extending the attack to work with the cryptopals parameters is trivial. Plug in the provided values for p, g and q when initializing DH in dh_small_subgroup. For rs, factor (p-1) / q into small non-repeating primes until the product of all of your factors is greater than or equal to q. One thing to note is that, in the cryptopals case, q != p-1. q is just a large factor of p-1 and the small subgroups that we use are not necessarily subgroups of the group that g generates! Most libraries do not do not check this.

Analysis

How much more efficient is this attack than brute force? On my computer, with an intel i9-9900k, it runs basically instantaneously. For our given parameters q is 128 bits, so brute forcing the secret key is comparable to brute forcing an AES-128 key. With our small subgroup attack, the worst case is that we have to check every possible value in each subgroup. Given that our subgroups are very small, this is trivial for a computer. The worst case would require sum(rs) = 6376 iterations. log2(6376) ~= 13, so we achieve a speedup of about 2^(128 - 13 = 115) in this particular case.

Note also that none of this requires us to have any way of directly accessing or knowing Bob's secret key. The only value we control that Bob does any computations on is our public key A, which is exactly the value that we can use to force Bob into a small subgroup. Bob could check whether the group generated by our public key is small, but most libraries and DH code do not do this. The better approach is to use published and standardized DH group params that have been selected specifically so as to not be vulnerable to this kind of attack.

If you absolutely must generate your own DH params (you shouldn't!) then to guard against this particular attack you should ensure that p-1 has very few small factors that can be used to recover key residues. ps that have this property are called "safe primes" and are of the form p = 2x + 1 where x is also a prime. Note that this means p-1 has two factors, 2 and x. If p is sufficiently large, this means that a small subgroup confinement attack can recover exactly one bit of information via the subgroup of order 2.

Appendix: Full Code


  from dataclasses import dataclass
  from hashlib import sha3_256
  from hmac import HMAC
  from math import ceil, gcd
  from random import randint


  class DH:
      def __init__(self, g: int, p: int, q: int):
          self.g = g
          self.p = p
          self.secret = randint(0, q-1)
      
      def public_key(self) -> int:
          return pow(self.g, self.secret, self.p)
      
      def shared_secret(self, other_public_key: int) -> int:
          return pow(other_public_key, self.secret, self.p)
      

  class Bob:
      def __init__(self, dh: DH):
          self.dh = dh
      
      def protocol(self, A: int) -> tuple[bytes, bytes]:
          k = self.dh.shared_secret(A)
          m = b"crazy flamboyant for the rap enjoyment"
          return mac(k, m)


  @dataclass
  class Congruence:
      x: int
      m: int


  def dh_small_subgroup():
      p = 213805068284015711499317585976785698439
      g = 11
      q = p - 1

      dh = DH(g, p, q)
      bob = Bob(dh)

      rs = [
          2, 11, 41, 79, 97, 109, 127, 277, 349, 
          359, 389, 499, 653, 787, 821, 839, 937
      ]
      recovered = recover_key(bob, rs)

      print(f"Recovered = {recovered}")
      print(f"Matches Bob's actual key = {bob.dh.secret == recovered}")


  def recover_key(bob: Bob, rs: list[int]) -> int:
      congruences: list[Congruence] = []
      
      for r in rs:
          residue = recover_residue(bob, r)
          congruence = Congruence(x=residue, m=r)
          congruences.append(congruence)
      
      return crt(congruences)


  def recover_residue(bob: Bob, r: int) -> int:
      p = bob.dh.p
      A = generator_for_prime_order(r, p)
      m, t = bob.protocol(A)
      partial = recover_partial_secret(A, p, m, t)
      return partial


  def recover_partial_secret(A: int, p: int, m: bytes, t: bytes) -> int:
      b_candidate = 0
      k = pow(A, b_candidate, p)

      while mac(k, m) != (m, t):
          b_candidate += 1
          k = pow(A, b_candidate, p)
      
      return b_candidate


  def mac(k: int, m: bytes) -> tuple[bytes, bytes]:
      k_bytes = _int_to_bytes(k)
      t = HMAC(k_bytes, m, sha3_256).digest()

      return (m, t)


  def gen(g: int, p: int):
      if gcd(g, p) != 1:
          raise ValueError("g and p must be coprime")

      g %= p
      current_element = g
      group = {g}

      while current_element != 1:
          current_element = (current_element * g) % p
          group.add(current_element)
      
      print(f"Generated group = {group}")
      print(f"Group order = {len(group)}")


  def generator_for_prime_order(r: int, p: int) -> int:
      quotient, remainder = divmod(p-1, r)
      
      if remainder != 0:
          raise ValueError("r must divide p-1 evenly")

      g = 1
      
      while g == 1:
          base = randint(2, p)
          g = pow(base, quotient, p)
      
      return g


  def crt(cs: list[Congruence]) -> int:
      if len(cs) == 1:
          return cs[0].x

      x, m = cs[0].x, cs[0].m

      for i in range(1, len(cs)):
          u, v, d = extended_gcd(m, cs[i].m)
          if d > 1:
              raise ValueError(f'{m} and {cs[i].m} are not coprime')

          x = u * m * cs[i].x + v * cs[i].m * x
          m = m * cs[i].m
          x = x % m

          if x < 0:
              x += m

      return x


  def extended_gcd(a: int, b: int) -> tuple[int, int, int]:
      u, d = 1, a
      if b == 0:
          return u, 0, d

      v1, v3 = 0, b

      while v3 != 0:
          q, t3 = d // v3, d % v3
          t1 = u - q*v1
          u, d, v1, v3 = v1, v3, t1, t3

      return u, (d - a * u) // b, d


  def _int_to_bytes(k: int) -> bytes:
      byte_size = ceil(k.bit_length() / 8)
      return k.to_bytes(byte_size, byteorder="big")


  if __name__ == "__main__":
      dh_small_subgroup()
  

  1. See wikipedia for a refresher on Diffie-Hellman. ↩︎

  2. Why are they in this range? Because the order of the group generated by g is q. If a were some value greater than q-1, then there is a' = a mod q such that g^a = g^a' mod p. ↩︎

  3. If a generator g has order q = p-1, we call g a primitive root modulo p. ↩︎

  4. Note that 0 is not part of this group as it is not coprime to p. ↩︎

  5. We could generalize the algorithm to also work with non-prime q, but it requires more checks and isn't central to the attack. ↩︎