Coverage Report - org.owasp.dependencycheck.data.update.CpeUpdater
 
Classes in this File Line Coverage Branch Coverage Complexity
CpeUpdater
0%
0/75
0%
0/26
6.6
 
 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) 2015 Jeremy Long. All Rights Reserved.
 17  
  */
 18  
 package org.owasp.dependencycheck.data.update;
 19  
 
 20  
 import java.io.File;
 21  
 import java.io.FileInputStream;
 22  
 import java.io.FileNotFoundException;
 23  
 import java.io.FileOutputStream;
 24  
 import java.io.IOException;
 25  
 import java.net.MalformedURLException;
 26  
 import java.net.URL;
 27  
 import java.util.Date;
 28  
 import java.util.List;
 29  
 import java.util.zip.GZIPInputStream;
 30  
 import javax.xml.parsers.ParserConfigurationException;
 31  
 import javax.xml.parsers.SAXParser;
 32  
 import javax.xml.parsers.SAXParserFactory;
 33  
 import org.apache.commons.io.FileUtils;
 34  
 import static org.owasp.dependencycheck.data.nvdcve.DatabaseProperties.LAST_CPE_UPDATE;
 35  
 import org.owasp.dependencycheck.data.update.cpe.CPEHandler;
 36  
 import org.owasp.dependencycheck.data.update.cpe.Cpe;
 37  
 import org.owasp.dependencycheck.data.update.exception.UpdateException;
 38  
 import org.owasp.dependencycheck.utils.DateUtil;
 39  
 import org.owasp.dependencycheck.utils.DownloadFailedException;
 40  
 import org.owasp.dependencycheck.utils.Downloader;
 41  
 import org.owasp.dependencycheck.utils.Settings;
 42  
 import org.slf4j.Logger;
 43  
 import org.slf4j.LoggerFactory;
 44  
 import org.xml.sax.SAXException;
 45  
 
 46  
 /**
 47  
  * The CpeUpdater is designed to download the CPE data file from NIST and import the data into the database. However, as this
 48  
  * currently adds no beneficial data, compared to what is in the CPE data contained in the CVE data files, this class is not
 49  
  * currently used. The code is being kept as a future update may utilize more data from the CPE xml files.
 50  
  *
 51  
  * @author Jeremy Long
 52  
  */
 53  0
 public class CpeUpdater extends BaseUpdater implements CachedWebDataSource {
 54  
 
 55  
     /**
 56  
      * Static logger.
 57  
      */
 58  0
     private static final Logger LOGGER = LoggerFactory.getLogger(CpeUpdater.class);
 59  
 
 60  
     @Override
 61  
     public void update() throws UpdateException {
 62  
         try {
 63  0
             openDataStores();
 64  0
             if (updateNeeded()) {
 65  0
                 LOGGER.info("Updating the Common Platform Enumeration (CPE)");
 66  0
                 final File xml = downloadCpe();
 67  0
                 final List<Cpe> cpes = processXML(xml);
 68  0
                 getCveDB().deleteUnusedCpe();
 69  0
                 for (Cpe cpe : cpes) {
 70  0
                     getCveDB().addCpe(cpe.getValue(), cpe.getVendor(), cpe.getProduct());
 71  0
                 }
 72  0
                 final Date now = new Date();
 73  0
                 getProperties().save(LAST_CPE_UPDATE, Long.toString(now.getTime()));
 74  0
                 LOGGER.info("CPE update complete");
 75  
             }
 76  
         } finally {
 77  0
             closeDataStores();
 78  0
         }
 79  0
     }
 80  
 
 81  
     /**
 82  
      * Downloads the CPE XML file.
 83  
      *
 84  
      * @return the file reference to the CPE.xml file
 85  
      * @throws UpdateException thrown if there is an issue downloading the XML file
 86  
      */
 87  
     private File downloadCpe() throws UpdateException {
 88  
         File xml;
 89  
         final URL url;
 90  
         try {
 91  0
             url = new URL(Settings.getString(Settings.KEYS.CPE_URL));
 92  0
             xml = File.createTempFile("cpe", ".xml", Settings.getTempDirectory());
 93  0
             Downloader.fetchFile(url, xml);
 94  0
             if (url.toExternalForm().endsWith(".xml.gz")) {
 95  0
                 extractGzip(xml);
 96  
             }
 97  
 
 98  0
         } catch (MalformedURLException ex) {
 99  0
             throw new UpdateException("Invalid CPE URL", ex);
 100  0
         } catch (DownloadFailedException ex) {
 101  0
             throw new UpdateException("Unable to download CPE XML file", ex);
 102  0
         } catch (IOException ex) {
 103  0
             throw new UpdateException("Unable to create temporary file to download CPE", ex);
 104  0
         }
 105  0
         return xml;
 106  
     }
 107  
 
 108  
     /**
 109  
      * Parses the CPE XML file to return a list of CPE entries.
 110  
      *
 111  
      * @param xml the CPE data file
 112  
      * @return the list of CPE entries
 113  
      * @throws UpdateException thrown if there is an issue with parsing the XML file
 114  
      */
 115  
     private List<Cpe> processXML(final File xml) throws UpdateException {
 116  
         try {
 117  0
             final SAXParserFactory factory = SAXParserFactory.newInstance();
 118  0
             final SAXParser saxParser = factory.newSAXParser();
 119  0
             final CPEHandler handler = new CPEHandler();
 120  0
             saxParser.parse(xml, handler);
 121  0
             return handler.getData();
 122  0
         } catch (ParserConfigurationException ex) {
 123  0
             throw new UpdateException("Unable to parse CPE XML file due to SAX Parser Issue", ex);
 124  0
         } catch (SAXException ex) {
 125  0
             throw new UpdateException("Unable to parse CPE XML file due to SAX Parser Exception", ex);
 126  0
         } catch (IOException ex) {
 127  0
             throw new UpdateException("Unable to parse CPE XML file due to IO Failure", ex);
 128  
         }
 129  
     }
 130  
 
 131  
     /**
 132  
      * Checks to find the last time the CPE data was refreshed and if it needs to be updated.
 133  
      *
 134  
      * @return true if the CPE data should be refreshed
 135  
      */
 136  
     private boolean updateNeeded() {
 137  0
         final Date now = new Date();
 138  0
         final int days = Settings.getInt(Settings.KEYS.CVE_MODIFIED_VALID_FOR_DAYS, 30);
 139  0
         long timestamp = 0;
 140  0
         final String ts = getProperties().getProperty(LAST_CPE_UPDATE);
 141  0
         if (ts != null && ts.matches("^[0-9]+$")) {
 142  0
             timestamp = Long.parseLong(ts);
 143  
         }
 144  0
         return !DateUtil.withinDateRange(timestamp, now.getTime(), days);
 145  
     }
 146  
 
 147  
     /**
 148  
      * Extracts the file contained in a gzip archive. The extracted file is placed in the exact same path as the file specified.
 149  
      *
 150  
      * @param file the archive file
 151  
      * @throws FileNotFoundException thrown if the file does not exist
 152  
      * @throws IOException thrown if there is an error extracting the file.
 153  
      */
 154  
     private void extractGzip(File file) throws FileNotFoundException, IOException {
 155  
         //TODO - move this to a util class as it is duplicative of (copy of) code in the DownloadTask
 156  0
         final String originalPath = file.getPath();
 157  0
         final File gzip = new File(originalPath + ".gz");
 158  0
         if (gzip.isFile() && !gzip.delete()) {
 159  0
             gzip.deleteOnExit();
 160  
         }
 161  0
         if (!file.renameTo(gzip)) {
 162  0
             throw new IOException("Unable to rename '" + file.getPath() + "'");
 163  
         }
 164  0
         final File newfile = new File(originalPath);
 165  
 
 166  0
         final byte[] buffer = new byte[4096];
 167  
 
 168  0
         GZIPInputStream cin = null;
 169  0
         FileOutputStream out = null;
 170  
         try {
 171  0
             cin = new GZIPInputStream(new FileInputStream(gzip));
 172  0
             out = new FileOutputStream(newfile);
 173  
 
 174  
             int len;
 175  0
             while ((len = cin.read(buffer)) > 0) {
 176  0
                 out.write(buffer, 0, len);
 177  
             }
 178  
         } finally {
 179  0
             if (cin != null) {
 180  
                 try {
 181  0
                     cin.close();
 182  0
                 } catch (IOException ex) {
 183  0
                     LOGGER.trace("ignore", ex);
 184  0
                 }
 185  
             }
 186  0
             if (out != null) {
 187  
                 try {
 188  0
                     out.close();
 189  0
                 } catch (IOException ex) {
 190  0
                     LOGGER.trace("ignore", ex);
 191  0
                 }
 192  
             }
 193  0
             if (gzip.isFile()) {
 194  0
                 FileUtils.deleteQuietly(gzip);
 195  
             }
 196  
         }
 197  0
     }
 198  
 }