Ejemplo n.º 1
0
        internal static CryptoKeySecurity GetKeySetSecurityInfo(SafeProvHandle hProv, AccessControlSections accessControlSections)
        {
            SecurityInfos securityInfo = (SecurityInfos)0;
            Privilege     privilege    = (Privilege)null;

            if ((accessControlSections & AccessControlSections.Owner) != AccessControlSections.None)
            {
                securityInfo |= SecurityInfos.Owner;
            }
            if ((accessControlSections & AccessControlSections.Group) != AccessControlSections.None)
            {
                securityInfo |= SecurityInfos.Group;
            }
            if ((accessControlSections & AccessControlSections.Access) != AccessControlSections.None)
            {
                securityInfo |= SecurityInfos.DiscretionaryAcl;
            }
            byte[] binaryForm = (byte[])null;
            RuntimeHelpers.PrepareConstrainedRegions();
            int error;

            try
            {
                if ((accessControlSections & AccessControlSections.Audit) != AccessControlSections.None)
                {
                    securityInfo |= SecurityInfos.SystemAcl;
                    privilege     = new Privilege("SeSecurityPrivilege");
                    privilege.Enable();
                }
                binaryForm = Utils._GetKeySetSecurityInfo(hProv, securityInfo, out error);
            }
            finally
            {
                if (privilege != null)
                {
                    privilege.Revert();
                }
            }
            if (error == 0 && (binaryForm == null || binaryForm.Length == 0))
            {
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoSecurityDescriptor"));
            }
            if (error == 8)
            {
                throw new OutOfMemoryException();
            }
            if (error == 5)
            {
                throw new UnauthorizedAccessException();
            }
            if (error == 1314)
            {
                throw new PrivilegeNotHeldException("SeSecurityPrivilege");
            }
            if (error != 0)
            {
                throw new CryptographicException(error);
            }
            return(new CryptoKeySecurity(new CommonSecurityDescriptor(false, false, new RawSecurityDescriptor(binaryForm, 0), true)));
        }
Ejemplo n.º 2
0
        public static void TakeOwnFile(string path)
        {
            FileInfo     fileInfo     = new FileInfo(path);
            FileSecurity fileSecurity = fileInfo.GetAccessControl();

            fileSecurity.SetOwner(WindowsIdentity.GetCurrent().User);

            Privilege p = new Privilege(Privilege.TakeOwnership);
            bool      ownershipTaken = false;

            try
            {
                p.Enable();

                new FileInfo(path).SetAccessControl(fileSecurity);
                ownershipTaken = true;
            }
            catch (PrivilegeClass.PrivilegeNotHeldException e)
            {
                Console.WriteLine("Failed to assign privileges. " + e.ToString());
            }
            finally
            {
                p.Revert();
            }

            if (ownershipTaken)
            {
                AdjustPermissionsForFile(path);
            }
        }
