473,406 Members | 2,847 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

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

Hi,

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

Vincent
Nov 15 '05 #1
7 29270
Vincent,
Does anyone know how call Win32 native API GetTokenInformation() by using
C#? Any sample code would be helpful. Thanks!


What kind of information are you going to retrieve with it, i.e which
TOKEN_INFORMATION_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.
Nov 15 '05 #2
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" <ma********************@mvps.org> wrote in message
news:OO**************@tk2msftngp13.phx.gbl...
Vincent,
Does anyone know how call Win32 native API GetTokenInformation() by using
C#? Any sample code would be helpful. Thanks!


What kind of information are you going to retrieve with it, i.e which
TOKEN_INFORMATION_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.

Nov 15 '05 #3
Vincent,
I want to retrieve the access tokens for a user, and I want to pass in the
TOKEN_GROUPS. Thanks for the reply!


See if this helps you get it working

http://groups.google.com/groups?thre...%40tkmsftngp11
http://www.dotnetinterop.com/faq/?q=...leLengthStruct

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/
Please reply only to the newsgroup.
Nov 15 '05 #4
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.Diagnostics;

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

const int ERROR_NO_MORE_ITEMS = 259;

enum TOKEN_INFORMATION_CLASS
{
TokenUser = 1,
TokenGroups,
TokenPrivileges,
TokenOwner,
TokenPrimaryGroup,
TokenDefaultDacl,
TokenSource,
TokenType,
TokenImpersonationLevel,
TokenStatistics,
TokenRestrictedSids,
TokenSessionId
}

[StructLayout(LayoutKind.Sequential)]
struct TOKEN_USER
{
public _SID_AND_ATTRIBUTES User;
}

[StructLayout(LayoutKind.Sequential)]
public struct _SID_AND_ATTRIBUTES
{
public IntPtr Sid;
public int Attributes;
}
[DllImport("advapi32")]
static extern bool OpenProcessToken(
HANDLE ProcessHandle, // handle to process
int DesiredAccess, // desired access to process
ref IntPtr TokenHandle // handle to open access token
);

[DllImport("kernel32")]
static extern HANDLE GetCurrentProcess();

[DllImport("advapi32", CharSet=CharSet.Auto)]
static extern bool GetTokenInformation(
HANDLE hToken,
TOKEN_INFORMATION_CLASS tokenInfoClass,
IntPtr TokenInformation,
int tokeInfoLength,
ref int reqLength);

[DllImport("kernel32")]
static extern bool CloseHandle(HANDLE handle);

[DllImport("advapi32", CharSet=CharSet.Auto)]
static extern bool LookupAccountSid
(
[In,MarshalAs(UnmanagedType.LPTStr)] 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("advapi32", CharSet=CharSet.Auto)]
static extern bool ConvertSidToStringSid(
IntPtr pSID,
[In,Out,MarshalAs(UnmanagedType.LPTStr)] ref string pStringSid);

public static void Main() {
string processName = Process.GetCurrentProcess().ProcessName;
Process[] myProcesses = Process.GetProcessesByName(processName);
if(myProcesses.Length == 0)
Console.WriteLine("Could not find notepad processes on remote machine");
foreach(Process myProcess in myProcesses)
{
Console.Write("Process Name : " + myProcess.ProcessName + " Process ID : "
+ myProcess.Id + " MachineName : " + myProcess.MachineName + "\n");
DumpUserInfo(myProcess.Handle);
}
}

static void DumpUserInfo(HANDLE 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 ( OpenProcessToken( pToken, Access, ref procToken ) )
{
sb.Append("Process Token:\n");
sb.Append(PerformDump(procToken));
CloseHandle(procToken);
}
Console.WriteLine(sb.ToString());
}
static StringBuilder PerformDump(HANDLE token)
{
StringBuilder sb = new StringBuilder();
TOKEN_USER tokUser;
const int bufLength = 256;
IntPtr tu = Marshal.AllocHGlobal( bufLength );
int cb = bufLength;
GetTokenInformation( token, TOKEN_INFORMATION_CLASS.TokenUser, tu, cb, ref cb );
tokUser = (TOKEN_USER) Marshal.PtrToStructure(tu, typeof(TOKEN_USER) );
sb.Append(DumpAccountSid(tokUser.User.Sid));
Marshal.FreeHGlobal( 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 = LookupAccountSid(null, SID, Account, ref cchAccount, Domain, ref cchDomain, ref snu);
if ( ret == true )
if ( Marshal.GetLastWin32Error() == ERROR_NO_MORE_ITEMS )
return "Error";
try
{
Account = new StringBuilder( cchAccount );
Domain = new StringBuilder( cchDomain );
ret = LookupAccountSid(null, SID, Account, ref cchAccount, Domain, ref cchDomain, ref snu);
if (ret)
{
sb.Append(Domain);
sb.Append(@"\\");
sb.Append(Account);
}
else
Console.WriteLine("logon account (no name) ");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
}
string SidString = null;
ConvertSidToStringSid(SID, ref SidString);
sb.Append("\nSID: ");
sb.Append(SidString);
return sb.ToString();
}
}
// End of code sample

