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