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