Willy.
Nov 15 '05 #5
Willy,

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

Vincent

"Willy Denoyette [MVP]" <wi*************@skynet.be> wrote in message
news:uc**************@TK2MSFTNGP09.phx.gbl...
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.Diagnostics;

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

const int ERROR_NO_MORE_ITEMS = 259;

enum TOKEN_INFORMATION_CLASS
{
TokenUser = 1,
TokenGroups,
TokenPrivileges,
TokenOwner,
TokenPrimaryGroup,
TokenDefaultDacl,
TokenSource,
TokenType,
TokenImpersonationLevel,
TokenStatistics,
TokenRestrictedSids,
TokenSessionId
}

[StructLayout(LayoutKind.Sequential)]
struct TOKEN_USER
{
public _SID_AND_ATTRIBUTES User;
}

[StructLayout(LayoutKind.Sequential)]
public struct _SID_AND_ATTRIBUTES
{
public IntPtr Sid;
public int Attributes;
}
[DllImport("advapi32")]
static extern bool OpenProcessToken(
HANDLE ProcessHandle, // handle to process
int DesiredAccess, // desired access to process
ref IntPtr TokenHandle // handle to open access token
);

[DllImport("kernel32")]
static extern HANDLE GetCurrentProcess();

[DllImport("advapi32", CharSet=CharSet.Auto)]
static extern bool GetTokenInformation(
HANDLE hToken,
TOKEN_INFORMATION_CLASS tokenInfoClass,
IntPtr TokenInformation,
int tokeInfoLength,
ref int reqLength);

[DllImport("kernel32")]
static extern bool CloseHandle(HANDLE handle);

[DllImport("advapi32", CharSet=CharSet.Auto)]
static extern bool LookupAccountSid
(
[In,MarshalAs(UnmanagedType.LPTStr)] 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("advapi32", CharSet=CharSet.Auto)]
static extern bool ConvertSidToStringSid(
IntPtr pSID,
[In,Out,MarshalAs(UnmanagedType.LPTStr)] ref string pStringSid);

public static void Main() {
string processName = Process.GetCurrentProcess().ProcessName;
Process[] myProcesses = Process.GetProcessesByName(processName);
if(myProcesses.Length == 0)
Console.WriteLine("Could not find notepad processes on remote machine"); foreach(Process myProcess in myProcesses)
{
Console.Write("Process Name : " + myProcess.ProcessName + " Process ID : " + myProcess.Id + " MachineName : " + myProcess.MachineName + "\n");
DumpUserInfo(myProcess.Handle);
}
}

static void DumpUserInfo(HANDLE 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 ( OpenProcessToken( pToken, Access, ref procToken ) )
{
sb.Append("Process Token:\n");
sb.Append(PerformDump(procToken));
CloseHandle(procToken);
}
Console.WriteLine(sb.ToString());
}
static StringBuilder PerformDump(HANDLE token)
{
StringBuilder sb = new StringBuilder();
TOKEN_USER tokUser;
const int bufLength = 256;
IntPtr tu = Marshal.AllocHGlobal( bufLength );
int cb = bufLength;
GetTokenInformation( token, TOKEN_INFORMATION_CLASS.TokenUser, tu, cb, ref cb ); tokUser = (TOKEN_USER) Marshal.PtrToStructure(tu, typeof(TOKEN_USER) );
sb.Append(DumpAccountSid(tokUser.User.Sid));
Marshal.FreeHGlobal( 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 = LookupAccountSid(null, SID, Account, ref cchAccount, Domain, ref cchDomain, ref snu); if ( ret == true )
if ( Marshal.GetLastWin32Error() == ERROR_NO_MORE_ITEMS )
return "Error";
try
{
Account = new StringBuilder( cchAccount );
Domain = new StringBuilder( cchDomain );
ret = LookupAccountSid(null, SID, Account, ref cchAccount, Domain, ref cchDomain, ref snu); if (ret)
{
sb.Append(Domain);
sb.Append(@"\\");
sb.Append(Account);
}
else
Console.WriteLine("logon account (no name) ");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
}
string SidString = null;
ConvertSidToStringSid(SID, ref SidString);
sb.Append("\nSID: ");
sb.Append(SidString);
return sb.ToString();
}
}
// End of code sample

