Language-Specific Analysis

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

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

Lesson: Language-Specific Analysis in CodeQL

Introduction to Language-Specific Analysis

In the realm of static analysis, CodeQL stands out because it treats your source code as data. Instead of performing simple text pattern matching, CodeQL transforms your code into a relational database, allowing you to run complex queries against the structure, flow, and semantics of your application. While general security principles—like ensuring input is sanitized—apply across all programming languages, the way those principles are implemented varies drastically between a language like C++ and a language like JavaScript.

Language-specific analysis is the practice of tailoring your security queries to the unique idioms, memory models, and standard libraries of the language you are analyzing. A vulnerability in a Java application, such as an insecure deserialization flaw, looks nothing like a buffer overflow in C. If you attempt to write generic queries that ignore these language-specific nuances, you will inevitably deal with a high rate of false positives or, worse, miss critical vulnerabilities. Understanding how to leverage the specific features of the CodeQL language libraries is what separates a novice user from a security engineer who can effectively secure a complex codebase.

This lesson explores how to navigate the language-specific libraries in CodeQL. We will examine how different languages represent concepts like data flow, control flow, and API usage, and we will walk through the process of writing queries that are optimized for specific environments. By the end of this module, you will understand how to move beyond basic pattern matching and start writing sophisticated, context-aware security rules.

Not read yet

Understanding the CodeQL Library Hierarchy

CodeQL organizes its knowledge into libraries that mirror the structure of the target language. When you write a query for Java, you are interacting with the java.qll library, which provides access to classes like Method, Class, and Parameter. When you switch to Python, you use python.qll, which structures the database around different abstractions like Function, Module, and Attribute.

The core strength of this modular approach is that it abstracts away the complexity of the Abstract Syntax Tree (AST). You do not need to know the internal representation of every node in the AST to find a vulnerability; you only need to know the high-level classes provided by the language library. However, to write advanced queries, you must understand the specific abstractions that each language provides.

The Role of Data Flow Libraries

Most security queries rely on "Taint Analysis," which tracks how data moves from a source (where untrusted input enters the system) to a sink (where the data is used in a dangerous way). Every language library in CodeQL includes a DataFlow and a TaintTracking module, but the implementation details are language-specific.

For example, in C++, tracking data flow often involves managing pointers, references, and memory buffers. The CodeQL C++ library provides specific classes to handle these memory-level concerns. In contrast, JavaScript data flow analysis focuses on object properties, function closures, and asynchronous callbacks. Because these languages handle data differently, the configuration for your taint tracking—specifically your definition of sources, sinks, and sanitizers—must be adjusted to match the language's behavior.

Callout: The Importance of Modeling The most critical part of language-specific analysis is "modeling." Modeling refers to the process of defining which functions act as sources of untrusted data and which functions act as dangerous sinks. If you do not model your application’s unique frameworks (e.g., a custom logging library or a specific database wrapper), CodeQL will be blind to those data paths. Language-specific analysis requires you to map your application's custom logic to the general patterns CodeQL understands.

Not read yet

Java-Specific Analysis: Handling Enterprise Patterns

Java is a verbose, object-oriented language that relies heavily on frameworks like Spring, Hibernate, and Jakarta EE. Security analysis in Java often revolves around how these frameworks handle object lifecycle, dependency injection, and reflection.

Analyzing Reflection and Serialization

Java’s reflection API allows code to inspect and modify its own structure at runtime. While powerful, it is a common vector for security issues, such as arbitrary code execution. A generic query might miss reflection-based attacks because the method calls are resolved dynamically. To analyze reflection in Java, you must use the ReflectiveCall class provided in the CodeQL Java library.

Consider a scenario where an application uses Class.forName() to load a class based on user input. Here is how you might construct a query to identify this:

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

// Define the source: user input from a web request
class UserInputSource extends DataFlow::Node {
  UserInputSource() {
    this.asParameter().getCallable().getDeclaringType().hasName("HttpServletRequest")
  }
}

// Define the sink: the class name argument in Class.forName
class ReflectionSink extends DataFlow::Node {
  ReflectionSink() {
    exists(MethodAccess ma |
      ma.getMethod().hasName("forName") and
      ma.getMethod().getDeclaringType().hasQualifiedName("java.lang", "Class") and
      this.asExpr() = ma.getArgument(0)
    )
  }
}

// Data flow configuration
class ReflectionFlowConfig extends TaintTracking::Configuration {
  ReflectionFlowConfig() { this = "ReflectionFlowConfig" }
  override predicate isSource(DataFlow::Node source) { source instanceof UserInputSource }
  override predicate isSink(DataFlow::Node sink) { sink instanceof ReflectionSink }
}

This query is highly specific to Java's java.lang.Class structure. It tracks data from an HTTP request parameter directly into the reflection mechanism. By focusing on the MethodAccess node and the specific class name, we ensure the query is precise and avoids flagging legitimate, safe uses of reflection.

Not read yet

JavaScript and TypeScript: Dealing with Asynchrony

