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