private static IntPtr GetTrustedDomainInfo(DirectoryContext targetContext, string? targetName, bool isForest) { PolicySafeHandle? policyHandle = null; IntPtr buffer = (IntPtr)0; bool impersonated = false; string? serverName = null; try { try { serverName = Utils.GetPolicyServerName(targetContext, isForest, false, targetName); impersonated = Utils.Impersonate(targetContext); try { policyHandle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName)); } catch (ActiveDirectoryOperationException) { if (impersonated) { Utils.Revert(); impersonated = false; } // try anonymous Utils.ImpersonateAnonymous(); impersonated = true; policyHandle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName)); } catch (UnauthorizedAccessException) { if (impersonated) { Utils.Revert(); impersonated = false; } // try anonymous Utils.ImpersonateAnonymous(); impersonated = true; policyHandle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName)); } int result = UnsafeNativeMethods.LsaQueryInformationPolicy(policyHandle, policyDnsDomainInformation, out buffer); if (result != 0) { throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError(result), serverName); } return buffer; } finally { if (impersonated) Utils.Revert(); } } catch { throw; } }
private static IntPtr GetTrustedDomainInfo(DirectoryContext targetContext, string targetName, bool isForest) { PolicySafeHandle handle = null; IntPtr ptr2; IntPtr zero = IntPtr.Zero; bool flag = false; string serverName = null; try { try { serverName = System.DirectoryServices.ActiveDirectory.Utils.GetPolicyServerName(targetContext, isForest, false, targetName); flag = System.DirectoryServices.ActiveDirectory.Utils.Impersonate(targetContext); try { handle = new PolicySafeHandle(System.DirectoryServices.ActiveDirectory.Utils.GetPolicyHandle(serverName)); } catch (ActiveDirectoryOperationException) { if (flag) { System.DirectoryServices.ActiveDirectory.Utils.Revert(); flag = false; } System.DirectoryServices.ActiveDirectory.Utils.ImpersonateAnonymous(); flag = true; handle = new PolicySafeHandle(System.DirectoryServices.ActiveDirectory.Utils.GetPolicyHandle(serverName)); } catch (UnauthorizedAccessException) { if (flag) { System.DirectoryServices.ActiveDirectory.Utils.Revert(); flag = false; } System.DirectoryServices.ActiveDirectory.Utils.ImpersonateAnonymous(); flag = true; handle = new PolicySafeHandle(System.DirectoryServices.ActiveDirectory.Utils.GetPolicyHandle(serverName)); } int status = UnsafeNativeMethods.LsaQueryInformationPolicy(handle, PolicyDnsDomainInformation, out zero); if (status != 0) { throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError(status), serverName); } ptr2 = zero; } finally { if (flag) { System.DirectoryServices.ActiveDirectory.Utils.Revert(); } } } catch { throw; } return(ptr2); }