Guest User

Untitled

a guest
Jun 19th, 2018
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.55 KB | None | 0 0
  1. Public Sub BeginImpersonation()
  2. Const LOGON32_PROVIDER_DEFAULT As Integer = 0
  3. Const LOGON32_LOGON_INTERACTIVE As Integer = 2
  4. Const SecurityImpersonation As Integer = 2
  5.  
  6. Dim win32ErrorNumber As Integer
  7.  
  8. _tokenHandle = IntPtr.Zero
  9. _dupeTokenHandle = IntPtr.Zero
  10.  
  11. If Not LogonUser(_username, _domainname, _password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, _tokenHandle) Then
  12. win32ErrorNumber = System.Runtime.InteropServices.Marshal.GetLastWin32Error()
  13. Throw New ImpersonationException(win32ErrorNumber, GetErrorMessage(win32ErrorNumber), _username, _domainname)
  14. End If
  15.  
  16. If Not DuplicateToken(_tokenHandle, SecurityImpersonation, _dupeTokenHandle) Then
  17. win32ErrorNumber = System.Runtime.InteropServices.Marshal.GetLastWin32Error()
  18.  
  19. CloseHandle(_tokenHandle)
  20. Throw New ImpersonationException(win32ErrorNumber, "Unable to duplicate token!", _username, _domainname)
  21. End If
  22.  
  23. Dim newId As New System.Security.Principal.WindowsIdentity(_dupeTokenHandle)
  24. _impersonatedUser = newId.Impersonate()
  25. _impersonating = True
  26. End Sub
  27.  
  28. Enum LOGON32_LOGON
  29. INTERACTIVE = 2
  30. NETWORK = 3
  31. BATCH = 4
  32. SERVICE = 5
  33. UNLOCK = 7
  34. NETWORK_CLEARTEXT = 8
  35. NEW_CREDENTIALS = 9
  36. End Enum
  37. Enum LOGON32_PROVIDER
  38. [DEFAULT] = 0
  39. WINNT35 = 1
  40. WINNT40 = 2
  41. WINNT50 = 3
  42. End Enum
  43. Enum SECURITY_LEVEL
  44. Anonymous = 0
  45. Identification = 1
  46. Impersonation = 2
  47. Delegation = 3
  48. End Enum
  49.  
  50. Dim myProcessStartInfo As ProcessStartInfo = New ProcessStartInfo
  51.  
  52. With myProcessStartInfo
  53.  
  54. .FileName = "file path and name"
  55.  
  56. .Domain = "domainname"
  57. .UserName = "username"
  58.  
  59. 'password needs to be a SerureString
  60. Using NewPassword As New Security.SecureString
  61. With NewPassword
  62. For Each c As Char In "password".ToCharArray
  63. .AppendChar(c)
  64. Next c
  65. .MakeReadOnly()
  66. End With
  67. .Password = NewPassword.Copy
  68. End Using
  69.  
  70. 'UseShellExecute must be false for impersonated process
  71. .UseShellExecute = False
  72.  
  73. End With
  74.  
  75. Using Process As New System.Diagnostics.Process
  76. With Process
  77. .StartInfo = myProcessStartInfo
  78. .Start()
  79. End With
  80. End Using
  81.  
  82. LogonUser(_username, _domainname, _password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_WINNT50, _tokenHandle)
  83.  
  84. Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Long
  85. Declare Auto Function RevertToSelf Lib "advapi32.dll" () As Long
Add Comment
Please, Sign In to add comment