19 package org.sleuthkit.autopsy.modules.vmextractor;
 
   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;
 
   55 import org.
sleuthkit.datamodel.ReadContentInputStream.ReadContentInputStreamException;
 
   64 @NbBundle.Messages({
"# {0} - output directory name", 
"VMExtractorIngestModule.cannotCreateOutputDir.message=Unable to create output directory: {0}." 
   66 final class VMExtractorIngestModule extends DataSourceIngestModuleAdapter {
 
   68     private static final Logger logger = Logger.getLogger(VMExtractorIngestModule.class.getName());
 
   69     private IngestJobContext context;
 
   70     private Path ingestJobOutputDir;
 
   71     private String parentDeviceId;
 
   72     private String parentTimeZone;
 
   74     private final HashMap<String, String> imageFolderToOutputFolder = 
new HashMap<>();
 
   75     private int folderId = 0;
 
   77     @Messages({
"# {0} - data source name", 
"deviceIdQueryErrMsg=Data source {0} missing Device ID", 
 
   78         "VMExtractorIngestModule.noOpenCase.errMsg=No open case available."})
 
   80     public void startUp(IngestJobContext context) 
throws IngestModuleException {
 
   81         this.context = context;
 
   82         long dataSourceObjId = context.getDataSource().getId();
 
   84             Case currentCase = Case.getCurrentCaseThrows();
 
   85             SleuthkitCase caseDb = currentCase.getSleuthkitCase();
 
   86             DataSource dataSource = caseDb.getDataSource(dataSourceObjId);
 
   87             parentDeviceId = dataSource.getDeviceId();
 
   88             parentTimeZone = dataSource.getTimeZone();
 
   89             SimpleDateFormat dateFormat = 
new SimpleDateFormat(
"yyyy_MM_dd_HH_mm_ss");
 
   90             String timeStamp = dateFormat.format(Calendar.getInstance().getTime());
 
   91             String ingestJobOutputDirName = context.getDataSource().getName() + 
"_" + context.getDataSource().getId() + 
"_" + timeStamp;
 
   92             ingestJobOutputDirName = ingestJobOutputDirName.replace(
':', 
'_');
 
   93             ingestJobOutputDir = Paths.get(currentCase.getModuleDirectory(), VMExtractorIngestModuleFactory.getModuleName(), ingestJobOutputDirName);
 
   95             Files.createDirectories(ingestJobOutputDir);
 
   96         } 
catch (IOException | SecurityException | UnsupportedOperationException ex) {
 
   97             throw new IngestModule.IngestModuleException(Bundle.VMExtractorIngestModule_cannotCreateOutputDir_message(ex.getLocalizedMessage()), ex);
 
   98         } 
catch (TskDataException | TskCoreException ex) {
 
   99             throw new IngestModule.IngestModuleException(Bundle.deviceIdQueryErrMsg(context.getDataSource().getName()), ex);
 
  100         } 
catch (NoCurrentCaseException ex) {
 
  101             throw new IngestModule.IngestModuleException(Bundle.VMExtractorIngestModule_noOpenCase_errMsg(), ex);
 
  106     public ProcessResult process(Content dataSource, DataSourceIngestModuleProgress progressBar) {
 
  108         String outputFolderForThisVM;
 
  109         List<AbstractFile> vmFiles;
 
  112         progressBar.progress(NbBundle.getMessage(
this.getClass(), 
"VMExtractorIngestModule.searchingImage.message"));
 
  114         progressBar.switchToIndeterminate();
 
  116         logger.log(Level.INFO, 
"Looking for virtual machine files in data source {0}", dataSource.getName()); 
 
  120             vmFiles = findVirtualMachineFiles(dataSource);
 
  121         } 
catch (TskCoreException ex) {
 
  122             logger.log(Level.SEVERE, 
"Error querying case database", ex); 
 
  123             return ProcessResult.ERROR;
 
  124         } 
catch (NoCurrentCaseException ex) {
 
  125             logger.log(Level.SEVERE, 
"Exception while getting open case.", ex); 
 
  126             return ProcessResult.ERROR;
 
  129         if (vmFiles.isEmpty()) {
 
  131             logger.log(Level.INFO, 
"No virtual machine files found in data source {0}", dataSource.getName()); 
 
  132             return ProcessResult.OK;
 
  135         progressBar.switchToDeterminate(vmFiles.size());
 
  136         progressBar.progress(NbBundle.getMessage(
this.getClass(), 
"VMExtractorIngestModule.exportingToDisk.message"));
 
  138         int numFilesSaved = 0;
 
  139         for (AbstractFile vmFile : vmFiles) {
 
  140             if (context.dataSourceIngestIsCancelled()) {
 
  144             logger.log(Level.INFO, 
"Saving virtual machine file {0} to disk", vmFile.getName()); 
 
  147             String vmFolderPathInsideTheImage = vmFile.getParentPath();
 
  150             if (imageFolderToOutputFolder.containsKey(vmFolderPathInsideTheImage)) {
 
  152                 outputFolderForThisVM = imageFolderToOutputFolder.get(vmFolderPathInsideTheImage);
 
  156                 outputFolderForThisVM = Paths.get(ingestJobOutputDir.toString(), Integer.toString(folderId)).toString();
 
  159                 imageFolderToOutputFolder.put(vmFolderPathInsideTheImage, outputFolderForThisVM);
 
  164                 writeVirtualMachineToDisk(vmFile, outputFolderForThisVM);
 
  165             } 
catch (ReadContentInputStreamException ex) {
 
  166                 logger.log(Level.WARNING, String.format(
"Failed to read virtual machine file '%s' (id=%d).",
 
  167                         vmFile.getName(), vmFile.getId()), ex); 
 
  168                 MessageNotifyUtil.Notify.error(NbBundle.getMessage(
this.getClass(), 
"VMExtractorIngestModule.msgNotify.failedExtractVM.title.txt"),
 
  169                         NbBundle.getMessage(
this.getClass(), 
"VMExtractorIngestModule.msgNotify.failedExtractVM.msg.txt", vmFile.getName()));
 
  170             } 
catch (Exception ex) {
 
  171                 logger.log(Level.SEVERE, String.format(
"Failed to write virtual machine file '%s' (id=%d) to folder '%s'.",
 
  172                         vmFile.getName(), vmFile.getId(), outputFolderForThisVM), ex); 
 
  173                 MessageNotifyUtil.Notify.error(NbBundle.getMessage(
this.getClass(), 
"VMExtractorIngestModule.msgNotify.failedExtractVM.title.txt"),
 
  174                         NbBundle.getMessage(
this.getClass(), 
"VMExtractorIngestModule.msgNotify.failedExtractVM.msg.txt", vmFile.getName()));
 
  179             progressBar.progress(NbBundle.getMessage(
this.getClass(), 
"VMExtractorIngestModule.exportingToDisk.message"), numFilesSaved);
 
  181         logger.log(Level.INFO, 
"Finished saving virtual machine files to disk"); 
 
  184         progressBar.switchToDeterminate(imageFolderToOutputFolder.size());
 
  185         progressBar.progress(NbBundle.getMessage(
this.getClass(), 
"VMExtractorIngestModule.queuingIngestJobs.message"));
 
  187         int numJobsQueued = 0;
 
  189         for (String folder : imageFolderToOutputFolder.values()) {
 
  190             if (context.dataSourceIngestIsCancelled()) {
 
  193             List<String> vmFilesToIngest = VirtualMachineFinder.identifyVirtualMachines(Paths.get(folder));
 
  194             for (String file : vmFilesToIngest) {
 
  196                     logger.log(Level.INFO, 
"Ingesting virtual machine file {0} in folder {1}", 
new Object[]{file, folder}); 
 
  200                     ingestVirtualMachineImage(Paths.get(folder, file));
 
  201                     logger.log(Level.INFO, 
"Ingest complete for virtual machine file {0} in folder {1}", 
new Object[]{file, folder}); 
 
  202                 } 
catch (InterruptedException ex) {
 
  203                     logger.log(Level.INFO, 
"Interrupted while ingesting virtual machine file " + file + 
" in folder " + folder, ex); 
 
  204                 } 
catch (IOException ex) {
 
  205                     logger.log(Level.SEVERE, 
"Failed to ingest virtual machine file " + file + 
" in folder " + folder, ex); 
 
  206                     MessageNotifyUtil.Notify.error(NbBundle.getMessage(
this.getClass(), 
"VMExtractorIngestModule.msgNotify.failedIngestVM.title.txt"),
 
  207                             NbBundle.getMessage(
this.getClass(), 
"VMExtractorIngestModule.msgNotify.failedIngestVM.msg.txt", file));
 
  208                 } 
catch (NoCurrentCaseException ex) {
 
  209                     logger.log(Level.SEVERE, 
"Exception while getting open case.", ex); 
 
  210                     MessageNotifyUtil.Notify.error(NbBundle.getMessage(
this.getClass(), 
"VMExtractorIngestModule.msgNotify.failedIngestVM.title.txt"),
 
  211                             Bundle.VMExtractorIngestModule_noOpenCase_errMsg());
 
  216             progressBar.progress(NbBundle.getMessage(
this.getClass(), 
"VMExtractorIngestModule.queuingIngestJobs.message"), numJobsQueued);
 
  218         logger.log(Level.INFO, 
"VMExtractorIngestModule completed processing of data source {0}", dataSource.getName()); 
 
  219         return ProcessResult.OK;
 
  233     private static List<AbstractFile> findVirtualMachineFiles(Content dataSource) 
throws TskCoreException, NoCurrentCaseException {
 
  234         List<AbstractFile> vmFiles = 
new ArrayList<>();
 
  235         for (String vmExtension : GeneralFilter.VIRTUAL_MACHINE_EXTS) {
 
  236             String searchString = 
"%" + vmExtension;    
 
  237             vmFiles.addAll(Case.getCurrentCaseThrows().getServices().getFileManager().findFiles(dataSource, searchString));
 
  251     private void writeVirtualMachineToDisk(AbstractFile vmFile, String outputFolderForThisVM) 
throws ReadContentInputStreamException, IOException {
 
  255         File destinationFolder = Paths.get(outputFolderForThisVM).toFile();
 
  256         if (!destinationFolder.exists()) {
 
  257             destinationFolder.mkdirs();
 
  262         File localFile = Paths.get(outputFolderForThisVM, vmFile.getName()).toFile();
 
  263         ContentUtils.writeToFile(vmFile, localFile, context::dataSourceIngestIsCancelled);
 
  272     private void ingestVirtualMachineImage(Path vmFile) 
throws InterruptedException, IOException, NoCurrentCaseException {
 
  277         UUID taskId = UUID.randomUUID();
 
  278         Case.getCurrentCaseThrows().notifyAddingDataSource(taskId);
 
  279         ImageDSProcessor dataSourceProcessor = 
new ImageDSProcessor();
 
  280         AddDataSourceCallback dspCallback = 
new AddDataSourceCallback(vmFile);
 
  281         synchronized (
this) {
 
  282             dataSourceProcessor.run(parentDeviceId, vmFile.toString(), parentTimeZone, 
false, 
new AddDataSourceProgressMonitor(), dspCallback);
 
  293         if (!dspCallback.vmDataSources.isEmpty()) {
 
  294             Case.getCurrentCaseThrows().notifyDataSourceAdded(dspCallback.vmDataSources.get(0), taskId);
 
  295             List<Content> dataSourceContent = 
new ArrayList<>(dspCallback.vmDataSources);
 
  296             IngestJobSettings ingestJobSettings = 
new IngestJobSettings(context.getExecutionContext());
 
  297             for (String warning : ingestJobSettings.getWarnings()) {
 
  298                 logger.log(Level.WARNING, String.format(
"Ingest job settings warning for virtual machine file %s : %s", vmFile.toString(), warning)); 
 
  300             IngestServices.getInstance().postMessage(IngestMessage.createMessage(IngestMessage.MessageType.INFO,
 
  301                     VMExtractorIngestModuleFactory.getModuleName(),
 
  302                     NbBundle.getMessage(this.getClass(), 
"VMExtractorIngestModule.addedVirtualMachineImage.message", vmFile.toString())));
 
  303             IngestManager.getInstance().queueIngestJob(dataSourceContent, ingestJobSettings);
 
  305             Case.getCurrentCaseThrows().notifyFailedAddingDataSource(taskId);
 
  343             this.vmFile = vmFile;
 
  344             vmDataSources = 
new ArrayList<>();
 
  349             for (String error : errList) {
 
  350                 String logMessage = String.format(
"Data source processor error for virtual machine file %s: %s", vmFile.toString(), error); 
 
  352                     logger.log(Level.SEVERE, logMessage);
 
  354                     logger.log(Level.WARNING, logMessage);
 
  362             if (!content.isEmpty()) {
 
  363                 vmDataSources.add(content.get(0));
 
  369             synchronized (VMExtractorIngestModule.this) {
 
  370                 VMExtractorIngestModule.this.notify();
 
  376             done(result, errList, newContents);