ID do artigo: 185215 - Última revisão: terça-feira, 13 de julho de 2004 - Revisão: 2.1

Como usar o SeDebugPrivilege para obter qualquer identificador de processo

Dica do SistemaEste artigo aplica-se a um sistema operativo diferente do que está a utilizar. Foi desactivado o conteúdo do artigo, que pode não ser relevante para si.

Nesta página

Expandir tudo | Recolher tudo

Sumário

Definindo o privilégio SeDebugPrivilege sobre o processo em execução, você pode obter o identificador de processo de qualquer aplicativo em execução. Ao obter o identificador para um processo, em seguida, você pode especificar o sinalizador PROCESS_ALL_ACCESS, que permitirá que a chamada de diversas APIs do Win32 após esse identificador de processo, você normalmente não pode fazer. Algumas das APIs do Win32 que pode ser chamado com êxito incluem o seguinte:
  • TerminateProcess
  • CreateRemoteThread
Este artigo contém um exemplo detalhado em como definir o SeDebugPrivilege após o token de processo do aplicativo e usar para encerrar outro aplicativo. Isso é um tópico avançado e um conhecimento de alta segurança do processo de segurança é altamente recomendável.

A discussão sobre o processo Access, tokens de processo e privilégios de token não são cobertos dentro do escopo deste artigo. Este artigo presume que o leitor já compreenda esses tópicos avançados.

Mais Informações

Este exemplo envolve criar três aplicativos separados do Visual Basic. Cada aplicativo ser criado um de cada vez e usado em conjunto para demonstrar o poder do privilégio de processo SeDebugPrivilege.

Aplicativo 1 (Term01.exe)

  1. Crie um novo projeto Standard EXE no Visual Basic 5.0.
  2. Altere o nome de projeto para Term01.
  3. Renomeie Form1 para frmTerm01.
  4. Adicione um botão de comando frmTerm01.
  5. Definir a legenda para Command1 para "Bloco de notas terminar".
  6. Adicione o seguinte código para frmTerm01:
          Option Explicit
    
          Private Sub Command1_Click()
    
             ' This is a simple application that attempts
             ' to shut down any process that is passed in through
             ' the command line.
    
             Call TerminateProcess(CLng(Command$), 0)
    
          End Sub
    
    						
  7. Adicione um módulo padrão para o projeto e renomeá-lo para MdlApi01.
  8. Adicione o seguinte código para MdlApi01:
          Option Explicit
    
          Declare Function TerminateProcess Lib "kernel32" _
             (ByVal hProcess As Long, _
             ByVal uExitCode As Long) As Long
    
    						
  9. Salve o projeto e tornar o arquivo exe (Term01.exe).

