This note describes how to determine a secret constant value used in a vulnerable invite code generation system. The system uses PHP’s mt_rand()
function seeded with a value derived from the user’s email and the secret constant. The weakness allows us to reverse-engineer the constant.
1. Seed Value Calculation:
The seed value for mt_rand()
is calculated using the function:
function calculate_seed_value($email, $constant_value) {
$email_length = strlen($email);
$email_hex = hexdec(substr($email, 0, 8));
$seed_value = $email_length + $constant_value + $email_hex;
return $seed_value;
}
This means the seed ($seed_value
) is the sum of:
$email_length
: The length of the email address.$email_hex
: The hexadecimal value of the first 8 characters of the email address.$constant_value
: The secret constant we aim to find.
2. Reverse-Engineering the Constant:
We can rearrange the seed calculation formula to solve for the constant:
$constant_value = $seed_value - ($email_length + $email_hex);
To use this formula:
- We need a known
$seed_value
. This is obtained by decoding a known invite code (Base64 decoded output ofmt_rand()
) and then using a tool likephp_mt_seed
to determine the seed that produced that number. - We calculate
$email_length
and$email_hex
from a known email address used to generate the initial invite code.
3. Determining a Reasonable Range for the Constant:
The $constant_value
is not arbitrarily large. It’s constrained by the range of possible seed values. Because $seed_value
is a sum that includes the constant, the constant will likely be within a similar range as the seed values found using php_mt_seed
.
4. Narrowing Down the Constant Value:
- Obtain Seed Range: Use
php_mt_seed
to identify a range of possible seed values that could have produced the decoded invite code. - Calculate Email Values: Determine
$email_length
and$email_hex
for the email used to generate the known invite code. - Iterate and Test: Iterate through the range of possible seed values. For each seed value, calculate the corresponding
$constant_value
using the rearranged formula. Test this$constant_value
by generating a new seed using thecalculate_seed_value()
function with a different email address. Generate the invite code and check its validity against the system.
The correct $constant_value
will generate a valid invite code when tested against a different email address.
5. Conclusion:
By exploiting the predictable nature of mt_rand()
and the simple formula used to generate the seed, we can determine the secret constant value. This highlights the importance of using cryptographically secure random number generators and more complex seed generation methods in security-sensitive applications.