On 08/18/2016 01:25 PM, Martin Babinsky wrote:
On 08/17/2016 01:20 PM, Alexander Bokovoy wrote:
On Wed, 17 Aug 2016, Martin Babinsky wrote:
Hi Alexander,

patch 207: LGTM, but I have a feeling that the patch should be linked
to both #6021 and #6076 so that it is not lost during backports.

patch 218:

ipalib/errors.py:

1.)
I'm not sure if TrustTopologyConflictError should inherit from
InvocationError. The semantics of InvocationError implies that
something was wrong when trying to invoke the command (a param failed
to validate/convert, incorrect number of args, etc.), while this is
more of an exception during command execution (no. and type of params
was correct, command started to execute but encountered an error
condition). Thus I think it should inherit from ExecutionError. CC'ing
Jan for more thoughts on this.
Using ExecutionError would work to me too, as long as we display the
error to a user.
Why is TrustTopologyConflictSolved listed amogn public errors? Since
it is used only in dcerpc.py to restart trust establishment after
resolving conflicts, it should be a private exception in dcerpc.py for
this purpose.
I originally wanted to make it a warning -- i.e. if we fixed the
conflict, return the result and show the warning that we did solve the
conflict. After all, the code is modifying another trusted forest's
topology on behalf of the user. I can move the error class to dcerpc.py


3.)
Also please split the exception format string like this so that the
line is not too long (there is not much we can do about doctest so
leave that line as it is):

@@ -882,7 +882,8 @@ class TrustTopologyConflictError(InvocationError):
    """

    errno = 3017
-    format = _("Forest '%(forest)s' has existing trust to forest(s)
%(domains)s which prevents a trust to '%(conflict)s'")
+    format = _("Forest '%(forest)s' has existing trust to forest(s) "
+               "%(domains)s which prevents a trust to '%(conflict)s'")

Do not worry about gettext, it can handle it just fine, there are
plenty of examples in server plugins, for example.
Done.

ipaserver/dcerpc.py:

1.)

I think that instead of returning result and raising
TrustTopologyConflictError based on that, the 'clear_ftinfo_conflict'
can raise this exception directly. You can have an empty list defined
at the beginning instead of 'result list', append unresolvable
conflicts to it and then at the end of the method check if it is
non-empty and raise the exception.
Good suggestion, fixed.


2.)

+        # In the code below:
+        # self -- the forest we establish trust to
+        # another_domain -- a forest that establishes trust to 'self'
+        # cinfo -- lsa_ForestTrustCollisionInfo structure that contain
+        #          set of of lsa_ForestTrustCollisionRecord structures
I would add this directly into the method docstring:

"""
...

:param self: the forest we establish trust to
:param another_domain: a forest that establishes trust to 'self'
:param cinfo: lsa_ForestTrustCollisionInfo structure that contain
          set of of lsa_ForestTrustCollisionRecord structures
"""
Added.

Additionally, the behavior specifed in previous comment can be added
using :raises: stanza:

"""
:raises: errors.TrustTopologyConflictError if there are unresolvable
   namespace conflicts between trusted domains
