[Freeipa-devel] [PATCH] 0207, 0218-0219 Solving trust conflicts and external trust topology fixes

Alexander Bokovoy abokovoy at redhat.com
Wed Aug 17 11:20:37 UTC 2016


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.
-- 
/ Alexander Bokovoy
-------------- next part --------------
From 4c6e1c5ce1eddd70aac5cf97075af3cf15bb951a Mon Sep 17 00:00:00 2001
From: Alexander Bokovoy <abokovoy at redhat.com>
Date: Mon, 15 Aug 2016 18:14:00 +0300
Subject: [PATCH 09/10] 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 7b4f15d..4cc4455 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 19be6bf..da70ac3 100644
--- a/ipaserver/dcerpc.py
+++ b/ipaserver/dcerpc.py
@@ -1,7 +1,7 @@
 # Authors:
 #     Alexander Bokovoy <abokovoy at 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(errors.TrustError):
+    """
+    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

-------------- next part --------------
From e56bba9bc6718c7b1cea88a75a9d7633d2cc7da1 Mon Sep 17 00:00:00 2001
From: Alexander Bokovoy <abokovoy at redhat.com>
Date: Mon, 15 Aug 2016 18:32:25 +0300
Subject: [PATCH 10/10] trust: make sure external trust topology is correctly
 rendered

When external trust is established, it is by definition is
non-transitive: it is not possible to obtain Kerberos tickets to any
service outside the trusted domain.

Reflect this reality by only accepting UPN suffixes from the external
trust -- since the trusted domain is a part of another forest and UPN
suffixes are forest-wide, there could be user accounts in the trusted
domain that use forest-wide UPN suffix but it will be impossible to
reach the forest root via the externally trusted domain.

Also, an argument to netr_DsRGetForestTrustInformation() has to be
either forest root domain name or None (NULL). Otherwise we'll get
an error as explained in MS-NRPC 3.5.4.7.5.

https://fedorahosted.org/freeipa/ticket/6021
---
 ipaserver/dcerpc.py        |  2 +-
 ipaserver/plugins/trust.py | 28 +++++++++++++++++-----------
 2 files changed, 18 insertions(+), 12 deletions(-)

diff --git a/ipaserver/dcerpc.py b/ipaserver/dcerpc.py
index da70ac3..d13cdf0 100644
--- a/ipaserver/dcerpc.py
+++ b/ipaserver/dcerpc.py
@@ -1449,7 +1449,7 @@ def fetch_domains(api, mydomain, trustdomain, creds=None, server=None):
         # Older FreeIPA versions used netr_DsrEnumerateDomainTrusts call
         # but it doesn't provide information about non-domain UPNs associated
         # with the forest, thus we have to use netr_DsRGetForestTrustInformation
-        domains = netr_pipe.netr_DsRGetForestTrustInformation(td.info['dc'], '', 0)
+        domains = netr_pipe.netr_DsRGetForestTrustInformation(td.info['dc'], None, 0)
         return domains
 
     domains = None
diff --git a/ipaserver/plugins/trust.py b/ipaserver/plugins/trust.py
index f90d9c1..b9d9b12 100644
--- a/ipaserver/plugins/trust.py
+++ b/ipaserver/plugins/trust.py
@@ -1663,6 +1663,23 @@ def add_new_domains_from_trust(myapi, trustinstance, trust_entry, domains, **opt
                     for x, y in six.iteritems(domains['suffixes'])
                     if x not in domains['domains'])
 
+    try:
+        dn = myapi.Object.trust.get_dn(trust_name, trust_type=u'ad')
+        ldap = myapi.Backend.ldap2
+        entry = ldap.get_entry(dn)
+        tlns = entry.get('ipantadditionalsuffixes', [])
+        tlns.extend(x for x in suffixes if x not in tlns)
+        entry['ipantadditionalsuffixes'] = tlns
+        ldap.update_entry(entry)
+    except errors.EmptyModlist:
+        pass
+
+    is_nontransitive = int(trust_entry.get('ipanttrustattributes',
+                           [0])[0]) & LSA_TRUST_ATTRIBUTE_NON_TRANSITIVE
+
+    if is_nontransitive:
+        return result
+
     for dom in six.itervalues(domains['domains']):
         dom['trust_type'] = u'ad'
         try:
@@ -1690,17 +1707,6 @@ def add_new_domains_from_trust(myapi, trustinstance, trust_entry, domains, **opt
             # Ignore updating duplicate entries
             pass
 
-    try:
-        dn = myapi.Object.trust.get_dn(trust_name, trust_type=u'ad')
-        ldap = myapi.Backend.ldap2
-        entry = ldap.get_entry(dn)
-        tlns = entry.get('ipantadditionalsuffixes', [])
-        tlns.extend(x for x in suffixes if x not in tlns)
-        entry['ipantadditionalsuffixes'] = tlns
-        ldap.update_entry(entry)
-    except errors.EmptyModlist:
-        pass
-
     return result
 
 
-- 
2.7.4



More information about the Freeipa-devel mailing list