Skip to main content

Insecure Use of Cryptography

Insecure RSA key length

About insecure encryption strength

What is insecure encryption strength?

Insecure encryption strength refers to the use of encryption mechanisms that are not strong enough to provide adequate protection for sensitive information.

Encryption is used to protect data by converting it into a form that cannot be read without the appropriate decryption key or password. Encryption strength is determined by the size of the encryption key used, with longer keys generally being stronger and more resistant to attacks.

If encryption strength is insecure, attackers may be able to decrypt and access sensitive information, which can lead to data breaches and information disclosure. Insecure encryption can also make it easier for attackers to carry out other types of attacks, such as man-in-the-middle attacks, where attackers intercept and modify encrypted communications.

Check out this video for a high-level explanation:

What is the impact of insecure encryption strength?

Insecure encryption strength can lead to data breaches and information disclosure. If encryption strength is not sufficient, attackers may be able to decrypt and access sensitive information that is intended to be protected, which can result in a range of negative consequences, including:

  • Data loss: Sensitive information may be lost or stolen, which can result in financial loss, legal liabilities, and reputational damage.
  • Compromise of user accounts: If user accounts are not properly protected with strong encryption, attackers may be able to gain unauthorized access to user data, which can lead to identity theft, fraud, and other malicious activities.
  • Regulatory violations: Inadequate encryption strength may lead to violations of regulatory requirements related to data privacy and security, which can result in fines and legal liabilities.
  • Loss of trust: If customer data is compromised due to insecure encryption, it can damage the trust and confidence that customers have in an organization, which can have long-term negative impacts on the business.

How to prevent insecure encryption strength?

To prevent insecure encryption strength, organizations should follow best practices for encryption, such as:

  • Use strong encryption algorithms: Organizations should use encryption algorithms that are widely accepted and considered to be secure, such as Advanced Encryption Standard (AES), and avoid using outdated or weakened encryption algorithms.
  • Use proper encryption key lengths: Ensure that the encryption key lengths are appropriate for the selected cryptographic algorithm and that the key derivation process is secure.
  • Regularly review and update encryption: Encryption algorithms and keys should be regularly reviewed and updated to ensure they remain strong enough to resist attacks, especially when new vulnerabilities or weaknesses are discovered.
  • Follow best practices for key management: Encryption keys should be properly managed, stored securely, and rotated on a regular basis to reduce the risk of key compromise.
  • Test encryption strength: Regular vulnerability scanning and penetration testing can help identify weaknesses in encryption strength and provide an opportunity to improve security.

References

Taxonomies

Explanation & Prevention

Training

RSA is considered insecure if a key length of less than 2048 bits is used.

Rule-specific references:

The recommended RSA key length is 2048 or higher. Therefore we recommend increasing the key length of your RSA keys if they are less than 2048 bites in length.

  1. Go through the issues that GuardRails identified in the PR/MR.

  2. Locate the vulnerable pattern (example below):

    pvk, err := rsa.GenerateKey(rand.Reader, 1024)
    if err != nil {
    panic(err)
    }

    pvk2, err := rsa.GenerateMultiPrimeKey(rand.Reader, 5, 512)
    if err != nil {
    panic(err)
    }
  3. Replace the key length with 2048 or higher

    pvk, err := rsa.GenerateKey(rand.Reader, 2048)
    if err != nil {
    panic(err)
    }

    pvk2, err := rsa.GenerateMultiPrimeKey(rand.Reader, 5, 4096)
    if err != nil {
    panic(err)
    }
  4. Test it

  5. Ship it 🚢 and relax 🌴

Insecure DES and RC4 encryption algorithms

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

Explanation & Prevention

Training

This rule detects the usage of Data Encryption Standard (DES) and RC4 encryption algorithms. They are well known to be insecure and are considered deprecated.

Rule-specific references:

Option A: Replace DES or RC4 with AES-256

