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