473,546 Members | 2,205 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using OpenProcessToke n

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
OpenProcessToke n 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 24971

"Niclas" <li************ *@hotmail.com> wrote in message
news:%2******** ********@TK2MSF TNGP14.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
| OpenProcessToke n 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.Collecti ons.Generic;
using System.Diagnost ics;
using System.Security ;
using System.Security .Principal;
namespace TestSecurity
{
class Tester
{

[DllImport("adva pi32", SetLastError=tr ue),
SuppressUnmanag edCodeSecurityA ttribute]
static extern int OpenProcessToke n(
System.IntPtr ProcessHandle, // handle to process
int DesiredAccess, // desired access to process
ref IntPtr TokenHandle // handle to open access token
);

[DllImport("kern el32", SetLastError=tr ue),
SuppressUnmanag edCodeSecurityA ttribute]
static extern bool CloseHandle(Int Ptr handle);
[DllImport("adva pi32.dll", CharSet=CharSet .Auto, SetLastError=tr ue)]
public extern static bool DuplicateToken( IntPtr ExistingTokenHa ndle,
int SECURITY_IMPERS ONATION_LEVEL, ref IntPtr DuplicateTokenH andle);

public const int TOKEN_DUPLICATE = 2;
public const int TOKEN_QUERY = 0X00000008;
public const int TOKEN_IMPERSONA TE = 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.GetProc essById(4);
if (OpenProcessTok en(proc.Handle,
TOKEN_QUERY|TOK EN_IMPERSONATE| TOKEN_DUPLICATE ,
ref hToken) != 0)
{
WindowsIdentity newId = new WindowsIdentity (hToken);
Console.WriteLi ne(newId.Owner );
try
{
const int SecurityImperso nation = 2;
dupeTokenHandle = DupeToken(hToke n,
SecurityImperso nation);
if(IntPtr.Zero == dupeTokenHandle )
{
string s = String.Format(" Dup failed {0}, privilege not held",
Marshal.GetLast Win32Error());
throw new Exception(s);
}

WindowsImperson ationContext impersonatedUse r =
newId.Impersona te();
IntPtr accountToken = WindowsIdentity .GetCurrent().T oken;
Console.WriteLi ne( "Token number is: " + accountToken.To String());
Console.WriteLi ne( "Windows ID Name is: " +
WindowsIdentity .GetCurrent().N ame);
}
finally
{
CloseHandle(hTo ken);
}
}
else
{
string s = String.Format(" OpenProcess Failed {0}, privilege not
held", Marshal.GetLast Win32Error());
throw new Exception(s);
}
}
static IntPtr DupeToken(IntPt r 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******** *****@TK2MSFTNG P15.phx.gbl...

"Niclas" <li************ *@hotmail.com> wrote in message
news:%2******** ********@TK2MSF TNGP14.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
| OpenProcessToke n 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.Collecti ons.Generic;
using System.Diagnost ics;
using System.Security ;
using System.Security .Principal;
namespace TestSecurity
{
class Tester
{

[DllImport("adva pi32", SetLastError=tr ue),
SuppressUnmanag edCodeSecurityA ttribute]
static extern int OpenProcessToke n(
System.IntPtr ProcessHandle, // handle to process
int DesiredAccess, // desired access to process
ref IntPtr TokenHandle // handle to open access token
);

[DllImport("kern el32", SetLastError=tr ue),
SuppressUnmanag edCodeSecurityA ttribute]
static extern bool CloseHandle(Int Ptr handle);
[DllImport("adva pi32.dll", CharSet=CharSet .Auto, SetLastError=tr ue)]
public extern static bool DuplicateToken( IntPtr ExistingTokenHa ndle,
int SECURITY_IMPERS ONATION_LEVEL, ref IntPtr DuplicateTokenH andle);

public const int TOKEN_DUPLICATE = 2;
public const int TOKEN_QUERY = 0X00000008;
public const int TOKEN_IMPERSONA TE = 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.GetProc essById(4);
if (OpenProcessTok en(proc.Handle,
TOKEN_QUERY|TOK EN_IMPERSONATE| TOKEN_DUPLICATE ,
ref hToken) != 0)
{
WindowsIdentity newId = new WindowsIdentity (hToken);
Console.WriteLi ne(newId.Owner );
try
{
const int SecurityImperso nation = 2;
dupeTokenHandle = DupeToken(hToke n,
SecurityImperso nation);
if(IntPtr.Zero == dupeTokenHandle )
{
string s = String.Format(" Dup failed {0}, privilege not held",
Marshal.GetLast Win32Error());
throw new Exception(s);
}

WindowsImperson ationContext impersonatedUse r =
newId.Impersona te();
IntPtr accountToken = WindowsIdentity .GetCurrent().T oken;
Console.WriteLi ne( "Token number is: " +
accountToken.To String());
Console.WriteLi ne( "Windows ID Name is: " +
WindowsIdentity .GetCurrent().N ame);
}
finally
{
CloseHandle(hTo ken);
}
}
else
{
string s = String.Format(" OpenProcess Failed {0}, privilege not
held", Marshal.GetLast Win32Error());
throw new Exception(s);
}
}
static IntPtr DupeToken(IntPt r 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
6390
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 "C:\Python23\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\python\Script1.py", line 30, in ? File "C:\python\Script1.py",...
5
5693
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. ================================================================= Error 19: "CORBAManagerMessages.h", line 4 # Unexpected 'std'. using std::string; ^^^
7
29314
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
42206
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 application) thanks Mohammed
1
4908
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 through GetLastError() function and the result is "998" which means, in the system error code in MSDN, "Invalid access to memory location." I don't know...
3
4544
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 through GetLastError() function and the result is "997" which means, in the system error code in MSDN, "Overlapped I/O operation is in progress." I...
2
11391
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, OpenProcessToken, LookupPrivilegeValue, AdjustTokenPrivilegese, ExitWindowsEx. I am trying to avoid using any API calls if possible and to use...
1
2177
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
1749
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 the last dll error although the c# code works fine, can anybody help please Public Declare Function OpenProcessToken Lib "advapi32.dll" _ (ByVal...
0
7698
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7947
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7794
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5361
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3492
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3472
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1922
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 we have to send another system
1
1046
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
747
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.