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