"""
Added.


3.)

rewriting 'clear_ftinfo_conflict' according to point 1.) will allow to
simplify code in 'update_ftinfo' like this:

"""
-                res = self.clear_ftinfo_conflict(another_domain, cinfo)
-                if len(res[1]) != 0:
-                    domains = [x.name.string for x in res[1]]
-                    raise errors.TrustTopologyConflictError(
-                              target=self.info['dns_domain'],
-
conflict=another_domain.info['dns_domain'],
-                              domains=domains)
-                else:
-                    raise errors.TrustTopologyConflictSolved(
-                              target=self.info['dns_domain'],
-
conflict=another_domain.info['dns_domain'])
+                self.clear_ftinfo_conflict(another_domain, cinfo)
+                raise errors.TrustTopologyConflictSolved(
+                    target=self.info['dns_domain'],
+                    conflict=another_domain.info['dns_domain'])
"""
done.


Patch 218:

1.)
typo in the commit message:

"""
...
suffixes are forest-wide, there *are could be* user accounts in the
...
"""
Fixed.

Updated patches attached.

PATCH 207: ACK, I am attaching rebased version for ipa-4-3. Please check
if the rebase is correct.

PATCH 218: I am attaching rebased version for control. Unfortunately, I
am unable to properly test conflict resolution due to reasons beyond my
control but it does not break any ordinary workflows and code looks OK,
so ACK.


I have noticed that raising of TrustTopologyConflictSolved is broken. I have changed the base class to Exception and it works. Attaching patches with the change.

PATCH 219: ACK





--
Martin^3 Babinsky
From 6b7c859150736b39d28b8a0ca3ee196432fbd2ee Mon Sep 17 00:00:00 2001
From: Alexander Bokovoy <aboko...@redhat.com>
Date: Mon, 15 Aug 2016 18:14:00 +0300
Subject: [PATCH] trust: automatically resolve DNS trust conflicts for triangle
 trusts

For configuration where:
  - AD example.com trusts IPA at ipa.example.com
  - AD example.org trusts AD example.com
  - a trust is tried to be established between ipa.example.com and
    example.org,

there will be a trust topology conflict detected by example.org domain
controller because ipa.example.com DNS namespace overlaps with
example.com DNS namespace.

This type of trust topology conflict is documented in MS-ADTS 6.1.6.9.3.2
"Building Well-Formed msDS-TrustForestTrustInfo Message". A similar
conflict can arise for SID and NetBIOS namespaces. However, unlike SID
and NetBIOS namespaces, we can solve DNS namespace conflict
automatically if there are administrative credentials for example.org
available.

A manual sequence to solve the DNS namespace conflict is described in
https://msdn.microsoft.com/it-it/library/cc786254%28v=ws.10%29.aspx.
This sequence boils down to the following steps:

   1. As an administrator of the example.org, you need to add an
exclusion entry for ipa.example.com in the properties of the trust to
example.com
   2. Establish trust between ipa.example.com and example.org

It is important to add the exclusion entry before step 4 or there will
be conflict recorded which cannot be cleared easily right now due to a
combination of bugs in both IPA and Active Directory.

This patchset implements automated solution for the case when we have
access to the example.org's administrator credentials:

   1. Attempt to establish trust and update trust topology information.
   2. If trust topology conflict is detected as result of (1):
   2.1. Fetch trust topology infromation for the conflicting forest
        trust
   2.2. Add exclusion entry to our domain to the trust topology obtained
        in (2.1)
   2.3. Update trust topology for the conflicting forest trust
   3. Re-establish trust between ipa.example.com and example.org

We cannot do the same for shared secret trust and for external trust,
though:

   1. For shared secret trust we don't have administrative credentials
      in the forest reporting the conflict

   2. For the external trust we cannot set topology information due to
      MS-LSAD 3.1.4.7.16 because external trust is non-transitive by
      definition and thus setting topology information will fail.

To test this logic one can use two Samba AD forests with FreeIPA
using a sub-domain of one of them.

Fixes: https://fedorahosted.org/freeipa/ticket/6076
---
 ipalib/errors.py    |  29 ++++++-
 ipaserver/dcerpc.py | 218 +++++++++++++++++++++++++++++++++++++++++++++-------
 2 files changed, 219 insertions(+), 28 deletions(-)

diff --git a/ipalib/errors.py b/ipalib/errors.py
index 864310dfbeb181a5aff454a9911a55bfd3661142..6d1b328bc1dd34cdb0dc40741a4c84526a95925b 100644
--- a/ipalib/errors.py
+++ b/ipalib/errors.py
@@ -846,7 +846,6 @@ class NotAForestRootError(InvocationError):
     errno = 3016
     format = _("Domain '%(domain)s' is not a root domain for forest '%(forest)s'")
 
-
 ##############################################################################
 # 4000 - 4999: Execution errors
 
@@ -1814,6 +1813,34 @@ class DNSResolverError(DNSError):
     errno = 4401
     format = _('%(exception)s')
 
+class TrustError(ExecutionError):
+    """
+    **4500** Base class for trust execution errors (*4500 - 4599*).
+    These are typically instantiated when there is an error in establishing or
+    modifying a trust to another forest.
+    """
+
+    errno = 4500
+
+class TrustTopologyConflictError(TrustError):
+    """
+    **4501** Raised when an attempt to establish trust fails with a topology
+             conflict against another forest the target forest trusts
+
+    For example:
+
+    >>> raise TrustTopologyConflictError(forest='example.test',
+                                         conflict='my.ad.test',
+                                         domains=['ad.test'])
+    Traceback (most recent call last):
+      ...
+    TrustTopologyConflictError: Forest 'example.test' has existing trust to forest(s) ['ad.test'] which prevents a trust to 'my.ad.test'
+    """
+
+    errno = 4501
+    format = _("Forest '%(forest)s' has existing trust to forest(s) "
+               "%(domains)s which prevents a trust to '%(conflict)s'")
+
 
 ##############################################################################
 # 5000 - 5999: Generic errors
diff --git a/ipaserver/dcerpc.py b/ipaserver/dcerpc.py
index e1f2d5f56fc292e512d39f7f13197a9bed5f87a0..dee93fd5616782e5f9149055c829a1ea69d4ee9e 100644
--- a/ipaserver/dcerpc.py
+++ b/ipaserver/dcerpc.py
@@ -1,7 +1,7 @@
 # Authors:
 #     Alexander Bokovoy <aboko...@redhat.com>
 #
-# Copyright (C) 2011  Red Hat
+# Copyright (C) 2011-2016  Red Hat
 # see file 'COPYING' for use and warranty information
 #
 # Portions (C) Andrew Tridgell, Andrew Bartlett
@@ -135,6 +135,15 @@ pysss_type_key_translation_dict = {
     pysss_nss_idmap.ID_BOTH: 'both',
 }
 
+class TrustTopologyConflictSolved(Exception):
+    """
+    Internal trust error: raised when previously detected
+    trust topology conflict is automatically solved.
+
+    No separate errno is assigned as this error should
+    not be visible outside the dcerpc.py code.
+    """
+    pass
 
 def assess_dcerpc_exception(num=None, message=None):
     """
