0

I need to make a program that reads data from a text file and changes the program state according to specific data found in the text file, where my program needs privileges to read, write and create a text file.

I want the users or even other software to be prevented from deleting, modifying, or copying the file. How would I begin to implement this?

Paul Zahra
  • 9,522
  • 8
  • 54
  • 76
naheiwProg
  • 99
  • 2
  • 11
  • 6
    Try to elaborate more, show some samples and so on. Right now it is totally unclear what you're asking and what is your problem. – Andrey Korneyev May 15 '15 at 08:55
  • Let me rephrase that, to make sure I understand: your software reads data from a configuration file and you want to make sure that no one tampers with that file. Is that correct? – Andrei V May 15 '15 at 08:58
  • I guess he's looking for that Andrei. What have you tried until now? – Gino May 15 '15 at 09:00
  • yes @AndreiV exactly. I want my program to read the contents of the text file and adapt the program state, for example show a page to create an administrators account or login as a user ext – naheiwProg May 15 '15 at 09:01
  • 2
    It is not possible to prevent a user or other programs from reading or modifying a file. A program on Windows will only ever have the same access as the user running the program. What you could do would be to create another user that you run the program under and set access rights on the file for only that user, but that user will of course have full access to the file and any other programs that same user would run would have access as well. – Lasse V. Karlsen May 15 '15 at 09:03
  • But then you're actual problem is locking the access to that specific file. – Andrei V May 15 '15 at 09:03
  • Do you want the file to be protected only while you access it, or before and after as well? I.e. do you just want to make sure the contents don't change while your read them? – PJTraill May 15 '15 at 09:03
  • Are you trying to prevent / make it difficult to tamper with the file or are the criteria exactly like you specified? In other words, is this an X/Y problem? Why do you have those criteria? Could you tell us a bit about the problem you're trying to solve other than locking down the file? Why do you want to lock down the file? – Lasse V. Karlsen May 15 '15 at 09:04
  • What is the relevance of the privileges needed by your programme (which, as you describe it, really only needs to read the given file)? – PJTraill May 15 '15 at 09:06
  • @ PJTraill I want it protected even when my program is not running. @LasseV.Karlsen I want my program to look at the contents of the file when the form is first loaded. Then the software will change the form contents to either "create a admin account" or "login as either user or admin". I want the text file protected so that nobody can change it to create an unauthorized admin user. – naheiwProg May 15 '15 at 09:10
  • And you can't do that so you need to find a different way to approach your goal. There is no way to protect a file like that except access rights, but these are *per user*, not *per program*, which means that whichever user you give access rights to the file can access it, with any program he or she wants. You *could* encrypt the file or similar to make it difficult to tamper with the file, but you cannot make it impossible. – Lasse V. Karlsen May 15 '15 at 09:11

2 Answers2

0

You can achieve this in three ways:

1) as soon as the application starts get your filehandle and lock the file. This would of course only work if the applications runs (for example as a service) all the time

2) Adjust the priviledges in the files security tab and set it to read only. Create a technical user for write access (works best in domains). Open the file in your program with the technical user while using impersionation (WindowsImpersonationContext). Using would be simple:

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

a sample class that will get you a WindowsImpersonationContext (should work like a charm):

[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);
        }
    }
}

Another attempt (including using) is shown here: Open a shared file under another user and domain?

3) Obviously running the program as a different user who has access rights - all other users have readonly rights (use a technical User when registered as a service or with the runas /user command)

Community
  • 1
  • 1
Marc Wittmann
  • 2,286
  • 2
  • 28
  • 41
0

You can open the File with a specific access condition (https://msdn.microsoft.com/de-de/library/s67691sb(v=vs.110).aspx). The application won't be able to modify the data if you deny the privilege here. To make this clear, your application access is then read-only and you can't modify it.

Preventing other applications or users to delete/modify/whatever your text file is not possible in C#. You can restrict the permissions in the file systems, but that's all.

If this is important then you should rethink your implementation. C# offers resource files for instance or application specific parameter in your application config.

Bjoern
  • 164
  • 2
  • 11