Click here to Skip to main content
Click here to Skip to main content

NT Security Classes for .NET

By , 19 Feb 2004
 

Introduction

This class library allows access to the Win32 security calls in a .NET friendly way. It encapsulates the concepts of a user, a securable object (like a file, named pipe, directory, etc.), and permissions. This library was written in Managed C++ to simplify the amount of work needed to link to existing Win32 libraries. However, since it exposes all of its functionality via .NET, it can be used from any .NET compliant language, including C# and Visual Basic. The project was written and compiled with Visual Studio 2002.

NOTE: There is a library written by some Microsoft guys on GotDotNet that does much of the same thing and more. It can be found at http://www.gotdotnet.com/Community/UserSamples/Details.aspx?SampleGuid=e6098575-dda0-48b8-9abf-e0705af065d9.

This article outlines the primary objects in the library and their use in manipulating security objects.

Documentation

WindowsUser class

This class represents a single Windows identity (SID). It can be created by specifying either a username ("DOMAIN\user" format) or the string representation of a SID ("S-1-5-xxxx-xxx..."). You can also get the identity of the current user using the static property CurrentUser.

There are a number of predefined identities that exist as static members of a child class called WellKnownIdentities. Once you have an identity, you can get the following properties:

  • AccountName: string name of the account
  • Domain: string name of the account's domain
  • FullName: string in the form of "Domain\AccountName"
  • SidString: string representation of the SID

SecuredObject class

This class represents an object which can have a security descriptor. It can be created by specifying the name of the resource along with its type or by passing a handle (as an IntPtr) to the resource.

Once you have the object, you can update the permissions, audit information, owner and group.

PermissionsList

This class encapsulates actions on the ACL. It allows granting, revoking, changing, and denying access levels to different users. Derived from AccessList, which is a collection class for AccessEntry.

AuditingList

This class encapsulates actions on the auditing list of an object. It allows getting and setting audit success and failure rights. Derived from AccessList, which is a collection class for AccessEntry.

AccessEntry

This class encapsulates the Access Control Entry or ACE. You can set the user (trustee) and the associated rights and inheritance.

Example