@@ -1085,34 +1094,165 @@ class TrustDomainInstance(object):
         info.entries = ftinfo_records
         return info
 
+    def clear_ftinfo_conflict(self, another_domain, cinfo):
+        """
+        Attempt to clean up the forest trust collisions
+
+        :param self: the forest we establish trust to
+        :param another_domain: a forest that establishes trust to 'self'
+        :param cinfo: lsa_ForestTrustCollisionInfo structure that contain
+                      set of of lsa_ForestTrustCollisionRecord structures
+        :raises: TrustTopologyConflictSolved, TrustTopologyConflictError
+
+        This code tries to perform intelligent job of going
+        over individual collisions and making exclusion entries
+        for affected IPA namespaces.
+
+        There are three possible conflict configurations:
+          - conflict of DNS namespace (TLN conflict, LSA_TLN_DISABLED_CONFLICT)
+          - conflict of SID namespace (LSA_SID_DISABLED_CONFLICT)
+          - conflict of NetBIOS namespace (LSA_NB_DISABLED_CONFLICT)
+
+        we only can handle TLN conflicts because (a) excluding SID namespace
+        is not possible and (b) excluding NetBIOS namespace not possible.
+        These two types of conflicts should result in trust-add CLI error
+
+        These conflicts can come from external source (another forest) or
+        from internal source (another domain in the same forest). We only
+        can fix the problems with another forest.
+
+        To resolve TLN conflict we need to do following:
+          1. Retrieve forest trust information for the forest we conflict on
+          2. Add an exclusion entry for IPA DNS namespace to it
+          3. Set forest trust information for the forest we conflict on
+          4. Re-try establishing trust to the original forest
+
+        This all can only be done under privileges of Active Directory admin
+        that can change forest trusts. If we cannot have those privileges,
+        the work has to be done manually in the Windows UI for
+        'Active Directory Domains and Trusts' by the administrator of the
+        original forest.
+        """
+
+        # List of entries for unsolved conflicts
+        result = []
+
+        trust_timestamp = long(time.time()*1e7+116444736000000000)
+
+        # Collision information contains entries for specific trusted domains
+        # we collide with. Look into TLN collisions and add a TLN exclusion
+        # entry to the specific domain trust.
+        root_logger.error("Attempt to solve forest trust topology conflicts")
+        for rec in cinfo.entries:
+            if rec.type == lsa.LSA_FOREST_TRUST_COLLISION_TDO:
+                dominfo = self._pipe.lsaRQueryForestTrustInformation(
+                                 self._policy_handle,
+                                 rec.name,
+                                 lsa.LSA_FOREST_TRUST_DOMAIN_INFO)
+
+                # Oops, we were unable to retrieve trust topology for this
+                # trusted domain (forest).
+                if not dominfo:
+                    result.append(rec)
+                    root_logger.error("Unable to resolve conflict for "
+                                      "DNS domain %s in the forest %s "
+                                      "for domain trust %s. Trust cannot "
+                                      "be established unless this conflict "
+                                      "is fixed manually."
+                                      % (another_domain.info['dns_domain'],
+                                         self.info['dns_domain'],
+                                         rec.name.string))
+                    continue
+
+                # Copy over the entries, extend with TLN exclusion
+                entries = []
+                for e in dominfo.entries:
+                    e1 = lsa.ForestTrustRecord()
+                    e1.type = e.type
+                    e1.flags = e.flags
+                    e1.time = e.time
+                    e1.forest_trust_data = e.forest_trust_data
+                    entries.append(e1)
+
+                # Create TLN exclusion record
+                record = lsa.ForestTrustRecord()
+                record.type = lsa.LSA_FOREST_TRUST_TOP_LEVEL_NAME_EX
+                record.flags = 0
+                record.time = trust_timestamp
+                record.forest_trust_data.string = \
+                    another_domain.info['dns_domain']
+                entries.append(record)
+
+                fti = lsa.ForestTrustInformation()
+                fti.count = len(entries)
+                fti.entries = entries
+
+                # Update the forest trust information now
+                ldname = lsa.StringLarge()
+                ldname.string = rec.name.string
+                cninfo = self._pipe.lsaRSetForestTrustInformation(
+                             self._policy_handle,
+                             ldname,
+                             lsa.LSA_FOREST_TRUST_DOMAIN_INFO,
+                             fti, 0)
+                if cninfo:
+                    result.append(rec)
+                    root_logger.error("When defining exception for DNS "
+                                      "domain %s in forest %s for "
+                                      "trusted forest %s, "
+                                      "got collision info back:\n%s"
+                                      % (another_domain.info['dns_domain'],
+                                         self.info['dns_domain'],
+                                         rec.name.string,
+                                         ndr_print(cninfo)))
+            else:
+                result.append(rec)
+                root_logger.error("Unable to resolve conflict for "
+                                  "DNS domain %s in the forest %s "
+                                  "for in-forest domain %s. Trust cannot "
+                                  "be established unless this conflict "
+                                  "is fixed manually."
+                                  % (another_domain.info['dns_domain'],
+                                     self.info['dns_domain'],
+                                     rec.name.string))
+
+        if len(result) == 0:
+            root_logger.error("Successfully solved all conflicts")
+            raise TrustTopologyConflictSolved()
+
+        # Otherwise, raise TrustTopologyConflictError() exception
+        domains = [x.name.string for x in result]
+        raise errors.TrustTopologyConflictError(
+                              target=self.info['dns_domain'],
+                              conflict=another_domain.info['dns_domain'],
+                              domains=domains)
+
+
+
     def update_ftinfo(self, another_domain):
         """
         Updates forest trust information in this forest corresponding
         to the another domain's information.
         """
