跳转到主要内容

SARIF工具

项目描述

SARIF工具

一套用于处理SARIF文件的命令行工具和Python库。

有关SARIF格式的更多信息,请参阅此处:sarifweb.azurewebsites.net

安装

先决条件

您需要安装Python 3.8或更高版本。从python.org获取它。此文档假定python命令运行该版本。

在Windows上安装

打开用户命令提示符并输入

pip install sarif-tools

检查是否有如下警告:

WARNING: The script sarif.exe is installed in 'C:\tools\Python38\Scripts' which is not on PATH.

进入Windows设置,搜索“env”(编辑您的账户环境变量)并添加缺失的路径到PATH变量中。您需要打开一个新的终端或重新启动,然后可以在命令提示符中输入sarif --version

要为所有用户全局安装,如果愿意承担安全风险,请使用管理员命令提示符。

在Linux或Mac上安装

pip install sarif-tools

检查是否有如下警告:

WARNING: The script sarif is installed in '/home/XYZ/.local/bin' which is not on PATH.

将缺失的路径添加到您的PATH中。具体做法因Linux版本而异,但编辑~/.profile通常是不错的选择。然后在打开一个新的终端或运行source ~/.profile之后,您应该在命令提示符中能够输入sarif --version

要全局安装,请使用sudo pip install。请注意,从安全角度来看,不建议这样做。

测试安装

使用pip安装后,您应该能够运行

sarif --version

安装故障排除

本节提供了一些建议,以防安装后无法使用sarif命令。

在Python的Scripts目录中创建了一个名为sarifsarif.exe的启动器。要能够在命令提示符中输入sarif,需要将Scripts目录放在环境变量PATH中;如果安装时以超级用户身份运行pip(例如,Windows上的管理员命令提示符或Linux上的sudo),则最可能是这种情况。如果SARIF工具仅为当前用户安装,则将用户的Scripts目录添加到当前用户的PATH变量中是最佳做法。请在您的系统上搜索如何做到这一点。

如果Scripts目录不在PATH中,则可以输入python -m sarif代替sarif来运行工具。

当PATH中的pythonpip命令来自不同的安装,或者超级用户PATH中的python安装与普通用户的PATH中的python命令不同时,可能会出现混淆。在Windows上,您可以在正常CMD和Admin CMD中使用where pythonwhere pip来查看正在使用的安装;在Linux上,使用带或不带sudowhich pythonwhich pip

文件格式变化

SARIF是静态分析工具输出格式的标准,但像往常一样,不同的工具以不同的方式使用该标准。SARIF工具查看的规范的关键部分是

  • 严重性:SARIF标准只允许errorwarningnotenone
  • 代码和消息:问题类型应有一个简短的代码和简短名称,在标准中称为“message”,在Sarif-Tools中通常称为“description”。
  • 位置:问题发生的位置,通常是一个文件路径和行号。

静态分析工具通常对如何表示这些数据有不同的看法,并且工具作者将不同级别的努力映射到SARIF标准。我们所看到的例子包括

  • 只使用一个SARIF严重性级别,并将“真实”严重性级别放入自定义属性中。
  • 在消息中包含位置信息,使得相同的问题在不同位置有不同的消息。
  • 以不同的方式表示位置。

Sarif-Tools代码对略微不同的工具进行了一些微调,以产生令人满意的结果。例如,通过代码和截断消息的组合来识别问题类型,其中任一都可以为空。然而,如果Sarif-Tools对某个特定工具产生了不良结果,您可能需要实现自定义的SARIF输出预处理,或者要求工具作者改进其工具的SARIF输出质量以更好地符合标准,或者在Sarif-Tools上提出问题

命令行使用

usage: sarif [-h] [--version] [--debug] [--check {error,warning,note}] {blame,codeclimate,copy,csv,diff,emacs,html,info,ls,summary,trend,usage,word} ...

Process sets of SARIF files

positional arguments:
  {blame,codeclimate,copy,csv,diff,emacs,html,info,ls,summary,trend,usage,word}
                        command

optional arguments:
  -h, --help            show this help message and exit
  --version, -v         show program's version number and exit
  --debug               Print information useful for debugging
  --check {error,warning,note}, -x {error,warning,note}
                        Exit with error code if there are any issues of the specified level (or for diff, an increase in issues at that level).

