首页 > 其他分享 >csharp 远程桌面登录 mstsc rdp文件

csharp 远程桌面登录 mstsc rdp文件

时间:2024-01-31 18:45:19浏览次数:30  
标签:info IntPtr CRYPTPROTECT mstsc static 远程桌面 public string rdp

RemoteDesktopConnection\src\LogInfo.cs

namespace RDP
{
    class LogInfo
    {
        public string Ipaddress { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
    }
}

RemoteDesktopConnection\src\Program.cs

#define debug
using System;
using System.Text.RegularExpressions;

namespace RDP
{
    class Program
    {
        static void Main(string[] args)
        {

            var info = new LogInfo();
        #if debug
            Console.WriteLine("please enter ipAddress");
            while (true)
            {
                info.Ipaddress = Console.ReadLine();
                if (new Regex(RdpConstant.IpaddressPatten).IsMatch(info.Ipaddress))
                {
                    break;
                }
            }
            Console.WriteLine("please enter username");
            info.Username = Console.ReadLine();
            Console.WriteLine(info.Username);
            Console.WriteLine("please enter password");
            info.Password = Console.ReadLine();
         #else
            info.Ipaddress = "120";
            info.Username = "Adm";
            info.Password = "wu";
        #endif
            RdpHandler.Rrocess(info);
        }
    }
}



RemoteDesktopConnection\src\RdpConstant.cs

namespace RDP
{
    class RdpConstant
    {
        public static readonly string IpaddressPatten= @"^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$";
        public static readonly string FilePath = "rdp.rdp";
        public static readonly string templatePath="../../encryption/TemplateRDP.txt";
    }
}

RemoteDesktopConnection\src\encryption\DataProtection.cs

using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Security;

namespace RDP
{
    [Serializable()]
    public sealed class DataProtection
    {
        [Flags()]
        public enum CryptProtectPromptFlags
        {
            CRYPTPROTECT_PROMPT_ON_UNPROTECT = 0x01,
            CRYPTPROTECT_PROMPT_ON_PROTECT = 0x02,
            CRYPTPROTECT_PROMPT_RESERVED = 0x04,
            CRYPTPROTECT_PROMPT_STRONG = 0x08,
            CRYPTPROTECT_PROMPT_REQUIRE_STRONG = 0x10
        }

        [Flags()]
        public enum CryptProtectDataFlags
        {
            CRYPTPROTECT_UI_FORBIDDEN = 0x01,
            CRYPTPROTECT_LOCAL_MACHINE = 0x04,
            CRYPTPROTECT_CRED_SYNC = 0x08,
            CRYPTPROTECT_AUDIT = 0x10,
            CRYPTPROTECT_NO_RECOVERY = 0x20,
            CRYPTPROTECT_VERIFY_PROTECTION = 0x40,
            CRYPTPROTECT_CRED_REGENERATE = 0x80
        }

        public static string ProtectData(string data, string name)
        {
            return ProtectData(data, name,
                CryptProtectDataFlags.CRYPTPROTECT_UI_FORBIDDEN | CryptProtectDataFlags.CRYPTPROTECT_LOCAL_MACHINE);
        }

        public static byte[] ProtectData(byte[] data, string name)
        {
            return ProtectData(data, name,
                CryptProtectDataFlags.CRYPTPROTECT_UI_FORBIDDEN | CryptProtectDataFlags.CRYPTPROTECT_LOCAL_MACHINE);
        }

        public static string ProtectData(string data, string name, CryptProtectDataFlags flags)
        {
            byte[] dataIn = Encoding.Unicode.GetBytes(data);
            byte[] dataOut = ProtectData(dataIn, name, flags);

            if (dataOut != null)
                return (Convert.ToBase64String(dataOut));
            else
                return null;
        }


        private static byte[] ProtectData(byte[] data, string name, CryptProtectDataFlags dwFlags)
        {
            byte[] cipherText = null;

            // copy data into unmanaged memory
            DPAPI.DATA_BLOB din = new DPAPI.DATA_BLOB();
            din.cbData = data.Length;

            din.pbData = Marshal.AllocHGlobal(din.cbData);

            if (din.pbData.Equals(IntPtr.Zero))
                throw new OutOfMemoryException("Unable to allocate memory for buffer.");

            Marshal.Copy(data, 0, din.pbData, din.cbData);

            DPAPI.DATA_BLOB dout = new DPAPI.DATA_BLOB();

            try
            {
                bool cryptoRetval = DPAPI.CryptProtectData(ref din, name, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, dwFlags, ref dout);

                if (cryptoRetval) 
                {
                    int startIndex = 0;
                    cipherText = new byte[dout.cbData];
                    Marshal.Copy(dout.pbData, cipherText, startIndex, dout.cbData);
                    DPAPI.LocalFree(dout.pbData);
                }
                else
                {
                    int errCode = Marshal.GetLastWin32Error();
                    StringBuilder buffer = new StringBuilder(256);
                    Win32Error.FormatMessage(Win32Error.FormatMessageFlags.FORMAT_MESSAGE_FROM_SYSTEM, IntPtr.Zero, errCode, 0, buffer, buffer.Capacity, IntPtr.Zero);
                }
            }
            finally
            {
                if (!din.pbData.Equals(IntPtr.Zero))
                    Marshal.FreeHGlobal(din.pbData);
            }

            return cipherText;
        }

