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