commands:
blame        Enhance SARIF file with information from `git blame`
codeclimate  Write a JSON representation in Code Climate format of SARIF file(s) for viewing as a Code Quality report in GitLab UI
copy         Write a new SARIF file containing optionally-filtered data from other SARIF file(s)
csv          Write a CSV file listing the issues from the SARIF files(s) specified
diff         Find the difference between two [sets of] SARIF files
emacs        Write a representation of SARIF file(s) for viewing in emacs
html         Write an HTML representation of SARIF file(s) for viewing in a web browser
info         Print information about SARIF file(s) structure
ls           List all SARIF files in the directories specified
summary      Write a text summary with the counts of issues from the SARIF files(s) specified
trend        Write a CSV file with time series data from SARIF files with "yyyymmddThhmmssZ" timestamps in their filenames
usage        (Command optional) - print usage and exit
word         Produce MS Word .docx summaries of the SARIF files specified
Run `sarif <COMMAND> --help` for command-specific help.

命令

以下展示了命令的使用示例,假设输入文件位于以下位置

  • C:\temp\sarif_files = 一个包含任意文件名的SARIF文件的目录。
  • C:\temp\sarif_with_date = 一个包含包含时间戳的文件名的SARIF文件的目录,例如 C:\temp\sarif_with_date\myapp_devskim_output_20211001T012000Z.sarif
  • C:\temp\old_sarif_files = 一个包含来自较旧构建的任意文件名的SARIF文件的目录。
  • C:\code\my_source_repo = 从中获取SARIF结果的源代码文件的签出目录。

blame

usage: sarif blame [-h] [--output PATH] [--code PATH] [file_or_dir [file_or_dir ...]]

Enhance SARIF file with information from `git blame`

positional arguments:
  file_or_dir           A SARIF file or a directory containing SARIF files

optional arguments:
  -h, --help            show this help message and exit
  --output PATH, -o PATH
                        Output file or directory
  --code PATH, -c PATH  Path to git repository; if not specified, the current working directory is used

git blame信息添加到SARIF文件中,并将增强的文件写入指定的位置。

sarif blame -o "C:\temp\sarif_files_with_blame_info" -c "C:\code\my_source_repo" "C:\temp\sarif_files"

如果当前工作目录是git仓库,则可以省略-c参数。

成功获取的每个result对象的属性包中都会添加责任信息。使用的键和值与git blame porcelain格式中的一致。例如。

{
  "ruleId": "SM00702",
  ...
  "properties": {
    "blame": {
      "author": "aperson",
      "author-mail": "<aperson@acompany.com>",
      "author-time": "1350899798",
      "author-tz": "+0000",
      "committer": "aperson",
      "committer-mail": "<aperson@acompany.com>",
      "committer-time": "1350899798",
      "committer-tz": "+0000",
      "summary": "blah blah commit comment blah",
      "boundary": true,
      "filename": "src/net/myproject/mypackage/MyClass.java"
    }
  }
}

请注意,裸露的boundary键被赋予了自动值true

codeclimate

usage: sarif codeclimate [-h] [--output PATH] [--filter FILE] [--autotrim] [--trim PREFIX] [file_or_dir ...]

Write a JSON representation in Code Climate format of SARIF file(s) for viewing as a Code Quality report in GitLab UI

positional arguments:
  file_or_dir           A SARIF file or a directory containing SARIF files

optional arguments:
  -h, --help            show this help message and exit
  --output PATH, -o PATH
                        Output file or directory
  --filter FILE, -b FILE
                        Specify the filter file to apply. See README for format.
  --autotrim, -a        Strip off the common prefix of paths in the CSV output
  --trim PREFIX         Prefix to strip from issue paths, e.g. the checkout directory on the build agent

从[一组]SARIF文件中输出Code Climate工具格式的JSON文件。然后可以作为GitLab管道中的代码质量报告工件发布,并在GitLab UI中显示合并请求。

JSON输出也可以使用责任信息进行过滤;请参阅过滤部分,了解如何使用--filter选项。

copy

usage: sarif copy [-h] [--output FILE] [--filter FILE] [--timestamp] [file_or_dir [file_or_dir ...]]

Write a new SARIF file containing optionally-filtered data from other SARIF file(s)

positional arguments:
  file_or_dir           A SARIF file or a directory containing SARIF files