        internal static void InitPromptstruct(ref DPAPI.CRYPTPROTECT_PROMPTSTRUCT ps)
        {
            ps.cbSize = Marshal.SizeOf(typeof(DPAPI.CRYPTPROTECT_PROMPTSTRUCT));
            ps.dwPromptFlags = 0;
            ps.hwndApp = IntPtr.Zero;
            ps.szPrompt = null;
        }
    }

    [SuppressUnmanagedCodeSecurityAttribute()]
    internal class DPAPI
    {
        [DllImport("crypt32")]
        public static extern bool CryptProtectData(ref DATA_BLOB dataIn, string szDataDescr, IntPtr optionalEntropy, IntPtr pvReserved,
            IntPtr pPromptStruct, DataProtection.CryptProtectDataFlags dwFlags, ref DATA_BLOB pDataOut);

        [DllImport("crypt32")]
        public static extern bool CryptUnprotectData(ref DATA_BLOB dataIn, StringBuilder ppszDataDescr, IntPtr optionalEntropy,
            IntPtr pvReserved, IntPtr pPromptStruct, DataProtection.CryptProtectDataFlags dwFlags, ref DATA_BLOB pDataOut);

        [DllImport("Kernel32.dll")]
        public static extern IntPtr LocalFree(IntPtr hMem);

        [StructLayout(LayoutKind.Sequential)]
        public struct DATA_BLOB
        {
            public int cbData;
            public IntPtr pbData;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct CRYPTPROTECT_PROMPTSTRUCT
        {
            public int cbSize; // = Marshal.SizeOf(typeof(CRYPTPROTECT_PROMPTSTRUCT))
            public int dwPromptFlags; // = 0
            public IntPtr hwndApp; // = IntPtr.Zero
            public string szPrompt; // = null
        }
    }

    internal class Win32Error
    {
        [Flags()]
        public enum FormatMessageFlags : int
        {
            FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x0100,
            FORMAT_MESSAGE_IGNORE_INSERTS = 0x0200,
            FORMAT_MESSAGE_FROM_STRING = 0x0400,
            FORMAT_MESSAGE_FROM_HMODULE = 0x0800,
            FORMAT_MESSAGE_FROM_SYSTEM = 0x1000,
            FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x2000,
            FORMAT_MESSAGE_MAX_WIDTH_MASK = 0xFF,
        }

        [DllImport("Kernel32.dll")]
        public static extern int FormatMessage(FormatMessageFlags flags, IntPtr source, int messageId, int languageId,
            StringBuilder buffer, int size, IntPtr arguments);
    }
}

RemoteDesktopConnection\src\encryption\Rdp.cs

using System;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace RDP
{
    class RdpHandler
    {
        public static void Rrocess(LogInfo info) {
            if (string.IsNullOrEmpty(info.Username) || string.IsNullOrEmpty(info.Password)) {
                throw new ArgumentNullException("username and password can't be empty");
            }
            var pwstr = BitConverter.ToString(DataProtection.ProtectData(Encoding.Unicode.GetBytes(info.Password), "")).Replace("-", "");
            var rdpInfo = String.Format(File.ReadAllText(RdpConstant.templatePath), info.Ipaddress, info.Username, pwstr);
            File.WriteAllText(RdpConstant.FilePath,rdpInfo);
            _mstsc("mstsc " + RdpConstant.FilePath);
        }

        private static void _mstsc(String cmd)
        {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.CreateNoWindow = true;
            p.Start();
            p.StandardInput.WriteLine(cmd);
        }
    }
}

RemoteDesktopConnection\src\encryption\TemplateRDP.txt

screen mode id:i:2
use multimon:i:0
desktopwidth:i:1600
desktopheight:i:900
session bpp:i:32
winposstr:s:0,3,0,0,800,600
compression:i:1
keyboardhook:i:2
audiocapturemode:i:0
videoplaybackmode:i:1
connection type:i:2
networkautodetect:i:1
bandwidthautodetect:i:1
displayconnectionbar:i:1
enableworkspacereconnect:i:0
disable wallpaper:i:1
allow font smoothing:i:0
allow desktop composition:i:0
disable full window drag:i:1
disable menu anims:i:1
disable themes:i:0
disable cursor setting:i:0
bitmapcachepersistenable:i:1
audiomode:i:1
redirectprinters:i:1
redirectcomports:i:0
redirectsmartcards:i:1
redirectclipboard:i:1
redirectposdevices:i:0
autoreconnection enabled:i:1
authentication level:i:2
prompt for credentials:i:0
negotiate security layer:i:1
remoteapplicationmode:i:0
alternate shell:s:
shell working directory:s:
gatewayhostname:s:
gatewayusagemethod:i:4
gatewaycredentialssource:i:4
gatewayprofileusagemethod:i:0
promptcredentialonce:i:0
use redirection server name:i:0
rdgiskdcproxy:i:0
kdcproxyname:s:
drivestoredirect:s:
redirectdirectx:i:1
full address:s:{0}
username:s:{1}
password 51:b:{2}

标签:info,IntPtr,CRYPTPROTECT,mstsc,static,远程桌面,public,string,rdp
From: https://www.cnblogs.com/zhuoss/p/17999904

相关文章