Aplicativo # 2 (Term02.exe)

  1. Crie um novo EXE padrão no Visual Basic 5.0.
  2. Altere o nome de projeto para Term02.
  3. Renomeie Form1 para frmTerm02.
  4. Adicione um botão de comando frmTerm02.
  5. Definir a legenda para Command1 para "Bloco de notas terminar".
  6. Adicione uma caixa de lista para frmTerm02.
  7. Defina a largura de ListBox1 para 3735.
  8. Adicione o seguinte código para frmTerm02:
          Private Sub Command1_Click()
    
             ' The PID of the application you want to kill will be received
             ' through the command line. Convert it to a long so it can be
             ' used with the various API calls.
    
             SeDebugSample CLng(Command$)
    
          End Sub
    
    						
  9. Adicione um módulo padrão para o projeto e renomeá-lo para mdlAPI02.
  10. Adicione o seguinte código ao mdlApi02 módulo:
          Option Explicit
    
          ' Constants used for various API calls. Refer to MSDN for detailed
          ' information about what these constants mean.
    
          Public Const TOKEN_ADJUST_PRIVILEGES = &H20
          Public Const TOKEN_QUERY = &H8
          Public Const ANYSIZE_ARRAY = 1
          Public Const PROCESS_ALL_ACCESS = &H1F0FFF
          Public Const SE_DEBUG_NAME = "SeDebugPrivilege"
          Public Const SE_PRIVILEGE_ENABLED = &H2
    
          ' Structures used with various API calls.
          ' Refer to MSDN for detailed information
          ' about what these structures are, and how they are used.
    
          Type LARGE_INTEGER
             lowpart As Long
             highpart As Long
          End Type
    
          Type Luid
             lowpart As Long
             highpart As Long
          End Type
    
          Type LUID_AND_ATTRIBUTES
             pLuid As Luid
             Attributes As Long
          End Type
    
          Type TOKEN_PRIVILEGES
             PrivilegeCount As Long
             Privileges(ANYSIZE_ARRAY) As LUID_AND_ATTRIBUTES
          End Type
    
          ' Refer to the MSDN for detailed information on
          ' all of these API calls.
    
          Declare Function CloseHandle Lib "kernel32" _
             (ByVal hObject As Long)As Long
          Declare Function GetCurrentProcess Lib "kernel32" () As Long
          Declare Function OpenProcessToken Lib "advapi32.dll" _
             (ByVal ProcessHandle As Long, ByVal DesiredAccess As Long, _
          TokenHandle As Long) As Long
          Declare Function LookupPrivilegeValue Lib "advapi32.dll" Alias _
             "LookupPrivilegeValueA" (ByVal lpSystemName As String, _
             ByVal lpName As String, lpLuid As Luid) As Long
          Declare Function AdjustTokenPrivileges Lib "advapi32.dll" _
             (ByVal TokenHandle As Long, ByVal DisableAllPrivileges As Long, _
             NewState As TOKEN_PRIVILEGES, ByVal BufferLength As Long, _
             PreviousState As TOKEN_PRIVILEGES, ReturnLength As Long) As Long
          Declare Function OpenProcess Lib "kernel32" _
             (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, _
             ByVal dwProcessId As Long) As Long
          Declare Function TerminateProcess Lib "kernel32" _
             (ByVal hProcess As Long, ByVal uExitCode As Long) As Long
    
          ' SeDebugSample shows how to grab the Process Handle of any running
          ' Application, and then use the SeDebug privilege to shut it down.
    
          Public Sub SeDebugSample(ApplicationPID As Long)
             Dim hProcessID As Long         ' Handle to your sample
                                            ' process you are going to
                                            ' terminate.
             Dim hProcess As Long           ' Handle to your current process
                                            ' (Term02.exe).
             Dim hToken As Long             ' Handle to your process token.
             Dim lPrivilege As Long         ' Privilege to enable/disable
             Dim iPrivilegeflag As Boolean  ' Flag whether to enable/disable
                                            ' the privilege of concern.
             Dim lResult As Long            ' Result call of various APIs.
    
             ' clear the list box first
             frmTerm02.List1.Clear
             frmTerm02.List1.AddItem "Start SeDebug Sample"
    
             ' set the incoming PID to our internal variable
             hProcessID = ApplicationPID
    
             ' get our current process handle
             hProcess = GetCurrentProcess
    
             ' show our handle just for fun
             frmTerm02.List1.AddItem "Current (Pseudo) Process Handle : " & _
                                     Hex(hProcess)
    
             ' open the tokens for this process (Term02.exe)
             lResult = OpenProcessToken(hProcess, TOKEN_ADJUST_PRIVILEGES Or _
                                       TOKEN_QUERY, hToken)
    
             ' if OpenProcessToken fails, the return result is zero, test for
             ' success here
    
             If (lResult = 0) Then
             frmTerm02.List1.AddItem "Error: _
                                     Unable To Open Process Token : " _
                                     & Err.LastDllError
                CloseHandle (hToken)
                Exit Sub
             Else
                ' show success
                frmTerm02.List1.AddItem "Opened Process Token : " & hToken
             End If
    
             ' Now that you have the token for this process, you want to set
             ' the SE_DEBUG_NAME privilege.
    
             lResult = SetPrivilege(hToken, SE_DEBUG_NAME, True)
    
             ' Make sure you could set the privilege on this token.
    
             If (lResult = False) Then
                frmTerm02.List1.AddItem _
                   "Error : Could Not Set SeDebug Privilege on Token Handle"
                CloseHandle (hToken)
                Exit Sub
             Else
                frmTerm02.List1.AddItem "Set SeDebug Privilege On Token Handle"
             End If
    
             ' Now that you have changed the privileges on the token,
             ' have some fun. You can now get a process handle to the
             ' process ID that you passed into this program, and
             ' demand whatever access you want on it!
    
             hProcess = OpenProcess(PROCESS_ALL_ACCESS, 0, hProcessID)
    
             ' Make sure you opened the process so you can do stuff with it
             If (hProcess = Null) Then
                frmTerm02.List1.AddItem _
                   "Error : Unable To Open Process : " & Err.LastDllError
                CloseHandle (hToken)
                Exit Sub
             Else
                frmTerm02.List1.AddItem "Opened Process : " & hProcess
             End If
    
             ' Now turn the SE_DEBUG_PRIV back off,
             lResult = SetPrivilege(hToken, SE_DEBUG_NAME, False)
    
             ' Make sure you succeeded in reversing the privilege!
             If (lResult = False) Then
                frmTerm02.List1.AddItem _
                  "Error : Unable To Disable SeDebug Privilege On Token Handle"
                CloseHandle (hProcess)
                CloseHandle (hToken)
                Exit Sub
             Else
                frmTerm02.List1.AddItem _
                   "Disabled SeDebug Privilege On Token Handle"
             End If
    
             ' Now you want to kill the application, which you can do since
             ' your process handle to the application includes full access to
             ' romp and roam - you got the process handle when you had the
             ' SE_DEBUG_NAME privilege enabled!
             lResult = TerminateProcess(hProcess, 0)
    
             ' Let's see the result, and go from there.
             If (lResult = 0) Then
                frmTerm02.List1.AddItem _
                "Error : Unable To Terminate Application : " & Err.LastDllError
                CloseHandle (hProcess)
                CloseHandle (hToken)
                Exit Sub
             Else
                frmTerm02.List1.AddItem "Terminated Application"
             End If
    
             ' Close our handles and get out of here.
             CloseHandle (hProcess)
             CloseHandle (hToken)
    
             ' Finally, let the user know that you have completed the
             ' SeDebug Sample.
             frmTerm02.List1.AddItem "SeDebug Sample Completed"
    
          End Sub
    
          ' The SetPrivilege function will accept a handle to a token, a
          ' privilege, and a flag to either enable/disable that privilege. The
          ' function will attempt to perform the desired action upon the token
          ' returning TRUE if it succeeded, or FALSE if it failed.
    
          Private Function SetPrivilege(hToken As Long, Privilege As String, _
                                        bSetFlag As Boolean) As Boolean
    
             Dim TP As TOKEN_PRIVILEGES          ' Used in getting the current
                                                 ' token privileges
             Dim TPPrevious As TOKEN_PRIVILEGES  ' Used in setting the new
                                                 ' token privileges
             Dim Luid As Luid                    ' Stores the Local Unique
                                                 ' Identifier - refer to MSDN
             Dim cbPrevious As Long              ' Previous size of the
                                                 ' TOKEN_PRIVILEGES structure
             Dim lResult As Long                 ' Result of various API calls
    
             ' Grab the size of the TOKEN_PRIVILEGES structure,
             ' used in making the API calls.
             cbPrevious = Len(TP)
    
             ' Grab the LUID for the request privilege.
             lResult = LookupPrivilegeValue("", Privilege, Luid)
    
             ' If LoopupPrivilegeValue fails, the return result will be zero.
             ' Test to make sure that the call succeeded.
             If (lResult = 0) Then
                SetPrivilege = False
             End If
    
             ' Set up basic information for a call.
             ' You want to retrieve the current privileges
             ' of the token under concern before you can modify them.
             TP.PrivilegeCount = 1
             TP.Privileges(0).pLuid = Luid
             TP.Privileges(0).Attributes = 0
             SetPrivilege = lResult
    
             ' You need to acquire the current privileges first
             lResult = AdjustTokenPrivileges(hToken, -1, TP, Len(TP), _
                                            TPPrevious, cbPrevious)
    
             ' If AdjustTokenPrivileges fails, the return result is zero,
             ' test for success.
             If (lResult = 0) Then
                SetPrivilege = False
             End If
    
             ' Now you can set the token privilege information
             ' to what the user is requesting.
             TPPrevious.PrivilegeCount = 1
             TPPrevious.Privileges(0).pLuid = Luid
    
             ' either enable or disable the privilege,
             ' depending on what the user wants.
             Select Case bSetFlag
                Case True: TPPrevious.Privileges(0).Attributes = _
                           TPPrevious.Privileges(0).Attributes Or _
                           (SE_PRIVILEGE_ENABLED)
                Case False: TPPrevious.Privileges(0).Attributes = _
                            TPPrevious.Privileges(0).Attributes Xor _
                            (SE_PRIVILEGE_ENABLED And _
                            TPPrevious.Privileges(0).Attributes)
             End Select
    
             ' Call adjust the token privilege information.
             lResult = AdjustTokenPrivileges(hToken, -1, TPPrevious, _
                                            cbPrevious, TP, cbPrevious)
    
             ' Determine your final result of this function.
             If (lResult = 0) Then
                ' You were not able to set the privilege on this token.
                SetPrivilege = False
             Else
                ' You managed to modify the token privilege
                SetPrivilege = True
             End If
    
          End Function
    
    						
  11. Salve o projeto no mesmo diretório como o projeto Term01 e tornar o arquivo .exe (Term02.exe).

