473,804 Members | 3,353 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Run as Administrator, then execute something as the user

I'm writing a little program that will run when a user logs in, checks their
password expiration and also installs a piece of monitoring software if
necessary.
The program has to run on Vista so I got my first experience writing for UAC.

I've worked though the signed manifest and all the other little quirky stuff
I have to do to get my app to run as Administrator (System.Directo ryServices
said it required admin rights) and everything is working just dandy.

But, I would also like to map drives for the user as I do this. Problem is
that when I map the drive using the Admin split token privs, it actually maps
the drive for the admin user, not the lower priv user token. So I see that
it works, it reports that it works, even checking the existence of the drive
letter work but the drive letters don't show for the end user.

Now for the weird $50 question.

Is there a way while my program is running under the Admin token to execute
something as the user? Like open a cmd shell and run a simple net use
command?

I have this code running the mapping. Works great on XP, and works under
Vista but I just don't see the drives as the user on Vista. (comments
removed for space)

Dim myProcess As Process = New Process
myProcess.Start Info.FileName = "cmd.exe"
myProcess.Start Info.WindowStyl e = ProcessWindowSt yle.Hidden
myProcess.Start Info.CreateNoWi ndow = True
myProcess.Start Info.Arguments = "/C net use K: \\vail\vmdk /persistent:no"
myProcess.Start ()
myProcess.WaitF orExit(10000)
If System.IO.Direc tory.Exists(str Drive) Then
txtStatus.Text = txtStatus.Text & "->Success "
Else
txtStatus.Text = txtStatus.Text & "->Failed "
End If
Really hoping that made sense....
Aug 15 '08 #1
4 7096
Hmm $50,-- :-)

I have written a class that can solve this problem , i use this class to
write to a locations where normall users do not have access rights


### CLASS CODE ###
'Michel Posseth [MCP] 10-07-2008 , written to run parts of code in another
user context during runtime

Imports System.Security

Imports System.Security .Principal

Imports System.Runtime. InteropServices

Public Class ImpersonateSpec ificUser

Implements IDisposable

Private Const LOGON32_LOGON_I NTERACTIVE As Integer = 2

Private Const LOGON32_PROVIDE R_DEFAULT As Integer = 0

Private impersonationCo ntext As WindowsImperson ationContext

Declare Function LogonUserA Lib "advapi32.d ll" (ByVal lpszUsername As
String, _

ByVal lpszDomain As String, _

ByVal lpszPassword As String, _

ByVal dwLogonType As Integer, _

ByVal dwLogonProvider As Integer, _

ByRef phToken As IntPtr) As Integer

Declare Auto Function DuplicateToken Lib "advapi32.d ll" ( _

ByVal ExistingTokenHa ndle As IntPtr, _

ByVal ImpersonationLe vel As Integer, _

ByRef DuplicateTokenH andle As IntPtr) As Integer

Declare Auto Function RevertToSelf Lib "advapi32.d ll" () As Long

Declare Auto Function CloseHandle Lib "kernel32.d ll" (ByVal handle As
IntPtr) As Long

Public Event eSpecificUserIm personation(ByV al Success As Boolean)

Private _Impersonated As Boolean

''' <summary>

''' Gets or sets a value indicating whether this <see
cref="Impersona teSpecificUser" /is impersonated.

''' </summary>

''' <value><c>tru e</cif impersonated; otherwise, <c>false</c>.</value>

Public Property Impersonated() As Boolean

Get

Return _Impersonated

End Get

Private Set(ByVal value As Boolean)

_Impersonated = value

End Set

End Property

''' <summary>

''' Initializes a new instance of the <see cref="Impersona teSpecificUser" />
class.

''' </summary>

''' <param name="UserName" >Name of the user.</param>

''' <param name="Password" >The password.</param>

''' <param name="Domain">T he domain.</param>

Public Sub New(ByVal UserName As String, ByVal Password As String, ByVal
Domain As String)

If impersonateVali dUser(UserName, Domain, Password) Then

RaiseEvent eSpecificUserIm personation(Tru e)

Else

'Your impersonation failed. Therefore, include a fail-safe mechanism here.

RaiseEvent eSpecificUserIm personation(Fal se)

End If

End Sub

''' <summary>

''' Impersonates the valid user.

''' </summary>

''' <param name="userName" >Name of the user.</param>

''' <param name="domain">T he domain.</param>

''' <param name="password" >The password.</param>