optional arguments:
  -h, --help            show this help message and exit
  --output FILE, -o FILE
                        Output file
  --filter FILE, -b FILE
                        Specify the filter file to apply. See README for format.
  --timestamp, -t       Append current timestamp to output filename in the "yyyymmddThhmmssZ" format used by the `sarif trend` command

写入包含从现有SARIF文件或多个SARIF文件中可选过滤的数据的新SARIF文件。结果文件包含来自原始SARIF文件中的每个运行,依次排列。结果可以进行过滤(请参阅过滤部分),在这种情况下,仅包括符合过滤条件的原始SARIF文件中的结果;输出文件不包含关于排除记录的信息。如果原始文件中的运行为空,或者其所有结果都被过滤掉,则仍然包含空运行。

如果没有提供输出文件名,将在当前目录中写入一个名为out.sarif的文件。如果输出文件已存在并且也在输入文件列表中,它将不会包含在输入中,以避免结果重复。输出文件将无警告地覆盖。

file_or_dir指定符可以包含通配符,例如c:\temp\**\devskim*.sarif(即“glob”)。这对于所有命令都适用,但对于copy尤其有用。

这种用法之一是将构建过程中运行的多组SARIF文件合并成一个文件,以便更容易作为构建资产存储和处理。

csv

usage: sarif csv [-h] [--output PATH] [--filter FILE] [--autotrim] [--trim PREFIX] [file_or_dir [file_or_dir ...]]

Write a CSV file listing the issues from the SARIF files(s) specified

positional arguments:
  file_or_dir           A SARIF file or a directory containing SARIF files

optional arguments:
  -h, --help            show this help message and exit
  --output PATH, -o PATH
                        Output file or directory
  --filter FILE, -b FILE
                        Specify the filter file to apply. See README for format.
  --autotrim, -a        Strip off the common prefix of paths in the CSV output
  --trim PREFIX         Prefix to strip from issue paths, e.g. the checkout directory on the build agent

从[一组]SARIF文件中输出一个简单表格的问题列表。然后可以进行分析,例如通过Excel中的数据透视表。

使用--trim选项从路径中删除特定的前缀,以使CSV更简洁。或者,使用--autotrim删除最长的公共前缀。

生成一个抑制常见文件路径前缀的单一SARIF文件的CSV摘要

sarif csv "C:\temp\sarif_files\devskim_myapp.sarif"

生成一个抑制路径前缀C:\code\my_source_repo的SARIF文件目录的CSV摘要

sarif csv --trim c:\code\my_source_repo "C:\temp\sarif_files"

如果 SARIF 文件(夹)包含归因信息(由 blame 命令添加),则 CSV 包含一个 "作者" 列,指示谁最后修改了相关行。

CSV 输出也可以使用相同的归因信息进行过滤;有关如何使用 --filter 选项的说明,请参阅下文的 过滤

diff

usage: sarif diff [-h] [--output FILE] [--filter FILE] old_file_or_dir new_file_or_dir

Find the difference between two [sets of] SARIF files

positional arguments:
  old_file_or_dir       An old SARIF file or a directory containing the old SARIF files
  new_file_or_dir       A new SARIF file or a directory containing the new SARIF files

optional arguments:
  -h, --help            show this help message and exit
  --output FILE, -o FILE
                        Output file
  --filter FILE, -b FILE
                        Specify the filter file to apply. See README for format.

打印两个 [组] SARIF 文件之间的差异。

两个 SARIF 文件中问题的差异

sarif diff "C:\temp\old_sarif_files\devskim_myapp.sarif" "C:\temp\sarif_files\devskim_myapp.sarif"

两个 SARIF 文件目录中问题的差异

sarif diff "C:\temp\old_sarif_files" "C:\temp\sarif_files"

将输出写入 JSON 文件而不是打印到 stdout

sarif diff -o mydiff.json "C:\temp\old_sarif_files\devskim_myapp.sarif" "C:\temp\sarif_files\devskim_myapp.sarif"

JSON 格式如下

{
    "all": {
        "+": 5,
        "-": 11
    },
    "error": {
        "+": 2,
        "-": 0,
        "codes": {
            "XYZ1234 Some Issue": {
                "<": 0,
                ">": 2,
                "+@": [
                    {
                        "Location": "C:\\code\\file1.py",
                        "Line": 119
                    },
                    {
                        "Location": "C:\\code\\file2.py",
                        "Line": 61
                    }
                ]
            },
        }
    },
    "warning": {
        "+": 3,
        "-": 11,
        "codes": {...}
    },
    "note": {
        "+": 3,
        "-": 11,
        "codes": {...}
    }
}

