Coverage Report - org.owasp.dependencycheck.analyzer.CPEAnalyzer
 
Classes in this File Line Coverage Branch Coverage Complexity
CPEAnalyzer
83%
164/197
72%
90/124
4.444
CPEAnalyzer$IdentifierConfidence
100%
4/4
N/A
4.444
CPEAnalyzer$IdentifierMatch
40%
12/30
16%
4/24
4.444
 
 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) 2012 Jeremy Long. All Rights Reserved.
 17  
  */
 18  
 package org.owasp.dependencycheck.analyzer;
 19  
 
 20  
 import java.io.IOException;
 21  
 import java.io.UnsupportedEncodingException;
 22  
 import java.net.URLEncoder;
 23  
 import java.util.ArrayList;
 24  
 import java.util.Collections;
 25  
 import java.util.List;
 26  
 import java.util.Set;
 27  
 import java.util.StringTokenizer;
 28  
 import java.util.logging.Level;
 29  
 import java.util.logging.Logger;
 30  
 import org.apache.lucene.document.Document;
 31  
 import org.apache.lucene.index.CorruptIndexException;
 32  
 import org.apache.lucene.queryparser.classic.ParseException;
 33  
 import org.apache.lucene.search.ScoreDoc;
 34  
 import org.apache.lucene.search.TopDocs;
 35  
 import org.owasp.dependencycheck.Engine;
 36  
 import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
 37  
 import org.owasp.dependencycheck.data.cpe.CpeMemoryIndex;
 38  
 import org.owasp.dependencycheck.data.cpe.Fields;
 39  
 import org.owasp.dependencycheck.data.cpe.IndexEntry;
 40  
 import org.owasp.dependencycheck.data.cpe.IndexException;
 41  
 import org.owasp.dependencycheck.data.lucene.LuceneUtils;
 42  
 import org.owasp.dependencycheck.data.nvdcve.CveDB;
 43  
 import org.owasp.dependencycheck.data.nvdcve.DatabaseException;
 44  
 import org.owasp.dependencycheck.dependency.Confidence;
 45  
 import org.owasp.dependencycheck.dependency.Dependency;
 46  
 import org.owasp.dependencycheck.dependency.Evidence;
 47  
 import org.owasp.dependencycheck.dependency.EvidenceCollection;
 48  
 import org.owasp.dependencycheck.dependency.Identifier;
 49  
 import org.owasp.dependencycheck.dependency.VulnerableSoftware;
 50  
 import org.owasp.dependencycheck.utils.DependencyVersion;
 51  
 import org.owasp.dependencycheck.utils.DependencyVersionUtil;
 52  
 
 53  
 /**
 54  
  * CPEAnalyzer is a utility class that takes a project dependency and attempts to discern if there is an associated CPE.
 55  
  * It uses the evidence contained within the dependency to search the Lucene index.
 56  
  *
 57  
  * @author Jeremy Long <jeremy.long@owasp.org>
 58  
  */
 59  
 public class CPEAnalyzer implements Analyzer {
 60  
 
 61  
     /**
 62  
      * The Logger.
 63  
      */
 64  1
     private static final Logger LOGGER = Logger.getLogger(CPEAnalyzer.class.getName());
 65  
     /**
 66  
      * The maximum number of query results to return.
 67  
      */
 68  
     static final int MAX_QUERY_RESULTS = 25;
 69  
     /**
 70  
      * The weighting boost to give terms when constructing the Lucene query.
 71  
      */
 72  
     static final String WEIGHTING_BOOST = "^5";
 73  
     /**
 74  
      * A string representation of a regular expression defining characters utilized within the CPE Names.
 75  
      */
 76  
     static final String CLEANSE_CHARACTER_RX = "[^A-Za-z0-9 ._-]";
 77  
     /**
 78  
      * A string representation of a regular expression used to remove all but alpha characters.
 79  
      */
 80  
     static final String CLEANSE_NONALPHA_RX = "[^A-Za-z]*";
 81  
     /**
 82  
      * The additional size to add to a new StringBuilder to account for extra data that will be written into the string.
 83  
      */
 84  
     static final int STRING_BUILDER_BUFFER = 20;
 85  
     /**
 86  
      * The CPE in memory index.
 87  
      */
 88  
     private CpeMemoryIndex cpe;
 89  
     /**
 90  
      * The CVE Database.
 91  
      */
 92  
     private CveDB cve;
 93  
 
 94  
     /**
 95  
      * The URL to perform a search of the NVD CVE data at NIST.
 96  
      */
 97  
     public static final String NVD_SEARCH_URL = "https://web.nvd.nist.gov/view/vuln/search-results?adv_search=true&cves=on&cpe_version=%s";
 98  
 
 99  
     /**
 100  
      * Returns the name of this analyzer.
 101  
      *
 102  
      * @return the name of this analyzer.
 103  
      */
 104  
     @Override
 105  
     public String getName() {
 106  4
         return "CPE Analyzer";
 107  
     }
 108  
 
 109  
     /**
 110  
      * Returns the analysis phase that this analyzer should run in.
 111  
      *
 112  
      * @return the analysis phase that this analyzer should run in.
 113  
      */
 114  
     @Override
 115  
     public AnalysisPhase getAnalysisPhase() {
 116  1
         return AnalysisPhase.IDENTIFIER_ANALYSIS;
 117  
     }
 118  
 
 119  
     /**
 120  
      * Creates the CPE Lucene Index.
 121  
      *
 122  
      * @throws Exception is thrown if there is an issue opening the index.
 123  
      */
 124  
     @Override
 125  
     public void initialize() throws Exception {
 126  1
         this.open();
 127  1
     }
 128  
 
 129  
     /**
 130  
      * Opens the data source.
 131  
      *
 132  
      * @throws IOException when the Lucene directory to be queried does not exist or is corrupt.
 133  
      * @throws DatabaseException when the database throws an exception. This usually occurs when the database is in use
 134  
      * by another process.
 135  
      */
 136  
     public void open() throws IOException, DatabaseException {
 137  1
         LOGGER.log(Level.FINE, "Opening the CVE Database");
 138  1
         cve = new CveDB();
 139  1
         cve.open();
 140  1
         LOGGER.log(Level.FINE, "Creating the Lucene CPE Index");
 141  1
         cpe = CpeMemoryIndex.getInstance();
 142  
         try {
 143  1
             cpe.open(cve);
 144  0
         } catch (IndexException ex) {
 145  0
             LOGGER.log(Level.FINE, "IndexException", ex);
 146  0
             throw new DatabaseException(ex);
 147  1
         }
 148  1
     }
 149  
 
 150  
     /**
 151  
      * Closes the data sources.
 152  
      */
 153  
     @Override
 154  
     public void close() {
 155  1
         if (cpe != null) {
 156  1
             cpe.close();
 157  
         }
 158  1
         if (cve != null) {
 159  1
             cve.close();
 160  
         }
 161  1
     }
 162  
 
 163  
     /**
 164  
      * Searches the data store of CPE entries, trying to identify the CPE for the given dependency based on the evidence
 165  
      * contained within. The dependency passed in is updated with any identified CPE values.
 166  
      *
 167  
      * @param dependency the dependency to search for CPE entries on.
 168  
      * @throws CorruptIndexException is thrown when the Lucene index is corrupt.
 169  
      * @throws IOException is thrown when an IOException occurs.
 170  
      * @throws ParseException is thrown when the Lucene query cannot be parsed.
 171  
      */
 172  
     protected void determineCPE(Dependency dependency) throws CorruptIndexException, IOException, ParseException {
 173  
         //TODO test dojo-war against this. we shold get dojo-toolkit:dojo-toolkit AND dojo-toolkit:toolkit
 174  2
         String vendors = "";
 175  2
         String products = "";
 176  7
         for (Confidence confidence : Confidence.values()) {
 177  6
             if (dependency.getVendorEvidence().contains(confidence)) {
 178  6
                 vendors = addEvidenceWithoutDuplicateTerms(vendors, dependency.getVendorEvidence(), confidence);
 179  
             }
 180  6
             if (dependency.getProductEvidence().contains(confidence)) {
 181  5
                 products = addEvidenceWithoutDuplicateTerms(products, dependency.getProductEvidence(), confidence);
 182  
             }
 183  
             /* bug fix for #40 - version evidence is not showing up as "used" in the reports if there is no
 184  
              * CPE identified. As such, we are "using" the evidence and ignoring the results. */
 185  
 //            if (dependency.getVersionEvidence().contains(confidence)) {
 186  
 //                addEvidenceWithoutDuplicateTerms("", dependency.getVersionEvidence(), confidence);
 187  
 //            }
 188  6
             if (!vendors.isEmpty() && !products.isEmpty()) {
 189  6
                 final List<IndexEntry> entries = searchCPE(vendors, products, dependency.getProductEvidence().getWeighting(),
 190  
                         dependency.getVendorEvidence().getWeighting());
 191  
 
 192  6
                 boolean identifierAdded = false;
 193  6
                 for (IndexEntry e : entries) {
 194  23
                     if (verifyEntry(e, dependency)) {
 195  2
                         final String vendor = e.getVendor();
 196  2
                         final String product = e.getProduct();
 197  2
                         identifierAdded |= determineIdentifiers(dependency, vendor, product, confidence);
 198  
                     }
 199  23
                 }
 200  6
                 if (identifierAdded) {
 201  1
                     break;
 202  
                 }
 203  
             }
 204  
         }
 205  2
     }
 206  
 
 207  
     /**
 208  
      * Returns the text created by concatenating the text and the values from the EvidenceCollection (filtered for a
 209  
      * specific confidence). This attempts to prevent duplicate terms from being added.<br/<br/> Note, if the evidence
 210  
      * is longer then 200 characters it will be truncated.
 211  
      *
 212  
      * @param text the base text.
 213  
      * @param ec an EvidenceCollection
 214  
      * @param confidenceFilter a Confidence level to filter the evidence by.
 215  
      * @return the new evidence text
 216  
      */
 217  
     private String addEvidenceWithoutDuplicateTerms(final String text, final EvidenceCollection ec, Confidence confidenceFilter) {
 218  11
         final String txt = (text == null) ? "" : text;
 219  11
         final StringBuilder sb = new StringBuilder(txt.length() + (20 * ec.size()));
 220  11
         sb.append(' ').append(txt).append(' ');
 221  11
         for (Evidence e : ec.iterator(confidenceFilter)) {
 222  39
             String value = e.getValue();
 223  
 
 224  
             //hack to get around the fact that lucene does a really good job of recognizing domains and not
 225  
             // splitting them. TODO - put together a better lucene analyzer specific to the domain.
 226  39
             if (value.startsWith("http://")) {
 227  2
                 value = value.substring(7).replaceAll("\\.", " ");
 228  
             }
 229  39
             if (value.startsWith("https://")) {
 230  0
                 value = value.substring(8).replaceAll("\\.", " ");
 231  
             }
 232  39
             if (sb.indexOf(" " + value + " ") < 0) {
 233  34
                 sb.append(value).append(' ');
 234  
             }
 235  39
         }
 236  11
         return sb.toString().trim();
 237  
     }
 238  
 
 239  
     /**
 240  
      * <p>
 241  
      * Searches the Lucene CPE index to identify possible CPE entries associated with the supplied vendor, product, and
 242  
      * version.</p>
 243  
      *
 244  
      * <p>
 245  
      * If either the vendorWeightings or productWeightings lists have been populated this data is used to add weighting
 246  
      * factors to the search.</p>
 247  
      *
 248  
      * @param vendor the text used to search the vendor field
 249  
      * @param product the text used to search the product field
 250  
      * @param vendorWeightings a list of strings to use to add weighting factors to the vendor field
 251  
      * @param productWeightings Adds a list of strings that will be used to add weighting factors to the product search
 252  
      * @return a list of possible CPE values
 253  
      * @throws CorruptIndexException when the Lucene index is corrupt
 254  
      * @throws IOException when the Lucene index is not found
 255  
      * @throws ParseException when the generated query is not valid
 256  
      */
 257  
     protected List<IndexEntry> searchCPE(String vendor, String product,
 258  
             Set<String> vendorWeightings, Set<String> productWeightings)
 259  
             throws CorruptIndexException, IOException, ParseException {
 260  6
         final ArrayList<IndexEntry> ret = new ArrayList<IndexEntry>(MAX_QUERY_RESULTS);
 261  
 
 262  6
         final String searchString = buildSearch(vendor, product, vendorWeightings, productWeightings);
 263  6
         if (searchString == null) {
 264  0
             return ret;
 265  
         }
 266  
 
 267  6
         final TopDocs docs = cpe.search(searchString, MAX_QUERY_RESULTS);
 268  156
         for (ScoreDoc d : docs.scoreDocs) {
 269  150
             if (d.score >= 0.08) {
 270  23
                 final Document doc = cpe.getDocument(d.doc);
 271  23
                 final IndexEntry entry = new IndexEntry();
 272  23
                 entry.setVendor(doc.get(Fields.VENDOR));
 273  23
                 entry.setProduct(doc.get(Fields.PRODUCT));
 274  
 //                if (d.score < 0.08) {
 275  
 //                    System.out.print(entry.getVendor());
 276  
 //                    System.out.print(":");
 277  
 //                    System.out.print(entry.getProduct());
 278  
 //                    System.out.print(":");
 279  
 //                    System.out.println(d.score);
 280  
 //                }
 281  23
                 entry.setSearchScore(d.score);
 282  23
                 if (!ret.contains(entry)) {
 283  23
                     ret.add(entry);
 284  
                 }
 285  
             }
 286  
         }
 287  6
         return ret;
 288  
     }
 289  
 
 290  
     /**
 291  
      * <p>
 292  
      * Builds a Lucene search string by properly escaping data and constructing a valid search query.</p>
 293  
      *
 294  
      * <p>
 295  
      * If either the possibleVendor or possibleProducts lists have been populated this data is used to add weighting
 296  
      * factors to the search string generated.</p>
 297  
      *
 298  
      * @param vendor text to search the vendor field
 299  
      * @param product text to search the product field
 300  
      * @param vendorWeighting a list of strings to apply to the vendor to boost the terms weight
 301  
      * @param productWeightings a list of strings to apply to the product to boost the terms weight
 302  
      * @return the Lucene query
 303  
      */
 304  
     protected String buildSearch(String vendor, String product,
 305  
             Set<String> vendorWeighting, Set<String> productWeightings) {
 306  6
         final String v = vendor; //.replaceAll("[^\\w\\d]", " ");
 307  6
         final String p = product; //.replaceAll("[^\\w\\d]", " ");
 308  6
         final StringBuilder sb = new StringBuilder(v.length() + p.length()
 309  
                 + Fields.PRODUCT.length() + Fields.VENDOR.length() + STRING_BUILDER_BUFFER);
 310  
 
 311  6
         if (!appendWeightedSearch(sb, Fields.PRODUCT, p, productWeightings)) {
 312  0
             return null;
 313  
         }
 314  6
         sb.append(" AND ");
 315  6
         if (!appendWeightedSearch(sb, Fields.VENDOR, v, vendorWeighting)) {
 316  0
             return null;
 317  
         }
 318  6
         return sb.toString();
 319  
     }
 320  
 
 321  
     /**
 322  
      * This method constructs a Lucene query for a given field. The searchText is split into separate words and if the
 323  
      * word is within the list of weighted words then an additional weighting is applied to the term as it is appended
 324  
      * into the query.
 325  
      *
 326  
      * @param sb a StringBuilder that the query text will be appended to.
 327  
      * @param field the field within the Lucene index that the query is searching.
 328  
      * @param searchText text used to construct the query.
 329  
      * @param weightedText a list of terms that will be considered higher importance when searching.
 330  
      * @return if the append was successful.
 331  
      */
 332  
     private boolean appendWeightedSearch(StringBuilder sb, String field, String searchText, Set<String> weightedText) {
 333  12
         sb.append(" ").append(field).append(":( ");
 334  
 
 335  12
         final String cleanText = cleanseText(searchText);
 336  
 
 337  12
         if ("".equals(cleanText)) {
 338  0
             return false;
 339  
         }
 340  
 
 341  12
         if (weightedText == null || weightedText.isEmpty()) {
 342  0
             LuceneUtils.appendEscapedLuceneQuery(sb, cleanText);
 343  
         } else {
 344  12
             final StringTokenizer tokens = new StringTokenizer(cleanText);
 345  108
             while (tokens.hasMoreElements()) {
 346  96
                 final String word = tokens.nextToken();
 347  96
                 String temp = null;
 348  96
                 for (String weighted : weightedText) {
 349  215
                     final String weightedStr = cleanseText(weighted);
 350  215
                     if (equalsIgnoreCaseAndNonAlpha(word, weightedStr)) {
 351  22
                         temp = LuceneUtils.escapeLuceneQuery(word) + WEIGHTING_BOOST;
 352  22
                         if (!word.equalsIgnoreCase(weightedStr)) {
 353  0
                             temp += " " + LuceneUtils.escapeLuceneQuery(weightedStr) + WEIGHTING_BOOST;
 354  
                         }
 355  
                     }
 356  215
                 }
 357  96
                 if (temp == null) {
 358  74
                     temp = LuceneUtils.escapeLuceneQuery(word);
 359  
                 }
 360  96
                 sb.append(" ").append(temp);
 361  96
             }
 362  
         }
 363  12
         sb.append(" ) ");
 364  12
         return true;
 365  
     }
 366  
 
 367  
     /**
 368  
      * Removes characters from the input text that are not used within the CPE index.
 369  
      *
 370  
      * @param text is the text to remove the characters from.
 371  
      * @return the text having removed some characters.
 372  
      */
 373  
     private String cleanseText(String text) {
 374  227
         return text.replaceAll(CLEANSE_CHARACTER_RX, " ");
 375  
     }
 376  
 
 377  
     /**
 378  
      * Compares two strings after lower casing them and removing the non-alpha characters.
 379  
      *
 380  
      * @param l string one to compare.
 381  
      * @param r string two to compare.
 382  
      * @return whether or not the two strings are similar.
 383  
      */
 384  
     private boolean equalsIgnoreCaseAndNonAlpha(String l, String r) {
 385  215
         if (l == null || r == null) {
 386  0
             return false;
 387  
         }
 388  
 
 389  215
         final String left = l.replaceAll(CLEANSE_NONALPHA_RX, "");
 390  215
         final String right = r.replaceAll(CLEANSE_NONALPHA_RX, "");
 391  215
         return left.equalsIgnoreCase(right);
 392  
     }
 393  
 
 394  
     /**
 395  
      * Ensures that the CPE Identified matches the dependency. This validates that the product, vendor, and version
 396  
      * information for the CPE are contained within the dependencies evidence.
 397  
      *
 398  
      * @param entry a CPE entry.
 399  
      * @param dependency the dependency that the CPE entries could be for.
 400  
      * @return whether or not the entry is valid.
 401  
      */
 402  
     private boolean verifyEntry(final IndexEntry entry, final Dependency dependency) {
 403  23
         boolean isValid = false;
 404  
 
 405  23
         if (collectionContainsString(dependency.getProductEvidence(), entry.getProduct())
 406  
                 && collectionContainsString(dependency.getVendorEvidence(), entry.getVendor())) {
 407  
             //&& collectionContainsVersion(dependency.getVersionEvidence(), entry.getVersion())
 408  2
             isValid = true;
 409  
         }
 410  23
         return isValid;
 411  
     }
 412  
 
 413  
     /**
 414  
      * Used to determine if the EvidenceCollection contains a specific string.
 415  
      *
 416  
      * @param ec an EvidenceCollection
 417  
      * @param text the text to search for
 418  
      * @return whether or not the EvidenceCollection contains the string
 419  
      */
 420  
     private boolean collectionContainsString(EvidenceCollection ec, String text) {
 421  
 
 422  
         //<editor-fold defaultstate="collapsed" desc="This code fold contains an old version of the code, delete once more testing is done">
 423  
         //        String[] splitText = text.split("[\\s_-]");
 424  
         //
 425  
         //        for (String search : splitText) {
 426  
         //            //final String search = text.replaceAll("[\\s_-]", "").toLowerCase();
 427  
         //            if (ec.containsUsedString(search)) {
 428  
         //                return true;
 429  
         //            }
 430  
         //        }
 431  
         //</editor-fold>
 432  
         //TODO - likely need to change the split... not sure if this will work for CPE with special chars
 433  25
         if (text == null) {
 434  0
             return false;
 435  
         }
 436  25
         final String[] words = text.split("[\\s_-]");
 437  25
         final List<String> list = new ArrayList<String>();
 438  25
         String tempWord = null;
 439  83
         for (String word : words) {
 440  
             /*
 441  
              single letter words should be concatenated with the next word.
 442  
              so { "m", "core", "sample" } -> { "mcore", "sample" }
 443  
              */
 444  58
             if (tempWord != null) {
 445  2
                 list.add(tempWord + word);
 446  2
                 tempWord = null;
 447  56
             } else if (word.length() <= 2) {
 448  2
                 tempWord = word;
 449  
             } else {
 450  54
                 list.add(word);
 451  
             }
 452  
         }
 453  25
         if (tempWord != null && !list.isEmpty()) {
 454  0
             final String tmp = list.get(list.size() - 1) + tempWord;
 455  0
             list.add(tmp);
 456  
         }
 457  25
         boolean contains = true;
 458  25
         for (String word : list) {
 459  56
             contains &= ec.containsUsedString(word);
 460  56
         }
 461  25
         return contains;
 462  
     }
 463  
 
 464  
     /**
 465  
      * Analyzes a dependency and attempts to determine if there are any CPE identifiers for this dependency.
 466  
      *
 467  
      * @param dependency The Dependency to analyze.
 468  
      * @param engine The analysis engine
 469  
      * @throws AnalysisException is thrown if there is an issue analyzing the dependency.
 470  
      */
 471  
     @Override
 472  
     public void analyze(Dependency dependency, Engine engine) throws AnalysisException {
 473  
         try {
 474  2
             determineCPE(dependency);
 475  0
         } catch (CorruptIndexException ex) {
 476  0
             throw new AnalysisException("CPE Index is corrupt.", ex);
 477  0
         } catch (IOException ex) {
 478  0
             throw new AnalysisException("Failure opening the CPE Index.", ex);
 479  0
         } catch (ParseException ex) {
 480  0
             throw new AnalysisException("Unable to parse the generated Lucene query for this dependency.", ex);
 481  2
         }
 482  2
     }
 483  
 
 484  
     /**
 485  
      * Retrieves a list of CPE values from the CveDB based on the vendor and product passed in. The list is then
 486  
      * validated to find only CPEs that are valid for the given dependency. It is possible that the CPE identified is a
 487  
      * best effort "guess" based on the vendor, product, and version information.
 488  
      *
 489  
      * @param dependency the Dependency being analyzed
 490  
      * @param vendor the vendor for the CPE being analyzed
 491  
      * @param product the product for the CPE being analyzed
 492  
      * @return <code>true</code> if an identifier was added to the dependency; otherwise <code>false</code>
 493  
      * @throws UnsupportedEncodingException is thrown if UTF-8 is not supported
 494  
      */
 495  
     private boolean determineIdentifiers(Dependency dependency, String vendor, String product, Confidence currentConfidence) throws UnsupportedEncodingException {
 496  2
         final Set<VulnerableSoftware> cpes = cve.getCPEs(vendor, product);
 497  2
         DependencyVersion bestGuess = new DependencyVersion("-");
 498  2
         Confidence bestGuessConf = null;
 499  2
         boolean hasBroadMatch = false;
 500  2
         final List<IdentifierMatch> collected = new ArrayList<IdentifierMatch>();
 501  10
         for (Confidence conf : Confidence.values()) {
 502  
 //            if (conf.compareTo(currentConfidence) > 0) {
 503  
 //                break;
 504  
 //            }
 505  8
             for (Evidence evidence : dependency.getVersionEvidence().iterator(conf)) {
 506  8
                 final DependencyVersion evVer = DependencyVersionUtil.parseVersion(evidence.getValue());
 507  8
                 if (evVer == null) {
 508  0
                     continue;
 509  
                 }
 510  8
                 for (VulnerableSoftware vs : cpes) {
 511  
                     DependencyVersion dbVer;
 512  312
                     if (vs.getRevision() != null && !vs.getRevision().isEmpty()) {
 513  128
                         dbVer = DependencyVersionUtil.parseVersion(vs.getVersion() + "." + vs.getRevision());
 514  
                     } else {
 515  184
                         dbVer = DependencyVersionUtil.parseVersion(vs.getVersion());
 516  
                     }
 517  312
                     if (dbVer == null) { //special case, no version specified - everything is vulnerable
 518  0
                         hasBroadMatch = true;
 519  0
                         final String url = String.format(NVD_SEARCH_URL, URLEncoder.encode(vs.getName(), "UTF-8"));
 520  0
                         final IdentifierMatch match = new IdentifierMatch("cpe", vs.getName(), url, IdentifierConfidence.BROAD_MATCH, conf);
 521  0
                         collected.add(match);
 522  0
                     } else if (evVer.equals(dbVer)) { //yeah! exact match
 523  8
                         final String url = String.format(NVD_SEARCH_URL, URLEncoder.encode(vs.getName(), "UTF-8"));
 524  8
                         final IdentifierMatch match = new IdentifierMatch("cpe", vs.getName(), url, IdentifierConfidence.EXACT_MATCH, conf);
 525  8
                         collected.add(match);
 526  8
                     } else {
 527  
                         //TODO the following isn't quite right is it? need to think about this guessing game a bit more.
 528  304
                         if (evVer.getVersionParts().size() <= dbVer.getVersionParts().size()
 529  
                                 && evVer.matchesAtLeastThreeLevels(dbVer)) {
 530  64
                             if (bestGuessConf == null || bestGuessConf.compareTo(conf) > 0) {
 531  2
                                 if (bestGuess.getVersionParts().size() < dbVer.getVersionParts().size()) {
 532  2
                                     bestGuess = dbVer;
 533  2
                                     bestGuessConf = conf;
 534  
                                 }
 535  
                             }
 536  
                         }
 537  
                     }
 538  312
                 }
 539  8
                 if (bestGuessConf == null || bestGuessConf.compareTo(conf) > 0) {
 540  0
                     if (bestGuess.getVersionParts().size() < evVer.getVersionParts().size()) {
 541  0
                         bestGuess = evVer;
 542  0
                         bestGuessConf = conf;
 543  
                     }
 544  
                 }
 545  8
             }
 546  
         }
 547  2
         final String cpeName = String.format("cpe:/a:%s:%s:%s", vendor, product, bestGuess.toString());
 548  2
         String url = null;
 549  2
         if (hasBroadMatch) { //if we have a broad match we can add the URL to the best guess.
 550  0
             final String cpeUrlName = String.format("cpe:/a:%s:%s", vendor, product);
 551  0
             url = String.format(NVD_SEARCH_URL, URLEncoder.encode(cpeUrlName, "UTF-8"));
 552  
         }
 553  2
         if (bestGuessConf == null) {
 554  0
             bestGuessConf = Confidence.LOW;
 555  
         }
 556  2
         final IdentifierMatch match = new IdentifierMatch("cpe", cpeName, url, IdentifierConfidence.BEST_GUESS, bestGuessConf);
 557  2
         collected.add(match);
 558  
 
 559  2
         Collections.sort(collected);
 560  2
         final IdentifierConfidence bestIdentifierQuality = collected.get(0).getConfidence();
 561  2
         final Confidence bestEvidenceQuality = collected.get(0).getEvidenceConfidence();
 562  2
         boolean identifierAdded = false;
 563  2
         for (IdentifierMatch m : collected) {
 564  10
             if (bestIdentifierQuality.equals(m.getConfidence())
 565  
                     && bestEvidenceQuality.equals(m.getEvidenceConfidence())) {
 566  2
                 final Identifier i = m.getIdentifier();
 567  2
                 if (bestIdentifierQuality == IdentifierConfidence.BEST_GUESS) {
 568  0
                     i.setConfidence(Confidence.LOW);
 569  
                 } else {
 570  2
                     i.setConfidence(bestEvidenceQuality);
 571  
                 }
 572  2
                 dependency.addIdentifier(i);
 573  2
                 identifierAdded = true;
 574  
             }
 575  10
         }
 576  2
         return identifierAdded;
 577  
     }
 578  
 
 579  
     /**
 580  
      * The confidence whether the identifier is an exact match, or a best guess.
 581  
      */
 582  1
     private enum IdentifierConfidence {
 583  
 
 584  
         /**
 585  
          * An exact match for the CPE.
 586  
          */
 587  1
         EXACT_MATCH,
 588  
         /**
 589  
          * A best guess for the CPE.
 590  
          */
 591  1
         BEST_GUESS,
 592  
         /**
 593  
          * The entire vendor/product group must be added (without a guess at version) because there is a CVE with a VS
 594  
          * that only specifies vendor/product.
 595  
          */
 596  1
         BROAD_MATCH
 597  
     }
 598  
 
 599  
     /**
 600  
      * A simple object to hold an identifier and carry information about the confidence in the identifier.
 601  
      */
 602  8
     private static class IdentifierMatch implements Comparable<IdentifierMatch> {
 603  
 
 604  
         /**
 605  
          * Constructs an IdentifierMatch.
 606  
          *
 607  
          * @param type the type of identifier (such as CPE)
 608  
          * @param value the value of the identifier
 609  
          * @param url the URL of the identifier
 610  
          * @param identifierConfidence the confidence in the identifier: best guess or exact match
 611  
          * @param evidenceConfidence the confidence of the evidence used to find the identifier
 612  
          */
 613  10
         IdentifierMatch(String type, String value, String url, IdentifierConfidence identifierConfidence, Confidence evidenceConfidence) {
 614  10
             this.identifier = new Identifier(type, value, url);
 615  10
             this.confidence = identifierConfidence;
 616  10
             this.evidenceConfidence = evidenceConfidence;
 617  10
         }
 618  
         //<editor-fold defaultstate="collapsed" desc="Property implementations: evidenceConfidence, confidence, identifier">
 619  
         /**
 620  
          * The confidence in the evidence used to identify this match.
 621  
          */
 622  
         private Confidence evidenceConfidence;
 623  
 
 624  
         /**
 625  
          * Get the value of evidenceConfidence
 626  
          *
 627  
          * @return the value of evidenceConfidence
 628  
          */
 629  
         public Confidence getEvidenceConfidence() {
 630  
             return evidenceConfidence;
 631  
         }
 632  
 
 633  
         /**
 634  
          * Set the value of evidenceConfidence
 635  
          *
 636  
          * @param evidenceConfidence new value of evidenceConfidence
 637  
          */
 638  
         public void setEvidenceConfidence(Confidence evidenceConfidence) {
 639  
             this.evidenceConfidence = evidenceConfidence;
 640  
         }
 641  
         /**
 642  
          * The confidence whether this is an exact match, or a best guess.
 643  
          */
 644  
         private IdentifierConfidence confidence;
 645  
 
 646  
         /**
 647  
          * Get the value of confidence.
 648  
          *
 649  
          * @return the value of confidence
 650  
          */
 651  
         public IdentifierConfidence getConfidence() {
 652  
             return confidence;
 653  
         }
 654  
 
 655  
         /**
 656  
          * Set the value of confidence.
 657  
          *
 658  
          * @param confidence new value of confidence
 659  
          */
 660  
         public void setConfidence(IdentifierConfidence confidence) {
 661  
             this.confidence = confidence;
 662  
         }
 663  
         /**
 664  
          * The CPE identifier.
 665  
          */
 666  
         private Identifier identifier;
 667  
 
 668  
         /**
 669  
          * Get the value of identifier.
 670  
          *
 671  
          * @return the value of identifier
 672  
          */
 673  
         public Identifier getIdentifier() {
 674  
             return identifier;
 675  
         }
 676  
 
 677  
         /**
 678  
          * Set the value of identifier.
 679  
          *
 680  
          * @param identifier new value of identifier
 681  
          */
 682  
         public void setIdentifier(Identifier identifier) {
 683  
             this.identifier = identifier;
 684  
         }
 685  
         //</editor-fold>
 686  
         //<editor-fold defaultstate="collapsed" desc="Standard implementations of toString, hashCode, and equals">
 687  
 
 688  
         /**
 689  
          * Standard toString() implementation.
 690  
          *
 691  
          * @return the string representation of the object
 692  
          */
 693  
         @Override
 694  
         public String toString() {
 695  0
             return "IdentifierMatch{" + "evidenceConfidence=" + evidenceConfidence
 696  
                     + ", confidence=" + confidence + ", identifier=" + identifier + '}';
 697  
         }
 698  
 
 699  
         /**
 700  
          * Standard hashCode() implementation.
 701  
          *
 702  
          * @return the hashCode
 703  
          */
 704  
         @Override
 705  
         public int hashCode() {
 706  0
             int hash = 5;
 707  0
             hash = 97 * hash + (this.evidenceConfidence != null ? this.evidenceConfidence.hashCode() : 0);
 708  0
             hash = 97 * hash + (this.confidence != null ? this.confidence.hashCode() : 0);
 709  0
             hash = 97 * hash + (this.identifier != null ? this.identifier.hashCode() : 0);
 710  0
             return hash;
 711  
         }
 712  
 
 713  
         /**
 714  
          * Standard equals implementation.
 715  
          *
 716  
          * @param obj the object to compare
 717  
          * @return true if the objects are equal, otherwise false
 718  
          */
 719  
         @Override
 720  
         public boolean equals(Object obj) {
 721  0
             if (obj == null) {
 722  0
                 return false;
 723  
             }
 724  0
             if (getClass() != obj.getClass()) {
 725  0
                 return false;
 726  
             }
 727  0
             final IdentifierMatch other = (IdentifierMatch) obj;
 728  0
             if (this.evidenceConfidence != other.evidenceConfidence) {
 729  0
                 return false;
 730  
             }
 731  0
             if (this.confidence != other.confidence) {
 732  0
                 return false;
 733  
             }
 734  0
             if (this.identifier != other.identifier && (this.identifier == null || !this.identifier.equals(other.identifier))) {
 735  0
                 return false;
 736  
             }
 737  0
             return true;
 738  
         }
 739  
         //</editor-fold>
 740  
 
 741  
         /**
 742  
          * Standard implementation of compareTo that compares identifier confidence, evidence confidence, and then the
 743  
          * identifier.
 744  
          *
 745  
          * @param o the IdentifierMatch to compare to
 746  
          * @return the natural ordering of IdentifierMatch
 747  
          */
 748  
         @Override
 749  
         public int compareTo(IdentifierMatch o) {
 750  8
             int conf = this.confidence.compareTo(o.confidence);
 751  8
             if (conf == 0) {
 752  6
                 conf = this.evidenceConfidence.compareTo(o.evidenceConfidence);
 753  6
                 if (conf == 0) {
 754  2
                     conf = identifier.compareTo(o.identifier);
 755  
                 }
 756  
             }
 757  8
             return conf;
 758  
         }
 759  
     }
 760  
 }