Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >windows logon API

windows logon API

作者头像
阿新
发布于 2018-04-12 09:57:47
发布于 2018-04-12 09:57:47
9640
举报
文章被收录于专栏:c#开发者c#开发者

using System; using System.Collections.Generic; using System.Text; using System.ComponentModel;

using System.Security; using System.Security.Principal; using System.Runtime; using System.Runtime.InteropServices;

using System.Web; using System.Web.Security;

namespace Impersonate {     [StructLayout(LayoutKind.Sequential,CharSet=CharSet.Auto)] struct _USE_INFO_2 {   internal string ui2_local;   internal string ui2_remote;   internal IntPtr ui2_password; // don't pass a string or StringBuilder here!!   internal uint ui2_status;   internal uint ui2_asg_type;   internal uint ui2_refcount;   internal uint ui2_usecount;   internal string ui2_username;   internal string ui2_domainname; } class WinNet {   [DllImport("netapi32", CharSet=CharSet.Auto, SetLastError=true), SuppressUnmanagedCodeSecurityAttribute]   static extern int NetUseAdd(    string UncServerName, // not used    int Level,  // use info struct level 1 or 2    IntPtr Buf,  // Buffer    ref int ParmError   );   const uint USE_WILDCARD = 0xFFFFFFFF;

  // Establish a use record   public static void UseRecord(string resource, string user, string password, string domain)   {    int ret = 0;    int paramError = 0;    _USE_INFO_2 use2 = new _USE_INFO_2();    IntPtr pBuf = IntPtr.Zero;    use2.ui2_password = IntPtr.Zero;    try    {     pBuf = Marshal.AllocHGlobal(Marshal.SizeOf(use2));     use2.ui2_local = null;     use2.ui2_asg_type = USE_WILDCARD;     use2.ui2_remote = resource;     use2.ui2_password = Marshal.StringToHGlobalAuto(password);     use2.ui2_username = user;     use2.ui2_domainname = domain;     Marshal.StructureToPtr(use2, pBuf, true);     ret = NetUseAdd(null, 2, pBuf, ref paramError);     if(ret != 0)     {          throw new Exception(new Win32Exception(Marshal.GetLastWin32Error()).Message);     }    }    finally    {     Marshal.FreeHGlobal(use2.ui2_password);     Marshal.FreeHGlobal(pBuf);    }   } }

