File: sarifreport.cpp

package info (click to toggle)
cppcheck 2.19.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 26,688 kB
  • sloc: cpp: 272,455; python: 22,408; ansic: 8,088; sh: 1,059; makefile: 1,041; xml: 987; cs: 291
file content (222 lines) | stat: -rw-r--r-- 9,408 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
/*
 * Cppcheck - A tool for static C/C++ code analysis
 * Copyright (C) 2007-2025 Cppcheck team.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "sarifreport.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "settings.h"
#include "cppcheck.h"

#include <set>
#include <sstream>

static const char sarifVersion[] = "2.1.0";
static const char sarifSchema[] = "https://docs.oasis-open.org/sarif/sarif/v2.1.0/errata01/os/schemas/sarif-schema-2.1.0.json";

void SarifReport::addFinding(ErrorMessage msg)
{
    mFindings.push_back(std::move(msg));
}

picojson::array SarifReport::serializeRules() const
{
    picojson::array ret;
    std::set<std::string> ruleIds;
    for (const auto& finding : mFindings) {
        // github only supports findings with locations
        if (finding.callStack.empty())
            continue;
        if (ruleIds.insert(finding.id).second) {
            // setting name and description to empty strings will make github default
            // to the instance specific violation message and not rule description,
            // this makes it so not all the violations have the same description.
            picojson::object rule;
            rule["id"] = picojson::value(finding.id);
            // rule.name
            rule["name"] = picojson::value("");
            // rule.shortDescription.text
            picojson::object shortDescription;
            shortDescription["text"] = picojson::value("");
            rule["shortDescription"] = picojson::value(shortDescription);
            // rule.fullDescription.text
            picojson::object fullDescription;
            fullDescription["text"] = picojson::value("");
            rule["fullDescription"] = picojson::value(fullDescription);
            // rule.help.text
            picojson::object help;
            help["text"] = picojson::value("");
            rule["help"] = picojson::value(help);
            // rule.properties.precision, rule.properties.problem.severity
            picojson::object properties;
            properties["precision"] = picojson::value(sarifPrecision(finding));
            // rule.properties.security-severity, rule.properties.tags
            picojson::array tags;

            // If we have a CWE ID, treat it as security-related (CWE is the authoritative source for security weaknesses)
            if (finding.cwe.id > 0) {
                double securitySeverity = 0;
                if (finding.severity == Severity::error && !ErrorLogger::isCriticalErrorId(finding.id)) {
                    securitySeverity = 9.9; // critical = 9.0+
                }
                else if (finding.severity == Severity::warning) {
                    securitySeverity = 8.5; // high = 7.0 to 8.9
                }
                else if (finding.severity == Severity::performance || finding.severity == Severity::portability ||
                         finding.severity == Severity::style) {
                    securitySeverity = 5.5; // medium = 4.0 to 6.9
                }
                else if (finding.severity == Severity::information || finding.severity == Severity::internal ||
                         finding.severity == Severity::debug || finding.severity == Severity::none) {
                    securitySeverity = 2.0; // low = 0.1 to 3.9
                }
                if (securitySeverity > 0.0) {
                    std::ostringstream ss;
                    ss << securitySeverity;
                    properties["security-severity"] = picojson::value(ss.str());
                    tags.emplace_back("external/cwe/cwe-" + std::to_string(finding.cwe.id));
                    tags.emplace_back("security");
                }
            }

            // Add tags array if it has any content
            if (!tags.empty()) {
                properties["tags"] = picojson::value(tags);
            }

            // Set problem.severity for use with github
            const std::string problemSeverity = sarifSeverity(finding);
            properties["problem.severity"] = picojson::value(problemSeverity);
            rule["properties"] = picojson::value(properties);
            // rule.defaultConfiguration.level
            picojson::object defaultConfiguration;
            defaultConfiguration["level"] = picojson::value(sarifSeverity(finding));
            rule["defaultConfiguration"] = picojson::value(defaultConfiguration);

            ret.emplace_back(rule);
        }
    }
    return ret;
}

picojson::array SarifReport::serializeLocations(const ErrorMessage& finding)
{
    picojson::array ret;
    for (const auto& location : finding.callStack) {
        picojson::object physicalLocation;
        picojson::object artifactLocation;
        artifactLocation["uri"] = picojson::value(location.getfile(false));
        physicalLocation["artifactLocation"] = picojson::value(artifactLocation);
        picojson::object region;
        region["startLine"] = picojson::value(static_cast<int64_t>(location.line < 1 ? 1 : location.line));
        region["startColumn"] = picojson::value(static_cast<int64_t>(location.column < 1 ? 1 : location.column));
        region["endLine"] = region["startLine"];
        region["endColumn"] = region["startColumn"];
        physicalLocation["region"] = picojson::value(region);
        picojson::object loc;
        loc["physicalLocation"] = picojson::value(physicalLocation);
        ret.emplace_back(loc);
    }
    return ret;
}

picojson::array SarifReport::serializeResults() const
{
    picojson::array results;
    for (const auto& finding : mFindings) {
        // github only supports findings with locations
        if (finding.callStack.empty())
            continue;
        picojson::object res;
        res["level"] = picojson::value(sarifSeverity(finding));
        res["locations"] = picojson::value(serializeLocations(finding));
        picojson::object message;
        message["text"] = picojson::value(finding.shortMessage());
        res["message"] = picojson::value(message);
        res["ruleId"] = picojson::value(finding.id);
        if (finding.hash != 0) {
            picojson::object partialFingerprints;
            partialFingerprints["hash/v1"] = picojson::value(std::to_string(finding.hash));
            res["partialFingerprints"] = picojson::value(partialFingerprints);
        }
        results.emplace_back(res);
    }
    return results;
}

picojson::value SarifReport::serializeRuns(const std::string& productName, const std::string& version) const
{
    picojson::object driver;
    driver["name"] = picojson::value(productName);
    driver["semanticVersion"] = picojson::value(version);
    driver["informationUri"] = picojson::value("https://cppcheck.sourceforge.io");
    driver["rules"] = picojson::value(serializeRules());
    picojson::object tool;
    tool["driver"] = picojson::value(driver);
    picojson::object run;
    run["tool"] = picojson::value(tool);
    run["results"] = picojson::value(serializeResults());
    picojson::array runs{picojson::value(run)};
    return picojson::value(runs);
}

std::string SarifReport::serialize(std::string productName) const
{
    const auto nameAndVersion = Settings::getNameAndVersion(productName);
    productName = nameAndVersion.first.empty() ? "Cppcheck" : nameAndVersion.first;
    std::string version = nameAndVersion.first.empty() ? CppCheck::version() : nameAndVersion.second;
    if (version.find(' ') != std::string::npos)
        version.erase(version.find(' '), std::string::npos);

    picojson::object doc;
    doc["$schema"] = picojson::value(sarifSchema);
    doc["runs"] = serializeRuns(productName, version);

    // Insert "version" property at the start.
    // From SARIF specification (https://docs.oasis-open.org/sarif/sarif/v2.1.0/errata01/os/sarif-v2.1.0-errata01-os-complete.html#_Toc141790730):
    // Although the order in which properties appear in a JSON object value is not semantically significant, the version property SHOULD appear first.

    return "{\n  \"version\": \"" + std::string(sarifVersion) + "\"," + picojson::value(doc).serialize(true).substr(1);
}

std::string SarifReport::sarifSeverity(const ErrorMessage& errmsg)
{
    if (ErrorLogger::isCriticalErrorId(errmsg.id))
        return "error";
    switch (errmsg.severity) {
    case Severity::error:
    case Severity::warning:
        return "error";
    case Severity::style:
    case Severity::portability:
    case Severity::performance:
        return "warning";
    case Severity::information:
    case Severity::internal:
    case Severity::debug:
    case Severity::none:
        return "note";
    }
    return "note";
}

std::string SarifReport::sarifPrecision(const ErrorMessage& errmsg)
{
    if (errmsg.certainty == Certainty::inconclusive)
        return "medium";
    return "high";
}