Model Packs and Extensions

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 12 read · keep scrolling

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

CodeQL Advanced Topics: Model Packs and Extensions

Introduction to CodeQL Modeling

When you first start using CodeQL, you likely rely on the standard libraries provided by GitHub. These libraries cover a vast array of common vulnerabilities across many popular languages like Java, JavaScript, Python, and C++. However, as your codebase grows or incorporates proprietary frameworks, internal libraries, or niche dependencies, the standard queries may fail to recognize security-sensitive data flow. This is where CodeQL modeling comes into play.

CodeQL modeling is the process of teaching the engine about your specific code. It involves defining how data flows through your custom functions, which methods are sources of untrusted input, and which sinks are dangerous. By using Model Packs and Extensions, you can package these definitions and share them across your organization. This capability is essential for large-scale security operations because it prevents the "siloing" of knowledge, ensuring that every developer or automated scanner benefits from the same security intelligence regarding your unique application architecture.

Understanding how to build and maintain these models is the difference between a static analysis tool that produces a moderate amount of noise and one that acts as a precise, highly tuned instrument for detecting complex vulnerabilities in your specific software ecosystem.

Not read yet

Understanding the Core Concepts: Models vs. Queries

Before diving into the mechanics of Model Packs, it is important to distinguish between a CodeQL query and a model. A query is an executable program that searches for a specific pattern, such as a SQL injection or a cross-site scripting flaw. A model, on the other hand, is a declarative description of the environment. It tells the CodeQL engine that "this specific method in your internal library is a source of user-controlled data" or "this method is a sanitizer that cleans input."

By separating models from queries, you gain flexibility. You can define a model once and use it across dozens of different queries. If your internal library changes, you update the model in one place, and all dependent queries automatically reflect the new behavior. This approach follows the software engineering principle of "Don't Repeat Yourself" (DRY) and significantly reduces the maintenance burden on security engineers.

Callout: The Anatomy of a CodeQL Model A CodeQL model is essentially a map that guides the engine. While a query asks "Where is the data going?", the model answers "What are the characteristics of the functions the data passes through?" Without accurate models, the engine treats your proprietary framework as a "black box," often leading to false negatives where vulnerabilities go undetected because the engine cannot trace the path through your custom code.

Not read yet

What are Model Packs?

Model Packs are a specialized form of CodeQL packages. In the CodeQL ecosystem, a package is a bundle of code that can be versioned, distributed, and managed using the CodeQL CLI. A Model Pack specifically contains modeling data, usually in the form of CSV files or CodeQL library files, that describes how your libraries interact with the outside world.

Instead of writing complex predicates in every query to explain your framework, you create a Model Pack. You then declare this pack as a dependency in your project's qlpack.yml file. When you run your analysis, the CodeQL engine automatically loads the modeling data from the pack, effectively "teaching" the engine about your framework before it even begins searching for vulnerabilities.

The Structure of a Model Pack

A standard Model Pack follows the standard directory structure of any CodeQL package:

  • qlpack.yml: The metadata file defining the package name, version, and dependencies.
  • models/: A directory containing the actual modeling data, often formatted as CSV files for ease of maintenance.
  • lib/: A directory for any custom CodeQL library code that provides helper predicates or classes.
  • queries/: Optional, but sometimes used to include diagnostic queries that verify the model is being loaded correctly.

Not read yet

Practical Implementation: Building Your First Model

Let’s look at a concrete scenario. Imagine your company uses a custom logging framework called InternalSecureLogger. You want to ensure that no developer ever logs a raw password string. Without a model, CodeQL doesn't know that InternalSecureLogger.log(String) is a sink for sensitive data.

Step 1: Create the QL Pack

First, create a directory for your model and initialize it.

mkdir my-security-models
cd my-security-models
codeql pack init my-org/custom-models

This creates the qlpack.yml file. You should edit this file to ensure it has the correct dependencies. If you are modeling Java code, for example, your qlpack.yml should include the Java library as a dependency.

Step 2: Create the Model File

CodeQL uses a specific CSV format for modeling external libraries. Create a file at models/log-sinks.csv. The format generally follows the structure: package;type;subtypes;is_static;name;signature;ext;input;output;kind.

# package;type;subtypes;is_static;name;signature;ext;input;output;kind
com.mycompany.logging;InternalSecureLogger;;false;log;(String);;arg[0];;log-sink

In this example:

  • com.mycompany.logging is the package.
  • InternalSecureLogger is the class name.
  • log is the method name.
  • (String) is the method signature.
  • arg[0] indicates that the first argument is where the data enters the sink.
  • log-sink is the tag we will use in our queries to identify this as a dangerous location.

Step 3: Write a Query to Use the Model

Now that the model exists, you need to write a query that utilizes this information. You do this by creating a DataFlow::Configuration or using the newer DataFlow::PathGraph approach.

import java
import semmle.code.java.dataflow.DataFlow
import semmle.code.java.dataflow.TaintTracking

