if current user do not belong to Admin Group then get Admin priviledge

本文介绍了一个使用C#编写的窗体应用程序如何判断当前用户的管理员权限,并提供了权限不足时临时提升为管理员的方法。通过调用Windows API实现用户权限的模拟,包括获取令牌、复制令牌、使用令牌进行身份模拟等步骤。

 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


<think>我们正在处理一个HBase Shell报错:用户root没有权限列出角色,因为用户必须属于ADMIN角色并且当前角色设置为ADMIN。 根据之前的回答,我们知道这个错误通常与基于角色的访问控制(RBAC)有关,需要确保用户具有ADMIN角色并且当前角色设置为ADMIN。 解决方案: 1. 确保root用户被授予ADMIN角色。 2. 在HBase Shell中设置当前角色为ADMIN。 3. 如果问题仍然存在,检查HBase的RBAC配置。 具体步骤: - 使用管理员账户(可能是其他有权限的用户)将root添加到ADMIN角色。 - 在HBase Shell中,使用`grant`命令或HBase的RBAC命令(如果有)来分配角色。 - 然后,在HBase Shell中,使用`set current role`之类的命令(具体命令取决于HBase的版本和集成的安全框架)来设置当前角色。 注意:HBase本身并不直接支持RBAC,通常需要与Apache Ranger或Hadoop的安全机制(如Kerberos)集成。因此,错误可能来源于集成的安全系统(如Ranger)。 因此,回答将围绕如何解决在HBase Shell中遇到的这个权限问题。 步骤: 1. 确认安全集成:检查HBase是否与Apache Ranger或其他RBAC系统集成。 2. 使用管理员账户登录到Ranger管理界面(或其他安全系统)将root用户添加到ADMIN角色。 3. 在HBase Shell中,尝试设置当前角色(如果支持的话)或者重新登录。 如果是在集成了Ranger的环境中,通常需要在Ranger中配置策略。 另外,HBase Shell中可能没有直接设置角色的命令,所以可能需要通过安全系统的命令行工具或管理界面操作。 具体错误信息表明操作需要当前角色为ADMIN,所以我们需要确保在操作之前已经设置了当前角色。 可能的HBase Shell命令(如果支持): - 设置角色:`set_role`(但HBase本身不直接支持,所以可能不适用) - 或者使用Ranger的命令行工具:`ranger-admin`命令来添加用户到角色。 因此,实际步骤可能是在Ranger中配置,然后重新登录HBase Shell。 如果HBase没有集成外部安全系统,那么可能错误是由于HBase的AccessController协处理器配置引起的,但HBase的AccessController主要基于权限(如读、写、创建等)而不是角色。因此,这个错误信息更可能是来自集成的外部系统。 总结:需要检查HBase的安全集成情况,并在相应的安全系统中配置。 由于用户问题是在HBase Shell中报错,我们假设环境已经集成了RBAC系统(如Ranger)。 回答结构: - 解释错误原因 - 提供解决步骤 - 注意事项 然后,根据问题和回答提出3-5个相关问题。</think>### 回答: 在 HBase Shell 中遇到报错 `Current user : root is not allowed to list roles. User has to belong to ADMIN role and have it as current role, for this action.`,表明当前用户 **root 缺少 ADMIN 角色权限**。该错误通常发生在启用 RBAC(基于角色的访问控制)的 HBase 集群中,原因和解决方案如下: --- #### **错误原因** 1. **角色未分配**:用户 root 未被授予 ADMIN 角色。 2. **当前角色未激活**:即使 root 属于 ADMIN 角色,但未通过 `SET ROLE` 显式激活。 3. **安全集成问题**:若 HBase 集成 Apache Ranger 或 Kerberos,策略配置可能未生效。 4. **协处理器未生效**:HBase 的 `AccessController` 协处理器未正确加载或配置。 --- #### **解决方案** 1. **授予 ADMIN 角色**(需管理员执行): ```bash hbase shell> grant 'root', 'ADMIN' # 授予角色 hbase shell> user_permission '.*' # 验证权限 ``` 2. **激活 ADMIN 角色**(root 用户执行): ```bash hbase shell> set_role ADMIN # 设置当前角色 ``` 3. **检查协处理器配置**(在 `hbase-site.xml` 中): ```xml <property> <name>hbase.security.authorization</name> <value>true</value> </property> <property> <name>hbase.coprocessor.master.classes</name> <value>org.apache.hadoop.hbase.security.access.AccessController</value> </property> ``` 重启 HBase 服务使配置生效。 4. **集成系统检查**(如 Apache Ranger): - 在 Ranger Admin 控制台添加策略:授权 root 用户为 ADMIN 角色。 - 同步策略:执行 `ranger-admin --sync` 同步权限。 --- #### **验证步骤** ```bash hbase shell> whoami # 确认当前用户 hbase shell> list_roles # 应成功显示角色列表 hbase shell> list_namespaces # 测试管理员操作权限 ``` > **注意**:若问题持续,检查 HBase 日志(`logs/hbase-*.log`)排查协处理器加载错误或策略冲突。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值