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