class PasswordLoggingConfig extends TaintTracking::Configuration {
  PasswordLoggingConfig() { this = "PasswordLoggingConfig" }

  override predicate isSource(DataFlow::Node source) {
    // Define your source: e.g., a field named 'password'
    source.asExpr().(FieldAccess).getField().getName() = "password"
  }

  override predicate isSink(DataFlow::Node sink) {
    // Here we use the model we defined!
    exists(MethodAccess ma |
      ma.getMethod().hasQualifiedName("com.mycompany.logging", "InternalSecureLogger", "log") and
      sink.asExpr() = ma.getArgument(0)
    )
  }
}

Note: Always ensure that your model definitions match the exact signature of the library methods. Even a missing space or a typo in the method signature will cause the model to fail to match, resulting in silent failures where the query simply returns zero results.

Not read yet

Advanced Modeling: Extensions

While Model Packs are great for static definitions, sometimes you need more dynamic behavior. This is where CodeQL Extensions come in. Extensions allow you to augment the behavior of existing libraries without modifying the library source code itself.

For instance, if you have a library that performs input validation but doesn't explicitly implement a known "Sanitizer" interface, you can create an extension that tells CodeQL to treat that specific class as a sanitizer.

Implementing a Sanitizer Extension

Suppose you have a method Validator.clean(String input) that removes dangerous characters. You want the CodeQL engine to recognize this as a sanitizer.

  1. Define the Extension: Create a new library file in your pack, for example, lib/Sanitizers.qll.
  2. Extend the Library: Use the extends keyword to add your method to the DataFlow::Sanitizer class.
module MyCompanySanitizers {
  import semmle.code.java.dataflow.TaintTracking

  private class MyValidator extends TaintTracking::Sanitizer {
    MyValidator() {
      exists(Method m |
        m.hasName("clean") and
        m.getDeclaringType().hasName("Validator")
      )
    }
  }
}

By doing this, you are effectively "injecting" your logic into the global TaintTracking library. Any query in your project that imports the standard TaintTracking library will now automatically treat Validator.clean as a sanitizer, significantly reducing false positives in your vulnerability reports.

Not read yet

Best Practices for Maintaining Models

Managing models across a large organization requires discipline. If models are poorly maintained, they become "stale," leading to either false positives (because the model is too broad) or false negatives (because the model is out of date with the current library version).

1. Versioning and Dependency Management

Treat your Model Packs like any other piece of software. Use semantic versioning (SemVer) for your packs. If you update a library and the method signature changes, increment the major version of your Model Pack. This ensures that queries depending on the old version don't break unexpectedly.

2. Testing Your Models

Never deploy a model without testing it. Create "test code" within your repository—small snippets of code that intentionally contain the vulnerable patterns you are trying to detect. Run your queries against this test code to ensure the models are correctly identified. If a model change causes a previously detected vulnerability to disappear, you know immediately that your model is flawed.

3. Centralized Repository

Maintain a central repository for all organization-wide Model Packs. This allows security teams to audit the models and ensures that all teams are using the same version of the security intelligence.

Callout: The "False Negative" Trap The most dangerous aspect of advanced modeling is the false sense of security it can provide. If you define a model incorrectly—for instance, labeling a method as a sanitizer when it actually does nothing—you are effectively telling the CodeQL engine to ignore potential vulnerabilities. Always peer-review model changes with the same rigor you would apply to production code.

Not read yet

Troubleshooting Common Pitfalls

Even experienced security engineers encounter issues when working with CodeQL models. Here are some of the most frequent problems and how to solve them.

  • The "Silent Failure" Problem: If your query returns no results, it is often because the model is not being loaded or the signature is wrong. Use the --verbose flag when running the CodeQL CLI to see which packages are being loaded and if there are any warnings about missing dependencies.
  • Signature Mismatches: Java generics can be tricky. If your method signature includes generic types, ensure your model CSV reflects the erased type or the exact signature used by the compiler.
  • Scope Issues: Ensure your model is exported correctly from the package. If you define a predicate in a library file but don't export it in the main module file, other queries won't be able to see it.
  • Performance Degradation: Adding too many models can slow down your analysis. The CodeQL engine has to evaluate every node against every model. If you notice a significant drop in scan speed, review your models to ensure they are as specific as possible. Avoid overly broad wildcards in your signatures.

Not read yet

Comparison: Model Packs vs. Query Extensions

Feature Model Packs Query Extensions
Primary Purpose Define external library behavior Modify existing library logic
Data Format CSV files (declarative) QL code (imperative)
Reusability High (can be shared across teams) Medium (often project-specific)
Maintenance Easier (update CSV data) Harder (requires code changes)
Performance Optimized for bulk lookups Depends on logic complexity

Step-by-Step: Updating a Model for a Library Change

