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