-        try:
-            if another_domain.ftinfo_records:
-                ftinfo = self.generate_ftinfo(another_domain)
-                # Set forest trust information -- we do it only against AD DC as
-                # smbd already has the information about itself
-                ldname = lsa.StringLarge()
-                ldname.string = another_domain.info['dns_domain']
-                ftlevel = lsa.LSA_FOREST_TRUST_DOMAIN_INFO
-                # RSetForestTrustInformation returns collision information
-                # for trust topology
-                cinfo = self._pipe.lsaRSetForestTrustInformation(
-                            self._policy_handle,
-                            ldname,
-                            ftlevel,
-                            ftinfo, 0)
-                if cinfo:
-                    root_logger.error("When setting forest trust information, "
-                                      "got collision info back:\n%s"
-                                      % (ndr_print(cinfo)))
-        except RuntimeError as e:
-            # We can ignore the error here --
-            # setting up name suffix routes may fail
-            pass
+        if another_domain.ftinfo_records:
+            ftinfo = self.generate_ftinfo(another_domain)
+            # Set forest trust information -- we do it only against AD DC as
+            # smbd already has the information about itself
+            ldname = lsa.StringLarge()
+            ldname.string = another_domain.info['dns_domain']
+            ftlevel = lsa.LSA_FOREST_TRUST_DOMAIN_INFO
+            # RSetForestTrustInformation returns collision information
+            # for trust topology
+            cinfo = self._pipe.lsaRSetForestTrustInformation(
+                        self._policy_handle,
+                        ldname,
+                        ftlevel,
+                        ftinfo, 0)
+            if cinfo:
+                root_logger.error("When setting forest trust information, "
+                                  "got collision info back:\n%s"
+                                  % (ndr_print(cinfo)))
+                self.clear_ftinfo_conflict(another_domain, cinfo)
 
     def establish_trust(self, another_domain, trustdom_secret, trust_type='bidirectional'):
         """
@@ -1201,6 +1341,18 @@ class TrustDomainInstance(object):
             root_logger.error(
                 'unable to set trust to transitive: %s' % (str(e)))
             pass
+        # Updating forest trust info may fail
+        # If it failed due to topology conflict, it may be fixed automatically
+        # update_ftinfo() will through exceptions in that case
+        # Note that MS-LSAD 3.1.4.7.16 says:
+        # -------------------------
+        # The server MUST also make sure that the trust attributes associated
+        # with the trusted domain object referenced by the TrustedDomainName
+        # parameter has the TRUST_ATTRIBUTE_FOREST_TRANSITIVE set.
+        # If the attribute is not present, the server MUST return
+        # STATUS_INVALID_PARAMETER.
+        # -------------------------
+        # Thus, we must not update forest trust info for the external trust
         if self.info['is_pdc']:
             self.update_ftinfo(another_domain)
 
@@ -1478,9 +1630,21 @@ class TrustDomainJoins(object):
         if not self.remote_domain.read_only:
             trustdom_pass = samba.generate_random_password(128, 128)
             self.get_realmdomains()
-            self.remote_domain.establish_trust(self.local_domain,
-                                               trustdom_pass,
-                                               trust_type)
+
+            # Establishing trust may throw an exception for topology
+            # conflict. If it was solved, re-establish the trust again
+            # Otherwise let the CLI to display a message about the conflict
+            try:
+                self.remote_domain.establish_trust(self.local_domain,
+                                                   trustdom_pass,
+                                                   trust_type)
+            except TrustTopologyConflictSolved as e:
+                # we solved topology conflict, retry again
+                self.remote_domain.establish_trust(self.local_domain,
+                                                   trustdom_pass,
+                                                   trust_type)
+
+            # For local domain we don't set topology information
             self.local_domain.establish_trust(self.remote_domain,
                                               trustdom_pass,
                                               trust_type)
-- 
2.7.4

From a98ad700254e0d8d6c3659a898082e3d25724fa0 Mon Sep 17 00:00:00 2001
From: Alexander Bokovoy <aboko...@redhat.com>
Date: Mon, 15 Aug 2016 18:14:00 +0300
Subject: [PATCH 1/2] trust: automatically resolve DNS trust conflicts for
 triangle trusts

For configuration where:
  - AD example.com trusts IPA at ipa.example.com
  - AD example.org trusts AD example.com
  - a trust is tried to be established between ipa.example.com and
    example.org,

there will be a trust topology conflict detected by example.org domain
controller because ipa.example.com DNS namespace overlaps with
example.com DNS namespace.

This type of trust topology conflict is documented in MS-ADTS 6.1.6.9.3.2
"Building Well-Formed msDS-TrustForestTrustInfo Message". A similar
conflict can arise for SID and NetBIOS namespaces. However, unlike SID
and NetBIOS namespaces, we can solve DNS namespace conflict
automatically if there are administrative credentials for example.org
available.

A manual sequence to solve the DNS namespace conflict is described in
https://msdn.microsoft.com/it-it/library/cc786254%28v=ws.10%29.aspx.
This sequence boils down to the following steps:

   1. As an administrator of the example.org, you need to add an
exclusion entry for ipa.example.com in the properties of the trust to
example.com
   2. Establish trust between ipa.example.com and example.org

It is important to add the exclusion entry before step 4 or there will
be conflict recorded which cannot be cleared easily right now due to a
combination of bugs in both IPA and Active Directory.

This patchset implements automated solution for the case when we have
access to the example.org's administrator credentials:

   1. Attempt to establish trust and update trust topology information.
   2. If trust topology conflict is detected as result of (1):
   2.1. Fetch trust topology infromation for the conflicting forest
        trust
   2.2. Add exclusion entry to our domain to the trust topology obtained
        in (2.1)
   2.3. Update trust topology for the conflicting forest trust
   3. Re-establish trust between ipa.example.com and example.org

We cannot do the same for shared secret trust and for external trust,
though:

   1. For shared secret trust we don't have administrative credentials
      in the forest reporting the conflict

   2. For the external trust we cannot set topology information due to
      MS-LSAD 3.1.4.7.16 because external trust is non-transitive by
      definition and thus setting topology information will fail.

To test this logic one can use two Samba AD forests with FreeIPA
using a sub-domain of one of them.

Fixes: https://fedorahosted.org/freeipa/ticket/6076
---
 ipalib/errors.py    |  29 ++++++-
 ipaserver/dcerpc.py | 220 +++++++++++++++++++++++++++++++++++++++++++++-------
 2 files changed, 220 insertions(+), 29 deletions(-)

diff --git a/ipalib/errors.py b/ipalib/errors.py
index 7b4f15dd60ee80719195ba1b9b85d075b10bdf4f..4cc4455b0abf7d2b1366e1ce6dbb3762bc551cc6 100644
--- a/ipalib/errors.py
+++ b/ipalib/errors.py
@@ -866,7 +866,6 @@ class NotAForestRootError(InvocationError):
     errno = 3016
     format = _("Domain '%(domain)s' is not a root domain for forest '%(forest)s'")
 
-
 ##############################################################################
 # 4000 - 4999: Execution errors
 
@@ -1908,6 +1907,34 @@ class DNSResolverError(DNSError):
     errno = 4401
     format = _('%(exception)s')
 
+class TrustError(ExecutionError):
+    """
+    **4500** Base class for trust execution errors (*4500 - 4599*).
+    These are typically instantiated when there is an error in establishing or
+    modifying a trust to another forest.
+    """
+
+    errno = 4500
+
+class TrustTopologyConflictError(TrustError):
+    """
+    **4501** Raised when an attempt to establish trust fails with a topology
+             conflict against another forest the target forest trusts
+
+    For example:
+
+    >>> raise TrustTopologyConflictError(forest='example.test',
+                                         conflict='my.ad.test',
+                                         domains=['ad.test'])
+    Traceback (most recent call last):
+      ...
+    TrustTopologyConflictError: Forest 'example.test' has existing trust to forest(s) ['ad.test'] which prevents a trust to 'my.ad.test'
+    """
+
+    errno = 4501
+    format = _("Forest '%(forest)s' has existing trust to forest(s) "
+               "%(domains)s which prevents a trust to '%(conflict)s'")
+
 
 ##############################################################################
 # 5000 - 5999: Generic errors
diff --git a/ipaserver/dcerpc.py b/ipaserver/dcerpc.py
index 19be6bf7a3617a3b867d51a9358c9926e91049a7..a1c12f16a655493808d50e6adb95e618a664a98c 100644
--- a/ipaserver/dcerpc.py
+++ b/ipaserver/dcerpc.py
@@ -1,7 +1,7 @@
 # Authors:
 #     Alexander Bokovoy <aboko...@redhat.com>
 #
-# Copyright (C) 2011  Red Hat
+# Copyright (C) 2011-2016  Red Hat
 # see file 'COPYING' for use and warranty information
 #
 # Portions (C) Andrew Tridgell, Andrew Bartlett
@@ -140,6 +140,15 @@ pysss_type_key_translation_dict = {
     pysss_nss_idmap.ID_BOTH: 'both',
 }
 
+class TrustTopologyConflictSolved(Exception):
+    """
+    Internal trust error: raised when previously detected
+    trust topology conflict is automatically solved.
+
+    No separate errno is assigned as this error should
+    not be visible outside the dcerpc.py code.
+    """
+    pass
 
 def assess_dcerpc_exception(num=None, message=None):
     """
