Skip to content

Commit b2753ee

Browse files
committed
json-parser: read CWE from SARIF if available
1 parent 64441e1 commit b2753ee

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

src/json-parser.cc

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,9 +80,15 @@ class SarifTreeDecoder: public AbstractTreeDecoder {
8080
virtual bool readNode(Defect *def, pt::ptree::const_iterator defIter);
8181

8282
private:
83+
void updateCweMap(const pt::ptree *driverNode);
84+
8385
std::string singleChecker;
86+
const RE reCwe = RE("^CWE-([0-9]+)$");
8487
const RE reRuleId =
8588
RE("(" RE_CHECKER_NAME "): (" RE_EVENT ")");
89+
90+
typedef std::map<std::string, int> TCweMap;
91+
TCweMap cweMap;
8692
};
8793

8894
struct JsonParser::Private {
@@ -377,6 +383,40 @@ bool CovTreeDecoder::readNode(
377383
return true;
378384
}
379385

386+
void SarifTreeDecoder::updateCweMap(const pt::ptree *driverNode)
387+
{
388+
const pt::ptree *rules;
389+
if (!findChildOf(&rules, *driverNode, "rules"))
390+
return;
391+
392+
for (const auto &item : *rules) {
393+
const pt::ptree &rule = item.second;
394+
const auto id = valueOf<std::string>(rule, "id", "");
395+
if (id.empty())
396+
// rule ID missing
397+
continue;
398+
399+
const pt::ptree *props;
400+
if (!findChildOf(&props, rule, "properties"))
401+
// properties missing
402+
continue;
403+
404+
const pt::ptree *cweList;
405+
if (!findChildOf(&cweList, *props, "cwe") || cweList->empty())
406+
// cwe list missing
407+
continue;
408+
409+
const std::string cweStr = cweList->begin()->second.data();
410+
boost::smatch sm;
411+
if (!boost::regex_match(cweStr, sm, this->reCwe))
412+
// unable to parse cwe
413+
continue;
414+
415+
const int cwe = std::stoi(sm[/* cwe */ 1]);
416+
this->cweMap[id] = cwe;
417+
}
418+
}
419+
380420
void SarifTreeDecoder::readScanProps(
381421
TScanProps *pDst,
382422
const pt::ptree *root)
@@ -405,6 +445,8 @@ void SarifTreeDecoder::readScanProps(
405445
if (!findChildOf(&driverNode, *toolNode, "driver"))
406446
return;
407447

448+
this->updateCweMap(driverNode);
449+
408450
const auto name = valueOf<std::string>(*driverNode, "name", "");
409451
if (name == "SnykCode") {
410452
// Snyk Code detected!
@@ -539,6 +581,11 @@ bool SarifTreeDecoder::readNode(
539581
}
540582
}
541583

584+
// lookup cwe
585+
const TCweMap::const_iterator it = this->cweMap.find(rule);
586+
if (this->cweMap.end() != it)
587+
def->cwe = it->second;
588+
542589
// read location and diagnostic message
543590
keyEvent.fileName = "<unknown>";
544591
const pt::ptree *locs;

0 commit comments

Comments
 (0)