Kaspersky Password Manager: All your passwords are belong to us
Kaspersky Password Manager generated passwords using a weak PRNG seeded with the current time in seconds, making all generated passwords predictable and brute-forceable in minutes. An attacker who knows the approximate generation time could recover the password.
Published on donjon.ledger.com
The product has been updated and its newest versions aren’t affected by this issue.
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Context
Kaspersky Password Manager (KPM) is a password manager that stores passwords and documents in an encrypted vault protected by a master password. It is available for Windows, macOS, Android, iOS and the Web, and encrypted data is synchronised between devices, always protected by the master password.
One of the core features of any password manager is password generation: unlike humans, the tool is supposed to produce random, strong passwords. KPM has a built-in generator that creates passwords from a policy: password length, uppercase letters, lowercase letters, digits and a custom set of special characters. By default KPM generates 12-character passwords with an extended charset. The generator is meant to produce random, strong passwords, and this write-up is about how it was flawed and how the flaw was exploited. Passwords generated by the tool could be brute-forced in seconds. The issue was assigned CVE-2020-27020 and has since been patched on all versions of KPM.
Setup
The PRNG differed between the desktop and Web versions of Kaspersky Password Manager. The proof of concept was built and tested with Visual C++ 2017, because the floating point values in the source code do not have exactly the same values when compiled with Clang or gcc. The PoC was used to verify the flaw on Windows versions of Kaspersky Password Manager below 9.0.2 Patch F. The report was sent to Kaspersky through HackerOne on 15 June 2019.
Finding it
To explain why KPM's method was wrong, the author first describes a good method, using KeePass as the reference. KeePass implements password generation in the KeePassLib.Cryptography.PasswordGenerator namespace and offers three methods: charset-based, pattern-based and custom. The charset-based generator is the simplest. Its main loop is:
PwCharSet pcs = new PwCharSet(pwProfile.CharSet.ToString());
if(!PwGenerator.PrepareCharSet(pcs, pwProfile))
return PwgError.InvalidCharSet;
char[] v = new char[pwProfile.Length];
try
{
for(int i = 0; i < v.Length; ++i)
{
char ch = PwGenerator.GenerateCharacter(pcs, crsRandomSource);
if(ch == char.MinValue)
return PwgError.TooFewCharacters;
v[i] = ch;
if(pwProfile.NoRepeatingCharacters) pcs.Remove(ch);
}
...
}
GenerateCharacter is called for every character of the password, takes a charset and a random source, and returns a random character from the charset:
internal static char GenerateCharacter(PwCharSet pwCharSet,
CryptoRandomStream crsRandomSource)
{
uint cc = pwCharSet.Size;
if(cc == 0) return char.MinValue;
uint i = (uint)crsRandomSource.GetRandomUInt64(cc);
return pwCharSet[i];
}
GetRandomUInt64 is a uniform random number generator that outputs values between 0 and cc - 1:
internal ulong GetRandomUInt64(ulong uMaxExcl)
{
if(uMaxExcl == 0) { Debug.Assert(false); throw new ArgumentOutOfRangeException("uMaxExcl"); }
ulong uGen, uRem;
do
{
uGen = GetRandomUInt64();
uRem = uGen % uMaxExcl;
}
while((uGen - uRem) > (ulong.MaxValue - (uMaxExcl - 1UL)));
// This ensures that the last number of the block (i.e.
// (uGen - uRem) + (uMaxExcl - 1)) is generatable;
// for signed longs, overflow to negative number:
// while((uGen - uRem) + (uMaxExcl - 1) < 0);
return uRem;
}
The important property is that each character is generated independently from the others: every character is random, and knowing which character was generated before gives no information about the next one.
The loop in GetRandomUInt64 exists to avoid the modulo bias. If you pick a character from a 10-character charset with a generator that returns values from 0 to 31, the naive approach is:
const string charset = "0123456789";
return charset[GetRandom32() % 10];
With that code, "4" is returned when GetRandom32() returns 4, 14 or 24 (3 possible values), "5" when it returns 5, 15 or 25 (3 possible values), but "1" when it returns 1, 11, 21 and 31 (4 possible values). The distribution is shown below:
Digits 0 and 1 come out more often than the others. This is the modulo bias. The usual fix is to discard all numbers greater than or equal to 30, the biggest multiple of 10 below 32:
const string charset = "0123456789";
do {
uGen = GetRandom32();
} while (uGen >= 30);
return charset[uGen % 10];
This is what KeePass does, although its bias would be far less significant because GetRandomUInt64 generates values much larger than the size of the charset.
The random source itself matters. A good PRNG passes statistical tests such as Diehard or Dieharder. A cryptographically secure PRNG (CSPRNG) must also satisfy the next-bit test: given all the bits already generated, no polynomial-time method predicts the next bit with probability higher than 0.5. And if the whole state of the CSPRNG is compromised at any moment, there must be no way to retrieve the bits it returned previously. This matters for password generation: if one password is compromised and a non-CSPRNG generated it, an attacker could recover the other passwords generated by the same PRNG. Operating systems provide CSPRNGs: CryptGenRandom on Windows, /dev/random on UNIX-like systems. KeePass uses two PRNGs, based on Salsa20 and ChaCha20, plus a legacy one based on a variant of ARCFour.
KPM's generator is much more complex than KeePass's. It first picks two random floats r1 and r2 between 0 and 1, and multiplies them with the length of the charset to pick a value in the charset table:
charset = ... # character set to use
r1 = random.random()
r2 = random.random()
pos = r1 * r2 * len(charset)
return charset[pos]
The distribution of r1 x r2 is -ln(a), and it is not uniform: lower positions occur more often than values near 1. The author notes that this method is puzzling, but it seems to be exactly what KPM wanted to implement.
The charset is not simply ordered like "abcdefghij...". For the first three characters it is fully ordered, almost. For the following characters KPM relies on letter frequency: it assumes the least frequent letters in some language should appear more often in the generated password. The supposed frequency of appearance of each letter, as used in KPM, is shown in the graph below:
The charset is then ordered according to the inverse frequency of appearance: q, x, z, w ... n, a, e. Since lower values are more likely under the distribution, characters like "q" and "x" are much more likely to appear in generated passwords.
If the statistics were applied independently for every character, several "q", "x" or "z" would often appear. But generated characters are taken into account in the computation of the frequencies. If a "z" is generated, the probability of "z" in the frequency table is strongly increased, so "z" moves to the end of the table and has much less chance of being picked again.
These changes affect other letters too: after "z" is picked, the probability of "a", "e", "m", "q", "s" and "x" also increases, while "h" decreases. After "h" is picked, its probability increases a lot.
The author's hypothesis is that this method was implemented to trick standard password cracking tools. Hashcat and John the Ripper try probable passwords first, such as passwords generated by humans, because "e" and "a" are more likely than "x" or "j", and bigrams like "th" and "he" are more common than "qx" or "zr". Techniques such as the Markov generator assume a hidden Markov model in human password generation and can break this method directly. So KPM passwords sit far down the candidate list of these tools, and an attacker cracking a list of KPM-generated passwords would wait a long time before finding the first one. That part is clever.
But if an attacker knows a password was generated by KPM, he can adapt his tool to the model. The bias introduced to defeat password crackers can be used to generate the most probable KPM passwords and test them first, for example with a Markov generator such as the one provided by John the Ripper (the report notes this method was not tested). The generation algorithm in itself is not that bad: it resists standard tools. But against an attacker who knows the person uses KPM, the password is much easier to break than a fully random one. The recommendation is to generate random passwords long enough to resist such tools.
Exploitation
The two random values r1 and r2 come directly from the KPM PRNG, which outputs uniform floats between 0 and 1, 1 excluded. The PRNG differs between the Desktop and Web versions.
The Web version used Math.random(), which is not suitable for cryptographic material, as the Mozilla documentation states. The underlying PRNG in Chrome, Firefox and Safari for Math.random() is xorshift128+, which is fast but not suitable for cryptographic use. The security consequences in KPM were not studied, but Kaspersky was advised to replace it with window.crypto.getRandomValues().
The desktop version used the mt19937 Mersenne Twister provided by Boost. It is a very good and widely used PRNG, uniformly distributed, with a very long period, and fast. But it is not a CSPRNG: knowing 624 of its outputs allows an attacker to retrieve its full state and predict all values it will generate, plus all values it has already generated, using the Berlekamp-Massey or Reeds-Sloane algorithms. Off-the-shelf tools such as randcrack break Python's random module, which uses a very similar implementation of MT 19937, and only very minor adaptations should be needed for the Boost implementation.
In practice, exploiting this in KPM is hard. Passwords are short, 12 characters by default, so retrieving 624 password characters requires grabbing 52 passwords. The raw output value is not known: the output is the position in the charset of each letter, so more values could be necessary. And that position is the product of two values produced by the PRNG. The author does not see a straightforward way to attack the PRNG in the context of KPM.
The real problem is the seeding. The code responsible for initialisation should look like:
mt19937::result_type seed = ...;
auto mtrand = std::bind(std::uniform_real_distribution<float>(0,1), mt19937(seed));
The password generation function is called like this:
std::string pwlib::generatePassword(pwdlib::Policy policy, int seed)
{
if (seed == 0) {
FILETIME ft;
GetSystemTimeAsFileTime(&ft);
seed = ft.dwLowDateTime + ft.dwHighDateTime;
}
auto mtrand = std::bind(std::uniform_real_distribution<float>(0,1), mt19937(seed));
return generateRandomPassword(policy, mtrand);
}
Two things stand out. The seed is just 32 bits, so it can be brute-forced easily. And a PRNG instance is created every time a password is generated, so KPM can generate at most 2^32 passwords for a given charset.
GetSystemTimeAsFileTime is used only when no seed is provided. When a user requests a new password, the call is:
std::string pwlib::generatePassword(pwdlib::Policy policy)
{
return generatePassword(policy, time(0));
}
So the seed is the current system time in seconds. Every instance of Kaspersky Password Manager in the world generates the exact same password at a given second. This would be obvious if every click on the Generate button produced the same password, but password generation is animated: dozens of random characters are displayed while the real password has already been computed.
The animation takes more than one second, so it is not possible to click Generate several times within a second. That is why the weakness had not been discovered before.
The consequences are bad: every password could be brute-forced. There are 315,619,200 seconds between 2010 and 2021, so KPM could generate at most 315,619,200 passwords for a given charset, and brute-forcing them takes a few minutes. Websites and forums often display the creation time of accounts, so an attacker who knows the creation date of an account can try a small range of passwords (about 100) and gain access. Passwords from leaked databases containing hashed passwords, passwords for encrypted archives, TrueCrypt/VeraCrypt volumes and similar can also be recovered easily if they were generated with Kaspersky Password Manager.
Step 1: build the proof of concept
The author wrote a proof of concept to make sure nothing was missed. It generates a list of 1000 possible passwords from the current time. The file pwlib.cpp must be compiled with Visual C++, because the floating point values in the source code do not have exactly the same values when compiled with Clang or gcc. The author used Visual C++ 2017. In a Visual C++ 32-bit command prompt:
cmake -Bbuild -H. msbuild build\pwbrute.vcxproj
Step 2: generate the candidate list
Run the compiled executable to create a list of 1000 passwords:
Debug\pwbrute.exe > pass.txt
Step 3: create a password with the matching policy
Create a password in Kaspersky Password Manager with the following policy:
- Lowercase only
- 12 chars
Step 4: verify
Check that the generated password is present in pass.txt.
The PoC is not completely functional, but it allowed the author to discover a bug in the password generation process, in the function that computes the probability of appearance of a letter given the previously generated characters. The pseudo code for getContextProbabilities is:
const float *getContextProbabilities(const std::string &password) {
std::string lowercasePassword;
// Convert to lowercase, keep only lowercase
for (char c : password) {
if (islower(c)) {
lowercasePassword += c;
} else if (isupper(c)) {
lowercasePassword += char(c - 'A' + 'a');
}
}
...
int n = 0;
for (int i = lowercasePassword.length() - 1; i >= 0; i--) {
int index = password[i] - 'a'; // FIXME: replace with lowercasePassword
The password being built is converted to lowercase and non-letters are removed. Then the loop iterates over password instead of the lowercasePassword just created. This computes a wrong index, the position of a letter in the alphabet, which is used to retrieve an element of an array, causing an out-of-bounds read. The frequency of appearances is then computed from uninitialised or arbitrary data in some cases. Although the algorithm is wrong, it actually makes the passwords more difficult to brute-force in some cases. The PoC generates candidates for lowercase passwords only, so the index is always correctly computed; otherwise the PoC would need to be adapted.
Root cause
The major flaw is that the Mersenne Twister was seeded with the current time in seconds. A 32-bit seed can be brute-forced, and because a new PRNG instance is created for every password, the number of possible passwords for a given charset is bounded by the number of seconds in the relevant period. The Mersenne Twister itself is not a CSPRNG, but the seeding is what makes the attack practical. The Web version used Math.random(), based on xorshift128+, which is not suitable for cryptographic material; the security consequences in KPM were not studied.
Impact
Every password generated by vulnerable versions of KPM could be brute-forced. For a given charset, the number of candidates is bounded by the number of seconds in the period of interest: 315,619,200 between 2010 and 2021, which takes a few minutes to brute-force. If the approximate generation time is known, the range shrinks to about 100 candidates. Account creation dates displayed by websites and forums, leaked databases of hashed passwords, encrypted archives and TrueCrypt/VeraCrypt volumes are all exposed if the passwords came from KPM. The out-of-bounds read makes passwords more difficult to brute-force in some cases.
Fix
Kaspersky assigned CVE-2020-27020 and published a security advisory. All versions prior to these are affected:
| Product | Fixed version |
|---|---|
| Kaspersky Password Manager for Windows | 9.0.2 Patch F |
| Kaspersky Password Manager for Android | 9.2.14.872 |
| Kaspersky Password Manager for iOS | [redacted] |
On Windows, the Mersenne Twister was replaced with BCryptGenRandom:
float RandomFloat(BCRYPT_ALG_HANDLE *hAlgorithm) {
uint32_t l;
BCryptGenRandom(*hAlgorithm, (uint8_t *)&l, sizeof(l), 0);
return (float)l * (1.0f / 0x100000000);
}
The return value of this function was not checked in the beta versions provided by Kaspersky, but the author guesses this has been fixed. In the Web version, Math.random() was replaced with window.crypto.getRandomValues(). Android and iOS were also patched, but the author did not look at those fixes.
The timeline is worth noting. The report and PoC were sent on 15 June 2019; Kaspersky acknowledged receipt on 17 June and confirmed the vulnerability on 25 June. On 4 October 2019 Kaspersky sent a private Windows build for verification and said a solution for previously generated passwords would roll out before the end of the year. On 8 October the author confirmed the fixes but reported a new small defect in the fix. Windows 9.0.2 Patch D was released on 10 October 2019, fixing the vulnerabilities but not the reported defect, and the Web version was updated. Android 9.2.14.872 was released on 9 October 2019 and iOS [redacted] on 10 October 2019. Windows 9.0.2 Patch F, released on 10 December 2019, closed the defect in Patch D. On 9 April 2020 Kaspersky said a patch to handle previously generated passwords would come in October. Kaspersky Password Manager 9.0.2 Patch M was released on 13 October 2020 with a notification asking users to re-generate some passwords, and the same notification was planned for mobile versions during the first quarter of 2021; CVE-2020-27020 was reserved. On 28 December 2020 Kaspersky agreed the report could be disclosed after the CVE was published. The security advisory was published on 27 April 2021 and the CVE information on 14 May 2021.
Variants to test
- Time-seeded PRNGs in other generators. Look for password or token generators that seed a PRNG with
time(0),GetSystemTimeAsFileTimeor similar. A positive result is that the same output is produced at the same second across instances, or that a small time window yields the target value. - Non-CSPRNGs in security-sensitive code. Check for Mersenne Twister,
Math.random(), xorshift or languagerandommodules used for passwords, keys or session identifiers. A positive result is that 624 consecutive outputs (for MT 19937) allow state recovery and prediction of past and future values. - Modulo bias. Look for
random() % nwithout rejection sampling. A positive result is a measurable skew in the distribution of generated characters or values. - Frequency-based generation. If a generator orders its charset by letter frequency, try a Markov generator or a model of the generator to rank candidates. A positive result is that the target password appears early in the ranked list.
- Out-of-bounds reads in probability tables. Look for loops that index an array with a value derived from the wrong string, as in
getContextProbabilities. A positive result is a crash, sanitizer report or observable change in generated output when non-letter characters are present. - Animation as a rate limiter. If a UI animates generation, check whether the underlying value is computed before the animation finishes. A positive result is that the real value is fixed at click time and can be predicted from the click timestamp.
What happened, in plain words
Kaspersky Password Manager (KPM) is a program that keeps all your passwords and documents in one locked box, called a vault. You open the box with a single password you have to remember, the master password. The program runs on Windows, macOS, Android, iOS and in a web browser, and it copies your encrypted data between your devices so that every device shows the same vault, always protected by that one master password.
One of the main jobs of any password manager is to invent new passwords for you. Humans are bad at this: we pick names, dates and words. A password manager is supposed to pick something random and strong instead. KPM had a built-in generator that made passwords according to a policy: how long the password is, whether it uses uppercase letters, lowercase letters, digits and a custom set of special characters. By default it made 12-character passwords using an extended set of characters.
Generated passwords are the keys to your accounts elsewhere, so the generator matters. This write-up is about how that generator was flawed, and how the flaw could be exploited. Passwords made by the tool could be brute-forced in seconds. The problem was given the identifier CVE-2020-27020 and has since been fixed on all versions of KPM.
A few words you will meet constantly below. A password manager is software that stores many passwords behind one master password. Encryption is scrambling data with a key so that only someone with the key can read it. A charset is simply the set of characters a password may be built from, for example the ten digits 0123456789 or all lowercase letters. To brute-force means to try every possibility one after another until the right one is found; it is like trying every key on a keyring until the door opens. A PRNG (pseudo-random number generator) is a piece of software that produces sequences of numbers that look random. A seed is the starting value you give a PRNG; the same seed always produces the same sequence, like the same starting position on a board game leading to the same moves. A CVE is a public catalogue number for a known security flaw, so people can refer to it unambiguously.
Setup
The PRNG differed between the desktop and Web versions of Kaspersky Password Manager. The proof of concept, a small program written to demonstrate the attack, was built and tested with Visual C++ 2017. The reason for that specific compiler is that the floating point values in the source code do not have exactly the same values when compiled with Clang or gcc, so a different compiler could produce a program that does not reproduce the same passwords. The proof of concept was used to verify the flaw on Windows versions of Kaspersky Password Manager below 9.0.2 Patch F. The report was sent to Kaspersky through HackerOne, a platform where security researchers report bugs to companies, on 15 June 2019.
Finding it
To explain why KPM's method was wrong, the author first describes a good method, using KeePass as the reference. KeePass is an open source password manager, meaning its source code is public and anyone can read how it works, which makes it a convenient example of doing things properly. KeePass implements password generation in the KeePassLib.Cryptography.PasswordGenerator namespace, which is just a named folder-like grouping of code. It offers three methods: charset-based, pattern-based and custom. The charset-based generator is the simplest: it builds a password one character at a time, each character drawn from a set. Its main loop is:
PwCharSet pcs = new PwCharSet(pwProfile.CharSet.ToString());
if(!PwGenerator.PrepareCharSet(pcs, pwProfile))
return PwgError.InvalidCharSet;
char[] v = new char[pwProfile.Length];
try
{
for(int i = 0; i < v.Length; ++i)
{
char ch = PwGenerator.GenerateCharacter(pcs, crsRandomSource);
if(ch == char.MinValue)
return PwgError.TooFewCharacters;
v[i] = ch;
if(pwProfile.NoRepeatingCharacters) pcs.Remove(ch);
}
...
}
Line by line: the first line builds the set of allowed characters (pcs) from the user's settings. The next lines check that the set is usable and stop with an error if it is not. char[] v = new char[pwProfile.Length]; creates an empty array, a numbered list of slots, one slot per character of the desired password length. The for loop then walks through every slot from the first to the last. Inside, GenerateCharacter picks one random character from the set and stores it in the current slot. If the set has run out of characters, the code stops with an error. Finally, if the user asked for no repeated characters, the chosen character is removed from the set so it cannot be picked again. The point of this loop is that each slot is filled by an independent random draw.
GenerateCharacter is called for every character of the password, takes a charset and a random source, and returns a random character from the charset:
internal static char GenerateCharacter(PwCharSet pwCharSet,
CryptoRandomStream crsRandomSource)
{
uint cc = pwCharSet.Size;
if(cc == 0) return char.MinValue;
uint i = (uint)crsRandomSource.GetRandomUInt64(cc);
return pwCharSet[i];
}
Line by line: cc is the number of characters in the set. If the set is empty, the function returns a special "nothing" value so the caller knows it failed. Otherwise it asks the random source for a number between 0 and cc - 1, stores it in i, and returns the character sitting at that position in the set. In everyday terms, it is like rolling a die with exactly as many faces as there are characters, and taking the character that comes up.
GetRandomUInt64 is a uniform random number generator that outputs values between 0 and cc - 1:
internal ulong GetRandomUInt64(ulong uMaxExcl)
{
if(uMaxExcl == 0) { Debug.Assert(false); throw new ArgumentOutOfRangeException("uMaxExcl"); }
ulong uGen, uRem;
do
{
uGen = GetRandomUInt64();
uRem = uGen % uMaxExcl;
}
while((uGen - uRem) > (ulong.MaxValue - (uMaxExcl - 1UL)));
// This ensures that the last number of the block (i.e.
// (uGen - uRem) + (uMaxExcl - 1)) is generatable;
// for signed longs, overflow to negative number:
// while((uGen - uRem) + (uMaxExcl - 1) < 0);
return uRem;
}
Line by line: the function refuses to run if asked for a range of zero. It then repeatedly draws a raw random number uGen and computes the remainder of dividing it by the range size, uRem. The while condition throws away draws that fall in the last, incomplete block of the range, so that every possible result is equally likely. The comments explain that this keeps the final number of each block reachable. The function returns the remainder, which is guaranteed to be between 0 and the range size minus one. The important property is that each character is generated independently from the others: every character is random, and knowing which character was generated before gives no information about the next one. Think of drawing a card, putting it back in the deck and shuffling before every draw.
The loop in GetRandomUInt64 exists to avoid the modulo bias. The word modulo means the remainder after division: 17 modulo 10 is 7, because 17 is 10 plus 7. If you pick a character from a 10-character charset with a generator that returns values from 0 to 31, the naive approach is:
const string charset = "0123456789";
return charset[GetRandom32() % 10];
Line by line: charset is the ten digits. GetRandom32() produces a number from 0 to 31. The % 10 keeps only the remainder after dividing by ten, so 0 to 9, and that number is used as a position in the string to pick a digit. With that code, "4" is returned when GetRandom32() returns 4, 14 or 24 (3 possible values), "5" when it returns 5, 15 or 25 (3 possible values), but "1" when it returns 1, 11, 21 and 31 (4 possible values). The distribution is shown below:
Digits 0 and 1 come out more often than the others. This is the modulo bias: the leftover numbers at the top of the range all pile onto the first few results. It is like dealing cards from a deck of 32 into 10 piles; the first two piles get one extra card. The usual fix is to discard all numbers greater than or equal to 30, the biggest multiple of 10 below 32:
const string charset = "0123456789";
do {
uGen = GetRandom32();
} while (uGen >= 30);
return charset[uGen % 10];
Line by line: draw a number and keep drawing while it is 30 or 31, throwing those two away. Once you have a number from 0 to 29, take its remainder modulo 10 and use it to pick a digit. Now every digit has exactly three ways of being chosen, so the choice is fair. This is what KeePass does, although its bias would be far less significant because GetRandomUInt64 generates values much larger than the size of the charset, so the leftover block is a tiny fraction of the whole range.
The random source itself matters. A good PRNG passes statistical tests such as Diehard or Dieharder, which check that the numbers look random in various ways. A cryptographically secure PRNG (CSPRNG) must also satisfy the next-bit test: given all the bits already generated, no polynomial-time method predicts the next bit with probability higher than 0.5. "Polynomial-time" means fast enough to be practical; the point is that no realistic amount of computing can guess the next bit better than a coin flip. And if the whole state of the CSPRNG is compromised at any moment, there must be no way to retrieve the bits it returned previously. This matters for password generation: if one password is compromised and a non-CSPRNG generated it, an attacker could recover the other passwords generated by the same PRNG. Operating systems provide CSPRNGs: CryptGenRandom on Windows, /dev/random on UNIX-like systems. KeePass uses two PRNGs, based on Salsa20 and ChaCha20, plus a legacy one based on a variant of ARCFour.
KPM's generator is much more complex than KeePass's. It first picks two random floats r1 and r2 between 0 and 1, and multiplies them with the length of the charset to pick a value in the charset table:
charset = ... # character set to use
r1 = random.random()
r2 = random.random()
pos = r1 * r2 * len(charset)
return charset[pos]
Line by line: charset is the set of allowed characters. random.random() produces a decimal number between 0 and 1, and this is done twice, giving r1 and r2. Multiplying them together gives a number between 0 and 1 that is usually small, because two fractions below one multiplied together get smaller. Multiplying by the number of characters in the set turns that into a position in the set, and the character at that position is returned. The distribution of r1 x r2 is -ln(a), and it is not uniform: lower positions occur more often than values near 1. The author notes that this method is puzzling, but it seems to be exactly what KPM wanted to implement.
The charset is not simply ordered like "abcdefghij...". For the first three characters it is fully ordered, almost. For the following characters KPM relies on letter frequency: it assumes the least frequent letters in some language should appear more often in the generated password. The supposed frequency of appearance of each letter, as used in KPM, is shown in the graph below:
The charset is then ordered according to the inverse frequency of appearance: q, x, z, w ... n, a, e. Since lower values are more likely under the distribution, characters like "q" and "x" are much more likely to appear in generated passwords. In other words, the rarest letters are placed at the front of the table, where the generator looks most often.
If the statistics were applied independently for every character, several "q", "x" or "z" would often appear. But generated characters are taken into account in the computation of the frequencies. If a "z" is generated, the probability of "z" in the frequency table is strongly increased, so "z" moves to the end of the table and has much less chance of being picked again.
These changes affect other letters too: after "z" is picked, the probability of "a", "e", "m", "q", "s" and "x" also increases, while "h" decreases. After "h" is picked, its probability increases a lot. The table is being reshuffled after every character, like a card sharp who reorders the deck based on the cards already dealt.
The author's hypothesis is that this method was implemented to trick standard password cracking tools. Hashcat and John the Ripper are programs that guess passwords at high speed. They try probable passwords first, such as passwords generated by humans, because "e" and "a" are more likely than "x" or "j", and bigrams like "th" and "he" are more common than "qx" or "zr". A bigram is simply a pair of adjacent letters. Techniques such as the Markov generator assume a hidden Markov model in human password generation and can break this method directly. A Markov model here means a statistical model of which letter tends to follow which, learned from real passwords. So KPM passwords sit far down the candidate list of these tools, and an attacker cracking a list of KPM-generated passwords would wait a long time before finding the first one. That part is clever.
But if an attacker knows a password was generated by KPM, he can adapt his tool to the model. The bias introduced to defeat password crackers can be used to generate the most probable KPM passwords and test them first, for example with a Markov generator such as the one provided by John the Ripper (the report notes this method was not tested). The generation algorithm in itself is not that bad: it resists standard tools. But against an attacker who knows the person uses KPM, the password is much easier to break than a fully random one. The recommendation is to generate random passwords long enough to resist such tools.
Exploitation
The two random values r1 and r2 come directly from the KPM PRNG, which outputs uniform floats between 0 and 1, 1 excluded. The PRNG differs between the Desktop and Web versions.
The Web version used Math.random(), which is not suitable for cryptographic material, as the Mozilla documentation states. Math.random() is the built-in random function of JavaScript, the language of web pages; it is designed to be fast and convenient, not secret. The underlying PRNG in Chrome, Firefox and Safari for Math.random() is xorshift128+, which is fast but not suitable for cryptographic use. The security consequences in KPM were not studied, but Kaspersky was advised to replace it with window.crypto.getRandomValues(), the browser function meant for security-sensitive randomness.
The desktop version used the mt19937 Mersenne Twister provided by Boost. Boost is a well-known collection of C++ libraries. The Mersenne Twister is a very good and widely used PRNG, uniformly distributed, with a very long period, and fast. Period means how many numbers it produces before the sequence starts repeating. But it is not a CSPRNG: knowing 624 of its outputs allows an attacker to retrieve its full state and predict all values it will generate, plus all values it has already generated, using the Berlekamp-Massey or Reeds-Sloane algorithms. Those are mathematical procedures that reconstruct the internal state of the generator from its outputs. Off-the-shelf tools such as randcrack break Python's random module, which uses a very similar implementation of MT 19937, and only very minor adaptations should be needed for the Boost implementation.
In practice, exploiting this in KPM is hard. Passwords are short, 12 characters by default, so retrieving 624 password characters requires grabbing 52 passwords. The raw output value is not known: the output is the position in the charset of each letter, so more values could be necessary. And that position is the product of two values produced by the PRNG. The author does not see a straightforward way to attack the PRNG in the context of KPM.
The real problem is the seeding. The code responsible for initialisation should look like:
mt19937::result_type seed = ...;
auto mtrand = std::bind(std::uniform_real_distribution<float>(0,1), mt19937(seed));
Line by line: the first line declares a variable seed of the type the Mersenne Twister expects, with the actual value left out. The second line creates a random number generator mtrand by taking an mt19937 generator started with that seed and binding it to a distribution that turns its raw numbers into decimals between 0 and 1. The seed is the starting point of the whole sequence, so whoever knows it can reproduce every number the generator will produce.
The password generation function is called like this:
std::string pwlib::generatePassword(pwdlib::Policy policy, int seed)
{
if (seed == 0) {
FILETIME ft;
GetSystemTimeAsFileTime(&ft);
seed = ft.dwLowDateTime + ft.dwHighDateTime;
}
auto mtrand = std::bind(std::uniform_real_distribution<float>(0,1), mt19937(seed));
return generateRandomPassword(policy, mtrand);
}
Line by line: the function takes a policy (the settings for the password) and a seed. If the seed is zero, meaning none was supplied, it asks Windows for the current system time through GetSystemTimeAsFileTime, which fills a FILETIME structure with the time split into two parts, and adds those two parts together to make a seed. Then it builds the random generator from the seed and hands it to generateRandomPassword, which does the actual work. Two things stand out. The seed is just 32 bits, so it can be brute-forced easily. 32 bits means a number with about four billion possible values, which a computer can run through quickly. And a PRNG instance is created every time a password is generated, so KPM can generate at most 2^32 passwords for a given charset.
GetSystemTimeAsFileTime is used only when no seed is provided. When a user requests a new password, the call is:
std::string pwlib::generatePassword(pwdlib::Policy policy)
{
return generatePassword(policy, time(0));
}
Line by line: this simpler version of the function takes only the policy and immediately calls the version above, passing time(0) as the seed. time(0) is the current system time in seconds since 1 January 1970, a standard way to ask a computer what time it is. So the seed is the current system time in seconds. Every instance of Kaspersky Password Manager in the world generates the exact same password at a given second. This would be obvious if every click on the Generate button produced the same password, but password generation is animated: dozens of random characters are displayed while the real password has already been computed.
The animation takes more than one second, so it is not possible to click Generate several times within a second. That is why the weakness had not been discovered before: the animation accidentally acted as a brake on anyone trying to notice the repetition.
The consequences are bad: every password could be brute-forced. There are 315,619,200 seconds between 2010 and 2021, so KPM could generate at most 315,619,200 passwords for a given charset, and brute-forcing them takes a few minutes. Websites and forums often display the creation time of accounts, so an attacker who knows the creation date of an account can try a small range of passwords (about 100) and gain access. Passwords from leaked databases containing hashed passwords, passwords for encrypted archives, TrueCrypt/VeraCrypt volumes and similar can also be recovered easily if they were generated with Kaspersky Password Manager. A hash is a one-way fingerprint of data: you cannot turn it back into the password directly, but you can guess a password, hash the guess and compare. TrueCrypt and VeraCrypt are programs that create encrypted disk containers.
Step 1: build the proof of concept
The author wrote a proof of concept to make sure nothing was missed. It generates a list of 1000 possible passwords from the current time. The file pwlib.cpp must be compiled with Visual C++, because the floating point values in the source code do not have exactly the same values when compiled with Clang or gcc. The author used Visual C++ 2017. In a Visual C++ 32-bit command prompt:
cmake -Bbuild -H. msbuild build\pwbrute.vcxproj
Line by line: cmake -Bbuild -H. asks CMake, a tool that prepares a project for building, to read the project description in the current folder (-H.) and put the generated build files in a folder called build (-Bbuild). msbuild build\pwbrute.vcxproj then runs Microsoft's build tool on the project file inside that folder, producing the executable program. The step is needed because the proof of concept is source code, not a ready-to-run program.
Step 2: generate the candidate list
Run the compiled executable to create a list of 1000 passwords:
Debug\pwbrute.exe > pass.txt
Line by line: Debug\pwbrute.exe is the compiled program. The > symbol redirects its output into a file called pass.txt instead of showing it on screen. The result is a text file holding the 1000 candidate passwords the program computed from the current time.
Step 3: create a password with the matching policy
Create a password in Kaspersky Password Manager with the following policy:
- Lowercase only
- 12 chars
The policy has to match the one the proof of concept assumed, otherwise the candidate list will not contain the right password.
Step 4: verify
Check that the generated password is present in pass.txt. If it is, the generated password is among the candidates derived from the clock.
The PoC is not completely functional, but it allowed the author to discover a bug in the password generation process, in the function that computes the probability of appearance of a letter given the previously generated characters. The pseudo code for getContextProbabilities is:
const float *getContextProbabilities(const std::string &password) {
std::string lowercasePassword;
// Convert to lowercase, keep only lowercase
for (char c : password) {
if (islower(c)) {
lowercasePassword += c;
} else if (isupper(c)) {
lowercasePassword += char(c - 'A' + 'a');
}
}
...
int n = 0;
for (int i = lowercasePassword.length() - 1; i >= 0; i--) {
int index = password[i] - 'a'; // FIXME: replace with lowercasePassword
Line by line: the function receives the password built so far and declares an empty string lowercasePassword. The first loop walks over every character c of the password. If c is already a lowercase letter, it is appended as is. If it is an uppercase letter, it is converted to lowercase by subtracting the difference between the codes of 'A' and 'a' and appended. Anything else, such as a digit or a symbol, is dropped. The second loop then walks backwards from the end of lowercasePassword. Inside, index is meant to be the position of the letter in the alphabet, computed by subtracting the code of 'a' from the character. But the code reads password[i] instead of lowercasePassword[i], and the FIXME comment says exactly that. The password being built is converted to lowercase and non-letters are removed. Then the loop iterates over password instead of the lowercasePassword just created. This computes a wrong index, the position of a letter in the alphabet, which is used to retrieve an element of an array, causing an out-of-bounds read. An out-of-bounds read means reading a slot of an array that lies outside its intended limits, so you get whatever happens to be in memory there. The frequency of appearances is then computed from uninitialised or arbitrary data in some cases. Although the algorithm is wrong, it actually makes the passwords more difficult to brute-force in some cases. The PoC generates candidates for lowercase passwords only, so the index is always correctly computed; otherwise the PoC would need to be adapted.
Root cause
The major flaw is that the Mersenne Twister was seeded with the current time in seconds. A 32-bit seed can be brute-forced, and because a new PRNG instance is created for every password, the number of possible passwords for a given charset is bounded by the number of seconds in the relevant period. The Mersenne Twister itself is not a CSPRNG, but the seeding is what makes the attack practical. The Web version used Math.random(), based on xorshift128+, which is not suitable for cryptographic material; the security consequences in KPM were not studied.
Impact
Every password generated by vulnerable versions of KPM could be brute-forced. For a given charset, the number of candidates is bounded by the number of seconds in the period of interest: 315,619,200 between 2010 and 2021, which takes a few minutes to brute-force. If the approximate generation time is known, the range shrinks to about 100 candidates. Account creation dates displayed by websites and forums, leaked databases of hashed passwords, encrypted archives and TrueCrypt/VeraCrypt volumes are all exposed if the passwords came from KPM. The out-of-bounds read makes passwords more difficult to brute-force in some cases.
Fix
Kaspersky assigned CVE-2020-27020 and published a security advisory. All versions prior to these are affected:
| Product | Fixed version |
|---|---|
| Kaspersky Password Manager for Windows | 9.0.2 Patch F |
| Kaspersky Password Manager for Android | 9.2.14.872 |
| Kaspersky Password Manager for iOS | [redacted] |
On Windows, the Mersenne Twister was replaced with BCryptGenRandom:
float RandomFloat(BCRYPT_ALG_HANDLE *hAlgorithm) {
uint32_t l;
BCryptGenRandom(*hAlgorithm, (uint8_t *)&l, sizeof(l), 0);
return (float)l * (1.0f / 0x100000000);
}
Line by line: the function takes a handle to a Windows cryptographic algorithm. It declares a 32-bit unsigned integer l. BCryptGenRandom fills that variable with random bytes from the operating system's secure generator. The last line turns the number into a decimal between 0 and 1 by multiplying it by one over 2^32, written in hexadecimal as 0x100000000. The return value of this function was not checked in the beta versions provided by Kaspersky, but the author guesses this has been fixed. In the Web version, Math.random() was replaced with window.crypto.getRandomValues(). Android and iOS were also patched, but the author did not look at those fixes.
The timeline is worth noting. The report and PoC were sent on 15 June 2019; Kaspersky acknowledged receipt on 17 June and confirmed the vulnerability on 25 June. On 4 October 2019 Kaspersky sent a private Windows build for verification and said a solution for previously generated passwords would roll out before the end of the year. On 8 October the author confirmed the fixes but reported a new small defect in the fix. Windows 9.0.2 Patch D was released on 10 October 2019, fixing the vulnerabilities but not the reported defect, and the Web version was updated. Android 9.2.14.872 was released on 9 October 2019 and iOS [redacted] on 10 October 2019. Windows 9.0.2 Patch F, released on 10 December 2019, closed the defect in Patch D. On 9 April 2020 Kaspersky said a patch to handle previously generated passwords would come in October. Kaspersky Password Manager 9.0.2 Patch M was released on 13 October 2020 with a notification asking users to re-generate some passwords, and the same notification was planned for mobile versions during the first quarter of 2021; CVE-2020-27020 was reserved. On 28 December 2020 Kaspersky agreed the report could be disclosed after the CVE was published. The security advisory was published on 27 April 2021 and the CVE information on 14 May 2021.
Variants to test
- Time-seeded PRNGs in other generators. Look for password or token generators that seed a PRNG with
time(0),GetSystemTimeAsFileTimeor similar. A positive result is that the same output is produced at the same second across instances, or that a small time window yields the target value. - Non-CSPRNGs in security-sensitive code. Check for Mersenne Twister,
Math.random(), xorshift or languagerandommodules used for passwords, keys or session identifiers. A positive result is that 624 consecutive outputs (for MT 19937) allow state recovery and prediction of past and future values. - Modulo bias. Look for
random() % nwithout rejection sampling. A positive result is a measurable skew in the distribution of generated characters or values. - Frequency-based generation. If a generator orders its charset by letter frequency, try a Markov generator or a model of the generator to rank candidates. A positive result is that the target password appears early in the ranked list.
- Out-of-bounds reads in probability tables. Look for loops that index an array with a value derived from the wrong string, as in
getContextProbabilities. A positive result is a crash, sanitizer report or observable change in generated output when non-letter characters are present. - Animation as a rate limiter. If a UI animates generation, check whether the underlying value is computed before the animation finishes. A positive result is that the real value is fixed at click time and can be predicted from the click timestamp.
Glossary
- Password manager: software that stores many passwords and documents in an encrypted vault opened by one master password.
- Vault: the encrypted container where a password manager keeps your data.
- Master password: the single password that unlocks the vault.
- Encryption: scrambling data with a key so only someone holding the key can read it.
- Charset: the set of characters a password may be built from.
- Policy: the settings that describe what a generated password should look like, such as length and which character types to use.
- Brute-force: trying every possible value in turn until the right one is found.
- PRNG: pseudo-random number generator, software that produces sequences of numbers that look random.
- Seed: the starting value of a PRNG; the same seed always produces the same sequence.
- CSPRNG: cryptographically secure pseudo-random number generator, a PRNG whose output cannot be predicted even if earlier output is known.
- Next-bit test: the requirement that, given all bits already produced, no practical method predicts the next bit better than a coin flip.
- Modulo: the remainder after division, for example 17 modulo 10 is 7.
- Modulo bias: a skew in random selection caused by using a remainder when the range does not divide evenly.
- Rejection sampling: discarding random values that fall outside a fair range so that every result is equally likely.
- Uniform distribution: every possible value is equally likely.
- Float: a number with a decimal part, such as 0.37.
- Bit: a single binary digit, 0 or 1; 32 bits give about four billion possible values.
- Mersenne Twister: a widely used PRNG, known as MT 19937, that is fast and has a long period but is not cryptographically secure.
- Period: how many numbers a PRNG produces before its sequence starts repeating.
- State: the internal numbers a PRNG keeps to decide its next output.
- xorshift128+: a fast PRNG used by browsers for
Math.random(), not suitable for security. - Markov model / Markov generator: a statistical model of which character tends to follow which, used to rank likely passwords.
- Bigram: a pair of adjacent letters, such as "th".
- Hash: a one-way fingerprint of data, used to check guesses without storing the original.
- Out-of-bounds read: reading a slot of an array outside its intended limits, returning whatever is in memory there.
- Proof of concept (PoC): a small program written to demonstrate that a flaw is real and exploitable.
- Compiler: a program that turns source code into a runnable program.
- Namespace: a named grouping of code, like a folder for functions.
- CVE: a public catalogue number for a known security flaw.
- HackerOne: a platform where security researchers report bugs to companies.
- Security advisory: a public notice from a vendor describing a flaw and its fix.
- TrueCrypt / VeraCrypt: programs that create encrypted disk containers.
- Rate limiter: a mechanism that slows down how often an action can be repeated.