@@ -1087,34 +1096,165 @@ class TrustDomainInstance(object):
         info.entries = ftinfo_records
         return info
 
+    def clear_ftinfo_conflict(self, another_domain, cinfo):
+        """
+        Attempt to clean up the forest trust collisions
+
+        :param self: the forest we establish trust to
+        :param another_domain: a forest that establishes trust to 'self'
+        :param cinfo: lsa_ForestTrustCollisionInfo structure that contain
+                      set of of lsa_ForestTrustCollisionRecord structures
+        :raises: TrustTopologyConflictSolved, TrustTopologyConflictError
+
+        This code tries to perform intelligent job of going
+        over individual collisions and making exclusion entries
+        for affected IPA namespaces.
+
+        There are three possible conflict configurations:
+          - conflict of DNS namespace (TLN conflict, LSA_TLN_DISABLED_CONFLICT)
+          - conflict of SID namespace (LSA_SID_DISABLED_CONFLICT)
+          - conflict of NetBIOS namespace (LSA_NB_DISABLED_CONFLICT)
+
+        we only can handle TLN conflicts because (a) excluding SID namespace
+        is not possible and (b) excluding NetBIOS namespace not possible.
+        These two types of conflicts should result in trust-add CLI error
+
+        These conflicts can come from external source (another forest) or
+        from internal source (another domain in the same forest). We only
+        can fix the problems with another forest.
+
+        To resolve TLN conflict we need to do following:
+          1. Retrieve forest trust information for the forest we conflict on
+          2. Add an exclusion entry for IPA DNS namespace to it
+          3. Set forest trust information for the forest we conflict on
+          4. Re-try establishing trust to the original forest
+
+        This all can only be done under privileges of Active Directory admin
+        that can change forest trusts. If we cannot have those privileges,
+        the work has to be done manually in the Windows UI for
+        'Active Directory Domains and Trusts' by the administrator of the
+        original forest.
+        """
+
+        # List of entries for unsolved conflicts
+        result = []
+
+        trust_timestamp = long(time.time()*1e7+116444736000000000)
+
+        # Collision information contains entries for specific trusted domains
+        # we collide with. Look into TLN collisions and add a TLN exclusion
+        # entry to the specific domain trust.
+        root_logger.error("Attempt to solve forest trust topology conflicts")
+        for rec in cinfo.entries:
+            if rec.type == lsa.LSA_FOREST_TRUST_COLLISION_TDO:
+                dominfo = self._pipe.lsaRQueryForestTrustInformation(
+                                 self._policy_handle,
+                                 rec.name,
+                                 lsa.LSA_FOREST_TRUST_DOMAIN_INFO)
+
+                # Oops, we were unable to retrieve trust topology for this
+                # trusted domain (forest).
+                if not dominfo:
+                    result.append(rec)
+                    root_logger.error("Unable to resolve conflict for "
+                                      "DNS domain %s in the forest %s "
+                                      "for domain trust %s. Trust cannot "
+                                      "be established unless this conflict "
+                                      "is fixed manually."
+                                      % (another_domain.info['dns_domain'],
+                                         self.info['dns_domain'],
+                                         rec.name.string))
+                    continue
+
+                # Copy over the entries, extend with TLN exclusion
+                entries = []
+                for e in dominfo.entries:
+                    e1 = lsa.ForestTrustRecord()
+                    e1.type = e.type
+                    e1.flags = e.flags
+                    e1.time = e.time
+                    e1.forest_trust_data = e.forest_trust_data
+                    entries.append(e1)
+
+                # Create TLN exclusion record
+                record = lsa.ForestTrustRecord()
+                record.type = lsa.LSA_FOREST_TRUST_TOP_LEVEL_NAME_EX
+                record.flags = 0
+                record.time = trust_timestamp
+                record.forest_trust_data.string = \
+                    another_domain.info['dns_domain']
+                entries.append(record)
+
+                fti = lsa.ForestTrustInformation()
+                fti.count = len(entries)
+                fti.entries = entries
+
+                # Update the forest trust information now
+                ldname = lsa.StringLarge()
+                ldname.string = rec.name.string
+                cninfo = self._pipe.lsaRSetForestTrustInformation(
+                             self._policy_handle,
+                             ldname,
+                             lsa.LSA_FOREST_TRUST_DOMAIN_INFO,
+                             fti, 0)
+                if cninfo:
+                    result.append(rec)
+                    root_logger.error("When defining exception for DNS "
+                                      "domain %s in forest %s for "
+                                      "trusted forest %s, "
+                                      "got collision info back:\n%s"
+                                      % (another_domain.info['dns_domain'],
+                                         self.info['dns_domain'],
+                                         rec.name.string,
+                                         ndr_print(cninfo)))
+            else:
+                result.append(rec)
+                root_logger.error("Unable to resolve conflict for "
+                                  "DNS domain %s in the forest %s "
+                                  "for in-forest domain %s. Trust cannot "
+                                  "be established unless this conflict "
+                                  "is fixed manually."
+                                  % (another_domain.info['dns_domain'],
+                                     self.info['dns_domain'],
+                                     rec.name.string))
+
+        if len(result) == 0:
+            root_logger.error("Successfully solved all conflicts")
+            raise TrustTopologyConflictSolved()
+
+        # Otherwise, raise TrustTopologyConflictError() exception
+        domains = [x.name.string for x in result]
+        raise errors.TrustTopologyConflictError(
+                              target=self.info['dns_domain'],
+                              conflict=another_domain.info['dns_domain'],
+                              domains=domains)
+
+
+
     def update_ftinfo(self, another_domain):
         """
         Updates forest trust information in this forest corresponding
         to the another domain's information.
         """