''' <returns></returns>

Private Function impersonateVali dUser(ByVal userName As String, ByVal domain
As String, ByVal password As String) As Boolean

Dim tempWindowsIden tity As WindowsIdentity

Dim token As IntPtr = IntPtr.Zero

Dim tokenDuplicate As IntPtr = IntPtr.Zero

impersonateVali dUser = False

If RevertToSelf() Then

If LogonUserA(user Name, domain, password, LOGON32_LOGON_I NTERACTIVE,
LOGON32_PROVIDE R_DEFAULT, token) <0 Then

If DuplicateToken( token, 2, tokenDuplicate) <0 Then

tempWindowsIden tity = New WindowsIdentity (tokenDuplicate )

impersonationCo ntext = tempWindowsIden tity.Impersonat e()

If Not impersonationCo ntext Is Nothing Then

impersonateVali dUser = True

End If

End If

End If

End If

If Not tokenDuplicate. Equals(IntPtr.Z ero) Then

CloseHandle(tok enDuplicate)

End If

If Not token.Equals(In tPtr.Zero) Then

CloseHandle(tok en)

End If

End Function

''' <summary>

''' Undoes the impersonation.

''' </summary>

Public Sub undoImpersonati on()

impersonationCo ntext.Undo()

Impersonated = False

End Sub

#Region " IDisposable Support "

Private disposedValue As Boolean = False ' To detect redundant calls

' IDisposable

Protected Overridable Sub Dispose(ByVal disposing As Boolean)

If Not Me.disposedValu e Then

If disposing Then

' TODO: free other state (managed objects).

End If

If Impersonated Then 'wees er zeer van dat we weer in een normale context
draaien

undoImpersonati on()

End If

' TODO: free your own state (unmanaged objects).

' TODO: set large fields to null.

End If

Me.disposedValu e = True

End Sub

' This code added by Visual Basic to correctly implement the disposable
pattern.

Public Sub Dispose() Implements IDisposable.Dis pose

' Do not change this code. Put cleanup code in Dispose(ByVal disposing As
Boolean) above.

Dispose(True)

GC.SuppressFina lize(Me)

End Sub

#End Region

''' <summary>

''' Impersonates the specific user_e specific user impersonation.

''' </summary>

''' <param name="Success"> if set to <c>true</c[success].</param>

Private Sub ImpersonateSpec ificUser_eSpeci ficUserImperson ation(ByVal Success
As Boolean) Handles Me.eSpecificUse rImpersonation

Me.Impersonated = Success

End Sub

End Class

### CLASS CODE ###

Usage :

Using UImp As New UserImpersonate .ImpersonateSpe cificUser("User name",
"password", "Domain")

IF UImp.Impersonat ed Then

'all code here that must run in the user context or the method calls to
other procedures

End If

End Using

after this point the code runs in "Normall" modus

HTH
Michel Posseth [MCP]



"Zarborg" <Za*****@discus sions.microsoft .comschreef in bericht
news:F0******** *************** ***********@mic rosoft.com...
I'm writing a little program that will run when a user logs in, checks
their
password expiration and also installs a piece of monitoring software if
necessary.
The program has to run on Vista so I got my first experience writing for
UAC.

I've worked though the signed manifest and all the other little quirky
stuff
I have to do to get my app to run as Administrator
(System.Directo ryServices
said it required admin rights) and everything is working just dandy.

But, I would also like to map drives for the user as I do this. Problem
is
that when I map the drive using the Admin split token privs, it actually
maps
the drive for the admin user, not the lower priv user token. So I see
that
it works, it reports that it works, even checking the existence of the
drive
letter work but the drive letters don't show for the end user.

Now for the weird $50 question.

Is there a way while my program is running under the Admin token to
execute
something as the user? Like open a cmd shell and run a simple net use
command?

I have this code running the mapping. Works great on XP, and works under
Vista but I just don't see the drives as the user on Vista. (comments
removed for space)

Dim myProcess As Process = New Process
myProcess.Start Info.FileName = "cmd.exe"
myProcess.Start Info.WindowStyl e = ProcessWindowSt yle.Hidden
myProcess.Start Info.CreateNoWi ndow = True
myProcess.Start Info.Arguments = "/C net use K: \\vail\vmdk /persistent:no"
myProcess.Start ()
myProcess.WaitF orExit(10000)
If System.IO.Direc tory.Exists(str Drive) Then
txtStatus.Text = txtStatus.Text & "->Success "
Else
txtStatus.Text = txtStatus.Text & "->Failed "
End If
Really hoping that made sense....

Aug 16 '08 #2
Hello Zarborg

Did the previous post solve your problem or can i give you anny further
assistance ?

regards

Michel

"Zarborg" <Za*****@discus sions.microsoft .comschreef in bericht
news:F0******** *************** ***********@mic rosoft.com...
I'm writing a little program that will run when a user logs in, checks
their
password expiration and also installs a piece of monitoring software if
necessary.
The program has to run on Vista so I got my first experience writing for
UAC.

I've worked though the signed manifest and all the other little quirky
stuff
I have to do to get my app to run as Administrator
(System.Directo ryServices
said it required admin rights) and everything is working just dandy.

But, I would also like to map drives for the user as I do this. Problem
is
that when I map the drive using the Admin split token privs, it actually
maps
the drive for the admin user, not the lower priv user token. So I see
that
it works, it reports that it works, even checking the existence of the
drive
letter work but the drive letters don't show for the end user.

