Custom Secret Patterns

Earn 25 points (50 with Pro) in two steps

  1. ① Read through the lesson — each section gets a ✓ as you scroll through it.
  2. ② When every section has a ✓, tap Complete lesson.

0 of 11 read · keep scrolling

✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro

Lesson: Custom Secret Patterns in Secret Scanning

Introduction: The Hidden Risk in Your Codebase

In the modern landscape of software development, the accidental exposure of sensitive information is a critical security vulnerability. Developers often handle various types of credentials, including API keys, database connection strings, private cryptographic keys, and internal service tokens. While automated tools provided by platforms like GitHub, GitLab, or dedicated security scanners are excellent at detecting standard secrets like AWS access keys or Stripe tokens, they cannot possibly know the proprietary format of every unique internal secret your organization uses.

This is where custom secret patterns become essential. A custom secret pattern is a user-defined regular expression or rule set that instructs your scanning engine to look for specific strings that follow a format unique to your internal systems. By defining these patterns, you extend the reach of your security perimeter far beyond public-facing credentials, ensuring that your organization’s specific tokens, internal machine-to-machine passwords, and proprietary configuration values are also protected from accidental commits.

Understanding how to build, maintain, and test these patterns is a fundamental skill for any security-conscious engineer. Without custom patterns, your security scanning tools are effectively blind to the most sensitive data that your company generates. This lesson will guide you through the mechanics of defining these patterns, the logic behind regular expressions in a security context, and the best practices for minimizing false positives while maximizing detection coverage.


Not read yet

The Anatomy of a Secret Pattern

At its core, a secret pattern is a structured definition that tells a detection engine what a "secret" looks like in your codebase. Most systems use Regular Expressions (Regex) as the primary mechanism for matching strings. To build an effective pattern, you must understand the components that make a secret unique: the prefix, the entropy, and the suffix.

1. The Prefix

Many organizations use a naming convention for their secrets. For example, an internal API key might always start with INT_ followed by an alphanumeric string. If you know the prefix, your pattern becomes significantly more accurate because you are no longer searching for any random string that happens to look like a key; you are searching for a specific identifier.

2. The Entropy

Entropy refers to the randomness of the secret string. A high-entropy string is harder to guess and is the hallmark of a secure token. When writing patterns, you are often looking for a specific length of characters from a defined character set (e.g., base64, hexadecimal, or alphanumeric). If you know that your internal tokens are always 32 characters of hexadecimal, you can build a highly specific regex that ignores short or non-random strings, which helps reduce false positives.

3. The Suffix or Delimiter

Sometimes, secrets are wrapped in specific delimiters, such as double quotes, equal signs, or specific environment variable assignments. If your developers consistently use a standard format like DB_PASSWORD="secret_value", you can build a pattern that targets the structure of the assignment itself, making the detection logic much more resilient.

Callout: Regular Expressions vs. Entropy Analysis It is important to distinguish between pattern matching and entropy analysis. Regular expressions are deterministic; they look for a specific shape or structure. Entropy analysis, on the other hand, calculates the "randomness" of a string to determine if it looks like a secret, regardless of its format. Custom patterns rely on the former, but the best security suites combine both methods to catch secrets that don't fit a known pattern but still appear to be sensitive.


Not read yet

Designing Effective Regular Expressions for Secrets

Writing a regex for a secret requires a balance between strictness and flexibility. If your regex is too loose, you will trigger hundreds of false positives, causing "alert fatigue" among your developers. If it is too strict, you will miss actual secrets that vary slightly from your expected format.

The Basic Syntax

Let’s assume your organization uses a proprietary internal token that starts with ORG_ followed by 20 hexadecimal characters. The regex would look like this:

ORG_[a-f0-9]{20}

  • ORG_: Matches the literal prefix.
  • [a-f0-9]: Matches any character that is a hexadecimal digit.
  • {20}: Specifies that exactly 20 of these hexadecimal digits must follow the prefix.

Improving Specificity

To avoid matching this pattern in parts of larger strings (like NOT_AN_ORG_1234567890abcdef1234), you should use word boundaries or lookaheads. A word boundary \b ensures that the match starts at a clean break in the text.

\bORG_[a-f0-9]{20}\b

Handling Variability

What if your keys sometimes have an optional version prefix? If your keys can be ORG_V1_... or ORG_V2_..., you can use grouping and the OR operator:

\bORG_(V1|V2)_[a-f0-9]{20}\b

