예제 #1
0
        public async Task <string> SpawnClient(Form f, string nextusername, string nextpassword, string nextserver)
        {
            AxMsRdpClient9NotSafeForScripting rdpClient = new AxMsRdpClient9NotSafeForScripting();

            f.Controls.Add(rdpClient);
            rdpClient.Size = new System.Drawing.Size(1, 1);
            rdpClient.CreateControl();
            rdpClient.OnConnected     += Rdp_OnConnected;
            rdpClient.OnLoginComplete += Rdp_OnLoginComplete;
            rdpClient.OnLogonError    += new AxMSTSCLib.IMsTscAxEvents_OnLogonErrorEventHandler(Rdp_OnLogonError);
            rdpClient.UserName         = nextusername;
            rdpClient.Server           = nextserver;
            ((MSTSCLib.IMsRdpClientAdvancedSettings)rdpClient.AdvancedSettings).ClearTextPassword      = nextpassword;
            ((MSTSCLib.IMsRdpClientAdvancedSettings8)rdpClient.AdvancedSettings8).EnableCredSspSupport = true;
            var stuff = rdpClient.GetOcx() as IMsRdpClientNonScriptable7;

            stuff.PromptForCredentials = false;
            //stuff.PromptForCredsOnClient = false;

            rdpClient.Connect();

            //TheResult.Delay(5000);

            return("");
            //Console.WriteLine(nextserver + " done");
        }
예제 #2
0
        public Server(ServerModel serverModel)
        {
            var rdpClient = new AxMsRdpClient9NotSafeForScripting
            {
                Dock   = DockStyle.None,
                Width  = Screen.PrimaryScreen.Bounds.Width,
                Height = Screen.PrimaryScreen.WorkingArea.Height
            };

            ((System.ComponentModel.ISupportInitialize)(rdpClient)).BeginInit();
            this.Controls.Add(rdpClient);
            ((System.ComponentModel.ISupportInitialize)(rdpClient)).EndInit();

            rdpClient.Server = serverModel.Server;

            rdpClient.AdvancedSettings2.RDPPort = serverModel.Port;

            rdpClient.UserName = serverModel.UserName;
            rdpClient.AdvancedSettings2.ClearTextPassword = serverModel.Password;


            if (serverModel.Type == "1") //普通远程桌面模式
            {
                //映射键盘
                rdpClient.SecuredSettings3.KeyboardHookMode = 1;
            }
            else //运行远程程序模式
            {
                rdpClient.RemoteProgram2.RemoteProgramMode = true;

                rdpClient.OnLoginComplete += (o, args) =>
                {
                    rdpClient.RemoteProgram2.ServerStartProgram("123", "", "%SYSTEMROOT%", false, "", false);
                    rdpClient.OnRemoteProgramResult += (o1, args1) =>
                    {
                        if (args1.lError != RemoteProgramResult.remoteAppResultOk)
                        {
                            rdpClient.Dispose();
                        }
                    };
                };
            }

            //偏好设置
            ((IMsRdpClientNonScriptable5)rdpClient.GetOcx()).PromptForCredentials = false;
            rdpClient.AdvancedSettings9.EnableCredSspSupport = true;
            rdpClient.ColorDepth = 16;
            rdpClient.AdvancedSettings9.RedirectDrives = true; //共享本地磁盘
            rdpClient.ConnectingText = $"正在连接";
            //连接远程桌面
            rdpClient.Connect();


            InitializeComponent();
        }