Now for the weird $50 question.

Is there a way while my program is running under the Admin token to
execute
something as the user? Like open a cmd shell and run a simple net use
command?

I have this code running the mapping. Works great on XP, and works under
Vista but I just don't see the drives as the user on Vista. (comments
removed for space)

Dim myProcess As Process = New Process
myProcess.Start Info.FileName = "cmd.exe"
myProcess.Start Info.WindowStyl e = ProcessWindowSt yle.Hidden
myProcess.Start Info.CreateNoWi ndow = True
myProcess.Start Info.Arguments = "/C net use K: \\vail\vmdk /persistent:no"
myProcess.Start ()
myProcess.WaitF orExit(10000)
If System.IO.Direc tory.Exists(str Drive) Then
txtStatus.Text = txtStatus.Text & "->Success "
Else
txtStatus.Text = txtStatus.Text & "->Failed "
End If
Really hoping that made sense....

Aug 24 '08 #3
Just getting a chance to work on this one again, got sidetracked with having
to install SCCM, SCOM, SharePoint 2007 integrated with Report Server 2005 and
2 brand new SQL servers. Doh!

I'll update again with either yea or nea next week. Thanks for the class btw!

"Michel Posseth [MCP]" wrote:
Hello Zarborg

Did the previous post solve your problem or can i give you anny further
assistance ?
Sep 5 '08 #4
Oh, but I do have a question on the code though.

Because this is running as the user already, just under their admin level
token I don't have access to their password, nor would I want them to have to
enter it again during the login process. I'm going to look at this code to
see if I can get it to impersonate the non-admin token of the currently
logged in user, but if you knew how already that would be swell.

-Z

"Michel Posseth [MCP]" wrote:
Hello Zarborg

Did the previous post solve your problem or can i give you anny further
assistance ?
Sep 5 '08 #5

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

Similar topics

0
1272
by: *no spam* | last post by:
I've got Visual Studio.Net 2002, IIs, MSDE and SQL Web Administrator running on XP Prof SP2. When I try to execute the SQL Web Administrator (SWA), it first brings up the SWA Dialog Box. I check IIs, click START and the Microsoft Development Environment pops up (?!) I can see my MSDE server in the Server Explorer window, but I can't do things like assign or change user accounts. Is this the way the SWA is supposed to work under XP? ...
0
1185
by: Joe | last post by:
Hello: I have these tables where there's data that (apparentely) can only be seen when logged as Administrator on Windows 2000 and XP. This didn't happen before, and I think some security patch downloaded by "windows update" made some changes that suddenly caused this. I prefer to use my computer logged as an average user, but this has now become a problem. I've tried to change the permissions for the database and tables from the
2
2922
by: Simple Java Drinker | last post by:
I decided to reinstall the Windows XP on my computer by using the Repair Option. After typing "R" as required I am requested to input an administrator password. The problem is that no administrator user or password has ever been created and intalled in my computer. I am using Windows XP Professional OEM version, SP2, dot net one, security updates, Java. After shutdown and restarting from Windows CD the screen present the options to...
6
6127
by: Philip Wagenaar | last post by:
What is the best way to create a local user on the machine with administrator rights? I have problems with my code on machines that have password policy. The problem is that when the user is created there is no password, and password policy is set to min 7 chars or something. So the code only works if I turn of group policy. Can I create a user with pass (and even add him to administrators group) in one line/action? My code: Private...
1
3847
by: Daniel | last post by:
what permissions does a windows service need to execute another process? System.Diagnostics.Process process = System.Diagnostics.Process.Start(info); just local administrator? any specific permitions?
3
7947
by: W C Hull | last post by:
We have a request from Auditing to modify the password an a local workstation administrative account every 90 days. We are developing two programs - a VB6 GUI program that will allow the administrative support person to enter a new password into an App and have that encrypted password saved in a text file. The second part is a VB6 program that only is a command line program that will open the password text file, read the encrypted...
5
1975
by: sawilla | last post by:
First, I'm new to Python. I'm getting and error when I run Python 2.5.2 as a regular user in Vista but not when I run Python as an administrator. For example, if I type "import numpy" after I launch python from an adminstrator-privileged command window it loads fine. However, from a regular-user command window I get: Traceback (most recent call last): File "<stdin>", line 1, in <module>
5
4737
by: nagar | last post by:
I'm using the Process.Start method to launch an application from C#. How can I launch the App as Administrator in Windows Vista? Thanks. Andrea
2
2818
by: Scott | last post by:
Attempting to install WCF service on stand alone 2003 server as a admin user (not administrator but user "WCF" i.e user added to local admin group). It fails with user error: The description for Event ID ( 11001 ) in Source ( MsiInstaller ) cannot be found. The local computer may not have the necessary registry information or message DLL files to display messages from a remote computer. You may be able to use the /AUXSOURCE= flag to...
0
9591
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10594
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10343
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10331
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7631
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6861
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5529
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5667
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3831
muto222
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.