Reputation: 79
Is there a way i can invoke a vb command on my system as admin user by login to system as standard user? Eg: run a program to delete files from the system that can only be done by admin account.
Upvotes: 0
Views: 1220
Reputation: 1556
You can run processes as different users with something like this:
Function ConvertToSecureString(ByVal str As String)
Dim password As New SecureString
For Each c As Char In str.ToCharArray
password.AppendChar(c)
Next
Return password
End Function
Sub Main()
dim username as string = "Administrator"
dim password as SecureString = ConvertToSecureString("my password")
dim domain as string = Nothing
dim filename as string = "notepad.exe" ' %SYSTEMROOT%\system32
Try
System.Diagnostics.Process.Start(filename,username, password, domain)
Catch ex As Win32Exception
MessageBox.Show("Wrong username or password.", _
"Error logging in as administrator", MessageBoxButtons.OK, _
MessageBoxIcon.Error)
End Try
End Sub
Using this above pattern you can perform just about any operation under an assumed context. For example, if you wanted to delete a file, you could call 'cmd.exe /c del c:\somefile.exe'.
You can also use the lower level LogonUser P/Invoke / WindowsIdentity / WindowsImpersonationContext combo.
Imports System.Runtime.InteropServices
Imports System.Security.Principal
Module Module1
Private Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal un As String, ByVal domain As String, ByVal pw As String, ByVal LogonType As Integer, ByVal LogonProvider As Integer, ByRef Token As IntPtr) As Boolean
Public Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Boolean
Public Sub Main()
Dim tokenHandle As New IntPtr(0)
Try
If LogonUser("un", "DOMAINNAME", "pw", 2, 0, tokenHandle) Then
Dim newId As New WindowsIdentity(tokenHandle)
Using impersonatedUser As WindowsImpersonationContext = newId.Impersonate()
'perform impersonated commands
System.IO.File.WriteAllText("C:ttestimp.txt", "test")
End Using
CloseHandle(tokenHandle)
Else
'logon failed
End If
Catch ex As Exception
'exception
End Try
End Sub
End Module
Upvotes: 2