Rediger

Del via


CodeQL and the Static Tools Logo Test

CodeQL and Driver Security

Microsoft is committed to mitigating the attack surface for the Windows operating system, and ensuring that third party drivers meet a strong security bar is critical to accomplishing that goal. One step in setting this security bar is the requirement to the Windows Hardware Compatibility Program (WHCP) which states that all driver submissions must use the CodeQL engine on driver source code and fix any violations that are deemed "Must-Fix".

CodeQL, by GitHub, is a powerful semantic code analysis engine, and the combination of an extensive suite of high-value security queries along with a robust platform make it an invaluable tool for securing driver code.

Usage of CodeQL for the purpose of WHCP testing is acceptable under the Hardware Lab Kit (HLK) End User License Agreement. For WHCP participants, the HLK's EULA overwrites GitHub's CodeQL Terms and Conditions by stating that CodeQL can be used during automated analysis, CI or CD, as part of normal engineering processes for the purposes of analyzing drivers to be submitted and certified as part of the WHCP.

The requirement to analyze driver source code and fix any "Must-Fix" violations will be enforced by the Static Tools Logo Test.

This topic describes how to:

  • Use CodeQL to analyze your driver source code for known high impact security issues.
  • Ensure the Static Tools Logo Test can consume the results of running CodeQL.
  • Determine which "Must-Fix" queries must be run for WHCP certification.

Important

Windows Hardware Compatibility Program requires CodeQL for Static Tool Logo (STL) Tests on our Client and Server Operating Systems. We will continue to maintain support for SDV and CA on older products. Partners are highly encouraged to review the CodeQL requirements for the Static Tool Logo Test.

HLK EULA and CodeQL

Usage of CodeQL for the purpose of certifying for the Windows Hardware Compatibility Program testing is acceptable under the Hardware Lab Kit (HLK) End User License Agreement. For WHCP participants, the HLK's EULA overwrites GitHub's CodeQL Terms and Conditions. The HLK EULA states that CodeQL can be used during automated analysis, CI or CD, as part of normal engineering processes for the purposes of analyzing drivers to be submitted and certified as part of the Windows Hardware Compatibility Program. For those following along for general use, read the GitHub CodeQL Terms and Conditions and/or contact CodeQL.

CodeQL Concepts

CodeQL is a static analysis engine used by developers to perform security analysis on code outside of a live environment. CodeQL ingests code while it is compiling, and builds a database from it. The database becomes a directory containing queryable data, a source reference, and log files. Once the database is built, one can run analysis on it by utilizing CodeQL queries (also called checks or rules) which will determine if the source code contains violations or security vulnerabilities. CodeQL provides a library of standard queries which check for language correctness, semantics, and provides great value to developers who wish to ensure their code is free of bugs and vulnerabilities.

CodeQL also provides the option to build custom queries. For more information on writing custom queries, see Writing queries in the CodeQL docs.

CodeQL also provides a CodeQL command line tool (CLI) to easily perform CodeQL actions and/or perform large scale analysis.

Supplementary CodeQL CLI documentation can be found at CodeQL Getting Started.

1. CodeQL Setup

For Windows Hardware Compatibility Program Use

Windows Hardware Compatibility Program Release Version Matrix

Use this matrix to determine the versions to be downloaded.

Windows Release CodeQL CLI version microsoft/windows-drivers QL pack version codeql/cpp-queries QL pack version Branch to use
Windows Server 2022 2.4.6 or 2.15.4 1.0.13 (If using codeql 2.15.4) 0.9.0 (If using codeql 2.15.4) WHCP_21H2
Windows 11 2.4.6 or 2.15.4 1.0.13 (If using codeql 2.15.4) 0.9.0 (If using codeql 2.15.4) WHCP_21H2
Windows 11, version 22H2 2.6.3 or 2.15.4 1.0.13 (If using codeql 2.15.4) 0.9.0 (If using codeql 2.15.4) WHCP_22H2
Windows 11, version 23H2 2.6.3 or 2.15.4 1.0.13 (If using codeql 2.15.4) 0.9.0 (If using codeql 2.15.4) WHCP_22H2
Windows 11, version 24H2 2.15.4 1.1.0 0.9.0 WHCP_24H2

A version of the QL pack is not specified for CodeQL CLI 2.4.6 and 2.6.3 because only newer versions of CodeQL support QL packs.

For General Use

For general use of CodeQL with other versions of Windows outside of the WHCP program, or for developing and testing queries, we currently recommend the following version and branch:

CodeQL CLI version microsoft/windows-drivers qlpack version codeql/cpp-queries version Branch to use
2.15.4 latest latest main

Download and Install CodeQL

Note