    class Program     {         [System.Runtime.InteropServices.DllImport("advapi32.dll")]         public static extern int LogonUser(String lpszUserName,             String lpszDomain,             String lpszPassword,             int dwLogonType,             int dwLogonProvider,             ref IntPtr phToken);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]         public static extern int DuplicateToken(IntPtr hToken,             int impersonationLevel,             ref IntPtr hNewToken);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]         public static extern bool RevertToSelf();

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]         public static extern bool CloseHandle(IntPtr handle);

        const int LOGON32_PROVIDER_DEFAULT = 0;         const int LOGON32_LOGON_INTERACTIVE = 2;

        static public WindowsImpersonationContext wic;

        //static void Main(string[] args)         //{         //    IntPtr lnToken;

        //    if (ImpersonateValidUser("michaell", "cmp-0641", "wilma"))         //    {         //        using (wic)         //        {

        //            string dir = @"\\cmp-0641\C$\" + "Test";         //            System.IO.Directory.CreateDirectory(dir);         //        }

        //        StringBuilder sb = new StringBuilder(80, 80);         //        RevertToSelf();         //        //CloseHandle( lnToken );         //    }         //    else         //    {

        //    }         //    return;         //}

        static public bool ImpersonateValidUser(String userName, String domain, String password)         {             WindowsIdentity wi;             IntPtr token = IntPtr.Zero;             IntPtr tokenDuplicate = IntPtr.Zero;

            if (RevertToSelf())             {                 if (LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE,                     LOGON32_PROVIDER_DEFAULT, ref token) != 0)                 {                     if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)                     {                         wi = new WindowsIdentity(tokenDuplicate);                         wic = wi.Impersonate();                         if (wic != null)                         {                             CloseHandle(token);                             CloseHandle(tokenDuplicate);                             return true;                         }                     }                 }             }             if (token != IntPtr.Zero)                 CloseHandle(token);             if (tokenDuplicate != IntPtr.Zero)                 CloseHandle(tokenDuplicate);             return false;         }

    }

    public class LogOnUser     {         //LogonUser parameters         [DllImport("advapi32.dll")]         private static extern bool LogonUser(String lpszUsername,                                                 String lpszDomain,                                                 String lpszPassword,                                                 int dwLogonType,                                                 int dwLogonProvider,                                                 ref IntPtr phToken);

        //CloseHandle parameters. When you are finished,         //free the memory allocated for the handle.         [DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]         private static extern bool CloseHandle(IntPtr handle);

        public static WindowsIdentity GetWindowsIdentity(string pUserName, string pDomain)         {             return null;         }

        public static WindowsIdentity GetWindowsIdentity(string pUserName, string pDomain, string pPassword)         {             IntPtr tokenHandle = IntPtr.Zero;

            try             {                 const int LOGON32_PROVIDER_DEFAULT = 0;                 const int LOGON32_LOGON_NETWORK = 5;

                //Call LogonUser to obtain a                 //handle to an access token                 bool returnValue = LogonUser(pUserName, pDomain,                              pPassword,                             LOGON32_LOGON_NETWORK,                            LOGON32_PROVIDER_DEFAULT,                             ref tokenHandle);

                if (false == returnValue)                 {                     return null;                 }

                ////Check the identity                 //Console.WriteLine("Before impersonation: " +                 //         WindowsIdentity.GetCurrent().Name);

                //Create a WindowsIdentity from the impersonation                 //token, then impersonate the user.                 WindowsIdentity newId;                 newId = new WindowsIdentity(tokenHandle);                 return newId;             }

            catch (Exception ex)             {                 // TODO log the Exception Message.                 return null;             }         }

    }

}

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2008-05-22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
.net下模拟不同身份登陆以获取不同权限
.net下模拟不同身份登陆以获取不同权限     作者:佚名 时间:-- : 出处:互连网 责编:chinaitpower                   摘要:.net下模拟不同身份登陆以获取不同权限      不管是asp.net、web service还是window service,程序运行的时候只有本地计算机的部分权限,有时候需要更大的权限,比如读写某台服务器或域中的一台计算机上的文件等,这就需要更大的权限,比如域帐户权限。  通过获取不同身份的WindowsImpersonationCon
阿新
2018/04/13
1.1K0
C# Windows服务开发
我要开发一个系统服务,服务的作用是定时检测并关闭其他应用的弹窗,但是开发后却发现,服务在运行是压根获取不到任何窗口。
码客说
2022/05/23
1.3K0
C# Windows服务开发
C#/.NET基于Topshelf创建Windows服务的守护程序不显示UI界面的问题分析和解决方案
C#/.NET基于Topshelf创建Windows服务的守护程序作为服务启动的客户端桌面程序不显示UI界面的问题分析和解决方案
Rector
2019/05/25
1.3K0
[WCF权限控制]模拟(Impersonation)与委托(Delegation)[上篇]
由于服务操作是在寄宿进程中执行,在默认的情况下,服务操作是否具有足够的权限访问某个资源(比如文件)决定于执行寄宿进程Windows帐号的权限设置,而与作为客户端的Windows帐号无关。在有多情况下,我们希望服务操作执行在基于客户端的安全上下文中执行,以解决执行服务进行的帐号权限不足的问题。这就涉及到一个重要的话题——模拟(Impersonation)与委托(Delegation)[实例程序源代码从这里下载] 目录: 一、从访问令牌(Access Token)说起 二、再谈Windo
蒋金楠
2018/01/16
1.6K0
【C#】分享基于Win32 API的服务操作类(解决ManagedInstallerClass.InstallHelper不能带参数安装的问题)
------------------201508250915更新------------------
AhDung
2018/09/13
1.4K0
使用 C# 自动化关闭电脑
我查阅资料发现有一些可使用 C# 关闭用户电脑的方法,但我觉得都不是很简洁,所以我想在这里寻找一种简单或者使用原生 .NET 关闭的方式。
zls365
2021/04/23
5770
进程注入
通过 KernelCallBackTable 的进程注入涉及用自定义有效载荷替换原始回调函数,以便每当调用该函数时,都会触发有效载荷。在这种情况下,使用了 fnCOPYDATA 回调函数。
Khan安全团队
2021/12/31
5670
C#使用P/Invoke来实现注册表的增删改查功能
注册表可以用来进行存储一些程序的信息,例如用户的权限、或者某些值等,可以根据个人需要进行存储和删减。
Wesky
2024/08/13
1000
C#使用P/Invoke来实现注册表的增删改查功能
权限提升分析及防御
本篇继续阅读学习《内网安全攻防:渗透测试实战指南》,是第四章权限提升分析及防御,本章主要分析了系统的内核溢出漏洞提权、利用Windows操作系统错误配置提权、利用组策略首选项提权、绕过UAC提权、令牌窃取及无凭证条件下的权限获取,并提出了相应的安全防范措施
红客突击队
2022/09/29
1.5K0
从Win服务启动UI程序
从windows服务启动一个带UI程序的界面,这个需求在xp中是很随意的,从Vista开始似乎没有那么随意了,因为Vista中加入了Session的概念,那么什么是Session,我想这篇文章介绍的应该比我权威的多。Session隔离介绍
用户1175783
2019/09/18
1.1K0
打印自定义纸张大小
长江支流说的办法保留太多了,结果不行,很多类都是他在程序集里自定义的,源码又没公开
Java架构师必看
2021/03/22
7660
Windows查看硬盘总字节数
Get-PhysicalDisk命令虽然好,但是不适用低版本系统,比如Server2008R2和Win7
Windows技术交流
2023/12/27
2800
C# 纯控制台创建一个全屏窗口
使用 user32.dll 的 CreateWindowExW 方法就能创建窗口,代码请看
林德熙
2020/08/19
1.1K0
从执行上下文角度重新理解.NET(Core)的多线程编程[3]:安全上下文
在前两篇文章(《基于调用链的”参数”传递》和《同步上下文》)中,我们先后介绍了CallContext(IllogicalCallContext和LogicalCallContext)、AsyncLocal<T>和SynchronizationContext,它们都是线程执行上下文的一部分。本篇介绍的安全上下文(SecurityContext)同样是执行上下文的一部分,它携带了的身份和权限相关的信息决定了执行代码拥有的控制权限。
蒋金楠
2020/12/01
5730
从执行上下文角度重新理解.NET(Core)的多线程编程[3]:安全上下文
利用ActiveX实现web页面设置本地默认打印机、纸张大小
通常web技术无法设置本地计算机的默认打印机,包括用代码设置纸张大小,如果业务系统中真遇到这种需求,只能通过其它辅助手段(比如ActiveX)实现。下面这段代码,出自网上被广泛使用的"泥人张打印API"(抱歉未找到原始出处),已经用C#封装了很多关于底层打印的API方法
菩提树下的杨过
2018/09/20
2K1
wpf键盘记录器
很简单的一个wpf键盘记录器 这个程序我一样用了全局勾子,之前用的都是winform上运行了,前一段时间 在国外的论坛上逛看到了一个wpf能用的就做了一个小程序记录一下,为了方便大家直关的看我在页面上
lpxxn
2018/01/31
1.2K0
wpf键盘记录器
系统钩子
设置钩子代码 //定义一个钩子实例 var hookProc = new HookProc(HookProcCallback); //设置钩子 hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, proc, null, 0); if(hkeyboardHook!=IntPtr.Zero){ //设置成功 }
用户1175783
2019/09/18
9540
Windows任务管理 连接用户登录信息 通用类[C#版]
通用类名[ComputerLoginUserInfo.cs] 代码如下: using System; //---引用 using System.Runtime.InteropServices; using System.Text; /// <summary> /// Windows 任务管理器登录用户信息 /// author:Stone_W /// date:2011.1.14 /// </summary> public class ComputerLoginUserInfo { #regio
磊哥
2018/04/26
1.2K0
使用WINAPI安装Windows服务[转]
using system; using system.runtime.interopservices; namespace myserviceinstaller { class serviceinstaller { #region private variables private string _servicepath; private string _servicename; private string _service
liulun
2022/05/09
5180
借助API实现黑盒自动化测试工具的编写
  在日常编码过程中,我们常常会进行自动化测试。这里的自动化测试不是指单元测试,而是模拟人工输入来进行快速的、高并发的测试。可以使用的自动化工具有LOADRUNNER,以及目前在VS2010中的功能很强大的测试工作平台(录制操作步骤,自动生成代码)。但是,这些工具的熟练掌握也有一定的时间成本,并且,最主要的,对于一个程序员来说,那不够灵活。所以,比较高效的一个做法是,调用WINDOWS API,自己动手写编码来实现。
顾翔
2021/07/22
6360
相关推荐
.net下模拟不同身份登陆以获取不同权限
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文