' (Declarations) -- see MSDN for more details on these functions
Declare Function LogonUser Lib "advapi32.dll" Alias "LogonUserA" (_
Byval lpszUsername As String, _
Byval lpszDomain As String, _
Byval lpszPassword As String, _
Byval dwLogonType As Long, _
Byval dwLogonProvider As Long, _
phToken As Long _
) As Long
Declare Function ImpersonateLoggedOnUser Lib "advapi32.dll" Alias "ImpersonateLoggedOnUser" ( _
Byval hToken As Long _
) As Long
Declare Function RevertToSelf Lib "advapi32.dll" Alias "RevertToSelf" () As Long
Declare Function CloseHandle Lib "kernel32.dll" Alias "CloseHandle" ( _
Byval hObject As Long _
) As Long
Const LOGON32_PROVIDER_DEFAULT = 0
Const LOGON32_LOGON_INTERACTIVE = 2
Sub Initialize
%REM
This agent shows how to fetch a security token for a particular NT account, and impersonate that account. In
doing so, the agent can access files on remote machines under the security context of another NT account. Note
that impersonation only occurs in the current thread, and concludes when the current thread terminates.
Copyright 2001 Paul Ray. Use at your own risk.
%END REM
Dim hToken&
Dim file%
' get a security token for the specified NT account
If LogonUser("", "", "", LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, hToken&) = 0 Then
Msgbox "==>LogonUser failed."
Exit Sub
End If
' impersonate the NT user (only in the current thread)
If ImpersonateLoggedOnUser(hToken&) = 0 Then
Msgbox "==>ImpersonateLoggedOnUser failed."
If hToken& <> 0 Then CloseHandle(hToken&)
Exit Sub
End If
' close the handle to the token
If hToken& <> 0 Then CloseHandle(hToken&)
' -------------- INIZIO PARTE "CRITICA"
' create a file on another NT machine and write some text to it
file% = Freefile()
Open "P:\COMMPROF.TXT" For Output As file%
Write #file%, "Hello World!"
Close file%
' -------------- FINE PARTE "CRITICA"
' revert back to system account (not really required, as it should automatically revert back when thread terminates)
Call RevertToSelf()
End Sub