Using FileStream from Restricted User Accounts [Josh Free]

Every so often, I run into code that requests security permissions that are not needed. Take the following code snippet as an example:

// open the file for reading

FileStream fs1 = new FileStream(@"C:\Program Files\SomeFile.bin",

                                FileMode.Open);

From the code comment, the developer is using the FileStream object to read the file. However, the FileStream constructor they used requests FileAccess.ReadWrite access – giving the code read and write access to the file.

The developer should have written their code to only request read access:

// open the file for reading

FileStream fs1 = new FileStream(@"C:\Program Files\SomeFile.bin",

           FileMode.Open, FileAccess.Read);

Many of you may be thinking “so what?” – After all, on Windows XP (and earlier operating systems) most users run as Administrators or Power users. Since Administrators have unrestricted access to all files on the computer, this code is unlikely to fail.

If you are not familiar with the terms “Administrator”, “Power User”, and “Restricted User” you may want to look at the User Account Control Panel in Windows –

Administrators

Administrators have complete and unrestricted access to the computer/domain

Standard user (Power Users Group)

Users can change many system settings and install programs that don’t affect Windows system files.

Restricted user (Users Group)

Users can operate the computer and save documents, but cannot install programs or change system settings.

As you can see from the definitions above, security-minded users are able to run programs under Restricted user accounts. When one of these users runs your program they may end seeing an unhandled System.UnauthorizedAccessException!

To avoid this bad customer experience for Restricted user accounts you should:

  1. Only request the minimum permissions that your application needs to run
  2. Verify your application runs from a Restricted user account.