示例#1
0
 internal static extern NtStatus LsaCallAuthenticationPackage(
     SafeLsaLogonHandle LsaHandle,
     uint AuthenticationPackage,
     SafeBuffer ProtocolSubmitBuffer,
     int SubmitBufferLength,
     out SafeLsaReturnBufferHandle ProtocolReturnBuffer,
     out int ReturnBufferLength,
     out NtStatus ProtocolStatus
     );
示例#2
0
 internal static extern int LsaLogonUser(
     [In]  SafeLsaHandle LsaHandle,
     [In]  ref LSA_STRING OriginName,
     [In]  SECURITY_LOGON_TYPE LogonType,
     [In]  int AuthenticationPackage,
     [In]  IntPtr AuthenticationInformation,
     [In]  int AuthenticationInformationLength,
     [In]  IntPtr LocalGroups,
     [In]  ref TOKEN_SOURCE SourceContext,
     [Out] out SafeLsaReturnBufferHandle ProfileBuffer,
     [Out] out int ProfileBufferLength,
     [Out] out LUID LogonId,
     [Out] out SafeAccessTokenHandle Token,
     [Out] out QUOTA_LIMITS Quotas,
     [Out] out int SubStatus
     );
示例#3
0
 internal static extern NtStatus LsaLogonUser(
     SafeLsaLogonHandle LsaHandle,
     LsaString OriginName,
     SecurityLogonType LogonType,
     uint AuthenticationPackage,
     SafeBuffer AuthenticationInformation,
     int AuthenticationInformationLength,
     SafeTokenGroupsBuffer LocalGroups,
     TOKEN_SOURCE SourceContext,
     out SafeLsaReturnBufferHandle ProfileBuffer,
     out int ProfileBufferLength,
     out Luid LogonId,
     out SafeKernelObjectHandle Token,
     QUOTA_LIMITS Quotas,
     out NtStatus SubStatus
     );
示例#4
0
 internal static extern NtStatus LsaGetLogonSessionData(
     ref Luid LogonId,
     out SafeLsaReturnBufferHandle ppLogonSessionData
     );
示例#5
0
 internal static extern NtStatus LsaEnumerateLogonSessions(
     out int LogonSessionCount,
     out SafeLsaReturnBufferHandle LogonSessionList
     );
 internal static extern int LsaGetLogonSessionData(ref LUID LogonId, out SafeLsaReturnBufferHandle ppLogonSessionData);
示例#7
0
 public static extern bool LogonUserEx(string lpszUserName, string lpszDomain, string lpszPassword, LogonUserType dwLogonType, LogonUserProvider dwLogonProvider,
                                       out SafeHTOKEN phObject, out PSID ppLogonSid, out SafeLsaReturnBufferHandle ppProfileBuffer, out uint pdwProfileLength, out QUOTA_LIMITS pQuotaLimits);