Aplicativo 3 (MainTest.exe)

  1. Crie um novo projeto EXE padrão no Visual Basic 5.0.
  2. Renomeie o projeto para MainTest.
  3. Renomear frmTest para Form1.
  4. Adicione três botões de comando ao formulário.
  5. Definir a legenda para Command1 para "Bloco de notas iniciar".
  6. Definir a legenda para Command2 para "Iniciar Term01."
  7. Definir a legenda para Command3 para "Iniciar Term02."
  8. Adicione o seguinte código para frmTest:
          Option Explicit
    
          ' You want to keep the process ID of the NotePad instance
          ' that you create
          Private iAppPID As Long
    
          Private Sub Command1_Click()
    
             ' Create an instance of the NotePad.exe application.
             iAppPID = Shell("Notepad.exe", vbNormalFocus)
    
          End Sub
    
          Private Sub Command2_Click()
    
             ' You will try to terminate the NotePad application by another
             ' application, which is running in its own process space.
             ' This will FAIL.
    
             Call Shell(App.Path & "\Term01.Exe " & iAppPID, vbNormalFocus)
    
          End Sub
    
          Private Sub Command3_Click()
    
             ' You will try to terminate the NotePad application by another
             ' application, which is running in its own process space.
             ' However, this application is going to use the SeDebugPrivilege,
             ' and will be able to terminate the application without a fuss.
    
             Call Shell(App.Path & "\Term02.Exe " & iAppPID, vbNormalFocus)
    
          End Sub
    
    						
  9. Salve o projeto no mesmo diretório como o projeto Term01 e tornar o arquivo .exe (MainTest.exe).