JavaScript and TypeScript introduce challenges related to their event-driven, asynchronous nature. Data does not always move linearly from line A to line B; it often jumps through callbacks, promises, and event emitters.

Tracking Data through Promises and Callbacks

In JavaScript, a common security pitfall is "Prototype Pollution." This happens when an attacker can influence the keys or values of an object's prototype, leading to unexpected behavior across the entire application. Because JavaScript objects are highly dynamic, tracking property assignments requires a deep understanding of how objects are merged and modified.

When writing a query for JavaScript, you must account for the difference between a traditional function call and an arrow function, or a promise chain. The CodeQL JavaScript library provides the DataFlow::Node class, which is designed to handle these asynchronous jumps.

Tip: Use the CodeQL Query Console When developing language-specific queries, use the "CodeQL Query Console" in your IDE. You can hover over code elements to see their type. If you are unsure whether an element is a MethodAccess or an InvokeExpr, the console will show you the exact AST class, saving you hours of trial and error.

Best Practices for JavaScript Analysis

  1. Understand the Environment: Are you analyzing Node.js or browser-based code? Node.js analysis requires modeling require() or import statements to track how dependencies bring in data. Browser analysis requires tracking DOM-based sinks like innerHTML or document.write.
  2. Handle Type Definitions (TypeScript): If you are analyzing TypeScript, leverage the type information. You can filter your results by checking if a variable has a specific interface or type, which significantly reduces noise.
  3. Watch for Object Merging: Many prototype pollution vulnerabilities occur in deep-merge utilities. Instead of tracking every object, focus your taint analysis on the recursive calls within these merge functions.

Not read yet

C and C++: Memory Safety and Pointer Arithmetic

C and C++ are fundamentally different from Java and JavaScript. The primary concerns here are memory corruption, buffer overflows, and integer overflows. Language-specific analysis for C++ must focus on pointer arithmetic and the lifecycle of allocated memory.

Analyzing Buffer Overflows

In C, a buffer overflow often happens when a function like strcpy or gets is used without bounds checking. Because C++ allows direct memory manipulation, your queries must account for the size of buffers and the length of the input being copied.

import cpp

// Find calls to dangerous functions
class DangerousFunctionCall extends FunctionCall {
  DangerousFunctionCall() {
    this.getTarget().hasName(["strcpy", "gets", "sprintf"])
  }
}

// Check if the destination buffer is smaller than the source
predicate isPotentialOverflow(FunctionCall fc) {
  exists(Expr dest, Expr src |
    dest = fc.getArgument(0) and
    src = fc.getArgument(1) and
    dest.getSize() < src.getSize() // Simplified logic
  )
}

This snippet highlights a crucial aspect of C++ analysis: you need to reach into the compiler-level metadata to understand the size of an array or a pointer. The getSize() predicate is a powerful tool provided by the C++ library that isn't present in the higher-level language libraries.

Common Pitfalls in C++ Analysis

  • Ignoring Pointer Aliasing: If you track a variable, remember that another pointer might be pointing to the same memory address. Advanced C++ queries must use "Alias Analysis" to ensure that the data flow is tracked correctly across different pointers.
  • Assuming Standard Library Behavior: Do not assume that memcpy will behave the same way in every project. If a project uses a custom memory management library, you must model those functions as well.

Warning: False Positives in C++ C++ is notorious for producing false positives in static analysis. Because so much of the language is "undefined behavior," CodeQL might flag code that seems dangerous but is actually protected by logic that the analyzer cannot see. Always verify your findings with a manual code review before suggesting a fix.

Not read yet

Python: Dynamic Typing and Library Dependencies

Python’s dynamic nature makes it both easy to write and difficult to analyze statically. Because the type of a variable can change at runtime, CodeQL uses "Type Inference" to guess what kind of object a variable might be.

Tracking Data in Web Frameworks

In Python, security analysis often targets web frameworks like Django or Flask. These frameworks have specific ways of handling requests and responses. A language-specific query for Python should target the framework's internal request objects rather than generic input sources.

When analyzing Python, focus on:

  • Import Statements: Track where modules are imported from, as this can indicate the use of potentially vulnerable external libraries.
  • Decorators: Many security checks in Python are implemented as decorators (e.g., @login_required). Your queries should be aware of these wrappers, as they often act as sanitizers or access control points.

Not read yet

Comparison Table: Language-Specific Focus Areas

Language Primary Security Concern Key CodeQL Library Feature
Java Insecure Deserialization, Reflection ReflectiveCall, TaintTracking
JavaScript Prototype Pollution, DOM XSS DataFlow::Node, Asynchronous tracking
C++ Buffer Overflow, Memory Corruption PointerAccess, getSize()
Python Injection (SQL/Command), Import Hijacking Attribute, Decorator tracking

Practical Steps for Building a Language-Specific Query

If you are tasked with building a custom security rule, follow this step-by-step process to ensure it is robust and accurate.

Step 1: Define the Scope

Before writing a single line of QL, identify the specific vulnerability you are trying to catch. Is it a specific function call? A pattern of object usage? A configuration flaw? Write down the "Source" (where the bad data enters) and the "Sink" (where the bad data causes harm).