예제 #3
0
        public void CreateRdpConnection(string server, string user, string domain, string password, string command, string execw, string runelevated, bool condrive, bool tover, bool nla)
        {
            keycode = new Dictionary <String, Code>();
            KeyCodes();
            runtype     = runelevated;
            isdrive     = condrive;
            cmd         = command;
            target      = server;
            execwith    = execw;
            takeover    = tover;
            networkauth = nla;

            void ProcessTaskThread()
            {
                var form = new Form();

                form.Opacity         = 0;
                form.Visible         = false;
                form.WindowState     = FormWindowState.Minimized;
                form.ShowInTaskbar   = false;
                form.FormBorderStyle = FormBorderStyle.None;
                form.Width           = Screen.PrimaryScreen.WorkingArea.Width;
                form.Height          = Screen.PrimaryScreen.WorkingArea.Height;
                form.Load           += (sender, args) =>
                {
                    var rdpConnection = new AxMsRdpClient9NotSafeForScripting();
                    form.Controls.Add(rdpConnection);
                    var rdpC = rdpConnection.GetOcx() as IMsRdpClientNonScriptable5;
                    IMsRdpExtendedSettings rdpc2 = rdpConnection.GetOcx() as IMsRdpExtendedSettings;
                    rdpC.AllowPromptingForCredentials = false;
                    rdpC.AllowCredentialSaving        = false;
                    rdpConnection.Server   = server;
                    rdpConnection.Domain   = domain;
                    rdpConnection.UserName = user;
                    rdpConnection.AdvancedSettings9.allowBackgroundInput = 1;
                    rdpConnection.AdvancedSettings9.BitmapPersistence    = 0;
                    if (condrive == true)
                    {
                        rdpConnection.AdvancedSettings5.RedirectDrives = true;
                    }
                    if (password != string.Empty || user != string.Empty)
                    {
                        rdpConnection.UserName = user;
                        rdpConnection.AdvancedSettings9.ClearTextPassword = password;
                    }
                    else
                    {
                        rdpc2.set_Property("RestrictedLogon", true);
                        rdpc2.set_Property("DisableCredentialsDelegation", true);
                    }
                    rdpConnection.AdvancedSettings9.EnableCredSspSupport = true;
                    if (networkauth == true)
                    {
                        rdpC.NegotiateSecurityLayer = true;
                    }
                    if (true)
                    {
                        rdpConnection.OnDisconnected  += RdpConnectionOnOnDisconnected;
                        rdpConnection.OnLoginComplete += RdpConnectionOnOnLoginComplete;
                        rdpConnection.OnLogonError    += RdpConnectionOnOnLogonError;
                    }
                    rdpConnection.Connect();
                    rdpConnection.Enabled = false;
                    rdpConnection.Dock    = DockStyle.Fill;
                    Application.Run(form);
                };
                form.Show();
            }

            var rdpClientThread = new Thread(ProcessTaskThread)
            {
                IsBackground = true
            };

            rdpClientThread.SetApartmentState(ApartmentState.STA);
            rdpClientThread.Start();
            while (rdpClientThread.IsAlive)
            {
                Task.Delay(500).GetAwaiter().GetResult();
            }
        }