其中

  • "+" 表示在此严重性级别下出现的新问题类型,即 "error"、"warning" 或 "note"
  • "-" 表示已解决的问题类型在此严重性级别下(没有剩余发生情况)
  • "codes" 列出每个发生次数改变的问题代码
    • 表示在 "<" 之前的发生次数
    • 表示在 ">" 之后的发生次数
    • 新位置用 "+@" 表示

如果给定严重性的问题代码集已更改,即使该严重性的问题类型总数未改变,diff 也会报告这一点。

当问题代码的发生次数未改变时,diff 不会报告此问题代码,尽管可能出现了相同数量的新问题发生,同时解决了相同数量的特定问题。这是为了避免报告行号变化。

diff 操作显示每个问题的新的发生位置。当写入输出 JSON 文件时,将写入所有新位置,但当写入控制台输出时,最多显示三个位置。请注意,如果行号已更改,这里可能会有一些误报。

有关如何使用 --filter 选项的说明,请参阅下文的 过滤

emacs

usage: sarif emacs [-h] [--output PATH] [--filter FILE] [--no-autotrim] [--image IMAGE] [--trim PREFIX] [file_or_dir [file_or_dir ...]]

Write a representation of SARIF file(s) for viewing in emacs

positional arguments:
  file_or_dir           A SARIF file or a directory containing SARIF files

optional arguments:
  -h, --help            show this help message and exit
  --output PATH, -o PATH
                        Output file or directory
  --filter FILE, -b FILE
                        Specify the filter file to apply. See README for format.
  --no-autotrim, -n     Do not strip off the common prefix of paths in the output document
  --image IMAGE         Image to include at top of file - SARIF logo by default
  --trim PREFIX         Prefix to strip from issue paths, e.g. the checkout directory on the build agent

html

usage: sarif html [-h] [--output PATH] [--filter FILE] [--no-autotrim] [--image IMAGE] [--trim PREFIX] [file_or_dir [file_or_dir ...]]

Write an HTML representation of SARIF file(s) for viewing in a web browser

positional arguments:
  file_or_dir           A SARIF file or a directory containing SARIF files

optional arguments:
  -h, --help            show this help message and exit
  --output PATH, -o PATH
                        Output file or directory
  --filter FILE, -b FILE
                        Specify the filter file to apply. See README for format.
  --no-autotrim, -n     Do not strip off the common prefix of paths in the output document
  --image IMAGE         Image to include at top of file - SARIF logo by default
  --trim PREFIX         Prefix to strip from issue paths, e.g. the checkout directory on the build agent

创建一个总结 SARIF 结果的 HTML 文件。

sarif html -o summary.html "C:\temp\sarif_files"

使用 --trim 选项从路径中删除特定前缀,以使生成的 HTML 页面不那么冗长。除非指定了 --no-autotrim,否则将修剪路径的最长公共前缀。

使用 --image 选项为 HTML 页面的顶部提供标题图像。图像嵌入到 HTML 中,因此 HTML 文档保持为可移植的独立文件。

有关如何使用 --filter 选项的说明,请参阅下文的 过滤

info

usage: sarif info [-h] [--output FILE] [file_or_dir [file_or_dir ...]]

Print information about SARIF file(s) structure

positional arguments:
  file_or_dir           A SARIF file or a directory containing SARIF files

optional arguments:
  -h, --help            show this help message and exit
  --output FILE, -o FILE
                        Output file

打印有关 SARIF 文件或多个文件结构的说明。这关于 JSON 结构,而不是由工具生成的结果的任何含义。摘要包括文件的完整路径、大小和修改日期、运行的次数,以及对于每个运行,生成运行的工具、结果的数量以及结果属性包中的条目。

c:\temp\sarif_files\ios_devskim_output.sarif
  1256241 bytes (1.2 MiB)
  modified: 2021-10-13 21:50:01.251544, accessed: 2022-01-09 18:23:00.060573, ctime: 2021-10-13 20:49:00
  1 run
    Tool: devskim
    1323 results
    All results have properties: tags, DevSkimSeverity

