通过LogonUser API,先切换登入账户,再设置文件的ACL

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值