Tip: Testing Your Patterns Always test your regex against a corpus of both valid secrets and "noise" (common code snippets that look like secrets but aren't). Tools like Regex101 are invaluable for visualizing how your pattern matches strings and ensuring that you don't accidentally match common build artifacts or log formats.


Not read yet

Step-by-Step: Implementing Custom Patterns in Your Pipeline

Most modern CI/CD tools and secret scanners (such as GitHub Advanced Security, TruffleHog, or Gitleaks) allow you to provide a configuration file where custom rules are defined. Below is a general process for implementing these rules.

Step 1: Define the Pattern

Start by gathering examples of the actual secrets you want to protect. Create a small file containing these secrets, along with examples of "false positive" text (like random strings in comments or test data).

Step 2: Write the Configuration File

Most scanners use YAML or JSON for configuration. Here is an example of a gitleaks.toml configuration snippet:

[[rules]]
  id = "internal-api-key"
  description = "Detection of internal API keys"
  regex = '''\bORG_[a-f0-9]{20}\b'''
  entropy = 3.5
  keywords = ["ORG_"]

Step 3: Validate the Configuration

Run your scanner in a local "dry-run" mode against a test repository. This allows you to see what the scanner catches without blocking your developers.

# Example command for running a scanner locally
gitleaks detect --config=config.toml --source=./path/to/test-repo --verbose

Step 4: Iterative Refinement

Review the output. If you get too many false positives, tighten the regex or increase the required entropy. If you miss secrets, relax the constraints. Once the performance is acceptable, commit the configuration file to your security repository.


Not read yet

Common Pitfalls and How to Avoid Them

Even with a well-designed regex, there are traps that many teams fall into. Being aware of these will save you hours of debugging.

1. The "Greedy" Regex Trap

A greedy regex can match more than you intend. For example, if you use .* in your pattern, it might match from the beginning of a line all the way to the end, including legitimate code. Always be as specific as possible with character classes (like [a-z0-9]) rather than using the wildcard . (dot) operator.

2. Ignoring Case Sensitivity

Developers often mix cases. While some internal tokens are strictly lowercase, others might be mixed. Always check your organizational standards. If your token format is case-insensitive, ensure your regex flags are set to ignore case, or include both [a-z] and [A-Z] in your character classes.

3. Forgetting About Encoding

Sometimes secrets are base64 encoded when stored in configuration files. If your scanner only looks for the raw string, it might miss the encoded version. Consider whether you need to add rules that look for common encoding patterns, though be careful, as this significantly increases the risk of false positives.

4. Over-reliance on Patterns

Custom patterns are only one layer of defense. Relying solely on them is a mistake. Always combine pattern-based scanning with entropy-based scanning and, if possible, platform-level secret revocation capabilities.

Warning: Never Commit Real Secrets to Test! When testing your custom patterns, never use actual production secrets. Create "dummy" secrets that follow the exact same format as your production ones. If you accidentally commit a real secret to a test repository, you must assume it is compromised and rotate it immediately, regardless of whether the scanner caught it.


Not read yet

Comparison of Detection Methods

To understand where custom patterns fit, it helps to see how they compare to other common detection methods.

Method Strength Weakness
Regex Patterns Extremely fast; low false-negative rate for known formats. Requires manual maintenance; cannot detect unknown formats.
Entropy Analysis Detects high-randomness strings without knowing the format. High false-positive rate (e.g., hash values, UUIDs).
Keyword Matching Very simple to implement; effective for specific variable names. Easily bypassed; high noise if the keyword is common.
Provider-Specific Scanners Validates if the secret is actually active/live. Only works for supported services; requires API access.

Best Practices for Maintaining Secret Patterns

Managing custom patterns is not a "set it and forget it" task. As your infrastructure evolves, your patterns will need to change.

1. Centralized Rule Management

Do not allow individual teams to define their own secret patterns in isolated repositories. Maintain a centralized security repository where all custom patterns are defined. This ensures that every project in the organization is protected by the same set of rules.

2. Versioning Your Patterns

Treat your secret scanning configuration like code. Use a version control system (like Git) to manage your configuration files. This allows you to roll back if a new pattern causes an unexpected surge in false positives.

3. Periodic Audits

Once a quarter, review the alerts generated by your custom patterns. If a specific pattern is generating 90% of your false positives, it is time to refine it. If a specific pattern has never triggered an alert, investigate whether it is because the pattern is broken or because developers are actually following secure practices.

4. Developer Feedback Loops

When a developer receives an alert from a custom pattern, provide clear instructions on what they should do next. Do not just say "Secret detected." Instead, provide a link to your internal security documentation that explains how to rotate the secret, where to store it properly (e.g., in a Vault), and how to verify that the fix is correct.

5. Automation of Remediation

Where possible, integrate your scanner with automated remediation tools. If a secret is detected, can you automatically revoke it? Can you trigger an alert in your incident response system? The faster you move from detection to remediation, the smaller the window of risk.


Not read yet

Advanced Topic: Using Lookaheads for Context

Sometimes, a secret pattern is only valid if it appears in a specific context. For example, you might only care about a token if it appears on the same line as a variable assignment. Regular expression lookaheads are perfect for this.

A lookahead allows you to match a pattern only if it is preceded or followed by another pattern. Suppose you only want to flag API_KEY=... if it is assigned to a specific variable name.

(?<=PRIVATE_KEY_VAR=)[a-zA-Z0-9]{32}

  • (?<=...): This is a positive lookbehind. It asserts that the text immediately preceding the match must be PRIVATE_KEY_VAR=.
  • The scanner will only flag the 32-character string if it is immediately following that specific variable name.

This technique is incredibly powerful for reducing noise. It allows you to target your security scanning toward specific configuration files or specific variable naming conventions that are known to be high-risk.


Not read yet

Handling False Positives Gracefully

No matter how good your patterns are, you will eventually encounter false positives. A false positive is an alert that identifies a string as a secret when, in fact, it is not.

Why False Positives Occur

  • Hash Values: Many non-secret strings, such as git commit hashes or build IDs, look like secrets.
  • Example Code: Documentation and README files often contain "dummy" secrets that look real.
  • Legacy Data: Old configuration files may contain values that are no longer in use but still match your pattern.

How to Handle Them

  1. Ignore Files: Most scanners support an "ignore" or "allowlist" file. If a file contains a known false positive, add it to the ignore list, but ensure this list is regularly audited.
  2. Inline Suppression: If a specific line of code is flagged incorrectly, allow developers to use a comment to suppress the warning, such as # gitleaks:allow. Use this sparingly and ensure that any such suppression requires a peer review or security sign-off.
  3. Pattern Refinement: If a false positive is recurring, it is a sign that your regex is too broad. Use the false positive as a test case for your regex and refine the pattern until it no longer matches.

Not read yet

Integrating with the Development Workflow

The most effective place to catch secrets is on the developer's machine, before the code is even pushed to the server. This is known as "shifting left."

Pre-commit Hooks

You can install pre-commit hooks that run your secret scanner every time a developer attempts to commit code. If the scanner detects a secret, the commit is blocked.

# Example of a pre-commit hook configuration
- repo: https://github.com/gitleaks/gitleaks
  rev: v8.0.0
  hooks:
    - id: gitleaks

This approach is highly effective because it provides immediate feedback to the developer. They can fix the issue in seconds, rather than waiting for a CI pipeline to fail minutes or hours later.

CI/CD Integration

While pre-commit hooks are great, they are not foolproof. A developer might bypass them, or they might not have the hook installed. Therefore, you must also run the scanner as a mandatory step in your CI/CD pipeline. If a secret is detected in the pipeline, the build should fail, and the developer should be alerted.

Monitoring and Reporting

Use a centralized dashboard to monitor the status of your secret scanning. This allows you to track metrics such as:

  • Time-to-Remediation: How long does it take for a developer to fix a detected secret?
  • False Positive Rate: How many of your alerts are being marked as "not a secret"?
  • Secret Volume: Are the number of detected secrets increasing or decreasing over time?

Not read yet

Frequently Asked Questions (FAQ)

Q: Should I use one massive regex for all secrets? A: No. It is better to have many small, specific rules than one massive, complex regex. Smaller rules are easier to test, debug, and maintain.

Q: What if our secret format changes? A: This is why versioning your rules is important. When you update your secret format, you should create a new rule for the new format while keeping the old rule active for a period to catch any legacy secrets still in the codebase.

Q: How do I handle secrets that are generated dynamically? A: If secrets are generated dynamically (e.g., at runtime), they are less likely to be hardcoded in the repository. However, if they are saved to configuration files, they should be treated like any other secret. If they are truly dynamic and never stored, you don't need to worry about them in your static scanning.

Q: Is it okay to use public secret lists? A: Yes, many open-source projects maintain lists of regex patterns for popular services (like AWS, Google, etc.). You should definitely include these in your scanner, but they do not replace the need for your own custom patterns for your internal secrets.


Not read yet

Summary and Key Takeaways

Configuring custom secret patterns is a vital component of a modern security program. By moving beyond generic, off-the-shelf detection, you can protect the unique assets that define your organization.

Here are the key takeaways from this lesson:

  • Customization is Essential: Off-the-shelf tools cannot identify your proprietary secrets; you must define the patterns that match your specific internal formats.
  • Regex Discipline: Use strict, well-tested regular expressions. Avoid greedy wildcards and always include boundary anchors to reduce false positives.
  • Shift Left: Implement scanning at the developer's workstation using pre-commit hooks to catch secrets before they ever leave the local environment.
  • Manage, Don't Just Deploy: Treat your secret scanning configuration as code. Version it, audit it, and update it as your infrastructure changes.
  • Prioritize Context: Use lookaheads and specific variable names to make your patterns as precise as possible, ensuring that developers are only interrupted for genuine issues.
  • Continuous Improvement: Use false positives as a source of data to refine your patterns. If an alert is wrong, it is an opportunity to make your scanner better.
  • Layered Defense: Remember that secret scanning is only one layer of your security stack. Combine it with secret rotation policies, vaulting solutions, and access control to build a truly resilient system.

By following these principles, you will significantly reduce the risk of accidental secret exposure and create a safer environment for your development teams and your users. Start by identifying your most critical internal secrets, define a simple pattern, and begin the journey of automating your security posture.

Not read yet

Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.