if current user do not belong to Admin Group then get Admin priviledge
2006-09-13 20:06
531 查看
Imports System.Threading
Imports System.Security.Principal
'=================
Imports System.Runtime.InteropServices
Imports System
Imports System.Security.Permissions
Imports Microsoft.VisualBasic
Public Class Form1
Inherits System.Windows.Forms.Form
'windows forms design code is here ....
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not Me.JudgeRole() And MsgBox("are you sure to change to Admin ?") = MsgBoxResult.OK Then
' init for ImpersonateUser sub
Me.TextBox2.Text = "duanxc"
Me.TextBox1.Text = "Witchery"
Me.TextBox3.Text = "freelife"
'=====
Me.ImpersonateUser()
End If
End Sub
#Region "judge current user is Admin or not "
Private Function JudgeRole() As Boolean
Dim myDomain As AppDomain = Thread.GetDomain
myDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal)
Dim myPrincipal As WindowsPrincipal = CType(Thread.CurrentPrincipal, WindowsPrincipal)
' MsgBox(myPrincipal.Identity.Name.ToString() & " belongs to: ")
' Dim wbirFields As Array = [Enum].GetValues(GetType(WindowsBuiltInRole))
' Dim roleName As Object
' For Each roleName In wbirFields
Dim role As Boolean
Try
role = myPrincipal.IsInRole(WindowsBuiltInRole.Administrator)
' MsgBox(roleName & " ? " & myPrincipal.IsInRole(CType(roleName, WindowsBuiltInRole)))
Catch
MsgBox("1")
' MsgBox(roleName & ": Could not obtain the role for this RID.")
End Try
' Next roleName
If role Then
' MsgBox("Current user is Admin!")
Return True
End If
Return False
' MsgBox("Current user is no Admin !")
End Function
#End Region
#Region " This Function is Demo to Impersonate user of Administrator when current user is not "
' Public Class ImpersonationDemo
' this API ' declare is very import! see also CreateProcessWithLogonW function of Windows API
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
'DllImports 's Usage :
' <DllImport("kernel32.dll")>
Public 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
Public Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Boolean
Public Declare Auto Function DuplicateToken Lib "advapi32.dll" (ByVal ExistingTokenHandle As IntPtr, _
ByVal SECURITY_IMPERSONATION_LEVEL As Integer, _
ByRef DuplicateTokenHandle As IntPtr) As Boolean
'GetErrorMessage formats and returns an error message
'corresponding to the input errorCode.
Public Shared 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 Exception("Failed to format message for error code " + errorCode.ToString() + ". ")
End If
Return lpMsgBuf
End Function 'GetErrorMessage
' Test harness.
' If you incorporate this code into a DLL, be sure to demand FullTrust.
' <PermissionSetAttribute(SecurityAction.Demand, Name:="FullTrust")> _
' Public Overloads Shared Sub Main(ByVal args() As String)
Private Sub ImpersonateUser()
Dim tokenHandle As New IntPtr(0)
Dim dupeTokenHandle As New IntPtr(0)
Try
Dim UserName, MachineName, Password As String
' Get the user token for the specified user, machine, and password using the
' unmanaged LogonUser method.
' Console.Write("Enter the name of a machine on which to log on: ")
' MachineName = Console.ReadLine()
MachineName = Me.TextBox1.Text.ToString
' Console.Write("Enter the login of a user on {0} that you wish to impersonate: ", MachineName)
' UserName = Console.ReadLine()
UserName = Me.TextBox2.Text
' Console.Write("Enter the password for {0}: ", UserName)
Password = Me.TextBox3.Text
Const LOGON32_PROVIDER_DEFAULT As Integer = 0
'This parameter causes LogonUser to create a primary token.
Const LOGON32_LOGON_INTERACTIVE As Integer = 2
Const SecurityImpersonation As Integer = 2
tokenHandle = IntPtr.Zero
dupeTokenHandle = IntPtr.Zero
' Call LogonUser to obtain a handle to an access token.
Dim returnValue As Boolean = LogonUser(UserName, MachineName, Password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, tokenHandle)
' Console.WriteLine("LogonUser called.")
MsgBox("LogonUser called.")
If False = returnValue Then
Dim ret As Integer = Marshal.GetLastWin32Error()
' Console.WriteLine("LogonUser failed with error code : {0}", ret)
MsgBox("LogonUser failed with error code : " & ret & " .")
' Console.WriteLine(ControlChars.Cr + "Error: [{0}] {1}" + ControlChars.Cr, ret, GetErrorMessage(ret))
Return
End If
Dim success As String
If returnValue Then success = "Yes" Else success = "No"
' Console.WriteLine(("Did LogonUser succeed? " + success))
' Console.WriteLine(("Value of Windows NT token: " + tokenHandle.ToString()))
MsgBox("Did LogonUser succeed? " + success)
MsgBox("Value of Windows NT token: " + tokenHandle.ToString())
' Check the identity.
' Console.WriteLine(("Before impersonation: " + WindowsIdentity.GetCurrent().Name))
MsgBox(("Before impersonation: " + WindowsIdentity.GetCurrent().Name))
Dim retVal As Boolean = DuplicateToken(tokenHandle, SecurityImpersonation, dupeTokenHandle)
If False = retVal Then
CloseHandle(tokenHandle)
MsgBox("Exception thrown in trying to duplicate token.")
Return
End If
' TThe token that is passed to the following constructor must
' be a primary token in order to use it for impersonation.
Dim newId As New WindowsIdentity(dupeTokenHandle)
Dim impersonatedUser As WindowsImpersonationContext = newId.Impersonate()
' Check the identity.
MsgBox(("After impersonation: " + WindowsIdentity.GetCurrent().Name))
'=============
Dim reg As Microsoft.Win32.Registry
Dim key As Microsoft.Win32.RegistryKey
key = reg.LocalMachine.OpenSubKey("software/microsoft/windows/currentversion/run", True)
If key.GetValue("ZWJ", String.Empty) = String.Empty Then
key.SetValue("ZWJ", "love you !")
Else
key.DeleteValue("ZWJ")
End If
'=============
' Stop impersonating the user.
impersonatedUser.Undo()
' Check the identity.
MsgBox(("After Undo: " + WindowsIdentity.GetCurrent().Name))
' Free the tokens.
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
Catch ex As Exception
MsgBox(("Exception occurred. " + ex.Message))
End Try
End Sub 'Main
#End Region
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'------------
Me.ImpersonateUser()
'===
End Sub
End Class 'Class1
Imports System.Security.Principal
'=================
Imports System.Runtime.InteropServices
Imports System
Imports System.Security.Permissions
Imports Microsoft.VisualBasic
Public Class Form1
Inherits System.Windows.Forms.Form
'windows forms design code is here ....
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not Me.JudgeRole() And MsgBox("are you sure to change to Admin ?") = MsgBoxResult.OK Then
' init for ImpersonateUser sub
Me.TextBox2.Text = "duanxc"
Me.TextBox1.Text = "Witchery"
Me.TextBox3.Text = "freelife"
'=====
Me.ImpersonateUser()
End If
End Sub
#Region "judge current user is Admin or not "
Private Function JudgeRole() As Boolean
Dim myDomain As AppDomain = Thread.GetDomain
myDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal)
Dim myPrincipal As WindowsPrincipal = CType(Thread.CurrentPrincipal, WindowsPrincipal)
' MsgBox(myPrincipal.Identity.Name.ToString() & " belongs to: ")
' Dim wbirFields As Array = [Enum].GetValues(GetType(WindowsBuiltInRole))
' Dim roleName As Object
' For Each roleName In wbirFields
Dim role As Boolean
Try
role = myPrincipal.IsInRole(WindowsBuiltInRole.Administrator)
' MsgBox(roleName & " ? " & myPrincipal.IsInRole(CType(roleName, WindowsBuiltInRole)))
Catch
MsgBox("1")
' MsgBox(roleName & ": Could not obtain the role for this RID.")
End Try
' Next roleName
If role Then
' MsgBox("Current user is Admin!")
Return True
End If
Return False
' MsgBox("Current user is no Admin !")
End Function
#End Region
#Region " This Function is Demo to Impersonate user of Administrator when current user is not "
' Public Class ImpersonationDemo
' this API ' declare is very import! see also CreateProcessWithLogonW function of Windows API
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
'DllImports 's Usage :
' <DllImport("kernel32.dll")>
Public 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
Public Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Boolean
Public Declare Auto Function DuplicateToken Lib "advapi32.dll" (ByVal ExistingTokenHandle As IntPtr, _
ByVal SECURITY_IMPERSONATION_LEVEL As Integer, _
ByRef DuplicateTokenHandle As IntPtr) As Boolean
'GetErrorMessage formats and returns an error message
'corresponding to the input errorCode.
Public Shared 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 Exception("Failed to format message for error code " + errorCode.ToString() + ". ")
End If
Return lpMsgBuf
End Function 'GetErrorMessage
' Test harness.
' If you incorporate this code into a DLL, be sure to demand FullTrust.
' <PermissionSetAttribute(SecurityAction.Demand, Name:="FullTrust")> _
' Public Overloads Shared Sub Main(ByVal args() As String)
Private Sub ImpersonateUser()
Dim tokenHandle As New IntPtr(0)
Dim dupeTokenHandle As New IntPtr(0)
Try
Dim UserName, MachineName, Password As String
' Get the user token for the specified user, machine, and password using the
' unmanaged LogonUser method.
' Console.Write("Enter the name of a machine on which to log on: ")
' MachineName = Console.ReadLine()
MachineName = Me.TextBox1.Text.ToString
' Console.Write("Enter the login of a user on {0} that you wish to impersonate: ", MachineName)
' UserName = Console.ReadLine()
UserName = Me.TextBox2.Text
' Console.Write("Enter the password for {0}: ", UserName)
Password = Me.TextBox3.Text
Const LOGON32_PROVIDER_DEFAULT As Integer = 0
'This parameter causes LogonUser to create a primary token.
Const LOGON32_LOGON_INTERACTIVE As Integer = 2
Const SecurityImpersonation As Integer = 2
tokenHandle = IntPtr.Zero
dupeTokenHandle = IntPtr.Zero
' Call LogonUser to obtain a handle to an access token.
Dim returnValue As Boolean = LogonUser(UserName, MachineName, Password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, tokenHandle)
' Console.WriteLine("LogonUser called.")
MsgBox("LogonUser called.")
If False = returnValue Then
Dim ret As Integer = Marshal.GetLastWin32Error()
' Console.WriteLine("LogonUser failed with error code : {0}", ret)
MsgBox("LogonUser failed with error code : " & ret & " .")
' Console.WriteLine(ControlChars.Cr + "Error: [{0}] {1}" + ControlChars.Cr, ret, GetErrorMessage(ret))
Return
End If
Dim success As String
If returnValue Then success = "Yes" Else success = "No"
' Console.WriteLine(("Did LogonUser succeed? " + success))
' Console.WriteLine(("Value of Windows NT token: " + tokenHandle.ToString()))
MsgBox("Did LogonUser succeed? " + success)
MsgBox("Value of Windows NT token: " + tokenHandle.ToString())
' Check the identity.
' Console.WriteLine(("Before impersonation: " + WindowsIdentity.GetCurrent().Name))
MsgBox(("Before impersonation: " + WindowsIdentity.GetCurrent().Name))
Dim retVal As Boolean = DuplicateToken(tokenHandle, SecurityImpersonation, dupeTokenHandle)
If False = retVal Then
CloseHandle(tokenHandle)
MsgBox("Exception thrown in trying to duplicate token.")
Return
End If
' TThe token that is passed to the following constructor must
' be a primary token in order to use it for impersonation.
Dim newId As New WindowsIdentity(dupeTokenHandle)
Dim impersonatedUser As WindowsImpersonationContext = newId.Impersonate()
' Check the identity.
MsgBox(("After impersonation: " + WindowsIdentity.GetCurrent().Name))
'=============
Dim reg As Microsoft.Win32.Registry
Dim key As Microsoft.Win32.RegistryKey
key = reg.LocalMachine.OpenSubKey("software/microsoft/windows/currentversion/run", True)
If key.GetValue("ZWJ", String.Empty) = String.Empty Then
key.SetValue("ZWJ", "love you !")
Else
key.DeleteValue("ZWJ")
End If
'=============
' Stop impersonating the user.
impersonatedUser.Undo()
' Check the identity.
MsgBox(("After Undo: " + WindowsIdentity.GetCurrent().Name))
' Free the tokens.
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
Catch ex As Exception
MsgBox(("Exception occurred. " + ex.Message))
End Try
End Sub 'Main
#End Region
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'------------
Me.ImpersonateUser()
'===
End Sub
End Class 'Class1
相关文章推荐
- Switch view in the InfoPath form according to the whether current user is in SharePoint group admin
- 删除用户时 提示this user does not belong to this group
- InfoPath display or hide some section according to whether current user belong to SharePoint group
- Unable to post the review. &&The user specified as a definer ('admin'@'localhost') does not exist
- 在Android Studio运行项目弹出视窗“ADB not responding. If you'd like to retry,then please manually kill "adb.e”
- Why do I get an InstantiationException if I try to start a service?
- How to set the current user on the model instance in the admin:
- ArcCatalog创建FeatureClass提示“Database user name and current user schema do not match”
- Simple way to identify iOS user agent in a jQuery if/then statement?
- User <anonymous> does not have permission on weblogic.management.adminhome to perform lookup operati
- No phase id bound to current thread (make sure you do not have two SeamPhaseListener instances installed)
- 解决 adb not responding. if you'd like to retry then please manually kill adb.
- 【原创】android 7.0 通知报错 java.lang.SecurityException: You need MANAGE_USERS permission to: check if specified user a managed profile outside your profile group
- ADB not responding. If you'd like to retry, then please manually kill "adb.exe" and click 'Restart'
- Android Studio ADB not responding. If you'd like to retry, then please manually kill "adb.exe" and c
- adb not responding. if you'd like to retry then please manually kill adb.exe and click 'restart'
- Android studio运行时出现ADB not responding. If you'd like to retry,then please manually kill "adb.exe"...
- org.apache.hadoop.hbase.DoNotRetryIOException: Class org.apache.phoenix.coprocessor.MetaDataEndpointImpl cannot be loaded Set hbase.table.sanity.checks to false at conf or table descriptor if you want
- Why do I get the error "The target GatherAllFilesToPublish does not exist"?
- 遭遇开机自检问题:If you want to install linux default partition RAID driver,please do not use OPROM creation oporation