防止用户删除、修改、扩展

Preventing a user from deleting, modifying, ext

我需要编写一个程序,从文本文件中读取数据并根据在文本文件中找到的特定数据更改程序状态,其中我的程序需要读取、写入和创建文本文件的权限。

我希望防止用户甚至其他软件删除、修改或复制文件。我将如何开始实施呢?

您可以通过三种方式实现此目的:

1) 应用程序启动后立即获取您的文件句柄并锁定文件。这当然只有在应用程序一直运行(例如作为服务)时才有效

2) 调整文件安全选项卡中的权限,将其设置为只读。为写访问创建一个技术用户(在域中效果最好)。在使用模拟 (WindowsImpersonationContext) 时与技术用户一起打开程序中的文件。使用起来很简单:

using (new Impersonation(domain, username, password))
{
    // do whatever you want
}

一个示例 class 将为您提供 WindowsImpersonationContext(应该很有魅力):

[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public class Impersonation : IDisposable
{
    private readonly SafeTokenHandle _handle;
    private readonly WindowsImpersonationContext _context;

    const int LOGON32_LOGON_NEW_CREDENTIALS = 9;

    public Impersonation(string domain, string username, string password)
    {
        var ok = LogonUser(username, domain, password,
                       LOGON32_LOGON_NEW_CREDENTIALS, 0, out this._handle);
        if (!ok)
        {
            var errorCode = Marshal.GetLastWin32Error();
            throw new ApplicationException(string.Format("Could not impersonate the elevated user.  LogonUser returned error code {0}.", errorCode));
        }

        this._context = WindowsIdentity.Impersonate(this._handle.DangerousGetHandle());
    }

    public void Dispose()
    {
        this._context.Dispose();
        this._handle.Dispose();
    }

    [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);

    public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
    {
        private SafeTokenHandle()
            : base(true) { }

        [DllImport("kernel32.dll")]
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        [SuppressUnmanagedCodeSecurity]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool CloseHandle(IntPtr handle);

        protected override bool ReleaseHandle()
        {
            return CloseHandle(handle);
        }
    }
}

这里显示了另一个尝试(包括使用):Open a shared file under another user and domain?

3) 显然 运行 作为具有访问权限的不同用户的程序 - 所有其他用户都具有只读权限(在注册为服务或使用 runas /user 命令时使用技术用户)

您可以打开具有特定访问条件的文件 (https://msdn.microsoft.com/de-de/library/s67691sb(v=vs.110).aspx)。 如果您在此处拒绝权限,应用程序将无法修改数据。 为清楚起见,您的应用程序访问权限是只读的,您无法修改它。

阻止其他应用程序或用户delete/modify/whatever您的文本文件在 C# 中是不可能的。您可以限制文件系统中的权限,仅此而已。

如果这很重要,那么您应该重新考虑您的实施。 C# 在您的应用程序配置中提供实例或应用程序特定参数的资源文件。