Démarrer un processus en tant qu’autre utilisateur à partir de Visual Basic

Cet article explique comment rediriger l’entrée et la sortie d’un processus enfant qui reçoit l’entrée du handle d’entrée standard ou qui envoie la sortie au handle de sortie standard.

Version du produit d’origine : Visual Basic
Numéro de la base de connaissances d’origine : 285879

Résumé

Cet article vous montre comment démarrer par programmation un processus en tant qu’autre utilisateur de Microsoft Visual Basic. Pour ce faire, vous pouvez utiliser les LogonUser API Win32 et CreateProcessAsUser Win32 sur un ordinateur exécutant Windows NT 4.0, ou vous pouvez utiliser l’API CreateProcessWithLogonW Win32 sur un ordinateur exécutant Windows 2000 ou version ultérieure. CreateProcessWithLogonW ne peut pas être appelé à partir d’un processus sous le compte LocalSystem.

Plus d’informations

Cet article contient un exemple de code Visual Basic qui détecte la version du système d’exploitation. Il utilise ensuite les API correspondantes pour démarrer un processus en tant qu’autre utilisateur.

Windows NT 4.0

  • Pour utiliser LogonUser et CreateProcessAsUser, le compte d’utilisateur appelant doit disposer de certaines autorisations.

  • Pour utiliser LogonUser(), le compte d’utilisateur appelant doit disposer de l’autorisation suivante :

    Autorisation Display Name SE_TCB_NAME Act dans le cadre du système d’exploitation

  • Pour utiliser CreateProcessAsUser(), le compte d’utilisateur appelant doit disposer des deux autorisations suivantes :

    Nom complet de l’autorisation

    • SE_ASSIGNPRIMARYTOKEN_NAME Remplacer un jeton de niveau processus
    • SE_INCREASE_QUOTA_NAME Augmenter les quotas

Si le compte d’utilisateur appelant n’est pas autorisé à « agir dans le cadre du système d’exploitation », l’API LogonUser() échoue et génère une valeur de retour de zéro. Si vous appelez Err.LastDllError, vous recevez le message d’erreur 1314. Ce message signifie qu’une autorisation requise n’est pas détenue par le client. De même, si le compte d’utilisateur appelant n’a pas les deux autorisations nécessaires pour « remplacer un jeton de niveau processus » et pour « augmenter les quotas », l’API CreateProcessAsUser() échoue et génère le message d’erreur 1314.

Si vous démarrez une application interactive en tant qu’autre utilisateur, vous devez avoir accès à la station de fenêtre interactive et au bureau nommé winsta0\default. Si l’application est interactive, l’appelant doit ajouter par programmation l’autorisation requise à winsta0\default. Après cela, l’appelant peut appeler la RunAsUser fonction d’assistance dans l’exemple de code Visual Basic ci-dessous.

Vous devez accorder suffisamment d’autorisations au compte d’utilisateur spécifié afin LogonUser() que l’application interactive puisse démarrer correctement. L’article suivant de la Base de connaissances contient des exemples de code Visual Basic que vous pouvez utiliser pour mettre à jour les autorisations sur une station de fenêtre et un bureau.

Windows 2000 et versions ultérieures

L’API CreateProcessWithLogonW() a été introduite dans Windows 2000. Un appel à CreateProcessWithLogonW() ne nécessite pas d’autorisations pour le compte d’utilisateur appelant, comme il le fait avec les API et CreateProcessAsUser logonUser.

À l’avenir, utilisez l’API CreateProcessWithLogonW() . Il gère les autorisations associées à la station de fenêtre héritée et au bureau. Dans ce scénario, l’application appelle simplement la RunAsUser fonction d’assistance dans l’exemple de code Visual Basic suivant.

Option Explicit

Private Const CREATE_DEFAULT_ERROR_MODE = &H4000000

Private Const LOGON_WITH_PROFILE = &H1
Private Const LOGON_NETCREDENTIALS_ONLY = &H2