Advanced Encryption Standard (AES) is chosen by NIST as a replacement for the DES.

  1. Go through the issues that GuardRails identified in the Pull Request

  2. Locate the following vulnerable pattern:

    import (
    "crypto/rc4"
    )

    func encrypt(filepath string) {
    file_content, err := os.ReadFile(filepath)
    if err != nil {
    panic(err)
    }
    cipher, err := rc4.NewCipher([]byte("5uP3r5EcRe7"))
    if err != nil {
    panic != nil
    }
    ciphertext := make([]byte, len(file_content))
    cipher.XORKeyStream(ciphertext, file_content)
    os.WriteFile(filepath, ciphertext, 0644)
    }
  3. Replace DES or RC4 with AES-256

    import (
    "crypto/aes"
    "crypto/cipher"
    )

    func encrypt2(filepath string) {
    file_content, err := os.ReadFile(filepath)
    if err != nil {
    panic(err)
    }
    c, err := aes.NewCipher([]byte("256-bits secret keyyyyyyyyyyyyyy"))
    if err != nil {
    panic(err)
    }
    ciphertext := make([]byte, aes.BlockSize+len(file_content))
    iv := ciphertext[:aes.BlockSize]
    if _, err = io.ReadFull(rand.Reader, iv); err != nil {
    panic(err)
    }
    // Because AES is block cipher so it needs
    // block cipher mode of operation to encrypt
    // plantext which is longer than block size
    cbc := cipher.NewCBCEncrypter(c, iv)
    cbc.CryptBlocks(ciphertext[aes.BlockSize:], file_content)
    os.WriteFile(filepath, ciphertext, 0644)
    }
  4. Test it

  5. Ship it 🚢 and relax 🌴

Insecure MD5 and SHA1 hash functions

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

Explanation & Prevention

Training

This rule detects the usage of MD5 and SHA1 hash functions. They are well known to be vulnerable and are considered deprecated.

Rule-specific references:

Option A: Use bcrypt algorithms for hashing password

The bcrypt function is the default password hash algorithm for OpenBSD and was the default for some Linux distributions such as SUSE Linux.

  1. Go through the issues that GuardRails identified in the Pull Request

  2. Locate the following vulnerable pattern:

    import (
    "crypto/md5"
    )

    func createUser(w http.ResponseWriter, req *http.Request) {
    ...
    h := md5.New()
    io.WriteString(h, password)
    user.setPassword(h.Sum(nil))
    ...
    }
  3. Replace MD5 or SHA-1 function with bcrypt function

    import (
    "golang.org/x/crypto/bcrypt"
    "golang.org/x/crypto/sha3"
    )

    func createUser(w http.ResponseWriter, req *http.Request) {
    ...
    sum := sha3.Sum512(password)
    user.setPassword(bcrypt.GenerateFromPassword(sum[:], 12))
    ...
    }
  4. Test it

  5. Ship it 🚢 and relax 🌴

Option B: Use SHA-3 for general purpose

SHA-3 (Secure Hash Algorithm 3) is the latest member of the Secure Hash Algorithm family of standards.

  1. Go through the issues that GuardRails identified in the Pull Request

  2. Locate the following vulnerable pattern:

    import (
    "crypto/sha1"
    )

    func hashFile(w http.ResponseWriter, req *http.Request) {
    dat, err := os.ReadFile(req.URL.Query().Get("file"))
    if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
    }
    w.Write([]byte(fmt.Sprintf("%x", sha1.Sum(dat))))
    }
  3. Replace MD5 or SHA-1 function with SHA-3 function

    import (
    "golang.org/x/crypto/sha3"
    )

    func hashFile(w http.ResponseWriter, req *http.Request) {
    dat, err := os.ReadFile(req.URL.Query().Get("file"))
    if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
    }
    w.Write([]byte(fmt.Sprintf("%x", sha3.Sum256(dat))))
    }
  4. Test it

  5. Ship it 🚢 and relax 🌴

Insecure Random Number used in a Security Context

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

Explanation & Prevention

Training

The random number generator provided by math/rand` is pseudo-random, and isn't cryptographically secure. Using a pseudo-random number generator (PRNG) where a cryptographically secure random number generator (CSRNG) should be used can lead to potential security issues.

Rule-specific references:

Option A: Use the crypto/rand module instead

Instead of using the math/rand module, use the crypto/rand module instead. This module provides a cryptographically secure random number generator that should be used for security-sensitive work.

One side-effect of using the crypto/rand module instead of the math/rand module is that it provides less functionality and can only generate big.Ints, prime numbers and []bytes. See this blog post if you wish to generate types that crypto/rand does not support.

  1. Find the vulnerable pattern (example below)

    import "math/rand"
    // ...
    func createUser(first, last string) {
    // ...
    db.Create(&User{ID: uint(rand.Uint64()), FirstName: first, LastName: last})
    // ...
    }
  2. Replace the vulnerable pattern (example continued from above)

    import "crypto/rand"
    import "encoding/binary"
    // ...
    func createUser(first) error {
    // ...
    var id uint
    if err := binary.Read(rand.Reader, binary.BigEndian, &id); err != nil {
    return err
    }
    db.Create(&User{ID: id, FirstName: "John", LastName: "Cena"})
    // ...
    }
  3. Test it

  4. Ship it 🚢 and relax 🌴