-        try:
-            if another_domain.ftinfo_records:
-                ftinfo = self.generate_ftinfo(another_domain)
-                # Set forest trust information -- we do it only against AD DC as
-                # smbd already has the information about itself
-                ldname = lsa.StringLarge()
-                ldname.string = another_domain.info['dns_domain']
-                ftlevel = lsa.LSA_FOREST_TRUST_DOMAIN_INFO
-                # RSetForestTrustInformation returns collision information
-                # for trust topology
-                cinfo = self._pipe.lsaRSetForestTrustInformation(
-                            self._policy_handle,
-                            ldname,
-                            ftlevel,
-                            ftinfo, 0)
-                if cinfo:
-                    root_logger.error("When setting forest trust information, "
-                                      "got collision info back:\n%s"
-                                      % (ndr_print(cinfo)))
-        except RuntimeError as e:
-            # We can ignore the error here --
-            # setting up name suffix routes may fail
-            pass
+        if another_domain.ftinfo_records:
+            ftinfo = self.generate_ftinfo(another_domain)
+            # Set forest trust information -- we do it only against AD DC as
+            # smbd already has the information about itself
+            ldname = lsa.StringLarge()
+            ldname.string = another_domain.info['dns_domain']
+            ftlevel = lsa.LSA_FOREST_TRUST_DOMAIN_INFO
+            # RSetForestTrustInformation returns collision information
+            # for trust topology
+            cinfo = self._pipe.lsaRSetForestTrustInformation(
+                        self._policy_handle,
+                        ldname,
+                        ftlevel,
+                        ftinfo, 0)
+            if cinfo:
+                root_logger.error("When setting forest trust information, "
+                                  "got collision info back:\n%s"
+                                  % (ndr_print(cinfo)))
+                self.clear_ftinfo_conflict(another_domain, cinfo)
 
     def establish_trust(self, another_domain, trustdom_secret,
                         trust_type='bidirectional', trust_external=False):