This code shows the library in action. It assumes you have aliased the Microsoft.Win32.Security namespace (using in C#, Imports in VB).

// Get the current user and print their information
WindowsUser user = WindowsUser.CurrentUser;
Console.WriteLine("{0} ({1})", user.FullName, user.SidString);

// Get the current user from their token
WindowsUser duser = new WindowsUser(
  System.Security.Principal.WindowsIdentity.GetCurrent().Token);
Console.WriteLine(duser.FullName);

// Compare users
if (user == duser)
   Console.WriteLine("Same");
else
   Console.WriteLine("Different");

// Get a well-known user
user = WindowsUser.WellKnownIdentities.World;
Console.WriteLine(user.FullName);

// Get a user by name from a specific server (usually a domain controller)
WindowsUser kuser = new WindowsUser("user2", @"\\MYPDC");
Console.WriteLine(kuser.FullName);

// Get a user by name
user = new WindowsUser("DOMAIN\\user3");
Console.WriteLine(user.FullName);

// Get a user by SID
user = new WindowsUser("S-1-5-21-21782756-1035017279-1439700725-1111");
Console.WriteLine(user.FullName);

// Get security for C:\ directory
SecuredObject sec = new SecuredObject("C:\\", SecuredObjectType.FileObject);
DumpObject(sec);

// Set some various permissions on the directory
sec.Permissions.SetAccess(kuser, AccessRights.FileRead,
   AceInheritanceFlags.ContainerInherit|AceInheritanceFlags.ObjectInherit);
sec.Permissions.GrantAccess(kuser, AccessRights.FileExecute,
   AceInheritanceFlags.ContainerInherit|AceInheritanceFlags.ObjectInherit);
sec.Permissions.DenyAccess(kuser, AccessRights.FileWriteUnsync,
   AceInheritanceFlags.ContainerInherit|AceInheritanceFlags.ObjectInherit);
WindowsUser owner = sec.Owner;
sec.Owner = duser;
sec.Auditing.SetAuditFailure(duser, AccessRights.FileReadUnsync,
   AceInheritanceFlags.ContainerInherit|AceInheritanceFlags.ObjectInherit);
DumpObject(sec);

// Revoke some access
sec.Permissions.RevokeAccess(kuser);
sec.Owner = owner;
DumpObject(sec) ;

// Reset the security on the directory
sec.Permissions.Clear();
sec.Permissions.InheritFromParent = true;
DumpObject(sec);

// Write the DACL using the Microsoft style
Console.WriteLine(sec.ToString());

The following function shows how to enumerate the permissions on a security object.

static void DumpObject(SecuredObject sec)
{
   Console.WriteLine("Security description:");
   Console.WriteLine("=====================");
   Console.WriteLine("Owner: {0}\nGroup: {1}", 
     sec.Owner.FullName, sec.Group.FullName);
   Console.WriteLine("Permissions:");
   foreach (AccessEntry ace in sec.Permissions)
      Console.WriteLine(String.Format("  {0} : {1} : {2}", 
         ace.Trustee.FullName,
         ace.Inheritance, ace.Rights));
   Console.WriteLine("Auditing:");
   foreach (AccessEntry ace in sec.Auditing)
      Console.WriteLine(String.Format("  {0} : {1} : {2}", 
         ace.Trustee.FullName,
         ace.Inheritance, ace.Rights));
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

David Hall
Architect
United States United States
Member
I have been a Windows software developer since 1991. Most of what I create fills the need for some aspect of bigger projects that I consult on.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralBroken Linkmembercilu11 Dec '09 - 5:41 
QuestionMemoryleak?membermackenb13 Oct '09 - 2:41 
GeneralWin32Helper Fails on comparing two null sids.memberMember 382942711 Aug '09 - 1:32 
QuestionHow to setup mmsseclib for usagememberJuergen Loewner21 Aug '07 - 20:43 
GeneralRe: How to setup mmsseclib for usagememberJuergen Loewner22 Aug '07 - 7:12 
GeneralConsole frontend à la (X)CaclsmemberLiQuick28 Mar '07 - 2:31 
There are still some console freaks like me (system administrators) out there that have used MS tools like (X)Cacls to automate several tasks. But due to several problems with (X)Cacls I had to resort to manual labour Sigh | :sigh: . But here it is!! A great library of David Hall! Have created a shell around it to make it more coworker friendly:->. You can find it on LiQuick.net. When all bugs are out, I'll try to write an add-on article to this page. Code of the console can be requested for by e-Mail.
QuestionCompiler problemmemberwakkoedu6 Dec '06 - 1:27 
QuestionDavid, can I use your dll in the commercial product?memberDmitry V.Trus23 Nov '06 - 5:07 
GenerallaunchPermission on componentmembersuperk10 May '06 - 0:44 
Generalexception questionmemberah_zen11 Mar '06 - 1:30 
GeneralRe: exception questionmemberMrBonus1 Aug '06 - 0:46 
QuestionVB 2005 issuememberlmwinbur13 Feb '06 - 18:11 
AnswerRe: VB 2005 issuememberbbosak23 Mar '06 - 10:11 
AnswerRe: VB 2005 issuememberOliProject18 Apr '07 - 3:27 
AnswerRe: VB 2005 issuememberMember 294579031 Dec '08 - 8:04 
GeneralOn NT4.0 SP6 Machinememberk_udct2 Jun '05 - 23:22 
GeneralRe: On NT4.0 SP6 MachinememberDavid Hall6 Jun '05 - 5:27 
GeneralRe: On NT4.0 SP6 Machinememberk_udct8 Jun '05 - 3:54 
GeneralRe: On NT4.0 SP6 MachinememberDavid Hall8 Jun '05 - 4:43 
GeneralError while assigning SecurityObjectmemberVikramSaraf30 May '05 - 21:07 
GeneralRe: Error while assigning SecurityObjectmemberDavid Hall6 Jun '05 - 5:30 
GeneralNamed pipe helpmembererictaneda26 Dec '04 - 8:45 
GeneralQuestion about enums.hmemberJohn Rusk29 Nov '04 - 16:36 
GeneralRe: Question about enums.hmemberDavid Hall30 Nov '04 - 4:51 
GeneralRe: Question about enums.hmemberJohn Rusk30 Nov '04 - 8:32 
GeneralAdds special permissions not regula permissionsmemberpatel_o19 Nov '04 - 4:54 
GeneralRe: Adds special permissions not regula permissionsmemberDavid Hall19 Nov '04 - 5:08 
GeneralRe: Adds special permissions not regula permissionsmemberpatel_o19 Nov '04 - 8:36 
GeneralRe: Adds special permissions not regula permissionsmemberDavid Hall7 Dec '04 - 7:07 
GeneralRe: Adds special permissions not regula permissionsmemberLiQuick9 May '06 - 1:16 
GeneralRegistry ACLsmemberJames Miles / 20810974316 Nov '04 - 18:10 
AnswerRe: Registry ACLsmemberfuzzylintman29 Sep '05 - 6:02 
GeneralNull ReferencememberXe Capital25 Aug '04 - 6:20 
QuestionGetEffectiveRights(user) does it work?membergryfgryf26 Jun '04 - 11:38 
GeneralAccessRights Error!memberReisses5 Feb '04 - 9:06 
GeneralRe: AccessRights Error!memberDavid Hall5 Feb '04 - 10:13 
GeneralRe: AccessRights Error!memberReisses5 Feb '04 - 10:24 
GeneralRe: AccessRights Error!memberDavid Hall5 Feb '04 - 10:28 
GeneralRe: AccessRights Error!memberReisses5 Feb '04 - 10:31 
GeneralRe: AccessRights Error!memberjohnleonard30 Sep '04 - 4:48 
GeneralCan't buildmemberthe_cRaCk_3 Dec '03 - 3:43 
GeneralRe: Can't buildmemberDavid Hall3 Dec '03 - 4:12 
GeneralRe: Can't buildmembergdumas7 Dec '03 - 22:48 
GeneralRe: Can't buildmemberthe_cRaCk_13 Jan '04 - 23:02 
GeneralRe: Can't buildmemberXe Capital23 Jul '04 - 7:38 
GeneralRe: Can't buildmemberDavid Hall29 Jul '04 - 5:29 
GeneralRe: Can't buildmembergibneys13 Jul '05 - 3:07 
GeneralGet file security with Win32Security from Microsoftmemberportyr24 Oct '03 - 0:43 
Generalunverifiable assembly....memberroglan9 Jun '03 - 23:12 
GeneralRe: unverifiable assembly....memberDavid Hall10 Jun '03 - 5:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 20 Feb 2004
Article Copyright 2002 by David Hall
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid