Autopsy  4.1
Graphical digital forensics platform for The Sleuth Kit and other tools.
VMExtractorIngestModule.java
Go to the documentation of this file.
1 /*
2  * Autopsy Forensic Browser
3  *
4  * Copyright 2012-2016 Basis Technology Corp.
5  * Contact: carrier <at> sleuthkit <dot> org
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19 package org.sleuthkit.autopsy.modules.vmextractor;
20 
21 import java.io.File;
22 import java.io.IOException;
23 import java.nio.file.Files;
24 import java.nio.file.Path;
25 import java.nio.file.Paths;
26 import java.text.SimpleDateFormat;
27 import java.util.ArrayList;
28 import java.util.Calendar;
29 import java.util.HashMap;
30 import java.util.List;
31 import java.util.UUID;
32 import java.util.logging.Level;
33 import org.openide.util.NbBundle;
34 import org.openide.util.NbBundle.Messages;
51 import org.sleuthkit.datamodel.AbstractFile;
52 import org.sleuthkit.datamodel.Content;
53 import org.sleuthkit.datamodel.DataSource;
54 import org.sleuthkit.datamodel.SleuthkitCase;
55 import org.sleuthkit.datamodel.TskCoreException;
56 import org.sleuthkit.datamodel.TskDataException;
57 
62 @NbBundle.Messages({"# {0} - output directory name", "VMExtractorIngestModule.cannotCreateOutputDir.message=Unable to create output directory: {0}."
63 })
64 final class VMExtractorIngestModule extends DataSourceIngestModuleAdapter {
65 
66  private static final Logger logger = Logger.getLogger(VMExtractorIngestModule.class.getName());
67  private IngestJobContext context;
68  private Path ingestJobOutputDir;
69  private String parentDeviceId;
70  private String parentTimeZone;
71 
72  private final HashMap<String, String> imageFolderToOutputFolder = new HashMap<>();
73  private int folderId = 0;
74 
75  @Messages({"# {0} - data source name", "deviceIdQueryErrMsg=Data source {0} missing Device ID"})
76  @Override
77  public void startUp(IngestJobContext context) throws IngestModuleException {
78  this.context = context;
79  long dataSourceObjId = context.getDataSource().getId();
80  try {
81  Case currentCase = Case.getCurrentCase();
82  SleuthkitCase caseDb = currentCase.getSleuthkitCase();
83  DataSource dataSource = caseDb.getDataSource(dataSourceObjId);
84  parentDeviceId = dataSource.getDeviceId();
85  parentTimeZone = dataSource.getTimeZone();
86  SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
87  String timeStamp = dateFormat.format(Calendar.getInstance().getTime());
88  String ingestJobOutputDirName = context.getDataSource().getName() + "_" + context.getDataSource().getId() + "_" + timeStamp;
89  ingestJobOutputDir = Paths.get(Case.getCurrentCase().getModuleDirectory(), VMExtractorIngestModuleFactory.getModuleName(), ingestJobOutputDirName);
90  // create module output folder to write extracted virtual machine files to
91  Files.createDirectories(ingestJobOutputDir);
92  } catch (IOException | SecurityException | UnsupportedOperationException ex) {
93  throw new IngestModule.IngestModuleException(Bundle.VMExtractorIngestModule_cannotCreateOutputDir_message(ex.getLocalizedMessage()), ex);
94  } catch (TskDataException | TskCoreException ex) {
95  throw new IngestModule.IngestModuleException(Bundle.deviceIdQueryErrMsg(context.getDataSource().getName()), ex);
96  }
97  }
98 
99  @Override
100  public ProcessResult process(Content dataSource, DataSourceIngestModuleProgress progressBar) {
101 
102  String outputFolderForThisVM;
103  List<AbstractFile> vmFiles;
104 
105  // Configure and start progress bar - looking for VM files
106  progressBar.progress(NbBundle.getMessage(this.getClass(), "VMExtractorIngestModule.searchingImage.message"));
107  // Not sure how long it will take for search to complete.
108  progressBar.switchToIndeterminate();
109 
110  logger.log(Level.INFO, "Looking for virtual machine files in data source {0}", dataSource.getName()); //NON-NLS
111 
112  try {
113  // look for all VM files
114  vmFiles = findVirtualMachineFiles(dataSource);
115  } catch (TskCoreException ex) {
116  logger.log(Level.SEVERE, "Error querying case database", ex); //NON-NLS
117  return ProcessResult.ERROR;
118  }
119 
120  if (vmFiles.isEmpty()) {
121  // no VM files found
122  logger.log(Level.INFO, "No virtual machine files found in data source {0}", dataSource.getName()); //NON-NLS
123  return ProcessResult.OK;
124  }
125  // display progress for saving each VM file to disk
126  progressBar.switchToDeterminate(vmFiles.size());
127  progressBar.progress(NbBundle.getMessage(this.getClass(), "VMExtractorIngestModule.exportingToDisk.message"));
128 
129  int numFilesSaved = 0;
130  for (AbstractFile vmFile : vmFiles) {
131  if (context.dataSourceIngestIsCancelled()) {
132  break;
133  }
134 
135  logger.log(Level.INFO, "Saving virtual machine file {0} to disk", vmFile.getName()); //NON-NLS
136 
137  // get vmFolderPathInsideTheImage to the folder where VM is located
138  String vmFolderPathInsideTheImage = vmFile.getParentPath();
139 
140  // check if the vmFolderPathInsideTheImage is already in hashmap
141  if (imageFolderToOutputFolder.containsKey(vmFolderPathInsideTheImage)) {
142  // if it is then we have already created output folder to write out all VM files in this parent folder
143  outputFolderForThisVM = imageFolderToOutputFolder.get(vmFolderPathInsideTheImage);
144  } else {
145  // if not - create output folder to write out VM files (can use any unique ID or number for folder name)
146  folderId++;
147  outputFolderForThisVM = Paths.get(ingestJobOutputDir.toString(), Integer.toString(folderId)).toString();
148 
149  // add vmFolderPathInsideTheImage to hashmap
150  imageFolderToOutputFolder.put(vmFolderPathInsideTheImage, outputFolderForThisVM);
151  }
152 
153  // write the vm file to output folder
154  try {
155  writeVirtualMachineToDisk(vmFile, outputFolderForThisVM);
156  } catch (Exception ex) {
157  logger.log(Level.SEVERE, "Failed to write virtual machine file " + vmFile.getName() + " to folder " + outputFolderForThisVM, ex); //NON-NLS
158  MessageNotifyUtil.Notify.error(NbBundle.getMessage(this.getClass(), "VMExtractorIngestModule.msgNotify.failedExtractVM.title.txt"),
159  NbBundle.getMessage(this.getClass(), "VMExtractorIngestModule.msgNotify.failedExtractVM.msg.txt", vmFile.getName()));
160  }
161 
162  // Update progress bar
163  numFilesSaved++;
164  progressBar.progress(NbBundle.getMessage(this.getClass(), "VMExtractorIngestModule.exportingToDisk.message"), numFilesSaved);
165  }
166  logger.log(Level.INFO, "Finished saving virtual machine files to disk"); //NON-NLS
167 
168  // update progress bar
169  progressBar.switchToDeterminate(imageFolderToOutputFolder.size());
170  progressBar.progress(NbBundle.getMessage(this.getClass(), "VMExtractorIngestModule.queuingIngestJobs.message"));
171  // this is for progress bar purposes because at this point we only know in advance how many job folders to ingest, not how many data sources.
172  int numJobsQueued = 0;
173  // start processing output folders after we are done writing out all vm files
174  for (String folder : imageFolderToOutputFolder.values()) {
175  if (context.dataSourceIngestIsCancelled()) {
176  break;
177  }
178  List<String> vmFilesToIngest = VirtualMachineFinder.identifyVirtualMachines(Paths.get(folder));
179  for (String file : vmFilesToIngest) {
180  try {
181  logger.log(Level.INFO, "Ingesting virtual machine file {0} in folder {1}", new Object[]{file, folder}); //NON-NLS
182 
183  // for extracted virtual machines there is no manifest XML file to read data source ID from so use parent data source ID.
184  // ingest the data sources
185  ingestVirtualMachineImage(Paths.get(folder, file));
186  logger.log(Level.INFO, "Ingest complete for virtual machine file {0} in folder {1}", new Object[]{file, folder}); //NON-NLS
187  } catch (InterruptedException ex) {
188  logger.log(Level.INFO, "Interrupted while ingesting virtual machine file " + file + " in folder " + folder, ex); //NON-NLS
189  } catch (IOException ex) {
190  logger.log(Level.SEVERE, "Failed to ingest virtual machine file " + file + " in folder " + folder, ex); //NON-NLS
191  MessageNotifyUtil.Notify.error(NbBundle.getMessage(this.getClass(), "VMExtractorIngestModule.msgNotify.failedIngestVM.title.txt"),
192  NbBundle.getMessage(this.getClass(), "VMExtractorIngestModule.msgNotify.failedIngestVM.msg.txt", file));
193  }
194  }
195  // Update progress bar
196  numJobsQueued++;
197  progressBar.progress(NbBundle.getMessage(this.getClass(), "VMExtractorIngestModule.queuingIngestJobs.message"), numJobsQueued);
198  }
199  logger.log(Level.INFO, "VMExtractorIngestModule completed processing of data source {0}", dataSource.getName()); //NON-NLS
200  return ProcessResult.OK;
201  }
202 
214  private static List<AbstractFile> findVirtualMachineFiles(Content dataSource) throws TskCoreException {
215  List<AbstractFile> vmFiles = new ArrayList<>();
216  for (String vmExtension : GeneralFilter.VIRTUAL_MACHINE_EXTS) {
217  String searchString = "%" + vmExtension; // want a search string that looks like this "%.vmdk"
218  vmFiles.addAll(Case.getCurrentCase().getServices().getFileManager().findFiles(dataSource, searchString));
219  }
220  return vmFiles;
221  }
222 
231  private void writeVirtualMachineToDisk(AbstractFile vmFile, String outputFolderForThisVM) throws IOException {
232 
233  // TODO: check available disk space first? See IngestMonitor.getFreeSpace()
234  // check if output folder exists
235  File destinationFolder = Paths.get(outputFolderForThisVM).toFile();
236  if (!destinationFolder.exists()) {
237  destinationFolder.mkdirs();
238  }
239  /*
240  * Write the virtual machine file to disk.
241  */
242  File localFile = Paths.get(outputFolderForThisVM, vmFile.getName()).toFile();
243  ContentUtils.writeToFile(vmFile, localFile, context::dataSourceIngestIsCancelled);
244  }
245 
252  private void ingestVirtualMachineImage(Path vmFile) throws InterruptedException, IOException {
253 
254  /*
255  * Try to add the virtual machine file to the case as a data source.
256  */
257  UUID taskId = UUID.randomUUID();
258  Case.getCurrentCase().notifyAddingDataSource(taskId);
259  ImageDSProcessor dataSourceProcessor = new ImageDSProcessor();
260  AddDataSourceCallback dspCallback = new AddDataSourceCallback(vmFile);
261  synchronized (this) {
262  dataSourceProcessor.run(parentDeviceId, vmFile.toString(), parentTimeZone, false, new AddDataSourceProgressMonitor(), dspCallback);
263  /*
264  * Block the ingest thread until the data source processor finishes.
265  */
266  this.wait();
267  }
268 
269  /*
270  * If the image was added, analyze it with the ingest modules for this
271  * ingest context.
272  */
273  if (!dspCallback.vmDataSources.isEmpty()) {
274  Case.getCurrentCase().notifyDataSourceAdded(dspCallback.vmDataSources.get(0), taskId);
275  List<Content> dataSourceContent = new ArrayList<>(dspCallback.vmDataSources);
276  IngestJobSettings ingestJobSettings = new IngestJobSettings(context.getExecutionContext());
277  for (String warning : ingestJobSettings.getWarnings()) {
278  logger.log(Level.WARNING, String.format("Ingest job settings warning for virtual machine file %s : %s", vmFile.toString(), warning)); //NON-NLS
279  }
280  IngestServices.getInstance().postMessage(IngestMessage.createMessage(IngestMessage.MessageType.INFO,
281  VMExtractorIngestModuleFactory.getModuleName(),
282  NbBundle.getMessage(this.getClass(), "VMExtractorIngestModule.addedVirtualMachineImage.message", vmFile.toString())));
283  IngestManager.getInstance().queueIngestJob(dataSourceContent, ingestJobSettings);
284  } else {
285  Case.getCurrentCase().notifyFailedAddingDataSource(taskId);
286  }
287  }
288 
292  private static final class AddDataSourceProgressMonitor implements DataSourceProcessorProgressMonitor {
293 
294  @Override
295  public void setIndeterminate(final boolean indeterminate) {
296  }
297 
298  @Override
299  public void setProgress(final int progress) {
300  }
301 
302  @Override
303  public void setProgressText(final String text) {
304  }
305 
306  }
307 
313 
314  private final Path vmFile;
315  private final List<Content> vmDataSources;
316 
322  private AddDataSourceCallback(Path vmFile) {
323  this.vmFile = vmFile;
324  vmDataSources = new ArrayList<>();
325  }
326 
327  @Override
328  public void done(DataSourceProcessorCallback.DataSourceProcessorResult result, List<String> errList, List<Content> content) {
329  for (String error : errList) {
330  String logMessage = String.format("Data source processor error for virtual machine file %s: %s", vmFile.toString(), error); //NON-NLS
332  logger.log(Level.SEVERE, logMessage);
333  } else {
334  logger.log(Level.WARNING, logMessage);
335  }
336  }
337 
338  /*
339  * Save a reference to the content object so it can be used to
340  * create a new ingest job.
341  */
342  if (!content.isEmpty()) {
343  vmDataSources.add(content.get(0));
344  }
345 
346  /*
347  * Unblock the ingest thread.
348  */
349  synchronized (VMExtractorIngestModule.this) {
350  VMExtractorIngestModule.this.notify();
351  }
352  }
353 
354  @Override
355  public void doneEDT(DataSourceProcessorResult result, List<String> errList, List<Content> newContents) {
356  done(result, errList, newContents);
357  }
358 
359  }
360 
361 }
void doneEDT(DataSourceProcessorResult result, List< String > errList, List< Content > newContents)
void done(DataSourceProcessorCallback.DataSourceProcessorResult result, List< String > errList, List< Content > content)

Copyright © 2012-2016 Basis Technology. Generated on: Mon Jan 2 2017
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License.