Coding Tip: Why you should always use well known SIDs over usernames for security groups
So have you ever tried to restrict access to your applications in a way so that you can maintain least privilege?
I do. All the time. And recently it blew up in my face, and I want to share my experience so others can learn from my failure.
Let me show you a faulty line of code:
if( principal.IsInRole( "Administrators" ) )
Seems rather harmless doesn't it? Can you spot the defect? Come on... its sitting right in the subject of this post.
Checking to see if the current user is in the "Administrators" group is a good idea. And using WindowsPrincipal is an appropriate way to do it. But you have to remember that not EVERYONE speaks English. In our particular case, we found a customer installed our product using English, but had a user with a French language pack. Guess what... the above code didn't work for them. Why? Because the local administrators group is actually "Administrateurs".
The fix is rather trivial:
SecurityIdentifier sid = new SecurityIdentifier( WellKnownSidType.BuiltinAdministratorsSid, null );
By using the well known SID for the Administrators group, we ensure the check regardless of the name or language used.
Lesson learned the hard way for me. We have an entire new class of defect we are auditing for, which we have found in several places in our code. it always fails securely, NOT letting them do anything, but that's not the point. It is still a defect. Other accounts we weren't considering were "Network Service" (its an ugly name on a German target) and "Guest". Just to name a few.
Hope you can learn from my mistake on that one. That's a silly but common error you may or may not be considering in your own code.