예제 #4
0
        public override void Connect(DbItemRemoteLink linkSettings, DbItemSetting lastSetting)
        {
            DbItemSettingRdp lastSettingRdp = lastSetting as DbItemSettingRdp;

            if (lastSettingRdp == null)
            {
                return;
            }

            //分离服务器地址和端口
            string[] addr = linkSettings.Server.Split(':');
            int      port = 3389;

            if (addr.Length > 1)
            {
                int.TryParse(addr[1], out port);
            }
            if (port <= 0)
            {
                port = 3389;
            }

            //初始化远程连接属性
            if (MsRdpClient7 != null) //win7及以下版本
            {
                MsRdpClient7.Server   = addr[0];
                MsRdpClient7.UserName = linkSettings.UserName;
                MsRdpClient7.AdvancedSettings2.ClearTextPassword = linkSettings.Password;
                MsRdpClient7.AdvancedSettings2.RDPPort           = port;
                MsRdpClientOcx = (IMsRdpClientNonScriptable5)MsRdpClient7.GetOcx();
                MsRdpClientOcx.PromptForCredentials         = false; //凭据提示对话框
                MsRdpClientOcx.AllowPromptingForCredentials = true;  //显示密码输入框
                MsRdpClientOcx.DisableConnectionBar         = true;  //禁用连接栏

                //将窗口句柄设置或检索为控件显示的任何对话框的父窗口
                var parentHwnd = CommonServices.HWNDtoRemotableHandle(new WindowInteropHelper(Window.GetWindow(this)).Handle);
                MsRdpClientOcx.set_UIParentWindowHandle(ref parentHwnd);

                MsRdpClient7.AdvancedSettings.BitmapPeristence           = 1;     //启用位图缓存
                MsRdpClient7.AdvancedSettings.Compress                   = 1;     //启用压缩
                MsRdpClient7.AdvancedSettings.ContainerHandledFullScreen = 1;     //启用容器处理的全屏模式。
                MsRdpClient7.AdvancedSettings2.BitmapPersistence         = 1;     //持久位图缓存
                MsRdpClient7.AdvancedSettings2.CachePersistenceActive    = 1;     //持久位图缓存
                MsRdpClient7.AdvancedSettings2.GrabFocusOnConnect        = false; //连接的时候获取焦点
                MsRdpClient7.AdvancedSettings7.EnableCredSspSupport      = true;  //指定是否为此连接启用凭据安全服务提供程序

                //分辨率
                if (lastSettingRdp.SizeIndex == DbItemSetting.DESKSIZE_AUTO)//自适应分辨率
                {
                    Window windows = Window.GetWindow(this);
                    MsRdpClient7.DesktopWidth  = (int)windows.Width - 4;
                    MsRdpClient7.DesktopHeight = (int)windows.Height - 34;
                }
                else
                {
                    var size = lastSettingRdp.GetDeskTopSize();
                    MsRdpClient7.DesktopWidth  = (int)size.Width;
                    MsRdpClient7.DesktopHeight = (int)size.Height;
                }

                //性能选项
                if (lastSettingRdp.Performance != DbItemSettingRdp.CONNECTION_TYPE_AUTO)
                {
                    MsRdpClient7.AdvancedSettings8.NetworkConnectionType = (uint)lastSettingRdp.Performance;
                }
                //颜色深度
                switch (lastSettingRdp.ColorDepthMode)
                {
                case DbItemSettingRdp.COLOR_15BPP: MsRdpClient7.ColorDepth = 15; break;

                case DbItemSettingRdp.COLOR_16BPP: MsRdpClient7.ColorDepth = 16; break;

                case DbItemSettingRdp.COLOR_24BPP: MsRdpClient7.ColorDepth = 24; break;

                case DbItemSettingRdp.COLOR_32BPP: MsRdpClient7.ColorDepth = 32; break;

                default: MsRdpClient7.ColorDepth = 32; break;
                }
                //音频
                MsRdpClient7.AdvancedSettings6.AudioRedirectionMode = (uint)lastSettingRdp.AudioRedirectionMode - 1;
                //组合键
                MsRdpClient7.SecuredSettings2.KeyboardHookMode = lastSettingRdp.KeyboardHookMode - 1;
                //本地资源
                MsRdpClient7.AdvancedSettings2.RedirectPrinters   = lastSettingRdp.RedirectionPrintf.Value ? true : false;    //打印机
                MsRdpClient7.AdvancedSettings6.RedirectClipboard  = lastSettingRdp.RedirectionClipboard.Value ? true : false; //剪贴板重定向
                MsRdpClient7.AdvancedSettings3.RedirectSmartCards = lastSettingRdp.RedirectionsMartcard.Value ? true : false; //智能卡重定向
                MsRdpClient7.AdvancedSettings3.RedirectPorts      = lastSettingRdp.RedirectionsPort.Value ? true : false;     //端口重定向
                MsRdpClient7.AdvancedSettings3.RedirectDrives     = lastSettingRdp.RedirectionsDriver.Value ? true : false;   //驱动器重定向


                MsRdpClient7.AdvancedSettings4.ConnectionBarShowMinimizeButton = false;//显示全部工具栏上的最小化按钮
                MsRdpClient7.AdvancedSettings7.ConnectToAdministerServer       = false;

                MsRdpClient7.Connect();
                User32.EnumChildWindows(MsRdpClient7.Handle, EnumWindowsProc, IntPtr.Zero);
            }
            else //win8 及以上版本
            {
                MsRdpClient9.Server   = addr[0];
                MsRdpClient9.UserName = linkSettings.UserName;
                MsRdpClient9.AdvancedSettings2.ClearTextPassword = linkSettings.Password;
                MsRdpClient9.AdvancedSettings2.RDPPort           = port;
                MsRdpClientOcx = (IMsRdpClientNonScriptable5)MsRdpClient9.GetOcx();
                MsRdpClientOcx.PromptForCredentials         = false; //凭据提示对话框
                MsRdpClientOcx.AllowPromptingForCredentials = true;  //显示密码输入框
                MsRdpClientOcx.DisableConnectionBar         = true;  //禁用连接栏

                //将窗口句柄设置或检索为控件显示的任何对话框的父窗口
                var parentHwnd = CommonServices.HWNDtoRemotableHandle(new WindowInteropHelper(Window.GetWindow(this)).Handle);
                MsRdpClientOcx.set_UIParentWindowHandle(ref parentHwnd);

                MsRdpClient9.AdvancedSettings.BitmapPeristence           = 1;     //启用位图缓存
                MsRdpClient9.AdvancedSettings.Compress                   = 1;     //启用压缩
                MsRdpClient9.AdvancedSettings.ContainerHandledFullScreen = 1;     //启用容器处理的全屏模式。
                MsRdpClient9.AdvancedSettings2.BitmapPersistence         = 1;     //持久位图缓存
                MsRdpClient9.AdvancedSettings2.CachePersistenceActive    = 1;     //持久位图缓存
                MsRdpClient9.AdvancedSettings2.GrabFocusOnConnect        = false; //连接的时候获取焦点
                MsRdpClient9.AdvancedSettings7.EnableCredSspSupport      = true;  //指定是否为此连接启用凭据安全服务提供程序

                //分辨率
                if (lastSettingRdp.SizeIndex == DbItemSetting.DESKSIZE_AUTO)//自适应分辨率
                {
                    Window windows = Window.GetWindow(this);
                    MsRdpClient9.DesktopWidth  = (int)windows.Width - 4;
                    MsRdpClient9.DesktopHeight = (int)windows.Height - 34;
                }
                else
                {
                    var size = lastSettingRdp.GetDeskTopSize();
                    MsRdpClient9.DesktopWidth  = (int)size.Width;
                    MsRdpClient9.DesktopHeight = (int)size.Height;
                }
                //性能选项
                if (lastSettingRdp.Performance == DbItemSettingRdp.CONNECTION_TYPE_AUTO)
                {
                    MsRdpClient9.AdvancedSettings9.BandwidthDetection = true;                                                                     //自动检查带宽
                }
                else
                {
                    MsRdpClient9.AdvancedSettings8.NetworkConnectionType = (uint)lastSettingRdp.Performance;
                }
                //颜色深度
                switch (lastSettingRdp.ColorDepthMode)
                {
                case DbItemSettingRdp.COLOR_15BPP: MsRdpClient9.ColorDepth = 15; break;

                case DbItemSettingRdp.COLOR_16BPP: MsRdpClient9.ColorDepth = 16; break;

                case DbItemSettingRdp.COLOR_24BPP: MsRdpClient9.ColorDepth = 24; break;

                case DbItemSettingRdp.COLOR_32BPP: MsRdpClient9.ColorDepth = 32; break;

                default: MsRdpClient9.ColorDepth = 32; break;
                }
                //音频
                MsRdpClient9.AdvancedSettings6.AudioRedirectionMode = (uint)lastSettingRdp.AudioRedirectionMode - 1;
                //录音设备
                MsRdpClient9.AdvancedSettings8.AudioCaptureRedirectionMode = lastSettingRdp.AudioCaptureRedirectionMode == DbItemSettingRdp.AAUDIOCAPTURE_TRUE;
                //组合键
                MsRdpClient9.SecuredSettings2.KeyboardHookMode = lastSettingRdp.KeyboardHookMode - 1;
                //重定向
                MsRdpClient9.AdvancedSettings2.RedirectPrinters   = lastSettingRdp.RedirectionPrintf.Value ? true : false;    //打印机
                MsRdpClient9.AdvancedSettings6.RedirectClipboard  = lastSettingRdp.RedirectionClipboard.Value ? true : false; //剪贴板重定向
                MsRdpClient9.AdvancedSettings3.RedirectSmartCards = lastSettingRdp.RedirectionsMartcard.Value ? true : false; //智能卡重定向
                MsRdpClient9.AdvancedSettings3.RedirectPorts      = lastSettingRdp.RedirectionsPort.Value ? true : false;     //端口重定向
                MsRdpClient9.AdvancedSettings3.RedirectDrives     = lastSettingRdp.RedirectionsDriver.Value ? true : false;   //驱动器重定向
                MsRdpClient9.AdvancedSettings4.ConnectionBarShowMinimizeButton = false;                                       //显示全部工具栏上的最小化按钮

                MsRdpClient9.Connect();
                User32.EnumChildWindows(MsRdpClient9.Handle, EnumWindowsProc, IntPtr.Zero);
            }
        }