ls

usage: sarif ls [-h] [--output FILE] [file_or_dir [file_or_dir ...]]

List all SARIF files in the directories specified

positional arguments:
  file_or_dir           A SARIF file or a directory containing SARIF files

optional arguments:
  -h, --help            show this help message and exit
  --output FILE, -o FILE
                        Output file

列出一个或多个目录中的 SARIF 文件。

sarif ls "C:\temp\sarif_files" "C:\temp\sarif_with_date"

summary

usage: sarif summary [-h] [--output PATH] [--filter FILE] [file_or_dir [file_or_dir ...]]

Write a text summary with the counts of issues from the SARIF files(s) specified

positional arguments:
  file_or_dir           A SARIF file or a directory containing SARIF files

optional arguments:
  -h, --help            show this help message and exit
  --output PATH, -o PATH
                        Output file or directory
  --filter FILE, -b FILE
                        Specify the filter file to apply. See README for format.

打印一个或多个 SARIF 文件(夹)中问题的摘要,按严重性分组,然后按发生次数排序。

当提供输入和输出目录时,为每个输入文件编写摘要,以及包含总计的另一个文件。

sarif summary -o summaries "C:\temp\sarif_files"

当未指定输出目录或文件时,将总体摘要打印到标准输出。

sarif summary "C:\temp\sarif_files\devskim_myapp.sarif"

有关如何使用 --filter 选项的说明,请参阅下文的 过滤

trend

usage: sarif trend [-h] [--output FILE] [--filter FILE] [--dateformat {dmy,mdy,ymd}] [file_or_dir [file_or_dir ...]]

Write a CSV file with time series data from SARIF files with "yyyymmddThhmmssZ" timestamps in their filenames

positional arguments:
  file_or_dir           A SARIF file or a directory containing SARIF files

optional arguments:
  -h, --help            show this help message and exit
  --output FILE, -o FILE
                        Output file
  --filter FILE, -b FILE
                        Specify the filter file to apply. See README for format.
  --dateformat {dmy,mdy,ymd}, -f {dmy,mdy,ymd}
                        Date component order to use in output CSV. Default is `dmy`

生成一个 CSV,显示目录中一组 SARIF 文件的按时间线排序的问题。SARIF 文件名必须包含特定格式的时间戳 yyyymmddThhhmmss,例如 20211012T110000Z

可以将 CSV 加载到 Microsoft Excel 中进行绘图和趋势分析。

sarif trend -o timeline.csv "C:\temp\sarif_with_date" --dateformat dmy

有关如何使用 --filter 选项的说明,请参阅下文的 过滤

upgrade-filter

usage: sarif upgrade-filter [-h] [--output PATH] [file [file ...]]

Upgrade a v1-style blame filter file to a v2-style filter YAML file

positional arguments:
  file                  A v1-style blame-filter file

optional arguments:
  -h, --help            show this help message and exit
  --output PATH, -o PATH
                        Output file or directory

usage

usage: sarif usage [-h] [--output FILE]

(Command optional) - print usage and exit

optional arguments:
  -h, --help            show this help message and exit
  --output FILE, -o FILE
                        Output file

打印用法并退出。

version

usage: sarif version [-h]

Print version and exit

optional arguments:
  -h, --help  show this help message and exit

以裸格式打印 sarif-tools 的版本号。

word

usage: sarif word [-h] [--output PATH] [--filter FILE] [--no-autotrim] [--image IMAGE] [--trim PREFIX] [file_or_dir [file_or_dir ...]]

Produce MS Word .docx summaries of the SARIF files specified

positional arguments:
  file_or_dir           A SARIF file or a directory containing SARIF files

optional arguments:
  -h, --help            show this help message and exit
  --output PATH, -o PATH
                        Output file or directory
  --filter FILE, -b FILE
                        Specify the filter file to apply. See README for format.
  --no-autotrim, -n     Do not strip off the common prefix of paths in the output document
  --image IMAGE         Image to include at top of file - SARIF logo by default
  --trim PREFIX         Prefix to strip from issue paths, e.g. the checkout directory on the build agent

创建表示SARIF文件或多个SARIF文件的Word文档。

如果提供了用于-o选项和输入的目录,则为每个单独的SARIF文件和全部SARIF文件集生成Word文档。否则,将创建一个Word文档。

