private static Tuple <double, double> GetLinxMemoryInGB() { try { var results = OSUtils.StartProcessWithResults("cat", "/proc/meminfo"); var resultsArr = results.Split('n'); var freeKB = resultsArr .FirstOrDefault(x => x.StartsWith("FreeMem")) .Split(" ".ToCharArray(), 2) .Last() // 9168236 kB .Trim() .Split(' ') .First(); // 9168236 var totalKB = resultsArr .FirstOrDefault(x => x.StartsWith("MemTotal")) .Split(" ".ToCharArray(), 2) .Last() // 16637468 kB .Trim() .Split(' ') .First(); // 16637468 var freeGB = Math.Round((double.Parse(freeKB) / 1024 / 1024), 2); var totalGB = Math.Round((double.Parse(totalKB) / 1024 / 1024), 2); return(new Tuple <double, double>(freeGB, totalGB)); } catch { return(new Tuple <double, double>(0, 0)); } }
private void StartLinuxScreenCaster(string args) { var xauthority = OSUtils.StartProcessWithResults("find", $"/ -name Xauthority").Split('\n', StringSplitOptions.RemoveEmptyEntries).First(); var display = ":0"; var whoString = OSUtils.StartProcessWithResults("who", "")?.Trim(); var username = string.Empty; if (!string.IsNullOrWhiteSpace(whoString)) { var whoLine = whoString.Split('\n', StringSplitOptions.RemoveEmptyEntries).First(); var whoSplit = whoLine.Split(' ', StringSplitOptions.RemoveEmptyEntries); username = whoSplit[0]; display = whoSplit.Last().Trim('(').Trim(')'); args = $"-u {username} {args}"; } var psi = new ProcessStartInfo() { FileName = "sudo", Arguments = args }; psi.Environment.Add("DISPLAY", display); psi.Environment.Add("XAUTHORITY", xauthority); Logger.Write($"Attempting to launch screen caster with username {username}, xauthority {xauthority}, and display {display}."); Process.Start(psi); }
private int StartLinuxScreenCaster(string args) { var xauthority = string.Empty; var processes = OSUtils.StartProcessWithResults("ps", "-eaf").Split(Environment.NewLine); var xorgLine = processes.FirstOrDefault(x => x.Contains("xorg")); var xorgSplit = xorgLine.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList(); var auth = xorgSplit[xorgSplit.IndexOf("-auth") + 1]; if (!string.IsNullOrWhiteSpace(auth)) { xauthority = auth; } var display = ":0"; var whoString = OSUtils.StartProcessWithResults("w", "-h")?.Trim(); var username = string.Empty; if (!string.IsNullOrWhiteSpace(whoString)) { try { var whoLine = whoString .Split('\n', StringSplitOptions.RemoveEmptyEntries) .First(); var whoSplit = whoLine.Split(' ', StringSplitOptions.RemoveEmptyEntries); username = whoSplit[0]; display = whoSplit[2]; xauthority = $"/home/{username}/.Xauthority"; args = $"-u {username} {args}"; } catch (Exception ex) { Logger.Write(ex); } } var psi = new ProcessStartInfo() { FileName = "sudo", Arguments = args }; psi.Environment.Add("DISPLAY", display); psi.Environment.Add("XAUTHORITY", xauthority); Logger.Write($"Attempting to launch screen caster with username {username}, xauthority {xauthority}, display {display}, and args {args}."); return(Process.Start(psi).Id); }
public static void UninstallAgent() { if (OSUtils.IsWindows) { Process.Start("cmd.exe", "/c sc delete Remotely_Service"); var deleteTime = DateTime.Now.AddMinutes(2).ToString("HH:mm"); var currentDir = AppDomain.CurrentDomain.BaseDirectory; Process.Start("cmd.exe", $"/c timeout 5 & rd /s /q \"{currentDir}\""); } else if (OSUtils.IsLinux) { var users = OSUtils.StartProcessWithResults("users", ""); var username = users?.Split()?.FirstOrDefault()?.Trim(); Process.Start("sudo", "systemctl stop remotely-agent").WaitForExit(); Directory.Delete("/usr/local/bin/Remotely", true); File.Delete("/etc/systemd/system/remotely-agent.service"); Process.Start("sudo", "systemctl daemon-reload").WaitForExit(); } Environment.Exit(0); }
private static string GetCurrentUser() { try { if (OSUtils.IsWindows) { var session = CimSession.Create(null); var computerSystem = session.EnumerateInstances("root\\cimv2", "CIM_ComputerSystem"); var username = computerSystem.FirstOrDefault().CimInstanceProperties["UserName"].Value ?? ""; return(username as string); } else if (OSUtils.IsLinux) { var users = OSUtils.StartProcessWithResults("users", ""); var username = users?.Split()?.FirstOrDefault()?.Trim(); return($"{Environment.UserDomainName}\\{username}"); } throw new Exception("Unsupported operating system."); } catch { return("Error Retrieving"); } }
public static void UninstallClient() { if (OSUtils.IsWindows) { Process.Start("cmd.exe", "/c sc delete Remotely_Service"); var tempFilePath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName()) + ".ps1"; var currentDir = AppDomain.CurrentDomain.BaseDirectory; var ps = PowerShell.Create(); ps.AddScript($@" $Success = $false; $Count = 0; while ((Test-Path ""{currentDir}"") -eq $true -and $Count -lt 10) {{ try {{ Get-Process -Name Agent | Stop-Process -Force; Start-Sleep -Seconds 3; Remove-Item ""{currentDir}"" -Force -Recurse; $Count++; continue; }} catch{{ continue; }} }} "); ps.Invoke(); } else if (OSUtils.IsLinux) { var users = OSUtils.StartProcessWithResults("users", ""); var username = users?.Split()?.FirstOrDefault()?.Trim(); Process.Start("systemctl", "stop remotely-client").WaitForExit(); Directory.Delete("/usr/local/bin/Remotely", true); File.Delete("/etc/systemd/system/remotely-client.service"); Process.Start("systemctl", "daemon-reload").WaitForExit(); } }
private static void RegisterMessageHandlers(HubConnection hubConnection) { hubConnection.On("ExecuteCommand", (async(string mode, string command, string commandID, string senderConnectionID) => { await ExecuteCommand(mode, command, commandID, senderConnectionID); })); hubConnection.On("TransferFiles", async(string transferID, List <string> fileIDs, string requesterID) => { Logger.Write($"File transfer started by {requesterID}."); var connectionInfo = Utilities.GetConnectionInfo(); 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); 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.InvokeAsync("TransferCompleted", transferID, requesterID); }); hubConnection.On("DeployScript", async(string mode, string fileID, string commandContextID, string requesterID) => { var connectionInfo = Utilities.GetConnectionInfo(); var sharedFilePath = Directory.CreateDirectory(Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Remotely", "SharedFiles" )).FullName; var webClient = new WebClient(); var url = $"{connectionInfo.Host}/API/FileSharing/{fileID}"; var wr = WebRequest.CreateHttp(url); var response = await wr.GetResponseAsync(); var cd = response.Headers["Content-Disposition"]; var filename = cd.Split(";").FirstOrDefault(x => x.Trim().StartsWith("filename")).Split("=")[1]; using (var rs = response.GetResponseStream()) { using (var sr = new StreamReader(rs)) { var result = await sr.ReadToEndAsync(); await ExecuteCommand(mode, result, commandContextID, requesterID); } } }); hubConnection.On("UninstallClient", () => { Uninstaller.UninstallAgent(); }); hubConnection.On("RemoteControl", async(string requesterID, string serviceID) => { if (!IsServerVerified) { Logger.Write("Remote control attempted before server was verified."); Uninstaller.UninstallAgent(); return; } try { var rcBinaryPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ScreenCast", OSUtils.ScreenCastExecutableFileName); if (!File.Exists(rcBinaryPath)) { await hubConnection.InvokeAsync("DisplayConsoleMessage", "Remote control executable not found on target device.", requesterID); return; } // Start ScreenCast. await hubConnection.InvokeAsync("DisplayConsoleMessage", $"Starting remote control...", requesterID); if (OSUtils.IsWindows) { if (Program.IsDebug) { Process.Start(rcBinaryPath, $"-mode Unattended -requester {requesterID} -serviceid {serviceID} -host {Utilities.GetConnectionInfo().Host} -desktop default"); } else { var result = Win32Interop.OpenInteractiveProcess(rcBinaryPath + $" -mode Unattended -requester {requesterID} -serviceid {serviceID} -host {Utilities.GetConnectionInfo().Host} -desktop default", "default", true, out _); if (!result) { await hubConnection.InvokeAsync("DisplayConsoleMessage", "Remote control failed to start on target device.", requesterID); } } } else if (OSUtils.IsLinux) { var users = OSUtils.StartProcessWithResults("users", ""); var username = users?.Split()?.FirstOrDefault()?.Trim(); var homeDir = OSUtils.StartProcessWithResults("sudo", $"-u {username} env | grep HOME")?.Split('=')?.Last(); var psi = new ProcessStartInfo() { FileName = "sudo", Arguments = $"-u {username} {rcBinaryPath} -mode Unattended -requester {requesterID} -serviceid {serviceID} -host {Utilities.GetConnectionInfo().Host} -desktop default & disown" }; psi.Environment.Add("DISPLAY", ":0"); psi.Environment.Add("XAUTHORITY", $"{homeDir}/.Xauthority"); var casterProc = Process.Start(psi); casterProc.WaitForExit(); } } catch (Exception ex) { Logger.Write(ex); await hubConnection.InvokeAsync("DisplayConsoleMessage", "Remote control failed to start on target device.", requesterID); throw; } }); hubConnection.On("RestartScreenCaster", async(List <string> viewerIDs, string serviceID, string requesterID) => { if (!IsServerVerified) { Logger.Write("Remote control attempted before server was verified."); Uninstaller.UninstallAgent(); return; } try { var rcBinaryPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ScreenCast", OSUtils.ScreenCastExecutableFileName); // Start ScreenCast. if (OSUtils.IsWindows) { if (Program.IsDebug) { Process.Start(rcBinaryPath, $"-mode Unattended -requester {requesterID} -serviceid {serviceID} -host {Utilities.GetConnectionInfo().Host} -relaunch true -desktop default -viewers {String.Join(",", viewerIDs)}"); } else { var result = Win32Interop.OpenInteractiveProcess(rcBinaryPath + $" -mode Unattended -requester {requesterID} -serviceid {serviceID} -host {Utilities.GetConnectionInfo().Host} -relaunch true -desktop default -viewers {String.Join(",", viewerIDs)}", "default", true, out _); if (!result) { Logger.Write("Failed to relaunch screen caster."); await hubConnection.InvokeAsync("SendConnectionFailedToViewers", viewerIDs); await hubConnection.InvokeAsync("DisplayConsoleMessage", "Remote control failed to start on target device.", requesterID); } } } else if (OSUtils.IsLinux) { var users = OSUtils.StartProcessWithResults("users", ""); var username = users?.Split()?.FirstOrDefault()?.Trim(); var homeDir = OSUtils.StartProcessWithResults("sudo", $"-u {username} env | grep HOME")?.Split('=')?.Last(); var psi = new ProcessStartInfo() { FileName = "sudo", Arguments = $"-u {username} {rcBinaryPath} -mode Unattended -requester {requesterID} -serviceid {serviceID} -host {Utilities.GetConnectionInfo().Host} -relaunch true -desktop default -viewers {String.Join(",", viewerIDs)} & disown" }; psi.Environment.Add("DISPLAY", ":0"); psi.Environment.Add("XAUTHORITY", $"{homeDir}/.Xauthority"); var casterProc = Process.Start(psi); casterProc.WaitForExit(); } } catch (Exception ex) { await hubConnection.InvokeAsync("SendConnectionFailedToViewers", viewerIDs); Logger.Write(ex); throw; } }); hubConnection.On("CtrlAltDel", () => { User32.SendSAS(false); }); hubConnection.On("ServerVerificationToken", (string verificationToken) => { if (verificationToken == Utilities.GetConnectionInfo().ServerVerificationToken) { IsServerVerified = true; if (!Program.IsDebug) { Updater.CheckForCoreUpdates(); } } else { Logger.Write($"Server sent an incorrect verification token. Token Sent: {verificationToken}."); Uninstaller.UninstallAgent(); return; } }); }
private static void RegisterMessageHandlers(HubConnection hubConnection) { hubConnection.On("ExecuteCommand", (async(string mode, string command, string commandID, string senderConnectionID) => { await ExecuteCommand(mode, command, commandID, senderConnectionID); })); hubConnection.On("TransferFiles", async(string transferID, List <string> fileIDs, string requesterID) => { Logger.Write("File transfer started."); var connectionInfo = Utilities.GetConnectionInfo(); var sharedFilePath = Directory.CreateDirectory(Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "DoXM", "SharedFiles" )).FullName; foreach (var fileID in fileIDs) { var url = $"{connectionInfo.Host}/API/FileSharing/{fileID}"; var wr = WebRequest.CreateHttp(url); var response = await wr.GetResponseAsync(); var cd = response.Headers["Content-Disposition"]; var filename = cd.Split(";").FirstOrDefault(x => x.Trim().StartsWith("filename")).Split("=")[1]; using (var rs = response.GetResponseStream()) { using (var fs = new FileStream(Path.Combine(sharedFilePath, filename), FileMode.Create)) { rs.CopyTo(fs); } } } await HubConnection.InvokeAsync("TransferCompleted", transferID, requesterID); }); hubConnection.On("DeployScript", async(string mode, string fileID, string commandContextID, string requesterID) => { var connectionInfo = Utilities.GetConnectionInfo(); var sharedFilePath = Directory.CreateDirectory(Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "DoXM", "SharedFiles" )).FullName; var webClient = new WebClient(); var url = $"{connectionInfo.Host}/API/FileSharing/{fileID}"; var wr = WebRequest.CreateHttp(url); var response = await wr.GetResponseAsync(); var cd = response.Headers["Content-Disposition"]; var filename = cd.Split(";").FirstOrDefault(x => x.Trim().StartsWith("filename")).Split("=")[1]; using (var rs = response.GetResponseStream()) { using (var sr = new StreamReader(rs)) { var result = await sr.ReadToEndAsync(); await ExecuteCommand(mode, result, commandContextID, requesterID); } } }); hubConnection.On("UninstallClient", () => { Uninstaller.UninstallClient(); }); hubConnection.On("LaunchRCInNewDesktop", async(string[] viewerIDs, string serviceID, string desktop) => { if (!IsServerVerified) { Logger.Write("Remote control attempted before server was verified."); Uninstaller.UninstallClient(); return; } var rcBinaryPath = Path.Combine(Utilities.AppDataDir, "remote_control", OSUtils.RemoteControlExecutableFileName); var procInfo = new ADVAPI32.PROCESS_INFORMATION(); var processResult = Win32Interop.OpenInteractiveProcess(rcBinaryPath + $" -mode desktopswitch -viewers {String.Join(",",viewerIDs)} -serviceid {serviceID} -desktop {desktop} -hostname {Utilities.GetConnectionInfo().Host.Split("//").Last()}", desktop, true, out procInfo); if (!processResult) { foreach (var viewer in viewerIDs) { await hubConnection.InvokeAsync("DesktopSwitchFailed", viewer); } } }); hubConnection.On("RemoteControl", async(string requesterID, string serviceID) => { if (!IsServerVerified) { Logger.Write("Remote control attempted before server was verified."); Uninstaller.UninstallClient(); return; } try { var latestVersion = await Updater.GetLatestRCVersion(); var rcBinaryPath = Path.Combine(Utilities.AppDataDir, "remote_control", OSUtils.RemoteControlExecutableFileName); var shouldUpdate = false; if (!File.Exists(rcBinaryPath)) { shouldUpdate = true; } else { var fileVersion = FileVersionInfo.GetVersionInfo(rcBinaryPath)?.FileVersion; if (!string.IsNullOrWhiteSpace(fileVersion) && fileVersion?.ToString() != latestVersion) { shouldUpdate = true; } } if (shouldUpdate) { await hubConnection.InvokeAsync("DisplayConsoleMessage", "A new version needs to be downloaded on the client machine.", requesterID); await Updater.DownloadLatestRCVersion(hubConnection, requesterID); } await hubConnection.InvokeAsync("DisplayConsoleMessage", $"Starting remote control...", requesterID); if (OSUtils.IsWindows) { var doxmClient = System.Reflection.Assembly.GetExecutingAssembly().Location.Replace(".dll", ".exe"); var procInfo = new ADVAPI32.PROCESS_INFORMATION(); Win32Interop.OpenInteractiveProcess(doxmClient + $" -mode remotecontrol -requester {requesterID} -serviceid {serviceID}", $"default", true, out procInfo); } else if (OSUtils.IsLinux) { var users = OSUtils.StartProcessWithResults("users", ""); var username = users?.Split()?.FirstOrDefault()?.Trim(); Process.Start("sudo", $"-u {username} {rcBinaryPath} -mode unattended -requester {requesterID} -serviceid {serviceID} -desktop default -hostname {Utilities.GetConnectionInfo().Host.Split("//").Last()}"); } } catch { await hubConnection.InvokeAsync("DisplayConsoleMessage", "Remote control failed to download or start on target machine.", requesterID); throw; } }); hubConnection.On("CtrlAltDel", () => { User32.SendSAS(false); }); hubConnection.On("ServerVerificationToken", (string verificationToken) => { if (verificationToken == Utilities.GetConnectionInfo().ServerVerificationToken) { IsServerVerified = true; Updater.CheckForCoreUpdates(); } else { Logger.Write($"Server sent an incorrect verification token. Token Sent: {verificationToken}."); Uninstaller.UninstallClient(); return; } }); }