博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
通过LogonUser API,先切换登入账户,再设置文件的ACL
阅读量:7280 次
发布时间:2019-06-30

本文共 5857 字,大约阅读时间需要 19 分钟。

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.AccessControl; using System.IO; using System.Diagnostics; using System.Security.Principal; using System.Runtime.InteropServices; namespace ConsoleApplication4 {
internal class NativeMethods {
// Methods [DllImport("kernel32.dll", CharSet = CharSet.Auto)] internal static extern bool CloseHandle(IntPtr handle); [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] internal static extern bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle); [DllImport("advapi32.dll", SetLastError = true)] internal static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); } class Program {
static void Main(string[] args) {
string filePath = "ClientFile_0.txt"; string userAccount = string.Format(@"{0}\{1}", Environment.UserDomainName, Environment.UserName); ImpersonateUser(Environment.GetEnvironmentVariable("COMPUTERNAME"), "Co9999CMLUser_0", "password(123"); File.WriteAllText(filePath, string.Format("{0}", "Hello World ආයූෝබවන්")); FileSecurity fileSecurity = new FileSecurity(); AddFileSecurity(filePath, userAccount, FileSystemRights.Read, AccessControlType.Deny); //RemoveFileSecurity(filePath, userAccount, FileSystemRights.Read, AccessControlType.Deny); //File.Delete(filePath); OutputFileAccess(filePath); //create windows user account //CreateUserAccount(Environment.GetEnvironmentVariable("COMPUTERNAME"), "Co9999CMLUser_0", "password(123"); Console.WriteLine("Done!"); Console.ReadLine(); } private static bool LogonUser(string MachineName, string UserName, string Password, ref IntPtr tokenHandle) {
tokenHandle = new IntPtr(0); tokenHandle = IntPtr.Zero; bool flag = NativeMethods.LogonUser(UserName, MachineName, Password, 2, 0, ref tokenHandle); if (!flag) {
int num = Marshal.GetLastWin32Error(); Console.WriteLine(" Failed with error code : {0}", num); //Console.WriteLine("\nError: [{0}] {1}\n", num, GetErrorMessage(num)); } return flag; } public static WindowsImpersonationContext ImpersonateUser(string MachineName, string UserName, string Password) {
IntPtr tokenHandle = new IntPtr(0); IntPtr duplicateTokenHandle = new IntPtr(0); if (!LogonUser(MachineName, UserName, Password, ref tokenHandle)) {
Console.WriteLine(MachineName); Console.WriteLine("Info_3047gs! CommonImpersonationUtilities::ImpersonateUser cannot test with local user"); return null; } if (!NativeMethods.DuplicateToken(tokenHandle, 2, ref duplicateTokenHandle)) {
Console.WriteLine("Err_23efad! CommonImpersonationUtilities::ImpersonateUser cannot get token for the local user"); NativeMethods.CloseHandle(tokenHandle); return null; } WindowsIdentity identity = new WindowsIdentity(duplicateTokenHandle); return identity.Impersonate(); } public static void OutputFileAccess(string filePath) {
FileSecurity fileSecurity = File.GetAccessControl(filePath); foreach (AuthorizationRule rule in fileSecurity.GetAccessRules(true, true, typeof(NTAccount))) {
var fileRule = rule as FileSystemAccessRule; Console.WriteLine("Access type: {0}", fileRule.AccessControlType); Console.WriteLine("Rights: {0}", fileRule.FileSystemRights); Console.WriteLine("Identity: {0}", fileRule.IdentityReference.Value); Console.WriteLine(); } } public static void AddFileSecurity(string fileName, string account, FileSystemRights rights, AccessControlType controlType) {
// Get a FileSecurity object that represents the // current security settings. FileSecurity fSecurity = File.GetAccessControl(fileName); // Add the FileSystemAccessRule to the security settings. fSecurity.AddAccessRule(new FileSystemAccessRule(account, rights, controlType)); //fSecurity.AddAccessRule(new FileSystemAccessRule(account, FileSystemRights.Delete, AccessControlType.Deny)); // Set the new access settings. File.SetAccessControl(fileName, fSecurity); } // Removes an ACL entry on the specified file for the specified account. public static void RemoveFileSecurity(string fileName, string account, FileSystemRights rights, AccessControlType controlType) {
// Get a FileSecurity object that represents the // current security settings. FileSecurity fSecurity = File.GetAccessControl(fileName); // Add the FileSystemAccessRule to the security settings. fSecurity.RemoveAccessRule(new FileSystemAccessRule(account, rights, controlType)); // Set the new access settings. File.SetAccessControl(fileName, fSecurity); } public static void CreateUserAccount(string strMachineName, string strUserName, string strPassword) {
Process process = new Process(); process.StartInfo = new ProcessStartInfo("net.exe", string.Format("user {0} {1} /add", strUserName, strPassword)) {
UseShellExecute = false }; process.Start(); process.WaitForExit(); } } }

注意:要设置的文件必须在切换登入用户之后再建立,也就是在ImpersonateUser()之后,才生成文件,否则在之后的File.SetAccessControl时候会出现没有授权的异常。

转载于:https://www.cnblogs.com/zhuzhenjesse/archive/2011/11/29/2267284.html

你可能感兴趣的文章
markdown 写 api 系统
查看>>
找回Mac丢失空间
查看>>
给大家推荐一个整合了python和bash的神器,xonsh
查看>>
数据库基本操作指令总结
查看>>
一对一直播源码全套开源,二次开发有保障!
查看>>
NumPy 超详细教程(3):ndarray 的内部机理及高级迭代
查看>>
侃一侃WebSocket
查看>>
hanlp源码解析之中文分词算法
查看>>
把你的程序放到桌面——Android桌面部件Widget
查看>>
《图解HTTP》第3章_HTTP报文内的HTTP信息-思维导图
查看>>
分享一个冷门知识——文本框的选择文本在业务中的应用
查看>>
彻底理解浏览器的跨域
查看>>
1009 说反话 (20 分)
查看>>
Flutter Wrap & Chip
查看>>
Vue路由自动注入实践
查看>>
类数组转化成数组的方法
查看>>
Android屏幕适配方案
查看>>
使用Databinding轻松快速打造仿携程app筛选控件(二)
查看>>
AppCompatActivity怎么对View做的拦截
查看>>
记b站的一次react尝试
查看>>