473,663 Members | 2,705 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

VB.net impersonation / credentials issues

HI guys,

I'm relatively new to the .net development realm. I am creating an
application in vb.net to monitor services on remote servers.

The application works great when I am logged in and using it - I am a
Domain Admin, and as a result a local admin on the remote computers.
However when I try to run the application as a standard domain user I
receive a priviledges error.

I have attempted to implement impersonation, using credentials
supplied by the application under 'My.Settings' however this seems not
to work either; I recieve a bad username or password error, despite
the fact I know that the passwords and username are correct.

The error clearly displays a valid username in the form of server_name
\userName (note that these remote machines are not part of a domain)
but my username and password are the same for the domain and remote
machines.

I have attched the relevant areas of my code for your viewing, and I
would be really grateful if anyone can point me in the right
direction!

Thanks,

-Chris

NB: Please note the error occurs on the line "aa.BeginImpers onation()"

------------------------------ Beging Code ------------------

Function service2(ByVal srvname)
Dim aa As New AliasAccount(My .Settings.userN ame,
My.Settings.pas sword, serverName)

Try
aa.BeginImperso nation()
arrRemoteServic es =
System.ServiceP rocess.ServiceC ontroller.GetSe rvices(serverNa me)

For Each Service In arrRemoteServic es
Dim x As New ListViewItem
Dim y As New ListViewItem
If Service.Service Name = srvname Then
'Can use DisplayName (long name of service)
If Service.Status =
System.ServiceP rocess.ServiceC ontrollerStatus .Running Then
If chkLogging.Chec ked = True Then
x.Text = TimeOfDay & "," & serverName & "
" & Service.Service Name & ": Running"
x.BackColor = Color.Green
x.ForeColor = Color.White
lstView1.Items. Add(x)
End If
y.Text = TimeOfDay & "," & serverName & " " &
Service.Service Name & ": Running"
y.BackColor = Color.Green
y.ForeColor = Color.White
frmHist.lstView 1.Items.Add(y)
serverStatus = serverStatus + 1
ElseIf Service.Status =
System.ServiceP rocess.ServiceC ontrollerStatus .StartPending Then
x.Text = TimeOfDay & "," & serverName & " " &
Service.Service Name & ": Starting"
x.BackColor = Color.Blue
x.ForeColor = Color.White
lstView1.Items. Add(x)
y.Text = TimeOfDay & "," & serverName & " " &
Service.Service Name & ": Starting"
y.BackColor = Color.Green
y.ForeColor = Color.White
frmHist.lstView 1.Items.Add(y)
ElseIf Service.Status =
System.ServiceP rocess.ServiceC ontrollerStatus .Stopped Then
x.Text = TimeOfDay & "," & serverName & " " &
Service.Service Name & ": Stopped"
x.BackColor = Color.Red
x.ForeColor = Color.White
lstView1.Items. Add(x)
y.Text = TimeOfDay & "," & serverName & " " &
Service.Service Name & ": Stopped"
y.BackColor = Color.Green
y.ForeColor = Color.White
frmHist.lstView 1.Items.Add(y)
ElseIf Service.Status =
System.ServiceP rocess.ServiceC ontrollerStatus .StopPending Then
x.Text = TimeOfDay & "," & serverName & " " &
Service.Service Name & ": Stopping"
x.BackColor = Color.Red
x.ForeColor = Color.White
lstView1.Items. Add(x)
y.Text = TimeOfDay & "," & serverName & " " &
Service.Service Name & ": Stopping"
y.BackColor = Color.Green
y.ForeColor = Color.White
frmHist.lstView 1.Items.Add(y)
End If
Failures2()
End If
Next
Catch x As Exception
MsgBox("Failed to obtain service information on server: "
& serverName & ", the error returned was: " & Err.Description )
Timer1.Enabled = False

End Try
aa.EndImpersona tion()
End Function

Public Class AliasAccount
Private _username, _password, _domainname As String
Private _tokenHandle As New IntPtr(0)
Private _dupeTokenHandl e As New IntPtr(0)
Private _impersonatedUs er As
System.Security .Principal.Wind owsImpersonatio nContext