When a dependency updates, your models will likely break. Follow this workflow to ensure a smooth transition:

  1. Identify the Change: Review the release notes of the updated library. Look for method signature changes or new class names.
  2. Update the Model CSV: Modify your models/*.csv files to reflect the new signatures.
  3. Run Regression Tests: Execute your test suite (the code snippets you wrote earlier) to confirm that the engine still flags the expected vulnerabilities.
  4. Verify Coverage: Use the CodeQL CLI's database analyze command with the --format=sarif-latest option to inspect the results. Compare the output with the results from the previous version of the library.
  5. Tag and Release: Once verified, tag your Model Pack repository with a new version number and update the qlpack.yml dependencies in all projects that consume this pack.

Not read yet

Integrating Models into CI/CD Pipelines

To ensure that your models are always up to date during the development process, integrate the Model Pack installation into your CI/CD pipeline.

# Example CI Script
# 1. Install the specific version of the model pack
codeql pack install my-org/custom-models@1.2.0

# 2. Run the analysis, including the model pack in the search path
codeql database analyze my-db --search-path=./my-security-models \
       --format=sarif-latest --output=results.sarif

By explicitly installing the pack and using the --search-path flag, you guarantee that the CI environment is using the exact version of the models that you have validated. This prevents "configuration drift" where different developers or build agents are using different versions of the security rules.

Advanced Modeling Techniques: Modeling Sources and Sinks via Annotations

In some cases, you may not want to maintain a separate CSV model file. If you have control over the source code of the library you are modeling, you can use CodeQL's support for annotations. By adding specific comments or markers in your Java or C# code, you can signal to the CodeQL engine how to treat those methods.

However, this is generally less recommended than using Model Packs, as it couples your security modeling to your application code. It is best reserved for scenarios where the library is internal and the security team has direct access to modify the source code. For third-party libraries, stick to Model Packs and external extensions.

Not read yet

The Future of Modeling: Automated Model Generation

The industry is moving toward automated model generation. Tools are emerging that can analyze the bytecode of a library and automatically generate the CSV model files for you. While these tools are not perfect and still require human review, they can significantly reduce the initial effort of modeling a large, complex framework.

Even with automation, the role of the security engineer remains critical. You must verify that the generated models are accurate and that they do not introduce unnecessary noise. Treat auto-generated models as a "draft" that needs to be polished before it is integrated into your production security scanning workflow.

Key Takeaways for Success

  • Models are the Foundation: Your security analysis is only as good as the models it uses. Do not treat modeling as an afterthought; it is a core component of your security strategy.
  • Use Declarative Models (CSV) whenever possible: They are easier to maintain, version control, and share across teams compared to complex QL code.
  • Prioritize Versioning: Treat Model Packs like production software. Use semantic versioning and clear dependency management to avoid breaking changes.
  • Test, Test, Test: Always maintain a repository of "test cases" (intentional vulnerabilities) to verify that your models are working as expected after every change.
  • Centralize Knowledge: Avoid creating local, private models. Share your models in a central repository so that the entire organization benefits from your security research.
  • Monitor Performance: Keep an eye on how your models impact scan times. Specific, well-defined models are better for both accuracy and performance than broad, catch-all patterns.
  • Review Regularly: Libraries change. Schedule regular audits of your Model Packs to ensure they stay in sync with the dependencies your applications are actually using.

Not read yet

FAQ: Common Questions about Model Packs

Q: Can I use a Model Pack for a language other than Java? A: Yes. Model Packs are supported for all languages that CodeQL supports, including Python, JavaScript, C++, and C#. The structure of the CSV might change slightly depending on the language's specific requirements, but the core concept remains the same.

Q: What if I have a conflict between two different models? A: If two models define different behaviors for the same method, the CodeQL engine will apply both. This can lead to unexpected results, so it is best practice to ensure that your models are disjointed and that there is a clear "source of truth" for the behavior of any given library method.

Q: How do I know if my model is being used? A: You can use the --verbose output of the CodeQL CLI. It will list all the packs that are being loaded. If your pack is not in that list, the engine is not using it. Double-check your qlpack.yml and your --search-path configuration.

Q: Is it better to write a custom query or a model? A: If you find yourself writing the same logic to identify a source or sink in multiple queries, you should move that logic into a model. Queries should focus on the logic of the vulnerability, while models should focus on the description of the framework.

Q: Can I share my models publicly? A: Absolutely. Many organizations share their CodeQL models on platforms like GitHub to help the community secure common frameworks. If you find yourself modeling a widely used open-source library, consider contributing your model back to the official CodeQL repository.

Not read yet

Conclusion

Mastering Model Packs and Extensions is the ultimate level-up for a security engineer using CodeQL. It shifts your role from simply running pre-packaged queries to actively shaping the way your organization detects vulnerabilities. By investing the time to accurately model your frameworks, you reduce noise, increase the precision of your security scans, and build a scalable system that grows alongside your codebase.

Remember that CodeQL is a tool that thrives on context. The more context you provide—about your libraries, your frameworks, and your data flows—the more effective the engine becomes. Start small, model your most critical internal libraries first, and gradually build out a comprehensive suite of Model Packs that protect your entire software development lifecycle. With these skills, you are no longer just scanning for bugs; you are building a custom, high-fidelity security analysis engine.

Not read yet

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