Insecure Use of Cryptography
Using Strong Random Numbers
About insecure randomness
What is insecure randomness?
Random number generation is the process of generating a sequence of numbers or symbols that cannot be reasonably predicted better than by random chance. The ability to generate true random numbers is important in many fields, including cryptography, simulation, and gaming, where the results must be unpredictable and unbiased.
In computer science and cryptography, random number generation is used to generate cryptographic keys, secure passwords, and other security-related data. Pseudorandom number generators (PRNGs) are commonly used to generate random numbers in computer systems, but they are not truly random since their output is determined by an algorithm that uses a seed value to generate a sequence of numbers. True random number generators (TRNGs) use physical processes or natural sources of randomness, such as radioactive decay or atmospheric noise, to generate true random numbers.
The quality of random number generation is crucial in many applications, particularly in the field of cryptography. If the random numbers are predictable or biased, they can be used to compromise the security of the system. Therefore, it is important to use reliable and secure random number generators in security-critical applications.
In summary, random number generation is the process of generating a sequence of numbers or symbols that cannot be reasonably predicted better than by random chance. True random number generators are preferable for security-critical applications to ensure that the output is unbiased and unpredictable.
Check out this video for a high-level explanation:
What is the impact of insecure randomness?
Insecure randomness in security systems has significant impacts on the security and privacy of data. Here are some of the potential impacts:
- Weak cryptography: Insecure randomness can result in the use of weak cryptographic keys or other security parameters, which can be exploited by attackers to gain unauthorized access to sensitive data. This can result in data breaches, where sensitive data is stolen or leaked.
- Malicious attacks: Attackers can use insecure randomness to launch various types of attacks, such as brute-force attacks or other guessing attacks, which can be used to break weak or outdated security systems.
- Regulatory compliance issues: Insecure randomness can result in non-compliance with various security standards and regulations, which can result in financial penalties or other legal consequences.
How to prevent insecure randomness?
Several measures can prevent insecure randomness, including:
- Use reliable and secure random number generators: Use reliable and secure random number generators that have been widely tested and validated by security experts. True random number generators (TRNGs) are preferable for security-critical applications to ensure that the output is unbiased and unpredictable.
- Use appropriate cryptographic keys and security parameters: Use appropriate cryptographic keys and security parameters to ensure that the security system is strong enough to resist attacks. The strength of the cryptographic keys and security parameters should be based on the level of security required by the system.
- Regularly update software and systems: Regularly update software and systems to ensure that the latest security patches are applied and known vulnerabilities related to insecure randomness are addressed.
- Regularly review and update security policies and procedures: Regularly review and update security policies and procedures to ensure that they remain up-to-date with the latest best practices and standards.
References
Taxonomies
- OWASP Top 10 - A02 Cryptographic Failures
- CWE-338: Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG)
- CWE-329: Not Using a Random IV with CBC Mode
- CWE-330: Use of Insufficiently Random Values
- CWE-331: Insufficient Entropy
- CWE-335: Incorrect Usage of Seeds in Pseudo-Random Number Generator(PRNG)
- CWE-336: Same Seed in Pseudo-Random Number Generator (PRNG)
- CWE-337: Predictable Seed in Pseudo-Random Number Generator (PRNG)
Explanation & Prevention
- OWASP: Insecure Randomness
- OWASP: Cryptographic Storage Cheat Sheet
- OWASP: Testing for Weak Encryption
Related CVEs
Training
Option A: Use A Strong Random Number Generator
The use of a predictable random values can lead to vulnerabilities when used in certain security critical contexts.
References:
- OWASP: Insecure Randomness
- CWE-330: Use of Insufficiently Random Values
- CWE-338: Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG)
- CWE-331: Insufficient Entropy
Go through the issues that GuardRails identified in the PR/MR.
Identify the following pattern:
var rnd = new Random();
byte[] buffer = new byte[16];
rnd.GetBytes(buffer);
return BitConverter.ToString(buffer);And replace it with:
using System.Security.Cryptography;
var rnd = RandomNumberGenerator.Create();Test it, ship it 🚢 and relax 🌴
Fixing Insecure Hashes
About Insecure Hashes
What are insecure hashes?
Insecure hashes are cryptographic hash functions that are vulnerable to attacks that can compromise the integrity and authenticity of data. Cryptographic hashes are widely used in security systems to ensure the integrity of data, such as passwords or digital signatures, by generating a fixed-length output that represents the original data.
Insecure hashes can be exploited by attackers to manipulate the original data without being detected, resulting in significant security vulnerabilities.
Examples of insecure hashes include the Message Digest 5 (MD5) and Secure Hash Algorithm 1 (SHA-1), which are vulnerable to collision attacks. A collision attack is an attack where an attacker can generate two different pieces of data that have the same hash value, which can be used to substitute one piece of data for another, without being detected.
Check out this video for a high-level explanation:
What is the impact of insecure hashes?
Insecure hashes in security systems have significant impacts on the security and privacy of data. Here are some of the potential impacts:
- Data breaches: Insecure hashes can result in vulnerabilities that can be exploited by attackers to gain unauthorized access to sensitive data.
- Information disclosure: Insecure hashes can also result in vulnerabilities that allow attackers to manipulate and forge data, which can result in information disclosure and impersonation.
- Malicious attacks: Attackers can use insecure hashes to launch various types of attacks, such as collision attacks or dictionary attacks, which can be used to break weak or outdated hashes.
- Reduced trust: Insecure hashes can erode the trust that users and customers have in a system or application. This can result in reputational damage and financial losses.
How to prevent insecure hashes?
Several measures can prevent the use of insecure hashes, including:
- Use strong cryptographic hash functions: Use strong and up-to-date cryptographic hash functions that have been widely tested and validated by security experts, such as SHA-256 or SHA-3. Avoid using outdated hash functions like MD5 or SHA-1, which are known to be insecure.
- Use appropriate hash lengths: Use appropriate hash lengths to ensure that the cryptographic hashes generated are strong enough to resist attacks. Longer hash lengths are generally more secure and harder to break.
- Use salt values: Use salt values to further strengthen the security of the cryptographic hashes generated. Salt values are random data that are added to the original data before hashing, which makes it harder for attackers to use precomputed tables or dictionaries to break the hashes.
- Regularly update software and systems: Regularly update software and systems to ensure that the latest security patches are applied and known vulnerabilities related to insecure hashes are addressed.
- Regularly review and update security policies and procedures: Regularly review and update security policies and procedures to ensure that they remain up-to-date with the latest best practices and standards.
References
Taxonomies
- OWASP Top 10 - A02 Cryptographic Failures
- CWE-328: Use of Weak Hash
- CWE-916: Use of Password Hash With Insufficient Computational Effort
Explanation & Prevention
- OWASP: Using a broken or risky cryptographic algorithm article
- OWASP: Cryptographic Storage Cheat Sheet
- OWASP: Password Storage Cheat Sheet
- OWASP: Testing for Weak Encryption
Related CVEs
Training
Option A: Use A Strong Hashing Function
MD5
or SHA1
have known collision weaknesses and are no longer considered strong hashing algorithms.
Go through the issues that GuardRails identified in the PR/MR.
Identify the following pattern:
var hashProvider = new SHA1CryptoServiceProvider();
var hash = hashProvider.ComputeHash(str);And replace it with:
var hashProvider = SHA256Managed.Create();
var hash = hashProvider.ComputeHash(str);Test it, ship it 🚢 and relax 🌴
Fixing insecure algorithms and cipher modes
About insecure algorithms and cipher modes
What are insecure algorithms and cipher modes?
A cryptographic algorithm and a cipher mode are two different concepts used in cryptography.
A cryptographic algorithm is a mathematical function used to encrypt or decrypt data. It defines the rules for transforming plaintext (unencrypted) data into ciphertext (encrypted) data, and vice versa. Common cryptographic algorithms include Advanced Encryption Standard (AES), RSA, and Triple Data Encryption Standard (3DES).
On the other hand, a cipher mode is a method of applying a cryptographic algorithm to encrypt or decrypt data. It defines the way in which plaintext is broken into blocks and how these blocks are transformed into ciphertext. Common cipher modes include Electronic Codebook (ECB), Cipher Block Chaining (CBC), and Galois/Counter Mode (GCM).
The difference between a cryptographic algorithm and a cipher mode is that an algorithm defines the mathematical rules for encryption and decryption, while a cipher mode defines the specific way in which these rules are applied to transform plaintext into ciphertext.
A cryptographic algorithm is a fundamental building block of cryptography, while a cipher mode provides additional security features and determines how data is processed.
Insecure algorithms are cryptographic algorithms that are known to have vulnerabilities that can be exploited by attackers. Cryptographic algorithms are used in security systems to protect data.
An example of an insecure algorithm is the Data Encryption Standard (DES), which is vulnerable to brute-force attacks.
Insecure cipher modes are cryptographic modes that have vulnerabilities or weaknesses that can be exploited by attackers to compromise the security of the encryption. The use of insecure cipher modes can result in data being decrypted or tampered with by unauthorized parties, which can lead to serious security breaches and data leaks.
Some examples of insecure cipher modes include:
- Electronic Codebook (ECB): ECB mode is insecure because it encrypts each block of plaintext independently, which can lead to patterns in the ciphertext that reveal information about the plaintext.
- Cipher Block Chaining (CBC) with a static IV: CBC mode with a static initialization vector (IV) is vulnerable to chosen plaintext attacks, where an attacker can manipulate the plaintext and observe the resulting ciphertext to learn more about the encryption algorithm.
- Cipher Feedback (CFB) mode with a small segment size: CFB mode with a small segment size can be vulnerable to bit-flipping attacks, where an attacker can manipulate the ciphertext to change the decrypted plaintext.
- Stream cipher modes using weak key schedules: Some stream cipher modes use weak key schedules that can be easily broken by attackers, allowing them to decrypt the ciphertext and gain access to sensitive data.
Check out this video for a high-level explanation:
What is the impact of insecure algorithms and cipher modes?
Insecure algorithms in security systems can have significant impacts on the security and privacy of data.
Here are some of the potential impacts:
- Data breaches: Insecure algorithms and cipher modes can be exploited by attackers to decrypt or tamper with encrypted data, leading to data breaches and the exposure of sensitive information.
- Data loss: In some cases, the use of insecure algorithms and cipher modes can result in the loss of encrypted data, either through accidental deletion or malicious tampering by attackers.
- Compliance violations: The use of insecure algorithms and cipher modes can lead to compliance violations with industry standards and regulations, such as the Payment Card Industry Data Security Standard (PCI DSS) or the General Data Protection Regulation (GDPR).
- Reputation damage: In the event of a data breach or other security incident caused by insecure algorithms and cipher modes, organizations may suffer reputational damage, loss of customer trust, and legal or financial penalties.
How to prevent insecure algorithms and cipher modes?
Several measures can prevent the use of insecure algorithms, including:
- Use strong cryptographic algorithms: Use strong and up-to-date cryptographic algorithms that have been widely tested and validated by security experts. For example, Advanced Encryption Standard (AES) encryption algorithm is widely used and has been proven to be secure.
- Disable or remove insecure algorithms: Disable or remove insecure algorithms, such as DES or RC4, from systems and applications.
- Use well-designed cipher modes: Use well-designed cipher modes that provide strong security guarantees, such as Cipher Block Chaining (CBC) with randomized initialization vectors (IVs) or Galois/Counter Mode (GCM).
- Avoid using weak cipher modes: Avoid using insecure cipher modes such as Electronic Codebook (ECB) or Cipher Feedback (CFB) mode with a small segment size.
- Regularly update cryptographic libraries and dependencies: Keep all cryptographic libraries and dependencies up-to-date with the latest security patches and updates.
- Regularly review and update security policies and procedures: Regularly review and update security policies and procedures to ensure that they remain up-to-date with the latest best practices and standards.
References
Taxonomies
- OWASP Top 10 - A02 Cryptographic Failures
- CWE-327: Use of a Broken or Risky Cryptographic Algorithm
- CWE-780: Use of RSA Algorithm without OAEP
Explanation & Prevention
- OWASP: Using a broken or risky cryptographic algorithm article
- OWASP: Cryptographic Storage Cheat Sheet
- OWASP: Testing for Weak Encryption
- Holistic Infosec: Cryptography on the Client
- NIST: Transitions: Recommendation for Transitioning the Use of Cryptographic Algorithms and Key Lengths
- CAPEC: Padding Oracle Crypto Attack
Related CVEs
Training
Option A: Use Strong Algorithms
DES
and 3DES
are not considered strong algorithms for modern applications. Currently, NIST recommends the usage of AES block ciphers instead. Broken or deprecated ciphers have known weaknesses. Attackers may brute force the secret key that was used for the encryption.
Go through the issues that GuardRails identified in the PR/MR.
Identify the following pattern:
DES DESalg = DES.Create();
// Create a string to encrypt.
byte[] encrypted;
ICryptoTransform encryptor = DESalg.CreateEncryptor(key, zeroIV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt,
encryptor,
CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(Data);
}
encrypted = msEncrypt.ToArray();
return encrypted;
}
}And replace it with AES:
// Create a string to encrypt.
byte[] encrypted;
var encryptor = new AesManaged();
encryptor.Key = key;
encryptor.GenerateIV();
var iv = encryptor.IV;
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt,
encryptor.CreateEncryptor(),
CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(Data);
}
encrypted = msEncrypt.ToArray();
return encrypted;
}
}Test it, ship it 🚢 and relax 🌴
Option B: Use strong cipher modes
If attackers can submit an encrypted payload and the server is decrypting its content. The attacker is likely able to decrypt its content because the CBC mode is susceptible to padding oracle attacks.
The ECB mode will produce an identical encrypted block for an equivalent plain text block. This could allow an attacker that is eavesdropping to guess the content sent. This same property can also allow the recovery of the original message. Furthermore, this cipher mode alone does not guarantee integrity. See also this resource for more information.
Go through the issues that GuardRails identified in the PR/MR.
Identify the following pattern:
using (var aes = new AesManaged {
KeySize = KeyBitSize,
BlockSize = BlockBitSize,
Mode = CipherMode.OFB,
Padding = PaddingMode.PKCS7
})
{
using (var encrypter = aes.CreateEncryptor(cryptKey, new byte[16]))
using (var cipherStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write))
using (var binaryWriter = new BinaryWriter(cryptoStream))
{
//Encrypt Data
binaryWriter.Write(secretMessage);
}
cipherText = cipherStream.ToArray();
}
}
//Missing HMAC suffix to assure integrityAnd replace it with:
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
public static readonly int BlockBitSize = 128;
public static readonly int KeyBitSize = 256;
public static byte[] SimpleEncrypt(byte[] secretMessage, byte[] key)
{
//User Error Checks
if (key == null || key.Length != KeyBitSize / 8)
throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "key");
if (secretMessage == null || secretMessage.Length == 0)
throw new ArgumentException("Secret Message Required!", "secretMessage");
//Using random nonce large enough not to repeat
var nonce = new byte[NonceBitSize / 8];
Random.NextBytes(nonce, 0, nonce.Length);
var cipher = new GcmBlockCipher(new AesFastEngine());
var parameters = new AeadParameters(new KeyParameter(key), MacBitSize, nonce, new byte[0]);
cipher.Init(true, parameters);
//Generate Cipher Text With Auth Tag
var cipherText = new byte[cipher.GetOutputSize(secretMessage.Length)];
var len = cipher.ProcessBytes(secretMessage, 0, secretMessage.Length, cipherText, 0);
cipher.DoFinal(cipherText, len);
//Assemble Message
using (var combinedStream = new MemoryStream())
{
using (var binaryWriter = new BinaryWriter(combinedStream))
{
//Prepend Nonce
binaryWriter.Write(nonce);
//Write Cipher Text
binaryWriter.Write(cipherText);
}
return combinedStream.ToArray();
}
}or:
using System.IO;
using System.Security.Cryptography;
public static byte[] SimpleEncrypt(byte[] secretMessage, byte[] cryptKey, byte[] authKey, byte[] nonSecretPayload = null)
{
//User Error Checks
if (cryptKey == null || cryptKey.Length != KeyBitSize / 8)
throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "cryptKey");
if (authKey == null || authKey.Length != KeyBitSize / 8)
throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "authKey");
if (secretMessage == null || secretMessage.Length < 1)
throw new ArgumentException("Secret Message Required!", "secretMessage");
byte[] cipherText;
byte[] iv;
using (var aes = new AesManaged {
KeySize = KeyBitSize,
BlockSize = BlockBitSize,
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7
})
{
//Use random IV
aes.GenerateIV();
iv = aes.IV;
using (var encrypter = aes.CreateEncryptor(cryptKey, iv))
using (var cipherStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write))
using (var binaryWriter = new BinaryWriter(cryptoStream))
{
//Encrypt Data
binaryWriter.Write(secretMessage);
}
cipherText = cipherStream.ToArray();
}
}
//Assemble encrypted message and add authentication
using (var hmac = new HMACSHA256(authKey))
using (var encryptedStream = new MemoryStream())
{
using (var binaryWriter = new BinaryWriter(encryptedStream))
{
//Prepend IV
binaryWriter.Write(iv);
//Write Ciphertext
binaryWriter.Write(cipherText);
binaryWriter.Flush();
//Authenticate all data
var tag = hmac.ComputeHash(encryptedStream.ToArray());
//Postpend tag
binaryWriter.Write(tag);
}
return encryptedStream.ToArray();
}
}Test it, ship it 🚢 and relax 🌴