在每个SARIF文件以及所有SARIF文件一起,在reports目录下创建Word文档(如果不存在则创建)

sarif word -o reports "C:\temp\sarif_files"

为单个SARIF文件创建Word文档

sarif word -o "reports\devskim_myapp.docx" "C:\temp\sarif_files\devskim_myapp.sarif"

使用--trim选项从路径中删除特定的前缀,以使生成的文档更简洁。除非指定了--no-autotrim,否则将删除路径的最长公共前缀。

使用--image选项为Word文档顶部提供标题图片。

有关如何使用 --filter 选项的说明,请参阅下文的 过滤

过滤

然后可以使用各种命令提供的--filter选项通过每个result对象中的数据进行过滤。此选项需要一个包含要匹配SARIF文件中数据的模式列表的filter-list YAML文件的路径。filter-list文件的格式如下

# Lines beginning with # are interpreted as comments and ignored.
# Optional description for the filter.  If no title is specified, the filter file name is used.
description: Example filter from README.md

# Optional configuration section to override default values.
configuration:
  # This option controls whether to include results where a property to check is missing, default
  # value is true.
  default-include: false
  # This option only applies filter criteria if the line number is present and not equal to 1.
  # Some static analysis tools set the line number to 1 for whole file issues, but this does not
  # work with blame filtering, because who last changed line 1 is irrelevant.  Default value is
  # true.
  check-line-number: true

# Items in `include` list are interpreted as inclusion filtering rules.
# Items are treated with OR operator, the filtered results includes objects matching any rule.
# Each item can be one rule or a list of rules, in the latter case rules in the list are treated
# with AND operator - all rules must match.
include:
  # The following line includes issues whose author-mail property contains "@microsoft.com" AND
  # found in Java files.
  # Values with special characters `\:;_()$%^@,` must be enclosed in quotes (single or double):
  - author-mail: "@microsoft.com"
    locations[*].physicalLocation.artifactLocation.uri: "*.java"
  # Instead of a substring, a regular expression can be used, enclosed in "/" characters.
  # Issues whose committer-mail property includes a string matching the regular expression are included.
  # Use ^ and $ to match the whole committer-mail property.
  - committer-mail:
      value: "/^<myname.*\\.com>$/"
      # Configuration options can be overridden for any rule.
      default-include: true
      check-line-number: true
# Lines under `exclude` are interpreted as exclusion filtering rules.
exclude:
  # The following line excludes issues whose location is in test Java files with names starting with
  #  the "Test" prefix.
  - location: "Test*.java"
  # The value for the property can be empty, in this case only existence of the property is checked.
  - suppression:

以下是一个示例filter-file,它包括由@microsoft.commyname.SOMETHING.com电子邮件地址更改的行的相关问题,但如果不以bot@microsoft.com结尾或包含GUID,则不包括这些问题。它与上面的例子相同,只是去掉了注释。

description: Example filter from README.md
configuration:
  default-include: true
  check-line-number: true
include:
  - author-mail: "@microsoft.com"
  - author-mail: "/myname\\..*\\.com/"
exclude:
  - author-mail: bot@microsoft.com
  - author-mail: '/[0-9A-F]{8}[-][0-9A-F]{4}[-][0-9A-F]{4}[-][0-9A-F]{4}[-][0-9A-F]{12}\@microsoft.com/'

字段名必须指定为JSONPath表示法,访问SARIF result对象中的数据。

对于常用属性,定义了以下快捷方式

快捷方式 完整的JSONPath
author properties.blame.author
author-mail properties.blame.author-mail
committer properties.blame.committer
committer-mail properties.blame.committer-mail
location locations[*].physicalLocation.artifactLocation.uri
rule ruleId
suppression suppressions[*].kind

对于uri属性(例如在locations[*].physicalLocation.artifactLocation.uri中),可以使用文件名通配符,因为它代表文件位置

  • ? - 目录或文件名中任意字符的单次出现
  • * - 目录或文件名中任意字符的零次或多次出现
  • ** - 多个目录级别的零次或多次出现

例如。

  • tests/Test???.js
  • src/js/*.js
  • src/js/**/*.js

所有匹配都是不区分大小写的,因为电子邮件地址是不区分大小写的。忽略行首和行尾的空白,这也意味着行终止字符不重要。filter文件必须使用UTF-8编码(包括plain ASCII7)。