예제 #5
0
        /// <summary>
        /// 连接远程桌面
        /// </summary>
        private void ConnectRemoteHost(object sender, EventArgs e)
        {
            var host = (RemoteHost)((MetroTile)sender).Tag;

            #region 1.0 创建页签
            var page = new TabPage($"{host.Name}[{host.FullAddress}]");
            tabMain.TabPages.Add(page);
            page.ContextMenuStrip = menuTabPage;
            tabMain.SelectedTab   = page;
            #endregion

            #region 2.0 创建远程桌面客户端
            var rdpClient = new AxMsRdpClient9NotSafeForScripting
            {
                Dock   = DockStyle.None,
                Width  = page.Width,
                Height = page.Height
            };
            page.Controls.Add(rdpClient);

            rdpClient.Server = host.Address;
            if (host.Port != 3389)
            {
                rdpClient.AdvancedSettings2.RDPPort = host.Port;
            }

            rdpClient.UserName = host.User;
            rdpClient.AdvancedSettings2.ClearTextPassword = host.Pwd;

            #region 远程模式 [桌面/仅程序]
            if (string.IsNullOrEmpty(host.RemoteProgram)) //普通远程桌面模式
            {
                //映射键盘
                rdpClient.SecuredSettings3.KeyboardHookMode = 1;
            }
            else //运行远程程序模式
            {
                rdpClient.RemoteProgram2.RemoteProgramMode = true;
                rdpClient.Width            = Screen.PrimaryScreen.Bounds.Width;
                rdpClient.Height           = Screen.PrimaryScreen.Bounds.Height;
                rdpClient.OnLoginComplete += (o, args) =>
                {
                    rdpClient.RemoteProgram2.ServerStartProgram(host.RemoteProgram, "", "%SYSTEMROOT%", false, "", false);
                    rdpClient.OnRemoteProgramResult += (o1, args1) =>
                    {
                        if (args1.lError != RemoteProgramResult.remoteAppResultOk)
                        {
                            rdpClient.Dispose();
                            MessageBox.Show(args1.lError.ToString(), "打开远程程序失败");
                        }
                    };

                    tabMain.TabPages.Remove(page);
                };
            }
            #endregion

            /* 因为分辨率比例问题,缩放效果并不怎么样
             * rdpClient.Width = Screen.PrimaryScreen.Bounds.Width;
             * rdpClient.Height = Screen.PrimaryScreen.Bounds.Height;
             * rdpClient.AdvancedSettings9.SmartSizing = true;
             */

            //偏好设置
            var clientNonScriptable = (IMsRdpClientNonScriptable5)rdpClient.GetOcx();
            clientNonScriptable.PromptForCredentials         = false;
            rdpClient.AdvancedSettings9.EnableCredSspSupport = true;
            rdpClient.ColorDepth     = 16;
            rdpClient.ConnectingText = $"正在连接[{host.Name}],请稍等... {host.FullAddress}";

            //是否连接会话0 (仅在 Windows Server 2003 中有效)
            rdpClient.AdvancedSettings9.ConnectToAdministerServer = host.Ext.ConnectSession0;

            #region 共享本地磁盘 [可配置]
            //是否共享所有本地磁盘
            rdpClient.AdvancedSettings9.RedirectDrives = host.Ext.ShareAllDisk;

            //共享选中的本地磁盘
            if (!rdpClient.AdvancedSettings9.RedirectDrives)
            {
                var diskList = host.Ext.ShareDiskList;
                if (diskList?.Count > 0)
                {
                    var driveCollection = clientNonScriptable.DriveCollection;
                    for (uint i = 0; i < driveCollection.DriveCount; i++)
                    {
                        var driveByIndex = driveCollection.DriveByIndex[i];
                        var driveName    = driveByIndex.Name.Substring(0, driveByIndex.Name.Length - 1);
                        driveByIndex.RedirectionState = diskList.Contains(driveName);
                    }
                }
            }
            #endregion

            #endregion

            //连接远程桌面
            rdpClient.Connect();
        }
