Coverage Report - org.owasp.dependencycheck.data.update.StandardUpdate
 
Classes in this File Line Coverage Branch Coverage Complexity
StandardUpdate
0%
0/140
0%
0/52
6.875
 
 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.data.update;
 19  
 
 20  
 import java.net.MalformedURLException;
 21  
 import java.util.Calendar;
 22  
 import java.util.Date;
 23  
 import java.util.HashSet;
 24  
 import java.util.Set;
 25  
 import java.util.concurrent.ExecutionException;
 26  
 import java.util.concurrent.ExecutorService;
 27  
 import java.util.concurrent.Executors;
 28  
 import java.util.concurrent.Future;
 29  
 import java.util.logging.Level;
 30  
 import java.util.logging.Logger;
 31  
 import org.owasp.dependencycheck.data.nvdcve.CveDB;
 32  
 import org.owasp.dependencycheck.data.nvdcve.DatabaseException;
 33  
 import org.owasp.dependencycheck.data.nvdcve.DatabaseProperties;
 34  
 import static org.owasp.dependencycheck.data.nvdcve.DatabaseProperties.MODIFIED;
 35  
 import org.owasp.dependencycheck.data.update.exception.InvalidDataException;
 36  
 import org.owasp.dependencycheck.data.update.exception.UpdateException;
 37  
 import org.owasp.dependencycheck.data.update.task.CallableDownloadTask;
 38  
 import org.owasp.dependencycheck.data.update.task.ProcessTask;
 39  
 import org.owasp.dependencycheck.utils.DownloadFailedException;
 40  
 import org.owasp.dependencycheck.utils.InvalidSettingException;
 41  
 import org.owasp.dependencycheck.utils.Settings;
 42  
 
 43  
 /**
 44  
  * Class responsible for updating the NVDCVE data store.
 45  
  *
 46  
  * @author Jeremy Long <jeremy.long@owasp.org>
 47  
  */
 48  
 public class StandardUpdate {
 49  
 
 50  
     /**
 51  
      * The max thread pool size to use when downloading files.
 52  
      */
 53  0
     public static final int MAX_THREAD_POOL_SIZE = Settings.getInt(Settings.KEYS.MAX_DOWNLOAD_THREAD_POOL_SIZE, 3);
 54  
     /**
 55  
      * Information about the timestamps and URLs for data that needs to be updated.
 56  
      */
 57  
     private DatabaseProperties properties;
 58  
     /**
 59  
      * A collection of updateable NVD CVE items.
 60  
      */
 61  
     private UpdateableNvdCve updateable;
 62  
     /**
 63  
      * Reference to the Cve Database.
 64  
      */
 65  0
     private CveDB cveDB = null;
 66  
 
 67  
     /**
 68  
      * Gets whether or not an update is needed.
 69  
      *
 70  
      * @return true or false depending on whether an update is needed
 71  
      */
 72  
     public boolean isUpdateNeeded() {
 73  0
         return updateable.isUpdateNeeded();
 74  
     }
 75  
 
 76  
     /**
 77  
      * Constructs a new Standard Update Task.
 78  
      *
 79  
      * @throws MalformedURLException thrown if a configured URL is malformed
 80  
      * @throws DownloadFailedException thrown if a timestamp cannot be checked on a configured URL
 81  
      * @throws UpdateException thrown if there is an exception generating the update task
 82  
      */
 83  0
     public StandardUpdate() throws MalformedURLException, DownloadFailedException, UpdateException {
 84  0
         openDataStores();
 85  0
         properties = cveDB.getDatabaseProperties();
 86  0
         updateable = updatesNeeded();
 87  0
     }
 88  
 
 89  
     /**
 90  
      * <p>
 91  
      * Downloads the latest NVD CVE XML file from the web and imports it into the current CVE Database.</p>
 92  
      *
 93  
      * @throws UpdateException is thrown if there is an error updating the database
 94  
      */
 95  
     public void update() throws UpdateException {
 96  0
         int maxUpdates = 0;
 97  
         try {
 98  0
             for (NvdCveInfo cve : updateable) {
 99  0
                 if (cve.getNeedsUpdate()) {
 100  0
                     maxUpdates += 1;
 101  
                 }
 102  0
             }
 103  0
             if (maxUpdates <= 0) {
 104  
                 return;
 105  
             }
 106  0
             if (maxUpdates > 3) {
 107  0
                 Logger.getLogger(StandardUpdate.class.getName()).log(Level.INFO,
 108  
                         "NVD CVE requires several updates; this could take a couple of minutes.");
 109  
             }
 110  0
             if (maxUpdates > 0) {
 111  0
                 openDataStores();
 112  
             }
 113  
 
 114  0
             final int poolSize = (MAX_THREAD_POOL_SIZE < maxUpdates) ? MAX_THREAD_POOL_SIZE : maxUpdates;
 115  
 
 116  0
             final ExecutorService downloadExecutors = Executors.newFixedThreadPool(poolSize);
 117  0
             final ExecutorService processExecutor = Executors.newSingleThreadExecutor();
 118  0
             final Set<Future<Future<ProcessTask>>> downloadFutures = new HashSet<Future<Future<ProcessTask>>>(maxUpdates);
 119  0
             for (NvdCveInfo cve : updateable) {
 120  0
                 if (cve.getNeedsUpdate()) {
 121  0
                     final CallableDownloadTask call = new CallableDownloadTask(cve, processExecutor, cveDB);
 122  0
                     downloadFutures.add(downloadExecutors.submit(call));
 123  
                 }
 124  0
             }
 125  0
             downloadExecutors.shutdown();
 126  
 
 127  
             //next, move the future future processTasks to just future processTasks
 128  0
             final Set<Future<ProcessTask>> processFutures = new HashSet<Future<ProcessTask>>(maxUpdates);
 129  0
             for (Future<Future<ProcessTask>> future : downloadFutures) {
 130  0
                 Future<ProcessTask> task = null;
 131  
                 try {
 132  0
                     task = future.get();
 133  0
                 } catch (InterruptedException ex) {
 134  0
                     downloadExecutors.shutdownNow();
 135  0
                     processExecutor.shutdownNow();
 136  
 
 137  0
                     Logger.getLogger(StandardUpdate.class.getName()).log(Level.FINE, "Thread was interrupted during download", ex);
 138  0
                     throw new UpdateException("The download was interrupted", ex);
 139  0
                 } catch (ExecutionException ex) {
 140  0
                     downloadExecutors.shutdownNow();
 141  0
                     processExecutor.shutdownNow();
 142  
 
 143  0
                     Logger.getLogger(StandardUpdate.class.getName()).log(Level.FINE, "Thread was interrupted during download execution", ex);
 144  0
                     throw new UpdateException("The execution of the download was interrupted", ex);
 145  0
                 }
 146  0
                 if (task == null) {
 147  0
                     downloadExecutors.shutdownNow();
 148  0
                     processExecutor.shutdownNow();
 149  0
                     Logger.getLogger(StandardUpdate.class.getName()).log(Level.FINE, "Thread was interrupted during download");
 150  0
                     throw new UpdateException("The download was interrupted; unable to complete the update");
 151  
                 } else {
 152  0
                     processFutures.add(task);
 153  
                 }
 154  0
             }
 155  
 
 156  0
             for (Future<ProcessTask> future : processFutures) {
 157  
                 try {
 158  0
                     final ProcessTask task = future.get();
 159  0
                     if (task.getException() != null) {
 160  0
                         throw task.getException();
 161  
                     }
 162  0
                 } catch (InterruptedException ex) {
 163  0
                     processExecutor.shutdownNow();
 164  0
                     Logger.getLogger(StandardUpdate.class.getName()).log(Level.FINE, "Thread was interrupted during processing", ex);
 165  0
                     throw new UpdateException(ex);
 166  0
                 } catch (ExecutionException ex) {
 167  0
                     processExecutor.shutdownNow();
 168  0
                     Logger.getLogger(StandardUpdate.class.getName()).log(Level.FINE, "Execution Exception during process", ex);
 169  0
                     throw new UpdateException(ex);
 170  
                 } finally {
 171  0
                     processExecutor.shutdown();
 172  0
                 }
 173  0
             }
 174  
 
 175  0
             if (maxUpdates >= 1) { //ensure the modified file date gets written (we may not have actually updated it)
 176  0
                 properties.save(updateable.get(MODIFIED));
 177  0
                 cveDB.cleanupDatabase();
 178  
             }
 179  
         } finally {
 180  0
             closeDataStores();
 181  0
         }
 182  0
     }
 183  
 
 184  
     /**
 185  
      * Determines if the index needs to be updated. This is done by fetching the NVD CVE meta data and checking the last
 186  
      * update date. If the data needs to be refreshed this method will return the NvdCveUrl for the files that need to
 187  
      * be updated.
 188  
      *
 189  
      * @return the collection of files that need to be updated
 190  
      * @throws MalformedURLException is thrown if the URL for the NVD CVE Meta data is incorrect
 191  
      * @throws DownloadFailedException is thrown if there is an error. downloading the NVD CVE download data file
 192  
      * @throws UpdateException Is thrown if there is an issue with the last updated properties file
 193  
      */
 194  
     protected final UpdateableNvdCve updatesNeeded() throws MalformedURLException, DownloadFailedException, UpdateException {
 195  0
         UpdateableNvdCve updates = null;
 196  
         try {
 197  0
             updates = retrieveCurrentTimestampsFromWeb();
 198  0
         } catch (InvalidDataException ex) {
 199  0
             final String msg = "Unable to retrieve valid timestamp from nvd cve downloads page";
 200  0
             Logger.getLogger(StandardUpdate.class.getName()).log(Level.FINE, msg, ex);
 201  0
             throw new DownloadFailedException(msg, ex);
 202  0
         } catch (InvalidSettingException ex) {
 203  0
             Logger.getLogger(StandardUpdate.class.getName()).log(Level.FINE, "Invalid setting found when retrieving timestamps", ex);
 204  0
             throw new DownloadFailedException("Invalid settings", ex);
 205  0
         }
 206  
 
 207  0
         if (updates == null) {
 208  0
             throw new DownloadFailedException("Unable to retrieve the timestamps of the currently published NVD CVE data");
 209  
         }
 210  0
         if (!properties.isEmpty()) {
 211  
             try {
 212  0
                 final long lastUpdated = Long.parseLong(properties.getProperty(DatabaseProperties.LAST_UPDATED, "0"));
 213  0
                 final Date now = new Date();
 214  0
                 final int days = Settings.getInt(Settings.KEYS.CVE_MODIFIED_VALID_FOR_DAYS, 7);
 215  0
                 if (lastUpdated == updates.getTimeStamp(MODIFIED)) {
 216  0
                     updates.clear(); //we don't need to update anything.
 217  0
                 } else if (withinRange(lastUpdated, now.getTime(), days)) {
 218  0
                     for (NvdCveInfo entry : updates) {
 219  0
                         if (MODIFIED.equals(entry.getId())) {
 220  0
                             entry.setNeedsUpdate(true);
 221  
                         } else {
 222  0
                             entry.setNeedsUpdate(false);
 223  
                         }
 224  0
                     }
 225  
                 } else { //we figure out which of the several XML files need to be downloaded.
 226  0
                     for (NvdCveInfo entry : updates) {
 227  0
                         if (MODIFIED.equals(entry.getId())) {
 228  0
                             entry.setNeedsUpdate(true);
 229  
                         } else {
 230  0
                             long currentTimestamp = 0;
 231  
                             try {
 232  0
                                 currentTimestamp = Long.parseLong(properties.getProperty(DatabaseProperties.LAST_UPDATED_BASE + entry.getId(), "0"));
 233  0
                             } catch (NumberFormatException ex) {
 234  0
                                 final String msg = String.format("Error parsing '%s' '%s' from nvdcve.lastupdated",
 235  
                                         DatabaseProperties.LAST_UPDATED_BASE, entry.getId());
 236  0
                                 Logger
 237  
                                         .getLogger(StandardUpdate.class
 238  
                                                 .getName()).log(Level.FINE, msg, ex);
 239  0
                             }
 240  0
                             if (currentTimestamp == entry.getTimestamp()) {
 241  0
                                 entry.setNeedsUpdate(false);
 242  
                             }
 243  
                         }
 244  0
                     }
 245  
                 }
 246  0
             } catch (NumberFormatException ex) {
 247  0
                 final String msg = "An invalid schema version or timestamp exists in the data.properties file.";
 248  0
                 Logger.getLogger(StandardUpdate.class.getName()).log(Level.WARNING, msg);
 249  0
                 Logger.getLogger(StandardUpdate.class.getName()).log(Level.FINE, "", ex);
 250  0
             }
 251  
         }
 252  0
         return updates;
 253  
     }
 254  
 
 255  
     /**
 256  
      * Retrieves the timestamps from the NVD CVE meta data file.
 257  
      *
 258  
      * @return the timestamp from the currently published nvdcve downloads page
 259  
      * @throws MalformedURLException thrown if the URL for the NVD CCE Meta data is incorrect.
 260  
      * @throws DownloadFailedException thrown if there is an error downloading the nvd cve meta data file
 261  
      * @throws InvalidDataException thrown if there is an exception parsing the timestamps
 262  
      * @throws InvalidSettingException thrown if the settings are invalid
 263  
      */
 264  
     private UpdateableNvdCve retrieveCurrentTimestampsFromWeb()
 265  
             throws MalformedURLException, DownloadFailedException, InvalidDataException, InvalidSettingException {
 266  
 
 267  0
         final UpdateableNvdCve updates = new UpdateableNvdCve();
 268  0
         updates.add(MODIFIED, Settings.getString(Settings.KEYS.CVE_MODIFIED_20_URL),
 269  
                 Settings.getString(Settings.KEYS.CVE_MODIFIED_12_URL),
 270  
                 false);
 271  
 
 272  0
         final int start = Settings.getInt(Settings.KEYS.CVE_START_YEAR);
 273  0
         final int end = Calendar.getInstance().get(Calendar.YEAR);
 274  0
         final String baseUrl20 = Settings.getString(Settings.KEYS.CVE_SCHEMA_2_0);
 275  0
         final String baseUrl12 = Settings.getString(Settings.KEYS.CVE_SCHEMA_1_2);
 276  0
         for (int i = start; i <= end; i++) {
 277  0
             updates.add(Integer.toString(i), String.format(baseUrl20, i),
 278  
                     String.format(baseUrl12, i),
 279  
                     true);
 280  
         }
 281  
 
 282  0
         return updates;
 283  
     }
 284  
 
 285  
     /**
 286  
      * Closes the CVE and CPE data stores.
 287  
      */
 288  
     protected void closeDataStores() {
 289  0
         if (cveDB != null) {
 290  
             try {
 291  0
                 cveDB.close();
 292  0
             } catch (Throwable ignore) {
 293  0
                 Logger.getLogger(StandardUpdate.class.getName()).log(Level.FINEST, "Error closing the cveDB", ignore);
 294  0
             }
 295  
         }
 296  0
     }
 297  
 
 298  
     /**
 299  
      * Opens the CVE and CPE data stores.
 300  
      *
 301  
      * @throws UpdateException thrown if a data store cannot be opened
 302  
      */
 303  
     protected final void openDataStores() throws UpdateException {
 304  0
         if (cveDB != null) {
 305  0
             return;
 306  
         }
 307  
         try {
 308  0
             cveDB = new CveDB();
 309  0
             cveDB.open();
 310  0
         } catch (DatabaseException ex) {
 311  0
             closeDataStores();
 312  0
             Logger.getLogger(StandardUpdate.class.getName()).log(Level.FINE, "Database Exception opening databases", ex);
 313  0
             throw new UpdateException("Error updating the CPE/CVE data, please see the log file for more details.");
 314  0
         }
 315  0
     }
 316  
 
 317  
     /**
 318  
      * Determines if the epoch date is within the range specified of the compareTo epoch time. This takes the
 319  
      * (compareTo-date)/1000/60/60/24 to get the number of days. If the calculated days is less then the range the date
 320  
      * is considered valid.
 321  
      *
 322  
      * @param date the date to be checked.
 323  
      * @param compareTo the date to compare to.
 324  
      * @param range the range in days to be considered valid.
 325  
      * @return whether or not the date is within the range.
 326  
      */
 327  
     protected boolean withinRange(long date, long compareTo, int range) {
 328  0
         final double differenceInDays = (compareTo - date) / 1000.0 / 60.0 / 60.0 / 24.0;
 329  0
         return differenceInDays < range;
 330  
     }
 331  
 }