Custom CodeQL Queries
Earn 25 points (50 with Pro) in two steps
- ① Read through the lesson — each section gets a ✓ as you scroll through it.
- ② 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 CodeQL Queries for Advanced Security Scanning
Introduction: Why Custom CodeQL Matters
In the modern software development lifecycle, automated security scanning has become a non-negotiable standard. While out-of-the-box security tools—such as the standard CodeQL query suites provided by GitHub—are excellent at catching common vulnerabilities like SQL injection or cross-site scripting (XSS), they cannot possibly understand the unique business logic, internal frameworks, or proprietary coding standards of every organization. This is where custom CodeQL queries become indispensable.
CodeQL is a semantic code analysis engine that allows you to treat your codebase as data. By writing queries in QL (the query language used by CodeQL), you can perform deep, structural analysis of your source code. You are not just looking for regex patterns or simple keyword matches; you are querying the abstract syntax tree and data-flow graphs of your application. This level of precision allows you to identify complex security flaws that are specific to how your team builds software.
Understanding how to write custom queries empowers your security team to shift from reactive patching to proactive, policy-driven development. If your company has a strict internal rule—for example, "all database queries must pass through our custom DatabaseConnector wrapper"—you can write a custom CodeQL query to enforce this rule globally. By integrating these custom checks into your CI/CD pipeline, you turn your security policy into executable code, ensuring that no developer can accidentally bypass your safety requirements.
Not read yet
Understanding the CodeQL Architecture
Before diving into writing queries, it is vital to understand what happens under the hood. CodeQL works by creating a relational representation of your code. When you run a CodeQL analysis, the engine creates a database containing tables that describe your source code's structure, including classes, methods, variables, and the flow of data between them.
A CodeQL query is essentially a set of instructions that asks the engine to find specific patterns within these relational tables. Because the engine understands the code's semantics, it can track data flow across multiple files and functions. This is known as "taint analysis." You define a "source" (where untrusted data enters the system) and a "sink" (where that data is used in a dangerous way), and the CodeQL engine calculates every possible path the data could take between them.
The Anatomy of a Query
Every CodeQL query follows a specific structure:
- Language Declaration: Specifies the language being analyzed (e.g.,
import java,import python). - Metadata: Provides information about the query, such as the unique ID, the severity level, and a human-readable description.
- Query Predicate: The
selectstatement that identifies the results to be returned by the engine.
Callout: Query vs. Library It is important to distinguish between a query and a library. A library in CodeQL is a collection of reusable modules, classes, and predicates that define common concepts like "what constitutes a sensitive sink." A query is the executable file that uses these libraries to report specific findings. When writing custom checks, you will often find yourself writing small library files to encapsulate logic that you might want to reuse in multiple queries.
Not read yet
Setting Up Your Development Environment
To write effective custom queries, you need a stable environment. You should not be writing these queries directly in your production repository. Instead, follow these steps to establish a dedicated workspace.
- Install the CodeQL CLI: Download the official CLI from the GitHub release page. Ensure it is added to your system's PATH so you can execute the
codeqlcommand from any terminal. - Clone the CodeQL Repository: While you can write queries from scratch, it is highly recommended to clone the official
github/codeqlrepository. This gives you access to the standard libraries, which contain thousands of definitions for common functions and frameworks. - Configure VS Code: The CodeQL extension for Visual Studio Code is the industry standard for development. It provides syntax highlighting, auto-completion, and a built-in query runner that allows you to test your queries against a local database.
Creating a Database
To test your query, you need a CodeQL database of a project. You can create one easily using the CLI:
codeql database create my-db --language=java --source-root=/path/to/my/project
Once the database is created, you can open it in VS Code via the CodeQL extension. This allows you to run your custom queries against the project and see the results immediately in the "CodeQL Queries" panel.
Not read yet
Writing Your First Custom Query
Let’s start with a practical example. Imagine your company has a rule that no developer should ever use the System.out.println method in production code, as it can leak sensitive information to logs. We want to write a query that flags every instance of this method call.
/**
* @name Forbidden System.out.println usage
* @description Detects the use of System.out.println which can leak sensitive data.
* @kind problem
* @problem.severity warning
* @id custom-security/java/forbidden-system-out
*/
import java
from MethodAccess ma
where ma.getMethod().hasQualifiedName("java.io.PrintStream", "println")
select ma, "This method call is forbidden; use a proper logging framework instead."
Explanation of the Code
import java: This loads the standard Java library, which gives us access to classes likeMethodAccess.from MethodAccess ma: We are looking for all instances where a method is being accessed or called.where ma.getMethod().hasQualifiedName(...): This is the filtering logic. We are narrowing down our search to only those methods that belong tojava.io.PrintStreamand are namedprintln.select ma, ...: This is the output. It tells the engine to highlight the specific point in the code where the forbidden method is called and provides the warning message.
This is a simple pattern-matching query. It does not require data flow analysis, but it is highly effective for enforcing coding standards.
Not read yet
Advanced Technique: Taint Analysis
Taint analysis is the heart of CodeQL's power. It allows you to track data from a source (like an HTTP request parameter) to a sink (like a SQL query execution). Let’s say we have an internal framework where developers are supposed to use a Sanitizer.clean() method before inserting data into a database. We want to find cases where this is skipped.
To perform this, you need to extend the TaintTracking module.
import java
import semmle.code.java.dataflow.TaintTracking
class MyConfig extends TaintTracking::Configuration {
MyConfig() { this = "MyConfig" }
override predicate isSource(DataFlow::Node source) {
// Define your source, e.g., HTTP request parameters
source instanceof RemoteFlowSource
}
override predicate isSink(DataFlow::Node sink) {
// Define your sink, e.g., a Database execute method
exists(MethodAccess ma |
ma.getMethod().hasName("executeRawQuery") and
sink.asExpr() = ma.getArgument(0)
)
}
}
from MyConfig config, DataFlow::PathGraph path, DataFlow::PathNode source, DataFlow::PathNode sink
where config.hasFlowPath(source, sink)
select sink, source, sink, "Untrusted data reaches a raw database query without sanitization."
Why This Is Powerful
This query is much more sophisticated than the first one. It doesn't just look for a single function call. It asks the engine to map out every possible path from an external input to a dangerous database function. If the data passes through Sanitizer.clean(), the taint is removed, and the query will not flag it. If the developer forgets to sanitize, the engine will draw the path from the request to the database, giving you a clear trail to fix the issue.
Note: When defining your
isSourceandisSinkpredicates, be as specific as possible. If your source or sink is too broad, you will generate a high volume of false positives, which will cause developers to ignore your security reports.
Not read yet
Best Practices for Custom Query Development
Writing custom queries is a form of software engineering, and the same rigor you apply to your application code should apply to your security queries.
1. Test Against Multiple Codebases
A query that works on a small demo project might fail or behave unexpectedly on a large, complex enterprise codebase. Run your queries against several different projects to ensure they are accurate and performant.
2. Manage False Positives
False positives are the enemy of security adoption. If your query flags legitimate code as a vulnerability, developers will lose trust in the tool. If you find a false positive, refine your where clause to exclude known safe patterns. Use the exists or not exists clauses to filter out common exceptions.
3. Use Modular Design
Do not cram all your logic into one file. Create separate files for your source and sink definitions. This allows you to reuse these definitions across different queries. For example, if you have a definition for "Internal API Endpoints," keep that in a separate library so you can use it in multiple security checks.
4. Version Control Your Queries
Store your custom queries in a dedicated repository. Treat them like production code: require code reviews for any changes, use automated tests to verify the queries, and document them thoroughly.
5. Keep Performance in Mind
CodeQL queries can be resource-intensive. Avoid unnecessary Cartesian products in your queries. If your query is running slowly, analyze the from and where clauses to see if you can restrict the search space earlier in the execution.
Not read yet
Common Pitfalls and How to Avoid Them
Even experienced security engineers stumble when writing their first few queries. Here are the most common mistakes and how you can avoid them.
Over-reliance on String Matching
Many beginners try to write queries that look for specific strings in the code. This is inefficient and prone to errors. CodeQL works best when you use the structural properties of the language (e.g., MethodAccess, VariableAccess, Type). Always prefer structural queries over string-based ones.
Ignoring Data Flow
If you are trying to find a vulnerability that involves user input, you must use taint analysis. Simply looking for a dangerous function call is often not enough, as the input might have already been sanitized or validated earlier in the code. Always define your sources and sinks to leverage the full power of the data-flow engine.
Hardcoding Values
Avoid hardcoding class names or method names directly in your main query logic. Use constants or helper predicates. This makes your queries easier to maintain as your internal frameworks evolve.
Callout: The Importance of Documentation Every custom query should include metadata that explains exactly what it does, why it is important, and how to remediate the finding. When a developer sees a security alert, they should be able to click through to documentation that explains the "why" behind the rule. Without this, your custom queries will just add noise to the development process.
Not read yet
Comparison of Query Types
| Query Type | Complexity | Use Case |
|---|---|---|
| Pattern Matching | Low | Enforcing coding standards, banning deprecated functions. |
| Control Flow | Medium | Checking if a specific function is called after another. |
| Taint Analysis | High | Detecting vulnerabilities like injection, XSS, or path traversal. |
| Type Analysis | Medium | Ensuring specific data types are used for sensitive fields. |
Integrating Custom Queries into CI/CD
Once your queries are written and tested, the final step is to integrate them into your CI/CD pipeline. This ensures that every pull request is automatically scanned by your custom rules.
- Create a Query Suite: A query suite is a YAML file that lists the queries you want to run. This allows you to bundle your custom queries with standard CodeQL queries.
- Configure the GitHub Action: If you are using GitHub Actions, update your
codeql-analysis.ymlfile to include your custom query suite. - Set Thresholds: You can configure your pipeline to block merges if a high-severity custom query finding is detected. This makes your security policy "hard" rather than just advisory.
Example Query Suite Configuration (my-suite.qls)
- description: "My organization's custom security suite"
- import: codeql-suites/java-security-and-quality.qls
- qlpack: my-custom-queries
include:
kind: problem
By pointing your analysis workflow to this suite, you ensure that the standard security checks run alongside your proprietary ones, providing a comprehensive view of your application's security posture.
Not read yet
Step-by-Step: Creating a New Custom Rule
Let's walk through the creation of a rule that prevents the use of a non-secure random number generator in a Java application.
Step 1: Identify the Target
We want to ban java.util.Random and require the use of java.security.SecureRandom for security-sensitive operations.
Step 2: Write the Query
import java
from ClassInstanceExpr cie
where cie.getType().(RefType).hasQualifiedName("java.util", "Random")
select cie, "Avoid java.util.Random for security-sensitive operations. Use java.security.SecureRandom instead."
Step 3: Test Locally Run this against your local CodeQL database using the VS Code extension. Check if it flags the intended instances. If it flags false positives (like a non-sensitive random number generation for a game), add a filter to ignore specific packages or classes.
Step 4: Refine
Refine the query to include new expressions. Note that ClassInstanceExpr covers the new keyword in Java, which is exactly what we need.
Step 5: Add to Suite
Add the file to your repository and update your qls file to include this new query.
Step 6: Deploy Push the code to your repository, and the next CI run will automatically include this new check.
Not read yet
FAQ: Common Questions
Q: Can I write CodeQL queries for languages not officially supported? A: CodeQL supports a core set of languages (C/C++, C#, Go, Java, JavaScript, Python, Ruby, Swift). While you can theoretically write support for other languages, it is a massive undertaking that involves defining the entire relational schema for that language. Stick to the supported languages for most use cases.
Q: How do I debug a query that isn't returning results?
A: Start by simplifying the query. Remove the where clause to see if you get any results at all. Then, add back conditions one by one until you find the one that is filtering out your expected result. Use the "Evaluate" feature in the VS Code extension to inspect individual predicates.
Q: Should I run all my custom queries on every build? A: If your custom queries are well-optimized, yes. If you find that they significantly slow down your CI, consider running "deep" queries (those with complex taint analysis) only on pull requests or nightly builds, while keeping "fast" queries (pattern matching) in every build.
Not read yet
Key Takeaways for Success
- Treat Queries as Code: Custom CodeQL queries are not just configuration files; they are executable code. They require testing, peer review, and version control.
- Prioritize Precision: A low-volume, high-accuracy query is significantly more valuable than a high-volume, noisy one. Always work to reduce false positives.
- Leverage Taint Analysis: For any vulnerability involving user input, move beyond basic pattern matching and utilize CodeQL’s powerful taint analysis capabilities.
- Modularize for Reuse: Build a library of common security concepts (sources, sinks, sanitizers) within your organization to make writing future queries faster and more consistent.
- Integrate Early: The value of security scanning is realized when it happens as close to the developer's keyboard as possible. Integrate your custom queries into the CI/CD pipeline to provide immediate feedback.
- Continuous Improvement: As your application evolves, so should your queries. Periodically review your custom query suite to remove outdated rules and update them to reflect new internal frameworks or updated security standards.
- Document the "Why": Never provide a security finding without clear, actionable documentation that explains the risk and how to fix it. This turns security alerts into educational opportunities for your developers.
By following these principles, you can transform CodeQL from a generic security scanner into a specialized security auditor that understands your business's unique requirements. This shift is essential for building a mature, proactive security culture that empowers developers rather than hindering them.
Not read yet
Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.
Spend your points to unlock exam-style practice questions
Spend points to unlock GH-500 exam-style practice questions.
Practice for GH-500