473,480 Members | 1,873 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Using OpenProcessToken

Hi,

I am trying to get a usertoken from a particular process running on the
computer, from a Windows Service to do a Windows group membership of the
user running that process. I was planning to use a API call to
OpenProcessToken and use the Tokenhandle retrieved to build a
WindowsIdentity object and do a access check on.

Has anyone done this before, and can advise if this would work, and if so
possible post a sample on how to do the API call and get the Token handle ?

Many thanks

Niclas
Mar 3 '06 #1
2 24935

"Niclas" <li*************@hotmail.com> wrote in message
news:%2****************@TK2MSFTNGP14.phx.gbl...
| Hi,
|
| I am trying to get a usertoken from a particular process running on the
| computer, from a Windows Service to do a Windows group membership of the
| user running that process. I was planning to use a API call to
| OpenProcessToken and use the Tokenhandle retrieved to build a
| WindowsIdentity object and do a access check on.
|
| Has anyone done this before, and can advise if this would work, and if so
| possible post a sample on how to do the API call and get the Token handle
?
|
| Many thanks
|
| Niclas
|
|
Yes, it's possible provided you are running this with appropriate
privileges, that is as SYSTEM to begin with.
Herewith a small sample that shows how to do.

using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Diagnostics;
using System.Security;
using System.Security.Principal;
namespace TestSecurity
{
class Tester
{

[DllImport("advapi32", SetLastError=true),
SuppressUnmanagedCodeSecurityAttribute]
static extern int OpenProcessToken(
System.IntPtr ProcessHandle, // handle to process
int DesiredAccess, // desired access to process
ref IntPtr TokenHandle // handle to open access token
);

[DllImport("kernel32", SetLastError=true),
SuppressUnmanagedCodeSecurityAttribute]
static extern bool CloseHandle(IntPtr handle);
[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public extern static bool DuplicateToken(IntPtr ExistingTokenHandle,
int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);

public const int TOKEN_DUPLICATE = 2;
public const int TOKEN_QUERY = 0X00000008;
public const int TOKEN_IMPERSONATE = 0X00000004;

static void Main()
{
IntPtr hToken = IntPtr.Zero;
IntPtr dupeTokenHandle = IntPtr.Zero;
// For simplicity I'm using the PID of System here
Process proc = Process.GetProcessById(4);
if (OpenProcessToken(proc.Handle,
TOKEN_QUERY|TOKEN_IMPERSONATE|TOKEN_DUPLICATE,
ref hToken) != 0)
{
WindowsIdentity newId = new WindowsIdentity(hToken);
Console.WriteLine(newId.Owner );
try
{
const int SecurityImpersonation = 2;
dupeTokenHandle = DupeToken(hToken,
SecurityImpersonation);
if(IntPtr.Zero == dupeTokenHandle)
{
string s = String.Format("Dup failed {0}, privilege not held",
Marshal.GetLastWin32Error());
throw new Exception(s);
}

WindowsImpersonationContext impersonatedUser =
newId.Impersonate();
IntPtr accountToken = WindowsIdentity.GetCurrent().Token;
Console.WriteLine( "Token number is: " + accountToken.ToString());
Console.WriteLine( "Windows ID Name is: " +
WindowsIdentity.GetCurrent().Name);
}
finally
{
CloseHandle(hToken);
}
}
else
{
string s = String.Format("OpenProcess Failed {0}, privilege not
held", Marshal.GetLastWin32Error());
throw new Exception(s);
}
}
static IntPtr DupeToken(IntPtr token, int Level)
{
IntPtr dupeTokenHandle = IntPtr.Zero;
bool retVal = DuplicateToken(token, Level, ref dupeTokenHandle);
return dupeTokenHandle;
}
}
}

Willy.

Mar 3 '06 #2
Willy,

Code works excellent. Many thanks for your help !

Niclas

"Willy Denoyette [MVP]" <wi*************@telenet.be> wrote in message
news:eZ*************@TK2MSFTNGP15.phx.gbl...

"Niclas" <li*************@hotmail.com> wrote in message
news:%2****************@TK2MSFTNGP14.phx.gbl...
| Hi,
|
| I am trying to get a usertoken from a particular process running on the
| computer, from a Windows Service to do a Windows group membership of the
| user running that process. I was planning to use a API call to
| OpenProcessToken and use the Tokenhandle retrieved to build a
| WindowsIdentity object and do a access check on.
|
| Has anyone done this before, and can advise if this would work, and if
so
| possible post a sample on how to do the API call and get the Token
handle
?
|
| Many thanks
|
| Niclas
|
|
Yes, it's possible provided you are running this with appropriate
privileges, that is as SYSTEM to begin with.
Herewith a small sample that shows how to do.

using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Diagnostics;
using System.Security;
using System.Security.Principal;
namespace TestSecurity
{
class Tester
{

[DllImport("advapi32", SetLastError=true),
SuppressUnmanagedCodeSecurityAttribute]
static extern int OpenProcessToken(
System.IntPtr ProcessHandle, // handle to process
int DesiredAccess, // desired access to process
ref IntPtr TokenHandle // handle to open access token
);

[DllImport("kernel32", SetLastError=true),
SuppressUnmanagedCodeSecurityAttribute]
static extern bool CloseHandle(IntPtr handle);
[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public extern static bool DuplicateToken(IntPtr ExistingTokenHandle,
int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);

public const int TOKEN_DUPLICATE = 2;
public const int TOKEN_QUERY = 0X00000008;
public const int TOKEN_IMPERSONATE = 0X00000004;

static void Main()
{
IntPtr hToken = IntPtr.Zero;
IntPtr dupeTokenHandle = IntPtr.Zero;
// For simplicity I'm using the PID of System here
Process proc = Process.GetProcessById(4);
if (OpenProcessToken(proc.Handle,
TOKEN_QUERY|TOKEN_IMPERSONATE|TOKEN_DUPLICATE,
ref hToken) != 0)
{
WindowsIdentity newId = new WindowsIdentity(hToken);
Console.WriteLine(newId.Owner );
try
{
const int SecurityImpersonation = 2;
dupeTokenHandle = DupeToken(hToken,
SecurityImpersonation);
if(IntPtr.Zero == dupeTokenHandle)
{
string s = String.Format("Dup failed {0}, privilege not held",
Marshal.GetLastWin32Error());
throw new Exception(s);
}

WindowsImpersonationContext impersonatedUser =
newId.Impersonate();
IntPtr accountToken = WindowsIdentity.GetCurrent().Token;
Console.WriteLine( "Token number is: " +
accountToken.ToString());
Console.WriteLine( "Windows ID Name is: " +
WindowsIdentity.GetCurrent().Name);
}
finally
{
CloseHandle(hToken);
}
}
else
{
string s = String.Format("OpenProcess Failed {0}, privilege not
held", Marshal.GetLastWin32Error());
throw new Exception(s);
}
}
static IntPtr DupeToken(IntPtr token, int Level)
{
IntPtr dupeTokenHandle = IntPtr.Zero;
bool retVal = DuplicateToken(token, Level, ref dupeTokenHandle);
return dupeTokenHandle;
}
}
}

Willy.

Mar 3 '06 #3

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

Similar topics

4
6380
by: Pete Fong | last post by:
Dear all, I am a beginner with Python. I want to write a program as "runas" in Windows XP. But I have got the following error: File...
5
5677
by: Enos Meroka | last post by:
Hallo, I am a student doing my project in the university.. I have been trying to compile the program using HP -UX aCC compiler, however I keep on getting the following errors. ...
7
29299
by: Vincent Nguyen | last post by:
Hi, Does anyone know how call Win32 native API GetTokenInformation() by using C#? Any sample code would be helpful. Thanks! Vincent
4
42183
by: Mohammed Abdel-Razzak | last post by:
Dear sirs I want to know how can I shutdown or restart my computer using C# Also I want to know how can I open any windows program using C# (EX: opening the windows calculator from my...
1
4893
by: Liang Yitao | last post by:
I used DllImport() to load the function OpenProcessToken () in advapi32.dll, and then called it in my button click event. But the function always returns false. I got the error code it left...
3
4538
by: Liang Yitao | last post by:
I used DllImport() to load the function LookupPrivilegeValue() in advapi32.dll, and then called it in my button click event. But the function always returns false. I got the error code it left...
2
11385
by: Brian Worth | last post by:
I have just upgraded from VB 4.0 to VB .NET 2002. One program under VB 4.0 was able to shut down or restart the (windows XP) machine using a series of API calls. (Getlasterror, GetCurrentProcess,...
1
2162
by: asnowfall | last post by:
I want to get the list of privilages set on process token using C#. Please let me know. Thanks Ramesh
0
1734
by: jg007 | last post by:
I have been trying to convert some C# code to VB but am getting stuck i've Tried everyting and spent ages on google but keep on getting Error 998 which I checked and is ERROR_NOACCESS when I check...
0
7055
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7103
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...
1
6758
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7010
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
5362
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,...
1
4799
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...
0
4499
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
1311
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
572
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.