Coverage Report - org.owasp.dependencycheck.data.cpe.CpeMemoryIndex
 
Classes in this File Line Coverage Branch Coverage Complexity
CpeMemoryIndex
73%
68/92
42%
12/28
2.929
 
 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) 2013 Jeremy Long. All Rights Reserved.
 17  
  */
 18  
 package org.owasp.dependencycheck.data.cpe;
 19  
 
 20  
 import java.io.IOException;
 21  
 import java.util.HashMap;
 22  
 import java.util.Map;
 23  
 import java.util.Set;
 24  
 import java.util.logging.Level;
 25  
 import java.util.logging.Logger;
 26  
 import org.apache.lucene.analysis.Analyzer;
 27  
 import org.apache.lucene.analysis.core.KeywordAnalyzer;
 28  
 import org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper;
 29  
 import org.apache.lucene.document.Document;
 30  
 import org.apache.lucene.document.Field;
 31  
 import org.apache.lucene.document.TextField;
 32  
 import org.apache.lucene.index.CorruptIndexException;
 33  
 import org.apache.lucene.index.DirectoryReader;
 34  
 import org.apache.lucene.index.IndexReader;
 35  
 import org.apache.lucene.index.IndexWriter;
 36  
 import org.apache.lucene.index.IndexWriterConfig;
 37  
 import org.apache.lucene.queryparser.classic.ParseException;
 38  
 import org.apache.lucene.queryparser.classic.QueryParser;
 39  
 import org.apache.lucene.search.IndexSearcher;
 40  
 import org.apache.lucene.search.Query;
 41  
 import org.apache.lucene.search.TopDocs;
 42  
 import org.apache.lucene.store.RAMDirectory;
 43  
 import org.owasp.dependencycheck.data.lucene.FieldAnalyzer;
 44  
 import org.owasp.dependencycheck.data.lucene.LuceneUtils;
 45  
 import org.owasp.dependencycheck.data.lucene.SearchFieldAnalyzer;
 46  
 import org.owasp.dependencycheck.data.nvdcve.CveDB;
 47  
 import org.owasp.dependencycheck.data.nvdcve.DatabaseException;
 48  
 import org.owasp.dependencycheck.utils.Pair;
 49  
 
 50  
 /**
 51  
  * An in memory lucene index that contains the vendor/product combinations from the CPE (application) identifiers within
 52  
  * the NVD CVE data.
 53  
  *
 54  
  * @author Jeremy Long <jeremy.long@owasp.org>
 55  
  */
 56  
 public final class CpeMemoryIndex {
 57  
 
 58  
     /**
 59  
      * The logger.
 60  
      */
 61  1
     private static final Logger LOGGER = Logger.getLogger(CpeMemoryIndex.class.getName());
 62  
     /**
 63  
      * singleton instance.
 64  
      */
 65  1
     private static CpeMemoryIndex instance = new CpeMemoryIndex();
 66  
 
 67  
     /**
 68  
      * private constructor for singleton.
 69  
      */
 70  
     private CpeMemoryIndex() {
 71  
     }
 72  
 
 73  
     /**
 74  
      * Gets the singleton instance of the CpeMemoryIndex.
 75  
      *
 76  
      * @return the instance of the CpeMemoryIndex
 77  
      */
 78  
     public static CpeMemoryIndex getInstance() {
 79  2
         return instance;
 80  
     }
 81  
     /**
 82  
      * The in memory Lucene index.
 83  
      */
 84  
     private RAMDirectory index;
 85  
     /**
 86  
      * The Lucene IndexReader.
 87  
      */
 88  
     private IndexReader indexReader;
 89  
     /**
 90  
      * The Lucene IndexSearcher.
 91  
      */
 92  
     private IndexSearcher indexSearcher;
 93  
     /**
 94  
      * The Lucene Analyzer used for Searching.
 95  
      */
 96  
     private Analyzer searchingAnalyzer;
 97  
     /**
 98  
      * The Lucene QueryParser used for Searching.
 99  
      */
 100  
     private QueryParser queryParser;
 101  
     /**
 102  
      * The search field analyzer for the product field.
 103  
      */
 104  
     private SearchFieldAnalyzer productSearchFieldAnalyzer;
 105  
     /**
 106  
      * The search field analyzer for the vendor field.
 107  
      */
 108  
     private SearchFieldAnalyzer vendorSearchFieldAnalyzer;
 109  
 
 110  
     /**
 111  
      * Creates and loads data into an in memory index.
 112  
      *
 113  
      * @param cve the data source to retrieve the cpe data
 114  
      * @throws IndexException thrown if there is an error creating the index
 115  
      */
 116  
     public void open(CveDB cve) throws IndexException {
 117  2
         if (!openState) {
 118  1
             index = new RAMDirectory();
 119  1
             buildIndex(cve);
 120  
             try {
 121  1
                 indexReader = DirectoryReader.open(index);
 122  0
             } catch (IOException ex) {
 123  0
                 throw new IndexException(ex);
 124  1
             }
 125  1
             indexSearcher = new IndexSearcher(indexReader);
 126  1
             searchingAnalyzer = createSearchingAnalyzer();
 127  1
             queryParser = new QueryParser(LuceneUtils.CURRENT_VERSION, Fields.DOCUMENT_KEY, searchingAnalyzer);
 128  1
             openState = true;
 129  
         }
 130  2
     }
 131  
     /**
 132  
      * A flag indicating whether or not the index is open.
 133  
      */
 134  
     private boolean openState = false;
 135  
 
 136  
     /**
 137  
      * returns whether or not the index is open.
 138  
      *
 139  
      * @return whether or not the index is open
 140  
      */
 141  
     public boolean isOpen() {
 142  
         return openState;
 143  
     }
 144  
 
 145  
     /**
 146  
      * Creates the indexing analyzer for the CPE Index.
 147  
      *
 148  
      * @return the CPE Analyzer.
 149  
      */
 150  
     @SuppressWarnings("unchecked")
 151  
     private Analyzer createIndexingAnalyzer() {
 152  1
         final Map fieldAnalyzers = new HashMap();
 153  1
         fieldAnalyzers.put(Fields.DOCUMENT_KEY, new KeywordAnalyzer());
 154  1
         return new PerFieldAnalyzerWrapper(new FieldAnalyzer(LuceneUtils.CURRENT_VERSION), fieldAnalyzers);
 155  
     }
 156  
 
 157  
     /**
 158  
      * Creates an Analyzer for searching the CPE Index.
 159  
      *
 160  
      * @return the CPE Analyzer.
 161  
      */
 162  
     @SuppressWarnings("unchecked")
 163  
     private Analyzer createSearchingAnalyzer() {
 164  1
         final Map<String, Analyzer> fieldAnalyzers = new HashMap<String, Analyzer>();
 165  1
         fieldAnalyzers.put(Fields.DOCUMENT_KEY, new KeywordAnalyzer());
 166  1
         productSearchFieldAnalyzer = new SearchFieldAnalyzer(LuceneUtils.CURRENT_VERSION);
 167  1
         vendorSearchFieldAnalyzer = new SearchFieldAnalyzer(LuceneUtils.CURRENT_VERSION);
 168  1
         fieldAnalyzers.put(Fields.PRODUCT, productSearchFieldAnalyzer);
 169  1
         fieldAnalyzers.put(Fields.VENDOR, vendorSearchFieldAnalyzer);
 170  
 
 171  1
         return new PerFieldAnalyzerWrapper(new FieldAnalyzer(LuceneUtils.CURRENT_VERSION), fieldAnalyzers);
 172  
     }
 173  
 
 174  
     /**
 175  
      * Saves a CPE IndexEntry into the Lucene index.
 176  
      *
 177  
      * @param vendor the vendor to index
 178  
      * @param product the product to index
 179  
      * @param indexWriter the index writer to write the entry into
 180  
      * @throws CorruptIndexException is thrown if the index is corrupt
 181  
      * @throws IOException is thrown if an IOException occurs
 182  
      */
 183  
     public void saveEntry(String vendor, String product, IndexWriter indexWriter) throws CorruptIndexException, IOException {
 184  22135
         final Document doc = new Document();
 185  22135
         final Field v = new TextField(Fields.VENDOR, vendor, Field.Store.YES);
 186  22135
         final Field p = new TextField(Fields.PRODUCT, product, Field.Store.YES);
 187  22135
         doc.add(v);
 188  22135
         doc.add(p);
 189  22135
         indexWriter.addDocument(doc);
 190  22135
     }
 191  
 
 192  
     /**
 193  
      * Closes the CPE Index.
 194  
      */
 195  
     public void close() {
 196  1
         if (searchingAnalyzer != null) {
 197  1
             searchingAnalyzer.close();
 198  1
             searchingAnalyzer = null;
 199  
         }
 200  1
         if (indexReader != null) {
 201  
             try {
 202  1
                 indexReader.close();
 203  0
             } catch (IOException ex) {
 204  0
                 LOGGER.log(Level.FINEST, null, ex);
 205  1
             }
 206  1
             indexReader = null;
 207  
         }
 208  1
         queryParser = null;
 209  1
         indexSearcher = null;
 210  1
         if (index != null) {
 211  1
             index.close();
 212  1
             index = null;
 213  
         }
 214  1
         openState = false;
 215  1
     }
 216  
 
 217  
     /**
 218  
      * Builds the CPE Lucene Index based off of the data within the CveDB.
 219  
      *
 220  
      * @param cve the data base containing the CPE data
 221  
      * @throws IndexException thrown if there is an issue creating the index
 222  
      */
 223  
     private void buildIndex(CveDB cve) throws IndexException {
 224  1
         Analyzer analyzer = null;
 225  1
         IndexWriter indexWriter = null;
 226  
         try {
 227  1
             analyzer = createIndexingAnalyzer();
 228  1
             final IndexWriterConfig conf = new IndexWriterConfig(LuceneUtils.CURRENT_VERSION, analyzer);
 229  1
             indexWriter = new IndexWriter(index, conf);
 230  
             try {
 231  1
                 final Set<Pair<String, String>> data = cve.getVendorProductList();
 232  1
                 for (Pair<String, String> pair : data) {
 233  22135
                     saveEntry(pair.getLeft(), pair.getRight(), indexWriter);
 234  22135
                 }
 235  0
             } catch (DatabaseException ex) {
 236  0
                 LOGGER.log(Level.FINE, null, ex);
 237  0
                 throw new IndexException("Error reading CPE data", ex);
 238  1
             }
 239  0
         } catch (CorruptIndexException ex) {
 240  0
             throw new IndexException("Unable to close an in-memory index", ex);
 241  0
         } catch (IOException ex) {
 242  0
             throw new IndexException("Unable to close an in-memory index", ex);
 243  
         } finally {
 244  1
             if (indexWriter != null) {
 245  
                 try {
 246  
                     try {
 247  1
                         indexWriter.commit();
 248  
                     } finally {
 249  1
                         indexWriter.close(true);
 250  1
                     }
 251  0
                 } catch (CorruptIndexException ex) {
 252  0
                     throw new IndexException("Unable to close an in-memory index", ex);
 253  0
                 } catch (IOException ex) {
 254  0
                     throw new IndexException("Unable to close an in-memory index", ex);
 255  1
                 }
 256  1
                 if (analyzer != null) {
 257  1
                     analyzer.close();
 258  
                 }
 259  
             }
 260  
         }
 261  1
     }
 262  
 
 263  
     /**
 264  
      * Resets the searching analyzers
 265  
      */
 266  
     private void resetSearchingAnalyzer() {
 267  0
         if (productSearchFieldAnalyzer != null) {
 268  0
             productSearchFieldAnalyzer.clear();
 269  
         }
 270  0
         if (vendorSearchFieldAnalyzer != null) {
 271  0
             vendorSearchFieldAnalyzer.clear();
 272  
         }
 273  0
     }
 274  
 
 275  
     /**
 276  
      * Searches the index using the given search string.
 277  
      *
 278  
      * @param searchString the query text
 279  
      * @param maxQueryResults the maximum number of documents to return
 280  
      * @return the TopDocs found by the search
 281  
      * @throws ParseException thrown when the searchString is invalid
 282  
      * @throws IOException is thrown if there is an issue with the underlying Index
 283  
      */
 284  
     public TopDocs search(String searchString, int maxQueryResults) throws ParseException, IOException {
 285  6
         if (searchString == null || searchString.trim().isEmpty()) {
 286  0
             throw new ParseException("Query is null or empty");
 287  
         }
 288  6
         final Query query = queryParser.parse(searchString);
 289  6
         return indexSearcher.search(query, maxQueryResults);
 290  
     }
 291  
 
 292  
     /**
 293  
      * Searches the index using the given query.
 294  
      *
 295  
      * @param query the query used to search the index
 296  
      * @param maxQueryResults the max number of results to return
 297  
      * @return the TopDocs found be the query
 298  
      * @throws CorruptIndexException thrown if the Index is corrupt
 299  
      * @throws IOException thrown if there is an IOException
 300  
      */
 301  
     public TopDocs search(Query query, int maxQueryResults) throws CorruptIndexException, IOException {
 302  0
         resetSearchingAnalyzer();
 303  0
         return indexSearcher.search(query, maxQueryResults);
 304  
     }
 305  
 
 306  
     /**
 307  
      * Retrieves a document from the Index.
 308  
      *
 309  
      * @param documentId the id of the document to retrieve
 310  
      * @return the Document
 311  
      * @throws IOException thrown if there is an IOException
 312  
      */
 313  
     public Document getDocument(int documentId) throws IOException {
 314  23
         return indexSearcher.doc(documentId);
 315  
     }
 316  
 
 317  
     /**
 318  
      * Returns the number of CPE entries stored in the index.
 319  
      *
 320  
      * @return the number of CPE entries stored in the index
 321  
      */
 322  
     public int numDocs() {
 323  1
         if (indexReader == null) {
 324  0
             return -1;
 325  
         }
 326  1
         return indexReader.numDocs();
 327  
     }
 328  
 }