Coverage Report - org.owasp.dependencycheck.data.update.BatchUpdateTask
 
Classes in this File Line Coverage Branch Coverage Complexity
BatchUpdateTask
28%
30/106
17%
8/46
7.167
 
 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.data.update;
 20  
 
 21  
 import org.owasp.dependencycheck.data.nvdcve.InvalidDataException;
 22  
 import java.io.File;
 23  
 import java.io.IOException;
 24  
 import java.net.MalformedURLException;
 25  
 import java.net.URISyntaxException;
 26  
 import java.net.URL;
 27  
 import java.util.Calendar;
 28  
 import java.util.Date;
 29  
 import java.util.logging.Level;
 30  
 import java.util.logging.Logger;
 31  
 import org.owasp.dependencycheck.data.UpdateException;
 32  
 import org.owasp.dependencycheck.data.nvdcve.CveDB;
 33  
 import org.owasp.dependencycheck.utils.DownloadFailedException;
 34  
 import org.owasp.dependencycheck.utils.Downloader;
 35  
 import org.owasp.dependencycheck.utils.FileUtils;
 36  
 import org.owasp.dependencycheck.utils.Settings;
 37  
 import org.owasp.dependencycheck.utils.InvalidSettingException;
 38  
 import static org.owasp.dependencycheck.data.update.DataStoreMetaInfo.BATCH;
 39  
 import static org.owasp.dependencycheck.data.update.DataStoreMetaInfo.MODIFIED;
 40  
 
 41  
 /**
 42  
  * Class responsible for updating the CPE and NVDCVE data stores.
 43  
  *
 44  
  * @author Jeremy Long (jeremy.long@owasp.org)
 45  
  * @deprecated batch update mode will no longer be supported.
 46  
  */
 47  
 @Deprecated
 48  
 public class BatchUpdateTask extends AbstractUpdateTask {
 49  
 
 50  
     /**
 51  
      * Constructs a new BatchUpdateTask.
 52  
      *
 53  
      * @param properties information about the data store
 54  
      * @throws MalformedURLException thrown if a configured URL is malformed
 55  
      * @throws DownloadFailedException thrown if a timestamp cannot be checked
 56  
      * on a configured URL
 57  
      * @throws UpdateException thrown if there is an exception generating the
 58  
      * update task
 59  
      */
 60  
     public BatchUpdateTask(DataStoreMetaInfo properties) throws MalformedURLException, DownloadFailedException, UpdateException {
 61  2
         super(properties);
 62  2
     }
 63  
     /**
 64  
      * A flag indicating whether or not the batch update should be performed.
 65  
      */
 66  
     private boolean doBatchUpdate;
 67  
 
 68  
     /**
 69  
      * Get the value of doBatchUpdate
 70  
      *
 71  
      * @return the value of doBatchUpdate
 72  
      */
 73  
     protected boolean isDoBatchUpdate() {
 74  1
         return doBatchUpdate;
 75  
     }
 76  
 
 77  
     /**
 78  
      * Set the value of doBatchUpdate
 79  
      *
 80  
      * @param doBatchUpdate new value of doBatchUpdate
 81  
      */
 82  
     protected void setDoBatchUpdate(boolean doBatchUpdate) {
 83  2
         this.doBatchUpdate = doBatchUpdate;
 84  2
     }
 85  
 
 86  
     /**
 87  
      * <p>Downloads the latest NVD CVE XML file from the web and imports it into
 88  
      * the current CVE Database.</p>
 89  
      *
 90  
      * @throws UpdateException is thrown if there is an error updating the
 91  
      * database
 92  
      */
 93  
     @Override
 94  
     public void update() throws UpdateException {
 95  1
         if (getProperties().isBatchUpdateMode() && doBatchUpdate) {
 96  1
             final String batchSrc = Settings.getString(Settings.KEYS.BATCH_UPDATE_URL);
 97  1
             File tmp = null;
 98  
             try {
 99  1
                 deleteExistingData();
 100  1
                 final File dataDirectory = CveDB.getDataDirectory().getParentFile();
 101  1
                 final URL batchUrl = new URL(batchSrc);
 102  1
                 if ("file".equals(batchUrl.getProtocol())) {
 103  
                     try {
 104  1
                         tmp = new File(batchUrl.toURI());
 105  0
                     } catch (URISyntaxException ex) {
 106  0
                         final String msg = String.format("Invalid batch update URI: %s", batchSrc);
 107  0
                         throw new UpdateException(msg, ex);
 108  1
                     }
 109  0
                 } else if ("http".equals(batchUrl.getProtocol())
 110  
                         || "https".equals(batchUrl.getProtocol())) {
 111  0
                     tmp = File.createTempFile("batch_", ".zip");
 112  0
                     Downloader.fetchFile(batchUrl, tmp);
 113  
                 }
 114  
                 //TODO add FTP?
 115  1
                 FileUtils.extractFiles(tmp, dataDirectory);
 116  
 
 117  0
             } catch (IOException ex) {
 118  0
                 final String msg = String.format("IO Exception Occured performing batch update using: %s", batchSrc);
 119  0
                 throw new UpdateException(msg, ex);
 120  
             } finally {
 121  1
                 if (tmp != null && !tmp.delete()) {
 122  0
                     tmp.deleteOnExit();
 123  
                 }
 124  
             }
 125  
         }
 126  1
     }
 127  
 
 128  
     /**
 129  
      * Determines if the index needs to be updated. This is done by fetching the
 130  
      * NVD CVE meta data and checking the last update date. If the data needs to
 131  
      * be refreshed this method will return the NvdCveUrl for the files that
 132  
      * need to be updated.
 133  
      *
 134  
      * @return the collection of files that need to be updated
 135  
      * @throws MalformedURLException is thrown if the URL for the NVD CVE Meta
 136  
      * data is incorrect
 137  
      * @throws DownloadFailedException is thrown if there is an error.
 138  
      * downloading the NVD CVE download data file
 139  
      * @throws UpdateException Is thrown if there is an issue with the last
 140  
      * updated properties file
 141  
      */
 142  
     @Override
 143  
     public Updateable updatesNeeded() throws MalformedURLException, DownloadFailedException, UpdateException {
 144  2
         Updateable updates = null;
 145  
         try {
 146  2
             updates = retrieveCurrentTimestampsFromWeb();
 147  0
         } catch (InvalidDataException ex) {
 148  0
             final String msg = "Unable to retrieve valid timestamp from nvd cve downloads page";
 149  0
             Logger.getLogger(BatchUpdateTask.class.getName()).log(Level.FINE, msg, ex);
 150  0
             throw new DownloadFailedException(msg, ex);
 151  0
         } catch (InvalidSettingException ex) {
 152  0
             Logger.getLogger(BatchUpdateTask.class.getName()).log(Level.FINE, "Invalid setting found when retrieving timestamps", ex);
 153  0
             throw new DownloadFailedException("Invalid settings", ex);
 154  2
         }
 155  
 
 156  2
         if (updates == null) {
 157  0
             throw new DownloadFailedException("Unable to retrieve the timestamps of the currently published NVD CVE data");
 158  
         }
 159  2
         final DataStoreMetaInfo properties = getProperties();
 160  2
         if (!properties.isEmpty()) {
 161  
             try {
 162  0
                 boolean deleteAndRecreate = false;
 163  
                 float version;
 164  
 
 165  0
                 if (properties.getProperty("version") == null) {
 166  0
                     deleteAndRecreate = true;
 167  
                 } else {
 168  
                     try {
 169  0
                         version = Float.parseFloat(properties.getProperty("version"));
 170  0
                         final float currentVersion = Float.parseFloat(CveDB.DB_SCHEMA_VERSION);
 171  0
                         if (currentVersion > version) {
 172  0
                             deleteAndRecreate = true;
 173  
                         }
 174  0
                     } catch (NumberFormatException ex) {
 175  0
                         deleteAndRecreate = true;
 176  0
                     }
 177  
                 }
 178  
 
 179  0
                 final NvdCveInfo batchInfo = updates.get(BATCH);
 180  0
                 if (properties.isBatchUpdateMode() && batchInfo != null) {
 181  0
                     final long lastUpdated = Long.parseLong(properties.getProperty(DataStoreMetaInfo.BATCH, "0"));
 182  0
                     if (lastUpdated != batchInfo.getTimestamp()) {
 183  0
                         deleteAndRecreate = true;
 184  
                     }
 185  
                 }
 186  
 
 187  0
                 if (deleteAndRecreate) {
 188  0
                     setDoBatchUpdate(properties.isBatchUpdateMode());
 189  
                     try {
 190  0
                         deleteExistingData();
 191  0
                     } catch (IOException ex) {
 192  0
                         final String msg = "Unable to delete existing data";
 193  0
                         Logger.getLogger(BatchUpdateTask.class.getName()).log(Level.WARNING, msg);
 194  0
                         Logger.getLogger(BatchUpdateTask.class.getName()).log(Level.FINE, null, ex);
 195  0
                     }
 196  0
                     return updates;
 197  
                 }
 198  
 
 199  0
                 final long lastUpdated = Long.parseLong(properties.getProperty(DataStoreMetaInfo.LAST_UPDATED, "0"));
 200  0
                 final Date now = new Date();
 201  0
                 final int days = Settings.getInt(Settings.KEYS.CVE_MODIFIED_VALID_FOR_DAYS, 7);
 202  0
                 final int start = Settings.getInt(Settings.KEYS.CVE_START_YEAR, 2002);
 203  0
                 final int end = Calendar.getInstance().get(Calendar.YEAR);
 204  0
                 if (lastUpdated == updates.get(MODIFIED).getTimestamp()) {
 205  0
                     updates.clear(); //we don't need to update anything.
 206  0
                     setDoBatchUpdate(properties.isBatchUpdateMode());
 207  0
                 } else if (withinRange(lastUpdated, now.getTime(), days)) {
 208  0
                     updates.get(MODIFIED).setNeedsUpdate(true);
 209  0
                     if (properties.isBatchUpdateMode()) {
 210  0
                         setDoBatchUpdate(false);
 211  
                     } else {
 212  0
                         for (int i = start; i <= end; i++) {
 213  0
                             updates.get(String.valueOf(i)).setNeedsUpdate(false);
 214  
                         }
 215  
                     }
 216  0
                 } else if (properties.isBatchUpdateMode()) {
 217  0
                     updates.get(MODIFIED).setNeedsUpdate(true);
 218  0
                     setDoBatchUpdate(true);
 219  
                 } else { //we figure out which of the several XML files need to be downloaded.
 220  0
                     updates.get(MODIFIED).setNeedsUpdate(false);
 221  0
                     for (int i = start; i <= end; i++) {
 222  0
                         final NvdCveInfo cve = updates.get(String.valueOf(i));
 223  0
                         long currentTimestamp = 0;
 224  
                         try {
 225  0
                             currentTimestamp = Long.parseLong(properties.getProperty(DataStoreMetaInfo.LAST_UPDATED_BASE + String.valueOf(i), "0"));
 226  0
                         } catch (NumberFormatException ex) {
 227  0
                             final String msg = String.format("Error parsing '%s' '%s' from nvdcve.lastupdated",
 228  
                                     DataStoreMetaInfo.LAST_UPDATED_BASE, String.valueOf(i));
 229  0
                             Logger.getLogger(BatchUpdateTask.class.getName()).log(Level.FINE, msg, ex);
 230  0
                         }
 231  0
                         if (currentTimestamp == cve.getTimestamp()) {
 232  0
                             cve.setNeedsUpdate(false); //they default to true.
 233  
                         }
 234  
                     }
 235  
                 }
 236  0
             } catch (NumberFormatException ex) {
 237  0
                 final String msg = "An invalid schema version or timestamp exists in the data.properties file.";
 238  0
                 Logger.getLogger(BatchUpdateTask.class.getName()).log(Level.WARNING, msg);
 239  0
                 Logger.getLogger(BatchUpdateTask.class.getName()).log(Level.FINE, null, ex);
 240  0
                 setDoBatchUpdate(properties.isBatchUpdateMode());
 241  0
             }
 242  
         }
 243  2
         return updates;
 244  
     }
 245  
 
 246  
     /**
 247  
      * Retrieves the timestamps from the NVD CVE meta data file.
 248  
      *
 249  
      * @return the timestamp from the currently published nvdcve downloads page
 250  
      * @throws MalformedURLException thrown if the URL for the NVD CCE Meta data
 251  
      * is incorrect.
 252  
      * @throws DownloadFailedException thrown if there is an error downloading
 253  
      * the nvd cve meta data file
 254  
      * @throws InvalidDataException thrown if there is an exception parsing the
 255  
      * timestamps
 256  
      * @throws InvalidSettingException thrown if the settings are invalid
 257  
      */
 258  
     private Updateable retrieveCurrentTimestampsFromWeb()
 259  
             throws MalformedURLException, DownloadFailedException, InvalidDataException, InvalidSettingException {
 260  2
         final Updateable updates = new Updateable();
 261  2
         updates.add(BATCH, Settings.getString(Settings.KEYS.BATCH_UPDATE_URL),
 262  
                 null, false);
 263  
 
 264  2
         final String url = Settings.getString(Settings.KEYS.CVE_MODIFIED_20_URL, "");
 265  2
         if (!url.isEmpty()) {
 266  2
             updates.add(MODIFIED, url,
 267  
                     Settings.getString(Settings.KEYS.CVE_MODIFIED_12_URL),
 268  
                     false);
 269  
         }
 270  2
         return updates;
 271  
     }
 272  
 }