Private Const LOGON32_LOGON_INTERACTIVE = 2
Private Const LOGON32_PROVIDER_DEFAULT = 0

Private Type STARTUPINFO
    cb As Long
    lpReserved As Long ' !!! must be Long for Unicode string
    lpDesktop As Long ' !!! must be Long for Unicode string
    lpTitle As Long ' !!! must be Long for Unicode string
    dwX As Long
    dwY As Long
    dwXSize As Long
    dwYSize As Long
    dwXCountChars As Long
    dwYCountChars As Long
    dwFillAttribute As Long
    dwFlags As Long
    wShowWindow As Integer
    cbReserved2 As Integer
    lpReserved2 As Long
    hStdInput As Long
    hStdOutput As Long
    hStdError As Long
End Type

Private Type PROCESS_INFORMATION
    hProcess As Long
    hThread As Long
    dwProcessId As Long
    dwThreadId As Long
End Type

' LogonUser() requires that the caller has the following permission
' Permission Display Name
' --------------------------------------------------------------------
' SE_TCB_NAME Act as part of the operating system

' CreateProcessAsUser() requires that the caller has the following permissions
' Permission Display Name
' ---------------------------------------------------------------
' SE_ASSIGNPRIMARYTOKEN_NAME Replace a process level token
' SE_INCREASE_QUOTA_NAME Increase quotas

Private Declare Function LogonUser Lib "advapi32.dll" Alias _"LogonUserA" _(ByVal lpszUsername As String, _ByVal lpszDomain As String, _ByVal lpszPassword As String, _ByVal dwLogonType As Long, _ByVal dwLogonProvider As Long, _phToken As Long) As Long

Private Declare Function CreateProcessAsUser Lib "advapi32.dll" _Alias "CreateProcessAsUserA" _(ByVal hToken As Long, _ByVal lpApplicationName As Long, _ByVal lpCommandLine As String, _ByVal lpProcessAttributes As Long, _ByVal lpThreadAttributes As Long, _ByVal bInheritHandles As Long, _ByVal dwCreationFlags As Long, _ByVal lpEnvironment As Long, _ByVal lpCurrentDirectory As String, _lpStartupInfo As STARTUPINFO, _lpProcessInformation As PROCESS_INFORMATION) As Long

' CreateProcessWithLogonW API is available only on Windows 2000 and later.
Private Declare Function CreateProcessWithLogonW Lib "advapi32.dll" _(ByVal lpUsername As String, _ByVal lpDomain As String, _ByVal lpPassword As String, _ByVal dwLogonFlags As Long, _ByVal lpApplicationName As Long, _ByVal lpCommandLine As String, _ByVal dwCreationFlags As Long, _ByVal lpEnvironment As Long, _ByVal lpCurrentDirectory As String, _ByRef lpStartupInfo As STARTUPINFO, _ByRef lpProcessInformation As PROCESS_INFORMATION) As Long

Private Declare Function CloseHandle Lib "kernel32.dll" _(ByVal hObject As Long) As Long

Private Declare Function SetErrorMode Lib "kernel32.dll" _(ByVal uMode As Long) As Long

Private Type OSVERSIONINFO
    dwOSVersionInfoSize As Long
    dwMajorVersion As Long
    dwMinorVersion As Long
    dwBuildNumber As Long
    dwPlatformId As Long
    szCSDVersion As String * 128
End Type

' Version Checking APIs
Private Declare Function GetVersionExA Lib "kernel32.dll" _(lpVersionInformation As OSVERSIONINFO) As Integer

Private Const VER_PLATFORM_WIN32_NT = &H2

