vb.net – 从其他不受信任的域模拟Windows或Active Directory用户

前端之家收集整理的这篇文章主要介绍了vb.net – 从其他不受信任的域模拟Windows或Active Directory用户前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要使用Windows身份验证对远程sql Server进行身份验证.远程sql Server在另一个域中运行,该域与我当前通过Windows登录的域没有信任关系.我无法使用sql Server身份验证,因为sql Server配置为仅信任域身份验证.

Windows本身允许通过用户界面进行此类模拟:

我之前使用过System.Security.Principal中的WindowsImpersonationContext类,但这似乎依赖于属于受信任域的所需用户名.

我正在使用Visual Studio 2012,最多可以使用Microsoft.Net 4.5,最好是VB,但如果需要,我可以轻松地从C#转换代码.

为了未来访问者的利益,我发布了一些VB.Net代码,允许进程使用NETONLY模拟对驻留在不受信任域中的远程服务器进行身份验证:
Option Explicit On
Option Infer Off

Imports System
Imports System.Runtime.InteropServices '   DllImport
Imports System.Security.Principal '  WindowsImpersonationContext

Public Class clsAuthenticator

    ' group type enum
    Enum SECURITY_IMPERSONATION_LEVEL As Int32
        SecurityAnonymous = 0
        SecurityIdentification = 1
        SecurityImpersonation = 2
        SecurityDelegation = 3
    End Enum

    Public Enum logonType As Integer
        'This logon type is intended for users who will be interactively using the computer,such as a user being logged on
        'by a terminal server,remote shell,or similar process.
        'This logon type has the additional expense of caching logon information for disconnected operations;
        'therefore,it is inappropriate for some client/server applications,'such as a mail server.
        logoN32_logoN_INTERACTIVE = 2

        'This logon type is intended for high performance servers to authenticate plaintext passwords.
        'The logonUser function does not cache credentials for this logon type.
        logoN32_logoN_NETWORK = 3

        'This logon type is intended for batch servers,where processes may be executing on behalf of a user without
        'their direct intervention. This type is also for higher performance servers that process many plaintext
        'authentication attempts at a time,such as mail or Web servers.
        'The logonUser function does not cache credentials for this logon type.
        logoN32_logoN_BATCH = 4

        'Indicates a service-type logon. The account provided must have the service privilege enabled.
        logoN32_logoN_SERVICE = 5

        'This logon type is for GINA DLLs that log on users who will be interactively using the computer.
        'This logon type can generate a unique audit record that shows when the workstation was unlocked.
        logoN32_logoN_UNLOCK = 7

        'This logon type preserves the name and password in the authentication package,which allows the server to make
        'connections to other network servers while impersonating the client. A server can accept plaintext credentials
        'from a client,call logonUser,verify that the user can access the system across the network,and still
        'communicate with other servers.
        'NOTE: Windows NT:  This value is not supported.
        logoN32_logoN_NETWORK_CLEARTEXT = 8

        'This logon type allows the caller to clone its current token and specify new credentials for outbound connections.
        'The new logon session has the same local identifier but uses different credentials for other network connections.
        'NOTE: This logon type is supported only by the logoN32_PROVIDER_WINNT50 logon provider.
        'NOTE: Windows NT:  This value is not supported.
        logoN32_logoN_NEW_CREDENTIALS = 9
    End Enum

    Public Enum logonProvider As Integer
        'Use the standard logon provider for the system.
        'The default security provider is negotiate,unless you pass NULL for the domain name and the user name
        'is not in UPN format. In this case,the default provider is NTLM.
        'NOTE: Windows 2000/NT:   The default security provider is NTLM.
        logoN32_PROVIDER_DEFAULT = 0
        logoN32_PROVIDER_WINNT35 = 1
        logoN32_PROVIDER_WINNT40 = 2
        logoN32_PROVIDER_WINNT50 = 3
    End Enum

    ' obtains user token
    Declare Auto Function logonUser Lib "advapi32.dll" (ByVal lpszUsername As String,ByVal lpszDomain As String,ByVal lpszPassword As String,ByVal dwlogonType As logonType,ByVal dwlogonProvider As logonProvider,ByRef phToken As IntPtr) As Integer


    ' closes open handles returned by logonUser
    Declare Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Boolean

    ' creates duplicate token handle
    Declare Auto Function DuplicateToken Lib "advapi32.dll" (ExistingTokenHandle As IntPtr,SECURITY_IMPERSONATION_LEVEL As Int16,ByRef DuplicateTokenHandle As IntPtr) As Boolean

    'WindowsImpersonationContext newUser;
    Private newUser As WindowsImpersonationContext


    ' 
    ' Attempts to impersonate a user.  If successful,returns 
    ' a WindowsImpersonationContext of the new user's identity.
    ' 
    ' Username you want to impersonate
    ' logon domain
    ' User's password to logon with
    ' 
    Public Sub Impersonator(ByVal sDomain As String,ByVal sUsername As String,ByVal sPassword As String)
        ' initialize tokens

        Dim pExistingTokenHandle As New IntPtr(0)
        Dim pDuplicateTokenHandle As New IntPtr(0)

        If sDomain = "" Then
            sDomain = System.Environment.MachineName
        End If

        Try

            Const logoN32_PROVIDER_DEFAULT As Int32 = 0
            Const logoN32_logoN_NEW_CREDENTIALS = 9

            Dim bImpersonated As Boolean = logonUser(sUsername,sDomain,sPassword,logoN32_logoN_NEW_CREDENTIALS,logoN32_PROVIDER_DEFAULT,pExistingTokenHandle)

            If bImpersonated = False Then
                Dim nErrorCode As Int32 = Marshal.GetLastWin32Error()
                Throw New ApplicationException("logonUser() Failed with error code: " & nErrorCode.ToString)
            End If

            Dim bRetVal As Boolean = DuplicateToken(pExistingTokenHandle,SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation,pDuplicateTokenHandle)
            If bRetVal = False Then
                Dim nErrorCode As Int32 = Marshal.GetLastWin32Error
                CloseHandle(pExistingTokenHandle)
                Throw New ApplicationException("DuplicateToken() Failed with error code: " & nErrorCode)
            Else
                Dim newId As New WindowsIdentity(pDuplicateTokenHandle)
                Dim impersonatedUser As WindowsImpersonationContext = newId.Impersonate
                newUser = impersonatedUser
            End If

        Catch ex As Exception

        Finally
            If pExistingTokenHandle <> IntPtr.Zero Then
                CloseHandle(pExistingTokenHandle)
            End If
            If pDuplicateTokenHandle <> IntPtr.Zero Then
                CloseHandle(pDuplicateTokenHandle)
            End If
        End Try

    End Sub

    Public Sub Undo()
        newUser.Undo()
    End Sub
End Class

这可以从另一段代码调用,如下所示:

Dim Impersonator As New clsAuthenticator
Dim sDomain as string = "SomeDomain"
Dim sUser as string = "SomeUserName"
Dim sPass as string = "SomePassword"
Impersonator.Impersonator(sDomain,sUser,sPass)
' Run whatever code needs to run against the remote server
Impersonator.Undo

不在代码中实际嵌入密码的标准警告当然适用于此.在现实世界中,我的应用程序从数据库中的加密列获取密码.

原文链接:https://www.f2er.com/vb/255947.html

猜你在找的VB相关文章