如果没有包含模式,则包括所有问题,但不包括匹配排除模式的问题。如果有包含模式,则只包括匹配包含模式的问题。如果一个问题匹配一个或多个包含模式,并且至少匹配一个排除模式,则将其排除。

作为Python库的使用

虽然这不是其主要目的,但您可以从Python脚本或模块中运行sarif-tools来加载和总结SARIF结果。

基本使用模式

安装后,使用sarif.loader加载SARIF文件或文件,然后使用返回的SarifFileSarifFileSet对象上的操作来探索数据。

from sarif import loader

sarif_data = loader.load_sarif_file(path_to_sarif_file)
report = sarif_data.get_report()
error_histogram = report.get_issue_type_histogram_for_severity("error")

文件和文件集

sarif_files模块中定义的三个类,SarifFileSetSarifFileSarifRun,提供了相似的API,这使得SARIF结果可以在多个聚合级别上以类似的方式处理。要探索结果,请使用get_report()

结果、记录和报告

从SARIF文件中提取的结果有三种规范化聚合级别

  1. 结果通过get_results()方法从SarifFileSetSarifFileSarifRun获取。这些是直接从SARIF数据中的JSON结果对象反序列化得到的dict,如SARIF标准第3.27节所述。
  2. 记录通过get_records()方法从SarifFileSetSarifFileSarifRun获取。每个记录是一个键值对字典,键为sarif_file.BASIC_RECORD_ATTRIBUTES中的键。
    • "Tool" - 包含结果的运行的工具名称。
    • "Severity" - 记录的SARIF严重性。可以是errorwarning(如果记录未指定则为默认值)、notenone
    • "Code" - 结果中的问题代码。
    • "Description" - 结果中的问题名称——对应于代码。
    • "Location" - 问题的位置,通常是包含问题的文件。格式因工具而异。
    • "Line" - 文件中发生问题的行号。如果工具无法识别行,则默认值为"1"。此扁平的记录列表对于如CSV这样的机器可读输出格式很有用。
  3. 报告是IssuesReport对象,如issues_report.py中定义。报告通过分组和排序记录,为如Word和HTML这样的可读输出格式提供有用的结构。报告可以通过get_report()方法从SarifFileSetSarifFileSarifRun获取。

文件和文件集的关键方法

这些方法存在于SarifFileSetSarifFileSarifRun中。

  • get_distinct_tool_names()
    • 返回一个SarifFile中的不同工具名称列表或SarifFileSet中所有文件的工具名称列表。由于SarifRun只有一个工具名称,因此等效方法是get_tool_name()
  • get_results()
    • 返回作为dict的SARIF结果对象列表——见上文。
  • get_records()
    • 返回作为扁平dict的SARIF记录列表——见上文。
  • get_report()
    • 返回分组并按位置排序记录的IssuesReport对象。

IssuesReport的关键方法

IssuesReport提供将问题分组为三个级别的功能

  1. 严重性:SARIF定义了严重性级别errorwarningnote,以及有时用于SARIF文件中的结果不是问题时使用的none
  2. 问题类型:SARIF结果通过代码、描述或二者的组合来识别。相同的问题可以出现在多个位置,因此IssuesReport将这些问题按问题类型分组,并在给定的严重性级别内进行分组。问题类型代码键由问题代码和问题描述组合而成,中间插入一个空格字符,但长度被截断为不超过120个字符。
  3. 记录:一个特定问题类型下的单个记录表示该问题出现的位置。它们被排序成一个合理的位置顺序。

IssuesReport的关键方法是

  • get_severities():获取从最严重到最不严重的有序严重性列表。要生成报告,获取严重性列表,然后迭代它们,调用其他方法以获取所需形式在该严重性级别上的结果摘要。
  • any_none_severities():如果有任何记录的严重性为none,则为TrueFalse。严重性none不被许多工具使用,因此只有在有匹配记录的情况下才将其作为标题包含,以避免冗余并可能引起混淆的none标题。严重性errorwarningnote始终包含,即使没有记录,因为这些级别对于静态分析问题都是相关的。
  • get_issue_count_for_severity(severity):获取此严重性的总结果数。
  • get_issue_type_count_for_severity(severity):获取此严重性的问题类型总数。
  • get_issues_grouped_by_type_for_severity(severity): 根据严重程度获取一个字典,键为问题类型(代码 + 描述),值为该类型的排序结果列表。
  • get_issue_type_histogram_for_severity(severity): 根据严重程度获取一个字典,键为问题类型(代码 + 描述),值为该类型的结果数量。
  • get_issues_for_severity(severity): 获取给定严重程度的结果的扁平列表。这类似于get_issues_grouped_by_type_for_severity的结果,但是从dict[str, list]展开为单个list,保持原始列表序列的顺序。

