Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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.GetLastWin32Error()
- Throw New ImpersonationException(win32ErrorNumber, GetErrorMessage(win32ErrorNumber), _username, _domainname)
- End If
- If Not DuplicateToken(_tokenHandle, SecurityImpersonation, _dupeTokenHandle) Then
- win32ErrorNumber = System.Runtime.InteropServices.Marshal.GetLastWin32Error()
- CloseHandle(_tokenHandle)
- Throw New ImpersonationException(win32ErrorNumber, "Unable to duplicate token!", _username, _domainname)
- End If
- Dim newId As New System.Security.Principal.WindowsIdentity(_dupeTokenHandle)
- _impersonatedUser = newId.Impersonate()
- _impersonating = True
- End Sub
- Enum LOGON32_LOGON
- INTERACTIVE = 2
- NETWORK = 3
- BATCH = 4
- SERVICE = 5
- UNLOCK = 7
- NETWORK_CLEARTEXT = 8
- NEW_CREDENTIALS = 9
- End Enum
- Enum LOGON32_PROVIDER
- [DEFAULT] = 0
- WINNT35 = 1
- WINNT40 = 2
- WINNT50 = 3
- End Enum
- Enum SECURITY_LEVEL
- Anonymous = 0
- Identification = 1
- Impersonation = 2
- Delegation = 3
- End Enum
- Dim myProcessStartInfo As ProcessStartInfo = New ProcessStartInfo
- With myProcessStartInfo
- .FileName = "file path and name"
- .Domain = "domainname"
- .UserName = "username"
- 'password needs to be a SerureString
- Using NewPassword As New Security.SecureString
- With NewPassword
- For Each c As Char In "password".ToCharArray
- .AppendChar(c)
- Next c
- .MakeReadOnly()
- End With
- .Password = NewPassword.Copy
- End Using
- 'UseShellExecute must be false for impersonated process
- .UseShellExecute = False
- End With
- Using Process As New System.Diagnostics.Process
- With Process
- .StartInfo = myProcessStartInfo
- .Start()
- End With
- End Using
- LogonUser(_username, _domainname, _password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_WINNT50, _tokenHandle)
- Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Long
- Declare Auto Function RevertToSelf Lib "advapi32.dll" () As Long
Add Comment
Please, Sign In to add comment