  • AnyDesk远程桌面创建快捷方式
    前言全局说明AnyDesk远程桌面创建快捷方式一、创建桌面快捷方式之前连接过的远程桌面,会在"最近会话"中显示,右键-置于桌面,就能在桌面获取一个,快速打开对应远程桌面的快捷方式,访问很方便右键-属性,可以修改参数,连接不同机器手动创建lnk文件:https://www.cnblogs.com/wutou......
  • 通过docker构建基于LNMP的WordPress项目
    docker构建基于LNMP先创建nginx的镜像 #在opt下创建dockerfile文件夹 #在docekrfile文件下创建三个文件夹。分别配置mysql,nginx,php         #编写nginx应用镜像dockerfile文件FROMcentos:7#基于centos7镜像MAINTAINERthisisnginxofLN......
  • 开发WordPress主题和插件,如果调试。
    来源:https://www.shanhubei.com/archives/11789.html开发WordPress主题和插件,如果调试。一、使用自带,设置一下:wp-config.php文件中添加一行代码以打开调试模式define('WP_DEBUG',true);//启用调试日志记录到/wp-content/debug.log文件define('WP_DEBUG_LOG',true......
  • Windows远程桌面不能共享剪贴板-Todesk&向日葵&TW等都可以解决
    大家常会遇到mstsc远程桌面的时候,本地和远程之间不能够复制和粘贴文本内容,大家可能会很疑惑,我远程的时候明明在“本地资源”里面勾选了“剪贴板”,但为什么还不能用,原因就是因为“rdpclip.exe”这个进程没有正常工作。解决办法:在服务器上打开任务管理器(Ctrl+Alt+Del),查看......
  • k8s之构建Mysql和Wordpress集群
    一、实验目的基于Kubernetes集群实现多负载的WordPress应用。将WordPress数据存储在后端Mysql,Mysql实现主从复制读写分离功能。1、准备Kubernetes集群环境root@k8s-master01:~#kubectlgetnodesNAMESTATUSROLESAGEVERSIONk8s-master01Re......
  • 微软账号密码修改后提示密码错误的解决方法(远程桌面&smb共享访问等)
    众所周知,自从微软将Microsoft账户与Windows账号强制绑定后,使用起来便一直有诸多困难,在MicrosoftSupport和搜索引擎长期搜索解决方案未果,今天偶然在一个佬的博客翻到了这个问题的解决方案,发现确实有效,原因就是网络部分密码更改后,并没有自动向本地系统内各组件同步更新密码,所以在以......
  • 远程桌面连接出现了内部错误怎么解决?
    远程桌面连接是一种非常方便的工具,可以让用户从远程访问其他计算机的桌面界面。但是,有时候在连接远程桌面时会出现内部错误,导致无法连接或者连接后无法正常使用。小德将分析远程桌面连接出现内部错误的原因和解决方法。1.确认网络连接在使用远程桌面连接之前,首先需要确保计算机之......
  • SiteGround如何设置WordPress网站自动更新
    SiteGroundAutoupdate功能会自动帮我们更新在他们这里托管的所有WordPress网站,这样做是为了保证网站安全,并且让它们一直保持最新状态。他们会根据我们选择的设置自动更新不同版本的WordPress,包括主要版本和次要版本。在每次自动更新之前,他们都会为我们的网站做一个完整的备份,这样......
  • 使用 WordPress搭建个人博客
    安装LNMP下载LNMP:wgethttp://soft.vpser.net/lnmp/lnmp2.0.tar.gz-cOlnmp2.0.tar.gz解压并执行:tarzxflnmp2.0.tar.gz&&cdlnmp1.5&&./install.shlnmp选择想要安装的版本然后回车开始安装时间比较长,耐心等待一下,看到以下显示表示安装成功配置nigix查看nginx配置文......
  • nginx反向代理SSH和远程桌面连接
       今天在实施一个项目过程中,防火墙厂家已经配置SSH和远程桌面连接的映射关系,为了网络更安全将采取在系统centos7.9安装nginx反向代理SSH和远程桌面连接的办法,现将实现过程记录如下:一、安装nginx(省略)二、查看./nginx-V[root@node1nginx]#cd/usr/local/nginx/[root@node......