Willy.

Nov 15 '05 #6
Vincent,
I don't know much about VB.NET. Do you have any C# sample code for this?


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
GetTokenInformation( token, TOKEN_INFORMATION_CLASS.TokenGroups,
IntPtr.Zero, 0, ref cb );
IntPtr tg = Marshal.AllocHGlobal( cb );
// Second call to actually retrieve data
GetTokenInformation( token, TOKEN_INFORMATION_CLASS.TokenGroups, tg,
cb, ref cb );
// Read TOKEN_GROUPS.GroupCount
int groupCount = Marshal.ReadInt32( tg );
// Read each SID_AND_ATTRIBUTES from TOKEN_GROUPS.Groups
int pSaa = (int)tg + 4;
for ( int i = 0; i < groupCount; i++ ) {
_SID_AND_ATTRIBUTES saa = (_SID_AND_ATTRIBUTES)
Marshal.PtrToStructure((IntPtr)pSaa, typeof(_SID_AND_ATTRIBUTES));
// do stuff with _SID_AND_ATTRIBUTES here
pSaa += Marshal.SizeOf( typeof(_SID_AND_ATTRIBUTES) );
}
....
Marshal.FreeHGlobal( tg );

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/
Please reply only to the newsgroup.
Nov 15 '05 #7
Mattias,

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

Vincent

"Mattias Sjögren" <ma********************@mvps.org> wrote in message
news:eP**************@TK2MSFTNGP12.phx.gbl...
Vincent,
I don't know much about VB.NET. Do you have any C# sample code for this?


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
GetTokenInformation( token, TOKEN_INFORMATION_CLASS.TokenGroups,
IntPtr.Zero, 0, ref cb );
IntPtr tg = Marshal.AllocHGlobal( cb );
// Second call to actually retrieve data
GetTokenInformation( token, TOKEN_INFORMATION_CLASS.TokenGroups, tg,
cb, ref cb );
// Read TOKEN_GROUPS.GroupCount
int groupCount = Marshal.ReadInt32( tg );
// Read each SID_AND_ATTRIBUTES from TOKEN_GROUPS.Groups
int pSaa = (int)tg + 4;
for ( int i = 0; i < groupCount; i++ ) {
_SID_AND_ATTRIBUTES saa = (_SID_AND_ATTRIBUTES)
Marshal.PtrToStructure((IntPtr)pSaa, typeof(_SID_AND_ATTRIBUTES));
// do stuff with _SID_AND_ATTRIBUTES here
pSaa += Marshal.SizeOf( typeof(_SID_AND_ATTRIBUTES) );
}
...
Marshal.FreeHGlobal( tg );

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/
Please reply only to the newsgroup.

Nov 15 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: sunil s via DotNetMonster.com | last post by:
Hi, I've got a native C++ app which calls a 3rd parth .NET DLL using the LoadLibrary/GetProcAddress functions. This works fine when the DLL is located in the app directory, but if I move it out...
4
by: Marek Lewczuk | last post by:
I'm looking at "TODO list for PostgreSQL" and "Fix upper()/lower() to work for multibyte encodings" has no dash (-) -- so it won't be made in 7.5 ? Another question is about WIN32 native release...
2
by: Chi Tang | last post by:
Hi, Does anybody know how to call a unmanaged win32 dll function from a .NET C# managed application? Do I need to write a managed C++ dll or a COM dll which become a server of .net C# app or I...
1
by: John Lee | last post by:
Hi, I have two web services and they are setup as "Integrated Windows Authentication" only and they are both assigned to application pool with Domain Account. I can use ws.Credentials =...
3
by: bb | last post by:
I have a windows network device driver written in c++ and a user interface im porting to c#, my problem is i dont seem to be getting notified of the event calls from the driver to the c# app im...
11
by: dolphin | last post by:
Hi All! I have a question that how to call a function just using a string. For example There is a .cpp file named a.cpp.There are some functions::fun1() fun2() fun3(). I have another fucntion...
7
by: Timothy Madden | last post by:
Hello I would like to use php-cli as a sort of shell scripting language or generic scripting language. I have php 5.2 on WindowsXP and I would like to call Win32 API functions like...
1
by: tess1243 | last post by:
How to call a web service using its url from a Windows application using C#? Any Sample code please??
4
by: Naga Prakash | last post by:
Hello All, I'm very much new to PERL scripting. I'm the admin for an online tool which has some Perl scripts. And i have a problem executing one of the script. I'm just writing a problematic code in...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.