View Javadoc
1   /*
2    * This file is part of dependency-check-core.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   *
16   * Copyright (c) 2018 Steve Springett. All Rights Reserved.
17   */
18  package org.owasp.dependencycheck.data.nodeaudit;
19  
20  import io.github.jeremylong.openvulnerability.client.nvd.CvssV3;
21  import org.json.JSONArray;
22  import org.json.JSONObject;
23  
24  import org.slf4j.Logger;
25  import org.slf4j.LoggerFactory;
26  import java.util.ArrayList;
27  import java.util.Iterator;
28  import java.util.List;
29  import org.json.JSONException;
30  import org.owasp.dependencycheck.utils.CvssUtil;
31  
32  /**
33   * Parser for NPM Audit API response. This parser is derived from:
34   * https://github.com/DependencyTrack/dependency-track/blob/master/src/main/java/org/owasp/dependencytrack/parser/npm/audit/NpmAuditParser.java
35   *
36   * @author Steve Springett
37   */
38  public class NpmAuditParser {
39  
40      /**
41       * The logger.
42       */
43      private static final Logger LOGGER = LoggerFactory.getLogger(NpmAuditParser.class);
44  
45      /**
46       * Parses the JSON response from the NPM Audit API.
47       *
48       * @param jsonResponse the JSON node to parse
49       * @return an AdvisoryResults object
50       * @throws org.json.JSONException thrown if the JSON is not of the expected
51       * schema
52       */
53      public List<Advisory> parse(JSONObject jsonResponse) throws JSONException {
54          LOGGER.debug("Parsing JSON node");
55          final List<Advisory> advisories = new ArrayList<>();
56          final JSONObject jsonAdvisories = jsonResponse.getJSONObject("advisories");
57          final Iterator<?> keys = jsonAdvisories.keys();
58          while (keys.hasNext()) {
59              final String key = (String) keys.next();
60              final Advisory advisory = parseAdvisory(jsonAdvisories.getJSONObject(key));
61              advisories.add(advisory);
62          }
63          return advisories;
64      }
65  
66      /**
67       * Parses the advisory from Node Audit.
68       *
69       * @param object the JSON object containing the advisory
70       * @return the Advisory object
71       * @throws org.json.JSONException thrown if the JSON is not of the expected
72       * schema
73       */
74      private Advisory parseAdvisory(JSONObject object) throws JSONException {
75          final Advisory advisory = new Advisory();
76          advisory.setGhsaId(object.getString("github_advisory_id"));
77          advisory.setOverview(object.optString("overview", null));
78          advisory.setReferences(object.optString("references", null));
79          advisory.setCreated(object.optString("created", null));
80          advisory.setUpdated(object.optString("updated", null));
81          advisory.setRecommendation(object.optString("recommendation", null));
82          advisory.setTitle(object.optString("title", null));
83          //advisory.setFoundBy(object.optString("author", null));
84          //advisory.setReportedBy(object.optString("author", null));
85          advisory.setModuleName(object.optString("module_name", null));
86          advisory.setVulnerableVersions(object.optString("vulnerable_versions", null));
87          advisory.setPatchedVersions(object.optString("patched_versions", null));
88          advisory.setAccess(object.optString("access", null));
89          advisory.setSeverity(object.optString("severity", null));
90  
91          final JSONArray jsonCwes = object.optJSONArray("cwe");
92          final List<String> stringCwes = new ArrayList<>();
93          if (jsonCwes != null) {
94              for (int j = 0; j < jsonCwes.length(); j++) {
95                  stringCwes.add(jsonCwes.getString(j));
96              }
97          }
98          advisory.setCwes(stringCwes);
99  
100         final JSONArray findings = object.optJSONArray("findings");
101         for (int i = 0; i < findings.length(); i++) {
102             final JSONObject finding = findings.getJSONObject(i);
103             final String version = finding.optString("version", null);
104             final JSONArray paths = finding.optJSONArray("paths");
105             for (int j = 0; j < paths.length(); j++) {
106                 final String path = paths.getString(j);
107                 if (path != null && path.equals(advisory.getModuleName())) {
108                     advisory.setVersion(version);
109                 }
110             }
111         }
112 
113         final JSONArray jsonCves = object.optJSONArray("cves");
114         final List<String> stringCves = new ArrayList<>();
115         if (jsonCves != null) {
116             for (int j = 0; j < jsonCves.length(); j++) {
117                 stringCves.add(jsonCves.getString(j));
118             }
119             advisory.setCves(stringCves);
120         }
121         final JSONObject jsonCvss = object.optJSONObject("cvss");
122         if (jsonCvss != null) {
123             double baseScore = -1.0;
124             final String score = jsonCvss.optString("score");
125             if (score != null) {
126                 try {
127                     baseScore = Float.parseFloat(score);
128                 } catch (NumberFormatException ignored) {
129                     LOGGER.trace("Swallowed NumberFormatException", ignored);
130                     baseScore = -1.0f;
131                 }
132             }
133             if (baseScore >= 0.0) {
134                 final String vector = jsonCvss.optString("vectorString");
135                 if (vector != null && !"null".equals(vector)) {
136                     if (vector.startsWith("CVSS:3") && baseScore >= 0.0) {
137                         try {
138                             final CvssV3 cvss = CvssUtil.vectorToCvssV3(vector, baseScore);
139                             advisory.setCvssV3(cvss);
140                         } catch (IllegalArgumentException iae) {
141                             LOGGER.warn("Invalid CVSS vector format encountered in NPM Audit results '{}': {} ", vector, iae.getMessage());
142                         }
143                     } else {
144                         LOGGER.warn("Unsupported CVSS vector format in NPM Audit results, please file a feature "
145                                 + "request at https://github.com/jeremylong/DependencyCheck/issues/new/choose to "
146                                 + "support vector format '{}' ", vector);
147                     }
148                 }
149             }
150         }
151         return advisory;
152     }
153 }