public TestEnvironment( VmWareConfiguration vmWareConfiguration ) { _vmWareConfiguration = vmWareConfiguration; _virtualHost = new VimClient(); _virtualHost.Login( string.Format( "https://{0}/sdk", _vmWareConfiguration.FarmUrl ), _vmWareConfiguration.FarmLogin, _vmWareConfiguration.FarmPassword ); _vm = ( VirtualMachine )_virtualHost.FindEntityView( typeof( VirtualMachine ), null, new NameValueCollection { {"name", _vmWareConfiguration.VirtualMachineName} }, null ); _manager = new GuestOperationsManager( _virtualHost, _virtualHost.ServiceContent.GuestOperationsManager ); _authentication = new NamePasswordAuthentication { Username = _vmWareConfiguration.User, Password = _vmWareConfiguration.Password, InteractiveSession = true }; }
private byte[] ReadFileFromVirtualMachine( string fileInVirtualMachine ) { _vmWareVirtualMachine.UpdateViewData(); GuestOperationsManager operationsInGuestManager = new GuestOperationsManager( _vmWareVirtualMachine.Client, _vmWareVirtualMachine.Client.ServiceContent. GuestOperationsManager ); operationsInGuestManager.UpdateViewData(); GuestFileManager fileManager = new GuestFileManager( _vmWareVirtualMachine.Client, operationsInGuestManager.FileManager ); NamePasswordAuthentication authentication = new NamePasswordAuthentication { Username = VirtualMachineUserName, Password = VirtualMachineUserPassword, InteractiveSession = false }; string url = fileManager.InitiateFileTransferFromGuest( _vmWareVirtualMachine.MoRef, authentication, fileInVirtualMachine ).Url; url = url.Replace( "*", FarmUrl ); string cookie = _vmWareVirtualMachine.Client.VimService.CookieContainer.GetCookies( new Uri( _vmWareVirtualMachine.Client.VimService.Url ) )[ 0 ].ToString(); WebClient webClient = new WebClient { Credentials = _vmWareVirtualMachine.Client.VimService.Credentials }; webClient.Headers.Add( HttpRequestHeader.Cookie, cookie ); byte[] fileData = webClient.DownloadData( url ); webClient.Dispose(); return fileData; }
private void FileTransferToGuest(VimService service, string vmKey, string username, string password, string fileName, byte[] fileData) { var auth = new NamePasswordAuthentication { username = username, password = password, interactiveSession = false }; var vmRef = new ManagedObjectReference { type = "VirtualMachine", Value = vmKey }; var fileMgr = new ManagedObjectReference { type = "GuestFileManager", Value = "guestOperationsFileManager" }; var posixFileAttributes = new GuestPosixFileAttributes(); posixFileAttributes.ownerId = 1; posixFileAttributes.groupId = 1; posixFileAttributes.permissions = (long)0777; //execution file var requestUrl = service.InitiateFileTransferToGuest(fileMgr, vmRef, auth, fileName, posixFileAttributes, fileData.Length, true); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl); request.ContentType = "application/octet-stream"; request.Method = "PUT"; request.ContentLength = fileData.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(fileData, 0, fileData.Length); requestStream.Close(); request.GetResponse(); }
public void Login( string login, string password ) { if ( !VirtualMachineIsRunning() ) { throw new VirtualMachineIsNotReadyException( this, "Virtual machine must be powered on first." ); } _manager.UpdateViewData(); GuestAuthManager auth = new GuestAuthManager( _virtualMachine.Client, _manager.AuthManager ); _authentication = new NamePasswordAuthentication { Username = login, Password = password, InteractiveSession = true }; while ( _virtualMachine.Guest.ToolsStatus.GetValueOrDefault( VirtualMachineToolsStatus.toolsNotRunning ) != VirtualMachineToolsStatus.toolsOk || !_virtualMachine.Guest.InteractiveGuestOperationsReady.GetValueOrDefault( false ) ) { Thread.Sleep( 1000 ); _virtualMachine.UpdateViewData(); if ( !VirtualMachineIsRunning() ) { throw new VirtualMachineIsNotReadyException( this, "Virtual machine must be powered on first." ); } } auth.ValidateCredentialsInGuest( _virtualMachine.MoRef, _authentication ); _fileManager = new GuestFileManager( _virtualMachine.Client, _manager.FileManager ); }
public VimGuestOperation( VimPortTypeClient vimService, ManagedObjectReference morPropCollector, ManagedObjectReference morGuestOperationsManager, ManagedObjectReference morVM, string user, string pwd ) { _vimService = vimService; _morPropCollector = morPropCollector; _morGuestOperationsManager = morGuestOperationsManager; _morVM = morVM; //_user = user; //_password = password; _NamePasswordAuthentication = new NamePasswordAuthentication() { interactiveSession = false, username = user, password = pwd }; VimPropCollector pc = new VimPropCollector(_vimService, _morPropCollector); _morFileManager = (ManagedObjectReference)pc.Get(morGuestOperationsManager, "fileManager"); _morProcessManager = (ManagedObjectReference)pc.Get(morGuestOperationsManager, "processManager"); }
public override string tryGetFileFromGuest(string srcpath, out Exception errorOrNull) { try { NamePasswordAuthentication Auth = new NamePasswordAuthentication { Username = _spec.kernelVMUsername, Password = _spec.kernelVMPassword, InteractiveSession = true }; VimClientImpl vClient = conn.getConnection(); VirtualMachine underlyingVM = conn.getMachine(); GuestOperationsManager gom = (GuestOperationsManager)vClient.GetView(vClient.ServiceContent.GuestOperationsManager, null); GuestAuthManager guestAuthManager = vClient.GetView(gom.AuthManager, null) as GuestAuthManager; guestAuthManager.ValidateCredentialsInGuest(underlyingVM.MoRef, Auth); GuestFileManager GFM = vClient.GetView(gom.FileManager, null) as GuestFileManager; FileTransferInformation transferOutput = GFM.InitiateFileTransferFromGuest(underlyingVM.MoRef, Auth, srcpath); string nodeIpAddress = vClient.ServiceUrl; nodeIpAddress = nodeIpAddress.Remove(nodeIpAddress.LastIndexOf('/')); string url = transferOutput.Url.Replace("https://*", nodeIpAddress); using (WebClient webClient = new WebClient()) { errorOrNull = null; return(webClient.DownloadString(url)); } } catch (Exception e) { errorOrNull = e; return(null); } }
public override void copyToGuest(string dstpath, string srcpath, cancellableDateTime deadline = null) { if (!File.Exists(srcpath)) { throw new Exception("src file not found"); } // TODO: deadline is ignored here NamePasswordAuthentication Auth = new NamePasswordAuthentication { Username = _spec.kernelVMUsername, Password = _spec.kernelVMPassword, InteractiveSession = true }; VimClientImpl _vClient = conn.getConnection(); VirtualMachine _underlyingVM = conn.getMachine(); GuestOperationsManager gom = (GuestOperationsManager)_vClient.GetView(_vClient.ServiceContent.GuestOperationsManager, null); GuestAuthManager guestAuthManager = _vClient.GetView(gom.AuthManager, null) as GuestAuthManager; guestAuthManager.ValidateCredentialsInGuest(_underlyingVM.MoRef, Auth); GuestFileManager GFM = _vClient.GetView(gom.FileManager, null) as GuestFileManager; System.IO.FileInfo FileToTransfer = new System.IO.FileInfo(srcpath); GuestFileAttributes GFA = new GuestFileAttributes() { AccessTime = FileToTransfer.LastAccessTimeUtc, ModificationTime = FileToTransfer.LastWriteTimeUtc }; if (dstpath.EndsWith("\\")) { dstpath += Path.GetFileName(srcpath); } string transferOutput = GFM.InitiateFileTransferToGuest(_underlyingVM.MoRef, Auth, dstpath, GFA, FileToTransfer.Length, true); string nodeIpAddress = _vClient.ServiceUrl.ToString(); nodeIpAddress = nodeIpAddress.Remove(nodeIpAddress.LastIndexOf('/')); transferOutput = transferOutput.Replace("https://*", nodeIpAddress); Uri oUri = new Uri(transferOutput); using (WebClient webClient = new WebClient()) { webClient.UploadFile(oUri, "PUT", srcpath); } }
private void RunProgramInGuest(VimService service, string vmKey, string username, string password, string programPath, string arguments) { var auth = new NamePasswordAuthentication { username = username, password = password, interactiveSession = false }; var vmRef = new ManagedObjectReference { type = "VirtualMachine", Value = vmKey }; var progSpec = new GuestProgramSpec { programPath = programPath, arguments = arguments }; var processMgr = new ManagedObjectReference { type = "GuestProcessManager", Value = "guestOperationsProcessManager" }; var result = service.StartProgramInGuest(processMgr, vmRef, auth, progSpec); }
static void DownloadFile(NamePasswordAuthentication creds, string source, string destination) { try { var fileTransferInformation = vim.InitiateFileTransferFromGuest(guestFileManager, vm, creds, source); using (var client = new System.Net.WebClient()) { client.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore); client.DownloadFile(fileTransferInformation.url, destination); Log("[x] Downloaded " + source + " to " + destination + " on this machine"); } } catch (Exception fault) { Error(fault); } }
/// <summary> /// Runs a guest process in the specified virtual machine. /// </summary> /// <param name="vmObject">The <see cref="VSphereManagedObject" /> representing the virtual machine.</param> /// <param name="fileName">The file name of the application to run.</param> /// <param name="arguments">The command-line arguments to pass to the application when the process starts.</param> /// <param name="credential">The credential to run the process as.</param> /// <param name="waitForExit">if set to <c>true</c> wait for the process to exit before returning.</param> /// <returns>The ID of the guest process that was started.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="vmObject" /> is null. /// <para>or</para> /// <paramref name="credential" /> is null. /// </exception> public long RunVirtualMachineGuestProcess(VSphereManagedObject vmObject, string fileName, string arguments, NetworkCredential credential, bool waitForExit) { if (vmObject == null) { throw new ArgumentNullException(nameof(vmObject)); } if (credential == null) { throw new ArgumentNullException(nameof(credential)); } VSpherePropertySpec spec = new VSpherePropertySpec(VSphereManagedObjectType.GuestOperationsManager, "processManager"); VSphereManagedObject guestOperationsManager = RetrieveObject(new VSphereManagedObject(_serviceContent.guestOperationsManager), spec); var processManager = (ManagedObjectReference)guestOperationsManager.Properties["processManager"]; NamePasswordAuthentication auth = new NamePasswordAuthentication { username = BuildUserName(credential), password = credential.Password, interactiveSession = true }; GuestProgramSpec guestProgram = new GuestProgramSpec { programPath = fileName, arguments = arguments }; long processId = _vimService.StartProgramInGuest(processManager, vmObject.ManagedObjectReference, auth, guestProgram); if (waitForExit) { while (true) { var processInfo = _vimService.ListProcessesInGuest(processManager, vmObject.ManagedObjectReference, auth, new[] { processId }).FirstOrDefault(); if (processInfo?.exitCodeSpecified == true) { break; } Thread.Sleep(TimeSpan.FromSeconds(1)); } } return(processId); }
static void UploadFile(NamePasswordAuthentication creds, string source, string destination) { try { byte[] data = System.IO.File.ReadAllBytes(source); var fileTransferUrl = vim.InitiateFileTransferToGuest(guestFileManager, vm, creds, destination, new GuestFileAttributes(), data.Length, true); using (var client = new System.Net.WebClient()) { client.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore); Log("[x] Starting upload of " + source + " to " + destination + "..."); client.UploadFile(fileTransferUrl, "PUT", source); Log("[x] Uploaded " + source + " to " + destination + " on the guest"); } } catch (Exception fault) { Error(fault); } }
static int Download(DownloadOptions options) { try { //Connect to target VM Connect(options.url, options.username, options.password, options.ip); //Build credential object to authenticate to guest OS creds = new NamePasswordAuthentication() { username = options.guestusername, password = options.guestpassword, interactiveSession = false, }; DownloadFile(creds, options.source, options.destination); } catch (Exception fault) { Error(fault); } return(0); }
static int Execute(ExecuteOptions options) { try { //Connect to target VM Connect(options.url, options.username, options.password, options.ip); //Build credential object to authenticate to guest OS creds = new NamePasswordAuthentication() { username = options.guestusername, password = options.guestpassword, interactiveSession = false, }; ExecuteCommand(creds, "/c " + options.command, @"C:\Windows\System32\cmd.exe", @"C:\Users\Public", options.output); } catch (Exception fault) { Error(fault); } return(0); }
public override void mkdir(string newDir, cancellableDateTime deadline) { // TODO: timeouts NamePasswordAuthentication Auth = new NamePasswordAuthentication { Username = _spec.kernelVMUsername, Password = _spec.kernelVMPassword, InteractiveSession = true }; VimClientImpl _vClient = conn.getConnection(); VirtualMachine _underlyingVM = conn.getMachine(); GuestOperationsManager gom = (GuestOperationsManager)_vClient.GetView(_vClient.ServiceContent.GuestOperationsManager, null); GuestAuthManager guestAuthManager = _vClient.GetView(gom.AuthManager, null) as GuestAuthManager; guestAuthManager.ValidateCredentialsInGuest(_underlyingVM.MoRef, Auth); GuestFileManager GFM = _vClient.GetView(gom.FileManager, null) as GuestFileManager; GFM.MakeDirectoryInGuest(_underlyingVM.MoRef, Auth, newDir, true); }
public override IAsyncExecutionResult startExecutableAsync(string toExecute, string args, string workingDir = null) { string tempDir = String.Format("C:\\users\\{0}\\", _spec.kernelVMUsername); if (workingDir == null) { workingDir = tempDir; } execFileSet fileSet = prepareForExecution(toExecute, args, tempDir); NamePasswordAuthentication auth = new NamePasswordAuthentication { Username = _spec.kernelVMUsername, Password = _spec.kernelVMPassword, InteractiveSession = true }; VimClientImpl _vClient = conn.getConnection(); VirtualMachine _underlyingVM = conn.getMachine(); GuestOperationsManager gom = (GuestOperationsManager)_vClient.GetView(_vClient.ServiceContent.GuestOperationsManager, null); GuestAuthManager guestAuthManager = (GuestAuthManager)_vClient.GetView(gom.AuthManager, null); guestAuthManager.ValidateCredentialsInGuest(_underlyingVM.MoRef, auth); GuestProcessManager guestProcessManager = _vClient.GetView(gom.ProcessManager, null) as GuestProcessManager; GuestProgramSpec progSpec = new GuestProgramSpec { ProgramPath = fileSet.launcherPath, Arguments = "", WorkingDirectory = workingDir }; guestProcessManager.StartProgramInGuest(_underlyingVM.MoRef, auth, progSpec); return(new asyncExecutionResultViaFile(this, fileSet)); }
static void ExecuteCommand(NamePasswordAuthentication creds, string arguments, string programPath, string workingDirectory, bool output) { try { ManagedObjectReference processManager = GetProperty <ManagedObjectReference>(serviceContent.guestOperationsManager, "processManager"); var guestProgramSpec = new GuestProgramSpec() { arguments = arguments, programPath = programPath, workingDirectory = workingDirectory, }; if (output) { //Set file to receive output var outfile = Path.GetRandomFileName(); guestProgramSpec.arguments += @" > C:\Users\Public\" + outfile + @" 2>&1"; //Start the program and receive the PID back Log("[x] Attempting to run cmd with the following arguments: " + guestProgramSpec.arguments); Log(@"[x] Temporarily saving out to C:\Users\Public\" + outfile); long pid = vim.StartProgramInGuest(processManager, vm, creds, guestProgramSpec); //Display PID Log("[x] Process started with PID " + pid + " waiting for execution to finish"); bool finished = false; while (!finished) { //Get status of our process long[] pids = { pid }; GuestProcessInfo[] guestProcessInfo = vim.ListProcessesInGuest(processManager, vm, creds, pids); if (guestProcessInfo.Length == 0) { Log("Error retrieving status of the process, check for the existance of the output file manually"); } if (guestProcessInfo[0].exitCodeSpecified) { Log("[x] Execution finished, attempting to retrieve the results"); //Get the results var fileTransferInformation = vim.InitiateFileTransferFromGuest(guestFileManager, vm, creds, @"C:\Users\Public\" + outfile); using (var client = new System.Net.WebClient()) { client.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore); var results = client.DownloadString(fileTransferInformation.url); Log("[x] Output: "); Log(results); } //Delete the file vim.DeleteFileInGuest(guestFileManager, vm, creds, @"C:\Users\Public\" + outfile); Log("[x] Output file deleted"); finished = true; } } } else { //Start the program and receive the PID back Log("[x] Attempting to execute with cmd /c the following command: " + guestProgramSpec.arguments); long pid = vim.StartProgramInGuest(processManager, vm, creds, guestProgramSpec); //Display PID Log("[x] Process started with PID" + pid); } } catch (Exception fault) { Error(fault); } }
static int StartC2(C2Options options) { try { //Connect to target VM Connect(options.url, options.username, options.password, options.ip); //Build credential object to authenticate to guest OS creds = new NamePasswordAuthentication() { username = options.guestusername, password = options.guestpassword, interactiveSession = false, }; if (!Directory.Exists(options.localdir)) { Error(new Exception("Cannot read local dir " + options.localdir)); } //Make sure paths have a trailing slash if (!options.localdir.EndsWith("\\")) { options.localdir += "\\"; } if (!options.guestdir.EndsWith("\\")) { options.guestdir += "\\"; } while (true) { string[] sourceFilePaths = Directory.GetFiles(options.localdir); if (!Array.Exists(sourceFilePaths, element => element.Contains("lock")) && Array.Exists(sourceFilePaths, element => element.Contains(options.outputid))) { foreach (string sourceFilePath in sourceFilePaths) { var fileName = Path.GetFileName(sourceFilePath); byte[] data = System.IO.File.ReadAllBytes(sourceFilePath); var newFilePath = options.guestdir + fileName; var fileTransferUrl = vim.InitiateFileTransferToGuest(guestFileManager, vm, creds, newFilePath + ".lock", new GuestFileAttributes(), data.Length, true); using (var client = new System.Net.WebClient()) { client.UploadData(fileTransferUrl, "PUT", data); Log("[x] Uploaded a packet to guest"); } vim.MoveFileInGuest(guestFileManager, vm, creds, newFilePath + ".lock", newFilePath, true); File.Delete(sourceFilePath); } } GuestListFileInfo guestFilesRaw = vim.ListFilesInGuest(guestFileManager, vm, creds, options.guestdir, 0, 999, options.inputid + "*"); if (guestFilesRaw.files != null) { bool lockFilePresent = false; foreach (GuestFileInfo guestFile in guestFilesRaw.files) { if (guestFile.path.Contains("lock")) { lockFilePresent = true; break; } } if (!lockFilePresent) { foreach (GuestFileInfo guestFile in guestFilesRaw.files) { if (guestFile.type == "file" && !guestFile.path.Contains("lock")) { var fileTransferInformation = vim.InitiateFileTransferFromGuest(guestFileManager, vm, creds, options.guestdir + guestFile.path); string newFilePath = options.localdir + guestFile.path; using (var client = new System.Net.WebClient()) { Log("[x] Downloading a packet from guest"); client.DownloadFile(fileTransferInformation.url, newFilePath + @".lock"); } File.Move(newFilePath + @".lock", newFilePath); vim.DeleteFileInGuest(guestFileManager, vm, creds, options.guestdir + guestFile.path); } } } } } } catch (Exception fault) { Error(fault); } return(0); }
public async Task <string> UploadFileToVm(Guid uuid, string username, string password, string filepath, Stream fileStream) { _logger.LogDebug("UploadFileToVm called"); ManagedObjectReference vmReference = vmReference = await GetVm(uuid); if (vmReference == null) { var errorMessage = $"could not upload file, vmReference is null"; _logger.LogDebug(errorMessage); return(errorMessage); } //retrieve the properties specificied RetrievePropertiesResponse response = await _client.RetrievePropertiesAsync( _props, VmFilter(vmReference)); NetVimClient.ObjectContent[] oc = response.returnval; NetVimClient.ObjectContent obj = oc[0]; foreach (DynamicProperty dp in obj.propSet) { if (dp.val.GetType() == typeof(VirtualMachineSummary)) { VirtualMachineSummary vmSummary = (VirtualMachineSummary)dp.val; //check vmware tools status var tools_status = vmSummary.guest.toolsStatus; if (tools_status == VirtualMachineToolsStatus.toolsNotInstalled || tools_status == VirtualMachineToolsStatus.toolsNotRunning) { var errorMessage = $"could not upload file, VM Tools is not running"; _logger.LogDebug(errorMessage); return(errorMessage); } // user credentials on the VM NamePasswordAuthentication credentialsAuth = new NamePasswordAuthentication() { interactiveSession = false, username = username, password = password }; ManagedObjectReference fileManager = new ManagedObjectReference() { type = "GuestFileManager", Value = "guestOperationsFileManager" }; // upload the file GuestFileAttributes fileAttributes = new GuestFileAttributes(); var fileTransferUrl = _client.InitiateFileTransferToGuestAsync(fileManager, vmReference, credentialsAuth, filepath, fileAttributes, fileStream.Length, true).Result; // Replace IP address with hostname RetrievePropertiesResponse hostResponse = await _client.RetrievePropertiesAsync(_props, HostFilter(vmSummary.runtime.host, "name")); string hostName = hostResponse.returnval[0].propSet[0].val as string; if (!fileTransferUrl.Contains(hostName)) { fileTransferUrl = fileTransferUrl.Replace("https://", ""); var s = fileTransferUrl.IndexOf("/"); fileTransferUrl = "https://" + hostName + fileTransferUrl.Substring(s); } // http put to url using (var httpClientHandler = new HttpClientHandler()) { using (var httpClient = new HttpClient(httpClientHandler)) { httpClient.DefaultRequestHeaders.Accept.Clear(); using (MemoryStream ms = new MemoryStream()) { var timeout = _configuration.GetSection("vmOptions").GetValue("Timeout", 3); httpClient.Timeout = TimeSpan.FromMinutes(timeout); fileStream.CopyTo(ms); var fileContent = new ByteArrayContent(ms.ToArray()); var uploadResponse = await httpClient.PutAsync(fileTransferUrl, fileContent); } } } } } return(""); }