public async Task ExecuteCommandFromApi(string mode, string requestID, string command, string commandID, string senderUserName, HubConnection hubConnection) { try { switch (mode.ToLower()) { case "pscore": var psCoreResult = PSCore.GetCurrent(senderUserName).WriteInput(command, commandID); await SendResultsViaAjax("PSCore", psCoreResult); break; case "winps": if (EnvironmentHelper.IsWindows) { var result = WindowsPS.GetCurrent(senderUserName).WriteInput(command, commandID); await SendResultsViaAjax("WinPS", result); } break; case "cmd": if (EnvironmentHelper.IsWindows) { var result = CMD.GetCurrent(senderUserName).WriteInput(command, commandID); await SendResultsViaAjax("CMD", result); } break; case "bash": if (EnvironmentHelper.IsLinux) { var result = Bash.GetCurrent(senderUserName).WriteInput(command, commandID); await SendResultsViaAjax("Bash", result); } break; default: break; } await hubConnection.SendAsync("CommandResultViaApi", commandID, requestID); } catch (Exception ex) { Logger.Write(ex); } }
// TODO: Async/await. private ScriptResult ExecuteScriptContent(ScriptingShell shell, string terminalSessionId, string command, TimeSpan timeout) { switch (shell) { case ScriptingShell.PSCore: return(PSCore.GetCurrent(terminalSessionId).WriteInput(command)); case ScriptingShell.WinPS: if (EnvironmentHelper.IsWindows) { return(ExternalScriptingShell .GetCurrent(ScriptingShell.WinPS, terminalSessionId) .WriteInput(command, timeout)); } break; case ScriptingShell.CMD: if (EnvironmentHelper.IsWindows) { return(ExternalScriptingShell .GetCurrent(ScriptingShell.CMD, terminalSessionId) .WriteInput(command, timeout)); } break; case ScriptingShell.Bash: return(ExternalScriptingShell .GetCurrent(ScriptingShell.Bash, terminalSessionId) .WriteInput(command, timeout)); default: break; } return(null); }
public static PSCore GetCurrent(string connectionID) { if (Sessions.ContainsKey(connectionID)) { var psCore = Sessions[connectionID]; psCore.ProcessIdleTimeout.Stop(); psCore.ProcessIdleTimeout.Start(); return(psCore); } else { var psCore = new PSCore(); psCore.ProcessIdleTimeout = new Timer(600000); // 10 minutes. psCore.ProcessIdleTimeout.AutoReset = false; psCore.ProcessIdleTimeout.Elapsed += (sender, args) => { Sessions.Remove(connectionID, out var pSCore); }; Sessions.AddOrUpdate(connectionID, psCore, (id, p) => psCore); psCore.ProcessIdleTimeout.Start(); return(psCore); } }
private void RegisterMessageHandlers() { // TODO: Remove possibility for circular dependencies in the future // by emitting these events so other services can listen for them. _hubConnection.On("ChangeWindowsSession", async(string serviceID, string viewerID, int targetSessionID) => { try { if (!IsServerVerified) { Logger.Write("Session change attempted before server was verified.", EventType.Warning); return; } await _appLauncher.RestartScreenCaster(new List <string>() { viewerID }, serviceID, viewerID, _hubConnection, targetSessionID); } catch (Exception ex) { Logger.Write(ex); } }); _hubConnection.On("Chat", async(string senderName, string message, string orgName, bool disconnected, string senderConnectionID) => { try { if (!IsServerVerified) { Logger.Write("Chat attempted before server was verified.", EventType.Warning); return; } await _chatService.SendMessage(senderName, message, orgName, disconnected, senderConnectionID, _hubConnection); } catch (Exception ex) { Logger.Write(ex); } }); _hubConnection.On("CtrlAltDel", () => { if (!IsServerVerified) { Logger.Write("CtrlAltDel attempted before server was verified.", EventType.Warning); return; } User32.SendSAS(false); }); _hubConnection.On("DownloadFile", async(string filePath, string senderConnectionID) => { try { if (!IsServerVerified) { Logger.Write("File download attempted before server was verified.", EventType.Warning); return; } filePath = filePath.Replace("\"", ""); if (!File.Exists(filePath)) { await _hubConnection.SendAsync("DisplayMessage", "File not found on remote device.", "File not found.", "bg-danger", senderConnectionID); return; } using var wc = new WebClient(); var lastProgressPercent = 0; wc.UploadProgressChanged += async(sender, args) => { if (args.ProgressPercentage > lastProgressPercent) { lastProgressPercent = args.ProgressPercentage; await _hubConnection.SendAsync("DownloadFileProgress", lastProgressPercent, senderConnectionID); } }; try { var response = await wc.UploadFileTaskAsync($"{ConnectionInfo.Host}/API/FileSharing/", filePath); var fileIDs = JsonSerializer.Deserialize <string[]>(Encoding.UTF8.GetString(response)); await _hubConnection.SendAsync("DownloadFile", fileIDs[0], senderConnectionID); } catch (Exception ex) { Logger.Write(ex); await _hubConnection.SendAsync("DisplayMessage", "Error occurred while uploading file from remote computer.", "Upload error.", "bg-danger", senderConnectionID); } } catch (Exception ex) { Logger.Write(ex); } }); _hubConnection.On("ExecuteCommand", ((ScriptingShell shell, string command, string authToken, string senderUsername, string senderConnectionID) => { try { if (!IsServerVerified) { Logger.Write($"Command attempted before server was verified. Shell: {shell}. Command: {command}. Sender: {senderConnectionID}", EventType.Warning); return; } _ = _scriptExecutor.RunCommandFromTerminal(shell, command, authToken, senderUsername, senderConnectionID, ScriptInputType.Terminal, TimeSpan.FromSeconds(30), _hubConnection); } catch (Exception ex) { Logger.Write(ex); } })); _hubConnection.On("ExecuteCommandFromApi", ( ScriptingShell shell, string authToken, string requestID, string command, string senderUsername) => { try { if (!IsServerVerified) { Logger.Write($"Command attempted before server was verified. Shell: {shell}. Command: {command}. Sender: {senderUsername}", EventType.Warning); return; } _ = _scriptExecutor.RunCommandFromApi(shell, requestID, command, senderUsername, authToken, _hubConnection); } catch (Exception ex) { Logger.Write(ex); } }); _hubConnection.On("GetLogs", async(string senderConnectionId) => { var logBytes = await Logger.ReadAllLogs(); if (!logBytes.Any()) { var message = "There are no log entries written."; await _hubConnection.InvokeAsync("SendLogs", message, senderConnectionId); return; } for (var i = 0; i < logBytes.Length; i += 100_000) { var chunk = Encoding.UTF8.GetString(logBytes.Skip(i).Take(100_000).ToArray()); await _hubConnection.InvokeAsync("SendLogs", chunk, senderConnectionId); } }); _hubConnection.On("GetPowerShellCompletions", async(string inputText, int currentIndex, CompletionIntent intent, bool?forward, string senderConnectionId) => { try { var session = PSCore.GetCurrent(senderConnectionId); var completion = session.GetCompletions(inputText, currentIndex, forward); var completionModel = completion.ToPwshCompletion(); await _hubConnection.InvokeAsync("ReturnPowerShellCompletions", completionModel, intent, senderConnectionId); } catch (Exception ex) { Logger.Write(ex); } }); _hubConnection.On("ReinstallAgent", async() => { try { await _updater.InstallLatestVersion(); } catch (Exception ex) { Logger.Write(ex); } }); _hubConnection.On("UninstallAgent", () => { try { _uninstaller.UninstallAgent(); } catch (Exception ex) { Logger.Write(ex); } }); _hubConnection.On("RemoteControl", async(string requesterID, string serviceID) => { try { if (!IsServerVerified) { Logger.Write("Remote control attempted before server was verified.", EventType.Warning); return; } await _appLauncher.LaunchRemoteControl(-1, requesterID, serviceID, _hubConnection); } catch (Exception ex) { Logger.Write(ex); } }); _hubConnection.On("RestartScreenCaster", async(List <string> viewerIDs, string serviceID, string requesterID) => { try { if (!IsServerVerified) { Logger.Write("Remote control attempted before server was verified.", EventType.Warning); return; } await _appLauncher.RestartScreenCaster(viewerIDs, serviceID, requesterID, _hubConnection); } catch (Exception ex) { Logger.Write(ex); } }); _hubConnection.On("RunScript", (Guid savedScriptId, int scriptRunId, string initiator, ScriptInputType scriptInputType, string authToken) => { try { if (!IsServerVerified) { Logger.Write($"Script run attempted before server was verified. Script ID: {savedScriptId}. Initiator: {initiator}", EventType.Warning); return; } _ = _scriptExecutor.RunScript(savedScriptId, scriptRunId, initiator, scriptInputType, authToken); } catch (Exception ex) { Logger.Write(ex); } }); _hubConnection.On("ServerVerificationToken", (string verificationToken) => { if (verificationToken == ConnectionInfo.ServerVerificationToken) { IsServerVerified = true; } else { Logger.Write($"Server sent an incorrect verification token. Token Sent: {verificationToken}.", EventType.Warning); return; } }); _hubConnection.On("TransferFileFromBrowserToAgent", async(string transferID, List <string> fileIDs, string requesterID, string authToken) => { try { if (!IsServerVerified) { Logger.Write("File upload attempted before server was verified.", EventType.Warning); return; } Logger.Write($"File upload started by {requesterID}."); var sharedFilePath = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "RemotelySharedFiles")).FullName; foreach (var fileID in fileIDs) { var url = $"{ConnectionInfo.Host}/API/FileSharing/{fileID}"; var wr = WebRequest.CreateHttp(url); wr.Headers[HttpRequestHeader.Authorization] = authToken; using var response = await wr.GetResponseAsync(); var cd = response.Headers["Content-Disposition"]; var filename = cd .Split(";") .FirstOrDefault(x => x.Trim() .StartsWith("filename")) .Split("=")[1]; var legalChars = filename.ToCharArray().Where(x => !Path.GetInvalidFileNameChars().Any(y => x == y)); filename = new string(legalChars.ToArray()); using var rs = response.GetResponseStream(); using var fs = new FileStream(Path.Combine(sharedFilePath, filename), FileMode.Create); rs.CopyTo(fs); } await _hubConnection.SendAsync("TransferCompleted", transferID, requesterID); } catch (Exception ex) { Logger.Write(ex); } }); _hubConnection.On("TriggerHeartbeat", async() => { await SendHeartbeat(); }); }
private static async Task ExecuteCommand(string mode, string command, string commandID, string senderConnectionID) { if (!IsServerVerified) { Logger.Write($"Command attempted before server was verified. Mode: {mode}. Command: {command}. Sender: {senderConnectionID}"); Uninstaller.UninstallAgent(); return; } try { switch (mode.ToLower()) { case "pscore": { var psCoreResult = PSCore.GetCurrent(senderConnectionID).WriteInput(command, commandID); var serializedResult = JsonConvert.SerializeObject(psCoreResult); if (Encoding.UTF8.GetBytes(serializedResult).Length > 400000) { SendResultsViaAjax("PSCore", psCoreResult); await HubConnection.InvokeAsync("PSCoreResultViaAjax", commandID); } else { await HubConnection.InvokeAsync("PSCoreResult", psCoreResult); } break; } case "winps": if (OSUtils.IsWindows) { var result = WindowsPS.GetCurrent(senderConnectionID).WriteInput(command, commandID); var serializedResult = JsonConvert.SerializeObject(result); if (Encoding.UTF8.GetBytes(serializedResult).Length > 400000) { SendResultsViaAjax("WinPS", result); await HubConnection.InvokeAsync("WinPSResultViaAjax", commandID); } else { await HubConnection.InvokeAsync("CommandResult", result); } } break; case "cmd": if (OSUtils.IsWindows) { var result = CMD.GetCurrent(senderConnectionID).WriteInput(command, commandID); var serializedResult = JsonConvert.SerializeObject(result); if (Encoding.UTF8.GetBytes(serializedResult).Length > 400000) { SendResultsViaAjax("CMD", result); await HubConnection.InvokeAsync("CMDResultViaAjax", commandID); } else { await HubConnection.InvokeAsync("CommandResult", result); } } break; case "bash": if (OSUtils.IsLinux) { var result = Bash.GetCurrent(senderConnectionID).WriteInput(command, commandID); var serializedResult = JsonConvert.SerializeObject(result); if (Encoding.UTF8.GetBytes(serializedResult).Length > 400000) { SendResultsViaAjax("Bash", result); } else { await HubConnection.InvokeAsync("CommandResult", result); } } break; default: break; } } catch (Exception ex) { Logger.Write(ex); await HubConnection.InvokeAsync("DisplayConsoleMessage", $"There was an error executing the command. It has been logged on the client device.", senderConnectionID); } }
public async Task ExecuteCommand(string mode, string command, string commandID, string senderConnectionID, HubConnection hubConnection) { try { switch (mode.ToLower()) { case "pscore": { var psCoreResult = PSCore.GetCurrent(senderConnectionID).WriteInput(command, commandID); var serializedResult = JsonSerializer.Serialize(psCoreResult); if (Encoding.UTF8.GetBytes(serializedResult).Length > 400000) { await SendResultsViaAjax("PSCore", psCoreResult); await hubConnection.SendAsync("PSCoreResultViaAjax", commandID); } else { await hubConnection.SendAsync("PSCoreResult", psCoreResult); } break; } case "winps": if (EnvironmentHelper.IsWindows) { var result = WindowsPS.GetCurrent(senderConnectionID).WriteInput(command, commandID); var serializedResult = JsonSerializer.Serialize(result); if (Encoding.UTF8.GetBytes(serializedResult).Length > 400000) { await SendResultsViaAjax("WinPS", result); await hubConnection.SendAsync("WinPSResultViaAjax", commandID); } else { await hubConnection.SendAsync("CommandResult", result); } } break; case "cmd": if (EnvironmentHelper.IsWindows) { var result = CMD.GetCurrent(senderConnectionID).WriteInput(command, commandID); var serializedResult = JsonSerializer.Serialize(result); if (Encoding.UTF8.GetBytes(serializedResult).Length > 400000) { await SendResultsViaAjax("CMD", result); await hubConnection.SendAsync("CMDResultViaAjax", commandID); } else { await hubConnection.SendAsync("CommandResult", result); } } break; case "bash": if (EnvironmentHelper.IsLinux) { var result = Bash.GetCurrent(senderConnectionID).WriteInput(command, commandID); var serializedResult = JsonSerializer.Serialize(result); if (Encoding.UTF8.GetBytes(serializedResult).Length > 400000) { await SendResultsViaAjax("Bash", result); await hubConnection.SendAsync("BashResultViaAjax", commandID); } else { await hubConnection.SendAsync("CommandResult", result); } } break; default: break; } } catch (Exception ex) { Logger.Write(ex); await hubConnection.SendAsync("DisplayMessage", "There was an error executing the command. It has been logged on the client device.", "Error executing command.", senderConnectionID); } }