Visual Studio 17.8 broke compatibility with the older versions of CodeQL used in the WHCP_21H2 and WHCP_22H2 branches. CodeQL CLI version 2.15.4 has been validated for use with WHCP 21H2 and WHCP 22H2 when using Visual Studio 17.8 or greater. For the WHCP Program, use the CodeQL CLI version in accordance with the table above and Windows release you are certifying for - version 2.4.6, version 2.6.3, or version 2.15.4. For general use with the main branch, use CodeQL CLI version 2.15.4.

  1. Create a directory to contain CodeQL. This example uses C:\codeql-home\

    C:\> mkdir C:\codeql-home
    
  2. Refer to the tables above to select which version of CodeQL CLI to use in accordance with the desired branch of Microsoft's driver queries. If you are performing analysis as part of the WHCP program, refer to the table For Windows Hardware Compatibility Program Use otherwise use Main branch and 2.15.4. Using a different version may result in a database incompatible with the libraries.

  3. Navigate to the CodeQL CLI binaries release associated with the tables above, and download the zip file in accordance with your project's architecture. For example, for 64 bit Windows "codeql-win64.zip".

  4. Extract Codeql CLI directory to the one you just created, for example: C:\codeql-home\codeql.

  5. Verify CodeQL is installed correctly by checking the version:

     C:\codeql-home\codeql>codeql --version
     CodeQL command-line toolchain release 2.15.4.
     Copyright (C) 2019-2023 GitHub, Inc.
     Unpacked in: C:\codeql-home\codeql
         Analysis results depend critically on separately distributed query and
         extractor modules. To list modules that are visible to the toolchain,
         use 'codeql resolve qlpacks' and 'codeql resolve languages'.
    
  6. The help command displays command line usage information.

    C:\codeql-home\codeql\>codeql --help
    Usage: codeql <command> <argument>...
    Create and query CodeQL databases, or work with the QL language.
    
    GitHub makes this program freely available for the analysis of open-source software and certain other uses, but it is
    not itself free software. Type codeql --license to see the license terms.
    
          --license              Show the license terms for the CodeQL toolchain.
    Common options:
      -h, --help                 Show this help text.
      -v, --verbose              Incrementally increase the number of progress messages printed.
      -q, --quiet                Incrementally decrease the number of progress messages printed.
    Some advanced options have been hidden; try --help -v for a fuller view.
    Commands:
      query     Compile and execute QL code.
      bqrs      Get information from .bqrs files.
      database  Create, analyze and process CodeQL databases.
      dataset   [Plumbing] Work with raw QL datasets.
      test      Execute QL unit tests.
      resolve   [Deep plumbing] Helper commands to resolve disk locations etc.
      execute   [Deep plumbing] Low-level commands that need special JVM options.
      version   Show the version of the CodeQL toolchain.
      generate  Generate formatted QL documentation.
    

Install CodeQL Packages

For WHCP_21H2 and WHCP_22H2 branches

If using Visual Studio 2022 17.8 or greater with WHCP_21H2 or WHCP_22H2 and CodeQL CLI version 2.15.4:

  • Follow the steps for "ALL OTHER BRANCHES."
  • Make sure to remove the CodeQL submodule if you still have an old version of the repo cloned. CodeQL might try to use the queries in the submodule by default, which will cause errors because of mismatched versions.

If using Visual Studio version 17.7 or below AND either WHCP_21H2 or WHCP_22H2 AND CodeQL CLI version 2.4.6 or 2.6.3:

  • Follow Special instructions for WHCP_21H2 and WHCP_22H2 using VS17.7 or earlier below.

ALL OTHER BRANCHES

Download the CodeQL query packages

It is no longer necessary to clone the Windows-Driver-Developer-Supplemental-Tools repo to use the queries for certification. CodeQL packages ("QL packs" or "query packs") are now used.

  1. Download the correct version of the microsoft/windows-drivers pack from the Windows Hardware Compatibility Program Release Version Matrix. Specify the @<version> in the command below.
C:\codeql-home\> codeql pack download microsoft/windows-drivers@<version>

For examples, if using WHCP_24H2, run the following command to download the 1.1.0 windows-drivers query pack:

C:\codeql-home\> codeql pack download microsoft/windows-drivers@1.1.0

Use this command to download version 0.9.0 of the CodeQL cpp-queries query pack.

C:\codeql-home\> codeql pack download codeql/cpp-queries@0.9.0

(It is possible to skip the above step, as the --download option will download needed queries later in the analysis process.)

CodeQL installs the downloaded query packs to the default directory:

C:\Users\<current user>\.codeql\packages\microsoft\windows-drivers\<downloaded version>\

Do not change this directory or move the installed pack.

Download the Windows driver query suites

Locate and copy to the local PC the two primary query suite files.

  • windows-driver-recommended.qls
  • windows-driver-mustfix.qls

Their contents are shown below in Queries and Suites; the two files are located at https://github.com/microsoft/Windows-Driver-Developer-Supplemental-Tools/tree/main/suites

2. Build the CodeQL Database

These examples assume use of a Windows development environment and that the installation location is C:\codeql-home, but you can use the setup that suits you. See CodeQL supported languages and frameworks for a list of which compilers are supported.

  1. Create a directory for CodeQL to place the databases it creates. For example: C:\codeql-home\databases

    mkdir C:\codeql-home\databases
    
  2. Use the CodeQL command to create a database using the following parameters:

    • the first parameter is a link to your database directory. For example: C:\codeql-home\databases\MyDriverDatabase (this command will fail if the directory already exists).
    • --language or -l is the language or languages your source code is in (this can be a comma separated list; ex: [cpp, javascript]).
    • -- source or -s is the path to your source code.
    • --command or -c is your build command or the path to your build file.
    codeql database create <database directory> --language=<language> --source=<path to source code> --command=<build command or path to build file>
    

Examples

Single driver example.

C:\codeql-home\codeql> codeql database create D:\DriverDatabase --language=cpp --source-root=D:\Drivers\SingleDriver --command="msbuild /t:rebuild D:\Drivers\SingleDriver\SingleDriver.sln"

Multiple drivers example.

C:\codeql-home\codeql> codeql database create D:\SampleDriversDatabase --language=cpp --source-root=D:\AllMyDrivers\SampleDrivers --command=D:\AllMyDrivers\SampleDrivers\BuildAllSampleDrivers.cmd

