473,396 Members | 1,683 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,396 software developers and data experts.

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.BeginImpersonation()"

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

Function service2(ByVal srvname)
Dim aa As New AliasAccount(My.Settings.userName,
My.Settings.password, serverName)

Try
aa.BeginImpersonation()
arrRemoteServices =
System.ServiceProcess.ServiceController.GetService s(serverName)

For Each Service In arrRemoteServices
Dim x As New ListViewItem
Dim y As New ListViewItem
If Service.ServiceName = srvname Then
'Can use DisplayName (long name of service)
If Service.Status =
System.ServiceProcess.ServiceControllerStatus.Runn ing Then
If chkLogging.Checked = True Then
x.Text = TimeOfDay & "," & serverName & "
" & Service.ServiceName & ": Running"
x.BackColor = Color.Green
x.ForeColor = Color.White
lstView1.Items.Add(x)
End If
y.Text = TimeOfDay & "," & serverName & " " &
Service.ServiceName & ": Running"
y.BackColor = Color.Green
y.ForeColor = Color.White
frmHist.lstView1.Items.Add(y)
serverStatus = serverStatus + 1
ElseIf Service.Status =
System.ServiceProcess.ServiceControllerStatus.Star tPending Then
x.Text = TimeOfDay & "," & serverName & " " &
Service.ServiceName & ": Starting"
x.BackColor = Color.Blue
x.ForeColor = Color.White
lstView1.Items.Add(x)
y.Text = TimeOfDay & "," & serverName & " " &
Service.ServiceName & ": Starting"
y.BackColor = Color.Green
y.ForeColor = Color.White
frmHist.lstView1.Items.Add(y)
ElseIf Service.Status =
System.ServiceProcess.ServiceControllerStatus.Stop ped Then
x.Text = TimeOfDay & "," & serverName & " " &
Service.ServiceName & ": Stopped"
x.BackColor = Color.Red
x.ForeColor = Color.White
lstView1.Items.Add(x)
y.Text = TimeOfDay & "," & serverName & " " &
Service.ServiceName & ": Stopped"
y.BackColor = Color.Green
y.ForeColor = Color.White
frmHist.lstView1.Items.Add(y)
ElseIf Service.Status =
System.ServiceProcess.ServiceControllerStatus.Stop Pending Then
x.Text = TimeOfDay & "," & serverName & " " &
Service.ServiceName & ": Stopping"
x.BackColor = Color.Red
x.ForeColor = Color.White
lstView1.Items.Add(x)
y.Text = TimeOfDay & "," & serverName & " " &
Service.ServiceName & ": Stopping"
y.BackColor = Color.Green
y.ForeColor = Color.White
frmHist.lstView1.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.EndImpersonation()
End Function

Public Class AliasAccount
Private _username, _password, _domainname As String
Private _tokenHandle As New IntPtr(0)
Private _dupeTokenHandle As New IntPtr(0)
Private _impersonatedUser As
System.Security.Principal.WindowsImpersonationCont ext

Public Sub New(ByVal username As String, ByVal password As String)
Dim nameparts() As String = username.Split("\")
If nameparts.Length 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 BeginImpersonation()
Const LOGON32_PROVIDER_DEFAULT As Integer = 0
Const LOGON32_LOGON_INTERACTIVE As Integer = 2
Const SecurityImpersonation As Integer = 2

Dim win32ErrorNumber As Integer

_tokenHandle = IntPtr.Zero
_dupeTokenHandle = IntPtr.Zero

If Not LogonUser(_username, _domainname, _password,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, _tokenHandle)
Then
win32ErrorNumber =
System.Runtime.InteropServices.Marshal.GetLastWin3 2Error()
Throw New ImpersonationException(win32ErrorNumber,
GetErrorMessage(win32ErrorNumber), _username, _domainname)
End If

If Not DuplicateToken(_tokenHandle, SecurityImpersonation,
_dupeTokenHandle) Then
win32ErrorNumber =
System.Runtime.InteropServices.Marshal.GetLastWin3 2Error()

CloseHandle(_tokenHandle)
Throw New ImpersonationException(win32ErrorNumber, "Unable
to duplicate token!", _username, _domainname)
End If

Dim newId As New
System.Security.Principal.WindowsIdentity(_dupeTok enHandle)
_impersonatedUser = newId.Impersonate()
End Sub

Public Sub EndImpersonation()
If Not _impersonatedUser Is Nothing Then
_impersonatedUser.Undo()
_impersonatedUser = Nothing

If Not System.IntPtr.op_Equality(_tokenHandle,
IntPtr.Zero) Then
CloseHandle(_tokenHandle)
End If
If Not System.IntPtr.op_Equality(_dupeTokenHandle,
IntPtr.Zero) Then
CloseHandle(_dupeTokenHandle)
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 currentWindowsUsername() As String
Get
Return
System.Security.Principal.WindowsIdentity.GetCurre nt().Name
End Get
End Property

#Region "Exception Class"
Public Class ImpersonationException
Inherits System.Exception

Public ReadOnly win32ErrorNumber As Integer

Public Sub New(ByVal win32ErrorNumber As Integer, ByVal msg As
String, ByVal username As String, ByVal domainname As String)
MyBase.New(String.Format("Impersonation of {1}\{0} failed!
[{2}] {3}", username, domainname, win32ErrorNumber, msg))
Me.win32ErrorNumber = win32ErrorNumber
End Sub
End Class
#End Region

#Region "External Declarations and Helpers"
Private Declare Auto Function LogonUser Lib "advapi32.dll" (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.dll" (ByVal ExistingTokenHandle As IntPtr, _
ByVal SECURITY_IMPERSONATION_LEVEL As Integer, _
ByRef DuplicateTokenHandle As IntPtr) As Boolean
Private Declare Auto Function CloseHandle Lib
"kernel32.dll" (ByVal handle As IntPtr) As Boolean

<System.Runtime.InteropServices.DllImport("kernel3 2.dll")_
Private Shared Function FormatMessage(ByVal 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(dwFlags, ptrlpSource,
errorCode, 0, lpMsgBuf, messageSize, prtArguments)
If 0 = retVal Then
Throw New System.Exception("Failed to format message for
error code " + errorCode.ToString() + ". ")
End If

Return lpMsgBuf
End Function

#End Region

End Class

Feb 28 '07 #1
0 6203

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

Similar topics

1
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...
6
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...
3
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...
1
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
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...
12
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...
3
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...
0
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...
5
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...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
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
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
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
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...

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.