您的位置:首页 > 其它

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