For more information or help using the database create command, go to Creating CodeQL Databases or use the following command:

C:\codeql-home\codeql> codeql database create --help

3. Perform Analysis

Note

If using Visual Studio version 17.7 or below AND either WHCP_21H2 or WHCP_22H2 AND CodeQL VLI version 2.4.6 or 2.6.3, follow Special instructions for WHCP_21H2 and WHCP_22H2 using VS17.7 or earlier below.

At this point, the set-up is complete and the next step is to perform the actual analysis on the driver source code.

  1. Use the CodeQL command to analyze your database using the following parameters:

    • the first parameter is a link to your database directory. For example: C:\codeql-home\databases\MyDriverDatabase. (This command will fail if the directory doesn't exist.)
    • --download flag tells CodeQL to download dependencies before running the queries.
    • --format is the file type of the output file. Options include: SARIF and CSV. (For WHCP Users use SARIF format.)
    • --output is the path to where you want the output file, be sure to include the format in the file name. (This command will fail if the directory doesn't already exist.)
    • the query specifiers parameter is a space separated list of arguments which can include:
      • a path to a query file
      • a path to a directory containing query files
      • a path to a query suite file
      • the name of a CodeQL query pack
    codeql database analyze --download <path to database> <path to query suite .qls file> --format=sarifv2.1.0 --output=<outputname>.sarif
    

    Example:

    codeql database analyze --download D:\DriverDatabase suites/windows-driver-recommended.qls --format=sarifv2.1.0 --output=D:\DriverAnalysis1.sarif 
    

    For more information or help using the database analyze command, go to Analyzing Databases with the CodeQL CLI and Using a CodeQL pack to analyze a CodeQL database.

    For command line help use the following command:

    C:\codeql-home\codeql> codeql database analyze --help
    

Special instructions for WHCP_21H2 and WHCP_22H2 using VS17.7 or earlier

These instructions only apply when using both Visual Studio 17.7 or earlier, along with CodeQL 2.6.3 or 2.4.6

  1. Install CodeQL version as indicated in above steps.

  2. Clone and install the Windows Driver Developer Supplemental Tools repository which contains the CodeQL queries specific for drivers:

    git clone https://github.com/microsoft/Windows-Driver-Developer-Supplemental-Tools.git --recurse-submodules

  3. Refer to the Windows Hardware Compatibility Program Release Version Matrix to identify the correct branch for the version of Windows you wish to certify for.

  4. Use the git checkout command to checkout the identified branch.

  5. Confirm that the submodules are present in the codeql-home directory.

     D:/codeql-home
         |--- codeql
         |--- Windows-Driver-Developer-Supplemental-Tools
    
  6. Analyze your CodeQL database.

    Update this example command to match your environment. Set the parameters, path to new database, format, output sarif file, path to CodeQL query or query suite to use in analysis.

    codeql database analyze <path to database> --format=sarifv2.1.0 --output=<"path to output file".sarif> <path to query/suite to run>

    Example:

    codeql database analyze D:\DriverDatabase --format=sarifv2.1.0 --output=D:\DriverAnalysis1.sarif D:\codeql-home\Windows-driver-developer-supplemental-tools\src\suites\windows_driver_mustfix.qls

    Be sure to check the path to the suite or query you want to run, not every branch has the same file structure.

  7. Refer to other guidance in this document for next steps, such as reviewing and submitting test results.

4. View and Interpret Results

We will be focusing on SARIF format for this section as it is what is required for the following steps, though you are welcome to use CSV format if it suits your needs better.

Static Analysis Results Interchange Format (SARIF) is a JSON type format used for sharing static analysis results. Read more about the standard at OASIS Static Analysis Results Interchange Format (SARIF), how CodeQL uses SARIF Output, and the schema json.

There are several methods for interpreting the analysis results, including manually sorting through the objects. Here are a few that we use:

  • The Microsoft Sarif Viewer (Web) has functionality which allows you to drag and drop your SARIF file into the viewer, then displays results categorized by rule. This is a very quick and easy way to see the count of violations or which queries have violations, but less easy to find source code information aside from the line number. Note that the page will not update if there are no violations.

  • The Microsoft SARIF Viewer for Visual Studio is great for displaying the results within Visual Studio for seamless transition from results to source code.

  • The SARIF extension for Visual Studio Code

The most important section of the SARIF file is the "Results" property within the "Run" object. Each query will have a Results property with details about any detected violations and where it occurred. If no violations are found, the property value will be empty.

Queries are classified using statuses such as "error" "warning" and "problem" but this classification is separate from how the Windows Hardware Compatibility Program and specifically the Static Tools Logo Test will grade the results. Any driver with defects from any query within the "Must-Fix" suite will not pass the Static Tools Logo Test and will fail to be certified, regardless of the query classification in the raw query file (ex. "warning").

5. Suppressing CodeQL Results (Optional)

CodeQL for drivers supports suppressing results. Suppressions are currently provided as a convenience to help developers triage issues and reduce noise, not as a way to bypass the must-fix checks. They have no impact on generating a Driver Verification Log or passing the Static Tools Logo test at this time. To use suppressions, you must run the DriverAlertSuppression.ql query at the same time as the other queries or suites you wish to run. By default, this query is enabled when running our suites from our githubs main/development branch.

For checks that have been ported from Code Analysis, existing Code Analysis suppressions will be honored. For more information, see C++ warning pragma.

  • Known limitation: You cannot combine a #pragma(disable) and #pragma(suppress) in the same line at this time.

For checks that are new to CodeQL, you can suppress them by doing one of two things:

  • Write a “#pragma(suppress:the-rule-id-here)” annotation (minus quotes) on the line above the violation, as you would for Code Analysis. “the-rule-id-here” can be replaced by the @id value in a given query’s metadata, viewable at the top of the file.

  • Write a comment on the line above comprised of the text “lgtm[the-rule-id-here]” (minus quotes). You will need to run the standard C/C++ alert suppression query instead of the driver alert suppression query.

Once a suppression is present and recognized, the resulting SARIF file will include data that a result was suppressed, and most result viewers will not show the result by default.

6. Convert SARIF to Driver Verification Log Format (DVL)

The Static Tools Logo Test parses a Driver Verification Log (DVL) which is the compiled results from several static analysis engines which have run on the driver source code. There are three ways to convert your SARIF file to DVL format, select the one that best fits your setup.

Using Visual Studio (WDK Preview Build 20190 and up)

  1. Place your SARIF results file in the same directory as your .vcxproj file.
  2. From the Driver extension menu, select Create Driver Verification Log.
  3. Verify the DVL UI detects your SARIF file.
    • Note: if you moved your SARIF file to the .vcxproj directory using the Visual Studio UI, it is possible Visual Studio created a reference to the SARIF file instead of actually moving it. Try opening the directory outside of Visual Studio to ensure it truly exists there.
  4. Select Create.

Using MSBuild

  1. Place your SARIF results file in the same directory as your .vcxproj file.

  2. Open your Visual Studio Command Prompt, Visual Studio Native Tools Command Prompt, or the Enterprise Windows Driver Kit (EWDK).

  3. Use the msbuild command with the following parameters:

    • path to vcx project file
    • /target:dvl
    • /p:Configuration="Release"
    • /P:Platform=<platform> (Use one of the following strings only: x86, x64, arm, arm64)

    msbuild.exe <vcxprojectfile> /target:dvl /p:Configuration="Release" /P:Platform=<platform>

Using CMD

  1. Locate the dvl.exe from the WDK or a mounted eWDK.

  2. Use the exe with the following parameters:

    • /manualCreate
    • driver name (Do not include the .sys file format)
    • driver architecture (Use one of the following strings only: x86, x64, arm, arm64)

    "C:\Program Files (x86)\Windows Kits\10\Tools\dvl\dvl.exe" /manualCreate <driver name> <driver architecture>

Further instructions for the Static Tools Logo HLK Test and guidance on where to place the DVL file can be found in Running the test.

7. Visual Studio Post-Build Event (Optional)

If you are building the driver using Visual Studio, you can configure CodeQL queries to run as a post build event.

In this example, a small batch file is created in the target location and called as a post build event. For more information about Visual Studio C++ build events, see Specifying build events.

  1. Create a small batch file which re-creates the CodeQL database then runs the desired queries on it. In this example, the batch file will be named RunCodeQLRebuildQuery.bat. Modify the paths shown in the example batch file to match your directory locations.

    ECHO ">>> Running CodeQL Security Rule V 1.0 <<<"
    ECHO ">>> Removing previously created rules database <<<"
    rmdir /s/q C:\codeql-home\databases\kmdf
    CALL C:\codeql-home\codeql\codeql\codeql.cmd database create -l=cpp -s="C:\codeql-home\drivers\kmdf" -c "msbuild /p:Configuration=Release /p:Platform=x64 C:\codeql-home\drivers\kmdf\kmdfecho.sln /t:rebuild /p:PostBuildEventUseInBuild=false " "C:\codeql-home\databases\kmdf" -j 0
    CALL C:\codeql-home\codeql\codeql\codeql database analyze "C:\codeql-home\databases\kmdf" "C:\codeql-home\Windows-Driver-Developer-Supplemental-Tools\codeql\codeql-queries\cpp\ql\src\Likely Bugs\Underspecified Functions" --format=sarifv2.1.0 --output=C:\codeql-home\databases\kmdf.sarif -j 0 --rerun
    ECHO ">>> Loading SARIF Results in Visual Studio <<<"
    CALL devenv /Edit C:\codeql-home\databases\kmdf.sarif
    SET ERRORLEVEL = 0
    
  2. The devenv.exe / Edit option is used in the batch file to open the SARIF results file in the existing instance of Visual Studio. To view the SARIF results install the Microsoft SARIF Viewer for Visual Studio and refer to the instructions there for more information.

  3. In the driver project, navigate to project properties. In the Configuration pull down, select the build configuration that you wish to check with CodeQL, we recommend "Release. Creating the CodeQL database and running the queries takes a few minutes, so we don't recommend you run CodeQL on the Debug configuration of your project.

  4. Select Build Events and Post-Build Event in the driver project properties.

  5. Provide a path to the batch file and a description of the post build event.

Visual Studio post build event configuration showing a batch file configured as a command line option.

  1. The results from the running the batch file will be displayed at the end of the build output.

    1>Starting evaluation of codeql-cpp\Likely Bugs\Underspecified Functions\MistypedFunctionArguments.ql.
    1>Starting evaluation of codeql-cpp\Likely Bugs\Underspecified Functions\TooManyArguments.ql.
    1>Starting evaluation of codeql-cpp\Likely Bugs\Underspecified Functions\TooFewArguments.ql.
    1>Starting evaluation of codeql-cpp\Likely Bugs\Underspecified Functions\ImplicitFunctionDeclaration.ql.
    1>[1/4 eval 4.4s] Evaluation done; writing results to codeql-cpp\Likely Bugs\Underspecified Functions\TooManyArguments.bqrs.
    1>[2/4 eval 4.4s] Evaluation done; writing results to codeql-cpp\Likely Bugs\Underspecified Functions\TooFewArguments.bqrs.
    1>[3/4 eval 4.5s] Evaluation done; writing results to codeql-cpp\Likely Bugs\Underspecified Functions\ImplicitFunctionDeclaration.bqrs.
    1>[4/4 eval 5.2s] Evaluation done; writing results to codeql-cpp\Likely Bugs\Underspecified Functions\MistypedFunctionArguments.bqrs.
    1>Shutting down query evaluator.
    1>Interpreting results.
    1>">>> Loading SARIF Results in Visual Studio <<<"
    

Troubleshooting

If you are certifying with WHCP, first ensure you are using the HLK version associated with the Windows release you are targeting, the associated branch in the Windows Driver Developer Supplemental Tools repository, and the subsequent CodeQL CLI version. For HLK/Windows Release compatibility matrix, see Windows Hardware Lab Kit and for Windows Release/Windows Driver Developer Supplemental Tools repo branch/CodeQL CLI version, see the WHCP table in the CodeQL Setup section.

Errors and Workarounds

For database version mismatches issues, the following tools may be helpful.

Use the codeql version command to display the version of the codeql exe.

C:\codeql-home\codeql\>codeql version
CodeQL command-line toolchain release 2.4.0.
Copyright (C) 2019-2020 GitHub, Inc.
Unpacked in: C:\codeql-home\codeql\
   Analysis results depend critically on separately distributed query and
   extractor modules. To list modules that are visible to the toolchain,
   use 'codeql resolve qlpacks' and 'codeql resolve languages'.

The database upgrade command will update a database. Be aware that this is a one way upgrade and is not reversible. For more information, see database upgrade.

Queries and Suites

As part of the Microsoft CodeQL GitHub repository, we provide two query suites to simplify the end-to-end driver developer workflow. The windows_driver_recommended.qls query suite is a superset of all the queries Microsoft has deemed valuable for driver developers. The windows_driver_mustfix.qls query suite contains queries deemed "Must-Fix" for WHCP certification, which must be run and passed in order to pass the Static Tools Logo Test. Both the Must-Fix and Recommended query suites are updated regularly.

Must-Fix Queries

The subset of queries below are Must-Fix for WHCP certification and are also included in the Recommended Fix suite.

This set of rules is included in windows_driver_mustfix.qls.

ID Location Common Weakness Enumeration
cpp/bad-addition-overflow-check codeql/cpp-queries/<Version>/Likely Bugs/Arithmetic/BadAdditionOverflowCheck.ql CWE-190, CWE-192
cpp/pointer-overflow-check codeql/cpp-queries/<Version>/Likely Bugs/Memory Management/PointerOverflow.ql N/A
cpp/too-few-arguments codeql/cpp-queries/<Version>/Likely Bugs/Underspecified Functions/TooFewArguments.ql N/A
cpp/comparison-with-wider-type codeql/cpp-queries/<Version>/Security/CWE/CWE-190/ComparisonWithWiderType.ql CWE-190, CWE-197, CWE-835
cpp/hresult-boolean-conversion codeql/cpp-queries/<Version>/Security/CWE/CWE-253/HResultBooleanConversion.ql CWE-253

The windows_driver_mustfix.qls file contains these must fix code queries.

# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.

- description: Security queries required to fix when certifying Windows Drivers
- queries: . 
  from: codeql/cpp-queries
  version: 0.9.0
- include:
    query path: 
      - Likely Bugs/Arithmetic/BadAdditionOverflowCheck.ql
      - Likely Bugs/Memory Management/PointerOverflow.ql
      - Likely Bugs/Underspecified Functions/TooFewArguments.ql
      - Security/CWE/CWE-190/ComparisonWithWiderType.ql
      - Security/CWE/CWE-253/HResultBooleanConversion.ql
- import: windows-driver-suites/windows_mustfix_partial.qls
  from: microsoft/windows-drivers

This set of rules is included in windows-driver-suites/windows_mustfix_partial.qls.

ID Location Common Weakness Enumeration
cpp/windows/wdk/deprecated-api /microsoft/windows-drivers/<Version>/drivers/general/queries/WdkDeprecatedApis/wdk-deprecated-api.ql N/A
microsoft/Security/CWE/CWE-704/WcharCharConversionLimited /microsoft/windows-drivers/<Version>/microsoft/Security/CWE/CWE-704/WcharCharConversionLimited.ql CWE-704

The windows_mustfix_partial.qls file contains these must fix code queries.

# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.

- description: Security queries required to fix when certifying Windows Drivers
- queries: .
  from: microsoft/windows-drivers
- include:
    query path: 
      - drivers/general/queries/WdkDeprecatedApis/wdk-deprecated-api.ql
      - microsoft/Security/CWE/CWE-704/WcharCharConversionLimited.ql

These queries are part of the windows_driver_recommended.qls query suite in the Microsoft GitHub CodeQL repository. The "Common Weakness Enumeration" (CWE) column specifies what kinds of security issues the given query searches for. See Mitre's page on CWE for more details around CWEs.

Best Practices

ID Location Common Weakness Enumeration
cpp/offset-use-before-range-check codeql/cpp-queries/<Version>/Best Practices/Likely Errors/OffsetUseBeforeRangeCheck.ql N/A

Likely Bugs

ID Location Common Weakness Enumeration
cpp/bad-addition-overflow-check codeql/cpp-queries/<Version>/Likely Bugs/Arithmetic/BadAdditionOverflowCheck.ql CWE-190, CWE-192
cpp/integer-multiplication-cast-to-long codeql/cpp-queries/<Version>/Likely Bugs/Arithmetic/IntMultToLong.ql CWE-190, CWE-192, CWE-197, CWE-681
cpp/signed-overflow-check codeql/cpp-queries/<Version>/Likely Bugs/Arithmetic/SignedOverflowCheck.ql N/A
cpp/upcast-array-pointer-arithmetic codeql/cpp-queries/<Version>/Likely Bugs/Conversion/CastArrayPointerArithmetic.ql CWE-119, CWE-843
cpp/pointer-overflow-check codeql/cpp-queries/<Version>/Likely Bugs/Memory Management/PointerOverflow.ql N/A
cpp/too-few-arguments codeql/cpp-queries/<Version>/Likely Bugs/Underspecified Functions/TooFewArguments.ql N/A
cpp/incorrect-not-operator-usage codeql/cpp-queries/<Version>/Likely Bugs/Likely Typos/IncorrectNotOperatorUsage.ql CWE-480
cpp/suspicious-add-sizeof codeql/cpp-queries/<Version>/Likely Bugs/Memory Management/SuspiciousSizeof.ql CWE-468
cpp/uninitialized-local codeql/cpp-queries/<Version>/Likely Bugs/Memory Management/UninitializedLocal.ql CWE-457, CWE-665

Security

ID Location Common Weakness Enumeration
cpp/conditionally-uninitialized-variable codeql/cpp-queries/<Version>/Security/CWE/CWE-457/ConditionallyUninitializedVariable.ql. CWE-457
cpp/unterminated-variadic-call codeql/cpp-queries/<Version>/Security/CWE/CWE-121/UnterminatedVarargsCall.ql CWE-121
cpp/suspicious-pointer-scaling codeql/cpp-queries/<Version>/Security/CWE/CWE-468/IncorrectPointerScaling.ql CWE-468
cpp/suspicious-pointer-scaling-void codeql/cpp-queries/<Version>/Security/CWE/CWE-468/IncorrectPointerScalingVoid.ql CWE-468
cpp/potentially-dangerous-function codeql/cpp-queries/<Version>/Security/CWE/CWE-676/PotentiallyDangerousFunction.ql CWE-676
cpp/incorrect-string-type-conversion codeql/cpp-queries/<Version>/Security/CWE/CWE-704/WcharCharConversion.ql CWE-704
cpp/comparison-with-wider-type codeql/cpp-queries/<Version>/Security/CWE/CWE-190/ComparisonWithWiderType.ql CWE-190, CWE-197, CWE-835
cpp/hresult-boolean-conversion codeql/cpp-queries/<Version>/Security/CWE/CWE-253/HResultBooleanConversion.ql CWE-253
cpp/suspicious-add-sizeof codeql/cpp-queries/<Version>/Security/CWE/CWE-468/CWE-468/SuspiciousAddWithSizeof.ql CWE-468

The windows_driver_recommended.qls file contains these recommended code queries.

# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.

- description: Recommended and required queries for Windows Drivers.
- import: windows-driver-suites/windows_mustfix_partial.qls
  from: microsoft/windows-drivers
- import: windows-driver-suites/windows_recommended_partial.qls
  from: microsoft/windows-drivers
- queries: . 
  from: codeql/cpp-queries
  version: 0.9.0
- include:
    query path: 
      - Best Practices/Likely Errors/OffsetUseBeforeRangeCheck.ql
      - Likely Bugs/Arithmetic/IntMultToLong.ql
      - Likely Bugs/Arithmetic/SignedOverflowCheck.ql
      - Likely Bugs/Conversion/CastArrayPointerArithmetic.ql
      - Likely Bugs/Likely Typos/IncorrectNotOperatorUsage.ql
      - Likely Bugs/Memory Management/SuspiciousSizeof.ql
      - Likely Bugs/Memory Management/UninitializedLocal.ql
      - Security/CWE/CWE-121/UnterminatedVarargsCall.ql
      - Security/CWE/CWE-457/ConditionallyUninitializedVariable.ql
      - Security/CWE/CWE-468/IncorrectPointerScaling.ql
      - Security/CWE/CWE-468/IncorrectPointerScalingVoid.ql
      - Security/CWE/CWE-468/SuspiciousAddWithSizeof.ql
      - Security/CWE/CWE-676/PotentiallyDangerousFunction.ql
      - Security/CWE/CWE-704/WcharCharConversion.ql
      - Likely Bugs/Arithmetic/BadAdditionOverflowCheck.ql
      - Likely Bugs/Memory Management/PointerOverflow.ql
      - Likely Bugs/Underspecified Functions/TooFewArguments.ql
      - Security/CWE/CWE-190/ComparisonWithWiderType.ql
      - Security/CWE/CWE-253/HResultBooleanConversion.ql

These queries are part of windows_recommended_partial.qls.

ID Location Common Weakness Enumeration
cpp/paddingbyteinformationdisclosure microsoft/windows-drivers/<Version>/microsoft/Likely Bugs/Boundary Violations/PaddingByteInformationDisclosure.ql N/A
cpp/badoverflowguard microsoft/windows-drivers/<Version>/microsoft/Likely Bugs/Conversion/BadOverflowGuard.ql N/A
cpp/infiniteloop microsoft/windows-drivers/<Version>/microsoft/Likely Bugs/Conversion/InfiniteLoop.ql N/A
cpp/uninitializedptrfield microsoft/windows-drivers/<Version>/microsoft/Likely Bugs/UninitializedPtrField.ql N/A
cpp/use-after-free microsoft/windows-drivers/<Version>/microsoft/Likely Bugs/Memory Management/UseAfterFree/UseAfterFree.ql N/A
ID Location Code Analysis Warning
cpp/weak-crypto/cng/hardcoded-iv /microsoft/windows-drivers/<Version>/microsoft/Security/Crytpography/HardcodedIVCNG.ql N/A

Drivers - General

ID Location Code Analysis Warning
cpp/drivers/ke-set-event-pageable /microsoft/windows-drivers/<Version>/drivers/general/queries/KeSetEventPageable/KeSetEventPageable.ql No associated CA check
cpp/drivers/role-type-correctly-used /microsoft/windows-drivers/<Version>/drivers/general/queries/RoleTypeCorrectlyUsed/RoleTypeCorrectlyUsed.ql No associated CA check
cpp/drivers/extended-deprecated-apis /microsoft/windows-drivers/<Version>/drivers/general/queries/ExtendedDeprecatedApis.ql C28719 Warning, C28726 Warning, C28735 Warning, C28750 Warning
cpp/drivers/irql-not-saved /microsoft/windows-drivers/<Version>/drivers/general/queries/IrqlNotSaved/IrqlNotSaved.ql C28158 Warning
cpp/drivers/irql-not-used /microsoft/windows-drivers/<Version>/drivers/general/queries/IrqlNotUsed/IrqlNotUsed.ql C28157 Warning
cpp/drivers/irql-set-too-high /microsoft/windows-drivers/<Version>/drivers/general/queries/IrqlTooHigh/IrqlTooHigh.ql C28150 Warning
cpp/drivers/irql-too-low /microsoft/windows-drivers/<Version>/drivers/general/queries/IrqlTooLow/IrqlTooLow.ql C28120 Warning
cpp/drivers/irql-set-too-high /microsoft/windows-drivers/<Version>/drivers/general/queries/IrqlSetTooHigh/IrqlTooHigh.ql C28121 Warning
cpp/drivers/irql-set-too-low /microsoft/windows-drivers/<Version>/drivers/general/queries/IrqlSetTooLow/IrqlSetTooLow.ql C28124 Warning
cpp/drivers/pool-tag-integral /microsoft/windows-drivers/<Version>/drivers/general/queries/PoolTagIntegral/PoolTagIntegral.ql C28134 Warning
cpp/drivers/str-safe /microsoft/windows-drivers/<Version>/drivers/general/queries/StrSafe/StrSafe.ql C28146 Warning

Drivers - WDM

ID Location Code Analysis Warning
cpp/drivers/illegal-field-access /microsoft/windows-drivers/<Version>/drivers/wdm/queries/IllegalFieldAccess/IllegalFieldAccess.ql C28128 Warning
cpp/drivers/illegal-field-access2 /microsoft/windows-drivers/<Version>/drivers/wdm/queries/IllegalFieldAccess2/IllegalFieldAccess2.ql C28175 Warning
cpp/drivers/illegal-field-write /microsoft/windows-drivers/<Version>/drivers/wdm/queries/IllegalFieldWrite/IllegalFieldWrite.ql C28176 Warning
cpp/drivers/opaque-mdl-use /microsoft/windows-drivers/<Version>/drivers/wdm/queries/OpaqueMdlUse/OpaqueMdlUse.ql (No associated CA check)
cpp/drivers/opaque-mdl-write /microsoft/windows-drivers/<Version>/drivers/wdm/queries/OpaqueMdlUse/OpaqueMdlWrite.ql C28145 Warning
cpp/drivers/pending-status-error /microsoft/windows-drivers/<Version>/drivers/wdm/queries/PendingStatusError/PendingStatusError.ql C28143 Warning
cpp/drivers/wrong-dispatch-table-assignment /microsoft/windows-drivers/<Version>/drivers/wdm/queries/WrongDispatchTableAssignment/WrongDispatchTableAssignment.ql C28169 Warning

The windows-driver-suites/windows_recommended_partial.qls file contains these recommended code queries.

# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.

- description: Recommended and required queries for Windows Drivers.
- import: windows-driver-suites/windows_mustfix_partial.qls
- queries: .
  from: microsoft/windows-drivers
- include:
    query path: 
      - microsoft/Likely Bugs/Boundary Violations/PaddingByteInformationDisclosure.ql
      - microsoft/Likely Bugs/Conversion/BadOverflowGuard.ql
      - microsoft/Likely Bugs/Conversion/InfiniteLoop.ql
      - microsoft/Likely Bugs/Memory Management/UseAfterFree/UseAfterFree.ql
      - microsoft/Likely Bugs/UninitializedPtrField.ql
      - microsoft/Security/Crytpography/HardcodedIVCNG.ql
      - drivers/general/queries/KeSetEventPageable/KeSetEventPageable.ql
      - drivers/general/queries/RoleTypeCorrectlyUsed/RoleTypeCorrectlyUsed.ql
      - drivers/general/queries/DefaultPoolTag/DefaultPoolTag.ql
      - drivers/general/queries/ExaminedValue/ExaminedValue.ql
      - drivers/general/queries/ExtendedDeprecatedApis/ExtendedDeprecatedApis.ql
      - drivers/general/queries/IrqlNotSaved/IrqlNotSaved.ql
      - drivers/general/queries/IrqlNotUsed/IrqlNotUsed.ql
      - drivers/general/queries/IrqlTooHigh/IrqlTooHigh.ql
      - drivers/general/queries/IrqlTooLow/IrqlTooLow.ql
      - drivers/general/queries/IrqlSetTooHigh/IrqlTooHigh.ql
      - drivers/general/queries/IrqlSetTooLow/IrqlSetTooLow.ql
      - drivers/general/queries/PoolTagIntegral/PoolTagIntegral.ql
      - drivers/general/queries/StrSafe/StrSafe.ql
      - drivers/wdm/queries/IllegalFieldAccess/IllegalFieldAccess.ql
      - drivers/wdm/queries/IllegalFieldAccess2/IllegalFieldAccess2.ql
      - drivers/wdm/queries/IllegalFieldWrite/IllegalFieldWrite.ql
      - drivers/wdm/queries/OpaqueMdlUse/OpaqueMdlUse.ql
      - drivers/wdm/queries/OpaqueMdlUse/OpaqueMdlWrite.ql
      - drivers/wdm/queries/PendingStatusError/PendingStatusError.ql
      - drivers/wdm/queries/WrongDispatchTableAssignment/WrongDispatchTableAssignment.ql

Frequently Asked Questions (FAQ's)

When will this be required for device certification?

See the Windows Hardware Compatibility Program Certification Process to for requirement details.

What is the motivation behind requiring CodeQL be run on driver source code?

The motivation for requiring CodeQL to be run on driver source code can be summarized by two main reasons:

  1. Security of Windows is paramount and requiring CodeQL to be run on driver source code is one step in helping improve the security of components which get certified by Microsoft.
  2. CodeQL queries are actively developed by security engineers at Microsoft, as Microsoft is committed to ensuring that its hardware ecosystem benefits from the same high-quality tooling that is used at Microsoft.

What types of drivers do CodeQL and the Static Tools Logo test apply to?

At present, the Static Tools Logo test requires that CodeQL be run and the "Must-Fix" set of queries passed for all kernel-mode drivers excluding graphics drivers. Note that running CodeQL on graphics drivers is highly recommended even though it is not currently required. Some queries may also find useful defects in user-mode components.

We anticipate extending the test and its queries to require results for graphics drivers, user-mode drivers and driver components, and other driver package components in the future. If you encounter unexpected behavior or false positives running CodeQL on graphics drivers or user-mode drivers, please file an issue on the Windows-Driver-Developer-Supplemental-Tools repo.

Which license governs the usage of CodeQL for driver developers?

Usage of CodeQL for the purpose of WHCP testing is acceptable under the Hardware Lab Kit (HLK) End User License Agreement. For WHCP participants, the HLK's EULA overwrites GitHub's CodeQL Terms and Conditions. The HLK EULA states that CodeQL can be used during automated analysis, CI or CD, as part of normal engineering processes for the purposes of analyzing drivers to be submitted and certified as part of the WHCP.

Do I need to use Visual Studio or msbuild to run CodeQL?

CodeQL does not require MSBuild or Visual Studio to be used. See supported languages and frameworks for a list of which compilers are supported.

How does the HLK verify that my driver was scanned by CodeQL?

The Static Tools Logo Test in the HLK is the test that enforces this requirement. Details on the Static Tools Logo Test can be found on its MS Docs page.

Are all defects reported by CodeQL true defects?

Every CodeQL query has varying levels of precision. Our goal is to minimize false positives, but occasionally they will occur. Our suite of "Must-Fix" queries have been developed and hand-picked for use with the WHCP program because our extensive testing results in nearly zero false positives. If you are seeing false positives from a query in the set of "Must-Fix" queries, email stlogohelp@microsoft.com immediately or file an issue on the Windows-Driver-Developer-Supplemental-Tools repo, and we will work to get it resolved as soon as possible.

Does a query's classification of either "warning" or "error" matter for the purposes of the Static Tools Logo Test?

Queries are classified using statuses such as "error" "warning" and "problem" in CodeQL but this classification is separate from how the Windows Hardware Compatibility Program and specifically the Static Tools Logo Test will grade the results. Any driver with defects from any query within the "Must-Fix" suite will not pass the Static Tools Logo Test and will fail to be certified, regardless of the query classification in the raw query file (ex. "warning").

Can I generate a DVL on Visual Studio solutions?

No, DVL generation must be run at the project level and cannot be run on Visual Studio solutions. Instructions for how to generate a DVL can be found at: Creating a Driver Verification Log.

Can I generate a Driver Verification Log (DVL) outside of the context of msbuild or Visual Studio?

As part of the Windows Driver Kit (WDK) and Enterprise WDK (eWDK), Microsoft ships a component called dvl.exe which can be used to generate Driver Verification Logs (DVLs). Starting in WDK/eWDK preview versions 21342 and above, it is possible to generate a DVL from the command line outside of the context of msbuild or Visual Studio by passing a driver name and architecture. See Creating a Driver Verification Log for more details.

I have comments or questions around how to use CodeQL on my driver, where do I send feedback?

Send feedback and questions to stlogohelp@microsoft.com.