Step 2: Explore the AST

Use the CodeQL database explorer in your IDE to look at the code you want to flag. Identify the classes that represent the nodes you are interested in. If you are targeting a function call, look for Call or MethodAccess classes. If you are targeting a variable assignment, look for Assignment classes.

Step 3: Draft the Data Flow

Create a TaintTracking configuration. Start by defining your isSource and isSink predicates. Keep them very restrictive at first to avoid false positives. You can always expand the definitions later.

Step 4: Add Sanitizers

If the analysis produces too many false positives, look for "sanitizers." A sanitizer is a function or a logical check that cleans the data. For example, if you are tracking SQL injection, a function that escapes special characters should be defined as a sanitizer in your configuration.

Step 5: Test and Refine

Run the query against a known vulnerable codebase and a known safe codebase. If the query flags safe code, examine the path to see why the data flow was considered "tainted." Adjust your predicates until the query produces clean, actionable results.

Not read yet

Best Practices for Maintaining CodeQL Queries

Writing a query is only the beginning. As your codebase evolves, your security queries must evolve with it.

  1. Modularize Your Queries: Don't write one massive query. Break your logic into separate libraries. For example, create a SecurityHelpers.qll file that contains your common sources and sinks, and import that into your specific security queries.
  2. Use Version Control: Treat your CodeQL queries like production code. Store them in a repository, use pull requests to review changes, and maintain a test suite (using the CodeQL testing framework) to ensure that updates don't break existing detection logic.
  3. Document the "Why": Every query should have a clear documentation header that explains what vulnerability it detects, why it is a problem, and how to fix it. This is essential for helping other team members understand the results.
  4. Prioritize High-Confidence Findings: If a query is prone to false positives, mark it as "low severity" or "warning" in your reporting dashboard. Reserve "critical" alerts for high-confidence queries that have been rigorously tested.

Callout: The "Why" of Static Analysis Static analysis is not meant to replace human review; it is meant to augment it. By automating the detection of common patterns, you free up your security team to focus on complex, architectural flaws that a machine cannot easily understand. Use CodeQL as a tool to shift security left, providing immediate feedback to developers as they write code.

Not read yet

Common Mistakes and How to Avoid Them

Even experienced security engineers fall into traps when writing CodeQL queries. Here are the most frequent mistakes and how to avoid them.

Over-Generalization

The biggest mistake is writing a query that is too broad. If you define every input from the web as a "source," you will get thousands of alerts, most of which are irrelevant.

  • The Fix: Be specific. Instead of tagging all HTTP parameters, tag only the parameters that are passed to dangerous APIs.

Missing Data Flow Across Files

CodeQL is powerful because it tracks data across the entire project. However, if your query is not configured to look at cross-file dependencies, it will miss vulnerabilities that span multiple modules.

  • The Fix: Ensure your query imports the necessary libraries and that the project database includes all relevant source files.

Forgetting About Configuration

Many modern applications use external configuration files (XML, YAML, JSON) to define behavior. If your query only looks at the source code, it might miss an attack vector that is enabled via a config file.

  • The Fix: Use CodeQL’s support for configuration files to pull data into your analysis. You can treat configuration settings as "sources" that influence the program's behavior.

Ignoring Implicit Data Flow

In languages like Java, data can flow through static initializers, constructors, and getters/setters. If you only look at direct function calls, you will miss these hidden paths.

  • The Fix: Use the built-in DataFlow library, which is designed to handle these implicit paths automatically. Avoid writing custom "manual" tracking logic unless absolutely necessary.

Not read yet

Summary of Key Takeaways

Language-specific analysis is the cornerstone of effective CodeQL security automation. By leveraging the unique idioms, libraries, and memory models of your target language, you can create high-precision queries that catch vulnerabilities that generic tools would ignore.

  • Context is King: Always tailor your sources, sinks, and sanitizers to the specific framework and language you are analyzing.
  • Library Hierarchy Matters: Understand the core abstractions of the language (e.g., MethodAccess in Java vs. FunctionCall in C++) to navigate the AST effectively.
  • Taint Analysis is a Tool, Not a Magic Bullet: Use TaintTracking configurations to map the movement of data, but always validate the results to manage false positives.
  • Model Your Frameworks: Generic queries will fail on custom enterprise frameworks. You must model your application-specific libraries for CodeQL to "see" them.
  • Maintainability is Essential: Treat your queries as software. Use version control, write tests, and document the rationale behind your detection logic.
  • Iterative Refinement: Start with a narrow, high-confidence query and expand it slowly based on the feedback from your test runs.
  • Focus on High-Impact Areas: Prioritize your analysis on the most sensitive parts of your application, such as authentication, authorization, and data handling layers.

By mastering these language-specific techniques, you move from simply running canned queries to building a custom security intelligence layer that deeply understands your organization’s unique technology stack. This proactive approach not only secures your code but also educates your development team on the specific pitfalls of the languages they work with every day.

Not read yet

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