@@ -1207,7 +1347,19 @@ class TrustDomainInstance(object):
                 root_logger.error(
                       'unable to set trust transitivity status: %s' % (str(e)))
 
-        if self.info['is_pdc'] or trust_external:
+        # Updating forest trust info may fail
+        # If it failed due to topology conflict, it may be fixed automatically
+        # update_ftinfo() will through exceptions in that case
+        # Note that MS-LSAD 3.1.4.7.16 says:
+        # -------------------------
+        # The server MUST also make sure that the trust attributes associated
+        # with the trusted domain object referenced by the TrustedDomainName
+        # parameter has the TRUST_ATTRIBUTE_FOREST_TRANSITIVE set.
+        # If the attribute is not present, the server MUST return
+        # STATUS_INVALID_PARAMETER.
+        # -------------------------
+        # Thus, we must not update forest trust info for the external trust
+        if self.info['is_pdc'] and not trust_external:
             self.update_ftinfo(another_domain)
 
     def verify_trust(self, another_domain):
@@ -1509,9 +1661,21 @@ class TrustDomainJoins(object):
         if not self.remote_domain.read_only:
             trustdom_pass = samba.generate_random_password(128, 128)
             self.get_realmdomains()
-            self.remote_domain.establish_trust(self.local_domain,
-                                               trustdom_pass,
-                                               trust_type, trust_external)
+
+            # Establishing trust may throw an exception for topology
+            # conflict. If it was solved, re-establish the trust again
+            # Otherwise let the CLI to display a message about the conflict
+            try:
+                self.remote_domain.establish_trust(self.local_domain,
+                                                   trustdom_pass,
+                                                   trust_type, trust_external)
+            except TrustTopologyConflictSolved as e:
+                # we solved topology conflict, retry again
+                self.remote_domain.establish_trust(self.local_domain,
+                                                   trustdom_pass,
+                                                   trust_type, trust_external)
+
+            # For local domain we don't set topology information
             self.local_domain.establish_trust(self.remote_domain,
                                               trustdom_pass,
                                               trust_type, trust_external)
-- 
2.7.4

-- 
Manage your subscription for the Freeipa-devel mailing list:
https://www.redhat.com/mailman/listinfo/freeipa-devel
Contribute to FreeIPA: http://www.freeipa.org/page/Contribute/Code

Reply via email to