Executando o exemplo

Depois de criados e compilados três aplicativos, você pode ver a demonstração em ação. No segundo aplicativo (Term02.exe), o código pressupõe que o aplicativo bloco de notas (Notepad.exe) está localizado dentro do caminho.
  1. Execute o programa MainTest.exe. Esse será o nosso "painel de controle" para a demonstração.
  2. Clique no botão Iniciar Bloco de notas. Isso iniciará o bloco de notas.
  3. Clique no botão Iniciar Term01. Isso iniciará o Term01 aplicativo.
  4. Clique no botão bloco de notas terminar no aplicativo Term01. Ele destina-se a desligar o bloco de notas, mas não terá êxito.
  5. Feche o aplicativo Term01.
  6. Clique no botão Iniciar Term02 no aplicativo MainTest. Isso iniciará o aplicativo Term02.
  7. Clique no botão terminar bloco de notas no aplicativo Term02. Isso irá iniciar a demonstração SeDebugPrivilege, que irá resultar no bloco de notas que está sendo encerrado. A caixa de lista fornece comentário visual para o que está acontecendo no processo.

A informação contida neste artigo aplica-se a:
  • Microsoft Visual Basic Control Creation Edition
  • Microsoft Visual Basic 5.0 Professional Edition
  • Microsoft Visual Basic 5.0 Enterprise Edition
Palavras-chave: 
kbmt kbcode kbhowto KB185215 KbMtpt
Tradução automáticaTradução automática
IMPORTANTE: Este artigo foi traduzido por um sistema de tradução automática (também designado por Machine Translation ou MT), não tendo sido portanto traduzido ou revisto por pessoas. A Microsoft possui artigos traduzidos por aplicações (MT) e artigos traduzidos por tradutores profissionais, com o objetivo de oferecer em português a totalidade dos artigos existentes na base de dados de suporte. No entanto, a tradução automática não é sempre perfeita, podendo conter erros de vocabulário, sintaxe ou gramática. A Microsoft não é responsável por incoerências, erros ou prejuízos ocorridos em decorrência da utilização dos artigos MT por parte dos nossos clientes. A Microsoft realiza atualizações freqüentes ao software de tradução automática (MT). Obrigado.
Clique aqui para ver a versão em Inglês deste artigo: 185215  (http://support.microsoft.com/kb/185215/en-us/ )
Retired KB ArticleAviso de Isenção de Responsabilidade sobre Conteúdo do KB Aposentado
Este artigo trata de produtos para os quais a Microsoft não mais oferece suporte. Por esta razão, este artigo é oferecido "como está" e não será mais atualizado.