分解和文件名访问

这些字段和方法允许访问SARIF文件的底层信息。

  • SarifFileSet.subdirs - 一个与SarifFileSet创建目录的子目录对应的SarifFileSet对象列表。
  • SarifFileSet.files - 一个与创建SarifFileSet的目录中包含的SARIF文件对应的SarifFile对象列表。
  • SarifFile.get_abs_file_path() - 获取SARIF文件的绝对路径。
  • SarifFile.get_file_name() - 获取SARIF文件的名称。
  • SarifFile.get_file_name_without_extension() - 获取不带扩展名的SARIF文件名称。对于构建派生文件名很有用。
  • SarifFile.get_filename_timestamp() - 从SARIF文件的文件名中提取时间戳,并将其作为字符串返回。时间戳必须符合在sarif trend命令中指定的格式。
  • SarifFile.runs - SARIF文件中包含的SarifRun对象列表。大多数SARIF文件只包含一个运行,但可能将来自多个工具的运行聚合到单个SARIF文件中。

路径缩短API

在一个SarifFileSetSarifFileSarifRun对象上调用init_path_prefix_stripping(autotrim, path_prefixes)以设置路径过滤,自动删除最长的公共前缀(autotrim=True)或删除特定的前缀(autotrim=Falsepath_prefixes中包含字符串列表)。

过滤API

在一个SarifFileSetSarifFileSarifRun对象上调用init_general_filter(filter_description, include_filters, exclude_filters)以设置过滤。filter_description是一个字符串,其他参数是包含和排除规则的列表。它们与上面描述的过滤中提到的过滤文件内容相对应。

调用get_filter_stats()以检索从SARIF文件中读取结果或记录后的过滤统计信息。如果没有过滤,则返回None,否则返回一个包含整数字段filtered_in_result_countfiltered_out_result_countsarif_file.FilterStats对象。在FilterStats对象上调用to_string()以获取这些统计信息的可读表示,它还包括过滤文件名称或描述(filter_description字段)。

在CI管道中的建议使用方法

使用--check选项与summary命令一起,如果存在任何指定级别或更高级别的问题,sarif-tools将以非零退出代码退出。这在SAST违规的情况下导致持续集成(CI)管道失败可能很有用。

SARIF问题级别为errorwarningnote。这些都是--check选项的有效选项。

例如,如果有任何错误或警告将失败

sarif --check warning summary c:\temp\sarif_files

diff命令可以检查相对于先前或基线构建的指定级别或以上问题的任何增加。

例如,如果有任何错误级别的新的问题代码将失败

sarif --check error diff c:\temp\old_sarif_files c:\temp\sarif_files

您还可以使用sarif-tools过滤和合并多个工具的输出。例如。

# First run your static analysis tools, configured to write SARIF output.  How to do that depends
# the tool.

# Now run the blame command to augment the output with blame information.
sarif blame -o with_blame/myapp_mytool_with_blame.sarif myapp_mytool.sarif

# Now combine all tools' output into a single file
sarif copy --timestamp -o artifacts/myapp_alltools_with_blame.sarif

下载生成的文件 myapp_alltools_with_blame_TIMESTAMP.sarif。然后您可以使用 --filter 参数过滤结果,或使用 sarif trend 生成代码质量随时间变化的图表。

致谢

sarif-tools 最初是在 2021 年微软全球黑客松期间由 Simon Abykov、Nick Brabbs、Anthony Hayward、Sivaji Kondapalli、Matt Parkes 和 Kathryn Pentland 开发的。

感谢自最初发布以来所有贡献过 pull requests 的人!

项目详情


下载文件

下载适用于您平台的文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。

源分发

sarif_tools-3.0.3.tar.gz (54.3 kB 查看散列)

上传时间

构建分发

sarif_tools-3.0.3-py3-none-any.whl (54.6 kB 查看散列)

上传时间 Python 3

由以下机构支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面