'********************************************************************' RunAsUser for Windows 2000 and Later
'********************************************************************
Public Function W2KRunAsUser(ByVal UserName As String, _ByVal Password As String, _ByVal DomainName As String, _ByVal CommandLine As String, _ByVal CurrentDirectory As String) As Long

    Dim si As STARTUPINFO
    Dim pi As PROCESS_INFORMATION
    Dim wUser As String
    Dim wDomain As String
    Dim wPassword As String
    Dim wCommandLine As String
    Dim wCurrentDir As String

    Dim Result As Long

    si.cb = Len(si)

    wUser = StrConv(UserName + Chr$(0), vbUnicode)
    wDomain = StrConv(DomainName + Chr$(0), vbUnicode)
    wPassword = StrConv(Password + Chr$(0), vbUnicode)
    wCommandLine = StrConv(CommandLine + Chr$(0), vbUnicode)
    wCurrentDir = StrConv(CurrentDirectory + Chr$(0), vbUnicode)

    Result = CreateProcessWithLogonW(wUser, wDomain, wPassword, _LOGON_WITH_PROFILE, 0&, wCommandLine, _CREATE_DEFAULT_ERROR_MODE, 0&, wCurrentDir, si, pi)' CreateProcessWithLogonW() does not
    If Result <> 0 Then
        CloseHandle pi.hThread
        CloseHandle pi.hProcess
        W2KRunAsUser = 0
    Else
        W2KRunAsUser = Err.LastDllError
        MsgBox "CreateProcessWithLogonW() failed with error " & Err.LastDllError, vbExclamation
    End If

End Function

'********************************************************************' RunAsUser for Windows NT 4.0
'********************************************************************
Public Function NT4RunAsUser(ByVal UserName As String, _ByVal Password As String, _ByVal DomainName As String, _ByVal CommandLine As String, _ByVal CurrentDirectory As String) As Long
    Dim Result As Long
    Dim hToken As Long
    Dim si As STARTUPINFO
    Dim pi As PROCESS_INFORMATION

    Result = LogonUser(UserName, DomainName, Password, LOGON32_LOGON_INTERACTIVE, _
    LOGON32_PROVIDER_DEFAULT, hToken)
    If Result = 0 Then
        NT4RunAsUser = Err.LastDllError
        ' LogonUser will fail with 1314 error code, if the user account associated
        ' with the calling security context does not have
        ' "Act as part of the operating system" permission
        MsgBox "LogonUser() failed with error " & Err.LastDllError, vbExclamation
        Exit Function
    End If

    si.cb = Len(si)
    Result = CreateProcessAsUser(hToken, 0&, CommandLine, 0&, 0&, False, _
    CREATE_DEFAULT_ERROR_MODE, _
    0&, CurrentDirectory, si, pi)
    If Result = 0 Then
        NT4RunAsUser = Err.LastDllError
        ' CreateProcessAsUser will fail with 1314 error code, if the user
        ' account associated with the calling security context does not have
        ' the following two permissions
        ' "Replace a process level token"
        ' "Increase Quotoas"
        MsgBox "CreateProcessAsUser() failed with error " & Err.LastDllError, vbExclamation
        CloseHandle hToken
        Exit Function
    End If

    CloseHandle hToken
    CloseHandle pi.hThread
    CloseHandle pi.hProcess
    NT4RunAsUser = 0

End Function

Public Function RunAsUser(ByVal UserName As String, _ByVal Password As String, _ByVal DomainName As String, _ByVal CommandLine As String, _ByVal CurrentDirectory As String) As Long

    Dim w2kOrAbove As Boolean
    Dim osinfo As OSVERSIONINFO
    Dim Result As Long
    Dim uErrorMode As Long

    ' Determine if system is Windows 2000 or later
    osinfo.dwOSVersionInfoSize = Len(osinfo)
    osinfo.szCSDVersion = Space$(128)
    GetVersionExA osinfo
    w2kOrAbove = _
    (osinfo.dwPlatformId = VER_PLATFORM_WIN32_NT And _
    osinfo.dwMajorVersion >= 5)
    If (w2kOrAbove) Then
    Result = W2KRunAsUser(UserName, Password, DomainName, _
    CommandLine, CurrentDirectory)
    Else
    Result = NT4RunAsUser(UserName, Password, DomainName, _
    CommandLine, CurrentDirectory)
    End If
    RunAsUser = Result
End Function