Public Sub New(ByVal username As String, ByVal password As String)
Dim nameparts() As String = username.Split( "\")
If nameparts.Lengt h 1 Then
_domainname = nameparts(0)
_username = nameparts(1)
Else
_username = username
End If
_password = password
End Sub

Public Sub New(ByVal username As String, ByVal password As String,
ByVal domainname As String)
_username = username
_password = password
_domainname = domainname
End Sub

Public Sub BeginImpersonat ion()
Const LOGON32_PROVIDE R_DEFAULT As Integer = 0
Const LOGON32_LOGON_I NTERACTIVE As Integer = 2
Const SecurityImperso nation As Integer = 2

Dim win32ErrorNumbe r As Integer

_tokenHandle = IntPtr.Zero
_dupeTokenHandl e = IntPtr.Zero

If Not LogonUser(_user name, _domainname, _password,
LOGON32_LOGON_I NTERACTIVE, LOGON32_PROVIDE R_DEFAULT, _tokenHandle)
Then
win32ErrorNumbe r =
System.Runtime. InteropServices .Marshal.GetLas tWin32Error()
Throw New ImpersonationEx ception(win32Er rorNumber,
GetErrorMessage (win32ErrorNumb er), _username, _domainname)
End If

If Not DuplicateToken( _tokenHandle, SecurityImperso nation,
_dupeTokenHandl e) Then
win32ErrorNumbe r =
System.Runtime. InteropServices .Marshal.GetLas tWin32Error()

CloseHandle(_to kenHandle)
Throw New ImpersonationEx ception(win32Er rorNumber, "Unable
to duplicate token!", _username, _domainname)
End If

Dim newId As New
System.Security .Principal.Wind owsIdentity(_du peTokenHandle)
_impersonatedUs er = newId.Impersona te()
End Sub

Public Sub EndImpersonatio n()
If Not _impersonatedUs er Is Nothing Then
_impersonatedUs er.Undo()
_impersonatedUs er = Nothing

If Not System.IntPtr.o p_Equality(_tok enHandle,
IntPtr.Zero) Then
CloseHandle(_to kenHandle)
End If
If Not System.IntPtr.o p_Equality(_dup eTokenHandle,
IntPtr.Zero) Then
CloseHandle(_du peTokenHandle)
End If
End If
End Sub

Public ReadOnly Property username() As String
Get
Return _username
End Get
End Property

Public ReadOnly Property domainname() As String
Get
Return _domainname
End Get
End Property

Public ReadOnly Property currentWindowsU sername() As String
Get
Return
System.Security .Principal.Wind owsIdentity.Get Current().Name
End Get
End Property

#Region "Exception Class"
Public Class ImpersonationEx ception
Inherits System.Exceptio n

Public ReadOnly win32ErrorNumbe r As Integer

Public Sub New(ByVal win32ErrorNumbe r As Integer, ByVal msg As
String, ByVal username As String, ByVal domainname As String)
MyBase.New(Stri ng.Format("Impe rsonation of {1}\{0} failed!
[{2}] {3}", username, domainname, win32ErrorNumbe r, msg))
Me.win32ErrorNu mber = win32ErrorNumbe r
End Sub
End Class
#End Region

#Region "External Declarations and Helpers"
Private Declare Auto Function LogonUser 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 Boolean
Private Declare Auto Function DuplicateToken Lib
"advapi32.d ll" (ByVal ExistingTokenHa ndle As IntPtr, _
ByVal SECURITY_IMPERS ONATION_LEVEL As Integer, _
ByRef DuplicateTokenH andle As IntPtr) As Boolean
Private Declare Auto Function CloseHandle Lib
"kernel32.d ll" (ByVal handle As IntPtr) As Boolean

<System.Runtime .InteropService s.DllImport("ke rnel32.dll")_
Private Shared Function FormatMessage(B yVal dwFlags As Integer,
ByRef lpSource As IntPtr, _
ByVal dwMessageId As Integer, ByVal dwLanguageId As
Integer, ByRef lpBuffer As [String], _
ByVal nSize As Integer, ByRef Arguments As IntPtr) As
Integer
End Function

Private Function GetErrorMessage (ByVal errorCode As Integer) As
String
Dim FORMAT_MESSAGE_ ALLOCATE_BUFFER As Integer = &H100
Dim FORMAT_MESSAGE_ IGNORE_INSERTS As Integer = &H200
Dim FORMAT_MESSAGE_ FROM_SYSTEM As Integer = &H1000

Dim messageSize As Integer = 255
Dim lpMsgBuf As String
Dim dwFlags As Integer = FORMAT_MESSAGE_ ALLOCATE_BUFFER Or
FORMAT_MESSAGE_ FROM_SYSTEM Or FORMAT_MESSAGE_ IGNORE_INSERTS

Dim ptrlpSource As IntPtr = IntPtr.Zero
Dim prtArguments As IntPtr = IntPtr.Zero

Dim retVal As Integer = FormatMessage(d wFlags, ptrlpSource,
errorCode, 0, lpMsgBuf, messageSize, prtArguments)
If 0 = retVal Then
Throw New System.Exceptio n("Failed to format message for
error code " + errorCode.ToStr ing() + ". ")
End If

Return lpMsgBuf
End Function

#End Region

End Class

Feb 28 '07 #1
0 6229

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

Similar topics

1
2111
by: CyberDigger | last post by:
I have two computers, client and server. The client is running Windows 2000 Professional and is in a workgroup, say "MyWorkgroup". The server is running Windows Server 2003 Standard Edition and is in a domain, say "MyDomain". What I need is to logon to the client as some generic local administrator user and then access resources (e.g. share folder, SQL Server using Windows Authentication, etc.) on the server. Here is what I did: I...
6
1032
by: Rob Bolton | last post by:
Hi there, If a program running under the interactive logon session (say Susan), needs to impersonate Bob (via "LogonUser()"), but Bob needs to access the network as Susan (i.e., his local credentials will be his own, but his network credentials will be Susan's), is there anyway to do this? The problem seems to rest with the fact that Bob needs Susan's cleartext password to invoke any of the appropriate functions but he can't get it -...
3
6503
by: Wm. Scott Miller | last post by:
What is the difference between using a username and password in the processmodel section vs using one in impersonation in the machine.config file? What are the advantages of each and what are the reasons for using each? Thanks for any replies, Scott
1
1638
by: Matt Tapia | last post by:
How can I temporaily impersonate another windows user within my asp.net application to run a line of code? Do I need to know both the user name and password?
15
3302
by: Patrick | last post by:
I set my web.config as follows: <authentication mode="Windows" /> <identity impersonate="true" /> Logon to my ASP.NET website as a user who can authenticate to the target database. 1) Works fine on my local PC running IIS5.1 on WinXP Pro SP1 2) does not work on IIS6.0 on Windows 2003 server: System.Data.SqlClient.SqlException: Login failed for user '(null)'. Reason:
12
13917
by: Craig S | last post by:
I've implemented the impersonation method shown here: http://support.microsoft.com/?id=306158 under the section "Impersonate a Specific User in Code". Essentially just interop the LogonUserA function in advapi32.dll, execute the code you want, and then undo impersonation. However, this only works for the domain that the machine you're running from is joined to. I want to run this code on a web server just in a workgroup and...
3
1468
by: headware | last post by:
We have a web app that is running under Integrated Windows Authentication. It must consume to a web service we are publishing on another server, also running under Integrated Windows Authentication. In order to make this work, we have to impersonate a user account with access to the web service and set the Credential property on the web service proxy object to DefaultCredentials before we actually make the web service call. If we don't...
0
1953
by: ChopStickr | last post by:
I have a custom control that is embedded (using the object tag) in an html document. The control takes a path to a local client ini file. Reads the file. Executes the program specified in the ini on the client's PC. After the program has ended the control looks in a client side temp folder (specified by the ini file) for an image created by the executed program. If the image is there, then the control moves the file to a public folder...
5
2662
by: =?Utf-8?B?S2l0dHlIYXdr?= | last post by:
I am in the process of migrating an II6 environment from a single server to a network load balanced system. Thus, I am using a virtual directory on a UNC share to house the dynamic data that the web farm will access. Since ASP.NET runs as a local account on the IIS servers, I have to use impersonation to perform any operations on the data that resides on the UNC share. I am hard-coding the impersonation credentials in the web.config files...
0
8435
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8857
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
8768
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...
0
7368
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5655
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
4348
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2763
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
2
1999
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1754
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.