How to call Win32 Native API GetTokenInformation() using C#?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Vincent Nguyen

    How to call Win32 Native API GetTokenInformation() using C#?

    Hi,

    Does anyone know how call Win32 native API GetTokenInforma tion() by using
    C#? Any sample code would be helpful. Thanks!

    Vincent


  • Mattias Sjögren

    #2
    Re: How to call Win32 Native API GetTokenInforma tion() using C#?

    Vincent,
    [color=blue]
    >Does anyone know how call Win32 native API GetTokenInforma tion() by using
    >C#? Any sample code would be helpful. Thanks![/color]

    What kind of information are you going to retrieve with it, i.e which
    TOKEN_INFORMATI ON_CLASS value are you going to pass in?



    Mattias

    --
    Mattias Sjögren [MVP] mattias @ mvps.org

    Please reply only to the newsgroup.

    Comment

    • Vincent Nguyen

      #3
      Re: How to call Win32 Native API GetTokenInforma tion() using C#?

      I want to retrieve the access tokens for a user, and I want to pass in the
      TOKEN_GROUPS. Thanks for the reply!

      "Mattias Sjögren" <mattias.dont.w ant.spam@mvps.o rg> wrote in message
      news:OOcfys5WDH A.2444@tk2msftn gp13.phx.gbl...[color=blue]
      > Vincent,
      >[color=green]
      > >Does anyone know how call Win32 native API GetTokenInforma tion() by using
      > >C#? Any sample code would be helpful. Thanks![/color]
      >
      > What kind of information are you going to retrieve with it, i.e which
      > TOKEN_INFORMATI ON_CLASS value are you going to pass in?
      >
      >
      >
      > Mattias
      >
      > --
      > Mattias Sjögren [MVP] mattias @ mvps.org
      > http://www.msjogren.net/dotnet/
      > Please reply only to the newsgroup.[/color]


      Comment

      • Mattias Sjögren

        #4
        Re: How to call Win32 Native API GetTokenInforma tion() using C#?

        Vincent,
        [color=blue]
        >I want to retrieve the access tokens for a user, and I want to pass in the
        >TOKEN_GROUPS . Thanks for the reply![/color]

        See if this helps you get it working






        Mattias

        --
        Mattias Sjögren [MVP] mattias @ mvps.org

        Please reply only to the newsgroup.

        Comment

        • Willy Denoyette [MVP]

          #5
          Re: How to call Win32 Native API GetTokenInforma tion() using C#?

          Vincent Nguyen wrote:
          || I don't know much about VB.NET. Do you have any C# sample code for
          || this? Thanks!


          Is this of any help?

          // Begin of code sample
          using System;
          using System.Text;
          using System.Runtime. InteropServices ;
          using System.Security .Permissions;
          using System.Security .Principal;
          using System.Diagnost ics;

          // Forward declarations
          using LUID = System.Int64;
          using HANDLE = System.IntPtr;
          class Tester {
          public const int TOKEN_QUERY = 0X00000008;

          const int ERROR_NO_MORE_I TEMS = 259;

          enum TOKEN_INFORMATI ON_CLASS
          {
          TokenUser = 1,
          TokenGroups,
          TokenPrivileges ,
          TokenOwner,
          TokenPrimaryGro up,
          TokenDefaultDac l,
          TokenSource,
          TokenType,
          TokenImpersonat ionLevel,
          TokenStatistics ,
          TokenRestricted Sids,
          TokenSessionId
          }

          [StructLayout(La youtKind.Sequen tial)]
          struct TOKEN_USER
          {
          public _SID_AND_ATTRIB UTES User;
          }

          [StructLayout(La youtKind.Sequen tial)]
          public struct _SID_AND_ATTRIB UTES
          {
          public IntPtr Sid;
          public int Attributes;
          }
          [DllImport("adva pi32")]
          static extern bool OpenProcessToke n(
          HANDLE ProcessHandle, // handle to process
          int DesiredAccess, // desired access to process
          ref IntPtr TokenHandle // handle to open access token
          );

          [DllImport("kern el32")]
          static extern HANDLE GetCurrentProce ss();

          [DllImport("adva pi32", CharSet=CharSet .Auto)]
          static extern bool GetTokenInforma tion(
          HANDLE hToken,
          TOKEN_INFORMATI ON_CLASS tokenInfoClass,
          IntPtr TokenInformatio n,
          int tokeInfoLength,
          ref int reqLength);

          [DllImport("kern el32")]
          static extern bool CloseHandle(HAN DLE handle);

          [DllImport("adva pi32", CharSet=CharSet .Auto)]
          static extern bool LookupAccountSi d
          (
          [In,MarshalAs(Un managedType.LPT Str)] string lpSystemName, // name of local or remote computer
          IntPtr pSid, // security identifier
          StringBuilder Account, // account name buffer
          ref int cbName, // size of account name buffer
          StringBuilder DomainName, // domain name
          ref int cbDomainName, // size of domain name buffer
          ref int peUse // SID type
          // ref _SID_NAME_USE peUse // SID type
          );

          [DllImport("adva pi32", CharSet=CharSet .Auto)]
          static extern bool ConvertSidToStr ingSid(
          IntPtr pSID,
          [In,Out,MarshalA s(UnmanagedType .LPTStr)] ref string pStringSid);

          public static void Main() {
          string processName = Process.GetCurr entProcess().Pr ocessName;
          Process[] myProcesses = Process.GetProc essesByName(pro cessName);
          if(myProcesses. Length == 0)
          Console.WriteLi ne("Could not find notepad processes on remote machine");
          foreach(Process myProcess in myProcesses)
          {
          Console.Write(" Process Name : " + myProcess.Proce ssName + " Process ID : "
          + myProcess.Id + " MachineName : " + myProcess.Machi neName + "\n");
          DumpUserInfo(my Process.Handle) ;
          }
          }

          static void DumpUserInfo(HA NDLE pToken)
          {
          int Access = TOKEN_QUERY;
          StringBuilder sb = new StringBuilder() ;
          sb.AppendFormat ("\nToken dump performed on {0}\n\n", DateTime.Now);
          HANDLE procToken = IntPtr.Zero;
          if ( OpenProcessToke n( pToken, Access, ref procToken ) )
          {
          sb.Append("Proc ess Token:\n");
          sb.Append(Perfo rmDump(procToke n));
          CloseHandle(pro cToken);
          }
          Console.WriteLi ne(sb.ToString( ));
          }
          static StringBuilder PerformDump(HAN DLE token)
          {
          StringBuilder sb = new StringBuilder() ;
          TOKEN_USER tokUser;
          const int bufLength = 256;
          IntPtr tu = Marshal.AllocHG lobal( bufLength );
          int cb = bufLength;
          GetTokenInforma tion( token, TOKEN_INFORMATI ON_CLASS.TokenU ser, tu, cb, ref cb );
          tokUser = (TOKEN_USER) Marshal.PtrToSt ructure(tu, typeof(TOKEN_US ER) );
          sb.Append(DumpA ccountSid(tokUs er.User.Sid));
          Marshal.FreeHGl obal( tu );
          return sb;
          }

          static string DumpAccountSid( IntPtr SID)
          {
          int cchAccount = 0;
          int cchDomain = 0;
          int snu = 0 ;
          StringBuilder sb = new StringBuilder() ;

          // Caller allocated buffer
          StringBuilder Account= null;
          StringBuilder Domain = null;
          bool ret = LookupAccountSi d(null, SID, Account, ref cchAccount, Domain, ref cchDomain, ref snu);
          if ( ret == true )
          if ( Marshal.GetLast Win32Error() == ERROR_NO_MORE_I TEMS )
          return "Error";
          try
          {
          Account = new StringBuilder( cchAccount );
          Domain = new StringBuilder( cchDomain );
          ret = LookupAccountSi d(null, SID, Account, ref cchAccount, Domain, ref cchDomain, ref snu);
          if (ret)
          {
          sb.Append(Domai n);
          sb.Append(@"\\" );
          sb.Append(Accou nt);
          }
          else
          Console.WriteLi ne("logon account (no name) ");
          }
          catch (Exception ex)
          {
          Console.WriteLi ne(ex.Message);
          }
          finally
          {
          }
          string SidString = null;
          ConvertSidToStr ingSid(SID, ref SidString);
          sb.Append("\nSI D: ");
          sb.Append(SidSt ring);
          return sb.ToString();
          }
          }
          // End of code sample

          Willy.


          Comment

          • Vincent Nguyen

            #6
            Re: How to call Win32 Native API GetTokenInforma tion() using C#?

            Willy,

            Thank you very much! The sample code is helped a lot! I really appriciate
            your helps!

            Vincent

            "Willy Denoyette [MVP]" <willy.denoyett e@skynet.be> wrote in message
            news:uc1hPp$WDH A.2200@TK2MSFTN GP09.phx.gbl...[color=blue]
            > Vincent Nguyen wrote:
            > || I don't know much about VB.NET. Do you have any C# sample code for
            > || this? Thanks!
            >
            >
            > Is this of any help?
            >
            > // Begin of code sample
            > using System;
            > using System.Text;
            > using System.Runtime. InteropServices ;
            > using System.Security .Permissions;
            > using System.Security .Principal;
            > using System.Diagnost ics;
            >
            > // Forward declarations
            > using LUID = System.Int64;
            > using HANDLE = System.IntPtr;
            > class Tester {
            > public const int TOKEN_QUERY = 0X00000008;
            >
            > const int ERROR_NO_MORE_I TEMS = 259;
            >
            > enum TOKEN_INFORMATI ON_CLASS
            > {
            > TokenUser = 1,
            > TokenGroups,
            > TokenPrivileges ,
            > TokenOwner,
            > TokenPrimaryGro up,
            > TokenDefaultDac l,
            > TokenSource,
            > TokenType,
            > TokenImpersonat ionLevel,
            > TokenStatistics ,
            > TokenRestricted Sids,
            > TokenSessionId
            > }
            >
            > [StructLayout(La youtKind.Sequen tial)]
            > struct TOKEN_USER
            > {
            > public _SID_AND_ATTRIB UTES User;
            > }
            >
            > [StructLayout(La youtKind.Sequen tial)]
            > public struct _SID_AND_ATTRIB UTES
            > {
            > public IntPtr Sid;
            > public int Attributes;
            > }
            > [DllImport("adva pi32")]
            > static extern bool OpenProcessToke n(
            > HANDLE ProcessHandle, // handle to process
            > int DesiredAccess, // desired access to process
            > ref IntPtr TokenHandle // handle to open access token
            > );
            >
            > [DllImport("kern el32")]
            > static extern HANDLE GetCurrentProce ss();
            >
            > [DllImport("adva pi32", CharSet=CharSet .Auto)]
            > static extern bool GetTokenInforma tion(
            > HANDLE hToken,
            > TOKEN_INFORMATI ON_CLASS tokenInfoClass,
            > IntPtr TokenInformatio n,
            > int tokeInfoLength,
            > ref int reqLength);
            >
            > [DllImport("kern el32")]
            > static extern bool CloseHandle(HAN DLE handle);
            >
            > [DllImport("adva pi32", CharSet=CharSet .Auto)]
            > static extern bool LookupAccountSi d
            > (
            > [In,MarshalAs(Un managedType.LPT Str)] string lpSystemName, // name of[/color]
            local or remote computer[color=blue]
            > IntPtr pSid, // security identifier
            > StringBuilder Account, // account name buffer
            > ref int cbName, // size of account name buffer
            > StringBuilder DomainName, // domain name
            > ref int cbDomainName, // size of domain name buffer
            > ref int peUse // SID type
            > // ref _SID_NAME_USE peUse // SID type
            > );
            >
            > [DllImport("adva pi32", CharSet=CharSet .Auto)]
            > static extern bool ConvertSidToStr ingSid(
            > IntPtr pSID,
            > [In,Out,MarshalA s(UnmanagedType .LPTStr)] ref string pStringSid);
            >
            > public static void Main() {
            > string processName = Process.GetCurr entProcess().Pr ocessName;
            > Process[] myProcesses = Process.GetProc essesByName(pro cessName);
            > if(myProcesses. Length == 0)
            > Console.WriteLi ne("Could not find notepad processes on remote[/color]
            machine");[color=blue]
            > foreach(Process myProcess in myProcesses)
            > {
            > Console.Write(" Process Name : " + myProcess.Proce ssName + "[/color]
            Process ID : "[color=blue]
            > + myProcess.Id + " MachineName : " + myProcess.Machi neName + "\n");
            > DumpUserInfo(my Process.Handle) ;
            > }
            > }
            >
            > static void DumpUserInfo(HA NDLE pToken)
            > {
            > int Access = TOKEN_QUERY;
            > StringBuilder sb = new StringBuilder() ;
            > sb.AppendFormat ("\nToken dump performed on {0}\n\n", DateTime.Now);
            > HANDLE procToken = IntPtr.Zero;
            > if ( OpenProcessToke n( pToken, Access, ref procToken ) )
            > {
            > sb.Append("Proc ess Token:\n");
            > sb.Append(Perfo rmDump(procToke n));
            > CloseHandle(pro cToken);
            > }
            > Console.WriteLi ne(sb.ToString( ));
            > }
            > static StringBuilder PerformDump(HAN DLE token)
            > {
            > StringBuilder sb = new StringBuilder() ;
            > TOKEN_USER tokUser;
            > const int bufLength = 256;
            > IntPtr tu = Marshal.AllocHG lobal( bufLength );
            > int cb = bufLength;
            > GetTokenInforma tion( token, TOKEN_INFORMATI ON_CLASS.TokenU ser, tu, cb,[/color]
            ref cb );[color=blue]
            > tokUser = (TOKEN_USER) Marshal.PtrToSt ructure(tu, typeof(TOKEN_US ER) );
            > sb.Append(DumpA ccountSid(tokUs er.User.Sid));
            > Marshal.FreeHGl obal( tu );
            > return sb;
            > }
            >
            > static string DumpAccountSid( IntPtr SID)
            > {
            > int cchAccount = 0;
            > int cchDomain = 0;
            > int snu = 0 ;
            > StringBuilder sb = new StringBuilder() ;
            >
            > // Caller allocated buffer
            > StringBuilder Account= null;
            > StringBuilder Domain = null;
            > bool ret = LookupAccountSi d(null, SID, Account, ref cchAccount, Domain,[/color]
            ref cchDomain, ref snu);[color=blue]
            > if ( ret == true )
            > if ( Marshal.GetLast Win32Error() == ERROR_NO_MORE_I TEMS )
            > return "Error";
            > try
            > {
            > Account = new StringBuilder( cchAccount );
            > Domain = new StringBuilder( cchDomain );
            > ret = LookupAccountSi d(null, SID, Account, ref cchAccount, Domain,[/color]
            ref cchDomain, ref snu);[color=blue]
            > if (ret)
            > {
            > sb.Append(Domai n);
            > sb.Append(@"\\" );
            > sb.Append(Accou nt);
            > }
            > else
            > Console.WriteLi ne("logon account (no name) ");
            > }
            > catch (Exception ex)
            > {
            > Console.WriteLi ne(ex.Message);
            > }
            > finally
            > {
            > }
            > string SidString = null;
            > ConvertSidToStr ingSid(SID, ref SidString);
            > sb.Append("\nSI D: ");
            > sb.Append(SidSt ring);
            > return sb.ToString();
            > }
            > }
            > // End of code sample
            >
            > Willy.
            >
            >[/color]


            Comment

            • Mattias Sjögren

              #7
              Re: How to call Win32 Native API GetTokenInforma tion() using C#?

              Vincent,
              [color=blue]
              >I don't know much about VB.NET. Do you have any C# sample code for this?[/color]

              I don't, but try something like this (using most of the defs from
              Willy's post):


              int cb = 0;
              // First call to get buffer size needed
              GetTokenInforma tion( token, TOKEN_INFORMATI ON_CLASS.TokenG roups,
              IntPtr.Zero, 0, ref cb );
              IntPtr tg = Marshal.AllocHG lobal( cb );
              // Second call to actually retrieve data
              GetTokenInforma tion( token, TOKEN_INFORMATI ON_CLASS.TokenG roups, tg,
              cb, ref cb );
              // Read TOKEN_GROUPS.Gr oupCount
              int groupCount = Marshal.ReadInt 32( tg );
              // Read each SID_AND_ATTRIBU TES from TOKEN_GROUPS.Gr oups
              int pSaa = (int)tg + 4;
              for ( int i = 0; i < groupCount; i++ ) {
              _SID_AND_ATTRIB UTES saa = (_SID_AND_ATTRI BUTES)
              Marshal.PtrToSt ructure((IntPtr )pSaa, typeof(_SID_AND _ATTRIBUTES));
              // do stuff with _SID_AND_ATTRIB UTES here
              pSaa += Marshal.SizeOf( typeof(_SID_AND _ATTRIBUTES) );
              }
              ....
              Marshal.FreeHGl obal( tg );



              Mattias

              --
              Mattias Sjögren [MVP] mattias @ mvps.org

              Please reply only to the newsgroup.

              Comment

              • Vincent Nguyen

                #8
                Re: How to call Win32 Native API GetTokenInforma tion() using C#?

                Mattias,

                The sample code worked perfect! Thank you very much for your helps!

                Vincent

                "Mattias Sjögren" <mattias.dont.w ant.spam@mvps.o rg> wrote in message
                news:ePMloqSXDH A.2352@TK2MSFTN GP12.phx.gbl...[color=blue]
                > Vincent,
                >[color=green]
                > >I don't know much about VB.NET. Do you have any C# sample code for this?[/color]
                >
                > I don't, but try something like this (using most of the defs from
                > Willy's post):
                >
                >
                > int cb = 0;
                > // First call to get buffer size needed
                > GetTokenInforma tion( token, TOKEN_INFORMATI ON_CLASS.TokenG roups,
                > IntPtr.Zero, 0, ref cb );
                > IntPtr tg = Marshal.AllocHG lobal( cb );
                > // Second call to actually retrieve data
                > GetTokenInforma tion( token, TOKEN_INFORMATI ON_CLASS.TokenG roups, tg,
                > cb, ref cb );
                > // Read TOKEN_GROUPS.Gr oupCount
                > int groupCount = Marshal.ReadInt 32( tg );
                > // Read each SID_AND_ATTRIBU TES from TOKEN_GROUPS.Gr oups
                > int pSaa = (int)tg + 4;
                > for ( int i = 0; i < groupCount; i++ ) {
                > _SID_AND_ATTRIB UTES saa = (_SID_AND_ATTRI BUTES)
                > Marshal.PtrToSt ructure((IntPtr )pSaa, typeof(_SID_AND _ATTRIBUTES));
                > // do stuff with _SID_AND_ATTRIB UTES here
                > pSaa += Marshal.SizeOf( typeof(_SID_AND _ATTRIBUTES) );
                > }
                > ...
                > Marshal.FreeHGl obal( tg );
                >
                >
                >
                > Mattias
                >
                > --
                > Mattias Sjögren [MVP] mattias @ mvps.org
                > http://www.msjogren.net/dotnet/
                > Please reply only to the newsgroup.[/color]


                Comment

                Working...