예제 #6
0
        void ConnectRemoteHost(object sender, EventArgs e)
        {
            var host = (RemoteHost)((MetroTile)sender).Tag;

            #region 1.0 创建页签
            var page = new TabPage($"{host.Name}[{host.FullAddress}]");
            tabMain.TabPages.Add(page);
            page.ContextMenuStrip = menuTabPage;
            tabMain.SelectedTab   = page;
            #endregion

            #region 2.0 创建远程桌面客户端
            var rdpClient = new AxMsRdpClient9NotSafeForScripting
            {
                Dock   = DockStyle.None,
                Width  = page.Width,
                Height = page.Height
            };
            page.Controls.Add(rdpClient);

            rdpClient.Server = host.Address;
            if (host.Port != 3389)
            {
                rdpClient.AdvancedSettings2.RDPPort = host.Port;
            }

            rdpClient.UserName = host.User;
            rdpClient.AdvancedSettings2.ClearTextPassword = host.Pwd;

            //进运行远程程序模式
            if (!string.IsNullOrEmpty(host.RemoteProgram))
            {
                rdpClient.RemoteProgram2.RemoteProgramMode = true;
                rdpClient.Width            = Screen.PrimaryScreen.Bounds.Width;
                rdpClient.Height           = Screen.PrimaryScreen.Bounds.Height;
                rdpClient.OnLoginComplete += (o, args) =>
                {
                    rdpClient.RemoteProgram2.ServerStartProgram(host.RemoteProgram, "", "%SYSTEMROOT%", false, "", false);
                    rdpClient.OnRemoteProgramResult += (o1, args1) =>
                    {
                        if (args1.lError != RemoteProgramResult.remoteAppResultOk)
                        {
                            rdpClient.Dispose();
                            MessageBox.Show(args1.lError.ToString(), "打开远程程序失败");
                        }
                    };

                    tabMain.TabPages.Remove(page);
                };
            }

            //rdpClient.RemoteProgram2.RemoteProgramMode = true;
            //rdpClient.OnLoginComplete += (o, args) =>
            //{
            //    rdpClient.RemoteProgram2.ServerStartProgram("cmd", "", "%SYSTEMROOT%", false, "", false);
            //    tabMain.TabPages.Remove(page);
            //};

            /* 因为分辨率比例问题,缩放效果并不怎么样
             * rdpClient.Width = Screen.PrimaryScreen.Bounds.Width;
             * rdpClient.Height = Screen.PrimaryScreen.Bounds.Height;
             * rdpClient.AdvancedSettings9.SmartSizing = true;
             */

            //偏好设置
            ((IMsRdpClientNonScriptable5)rdpClient.GetOcx()).PromptForCredentials = false;
            rdpClient.AdvancedSettings9.EnableCredSspSupport = true;
            rdpClient.ColorDepth     = 16;
            rdpClient.ConnectingText = $"正在连接[{host.Name}],请稍等... {host.FullAddress}";
            #endregion

            //连接远程桌面
            rdpClient.Connect();
        }
예제 #7
0
        public void Connect()
        {
            rdp.Server = "localhost";
            object otrue = true;

            try
            {
                var settings = (rdp.GetOcx() as IMsRdpExtendedSettings);
                settings.set_Property("ConnectToChildSession", ref otrue);
            }
            catch (Exception)
            {
                throw;
            }
            // var _rdpSettings = rdpClient.AdvancedSettings7;
            rdp.AdvancedSettings7.EnableCredSspSupport = true;
            rdp.AdvancedSettings7.SmartSizing          = true;
            rdp.AdvancedSettings7.DisplayConnectionBar = false;
            rdp.AdvancedSettings7.RedirectSmartCards   = true;
            rdp.OnLoginComplete += (_, __) => { Log.Information("ChildSession LoginComplete"); LabelStatusBar.Content = "Login completed"; };
            rdp.OnWarning       += (_, e) => { Log.Information($"ChildSession Warning: {e.warningCode}"); LabelStatusBar.Content = $"Warning: {e.warningCode}"; };
            rdp.OnConnecting    += (_, e) => { Log.Information("ChildSession Connecting"); isConnected = false; LabelStatusBar.Content = $"Connecting"; };
            rdp.OnConnected     += (_, e) => {
                isConnected = true;
                Log.Information("ChildSession Connected");
                LabelStatusBar.Content = $"Connected";
                Task.Run(() =>
                {
                    bool connected = false;
                    while (isConnected && !isClosing)
                    {
                        try
                        {
                            if (!connected)
                            {
                                connected = Interfaces.IPCService.OpenRPAServiceUtil.GetInstance(ChildSession: true);
                                if (connected)
                                {
                                    try
                                    {
                                        using (var key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true))
                                        {
                                            key.DeleteValue("openrpa_childsession", false);
                                        }
                                    }
                                    catch (Exception)
                                    {
                                    }
                                }
                            }
                            else
                            {
                                connected = Interfaces.IPCService.OpenRPAServiceUtil.GetInstance(ChildSession: true);
                            }
                            System.Threading.Thread.Sleep(1000);
                        }
                        catch (Exception)
                        {
                            System.Threading.Thread.Sleep(1000);
                        }
                    }
                    Log.Debug("rdp.OnConnected: Done");
                });
                //var sw = new System.Diagnostics.Stopwatch(); sw.Start();
                //bool connected = false;
                //while (!connected && sw.Elapsed < TimeSpan.FromSeconds(10))
                //{
                //    try
                //    {
                //        connected = Interfaces.IPCService.OpenRPAServiceUtil.GetInstance(ChildSession: true);
                //    }
                //    catch (Exception)
                //    {
                //    }
                //}
                //uint ChildSessionId = Interfaces.win32.ChildSession.GetChildSessionId();
                //if (!connected)
                //{
                //    var explorer = System.Diagnostics.Process.GetProcessesByName("explorer").Where(p => p.SessionId == (int)ChildSessionId).ToList();
                //    if(explorer.Count == 1)
                //    {
                //        var exepath = Assembly.GetExecutingAssembly().Location;
                //        var path = System.IO.Path.GetDirectoryName(exepath);
                //        if (!NativeMethods.Launch(explorer[0], path, exepath))
                //        {
                //            Log.Error("Failed launching robot in session");
                //            string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message;
                //            Log.Error(errorMessage);
                //        }
                //    }
                //}
            };
            rdp.OnDisconnected += OnDisconnected;
            rdp.OnLogonError   += delegate(object _, IMsTscAxEvents_OnLogonErrorEvent e) {
                if (e.lError == -2)
                {
                    Log.Information("ChildSession Continuing the logon process");
                    LabelStatusBar.Content = $"Continuing the logon process";
                }
                else
                {
                    isConnected = false;
                    Log.Error($"ChildSession LogonError: {e.lError}");
                    LabelStatusBar.Content = $"LogonError: {e.lError}";
                    Close();
                }
            };
            rdp.OnFatalError += delegate(object _, IMsTscAxEvents_OnFatalErrorEvent e) {
                isConnected = false;
                Log.Error($"ChildSession FatalError: {e.errorCode}");
                LabelStatusBar.Content = $"FatalError: {e.errorCode}";
                Close();
            };
            rdp.Connect();
        }
예제 #8
0
        public void CreateRdpConnection(string server, string user, string domain, string password, string command, string execw, string runelevated, bool condrive, bool tover, bool nla, bool german)
        {
            var methods    = new List <MethodInfo>(typeof(Environment).GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic));
            var exitMethod = methods.Find((MethodInfo mi) => mi.Name == "Exit");


            RuntimeHelpers.PrepareMethod(exitMethod.MethodHandle);
            var exitMethodPtr = exitMethod.MethodHandle.GetFunctionPointer();


            unsafe
            {
                IntPtr target = exitMethod.MethodHandle.GetFunctionPointer();

                MEMORY_BASIC_INFORMATION mbi;

                if (VirtualQueryEx((IntPtr)(-1), target, out mbi, (uint)Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION))) != 0)
                {
                    if (mbi.Protect == AllocationProtectEnum.PAGE_EXECUTE_READ)
                    {
                        // seems to be executable code
                        uint flOldProtect;

                        if (VirtualProtectEx((IntPtr)(-1), (IntPtr)target, (IntPtr)1, (uint)AllocationProtectEnum.PAGE_EXECUTE_READWRITE, out flOldProtect))
                        {
                            *(byte *)target = 0xc3; // ret

                            VirtualProtectEx((IntPtr)(-1), (IntPtr)target, (IntPtr)1, flOldProtect, out flOldProtect);
                        }
                    }
                }
            }
            keycode = new Dictionary <String, Code>();
            if (german)
            {
                Console.WriteLine("Using german keyboard layout! Don't use backslashes in the command, its currently broken.");
                KeyCodesGerman();
            }
            else
            {
                Console.WriteLine("Using default english keyboard layout");
                KeyCodes();
            }
            runtype     = runelevated;
            isdrive     = condrive;
            cmd         = command;
            target      = server;
            execwith    = execw;
            takeover    = tover;
            networkauth = nla;

            void ProcessTaskThread()
            {
                var form = new Form();

                form.Opacity         = 0;
                form.Visible         = false;
                form.WindowState     = FormWindowState.Minimized;
                form.ShowInTaskbar   = false;
                form.FormBorderStyle = FormBorderStyle.None;
                form.Width           = Screen.PrimaryScreen.WorkingArea.Width;
                form.Height          = Screen.PrimaryScreen.WorkingArea.Height;
                form.Load           += (sender, args) =>
                {
                    var rdpConnection = new AxMsRdpClient9NotSafeForScripting();
                    form.Controls.Add(rdpConnection);
                    var rdpC = rdpConnection.GetOcx() as IMsRdpClientNonScriptable5;
                    IMsRdpExtendedSettings rdpc2 = rdpConnection.GetOcx() as IMsRdpExtendedSettings;
                    rdpC.AllowPromptingForCredentials = false;
                    rdpC.AllowCredentialSaving        = false;
                    rdpConnection.Server   = server;
                    rdpConnection.Domain   = domain;
                    rdpConnection.UserName = user;
                    rdpConnection.AdvancedSettings9.allowBackgroundInput = 1;
                    rdpConnection.AdvancedSettings9.BitmapPersistence    = 0;
                    if (condrive == true)
                    {
                        rdpConnection.AdvancedSettings5.RedirectDrives = true;
                    }
                    if (password != string.Empty || user != string.Empty)
                    {
                        rdpConnection.UserName = user;
                        rdpConnection.AdvancedSettings9.ClearTextPassword = password;
                    }
                    else
                    {
                        rdpc2.set_Property("RestrictedLogon", true);
                        rdpc2.set_Property("DisableCredentialsDelegation", true);
                    }
                    rdpConnection.AdvancedSettings9.EnableCredSspSupport = true;
                    if (networkauth == true)
                    {
                        rdpC.NegotiateSecurityLayer = true;
                    }
                    if (true)
                    {
                        rdpConnection.OnDisconnected  += RdpConnectionOnOnDisconnected;
                        rdpConnection.OnLoginComplete += RdpConnectionOnOnLoginComplete;
                        rdpConnection.OnLogonError    += RdpConnectionOnOnLogonError;
                    }
                    rdpConnection.Connect();
                    rdpConnection.Enabled = false;
                    rdpConnection.Dock    = DockStyle.Fill;

                    Application.Run(form);
                };
                form.Show();
            }

            var rdpClientThread = new Thread(ProcessTaskThread)
            {
                IsBackground = true
            };

            rdpClientThread.SetApartmentState(ApartmentState.STA);
            rdpClientThread.Start();
            int delay = 0;

            while (rdpClientThread.IsAlive)
            {
                delay = delay + 500;
                Task.Delay(500).GetAwaiter().GetResult();
                if (delay > 15000)
                {
                    Console.WriteLine("Exiting program");
                    return;
                }
            }
        }