Ejemplo n.º 3
0
 private static bool EnablePrivilege(string name)
 {
     try
     {
         Privilege.Enable(name);
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Ejemplo n.º 4
0
        public static Exception RunWithPrivilege(string privilege, Action action)
        {
            Exception result = null;

            try
            {
                using (Privilege privilege2 = new Privilege(privilege))
                {
                    privilege2.Enable();
                    action();
                }
            }
            catch (PrivilegeNotHeldException ex)
            {
                result = ex;
            }
            return(result);
        }
Ejemplo n.º 5
0
        public static void TakeOwnDirectory(string path)
        {
            DirectoryInfo     directoryInfo     = new DirectoryInfo(path);
            DirectorySecurity directorySecurity = directoryInfo.GetAccessControl();

            directorySecurity.SetOwner(WindowsIdentity.GetCurrent().User);

            Privilege p = new Privilege(Privilege.TakeOwnership);
            bool      ownershipTaken = false;

            try
            {
                p.Enable();

                new DirectoryInfo(path).SetAccessControl(directorySecurity);
                ownershipTaken = true;
            }
            catch (PrivilegeClass.PrivilegeNotHeldException e)
            {
                Console.WriteLine("Failed to assign privileges. " + e.ToString());
            }
            finally
            {
                p.Revert();
            }

            if (ownershipTaken)
            {
                AdjustPermissionsForDirectory(path);

                var subFiles = Directory.EnumerateFiles(path);
                foreach (var subFile in subFiles)
                {
                    TakeOwnFile(subFile);
                }

                var subDirectories = Directory.EnumerateDirectories(path);
                foreach (var subDir in subDirectories)
                {
                    TakeOwnDirectory(subDir);
                }
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Pass ownership and full control of the specified file or directory to the Administrators group. The process must run elevated to do this.
        /// </summary>
        /// <param name="path">File or directory</param>
        /// <param name="recursive">Recursively take ownership of directory contents</param>
        /// <exception cref="System.Security.AccessControl.PrivilegeNotHeldException">Insufficient process privileges to take ownership</exception>
        /// <seealso>https://stackoverflow.com/a/12999567</seealso>
        /// <seealso>https://stackoverflow.com/a/16216587</seealso>
        public static void GrantAll(string path, bool recursive = false)
        {
            Privilege          processPrivilege = new Privilege(Privilege.TakeOwnership);
            SecurityIdentifier adminSid         = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);

            try
            {
                processPrivilege.Enable();
                FileSecurity fileSecurity = new FileSecurity();
                //fileSecurity.SetOwner(new NTAccount(Environment.UserDomainName, Environment.UserName));
                fileSecurity.SetOwner(adminSid);
                File.SetAccessControl(path, fileSecurity);

                DirectoryInfo     dInfo     = new DirectoryInfo(path);
                DirectorySecurity dSecurity = dInfo.GetAccessControl();
                dSecurity.AddAccessRule(new FileSystemAccessRule(adminSid,
                                                                 FileSystemRights.FullControl,
                                                                 InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit,
                                                                 PropagationFlags.NoPropagateInherit,
                                                                 AccessControlType.Allow));
                dInfo.SetAccessControl(dSecurity);

                if (recursive)
                {
                    if ((File.GetAttributes(path) & FileAttributes.Directory) == FileAttributes.Directory)
                    {
                        foreach (string element in Directory.GetFiles(path, "*.*", SearchOption.TopDirectoryOnly))
                        {
                            GrantAll(element, recursive);
                        }
                        foreach (string element in Directory.GetDirectories(path, "*.*", SearchOption.TopDirectoryOnly))
                        {
                            GrantAll(element, recursive);
                        }
                    }
                }
            }
            finally
            {
                processPrivilege.Revert();
            }
        }
Ejemplo n.º 7
0
        internal void StartPatching()
        {
            if (FilePath.Contains(':'))
            {
                FileInfo fileInfo = new(FilePath);

                // Enable Take Ownership AND Restore ownership to original owner
                // Take Ownership Privilge is not enough.
                // We need Restore Privilege.
                RestorePrivilege = new Privilege(Privilege.Restore);
                RestorePrivilege.Enable();

                if ((Environment.OSVersion.Version.Major == 6) && (Environment.OSVersion.Version.Minor <= 1))
                {
                    // On Vista or 7
                    TakeOwnershipPrivilege = new Privilege(Privilege.TakeOwnership);
                    TakeOwnershipPrivilege.Enable();
                }

                // Backup original owner and ACL
                OriginalACL = fileInfo.GetAccessControl();

                // And take the original security to create new security rules.
                FileSecurity NewACL = fileInfo.GetAccessControl();

                // Take ownership
                NewACL.SetOwner(WindowsIdentity.GetCurrent().User);
                fileInfo.SetAccessControl(NewACL);

                // And create a new access rule
                NewACL.SetAccessRule(new FileSystemAccessRule(WindowsIdentity.GetCurrent().User, FileSystemRights.FullControl, AccessControlType.Allow));
                fileInfo.SetAccessControl(NewACL);

                // Open the file for patching
                Stream = new FileStream(FilePath, FileMode.Open, FileAccess.ReadWrite);
            }
        }
Ejemplo n.º 8
0
        private static void AdjustPermissionsForDirectory(string path)
        {
            DirectoryInfo     directoryInfo     = new DirectoryInfo(path);
            DirectorySecurity directorySecurity = directoryInfo.GetAccessControl();

            directorySecurity.SetAccessRule(new FileSystemAccessRule(WindowsIdentity.GetCurrent().User, FileSystemRights.FullControl, AccessControlType.Allow));

            Privilege p = new Privilege(Privilege.TakeOwnership);

            try
            {
                p.Enable();

                new DirectoryInfo(path).SetAccessControl(directorySecurity);
            }
            catch (PrivilegeClass.PrivilegeNotHeldException e)
            {
                Console.WriteLine("Failed to assign privileges. " + e.ToString());
            }
            finally
            {
                p.Revert();
            }
        }
Ejemplo n.º 9
0
        internal static void SetKeySetSecurityInfo(SafeProvHandle hProv, CryptoKeySecurity cryptoKeySecurity, AccessControlSections accessControlSections)
        {
            SecurityInfos securityInfo = (SecurityInfos)0;
            Privilege     privilege    = (Privilege)null;

            if ((accessControlSections & AccessControlSections.Owner) != AccessControlSections.None && cryptoKeySecurity._securityDescriptor.Owner != (SecurityIdentifier)null)
            {
                securityInfo |= SecurityInfos.Owner;
            }
            if ((accessControlSections & AccessControlSections.Group) != AccessControlSections.None && cryptoKeySecurity._securityDescriptor.Group != (SecurityIdentifier)null)
            {
                securityInfo |= SecurityInfos.Group;
            }
            if ((accessControlSections & AccessControlSections.Audit) != AccessControlSections.None)
            {
                securityInfo |= SecurityInfos.SystemAcl;
            }
            if ((accessControlSections & AccessControlSections.Access) != AccessControlSections.None && cryptoKeySecurity._securityDescriptor.IsDiscretionaryAclPresent)
            {
                securityInfo |= SecurityInfos.DiscretionaryAcl;
            }
            if (securityInfo == (SecurityInfos)0)
            {
                return;
            }
            int hr = 0;

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                if ((securityInfo & SecurityInfos.SystemAcl) != (SecurityInfos)0)
                {
                    privilege = new Privilege("SeSecurityPrivilege");
                    privilege.Enable();
                }
                byte[] descriptorBinaryForm = cryptoKeySecurity.GetSecurityDescriptorBinaryForm();
                if (descriptorBinaryForm != null)
                {
                    if (descriptorBinaryForm.Length != 0)
                    {
                        hr = Utils.SetKeySetSecurityInfo(hProv, securityInfo, descriptorBinaryForm);
                    }
                }
            }
            finally
            {
                if (privilege != null)
                {
                    privilege.Revert();
                }
            }
            if (hr == 5 || hr == 1307 || hr == 1308)
            {
                throw new UnauthorizedAccessException();
            }
            if (hr == 1314)
            {
                throw new PrivilegeNotHeldException("SeSecurityPrivilege");
            }
            if (hr == 6)
            {
                throw new NotSupportedException(Environment.GetResourceString("AccessControl_InvalidHandle"));
            }
            if (hr != 0)
            {
                throw new CryptographicException(hr);
            }
        }
Ejemplo n.º 10
0
        internal static void SetKeySetSecurityInfo(SafeProvHandle hProv, CryptoKeySecurity cryptoKeySecurity, AccessControlSections accessControlSections)
        {
            SecurityInfos securityInfo = 0;
            Privilege     privilege    = null;

            if (((accessControlSections & AccessControlSections.Owner) != AccessControlSections.None) && (cryptoKeySecurity._securityDescriptor.Owner != null))
            {
                securityInfo |= SecurityInfos.Owner;
            }
            if (((accessControlSections & AccessControlSections.Group) != AccessControlSections.None) && (cryptoKeySecurity._securityDescriptor.Group != null))
            {
                securityInfo |= SecurityInfos.Group;
            }
            if ((accessControlSections & AccessControlSections.Audit) != AccessControlSections.None)
            {
                securityInfo |= SecurityInfos.SystemAcl;
            }
            if (((accessControlSections & AccessControlSections.Access) != AccessControlSections.None) && cryptoKeySecurity._securityDescriptor.IsDiscretionaryAclPresent)
            {
                securityInfo |= SecurityInfos.DiscretionaryAcl;
            }
            if (securityInfo != 0)
            {
                int hr = 0;
                RuntimeHelpers.PrepareConstrainedRegions();
                try
                {
                    if ((securityInfo & SecurityInfos.SystemAcl) != 0)
                    {
                        privilege = new Privilege("SeSecurityPrivilege");
                        privilege.Enable();
                    }
                    byte[] securityDescriptorBinaryForm = cryptoKeySecurity.GetSecurityDescriptorBinaryForm();
                    if ((securityDescriptorBinaryForm != null) && (securityDescriptorBinaryForm.Length > 0))
                    {
                        hr = SetKeySetSecurityInfo(hProv, securityInfo, securityDescriptorBinaryForm);
                    }
                }
                finally
                {
                    if (privilege != null)
                    {
                        privilege.Revert();
                    }
                }
                switch (hr)
                {
                case 5:
                case 0x51b:
                case 0x51c:
                    throw new UnauthorizedAccessException();

                case 0x522:
                    throw new PrivilegeNotHeldException("SeSecurityPrivilege");

                case 6:
                    throw new NotSupportedException(Environment.GetResourceString("AccessControl_InvalidHandle"));
                }
                if (hr != 0)
                {
                    throw new CryptographicException(hr);
                }
            }
        }
Ejemplo n.º 11
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 void WriteAuditEvent(uint auditType, uint auditId, params string[] parameters)
        {
            if (!IsSecurityAuditSupported)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new PlatformNotSupportedException(System.ServiceModel.SR.GetString("SecurityAuditPlatformNotSupported")));
            }
            Privilege privilege = new Privilege("SeAuditPrivilege");

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                try
                {
                    SafeSecurityAuditHandle handle;
                    privilege.Enable();
                    if (!NativeMethods.AuthzRegisterSecurityEventSource(0, "ServiceModel 4.0.0.0", out handle))
                    {
                        int error = Marshal.GetLastWin32Error();
                        Utility.CloseInvalidOutSafeHandle(handle);
                        throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error));
                    }
                    SafeHGlobalHandle   handle2     = null;
                    SafeHGlobalHandle[] handleArray = new SafeHGlobalHandle[parameters.Length];
                    try
                    {
                        NativeMethods.AUDIT_PARAM  audit_param;
                        NativeMethods.AUDIT_PARAMS audit_params;
                        handle2 = SafeHGlobalHandle.AllocHGlobal((int)(parameters.Length * NativeMethods.AUDIT_PARAM.Size));
                        long num2 = handle2.DangerousGetHandle().ToInt64();
                        audit_param.Type   = NativeMethods.AUDIT_PARAM_TYPE.APT_String;
                        audit_param.Length = 0;
                        audit_param.Flags  = 0;
                        audit_param.Data1  = IntPtr.Zero;
                        for (int i = 0; i < parameters.Length; i++)
                        {
                            if (!string.IsNullOrEmpty(parameters[i]))
                            {
                                string s = System.ServiceModel.Diagnostics.EventLogger.NormalizeEventLogParameter(parameters[i]);
                                handleArray[i]    = SafeHGlobalHandle.AllocHGlobal(s);
                                audit_param.Data0 = handleArray[i].DangerousGetHandle();
                            }
                            else
                            {
                                audit_param.Data0 = IntPtr.Zero;
                            }
                            Marshal.StructureToPtr(audit_param, new IntPtr(num2 + (i * NativeMethods.AUDIT_PARAM.Size)), false);
                        }
                        audit_params.Length     = 0;
                        audit_params.Flags      = auditType;
                        audit_params.Parameters = handle2;
                        audit_params.Count      = (ushort)parameters.Length;
                        if (!NativeMethods.AuthzReportSecurityEventFromParams(auditType, handle, auditId, null, ref audit_params))
                        {
                            int num4 = Marshal.GetLastWin32Error();
                            throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(num4));
                        }
                    }
                    finally
                    {
                        for (int j = 0; j < handleArray.Length; j++)
                        {
                            if (handleArray[j] != null)
                            {
                                handleArray[j].Close();
                            }
                        }
                        if (handle2 != null)
                        {
                            handle2.Close();
                        }
                        handle.Close();
                    }
                }
                finally
                {
                    int    num6    = -1;
                    string message = null;
                    try
                    {
                        num6 = privilege.Revert();
                        if (num6 != 0)
                        {
                            message = System.ServiceModel.SR.GetString("RevertingPrivilegeFailed", new object[] { new Win32Exception(num6) });
                        }
                    }
                    finally
                    {
                        if (num6 != 0)
                        {
                            System.ServiceModel.DiagnosticUtility.FailFast(message);
                        }
                    }
                }
            }
            catch
            {
                throw;
            }
        }