示例#8
0
        internal static WindowsIdentity KerberosCertificateLogon(X509Certificate2 certificate)
        {
            int status;
            SafeHGlobalHandle         pSourceName   = null;
            SafeHGlobalHandle         pPackageName  = null;
            SafeHGlobalHandle         pLogonInfo    = null;
            SafeLsaLogonProcessHandle logonHandle   = null;
            SafeLsaReturnBufferHandle profileHandle = null;
            SafeCloseHandle           tokenHandle   = null;

            try
            {
                pSourceName = SafeHGlobalHandle.AllocHGlobal(NativeMethods.LsaSourceName.Length + 1);
                Marshal.Copy(NativeMethods.LsaSourceName, 0, pSourceName.DangerousGetHandle(), NativeMethods.LsaSourceName.Length);
                UNICODE_INTPTR_STRING sourceName = new UNICODE_INTPTR_STRING(NativeMethods.LsaSourceName.Length, NativeMethods.LsaSourceName.Length + 1, pSourceName.DangerousGetHandle());

                Privilege privilege = null;

                RuntimeHelpers.PrepareConstrainedRegions();
                // Try to get an impersonation token.
                try
                {
                    // Try to enable the TCB privilege if possible
                    try
                    {
                        privilege = new Privilege(Privilege.SeTcbPrivilege);
                        privilege.Enable();
                    }
                    catch (PrivilegeNotHeldException ex)
                    {
                        DiagnosticUtility.TraceHandledException(ex, TraceEventType.Information);
                    }

                    IntPtr dummy = IntPtr.Zero;
                    status = NativeMethods.LsaRegisterLogonProcess(ref sourceName, out logonHandle, out dummy);
                    if (NativeMethods.ERROR_ACCESS_DENIED == NativeMethods.LsaNtStatusToWinError(status))
                    {
                        // We don't have the Tcb privilege. The best we can hope for is to get an Identification token.
                        status = NativeMethods.LsaConnectUntrusted(out logonHandle);
                    }
                    if (status < 0) // non-negative numbers indicate success
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(NativeMethods.LsaNtStatusToWinError(status)));
                    }
                }
                finally
                {
                    // if reverting privilege fails, fail fast!
                    int    revertResult = -1;
                    string message      = null;
                    try
                    {
                        revertResult = privilege.Revert();
                        if (revertResult != 0)
                        {
                            message = SR.GetString(SR.RevertingPrivilegeFailed, new Win32Exception(revertResult));
                        }
                    }
                    finally
                    {
                        if (revertResult != 0)
                        {
                            DiagnosticUtility.FailFast(message);
                        }
                    }
                }

                // package name ("Kerberos")
                pPackageName = SafeHGlobalHandle.AllocHGlobal(NativeMethods.LsaKerberosName.Length + 1);
                Marshal.Copy(NativeMethods.LsaKerberosName, 0, pPackageName.DangerousGetHandle(), NativeMethods.LsaKerberosName.Length);
                UNICODE_INTPTR_STRING packageName = new UNICODE_INTPTR_STRING(NativeMethods.LsaKerberosName.Length, NativeMethods.LsaKerberosName.Length + 1, pPackageName.DangerousGetHandle());

                uint packageId = 0;
                status = NativeMethods.LsaLookupAuthenticationPackage(logonHandle, ref packageName, out packageId);
                if (status < 0) // non-negative numbers indicate success
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(NativeMethods.LsaNtStatusToWinError(status)));
                }

                // source context
                TOKEN_SOURCE sourceContext = new TOKEN_SOURCE();
                if (!NativeMethods.AllocateLocallyUniqueId(out sourceContext.SourceIdentifier))
                {
                    int dwErrorCode = Marshal.GetLastWin32Error();
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(dwErrorCode));
                }

                // SourceContext
                sourceContext.Name    = new char[8];
                sourceContext.Name[0] = 'W'; sourceContext.Name[1] = 'C'; sourceContext.Name[2] = 'F';

                // LogonInfo
                byte[] certRawData   = certificate.RawData;
                int    logonInfoSize = KERB_CERTIFICATE_S4U_LOGON.Size + certRawData.Length;
                pLogonInfo = SafeHGlobalHandle.AllocHGlobal(logonInfoSize);
                unsafe
                {
                    KERB_CERTIFICATE_S4U_LOGON *pInfo = (KERB_CERTIFICATE_S4U_LOGON *)pLogonInfo.DangerousGetHandle().ToPointer();
                    pInfo->MessageType       = KERB_LOGON_SUBMIT_TYPE.KerbCertificateS4ULogon;
                    pInfo->Flags             = NativeMethods.KERB_CERTIFICATE_S4U_LOGON_FLAG_CHECK_LOGONHOURS;
                    pInfo->UserPrincipalName = new UNICODE_INTPTR_STRING(0, 0, IntPtr.Zero);
                    pInfo->DomainName        = new UNICODE_INTPTR_STRING(0, 0, IntPtr.Zero);
                    pInfo->CertificateLength = (uint)certRawData.Length;
                    pInfo->Certificate       = new IntPtr(pLogonInfo.DangerousGetHandle().ToInt64() + KERB_CERTIFICATE_S4U_LOGON.Size);
                    Marshal.Copy(certRawData, 0, pInfo->Certificate, certRawData.Length);
                }

                QUOTA_LIMITS quotas  = new QUOTA_LIMITS();
                LUID         logonId = new LUID();
                uint         profileBufferLength;
                int          subStatus = 0;

                // Call LsaLogonUser
                status = NativeMethods.LsaLogonUser(
                    logonHandle,
                    ref sourceName,
                    SecurityLogonType.Network,
                    packageId,
                    pLogonInfo.DangerousGetHandle(),
                    (uint)logonInfoSize,
                    IntPtr.Zero,
                    ref sourceContext,
                    out profileHandle,
                    out profileBufferLength,
                    out logonId,
                    out tokenHandle,
                    out quotas,
                    out subStatus
                    );

                // LsaLogon has restriction (eg. password expired).  SubStatus indicates the reason.
                if ((uint)status == NativeMethods.STATUS_ACCOUNT_RESTRICTION && subStatus < 0)
                {
                    status = subStatus;
                }
                if (status < 0) // non-negative numbers indicate success
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(NativeMethods.LsaNtStatusToWinError(status)));
                }
                if (subStatus < 0) // non-negative numbers indicate success
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(NativeMethods.LsaNtStatusToWinError(subStatus)));
                }

                return(new WindowsIdentity(tokenHandle.DangerousGetHandle(), SecurityUtils.AuthTypeCertMap));
            }
            finally
            {
                if (tokenHandle != null)
                {
                    tokenHandle.Close();
                }
                if (pLogonInfo != null)
                {
                    pLogonInfo.Close();
                }
                if (profileHandle != null)
                {
                    profileHandle.Close();
                }
                if (pSourceName != null)
                {
                    pSourceName.Close();
                }
                if (pPackageName != null)
                {
                    pPackageName.Close();
                }
                if (logonHandle != null)
                {
                    logonHandle.Close();
                }
            }
        }
        private static unsafe SafeTokenHandle KerbS4ULogon(string upn, ref SafeTokenHandle safeTokenHandle)
        {
            SafeTokenHandle handle6;

            byte[] array        = new byte[] { 0x43, 0x4c, 0x52 };
            IntPtr sizetdwBytes = new IntPtr((long)((ulong)(array.Length + 1)));

            using (SafeLocalAllocHandle handle = Win32Native.LocalAlloc(0x40, sizetdwBytes))
            {
                if ((handle == null) || handle.IsInvalid)
                {
                    throw new OutOfMemoryException();
                }
                handle.Initialize((ulong)(array.Length + 1L));
                handle.WriteArray <byte>(0L, array, 0, array.Length);
                Win32Native.UNICODE_INTPTR_STRING logonProcessName = new Win32Native.UNICODE_INTPTR_STRING(array.Length, handle);
                SafeLsaLogonProcessHandle         invalidHandle    = SafeLsaLogonProcessHandle.InvalidHandle;
                SafeLsaReturnBufferHandle         profileBuffer    = SafeLsaReturnBufferHandle.InvalidHandle;
                try
                {
                    int       num;
                    Privilege privilege = null;
                    RuntimeHelpers.PrepareConstrainedRegions();
                    try
                    {
                        try
                        {
                            privilege = new Privilege("SeTcbPrivilege");
                            privilege.Enable();
                        }
                        catch (PrivilegeNotHeldException)
                        {
                        }
                        IntPtr zero = IntPtr.Zero;
                        num = Win32Native.LsaRegisterLogonProcess(ref logonProcessName, ref invalidHandle, ref zero);
                        if (5 == Win32Native.LsaNtStatusToWinError(num))
                        {
                            num = Win32Native.LsaConnectUntrusted(ref invalidHandle);
                        }
                    }
                    catch
                    {
                        if (privilege != null)
                        {
                            privilege.Revert();
                        }
                        throw;
                    }
                    finally
                    {
                        if (privilege != null)
                        {
                            privilege.Revert();
                        }
                    }
                    if (num < 0)
                    {
                        throw GetExceptionFromNtStatus(num);
                    }
                    byte[] bytes = new byte["Kerberos".Length + 1];
                    Encoding.ASCII.GetBytes("Kerberos", 0, "Kerberos".Length, bytes, 0);
                    sizetdwBytes = new IntPtr((long)((ulong)bytes.Length));
                    using (SafeLocalAllocHandle handle4 = Win32Native.LocalAlloc(0, sizetdwBytes))
                    {
                        if ((handle4 == null) || handle4.IsInvalid)
                        {
                            throw new OutOfMemoryException();
                        }
                        handle4.Initialize((ulong)bytes.Length);
                        handle4.WriteArray <byte>(0L, bytes, 0, bytes.Length);
                        Win32Native.UNICODE_INTPTR_STRING packageName = new Win32Native.UNICODE_INTPTR_STRING("Kerberos".Length, handle4);
                        uint authenticationPackage = 0;
                        num = Win32Native.LsaLookupAuthenticationPackage(invalidHandle, ref packageName, ref authenticationPackage);
                        if (num < 0)
                        {
                            throw GetExceptionFromNtStatus(num);
                        }
                        Win32Native.TOKEN_SOURCE sourceContext = new Win32Native.TOKEN_SOURCE();
                        if (!Win32Native.AllocateLocallyUniqueId(ref sourceContext.SourceIdentifier))
                        {
                            throw new SecurityException(Win32Native.GetMessage(Marshal.GetLastWin32Error()));
                        }
                        sourceContext.Name    = new char[8];
                        sourceContext.Name[0] = 'C';
                        sourceContext.Name[1] = 'L';
                        sourceContext.Name[2] = 'R';
                        uint                     profileBufferLength = 0;
                        Win32Native.LUID         logonId             = new Win32Native.LUID();
                        Win32Native.QUOTA_LIMITS quotas = new Win32Native.QUOTA_LIMITS();
                        int    subStatus = 0;
                        byte[] buffer3   = Encoding.Unicode.GetBytes(upn);
                        int    num5      = Marshal.SizeOf(typeof(Win32Native.KERB_S4U_LOGON)) + buffer3.Length;
                        using (SafeLocalAllocHandle handle5 = Win32Native.LocalAlloc(0x40, new IntPtr(num5)))
                        {
                            if ((handle5 == null) || handle5.IsInvalid)
                            {
                                throw new OutOfMemoryException();
                            }
                            handle5.Initialize((ulong)num5);
                            ulong byteOffset = (ulong)Marshal.SizeOf(typeof(Win32Native.KERB_S4U_LOGON));
                            handle5.WriteArray <byte>(byteOffset, buffer3, 0, buffer3.Length);
                            byte *pointer = null;
                            RuntimeHelpers.PrepareConstrainedRegions();
                            try
                            {
                                handle5.AcquirePointer(ref pointer);
                                Win32Native.KERB_S4U_LOGON kerb_su_logon = new Win32Native.KERB_S4U_LOGON {
                                    MessageType = 12,
                                    Flags       = 0,
                                    ClientUpn   = new Win32Native.UNICODE_INTPTR_STRING(buffer3.Length, new IntPtr((void *)(pointer + byteOffset)))
                                };
                                handle5.Write <Win32Native.KERB_S4U_LOGON>(0L, kerb_su_logon);
                                num = Win32Native.LsaLogonUser(invalidHandle, ref logonProcessName, 3, authenticationPackage, new IntPtr((void *)pointer), (uint)handle5.ByteLength, IntPtr.Zero, ref sourceContext, ref profileBuffer, ref profileBufferLength, ref logonId, ref safeTokenHandle, ref quotas, ref subStatus);
                                if ((num == -1073741714) && (subStatus < 0))
                                {
                                    num = subStatus;
                                }
                                if (num < 0)
                                {
                                    throw GetExceptionFromNtStatus(num);
                                }
                                if (subStatus < 0)
                                {
                                    throw GetExceptionFromNtStatus(subStatus);
                                }
                            }
                            finally
                            {
                                if (pointer != null)
                                {
                                    handle5.ReleasePointer();
                                }
                            }
                        }
                        handle6 = safeTokenHandle;
                    }
                }
                finally
                {
                    if (!invalidHandle.IsInvalid)
                    {
                        invalidHandle.Dispose();
                    }
                    if (!profileBuffer.IsInvalid)
                    {
                        profileBuffer.Dispose();
                    }
                }
            }
            return(handle6);
        }
        private static unsafe WindowsIdentity KerberosCertificateLogon(X509Certificate2 certificate)
        {
            SafeHGlobalHandle         handle        = null;
            SafeHGlobalHandle         handle2       = null;
            SafeHGlobalHandle         handle3       = null;
            SafeLsaLogonProcessHandle lsaHandle     = null;
            SafeLsaReturnBufferHandle profileBuffer = null;
            SafeCloseHandle           token         = null;
            WindowsIdentity           identity;

            try
            {
                int  num;
                uint num6;
                handle = SafeHGlobalHandle.AllocHGlobal((int)(System.IdentityModel.NativeMethods.LsaSourceName.Length + 1));
                Marshal.Copy(System.IdentityModel.NativeMethods.LsaSourceName, 0, handle.DangerousGetHandle(), System.IdentityModel.NativeMethods.LsaSourceName.Length);
                UNICODE_INTPTR_STRING          logonProcessName = new UNICODE_INTPTR_STRING(System.IdentityModel.NativeMethods.LsaSourceName.Length, System.IdentityModel.NativeMethods.LsaSourceName.Length + 1, handle.DangerousGetHandle());
                System.IdentityModel.Privilege privilege        = null;
                RuntimeHelpers.PrepareConstrainedRegions();
                try
                {
                    try
                    {
                        privilege = new System.IdentityModel.Privilege("SeTcbPrivilege");
                        privilege.Enable();
                    }
                    catch (PrivilegeNotHeldException exception)
                    {
                        if (DiagnosticUtility.ShouldTraceInformation)
                        {
                            DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Information);
                        }
                    }
                    IntPtr zero = IntPtr.Zero;
                    num = System.IdentityModel.NativeMethods.LsaRegisterLogonProcess(ref logonProcessName, out lsaHandle, out zero);
                    if (5 == System.IdentityModel.NativeMethods.LsaNtStatusToWinError(num))
                    {
                        num = System.IdentityModel.NativeMethods.LsaConnectUntrusted(out lsaHandle);
                    }
                    if (num < 0)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(System.IdentityModel.NativeMethods.LsaNtStatusToWinError(num)));
                    }
                }
                finally
                {
                    int    error   = -1;
                    string message = null;
                    try
                    {
                        error = privilege.Revert();
                        if (error != 0)
                        {
                            message = System.IdentityModel.SR.GetString("RevertingPrivilegeFailed", new object[] { new Win32Exception(error) });
                        }
                    }
                    finally
                    {
                        if (error != 0)
                        {
                            DiagnosticUtility.FailFast(message);
                        }
                    }
                }
                handle2 = SafeHGlobalHandle.AllocHGlobal((int)(System.IdentityModel.NativeMethods.LsaKerberosName.Length + 1));
                Marshal.Copy(System.IdentityModel.NativeMethods.LsaKerberosName, 0, handle2.DangerousGetHandle(), System.IdentityModel.NativeMethods.LsaKerberosName.Length);
                UNICODE_INTPTR_STRING packageName = new UNICODE_INTPTR_STRING(System.IdentityModel.NativeMethods.LsaKerberosName.Length, System.IdentityModel.NativeMethods.LsaKerberosName.Length + 1, handle2.DangerousGetHandle());
                uint authenticationPackage        = 0;
                num = System.IdentityModel.NativeMethods.LsaLookupAuthenticationPackage(lsaHandle, ref packageName, out authenticationPackage);
                if (num < 0)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(System.IdentityModel.NativeMethods.LsaNtStatusToWinError(num)));
                }
                TOKEN_SOURCE sourceContext = new TOKEN_SOURCE();
                if (!System.IdentityModel.NativeMethods.AllocateLocallyUniqueId(out sourceContext.SourceIdentifier))
                {
                    int num4 = Marshal.GetLastWin32Error();
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(num4));
                }
                sourceContext.Name    = new char[8];
                sourceContext.Name[0] = 'W';
                sourceContext.Name[1] = 'C';
                sourceContext.Name[2] = 'F';
                byte[] rawData = certificate.RawData;
                int    cb      = KERB_CERTIFICATE_S4U_LOGON.Size + rawData.Length;
                handle3 = SafeHGlobalHandle.AllocHGlobal(cb);
                KERB_CERTIFICATE_S4U_LOGON *kerb_certificate_su_logonPtr = (KERB_CERTIFICATE_S4U_LOGON *)handle3.DangerousGetHandle().ToPointer();
                kerb_certificate_su_logonPtr->MessageType       = KERB_LOGON_SUBMIT_TYPE.KerbCertificateS4ULogon;
                kerb_certificate_su_logonPtr->Flags             = 2;
                kerb_certificate_su_logonPtr->UserPrincipalName = new UNICODE_INTPTR_STRING(0, 0, IntPtr.Zero);
                kerb_certificate_su_logonPtr->DomainName        = new UNICODE_INTPTR_STRING(0, 0, IntPtr.Zero);
                kerb_certificate_su_logonPtr->CertificateLength = (uint)rawData.Length;
                kerb_certificate_su_logonPtr->Certificate       = new IntPtr(handle3.DangerousGetHandle().ToInt64() + KERB_CERTIFICATE_S4U_LOGON.Size);
                Marshal.Copy(rawData, 0, kerb_certificate_su_logonPtr->Certificate, rawData.Length);
                QUOTA_LIMITS quotas    = new QUOTA_LIMITS();
                LUID         logonId   = new LUID();
                int          subStatus = 0;
                num = System.IdentityModel.NativeMethods.LsaLogonUser(lsaHandle, ref logonProcessName, System.IdentityModel.SecurityLogonType.Network, authenticationPackage, handle3.DangerousGetHandle(), (uint)cb, IntPtr.Zero, ref sourceContext, out profileBuffer, out num6, out logonId, out token, out quotas, out subStatus);
                if ((num == -1073741714) && (subStatus < 0))
                {
                    num = subStatus;
                }
                if (num < 0)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(System.IdentityModel.NativeMethods.LsaNtStatusToWinError(num)));
                }
                if (subStatus < 0)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(System.IdentityModel.NativeMethods.LsaNtStatusToWinError(subStatus)));
                }
                identity = new WindowsIdentity(token.DangerousGetHandle(), "SSL/PCT");
            }
            finally
            {
                if (token != null)
                {
                    token.Close();
                }
                if (handle3 != null)
                {
                    handle3.Close();
                }
                if (profileBuffer != null)
                {
                    profileBuffer.Close();
                }
                if (handle != null)
                {
                    handle.Close();
                }
                if (handle2 != null)
                {
                    handle2.Close();
                }
                if (lsaHandle != null)
                {
                    lsaHandle.Close();
                }
            }
            return(identity);
        }