private static void DoWork() { try { log("BEGIN::Set ProjectsDirectory"); // Don't mess with ProjectsDirectory if we need to reauth if (args.Length == 0) { Log.ResetLogPath(logpath); } log("Set UnhandledException"); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); System.Threading.Thread.Sleep(1000 * StartupWaitSeconds); if (args.Length != 0) { try { log("Get usefreerdp"); if (PluginConfig.usefreerdp) { log("Init Freerdp"); using (var rdp = new FreeRDP.Core.RDP()) { } } } catch (Exception) { Console.WriteLine("Failed initilizing FreeRDP, is Visual C++ Runtime installed ?"); // Console.WriteLine("https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads"); Console.WriteLine("https://www.microsoft.com/en-us/download/details.aspx?id=40784"); return; } } if (args.Length == 0) { log("Check IsServiceInstalled"); // System.Threading.Thread.Sleep(1000 * StartupWaitSeconds); if (!manager.IsServiceInstalled) { //Console.Write("Username (" + NativeMethods.GetProcessUserName() + "): "); //var username = Console.ReadLine(); //if (string.IsNullOrEmpty(username)) username = NativeMethods.GetProcessUserName(); //Console.Write("Password: "******""; //do //{ // ConsoleKeyInfo key = Console.ReadKey(true); // if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter) // { // pass += key.KeyChar; // Console.Write("*"); // } // else // { // if (key.Key == ConsoleKey.Backspace && pass.Length > 0) // { // pass = pass.Substring(0, (pass.Length - 1)); // Console.Write("\b \b"); // } // else if (key.Key == ConsoleKey.Enter) // { // break; // } // } //} while (true); //manager.InstallService(typeof(Program), new string[] { "username="******"password="******"InstallService"); manager.InstallService(typeof(Program), new string[] { }); } } if (args.Length > 0) { if (args[0].ToLower() == "auth" || args[0].ToLower() == "reauth") { if (Config.local.jwt != null && Config.local.jwt.Length > 0) { Log.Information("Saving temporart jwt token, from local settings.json"); PluginConfig.tempjwt = new System.Net.NetworkCredential(string.Empty, Config.local.UnprotectString(Config.local.jwt)).Password; PluginConfig.wsurl = Config.local.wsurl; PluginConfig.Save(); } return; } else if (args[0].ToLower() == "uninstall" || args[0].ToLower() == "u") { if (manager.IsServiceInstalled) { manager.UninstallService(typeof(Program)); } var asm = System.Reflection.Assembly.GetEntryAssembly(); var filepath = asm.CodeBase.Replace("file:///", ""); var exepath = System.IO.Path.GetDirectoryName(filepath); if (System.IO.File.Exists(System.IO.Path.Combine(exepath, "OpenRPA.RDServiceMonitor.exe"))) { var process = System.Diagnostics.Process.Start(System.IO.Path.Combine(exepath, "OpenRPA.RDServiceMonitor.exe"), "uninstall"); process.WaitForExit(); } return; } else { Console.WriteLine("unknown command " + args[0]); Console.WriteLine("try uninstall or reauth "); } return; } log("Create Tracing"); tracing = new Tracing(Console.Out); log("Add Tracing"); System.Diagnostics.Trace.Listeners.Add(tracing); log("Override SetOut"); Console.SetOut(new ConsoleDecorator(Console.Out)); log("Override SetError"); Console.SetError(new ConsoleDecorator(Console.Out, true)); log("ResetLogPath"); Log.ResetLogPath(logpath); Console.WriteLine("****** BEGIN"); Task.Run(async() => { try { Console.WriteLine("Connect to " + PluginConfig.wsurl); global.webSocketClient = new WebSocketClient(PluginConfig.wsurl); global.webSocketClient.OnOpen += WebSocketClient_OnOpen; global.webSocketClient.OnClose += WebSocketClient_OnClose; global.webSocketClient.OnQueueMessage += WebSocketClient_OnQueueMessage; await global.webSocketClient.Connect(); } catch (Exception ex) { Log.Error(ex.ToString()); } }); // NativeMethods.AllocConsole(); // if (System.Diagnostics.Debugger.IsAttached && !isService) if (!Monitormanager.IsServiceInstalled) { var asm = System.Reflection.Assembly.GetEntryAssembly(); var filepath = asm.CodeBase.Replace("file:///", ""); var exepath = System.IO.Path.GetDirectoryName(filepath); if (System.IO.File.Exists(System.IO.Path.Combine(exepath, "OpenRPA.RDServiceMonitor.exe"))) { var process = System.Diagnostics.Process.Start(System.IO.Path.Combine(exepath, "OpenRPA.RDServiceMonitor.exe")); process.WaitForExit(); } } if (!isService) { Log.Information("******************************"); Log.Information("* Done *"); Log.Information("******************************"); Console.ReadLine(); } else { if (Monitormanager.IsServiceInstalled) { _ = Monitormanager.StartService(); } while (MyServiceBase.isRunning) { System.Threading.Thread.Sleep(100); } if (Monitormanager.IsServiceInstalled) { // _ = Monitormanager.StopService(); } } } catch (Exception ex) { Log.Error(ex.ToString()); } }
static void Main(string[] args) { System.Threading.Thread.Sleep(1000 * StartupWaitSeconds); // Don't mess with ProjectsDirectory if we need to reauth if (args.Length == 0) { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); try { if (PluginConfig.usefreerdp) { using (var rdp = new FreeRDP.Core.RDP()) { } } } catch (Exception) { Console.WriteLine("Failed initilizing FreeRDP, is Visual C++ Runtime installed ?"); // Console.WriteLine("https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads"); Console.WriteLine("https://www.microsoft.com/en-us/download/details.aspx?id=40784"); return; } } var parentProcess = NativeMethods.GetParentProcessId(); isService = (parentProcess.ProcessName.ToLower() == "services"); if (args.Length == 0) { // System.Threading.Thread.Sleep(1000 * StartupWaitSeconds); if (!manager.IsServiceInstalled) { //Console.Write("Username (" + NativeMethods.GetProcessUserName() + "): "); //var username = Console.ReadLine(); //if (string.IsNullOrEmpty(username)) username = NativeMethods.GetProcessUserName(); //Console.Write("Password: "******""; //do //{ // ConsoleKeyInfo key = Console.ReadKey(true); // if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter) // { // pass += key.KeyChar; // Console.Write("*"); // } // else // { // if (key.Key == ConsoleKey.Backspace && pass.Length > 0) // { // pass = pass.Substring(0, (pass.Length - 1)); // Console.Write("\b \b"); // } // else if (key.Key == ConsoleKey.Enter) // { // break; // } // } //} while (true); //manager.InstallService(typeof(Program), new string[] { "username="******"password="******"****** BEGIN"); if (args.Length > 0) { if (args[0].ToLower() == "auth" || args[0].ToLower() == "reauth") { if (Config.local.jwt != null && Config.local.jwt.Length > 0) { Log.Information("Saving temporart jwt token, from local settings.json"); PluginConfig.tempjwt = new System.Net.NetworkCredential(string.Empty, Config.local.UnprotectString(Config.local.jwt)).Password; PluginConfig.Save(); Config.Save(); Console.WriteLine("local count: " + Config.local.properties.Count); Console.WriteLine("Plugin count: " + PluginConfig.globallocal.properties.Count); } return; } else if (args[0].ToLower() == "uninstall" || args[0].ToLower() == "u") { if (manager.IsServiceInstalled) { manager.UninstallService(typeof(Program)); } return; } } Console.WriteLine("****** isService: " + isService); if (isService) { System.ServiceProcess.ServiceBase.Run(new MyServiceBase(ServiceName, DoWork)); } else { DoWork(); } }
public void DoWork() { try { if (System.Diagnostics.Debugger.IsAttached) { skiprdp = true; } if (client == null) { Log.Information("client is null"); return; } if (string.IsNullOrEmpty(client._id)) { // Log.Information("client._id is null, Dummy client, ignore"); return; // Dummy client, ignore } if (connection != null && connection.IsConnected == false) { connection = null; created = DateTime.Now; } // Is OpenRPA connected for this user ? if (connection != null) { connection.PushMessage(new RPAMessage("ping")); // created = DateTime.Now; // return; } if ((DateTime.Now - created).TotalSeconds < 5) { return; } // Is user signed in ? // ownerexplorer = null; //if (ownerexplorer == null) var rdpip = "127.0.0.2"; // if ((ConnectionAttempts % 2) == 1) rdpip = "127.0.0.1"; if (PluginConfig.usefreerdp && !skiprdp) { if (freerdp == null || freerdp.Connected == false) { if (freerdp == null) { Console.WriteLine("rdp is null"); } if (string.IsNullOrEmpty(client.windowspassword)) { return; } lastrdp = DateTime.Now; } if (freerdp == null) { freerdp = new FreeRDP.Core.RDP(); } if (!freerdp.Connected) { var hostname = NativeMethods.GetHostName().ToLower(); try { Log.Information("Tesing connection to " + rdpip + " port 3389"); using (var tcpClient = new System.Net.Sockets.TcpClient()) { var ipAddress = System.Net.IPAddress.Parse(rdpip); var ipEndPoint = new System.Net.IPEndPoint(ipAddress, 3389); tcpClient.Connect(ipEndPoint); } Log.Information("Success"); } catch (Exception ex) { Log.Error(ex.ToString()); return; } var windowsusername = client.windowsusername.Substring(client.windowsusername.IndexOf("\\") + 1); var windowsdomain = client.windowsusername.Substring(0, client.windowsusername.IndexOf("\\")); using (var imp = new Impersonator(windowsusername, windowsdomain, client.windowspassword)) { ConnectionAttempts++; if (client.windowsusername.StartsWith(hostname + @"\")) { // var windowsusername = client.windowsusername.Substring(hostname.Length + 1); Log.Information("Connecting RDP connection to " + rdpip + " for " + windowsusername); freerdp.Connect(rdpip, "", windowsusername, client.windowspassword); } else { Log.Information("Connecting RDP connection to " + rdpip + " for " + client.windowsusername); freerdp.Connect(rdpip, "", client.windowsusername, client.windowspassword); } } created = DateTime.Now; return; } if (freerdp == null || freerdp.Connected == false) { return; } } else if (!skiprdp) { if (rdp == null || rdp.Connected == false) { if (rdp == null) { Console.WriteLine("rdp is null"); } if (string.IsNullOrEmpty(client.windowspassword)) { return; } lastrdp = DateTime.Now; } if (rdp == null) { rdp = new Client(); } if (rdp.Connecting) { return; } if (!rdp.Connected) { try { Log.Information("Tesing connection to " + rdpip + " port 3389"); using (var tcpClient = new System.Net.Sockets.TcpClient()) { var ipAddress = System.Net.IPAddress.Parse(rdpip); var ipEndPoint = new System.Net.IPEndPoint(ipAddress, 3389); tcpClient.Connect(ipEndPoint); } Log.Information("Success"); } catch (Exception ex) { Log.Error(ex.ToString()); return; } ConnectionAttempts++; var hostname = NativeMethods.GetHostName().ToLower(); if (client.windowsusername.StartsWith(hostname + @"\")) { var windowsusername = client.windowsusername.Substring(hostname.Length + 1); Log.Information("Connecting RDP connection to " + rdpip + " for " + windowsusername); // Task.Run(()=>rdp.CreateRdpConnectionasync(rdpip, "", client.windowsusername.Substring(hostname.Length + 1), client.windowspassword)); rdp.CreateRdpConnectionasync(rdpip, "", client.windowsusername.Substring(hostname.Length + 1), client.windowspassword); Log.Information("Connection initialized"); } else { Log.Information("Connecting RDP connection to " + rdpip + " for " + client.windowsusername); // Task.Run(() => rdp.CreateRdpConnectionasync(rdpip, "", client.windowsusername, client.windowspassword)); rdp.CreateRdpConnectionasync(rdpip, "", client.windowsusername, client.windowspassword); Log.Information("Connection initialized"); } created = DateTime.Now; } if (rdp == null || rdp.Connected == false) { return; } } try { var procs = Process.GetProcessesByName("explorer"); System.Diagnostics.Process ownerexplorer = null; foreach (var explorer in procs) { try { var owner = NativeMethods.GetProcessUserName(explorer).ToLower(); if (owner == client.windowsusername) { ownerexplorer = explorer; } } catch (Exception ex) { Log.Error(ex.ToString()); created = DateTime.Now; return; } } if (ownerexplorer == null) { return; } System.Diagnostics.Process ownerrpa = null; procs = Process.GetProcessesByName("openrpa"); foreach (var rpa in procs) { try { var owner = NativeMethods.GetProcessUserName(rpa).ToLower(); if (owner == client.windowsusername) { ownerrpa = rpa; } } catch (Exception ex) { Log.Error(ex.ToString()); created = DateTime.Now; return; } } if (ownerrpa != null) { //if(client.autorestart != TimeSpan.Zero && (DateTime.Now - lastheartbeat) > client.autorestart ) //{ // try // { // lastheartbeat = DateTime.Now; // ownerrpa.Kill(); // } // catch (Exception ex) // { // Log.Error(ex.ToString()); // } //} return; } if (string.IsNullOrEmpty(client.openrpapath)) { return; } if (!System.IO.File.Exists(client.openrpapath)) { return; } var path = System.IO.Path.GetDirectoryName(client.openrpapath); //if (!Program.isService) //{ // Log.Information("Not running as service, so just launching openrpa here"); // Log.Information(client.openrpapath); // created = DateTime.Now; // Process.Start(new ProcessStartInfo(client.openrpapath) { WorkingDirectory = path }); // return; //} Log.Information("Attaching to user explorer and launching robot in session"); Log.Information(client.openrpapath); created = DateTime.Now; // IntPtr hSessionToken = IntPtr.Zero; // SessionFinder sf = new SessionFinder(); // hSessionToken = sf.GetLocalInteractiveSession(); //var windowsusername = client.windowsusername.Substring(client.windowsusername.IndexOf("\\") + 1); //var windowsdomain = client.windowsusername.Substring(0, client.windowsusername.IndexOf("\\") ); //// hSessionToken = sf.GetSessionByUser(windowsdomain, windowsusername); //Impersonation.ExecuteAppAsLoggedOnUser(client.openrpapath, null, System.IO.Path.GetDirectoryName(client.openrpapath)); //var runner = new InteractiveProcessRunner(client.openrpapath, hSessionToken); //var p = runner.Run(); //if (!NativeMethods.Launch(ownerexplorer, path, @"c:\windows\system32\cmd.exe /C " + "\"" + client.openrpapath + "\"")) if (!NativeMethods.Launch(ownerexplorer, path, client.openrpapath.Replace("/", @"\"))) { Log.Error("Failed launching robot in session"); string errorMessage = new System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error()).Message; Log.Error(errorMessage); } } catch (Exception ex) { Log.Error(ex.ToString()); created = DateTime.Now; } } catch (Exception ex) { Log.Error(ex.ToString()); created = DateTime.Now; } }
public void DoWork() { try { if (System.Diagnostics.Debugger.IsAttached) { skiprdp = true; } if (client == null) { Log.Information("client is null"); return; } if (string.IsNullOrEmpty(client._id)) { // Log.Information("client._id is null, Dummy client, ignore"); return; // Dummy client, ignore } if (connection != null && connection.IsConnected == false) { connection = null; created = DateTime.Now; } // Is OpenRPA connected for this user ? if (connection != null) { connection.PushMessage(new RPAMessage("ping")); // created = DateTime.Now; // return; } if ((DateTime.Now - created).TotalSeconds < 5) { return; } // Is user signed in ? // ownerexplorer = null; //if (ownerexplorer == null) var rdpip = "127.0.0.2"; // if ((ConnectionAttempts % 2) == 1) rdpip = "127.0.0.1"; if (PluginConfig.usefreerdp && !skiprdp) { if (freerdp == null || freerdp.Connected == false) { if (freerdp == null) { Console.WriteLine("rdp is null"); } if (string.IsNullOrEmpty(client.windowspassword)) { return; } lastrdp = DateTime.Now; } if (freerdp == null) { freerdp = new FreeRDP.Core.RDP(); } if (!freerdp.Connected) { var hostname = NativeMethods.GetHostName().ToLower(); try { Log.Information("Tesing connection to " + rdpip + " port 3389"); using (var tcpClient = new System.Net.Sockets.TcpClient()) { var ipAddress = System.Net.IPAddress.Parse(rdpip); var ipEndPoint = new System.Net.IPEndPoint(ipAddress, 3389); tcpClient.Connect(ipEndPoint); } Log.Information("Success"); } catch (Exception ex) { Log.Error(ex.ToString()); return; } var windowsusername = client.windowsusername.Substring(client.windowsusername.IndexOf("\\") + 1); var windowsdomain = client.windowsusername.Substring(0, client.windowsusername.IndexOf("\\")); if (string.IsNullOrEmpty(client.windowslogin)) { if (client.windowsusername.StartsWith(hostname + @"\")) { client.windowslogin = windowsusername; } else { client.windowslogin = client.windowsusername; } } Log.Information("Impersonate " + client.windowslogin); try { using (var imp = new Impersonator(windowsusername, windowsdomain, client.windowspassword)) { ConnectionAttempts++; Log.Information("Connecting RDP connection to " + rdpip + " for " + client.windowslogin); freerdp.Connect(rdpip, "", client.windowslogin, client.windowspassword); //if (client.windowsusername.StartsWith(hostname + @"\")) //{ // // var windowsusername = client.windowsusername.Substring(hostname.Length + 1); // Log.Information("Connecting RDP connection to " + rdpip + " for " + windowsusername); // freerdp.Connect(rdpip, "", windowsusername, client.windowspassword); //} //else //{ // Log.Information("Connecting RDP connection to " + rdpip + " for " + client.windowsusername); // freerdp.Connect(rdpip, "", client.windowsusername, client.windowspassword); //} } } catch (Exception ex) { Log.Error("Login failed, waiting 10 seconds: " + ex.Message); System.Threading.Thread.Sleep(10 * 1000); throw; } created = DateTime.Now; return; } if (freerdp == null || freerdp.Connected == false) { return; } } else if (!skiprdp) { if (rdp == null || rdp.Connected == false) { if (rdp == null) { Console.WriteLine("rdp is null"); } if (string.IsNullOrEmpty(client.windowspassword)) { return; } lastrdp = DateTime.Now; } if (rdp == null) { rdp = new Client(); } if (rdp.Connecting) { return; } if (!rdp.Connected) { try { Log.Information("Tesing connection to " + rdpip + " port 3389"); using (var tcpClient = new System.Net.Sockets.TcpClient()) { var ipAddress = System.Net.IPAddress.Parse(rdpip); var ipEndPoint = new System.Net.IPEndPoint(ipAddress, 3389); tcpClient.Connect(ipEndPoint); } Log.Information("Success"); } catch (Exception ex) { Log.Error(ex.ToString()); return; } Log.Information("Increment ConnectionAttempts"); ConnectionAttempts++; Log.Information("Get HostName"); var hostname = NativeMethods.GetHostName().ToLower(); Log.Information("hostname is: " + hostname); Log.Information("Connecting RDP connection to " + rdpip + " for " + client.windowslogin); // Task.Run(()=>rdp.CreateRdpConnectionasync(rdpip, "", client.windowsusername.Substring(hostname.Length + 1), client.windowspassword)); if (string.IsNullOrEmpty(client.windowslogin)) { if (client.windowsusername.StartsWith(hostname + @"\")) { var windowsusername = client.windowsusername.Substring(hostname.Length + 1); client.windowslogin = windowsusername; } else { client.windowslogin = client.windowsusername; } } rdp.CreateRdpConnectionasync(rdpip, "", client.windowslogin, client.windowspassword); Log.Information("Connection initialized"); //if (client.windowsusername.StartsWith(hostname + @"\")) //{ // var windowsusername = client.windowsusername.Substring(hostname.Length + 1); // Log.Information("Connecting RDP connection to " + rdpip + " for " + windowsusername); // // Task.Run(()=>rdp.CreateRdpConnectionasync(rdpip, "", client.windowsusername.Substring(hostname.Length + 1), client.windowspassword)); // rdp.CreateRdpConnectionasync(rdpip, "", client.windowsusername.Substring(hostname.Length + 1), client.windowspassword); // Log.Information("Connection initialized"); //} //else //{ // Log.Information("Connecting RDP connection to " + rdpip + " for " + client.windowsusername); // // Task.Run(() => rdp.CreateRdpConnectionasync(rdpip, "", client.windowsusername, client.windowspassword)); // rdp.CreateRdpConnectionasync(rdpip, "", client.windowsusername, client.windowspassword); // Log.Information("Connection initialized"); //} created = DateTime.Now; } if (rdp == null || rdp.Connected == false) { return; } } NativeMethods.EnableDisablePrivilege(NativeMethods.GetSecurityEntityValue(NativeMethods.SecurityEntity.SE_ASSIGNPRIMARYTOKEN_NAME), true); NativeMethods.EnableDisablePrivilege(NativeMethods.GetSecurityEntityValue(NativeMethods.SecurityEntity.SE_BACKUP_NAME), true); NativeMethods.EnableDisablePrivilege(NativeMethods.GetSecurityEntityValue(NativeMethods.SecurityEntity.SE_DEBUG_NAME), true); NativeMethods.EnableDisablePrivilege(NativeMethods.GetSecurityEntityValue(NativeMethods.SecurityEntity.SE_LOAD_DRIVER_NAME), true); NativeMethods.EnableDisablePrivilege(NativeMethods.GetSecurityEntityValue(NativeMethods.SecurityEntity.SE_TCB_NAME), true); try { var procs = Process.GetProcessesByName("explorer"); System.Diagnostics.Process ownerexplorer = null; foreach (var explorer in procs) { try { var owner = NativeMethods.GetProcessUserName(explorer.Id).ToLower(); if (owner == client.windowsusername) { ownerexplorer = explorer; } } catch (Exception ex) { Log.Error(ex.ToString()); created = DateTime.Now; return; } } if (ownerexplorer == null) { return; } System.Diagnostics.Process ownerrpa = null; procs = Process.GetProcessesByName("openrpa"); foreach (var rpa in procs) { try { var owner = NativeMethods.GetProcessUserName(rpa.Id).ToLower(); if (owner == client.windowsusername) { ownerrpa = rpa; } } catch (Exception ex) { Log.Error(ex.ToString()); created = DateTime.Now; return; } } if (ownerrpa != null) { //if(client.autorestart != TimeSpan.Zero && (DateTime.Now - lastheartbeat) > client.autorestart ) //{ // try // { // lastheartbeat = DateTime.Now; // ownerrpa.Kill(); // } // catch (Exception ex) // { // Log.Error(ex.ToString()); // } //} return; } if (string.IsNullOrEmpty(client.openrpapath)) { return; } if (!System.IO.File.Exists(client.openrpapath)) { return; } var path = System.IO.Path.GetDirectoryName(client.openrpapath); //if (!Program.isService) //{ // Log.Information("Not running as service, so just launching openrpa here"); // Log.Information(client.openrpapath); // created = DateTime.Now; // Process.Start(new ProcessStartInfo(client.openrpapath) { WorkingDirectory = path }); // return; //} // IntPtr hSessionToken = IntPtr.Zero; // SessionFinder sf = new SessionFinder(); // hSessionToken = sf.GetLocalInteractiveSession(); //var windowsusername = client.windowsusername.Substring(client.windowsusername.IndexOf("\\") + 1); //var windowsdomain = client.windowsusername.Substring(0, client.windowsusername.IndexOf("\\") ); //// hSessionToken = sf.GetSessionByUser(windowsdomain, windowsusername); //Impersonation.ExecuteAppAsLoggedOnUser(client.openrpapath, null, System.IO.Path.GetDirectoryName(client.openrpapath)); //var runner = new InteractiveProcessRunner(client.openrpapath, hSessionToken); //var p = runner.Run(); //if (!NativeMethods.Launch(ownerexplorer, path, @"c:\windows\system32\cmd.exe /C " + "\"" + client.openrpapath + "\"")) //var me = System.Security.Principal.WindowsIdentity.GetCurrent(); ////var mep = new System.Security.Principal.WindowsPrincipal(me); //var acct = new System.Security.Principal.NTAccount(me.Name); //var rule = new ProcessAccessRule(acct, ProcessAccessRights.PROCESS_ALL_ACCESS, false, System.Security.AccessControl.InheritanceFlags.None, System.Security.AccessControl.PropagationFlags.None, System.Security.AccessControl.AccessControlType.Allow); //SafeTokenHandle handle = new SafeTokenHandle(ownerexplorer.Handle); ////var perm = new OpenRPA.Interfaces.ProcessSecurity(handle); //var perm = new OpenRPA.Interfaces.ProcessSecurity(handle); //perm.AddAccessRule(rule); //try //{ // perm.SaveChanges(handle); //} //catch (Exception ex) //{ // Log.Error(new Exception("Failed setting DACL on explore proccess: " + ex.Message, ex).ToString()); // created = DateTime.Now; // return; //} if (Program.isService) { Log.Information("Attaching to user explorer and launching robot in session"); Log.Information(client.openrpapath); created = DateTime.Now; hasShownLaunchWarning = false; if (!NativeMethods.Launch(ownerexplorer, path, client.openrpapath.Replace("/", @"\"))) { Log.Error("Failed launching robot in session"); string errorMessage = new System.ComponentModel.Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error()).Message; Log.Error(errorMessage); } } else if (!hasShownLaunchWarning) { Log.Warning("Not running as Local System, so cannot spawn processes in other users desktops"); created = DateTime.Now; hasShownLaunchWarning = true; } } catch (Exception ex) { Log.Error(ex.ToString()); created = DateTime.Now; } } catch (Exception ex) { Log.Error(ex.ToString()); created = DateTime.Now; } }
public void DoWork() { if (client == null) { return; } if (string.IsNullOrEmpty(client._id)) { return; // Dummy client, ignore } if (connection != null && connection.IsConnected == false) { connection = null; created = DateTime.Now; } // Is OpenRPA connected for this user ? if (connection != null) { connection.PushMessage(new RPAMessage("ping")); created = DateTime.Now; return; } if ((DateTime.Now - created).TotalSeconds < 5) { return; } // Is user signed in ? // ownerexplorer = null; //if (ownerexplorer == null) if (rdp == null || rdp.Connected == false) { if (rdp == null) { Console.WriteLine("rdp is null"); } else { //Console.WriteLine("rdp.Connected: " + rdp.Connected + " rdp.Connecting: " + rdp.Connecting); //if (rdp.Connecting) return; } // if((DateTime.Now - lastrdp) < client.autorestart) return; if (string.IsNullOrEmpty(client.windowspassword)) { return; } lastrdp = DateTime.Now; if (rdp != null) { //if (rdp.Connected) //{ // Log.Information("Disconnecting RDP connection for " + client.windowsusername); // rdp.Disconnect(); // rdp.Dispose(); // rdp = null; //} } //if (rdpClient!=null) //{ // if(rdpClient.isConnected) // { // Log.Information("Disconnecting RDP connection for " + client.windowsusername) ; // rdpClient.Disconnect(); // rdpClient.Dispose(); // rdpClient = null; // } //} // https://social.msdn.microsoft.com/Forums/vstudio/en-US/2daeecb3-778b-478e-b379-102b790777c2/c-remote-desktop-over-the-same-computer?forum=csharpgeneral // https://github.com/terminals-Origin/Terminals // https://www.codeproject.com/Articles/43705/Remote-Desktop-using-C-NET // https://www.codeproject.com/Articles/16374/How-to-Write-a-Terminal-Services-Add-in-in-Pure-C // https://stackoverflow.com/questions/52801093/create-windows-session-programmatically-from-console-or-windows-service try { // https://stackoverflow.com/questions/46807645/passing-a-struct-pointer-in-c-sharp-interop-results-in-null //var thread = new System.Threading.Thread(() => //{ // Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => // { // if(rdp==null) rdp = new Client(); // //if(NativeMethods.GetProcessUserName) // var hostname = NativeMethods.GetHostName().ToLower(); // if (client.windowsusername.StartsWith(hostname + @"\")) // { // Log.Information("Connecting RDP connection for " + client.windowsusername.Substring(hostname.Length + 1)); // rdp.CreateRdpConnectionasync("127.0.0.2", "", client.windowsusername.Substring(hostname.Length + 1), client.windowspassword); // } // else // { // Log.Information("Connecting RDP connection for " + client.windowsusername); // rdp.CreateRdpConnectionasync("127.0.0.2", "", client.windowsusername, client.windowspassword); // } // created = DateTime.Now; // })); // Dispatcher.Run(); //}); //thread.SetApartmentState(System.Threading.ApartmentState.STA); //thread.Start(); //thread.Join(); //var thread = new System.Threading.Thread(() => //{ // Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => // { // //rdpClient = new RdpClient(); // //rdpClient.Connect("127.0.0.2", "", client.windowsusername, client.windowspassword); // rdp = new FreeRDP.Core.RDP(); // rdp.Connect("127.0.0.2", "", client.windowsusername, client.windowspassword); // })); // Dispatcher.Run(); //}); //thread.SetApartmentState(System.Threading.ApartmentState.STA); //thread.Start(); //thread.Join(); if (rdp == null) { rdp = new FreeRDP.Core.RDP(); } //if(NativeMethods.GetProcessUserName) var hostname = NativeMethods.GetHostName().ToLower(); if (client.windowsusername.StartsWith(hostname + @"\")) { var windowsusername = client.windowsusername.Substring(hostname.Length + 1); Log.Information("Connecting RDP connection for " + windowsusername); // rdp.CreateRdpConnectionasync("127.0.0.2", "", client.windowsusername.Substring(hostname.Length + 1), client.windowspassword); rdp.Connect("127.0.0.2", "", windowsusername, client.windowspassword); } else { Log.Information("Connecting RDP connection for " + client.windowsusername); // rdp.CreateRdpConnectionasync("127.0.0.2", "", client.windowsusername, client.windowspassword); rdp.Connect("127.0.0.2", "", client.windowsusername, client.windowspassword); } created = DateTime.Now; } catch (Exception ex) { Log.Error(ex.ToString()); } return; } if (rdp == null) { Console.WriteLine("rdp is null"); } else { // Console.WriteLine("rdp.Connected: " + rdp.Connected + " rdp.Connecting: " + rdp.Connecting); Console.WriteLine("rdp.Connected: " + rdp.Connected); } if (rdp == null || rdp.Connected == false) { return; } try { var procs = Process.GetProcessesByName("explorer"); System.Diagnostics.Process ownerexplorer = null; foreach (var explorer in procs) { try { var owner = NativeMethods.GetProcessUserName(explorer).ToLower(); if (owner == client.windowsusername) { ownerexplorer = explorer; } } catch (Exception ex) { Log.Error(ex.ToString()); created = DateTime.Now; return; } } if (ownerexplorer == null) { return; } System.Diagnostics.Process ownerrpa = null; procs = Process.GetProcessesByName("openrpa"); foreach (var rpa in procs) { try { var owner = NativeMethods.GetProcessUserName(rpa).ToLower(); if (owner == client.windowsusername) { ownerrpa = rpa; } } catch (Exception ex) { Log.Error(ex.ToString()); created = DateTime.Now; return; } } if (ownerrpa != null) { //if(client.autorestart != TimeSpan.Zero && (DateTime.Now - lastheartbeat) > client.autorestart ) //{ // try // { // lastheartbeat = DateTime.Now; // ownerrpa.Kill(); // } // catch (Exception ex) // { // Log.Error(ex.ToString()); // } //} return; } if (string.IsNullOrEmpty(client.openrpapath)) { return; } if (!System.IO.File.Exists(client.openrpapath)) { return; } var path = System.IO.Path.GetDirectoryName(client.openrpapath); if (!Program.isService) { Log.Information("Not running as service, so just launching openrpa here"); Log.Information(client.openrpapath); created = DateTime.Now; Process.Start(new ProcessStartInfo(client.openrpapath) { WorkingDirectory = path }); return; } Log.Information("Attaching to user explorer and launching robot in session"); Log.Information(client.openrpapath); created = DateTime.Now; if (!NativeMethods.Launch(ownerexplorer, path, @"c:\windows\system32\cmd.exe /C " + "\"" + client.openrpapath + "\"")) { Log.Error("Failed launching robot in session"); } } catch (Exception ex) { Log.Error(ex.ToString()); created = DateTime.Now; } }