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:
- Only request the minimum permissions that your application needs to run
- Verify your application runs from a Restricted user account.
Comments
- Anonymous
May 05, 2006
This is perhaps more common when using the registry. Requesting read write access will fail for a large sections of the tree for a normal user account. - Anonymous
May 05, 2006
Attempting to address Rajesh's concerns about
optionality... [Via: Tim Ewald ]
Axis2 1.0 released... - Anonymous
May 07, 2006
So in hindsight, should the default FileAccess have been Read instead of ReadWrite? I personally think so . . . - Anonymous
May 08, 2006
The comment has been removed - Anonymous
May 29, 2009
PingBack from http://paidsurveyshub.info/story.php?title=bcl-team-blog-using-filestream-from-restricted-user-accounts-josh-free